diff --git a/.teamcity/settings.kts b/.teamcity/settings.kts index 3b4367ca19..b1445beaf3 100644 --- a/.teamcity/settings.kts +++ b/.teamcity/settings.kts @@ -36,8 +36,8 @@ project { buildType(PullRequestCompatibility) params { - text("docker_jdk_version", "17", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false) - text("docker_gradle_version", "7.5.1", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false) + text("docker_jdk_version", "21", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false) + text("docker_gradle_version", "8.7", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false) text("git_main_branch", "1.20.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false) text("git_branch_spec", """ +:refs/heads/(main*) diff --git a/build.gradle b/build.gradle index 9b42cfb165..1fc68fd4ba 100644 --- a/build.gradle +++ b/build.gradle @@ -7,8 +7,8 @@ plugins { id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)' id 'eclipse' id 'de.undercouch.download' version '5.4.0' - id 'net.minecraftforge.gradle.patcher' version '[6.0.16,6.2)' apply false - id 'net.minecraftforge.gradle.mcp' version '[6.0.16,6.2)' apply false + id 'net.minecraftforge.gradle.patcher' version '[6.0.22,6.2)' apply false + id 'net.minecraftforge.gradle.mcp' version '[6.0.22,6.2)' apply false id 'net.minecraftforge.gradlejarsigner' version '1.0.4' id 'org.barfuin.gradle.taskinfo' version '2.1.0' } diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 58428e6ac0..5b1dd25794 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -4,9 +4,9 @@ repositories { } dependencies { - implementation 'org.ow2.asm:asm:9.6' - implementation 'org.ow2.asm:asm-tree:9.6' - implementation 'net.minecraftforge:srgutils:0.5.+' + implementation 'org.ow2.asm:asm:9.7' + implementation 'org.ow2.asm:asm-tree:9.7' + implementation 'net.minecraftforge:srgutils:0.5.10' implementation 'commons-io:commons-io:2.13.0' implementation 'com.google.code.gson:gson:2.10.1' implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r' diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy index 70e1ef6921..9887122e74 100644 --- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy @@ -10,11 +10,13 @@ import java.util.zip.ZipFile abstract class BundleList extends DefaultTask { @InputFiles abstract ConfigurableFileCollection getConfig() + @InputFiles abstract ConfigurableFileCollection getConfigExtra() @InputFile abstract RegularFileProperty getServerBundle() @OutputFile abstract RegularFileProperty getOutput() BundleList() { config.setFrom(project.configurations.installer) + configExtra.setFrom(project.configurations.installerextra) output.convention(project.layout.buildDirectory.file("$name/output.list")) configure { dependsOn(project.tasks.universalJar) @@ -32,6 +34,13 @@ abstract class BundleList extends DefaultTask { entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path") } + resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts + for (def dep : resolved) { + def info = Util.getMavenInfoFromDep(dep) + //println("$dep.file.sha1\t$info.name\t$info.path") + entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path") + } + var packed = (AbstractArchiveTask) project.tasks.universalJar var info = Util.getMavenInfoFromTask(packed) def file = packed.archiveFile.get().asFile diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy index e9cf3a18d2..fe6f810398 100644 --- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy @@ -24,6 +24,7 @@ abstract class LauncherJson extends DefaultTask { dependsOn(project.tasks.universalJar) input.from(project.tasks.universalJar.archiveFile) input.from(project.configurations.installer) + input.from(project.configurations.installerextra) configure { def mc = project.rootProject.ext.MC_VERSION def forge = project.rootProject.ext.FORGE_VERSION @@ -88,6 +89,7 @@ abstract class LauncherJson extends DefaultTask { ] ]) + json.libraries.addAll(getArtifacts(project.configurations.installerextra).values()) json.libraries.addAll(getArtifacts(project.configurations.installer).values()) Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString()) } diff --git a/build_clean.gradle b/build_clean.gradle index 5853765f72..21471fcc6c 100644 --- a/build_clean.gradle +++ b/build_clean.gradle @@ -61,4 +61,13 @@ eclipse.classpath.file.whenMerged { def src = entries.find { it.path == 'src/main/java' } if (src == null) throw new IllegalStateException("You must run `setup` task before importing") src.entryAttributes['ignore_optional_problems'] = 'true' +} + +tasks.named('genPatches').configure { + onlyIf { false } +} + +tasks.named('extractRangeMap').configure { + onlyIf { false } + tool = 'net.minecraftforge:Srg2Source:8.1.0:fatjar' } \ No newline at end of file diff --git a/build_forge.gradle b/build_forge.gradle index 93eb2f9778..f6952705f1 100644 --- a/build_forge.gradle +++ b/build_forge.gradle @@ -12,9 +12,9 @@ import net.minecraftforge.gradle.common.tasks.ApplyBinPatches import net.minecraftforge.gradle.common.tasks.CheckJarCompatibility import net.minecraftforge.gradle.common.tasks.DownloadMavenArtifact import net.minecraftforge.gradle.common.tasks.ExtractInheritance +import net.minecraftforge.gradle.patcher.tasks.FilterNewJar import net.minecraftforge.gradle.patcher.tasks.GeneratePatches import net.minecraftforge.gradle.userdev.tasks.RenameJar -import net.minecraftforge.gradleutils.PomUtils import org.apache.tools.ant.filters.ReplaceTokens import org.objectweb.asm.Opcodes @@ -46,6 +46,7 @@ jarSigner.autoDetect('forge') applyPatches { level 'WARNING' + failOnError = UPDATING != 'true' } sourceSets { @@ -88,16 +89,21 @@ ext { final String MAVEN_PATH = ext.MAVEN_PATH final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar' -final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.0' +final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.3' final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6' +final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.1.0:fatjar' configurations { // Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it. - bootstrap { transitive = false } + bootstrap { transitive = false } installer { extendsFrom(bootstrap) transitive = false } + installerextra { + extendsFrom(bootstrap) + transitive = false + } api.extendsFrom(installer) } @@ -111,10 +117,11 @@ dependencies { bootstrap(libs.unsafe) // Needed by securemodules bootstrap(libs.bundles.asm) // Needed by securemodules + implementation(libs.jopt.simple) { version { strictly '5.0.4' } } + installer(libs.bootstrap) installer(libs.bootstrap.api) // Needed by securemodules installer(libs.accesstransformers) - installer(libs.antlr.runtime) // Dep of AccessTransformer installer(libs.eventbus) installer(libs.typetools) // Dep of EventBus installer(libs.forgespi) @@ -135,10 +142,16 @@ dependencies { installer(project(':lowcodelanguage')) installer(project(':mclanguage')) + installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off") + runtimeOnly(libs.bootstrap) runtimeOnly(libs.bootstrap.dev) } +tasks.named('extractRangeMap').configure { + tool = S2S_TOOL +} + patcher { excs.from file("$rootDir/src/main/resources/forge.exc") parent = project(':mcp') @@ -362,33 +375,15 @@ tasks.register('extractInheritance', ExtractInheritance) { Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).toList() } } -tasks.register("findFieldInstanceChecks", FieldCompareFinder) { - jar = createJoinedSRG.output - output = rootProject.file('src/main/resources/coremods/field_to_instanceof.json') - fields { - /* 1.17 changed most things to use Tags. So this isn't nessasary anymore so just make an empty list - bows { - cls = 'net/minecraft/world/item/Items' - name = 'f_42411_' - replacement = 'net/minecraft/world/item/BowItem' - } - crossbows { - cls = 'net/minecraft/world/item/Items' - name = 'f_42717_' - replacement = 'net/minecraft/world/item/CrossbowItem' - } - */ - } -} tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) { jar = createJoinedSRG.output output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json') predicate = { parent, node, insn -> - 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it. - && insn.getOpcode() === Opcodes.INVOKEVIRTUAL + return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it. + && insn.getOpcode().equals(Opcodes.INVOKEVIRTUAL) && insn.name == 'm_6518_' - && insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;' + && insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;'; } } tasks.register('validateDeprecations', ValidateDeprecations) { @@ -428,43 +423,34 @@ tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks. args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath] outputs.file(output) } -tasks.register('mergeClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) { - ext.output = file('build/client_mappings_merged.tsrg') - tool = INSTALLER_TOOLS + ':fatjar' - args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadClientMappings.output.absolutePath, '--output', output.absolutePath] - outputs.file(output) -} -tasks.register('mergeServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) { - ext.output = file('build/server_mappings_merged.tsrg') - tool = INSTALLER_TOOLS + ':fatjar' - args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadServerMappings.output.absolutePath, '--output', output.absolutePath] - outputs.file(output) -} tasks.register("createJoinedSRG", DownloadMavenArtifact) { artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg" } -tasks.register("createClientSRG", RenameJar) { +tasks.register("createClientOfficial", RenameJar) { tool = FART + ':all' - args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'] - mappings = createMcp2Srg.srg - dependsOn(downloadClientRaw) + args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'] + mappings = downloadClientMappings.output + dependsOn(downloadClientRaw, downloadClientMappings) input = downloadClientRaw.dest - output = file("build/createClientSRG/output.jar") + output = file("build/createClientOfficial/output.jar") } -tasks.register("createServerSRG", RenameJar) { +tasks.register("createServerOfficial", RenameJar) { tool = FART + ':all' - args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'] - mappings = createMcp2Srg.srg + args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'] + mappings = downloadServerMappings.output + dependsOn(downloadServerMappings) input = extractServer.output - output = file("build/createServerSRG/output.jar") + output = file("build/createServerOfficial/output.jar") } tasks.named('genClientBinPatches').configure { tool = BINPATCH_TOOL - cleanJar = createClientSRG.output + cleanJar = createClientOfficial.output + dirtyJar = jar.archiveFile } tasks.named('genServerBinPatches').configure { tool = BINPATCH_TOOL - cleanJar = createServerSRG.output + cleanJar = createServerOfficial.output + dirtyJar = jar.archiveFile } tasks.named('genJoinedBinPatches').configure { tool = BINPATCH_TOOL @@ -472,13 +458,13 @@ tasks.named('genJoinedBinPatches').configure { } tasks.register('applyClientBinPatches', ApplyBinPatches) { tool = BINPATCH_TOOL - clean = createClientSRG.output + clean = createClientOfficial.output patch = genClientBinPatches.output args.addAll(['--data', '--unpatched']) } tasks.register('applyServerBinPatches', ApplyBinPatches) { tool = BINPATCH_TOOL - clean = createServerSRG.output + clean = createServerOfficial.output patch = genServerBinPatches.output args.addAll(['--data', '--unpatched']) } @@ -523,7 +509,7 @@ tasks.register('checkAll') { group = 'checks' } tasks.register('checkAllAndFix') { - dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses' + dependsOn 'findFinalizeSpawnTargets', 'checkLicenses' group = 'checks' } @@ -637,15 +623,12 @@ tasks.register('installerJson', InstallerJson) { // Download Official Mappings dependsOn(downloadClientMappings, downloadServerMappings) input.from(downloadClientMappings.output, downloadServerMappings.output) - // Merge MCP and Official Mappings - dependsOn(mergeClientMappings, mergeServerMappings) - input.from(mergeClientMappings.output, mergeServerMappings.output) // Get 'base' MC jar, Client is straight download, server is extracted from the bundle dependsOn(downloadClientRaw, extractServer) input.from(downloadClientRaw.dest, extractServer.output) // Rename MC Jar - dependsOn(createClientSRG, createServerSRG) - input.from(createClientSRG.output, createServerSRG.output) + dependsOn(createClientOfficial, createServerOfficial) + input.from(createClientOfficial.output, createServerOfficial.output) // Apply Binary patches to vanilla jar dependsOn(applyClientBinPatches, applyServerBinPatches) input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar) @@ -672,21 +655,13 @@ tasks.register('installerJson', InstallerJson) { server: "'${extractMCPConfigMappings.output.sha1}'" ], MOJMAPS: [ - client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]", - server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]" + client: "[net.minecraft:client:${MC_VERSION}:mappings@tsrg]", + server: "[net.minecraft:server:${MC_VERSION}:mappings@tsrg]" ], MOJMAPS_SHA: [ client: "'${downloadClientMappings.output.sha1}'", server: "'${downloadServerMappings.output.sha1}'" ], - MERGED_MAPPINGS: [ - client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]", - server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]" - ], - MERGED_MAPPINGS_SHA: [ - client: "'${mergeClientMappings.output.sha1}'", - server: "'${mergeServerMappings.output.sha1}'" - ], MC_UNPACKED: [ client: "[net.minecraft:client:${MC_VERSION}]", server: "[net.minecraft:server:${MC_VERSION}:unpacked]" @@ -695,13 +670,13 @@ tasks.register('installerJson', InstallerJson) { client: "'${downloadClientRaw.dest.sha1}'", server: "'${extractServer.output.get().asFile.sha1}'" ], - MC_SRG: [ - client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]", - server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]" + MC_OFF: [ + client: "[net.minecraft:client:${MC_VERSION}:official]", + server: "[net.minecraft:server:${MC_VERSION}:official]" ], - MC_SRG_SHA: [ - client: "'${createClientSRG.output.get().asFile.sha1}'", - server: "'${createServerSRG.output.get().asFile.sha1}'" + MC_OFF_SHA: [ + client: "'${createClientOfficial.output.get().asFile.sha1}'", + server: "'${createServerOfficial.output.get().asFile.sha1}'" ], BINPATCH: [ client: '/data/client.lzma', @@ -793,31 +768,18 @@ tasks.register('installerJson', InstallerJson) { outputs: [ '{MOJMAPS}': '{MOJMAPS_SHA}' ] - ], [ - jar: INSTALLER_TOOLS, - classpath: INSTALLER_TOOLS_CLASSPATH, - args: [ - '--task', 'MERGE_MAPPING', - '--left', '{MAPPINGS}', - '--right', '{MOJMAPS}', - '--output', '{MERGED_MAPPINGS}', - '--classes', '--reverse-right' - ], - outputs: [ - '{MERGED_MAPPINGS}': '{MERGED_MAPPINGS_SHA}' - ] ], [ sides: ['server'], jar: FART, classpath: getClasspath(project, libs, FART), args: [ '--input', '{MC_UNPACKED}', - '--output', '{MC_SRG}', - '--names', '{MERGED_MAPPINGS}', - '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs' + '--output', '{MC_OFF}', + '--names', '{MOJMAPS}', + '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse' ], outputs: [ - '{MC_SRG}': '{MC_SRG_SHA}' + '{MC_OFF}': '{MC_OFF_SHA}' ] ], [ sides: ['client'], @@ -825,18 +787,18 @@ tasks.register('installerJson', InstallerJson) { classpath: getClasspath(project, libs, FART), args: [ '--input', '{MINECRAFT_JAR}', - '--output', '{MC_SRG}', - '--names', '{MERGED_MAPPINGS}', - '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs' + '--output', '{MC_OFF}', + '--names', '{MOJMAPS}', + '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse' ], outputs: [ - '{MC_SRG}': '{MC_SRG_SHA}' + '{MC_OFF}': '{MC_OFF_SHA}' ] ], [ jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]), args: [ - '--clean', '{MC_SRG}', + '--clean', '{MC_OFF}', '--output', '{PATCHED}', '--apply', '{BINPATCH}', '--data', '--unpatched' @@ -851,6 +813,27 @@ tasks.register('installerJson', InstallerJson) { } } +tasks.register('officialClassesOnly', Zip).configure { + dependsOn(jar) + destinationDirectory = file('build/libs') + archiveClassifier = 'official-classes' + from zipTree(jar.archiveFile).matching { + include '**/*.class' + exclude 'mcp/**' + } +} + +tasks.named('filterJarNew').configure { + dependsOn('officialClassesOnly') + input = officialClassesOnly.archiveFile +} + +tasks.register('filterJarNewSRG', FilterNewJar).configure { + input = reobfJar.output + srg = filterJarNew.srg + blacklist = filterJarNew.blacklist +} + tasks.named('universalJar').configure { dependsOn downloadCrowdin from zipTree(downloadCrowdin.dest).matching { @@ -882,6 +865,20 @@ tasks.named('universalJar').configure { jarSigner.sign(it) } +tasks.register('universalJarSrg', Jar).configure { + from zipTree(filterJarNewSRG.output) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + from zipTree(universalJar.archiveFile) + destinationDirectory = file('build/libs') + archiveClassifier = 'universal-srg' + manifest.from(universalJar.manifest) + jarSigner.sign(it) +} + +tasks.named('userdevConfig').configure { + universal = "$project.group:$project.name:$project.version:universal-srg@jar" +} + tasks.register('installerJar', InstallerJar) { fat = !System.env.TEAMCITY_VERSION //offline = true @@ -1068,6 +1065,7 @@ tasks.named('javadoc', Javadoc).configure { publishing { publications.register('mavenJava', MavenPublication).configure { artifact universalJar + artifact universalJarSrg artifact installerJar artifact mdkZip artifact userdevJar @@ -1079,8 +1077,8 @@ publishing { name = project.name description = 'Modifactions to Minecraft to enable mod developers.' url = 'https://github.com/MinecraftForge/MinecraftForge' - PomUtils.setGitHubDetails(pom, 'MinecraftForge') - license PomUtils.Licenses.LGPLv2_1 + gradleutils.pom.setGitHubDetails(pom, 'MinecraftForge') + license gradleutils.pom.Licenses.LGPLv2_1 } } @@ -1090,5 +1088,5 @@ publishing { } // Make sure we run bin compat checking during local testing. -if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) +if ((!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) && CHECK_COMPATIBILITY == "true") tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') } diff --git a/fmlloader/build.gradle b/fmlloader/build.gradle index e91b2be9ba..0791ce3956 100644 --- a/fmlloader/build.gradle +++ b/fmlloader/build.gradle @@ -37,7 +37,7 @@ dependencies { implementation(libs.jimfs) implementation(libs.log4j.core) - annotationProcessor(libs.log4j.core) + annotationProcessor(libs.bundles.log4j) testCompileOnly(libs.nulls) testRuntimeOnly(libs.bootstrap) diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java index 767bdfa1ec..40715abc0d 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java @@ -77,7 +77,7 @@ public class MCPNamingService implements INameMappingService { } private static void loadMappings(final String mappingFileName, BiConsumer mapStore) { - URL path = ClassLoader.getSystemResource(mappingFileName); //We EXPLICITLY go through the SystemClassLoader here because this is dev-time only. And will be on the root classpath. + URL path = MCPNamingService.class.getClassLoader().getResource(mappingFileName); if (path == null) return; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeProdLaunchHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeProdLaunchHandler.java index 7698c8aebb..4651575ccc 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeProdLaunchHandler.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeProdLaunchHandler.java @@ -15,7 +15,7 @@ abstract class ForgeProdLaunchHandler extends CommonLaunchHandler { super(type, "forge_"); } - @Override public String getNaming() { return "srg"; } + @Override public String getNaming() { return "mcp"; } @Override public boolean isProduction() { return true; } public static class Client extends ForgeProdLaunchHandler { diff --git a/gradle.properties b/gradle.properties index 2f4f8e953e..4909162882 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,9 +4,14 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false org.gradle.parallel=true -JAVA_VERSION=17 -MC_VERSION=1.20.4 +JAVA_VERSION=21 +MC_VERSION=1.20.6 MC_NEXT_VERSION=1.21 -MCP_VERSION=20231207.112700 +MCP_VERSION=20240429.135109 MAPPING_CHANNEL=official -MAPPING_VERSION=1.20.4 +MAPPING_VERSION=1.20.6 + +// Set to true before the first build of a new MC version, so we don't do compatibility checks +CHECK_COMPATIBILITY=false +// Set to true to allow for fuzzy patching. Useful during updateing +UPDATING=false \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 309b4e18db..bb6c191947 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/mdk/build.gradle b/mdk/build.gradle index a905511f67..4d92d9f01a 100644 --- a/mdk/build.gradle +++ b/mdk/build.gradle @@ -12,8 +12,8 @@ base { archivesName = mod_id } -// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. -java.toolchain.languageVersion = JavaLanguageVersion.of(17) +// Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21. +java.toolchain.languageVersion = JavaLanguageVersion.of(21) println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { @@ -124,11 +124,11 @@ dependencies { // then special handling is done to allow a setup of a vanilla dependency without the use of an external repository. minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" - // Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings + // Example mod dependency with JEI // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime - // compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}") - // compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}") - // runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}") + // compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}" + // compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}" + // runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}" // Example mod dependency using a mod jar from ./libs with a flat dir repository // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar @@ -138,6 +138,9 @@ dependencies { // For more info: // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html + + // Hack fix for now, force jopt-simple to be exactly 5.0.4 because Mojang ships that version, but some transtive dependencies request 6.0+ + implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } } } // This block of code expands all declared replace properties in the specified resource targets. @@ -171,16 +174,8 @@ tasks.named('jar', Jar).configure { 'Implementation-Vendor' : mod_authors ]) } - - // This is the preferred method to reobfuscate your jar file - finalizedBy 'reobfJar' } -// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing: -// tasks.named('publish').configure { -// dependsOn 'reobfJar' -// } - // Example configuration to allow publishing using the maven-publish plugin publishing { publications { diff --git a/mdk/src/main/java/com/example/examplemod/ExampleMod.java b/mdk/src/main/java/com/example/examplemod/ExampleMod.java index 990fd6357b..478de83be4 100644 --- a/mdk/src/main/java/com/example/examplemod/ExampleMod.java +++ b/mdk/src/main/java/com/example/examplemod/ExampleMod.java @@ -51,7 +51,7 @@ public class ExampleMod // Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2 public static final RegistryObject EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder() - .alwaysEat().nutrition(1).saturationMod(2f).build()))); + .alwaysEdible().nutrition(1).saturationModifier(2f).build()))); // Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab public static final RegistryObject EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder() diff --git a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch index de00a9db4f..ee6584d735 100644 --- a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch @@ -1,56 +1,50 @@ --- a/com/mojang/blaze3d/pipeline/RenderTarget.java +++ b/com/mojang/blaze3d/pipeline/RenderTarget.java -@@ -113,7 +_,10 @@ - GlStateManager._texParameter(3553, 34892, 0); +@@ -113,11 +_,19 @@ + GlStateManager._bindTexture(this.colorTextureId); GlStateManager._texParameter(3553, 10242, 33071); GlStateManager._texParameter(3553, 10243, 33071); -+ if (!stencilEnabled) - GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, (IntBuffer)null); -+ else ++ if (!stencilEnabled) + GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, null); ++ else + GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null); - } + GlStateManager._glBindFramebuffer(36160, this.frameBufferId); + GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0); +- if (this.useDepth) { ++ if (this.useDepth && !stencilEnabled) { + GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0); ++ } else if(this.useDepth && net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) { ++ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0); ++ } else if (this.useDepth) { ++ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0); ++ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0); + } - this.setFilterMode(9728); -@@ -124,7 +_,14 @@ - GlStateManager._glBindFramebuffer(36160, this.frameBufferId); - GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0); - if (this.useDepth) { -+ if(!stencilEnabled) - GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0); -+ else if(net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) { -+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0); -+ } else { -+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0); -+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0); -+ } - } + this.checkStatus(); +@@ -280,5 +_,26 @@ - this.checkStatus(); -@@ -292,4 +_,27 @@ - public int getDepthTextureId() { - return this.depthBufferId; - } + public int getDepthTextureId() { + return this.depthBufferId; ++ } + -+ /*================================ FORGE START ================================================*/ -+ private boolean stencilEnabled = false; -+ /** -+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer. -+ * Modders must call this directly to set things up. -+ * This is to prevent the default cause where graphics cards do not support stencil bits. -+ * Make sure to call this on the main render thread! -+ */ -+ public void enableStencil() { -+ if(stencilEnabled) return; -+ stencilEnabled = true; -+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX); -+ } ++ private boolean stencilEnabled = false; ++ /** ++ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer. ++ * Modders must call this directly to set things up. ++ * This is to prevent the default cause where graphics cards do not support stencil bits. ++ * Make sure to call this on the main render thread! ++ */ ++ public void enableStencil() { ++ if (stencilEnabled) return; ++ stencilEnabled = true; ++ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX); ++ } + -+ /** -+ * Returns wither or not this FBO has been successfully initialized with stencil bits. -+ * If not, and a modder wishes it to be, they must call enableStencil. -+ */ -+ public boolean isStencilEnabled() { -+ return this.stencilEnabled; -+ } -+ /*================================ FORGE END ================================================*/ ++ /** ++ * Returns wither or not this FBO has been successfully initialized with stencil bits. ++ * If not, and a modder wishes it to be, they must call enableStencil. ++ */ ++ public boolean isStencilEnabled() { ++ return this.stencilEnabled; + } } diff --git a/patches/minecraft/com/mojang/blaze3d/platform/GlStateManager.java.patch b/patches/minecraft/com/mojang/blaze3d/platform/GlStateManager.java.patch index 4b63f12c0d..c260d9bbe0 100644 --- a/patches/minecraft/com/mojang/blaze3d/platform/GlStateManager.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/platform/GlStateManager.java.patch @@ -1,19 +1,20 @@ --- a/com/mojang/blaze3d/platform/GlStateManager.java +++ b/com/mojang/blaze3d/platform/GlStateManager.java -@@ -501,9 +_,16 @@ +@@ -493,9 +_,17 @@ + } + } - } ++ /* Stores the last values sent into glMultiTexCoord2f */ ++ public static float lastBrightnessX = 0.0f; ++ public static float lastBrightnessY = 0.0f; ++ + public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) { + RenderSystem.assertOnRenderThreadOrInit(); + GL11.glTexParameterf(p_84161_, p_84162_, p_84163_); ++ if (p_84161_ == GL13.GL_TEXTURE1) { ++ lastBrightnessX = p_84162_; ++ lastBrightnessY = p_84163_; ++ } + } -+ /* Stores the last values sent into glMultiTexCoord2f */ -+ public static float lastBrightnessX = 0.0f; -+ public static float lastBrightnessY = 0.0f; - public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) { - RenderSystem.assertOnRenderThreadOrInit(); - GL11.glTexParameterf(p_84161_, p_84162_, p_84163_); -+ if (p_84161_ == GL13.GL_TEXTURE1) { -+ lastBrightnessX = p_84162_; -+ lastBrightnessY = p_84163_; -+ } - } - - public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) { + public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) { diff --git a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch index 81fc698a05..e266b5cbcc 100644 --- a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch @@ -1,28 +1,30 @@ --- a/com/mojang/blaze3d/platform/Window.java +++ b/com/mojang/blaze3d/platform/Window.java -@@ -81,7 +_,8 @@ - GLFW.glfwWindowHint(139267, 2); - GLFW.glfwWindowHint(139272, 204801); - GLFW.glfwWindowHint(139270, 1); -- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L); -+ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L); -+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) { - if (monitor != null) { - VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); - this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2; -@@ -93,6 +_,7 @@ - this.windowedX = this.x = aint1[0]; - this.windowedY = this.y = aint[0]; - } -+ } +@@ -82,7 +_,8 @@ + GLFW.glfwWindowHint(139267, 2); + GLFW.glfwWindowHint(139272, 204801); + GLFW.glfwWindowHint(139270, 1); +- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L); ++ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L); ++ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) { + if (monitor != null) { + VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); + this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2; +@@ -94,6 +_,7 @@ + this.windowedX = this.x = aint1[0]; + this.windowedY = this.y = aint[0]; + } ++ } - GLFW.glfwMakeContextCurrent(this.window); - GL.createCapabilities(); -@@ -242,6 +_,7 @@ - GLFW.glfwGetFramebufferSize(this.window, aint, aint1); - this.framebufferWidth = aint[0] > 0 ? aint[0] : 1; - this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1; -+ if (this.framebufferHeight == 0 || this.framebufferWidth==0) net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w->this.framebufferWidth=w, h->this.framebufferHeight=h); - } + GLFW.glfwMakeContextCurrent(this.window); + GL.createCapabilities(); +@@ -242,6 +_,9 @@ + GLFW.glfwGetFramebufferSize(this.window, aint, aint1); + this.framebufferWidth = aint[0] > 0 ? aint[0] : 1; + this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1; ++ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) { ++ net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w -> this.framebufferWidth = w, h -> this.framebufferHeight = h); ++ } + } - private void onResize(long p_85428_, int p_85429_, int p_85430_) { + private void onResize(long p_85428_, int p_85429_, int p_85430_) { diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/BufferBuilder.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/BufferBuilder.java.patch index c7fda2cc7f..6fb76b19c2 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/BufferBuilder.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/BufferBuilder.java.patch @@ -1,17 +1,18 @@ --- a/com/mojang/blaze3d/vertex/BufferBuilder.java +++ b/com/mojang/blaze3d/vertex/BufferBuilder.java -@@ -477,4 +_,14 @@ - this.sorting = p_277855_; - } - } +@@ -389,6 +_,15 @@ + return MemoryUtil.memSlice(this.buffer, p_231170_, p_231171_ - p_231170_); + } + ++ public void putBulkData(ByteBuffer buffer) { ++ ensureCapacity(buffer.limit() + this.format.getVertexSize()); ++ this.buffer.position(this.nextElementByte); ++ this.buffer.put(buffer); ++ this.buffer.position(0); ++ this.vertices += buffer.limit() / this.format.getVertexSize(); ++ this.nextElementByte += buffer.limit(); ++ } + -+ // Forge start -+ public void putBulkData(ByteBuffer buffer) { -+ ensureCapacity(buffer.limit() + this.format.getVertexSize()); -+ this.buffer.position(this.nextElementByte); -+ this.buffer.put(buffer); -+ this.buffer.position(0); -+ this.vertices += buffer.limit() / this.format.getVertexSize(); -+ this.nextElementByte += buffer.limit(); -+ } - } + @OnlyIn(Dist.CLIENT) + public static record DrawState( + VertexFormat format, int vertexCount, int indexCount, VertexFormat.Mode mode, VertexFormat.IndexType indexType, boolean indexOnly, boolean sequentialIndex diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/PoseStack.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/PoseStack.java.patch index 53a7f103c5..d7121ee657 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/PoseStack.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/PoseStack.java.patch @@ -1,11 +1,11 @@ --- a/com/mojang/blaze3d/vertex/PoseStack.java +++ b/com/mojang/blaze3d/vertex/PoseStack.java -@@ -11,7 +_,7 @@ - import org.joml.Quaternionf; +@@ -13,7 +_,7 @@ + import org.joml.Vector3f; @OnlyIn(Dist.CLIENT) -public class PoseStack { +public class PoseStack implements net.minecraftforge.client.extensions.IForgePoseStack { - private final Deque poseStack = Util.make(Queues.newArrayDeque(), (p_85848_) -> { - Matrix4f matrix4f = new Matrix4f(); - Matrix3f matrix3f = new Matrix3f(); + private final Deque poseStack = Util.make(Queues.newArrayDeque(), p_85848_ -> { + Matrix4f matrix4f = new Matrix4f(); + Matrix3f matrix3f = new Matrix3f(); diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java.patch index ed1bfde335..556f94340f 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java.patch @@ -1,11 +1,11 @@ --- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java +++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java -@@ -46,7 +_,7 @@ - - public void endVertex() { - Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz)); -- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z()); -+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z()); - Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F)); - vector4f.rotateY((float)Math.PI); - vector4f.rotateX((-(float)Math.PI / 2F)); +@@ -47,7 +_,7 @@ + @Override + public void endVertex() { + Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz)); +- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z()); ++ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z()); + Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F)); + vector4f.rotateY((float) Math.PI); + vector4f.rotateX((float) (-Math.PI / 2)); diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/VertexConsumer.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/VertexConsumer.java.patch index e5d73fa6da..1492481869 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/VertexConsumer.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/VertexConsumer.java.patch @@ -1,38 +1,24 @@ --- a/com/mojang/blaze3d/vertex/VertexConsumer.java +++ b/com/mojang/blaze3d/vertex/VertexConsumer.java -@@ -14,7 +_,7 @@ +@@ -13,7 +_,7 @@ import org.lwjgl.system.MemoryStack; @OnlyIn(Dist.CLIENT) -public interface VertexConsumer { +public interface VertexConsumer extends net.minecraftforge.client.extensions.IForgeVertexConsumer { - VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_); + VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_); - VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_); -@@ -64,6 +_,10 @@ - } + VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_); +@@ -142,10 +_,11 @@ + f5 = afloat[k] * p_85992_; + } - default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, int[] p_86002_, int p_86003_, boolean p_86004_) { -+ putBulkData(p_85996_, p_85997_, p_85998_, p_85999_, p_86000_, p_86001_, 1, p_86002_, p_86003_, p_86004_); -+ } -+ -+ default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, float alpha, int[] p_86002_, int p_86003_, boolean p_86004_) { - float[] afloat = new float[]{p_85998_[0], p_85998_[1], p_85998_[2], p_85998_[3]}; - int[] aint = new int[]{p_86002_[0], p_86002_[1], p_86002_[2], p_86002_[3]}; - int[] aint1 = p_85997_.getVertices(); -@@ -99,11 +_,13 @@ - f5 = afloat[k] * p_86001_; +- int l = aint[k]; ++ int l = applyBakedLighting(aint[k], bytebuffer); + float f9 = bytebuffer.getFloat(16); + float f10 = bytebuffer.getFloat(20); + Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F)); ++ applyBakedNormals(vector3f, bytebuffer, p_85988_.normal()); + this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, p_335371_, f9, f10, p_85993_, l, vector3f.x(), vector3f.y(), vector3f.z()); } - -- int l = aint[k]; -+ int l = applyBakedLighting(p_86002_[k], bytebuffer); - float f9 = bytebuffer.getFloat(16); - float f10 = bytebuffer.getFloat(20); - Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F)); -- this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, 1.0F, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z()); -+ applyBakedNormals(vector3f, bytebuffer, p_85996_.normal()); -+ float vertexAlpha = p_86004_ ? alpha * (float) (bytebuffer.get(15) & 255) / 255.0F : alpha; -+ this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, vertexAlpha, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z()); - } - } - + } diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch index 071270d1d8..dcf00584be 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch @@ -1,14 +1,16 @@ --- a/com/mojang/blaze3d/vertex/VertexFormat.java +++ b/com/mojang/blaze3d/vertex/VertexFormat.java -@@ -176,4 +_,11 @@ - return i; - } - } +@@ -114,6 +_,13 @@ + return vertexbuffer; + } + ++ public ImmutableMap getElementMapping() { return elementMapping; } ++ public int getOffset(int index) { return offsets.getInt(index); } ++ public boolean hasPosition() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.POSITION); } ++ public boolean hasNormal() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.NORMAL); } ++ public boolean hasColor() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.COLOR); } ++ public boolean hasUV(int which) { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == which); } + -+ public ImmutableMap getElementMapping() { return elementMapping; } -+ public int getOffset(int index) { return offsets.getInt(index); } -+ public boolean hasPosition() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.POSITION); } -+ public boolean hasNormal() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.NORMAL); } -+ public boolean hasColor() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.COLOR); } -+ public boolean hasUV(int which) { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == which); } - } + @OnlyIn(Dist.CLIENT) + public static enum IndexType { + SHORT(5123, 2), diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormatElement.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormatElement.java.patch deleted file mode 100644 index cedb5111eb..0000000000 --- a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormatElement.java.patch +++ /dev/null @@ -1,13 +0,0 @@ ---- a/com/mojang/blaze3d/vertex/VertexFormatElement.java -+++ b/com/mojang/blaze3d/vertex/VertexFormatElement.java -@@ -90,6 +_,10 @@ - this.usage.clearBufferState(this.index, p_166964_); - } - -+ public int getElementCount() { -+ return count; -+ } -+ - @OnlyIn(Dist.CLIENT) - public static enum Type { - FLOAT(4, "Float", 5126), diff --git a/patches/minecraft/com/mojang/math/Transformation.java.patch b/patches/minecraft/com/mojang/math/Transformation.java.patch index 1f58795a6b..000bd8ef2b 100644 --- a/patches/minecraft/com/mojang/math/Transformation.java.patch +++ b/patches/minecraft/com/mojang/math/Transformation.java.patch @@ -1,31 +1,31 @@ --- a/com/mojang/math/Transformation.java +++ b/com/mojang/math/Transformation.java @@ -13,7 +_,7 @@ + import org.joml.Quaternionf; import org.joml.Vector3f; - import org.joml.Vector3fc; -public final class Transformation { +public final class Transformation implements net.minecraftforge.common.extensions.IForgeTransformation { - private final Matrix4f matrix; - public static final Codec CODEC = RecordCodecBuilder.create((p_269604_) -> { - return p_269604_.group(ExtraCodecs.VECTOR3F.fieldOf("translation").forGetter((p_269599_) -> { -@@ -156,6 +_,19 @@ - public int hashCode() { - return Objects.hash(this.matrix); - } + private final Matrix4f matrix; + public static final Codec CODEC = RecordCodecBuilder.create( + p_269604_ -> p_269604_.group( +@@ -169,5 +_,19 @@ + vector3f1.lerp(p_175938_.getScale(), p_175939_); + quaternionf1.slerp(p_175938_.getRightRotation(), p_175939_); + return new Transformation(vector3f, quaternionf, vector3f1, quaternionf1); ++ } + + private Matrix3f normalTransform = null; + public Matrix3f getNormalMatrix() { + checkNormalTransform(); + return normalTransform; + } ++ + private void checkNormalTransform() { + if (normalTransform == null) { + normalTransform = new Matrix3f(matrix); + normalTransform.invert(); + normalTransform.transpose(); + } -+ } - - public Transformation slerp(Transformation p_175938_, float p_175939_) { - Vector3f vector3f = this.getTranslation(); + } + } diff --git a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch index f3f463e97a..e28eada9d5 100644 --- a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch +++ b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch @@ -1,10 +1,9 @@ --- a/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java +++ b/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java -@@ -61,6 +_,15 @@ - return Component.empty().append(this.lines.title).append(": ").append(this.lines.detail); - } +@@ -71,6 +_,15 @@ + } -+ @Override + @Override + public boolean keyPressed(int key, int scanCode, int modifiers) { + if (key == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) { + minecraft.setScreen(this.nextScreen); @@ -13,6 +12,7 @@ + return super.keyPressed(key, scanCode, modifiers); + } + - public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) { - super.render(p_283497_, p_88680_, p_88681_, p_88682_); - p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1); ++ @Override + public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) { + super.render(p_283497_, p_88680_, p_88681_, p_88682_); + p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1); diff --git a/patches/minecraft/net/minecraft/CrashReport.java.patch b/patches/minecraft/net/minecraft/CrashReport.java.patch index 33d672bdb6..c86740726f 100644 --- a/patches/minecraft/net/minecraft/CrashReport.java.patch +++ b/patches/minecraft/net/minecraft/CrashReport.java.patch @@ -1,48 +1,48 @@ --- a/net/minecraft/CrashReport.java +++ b/net/minecraft/CrashReport.java @@ -59,14 +_,9 @@ - if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) { - p_127520_.append("-- Head --\n"); - p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n"); -- p_127520_.append("Stacktrace:\n"); + if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) { + p_127520_.append("-- Head --\n"); + p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n"); +- p_127520_.append("Stacktrace:\n"); +- +- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) { +- p_127520_.append("\t").append("at ").append(stacktraceelement); +- p_127520_.append("\n"); +- } - -- for(StackTraceElement stacktraceelement : this.uncategorizedStackTrace) { -- p_127520_.append("\t").append("at ").append((Object)stacktraceelement); - p_127520_.append("\n"); -- } -- -- p_127520_.append("\n"); -+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace)); -+ p_127520_.append("Stacktrace:"); -+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace)); - } ++ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace)); ++ p_127520_.append("Stacktrace:"); ++ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace)); + } - for(CrashReportCategory crashreportcategory : this.details) { + for (CrashReportCategory crashreportcategory : this.details) { @@ -74,6 +_,7 @@ - p_127520_.append("\n\n"); - } + p_127520_.append("\n\n"); + } -+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport); - this.systemReport.appendToCrashReportString(p_127520_); - } ++ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport); + this.systemReport.appendToCrashReportString(p_127520_); + } @@ -93,18 +_,7 @@ - throwable.setStackTrace(this.exception.getStackTrace()); - } + throwable.setStackTrace(this.exception.getStackTrace()); + } -- String s; -- try { -- stringwriter = new StringWriter(); -- printwriter = new PrintWriter(stringwriter); -- throwable.printStackTrace(printwriter); -- s = stringwriter.toString(); -- } finally { -- IOUtils.closeQuietly((Writer)stringwriter); -- IOUtils.closeQuietly((Writer)printwriter); -- } +- String s; +- try { +- stringwriter = new StringWriter(); +- printwriter = new PrintWriter(stringwriter); +- throwable.printStackTrace(printwriter); +- s = stringwriter.toString(); +- } finally { +- IOUtils.closeQuietly((Writer)stringwriter); +- IOUtils.closeQuietly((Writer)printwriter); +- } - -- return s; -+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable); - } +- return s; ++ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable); + } - public String getFriendlyReport() { + public String getFriendlyReport() { diff --git a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch index 8e9d1e12c9..68be11a5d5 100644 --- a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch +++ b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch @@ -1,38 +1,37 @@ --- a/net/minecraft/CrashReportCategory.java +++ b/net/minecraft/CrashReportCategory.java -@@ -102,8 +_,10 @@ - if (astacktraceelement.length <= 0) { - return 0; - } else { -- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_]; -- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length); -+ int len = astacktraceelement.length - 3 - p_128149_; -+ if (len <= 0) len = astacktraceelement.length; -+ this.stackTrace = new StackTraceElement[len]; -+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length); - return this.stackTrace.length; - } - } -@@ -147,17 +_,17 @@ +@@ -112,8 +_,10 @@ + if (astacktraceelement.length <= 0) { + return 0; + } else { +- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_]; +- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length); ++ int len = astacktraceelement.length - 3 - p_128149_; ++ if (len <= 0) len = astacktraceelement.length; ++ this.stackTrace = new StackTraceElement[len]; ++ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length); + return this.stackTrace.length; + } + } +@@ -160,16 +_,16 @@ - if (this.stackTrace != null && this.stackTrace.length > 0) { - p_128169_.append("\nStacktrace:"); + if (this.stackTrace != null && this.stackTrace.length > 0) { + p_128169_.append("\nStacktrace:"); - -- for(StackTraceElement stacktraceelement : this.stackTrace) { -- p_128169_.append("\n\tat "); -- p_128169_.append((Object)stacktraceelement); -- } -+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace)); - } +- for (StackTraceElement stacktraceelement : this.stackTrace) { +- p_128169_.append("\n\tat "); +- p_128169_.append(stacktraceelement); +- } ++ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace)); + } + } - } - - public StackTraceElement[] getStacktrace() { - return this.stackTrace; -+ } + public StackTraceElement[] getStacktrace() { + return this.stackTrace; ++ } + -+ public void applyStackTrace(Throwable t) { -+ this.stackTrace = t.getStackTrace(); - } ++ public void applyStackTrace(Throwable t) { ++ this.stackTrace = t.getStackTrace(); + } - public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) { + public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) { diff --git a/patches/minecraft/net/minecraft/SharedConstants.java.patch b/patches/minecraft/net/minecraft/SharedConstants.java.patch index 437da75173..578d3eea38 100644 --- a/patches/minecraft/net/minecraft/SharedConstants.java.patch +++ b/patches/minecraft/net/minecraft/SharedConstants.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/SharedConstants.java +++ b/net/minecraft/SharedConstants.java -@@ -215,6 +_,7 @@ - } +@@ -181,6 +_,7 @@ + } - static { -+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified - ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION); - CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false; - CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions(); + static { ++ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified + ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION); + CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false; + CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions(); diff --git a/patches/minecraft/net/minecraft/Util.java.patch b/patches/minecraft/net/minecraft/Util.java.patch index 7337f3fb16..52a00eeaec 100644 --- a/patches/minecraft/net/minecraft/Util.java.patch +++ b/patches/minecraft/net/minecraft/Util.java.patch @@ -1,23 +1,11 @@ --- a/net/minecraft/Util.java +++ b/net/minecraft/Util.java -@@ -180,6 +_,11 @@ - return 255; - } - -+ // We add these inner classes to compensate for Mojang's missing inner classes and shift the anonymous class index. -+ // This allows us to obfuscate subsequent anonymous inner classes correctly. -+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT1 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } }; -+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT2 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } }; -+ - public static ExecutorService backgroundExecutor() { - return BACKGROUND_EXECUTOR; - } -@@ -254,7 +_,7 @@ - try { - type = DataFixers.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())).getChoiceType(p_137552_, p_137553_); - } catch (IllegalArgumentException illegalargumentexception) { -- LOGGER.error("No data fixer registered for {}", (Object)p_137553_); -+ LOGGER.debug("No data fixer registered for {}", (Object)p_137553_); - if (SharedConstants.IS_RUNNING_IN_IDE) { - throw illegalargumentexception; - } +@@ -267,7 +_,7 @@ + .getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())) + .getChoiceType(p_137552_, p_137553_); + } catch (IllegalArgumentException illegalargumentexception) { +- LOGGER.error("No data fixer registered for {}", p_137553_); ++ LOGGER.debug("No data fixer registered for {}", p_137553_); + if (SharedConstants.IS_RUNNING_IN_IDE) { + throw illegalargumentexception; + } diff --git a/patches/minecraft/net/minecraft/advancements/Advancement.java.patch b/patches/minecraft/net/minecraft/advancements/Advancement.java.patch index 561428a8bd..aade55343d 100644 --- a/patches/minecraft/net/minecraft/advancements/Advancement.java.patch +++ b/patches/minecraft/net/minecraft/advancements/Advancement.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/advancements/Advancement.java +++ b/net/minecraft/advancements/Advancement.java -@@ -171,7 +_,11 @@ - } +@@ -214,7 +_,11 @@ + } - public AdvancementHolder save(Consumer p_138390_, String p_138391_) { -- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_)); -+ return save(p_138390_, new ResourceLocation(p_138391_)); -+ } + public AdvancementHolder save(Consumer p_138390_, String p_138391_) { +- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_)); ++ return save(p_138390_, new ResourceLocation(p_138391_)); ++ } + -+ public AdvancementHolder save(Consumer p_138390_, ResourceLocation id) { -+ AdvancementHolder advancementholder = this.build(id); - p_138390_.accept(advancementholder); - return advancementholder; - } ++ public AdvancementHolder save(Consumer p_138390_, ResourceLocation id) { ++ AdvancementHolder advancementholder = this.build(id); + p_138390_.accept(advancementholder); + return advancementholder; + } diff --git a/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch b/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch index 571ebedca2..55fdf25a68 100644 --- a/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch +++ b/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch @@ -1,11 +1,10 @@ --- a/net/minecraft/advancements/AdvancementRewards.java +++ b/net/minecraft/advancements/AdvancementRewards.java -@@ -27,7 +_,7 @@ +@@ -40,6 +_,7 @@ + LootParams lootparams = new LootParams.Builder(p_9990_.serverLevel()) + .withParameter(LootContextParams.THIS_ENTITY, p_9990_) + .withParameter(LootContextParams.ORIGIN, p_9990_.position()) ++ .withLuck(p_9990_.getLuck()) + .create(LootContextParamSets.ADVANCEMENT_REWARD); + boolean flag = false; - public void grant(ServerPlayer p_9990_) { - p_9990_.giveExperiencePoints(this.experience); -- LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).create(LootContextParamSets.ADVANCEMENT_REWARD); -+ LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).withLuck(p_9990_.getLuck()).create(LootContextParamSets.ADVANCEMENT_REWARD); // Forge: Add luck to LootContext - boolean flag = false; - - for(ResourceLocation resourcelocation : this.loot) { diff --git a/patches/minecraft/net/minecraft/advancements/critereon/ItemPredicate.java.patch b/patches/minecraft/net/minecraft/advancements/critereon/ItemPredicate.java.patch deleted file mode 100644 index 1e0867f5de..0000000000 --- a/patches/minecraft/net/minecraft/advancements/critereon/ItemPredicate.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/advancements/critereon/ItemPredicate.java -+++ b/net/minecraft/advancements/critereon/ItemPredicate.java -@@ -45,7 +_,7 @@ - return false; - } else { - if (!this.enchantments.isEmpty()) { -- Map map = EnchantmentHelper.deserializeEnchantments(p_45050_.getEnchantmentTags()); -+ Map map = p_45050_.getAllEnchantments(); - - for(EnchantmentPredicate enchantmentpredicate : this.enchantments) { - if (!enchantmentpredicate.containedIn(map)) { diff --git a/patches/minecraft/net/minecraft/client/Camera.java.patch b/patches/minecraft/net/minecraft/client/Camera.java.patch index 90b7599b05..6c1ba59508 100644 --- a/patches/minecraft/net/minecraft/client/Camera.java.patch +++ b/patches/minecraft/net/minecraft/client/Camera.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/client/Camera.java +++ b/net/minecraft/client/Camera.java -@@ -212,6 +_,18 @@ - return this.partialTickTime; - } +@@ -227,6 +_,18 @@ + return this.partialTickTime; + } -+ public void setAnglesInternal(float yaw, float pitch) { -+ this.yRot = yaw; -+ this.xRot = pitch; -+ } ++ public void setAnglesInternal(float yaw, float pitch) { ++ this.yRot = yaw; ++ this.xRot = pitch; ++ } + -+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() { -+ if (!this.initialized) -+ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(); -+ else -+ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position); -+ } ++ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() { ++ if (!this.initialized) ++ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(); ++ else ++ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position); ++ } + - @OnlyIn(Dist.CLIENT) - public static class NearPlane { - final Vec3 forward; + @OnlyIn(Dist.CLIENT) + public static class NearPlane { + final Vec3 forward; diff --git a/patches/minecraft/net/minecraft/client/ClientBrandRetriever.java.patch b/patches/minecraft/net/minecraft/client/ClientBrandRetriever.java.patch index f455031da3..c61a6ce71e 100644 --- a/patches/minecraft/net/minecraft/client/ClientBrandRetriever.java.patch +++ b/patches/minecraft/net/minecraft/client/ClientBrandRetriever.java.patch @@ -2,9 +2,9 @@ +++ b/net/minecraft/client/ClientBrandRetriever.java @@ -10,6 +_,6 @@ - @DontObfuscate - public static String getClientModName() { -- return "vanilla"; -+ return net.minecraftforge.internal.BrandingControl.getClientBranding(); - } + @DontObfuscate + public static String getClientModName() { +- return "vanilla"; ++ return net.minecraftforge.internal.BrandingControl.getClientBranding(); + } } diff --git a/patches/minecraft/net/minecraft/client/ClientRecipeBook.java.patch b/patches/minecraft/net/minecraft/client/ClientRecipeBook.java.patch index 051f10074f..264d3465e3 100644 --- a/patches/minecraft/net/minecraft/client/ClientRecipeBook.java.patch +++ b/patches/minecraft/net/minecraft/client/ClientRecipeBook.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/ClientRecipeBook.java +++ b/net/minecraft/client/ClientRecipeBook.java -@@ -56,7 +_,7 @@ - Recipe recipe = recipeholder.value(); - if (!recipe.isSpecial() && !recipe.isIncomplete()) { - RecipeBookCategories recipebookcategories = getCategory(recipeholder); -- String s = recipe.getGroup(); -+ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty. - if (s.isEmpty()) { - map.computeIfAbsent(recipebookcategories, (p_90645_) -> { - return Lists.newArrayList(); -@@ -144,6 +_,8 @@ - } else if (recipetype == RecipeType.SMITHING) { - return RecipeBookCategories.SMITHING; - } else { -+ RecipeBookCategories categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType) recipetype, p_299041_); -+ if (categories != null) return categories; - LOGGER.warn("Unknown recipe category: {}/{}", LogUtils.defer(() -> { - return BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType()); - }), LogUtils.defer(p_299041_::id)); +@@ -65,7 +_,7 @@ + Recipe recipe = recipeholder.value(); + if (!recipe.isSpecial() && !recipe.isIncomplete()) { + RecipeBookCategories recipebookcategories = getCategory(recipeholder); +- String s = recipe.getGroup(); ++ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty. + if (s.isEmpty()) { + map.computeIfAbsent(recipebookcategories, p_90645_ -> Lists.newArrayList()).add(ImmutableList.of(recipeholder)); + } else { +@@ -125,6 +_,8 @@ + } else if (recipetype == RecipeType.SMITHING) { + return RecipeBookCategories.SMITHING; + } else { ++ var categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType)recipetype, p_299041_); ++ if (categories != null) return categories; + LOGGER.warn( + "Unknown recipe category: {}/{}", + LogUtils.defer(() -> BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType())), diff --git a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch index 595f3296d9..5630279bf4 100644 --- a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch @@ -1,182 +1,183 @@ --- a/net/minecraft/client/KeyMapping.java +++ b/net/minecraft/client/KeyMapping.java -@@ -13,9 +_,9 @@ +@@ -14,9 +_,9 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) -public class KeyMapping implements Comparable { +public class KeyMapping implements Comparable, net.minecraftforge.client.extensions.IForgeKeyMapping { - private static final Map ALL = Maps.newHashMap(); -- private static final Map MAP = Maps.newHashMap(); -+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup(); - private static final Set CATEGORIES = Sets.newHashSet(); - public static final String CATEGORY_MOVEMENT = "key.categories.movement"; - public static final String CATEGORY_MISC = "key.categories.misc"; -@@ -41,7 +_,7 @@ - private int clickCount; + private static final Map ALL = Maps.newHashMap(); +- private static final Map MAP = Maps.newHashMap(); ++ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup(); + private static final Set CATEGORIES = Sets.newHashSet(); + public static final String CATEGORY_MOVEMENT = "key.categories.movement"; + public static final String CATEGORY_MISC = "key.categories.misc"; +@@ -42,14 +_,14 @@ + private int clickCount; - public static void click(InputConstants.Key p_90836_) { -- KeyMapping keymapping = MAP.get(p_90836_); -+ for (KeyMapping keymapping : MAP.getAll(p_90836_)) - if (keymapping != null) { - ++keymapping.clickCount; - } -@@ -49,7 +_,7 @@ - } + public static void click(InputConstants.Key p_90836_) { +- KeyMapping keymapping = MAP.get(p_90836_); ++ for (KeyMapping keymapping : MAP.getAll(p_90836_)) + if (keymapping != null) { + keymapping.clickCount++; + } + } - public static void set(InputConstants.Key p_90838_, boolean p_90839_) { -- KeyMapping keymapping = MAP.get(p_90838_); -+ for (KeyMapping keymapping : MAP.getAll(p_90838_)) - if (keymapping != null) { - keymapping.setDown(p_90839_); - } -@@ -105,7 +_,7 @@ - } + public static void set(InputConstants.Key p_90838_, boolean p_90839_) { +- KeyMapping keymapping = MAP.get(p_90838_); ++ for (KeyMapping keymapping : MAP.getAll(p_90838_)) + if (keymapping != null) { + keymapping.setDown(p_90839_); + } +@@ -100,7 +_,7 @@ + } - public boolean isDown() { -- return this.isDown; -+ return this.isDown && isConflictContextAndModifierActive(); - } + public boolean isDown() { +- return this.isDown; ++ return this.isDown && isConflictContextAndModifierActive(); + } - public String getCategory() { -@@ -139,7 +_,13 @@ - } + public String getCategory() { +@@ -136,7 +_,16 @@ + public int compareTo(KeyMapping p_90841_) { + return this.category.equals(p_90841_.category) + ? I18n.get(this.name).compareTo(I18n.get(p_90841_.name)) +- : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category)); ++ : compareSort(this.category, p_90841_.category); ++ } ++ ++ private static int compareSort(String c1, String c2) { ++ Integer o1 = CATEGORY_SORT_ORDER.get(c1); ++ Integer o2 = CATEGORY_SORT_ORDER.get(c2); ++ if (o1 == null && o2 != null) return 1; ++ if (o1 != null && o2 == null) return -1; ++ if (o1 == null && o2 == null) return I18n.get(c1).compareTo(I18n.get(c2)); ++ return o1.compareTo(o2); + } - public int compareTo(KeyMapping p_90841_) { -- return this.category.equals(p_90841_.category) ? I18n.get(this.name).compareTo(I18n.get(p_90841_.name)) : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category)); -+ if (this.category.equals(p_90841_.category)) return I18n.get(this.name).compareTo(I18n.get(p_90841_.name)); -+ Integer tCat = CATEGORY_SORT_ORDER.get(this.category); -+ Integer oCat = CATEGORY_SORT_ORDER.get(p_90841_.category); -+ if (tCat == null && oCat != null) return 1; -+ if (tCat != null && oCat == null) return -1; -+ if (tCat == null && oCat == null) return I18n.get(this.category).compareTo(I18n.get(p_90841_.category)); -+ return tCat.compareTo(oCat); - } + public static Supplier createNameSupplier(String p_90843_) { +@@ -145,6 +_,20 @@ + } - public static Supplier createNameSupplier(String p_90843_) { -@@ -150,6 +_,20 @@ - } - - public boolean same(KeyMapping p_90851_) { -+ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) { -+ net.minecraftforge.client.settings.KeyModifier keyModifier = getKeyModifier(); -+ net.minecraftforge.client.settings.KeyModifier otherKeyModifier = p_90851_.getKeyModifier(); -+ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) { -+ return true; -+ } else if (getKey().equals(p_90851_.getKey())) { -+ // IN_GAME key contexts have a conflict when at least one modifier is NONE. -+ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E. -+ // GUI and other key contexts do not have this limitation. -+ return keyModifier == otherKeyModifier || -+ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) && -+ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE)); + public boolean same(KeyMapping p_90851_) { ++ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) { ++ var keyModifier = getKeyModifier(); ++ var otherKeyModifier = p_90851_.getKeyModifier(); ++ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) { ++ return true; ++ } else if (getKey().equals(p_90851_.getKey())) { ++ // IN_GAME key contexts have a conflict when at least one modifier is NONE. ++ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E. ++ // GUI and other key contexts do not have this limitation. ++ return keyModifier == otherKeyModifier || ++ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) && ++ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE)); ++ } + } -+ } - return this.key.equals(p_90851_.key); - } + return this.key.equals(p_90851_.key); + } -@@ -170,11 +_,13 @@ - } +@@ -163,11 +_,13 @@ + } - public Component getTranslatedKeyMessage() { -+ return getKeyModifier().getCombinedName(key, () -> { - return this.key.getDisplayName(); -+ }); - } + public Component getTranslatedKeyMessage() { ++ return getKeyModifier().getCombinedName(key, () -> { + return this.key.getDisplayName(); ++ }); + } - public boolean isDefault() { -- return this.key.equals(this.defaultKey); -+ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier(); - } + public boolean isDefault() { +- return this.key.equals(this.defaultKey); ++ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier(); + } - public String saveString() { -@@ -183,5 +_,89 @@ + public String saveString() { +@@ -176,5 +_,88 @@ - public void setDown(boolean p_90846_) { - this.isDown = p_90846_; -+ } + public void setDown(boolean p_90846_) { + this.isDown = p_90846_; ++ } + -+ /****************** Forge Start *****************************/ -+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE; -+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; -+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL; ++ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE; ++ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; ++ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL; + -+ /** -+ * Convenience constructor for creating KeyBindings with keyConflictContext set. -+ */ -+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) { -+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category); -+ } ++ /** ++ * Convenience constructor for creating KeyBindings with keyConflictContext set. ++ */ ++ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) { ++ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category); ++ } + -+ /** -+ * Convenience constructor for creating KeyBindings with keyConflictContext set. -+ */ -+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) { -+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category); -+ } ++ /** ++ * Convenience constructor for creating KeyBindings with keyConflictContext set. ++ */ ++ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) { ++ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category); ++ } + -+ /** -+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. -+ */ -+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) { -+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category); -+ } -+ -+ /** -+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. -+ */ -+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) { -+ this.name = description; -+ this.key = keyCode; -+ this.defaultKey = keyCode; -+ this.category = category; -+ this.keyConflictContext = keyConflictContext; -+ this.keyModifier = keyModifier; -+ this.keyModifierDefault = keyModifier; -+ if (this.keyModifier.matches(keyCode)) -+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; -+ ALL.put(description, this); -+ MAP.put(keyCode, this); -+ CATEGORIES.add(category); -+ } -+ -+ @Override -+ public InputConstants.Key getKey() { -+ return this.key; -+ } -+ -+ @Override -+ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) { -+ this.keyConflictContext = keyConflictContext; -+ } -+ -+ @Override -+ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() { -+ return keyConflictContext; -+ } -+ -+ @Override -+ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() { -+ return keyModifierDefault; -+ } -+ -+ @Override -+ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() { -+ return keyModifier; -+ } -+ -+ @Override -+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) { -+ MAP.remove(this); -+ -+ if (keyModifier == null) -+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key); -+ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode)) -+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; ++ /** ++ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. ++ */ ++ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) { ++ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category); ++ } + ++ /** ++ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. ++ */ ++ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) { ++ this.name = description; + this.key = keyCode; ++ this.defaultKey = keyCode; ++ this.category = category; ++ this.keyConflictContext = keyConflictContext; + this.keyModifier = keyModifier; -+ ++ this.keyModifierDefault = keyModifier; ++ if (this.keyModifier.matches(keyCode)) ++ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; ++ ALL.put(description, this); + MAP.put(keyCode, this); - } ++ CATEGORIES.add(category); ++ } ++ ++ @Override ++ public InputConstants.Key getKey() { ++ return this.key; ++ } ++ ++ @Override ++ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) { ++ this.keyConflictContext = keyConflictContext; ++ } ++ ++ @Override ++ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() { ++ return keyConflictContext; ++ } ++ ++ @Override ++ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() { ++ return keyModifierDefault; ++ } ++ ++ @Override ++ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() { ++ return keyModifier; ++ } ++ ++ @Override ++ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) { ++ MAP.remove(this); ++ ++ if (keyModifier == null) ++ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key); ++ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode)) ++ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; ++ ++ this.key = keyCode; ++ this.keyModifier = keyModifier; ++ ++ MAP.put(keyCode, this); + } } diff --git a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch index ddd2ef2bd9..f7caacad9c 100644 --- a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch @@ -1,50 +1,39 @@ --- a/net/minecraft/client/KeyboardHandler.java +++ b/net/minecraft/client/KeyboardHandler.java -@@ -397,11 +_,15 @@ - Screen.wrapScreenError(() -> { - if (p_90897_ != 1 && p_90897_ != 2) { - if (p_90897_ == 0) { -- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_); -+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPre(screen, p_90895_, p_90896_, p_90898_); -+ if (!aboolean[0]) aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_); -+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPost(screen, p_90895_, p_90896_, p_90898_); - } - } else { - screen.afterKeyboardAction(); -- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_); -+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPre(screen, p_90895_, p_90896_, p_90898_); -+ if (!aboolean[0]) aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_); -+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPost(screen, p_90895_, p_90896_, p_90898_); - } - - }, "keyPressed event handler", screen.getClass().getCanonicalName()); -@@ -478,21 +_,26 @@ +@@ -410,9 +_,9 @@ + Screen.wrapScreenError(() -> { + if (p_90897_ == 1 || p_90897_ == 2) { + screen.afterKeyboardAction(); +- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_); ++ net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(aboolean, screen, p_90895_, p_90896_, p_90898_); + } else if (p_90897_ == 0) { +- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_); ++ net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(aboolean, screen, p_90895_, p_90896_, p_90898_); + } + }, "keyPressed event handler", screen.getClass().getCanonicalName()); + if (aboolean[0]) { +@@ -481,20 +_,21 @@ + } + } } ++ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_); + } + } - } -+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_); - } - } - - private void charTyped(long p_90890_, int p_90891_, int p_90892_) { - if (p_90890_ == this.minecraft.getWindow().getWindow()) { -- GuiEventListener guieventlistener = this.minecraft.screen; -+ Screen guieventlistener = this.minecraft.screen; - if (guieventlistener != null && this.minecraft.getOverlay() == null) { - if (Character.charCount(p_90891_) == 1) { - Screen.wrapScreenError(() -> { -- guieventlistener.charTyped((char)p_90891_, p_90892_); -+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, (char)p_90891_, p_90892_)) return; -+ if (guieventlistener.charTyped((char)p_90891_, p_90892_)) return; -+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, (char)p_90891_, p_90892_); - }, "charTyped event handler", guieventlistener.getClass().getCanonicalName()); - } else { - for(char c0 : Character.toChars(p_90891_)) { - Screen.wrapScreenError(() -> { -- guieventlistener.charTyped(c0, p_90892_); -+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, c0, p_90892_)) return; -+ if (guieventlistener.charTyped(c0, p_90892_)) return; -+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, c0, p_90892_); - }, "charTyped event handler", guieventlistener.getClass().getCanonicalName()); - } + private void charTyped(long p_90890_, int p_90891_, int p_90892_) { + if (p_90890_ == this.minecraft.getWindow().getWindow()) { +- GuiEventListener guieventlistener = this.minecraft.screen; ++ Screen guieventlistener = this.minecraft.screen; + if (guieventlistener != null && this.minecraft.getOverlay() == null) { + if (Character.charCount(p_90891_) == 1) { + Screen.wrapScreenError( +- () -> guieventlistener.charTyped((char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName() ++ () -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, (char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName() + ); + } else { + for (char c0 : Character.toChars(p_90891_)) { +- Screen.wrapScreenError(() -> guieventlistener.charTyped(c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()); ++ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()); + } + } } diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch index e1dd113f01..b1873252c2 100644 --- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch +++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch @@ -1,447 +1,452 @@ --- a/net/minecraft/client/Minecraft.java +++ b/net/minecraft/client/Minecraft.java -@@ -254,7 +_,7 @@ +@@ -259,7 +_,7 @@ import org.slf4j.Logger; @OnlyIn(Dist.CLIENT) -public class Minecraft extends ReentrantBlockableEventLoop implements WindowEventHandler { +public class Minecraft extends ReentrantBlockableEventLoop implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft { - static Minecraft instance; - private static final Logger LOGGER = LogUtils.getLogger(); - public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX; + static Minecraft instance; + private static final Logger LOGGER = LogUtils.getLogger(); + public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX; @@ -438,7 +_,6 @@ - } - }, Util.nonCriticalIoPool()); - LOGGER.info("Setting user: {}", (Object)this.user.getName()); -- LOGGER.debug("(Session ID is {})", (Object)this.user.getSessionId()); - this.demo = p_91084_.game.demo; - this.allowsMultiplayer = !p_91084_.game.disableMultiplayer; - this.allowsChat = !p_91084_.game.disableChat; -@@ -474,15 +_,15 @@ - } - - this.window.setFramerateLimit(this.options.framerateLimit().get()); -+ // FORGE: Move mouse and keyboard handler setup further below - this.mouseHandler = new MouseHandler(this); -- this.mouseHandler.setup(this.window.getWindow()); - this.keyboardHandler = new KeyboardHandler(this); -- this.keyboardHandler.setup(this.window.getWindow()); - RenderSystem.initRenderer(this.options.glDebugVerbosity, false); - this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight()); - this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); - this.mainRenderTarget.clear(ON_OSX); - this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES); -+ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager); - this.resourcePackRepository.reload(); - this.options.loadSelectedResourcePacks(this.resourcePackRepository); - this.languageManager = new LanguageManager(this.options.languageCode); -@@ -538,10 +_,13 @@ - this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers); - this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener()); - this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent()); - this.resourceManager.registerReloadListener(this.levelRenderer); -- this.createSearchTrees(); -+ // Forge: We delay this to allow registration of modded creative mode tabs -+ // this.createSearchTrees(); - this.resourceManager.registerReloadListener(this.searchRegistry); - this.particleEngine = new ParticleEngine(this.level, this.textureManager); -+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine); - this.resourceManager.registerReloadListener(this.particleEngine); - this.paintingTextures = new PaintingTextureManager(this.textureManager); - this.resourceManager.registerReloadListener(this.paintingTextures); -@@ -552,7 +_,10 @@ - this.gpuWarnlistManager = new GpuWarnlistManager(); - this.resourceManager.registerReloadListener(this.gpuWarnlistManager); - this.resourceManager.registerReloadListener(this.regionalCompliancies); -- this.gui = new Gui(this, this.itemRenderer); -+ this.gui = new net.minecraftforge.client.gui.overlay.ForgeGui(this); -+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them. -+ this.mouseHandler.setup(this.window.getWindow()); -+ this.keyboardHandler.setup(this.window.getWindow()); - this.debugRenderer = new DebugRenderer(this); - RealmsClient realmsclient = RealmsClient.create(this); - this.realmsDataFetcher = new RealmsDataFetcher(realmsclient); -@@ -572,6 +_,7 @@ - TinyFileDialogs.tinyfd_messageBox("Minecraft", stringbuilder.toString(), "ok", "error", false); - } - -+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager); - this.window.updateVsync(this.options.enableVsync().get()); - this.window.updateRawMouseInput(this.options.rawMouseInput().get()); - this.window.setDefaultErrorCallback(); -@@ -592,7 +_,7 @@ - ReloadInstance reloadinstance = this.resourceManager.createReload(Util.backgroundExecutor(), this, RESOURCE_RELOAD_INITIAL_TASK, list); - GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); - Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay); -- this.setOverlay(new LoadingOverlay(this, reloadinstance, (p_296164_) -> { -+ this.setOverlay(net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay(() -> this, () -> reloadinstance, (p_296164_) -> { - Util.ifElse(p_296164_, (p_296162_) -> { - this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie); - }, () -> { -@@ -602,8 +_,10 @@ - - this.reloadStateTracker.finishReload(); - this.onResourceLoadFinished(minecraft$gameloadcookie); -+ if (net.minecraftforge.client.loading.ClientModLoader.completeModLoading()) -+ return; // Do not overwrite the error screen if there are errors - }); -- }, false)); -+ }, false).get()); - this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path()); - } - -@@ -701,7 +_,7 @@ - private String createTitle() { - StringBuilder stringbuilder = new StringBuilder("Minecraft"); - if (checkModStatus().shouldReportAsModified()) { -- stringbuilder.append("*"); -+ stringbuilder.append('*').append(" Forge"); - } - - stringbuilder.append(" "); -@@ -725,6 +_,8 @@ - } - - private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) { -+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam. -+ return UserApiService.OFFLINE; - return p_193586_.createUserApiService(p_193587_.user.user.getAccessToken()); - } - -@@ -733,7 +_,7 @@ - } - - private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) { -- if (this.resourcePackRepository.getSelectedIds().size() > 1) { -+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any. - this.clearResourcePacksOnError(p_91240_, (Component)null, p_299515_); - } else { - Util.throwAsRuntime(p_91240_); -@@ -819,7 +_,10 @@ - } - - public void createSearchTrees() { -- this.searchRegistry.register(SearchRegistry.CREATIVE_NAMES, (p_231451_) -> { -+ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys(); -+ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys(); -+ for (var nameSearchKey : nameSearchKeys.values()) -+ this.searchRegistry.register(nameSearchKey, (p_231451_) -> { - return new FullTextSearchTree<>((p_210797_) -> { - return p_210797_.getTooltipLines((Player)null, TooltipFlag.Default.NORMAL.asCreative()).stream().map((p_231455_) -> { - return ChatFormatting.stripFormatting(p_231455_.getString()).trim(); -@@ -830,7 +_,8 @@ - return Stream.of(BuiltInRegistries.ITEM.getKey(p_91317_.getItem())); - }, p_231451_); - }); -- this.searchRegistry.register(SearchRegistry.CREATIVE_TAGS, (p_231430_) -> { -+ for (var tagSearchKey : tagSearchKeys.values()) -+ this.searchRegistry.register(tagSearchKey, (p_231430_) -> { - return new IdSearchTree<>((p_231353_) -> { - return p_231353_.getTags().map(TagKey::location); - }, p_231430_); -@@ -850,9 +_,12 @@ - }); - }, p_301514_); - }); -- CreativeModeTabs.searchTab().setSearchTreeBuilder((p_255439_) -> { -- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_); -- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_); -+ nameSearchKeys.forEach((tab, nameSearchKey) -> { -+ var tagSearchKey = tagSearchKeys.get(tab); -+ tab.setSearchTreeBuilder(contents -> { -+ this.populateSearchTree(nameSearchKey, contents); -+ this.populateSearchTree(tagSearchKey, contents); -+ }); - }); - } - -@@ -1054,10 +_,6 @@ - LOGGER.error("setScreen called from non-game thread"); - } - -- if (this.screen != null) { -- this.screen.removed(); -- } -- - if (p_91153_ == null && this.clientLevelTeardownInProgress) { - throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); - } else { -@@ -1071,6 +_,19 @@ } - } + }, Util.nonCriticalIoPool()); + LOGGER.info("Setting user: {}", this.user.getName()); +- LOGGER.debug("(Session ID is {})", this.user.getSessionId()); + this.demo = p_91084_.game.demo; + this.allowsMultiplayer = !p_91084_.game.disableMultiplayer; + this.allowsChat = !p_91084_.game.disableChat; +@@ -475,15 +_,15 @@ + } -+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this); -+ Screen old = this.screen; -+ if (p_91153_ != null) { -+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_); -+ if (event == null) return; -+ p_91153_ = event; -+ } -+ -+ if (old != null && p_91153_ != old) { -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old); -+ old.removed(); -+ } -+ - this.screen = p_91153_; - if (this.screen != null) { - this.screen.added(); -@@ -1218,9 +_,12 @@ - RenderSystem.enableCull(); - this.profiler.pop(); - if (!this.noRender) { -+ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile -+ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick); - this.profiler.popPush("gameRenderer"); - this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_); - this.profiler.pop(); -+ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick); - } + this.window.setFramerateLimit(this.options.framerateLimit().get()); ++ // FORGE: Move mouse and keyboard handler setup further below + this.mouseHandler = new MouseHandler(this); +- this.mouseHandler.setup(this.window.getWindow()); + this.keyboardHandler = new KeyboardHandler(this); +- this.keyboardHandler.setup(this.window.getWindow()); + RenderSystem.initRenderer(this.options.glDebugVerbosity, false); + this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight()); + this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); + this.mainRenderTarget.clear(ON_OSX); + this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES); ++ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager); + this.resourcePackRepository.reload(); + this.options.loadSelectedResourcePacks(this.resourcePackRepository); + this.languageManager = new LanguageManager(this.options.languageCode); +@@ -542,6 +_,7 @@ + this.entityRenderDispatcher = new EntityRenderDispatcher(this, this.textureManager, this.itemRenderer, this.blockRenderer, this.font, this.options, this.entityModels); + this.resourceManager.registerReloadListener(this.entityRenderDispatcher); + this.particleEngine = new ParticleEngine(this.level, this.textureManager); ++ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine); + this.resourceManager.registerReloadListener(this.particleEngine); + this.paintingTextures = new PaintingTextureManager(this.textureManager); + this.resourceManager.registerReloadListener(this.paintingTextures); +@@ -554,13 +_,18 @@ + this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers); + this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener()); + this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent()); + this.resourceManager.registerReloadListener(this.levelRenderer); +- this.createSearchTrees(); ++ // Forge: We delay this to allow registration of modded creative mode tabs ++ //this.createSearchTrees(); + this.resourceManager.registerReloadListener(this.searchRegistry); + this.gpuWarnlistManager = new GpuWarnlistManager(); + this.resourceManager.registerReloadListener(this.gpuWarnlistManager); + this.resourceManager.registerReloadListener(this.regionalCompliancies); + this.gui = new Gui(this); ++ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them. ++ this.mouseHandler.setup(this.window.getWindow()); ++ this.keyboardHandler.setup(this.window.getWindow()); + this.debugRenderer = new DebugRenderer(this); + RealmsClient realmsclient = RealmsClient.create(this); + this.realmsDataFetcher = new RealmsDataFetcher(realmsclient); +@@ -584,6 +_,7 @@ + this.options.fullscreen().set(this.window.isFullscreen()); + } - if (this.fpsPieResults != null) { -@@ -1254,7 +_,8 @@ - this.window.setErrorSection("Post render"); - ++this.frames; - boolean flag1 = this.hasSingleplayerServer() && (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen()) && !this.singleplayerServer.isPublished(); -- if (this.pause != flag1) { -+ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) { -+ - if (flag1) { - this.pausePartialTick = this.timer.partialTick; - } else { -@@ -1262,6 +_,7 @@ - } - - this.pause = flag1; -+ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1); - } - - long l = Util.getNanos(); -@@ -1341,10 +_,12 @@ - this.window.setGuiScale((double)i); - if (this.screen != null) { - this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); -+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); - } - - RenderTarget rendertarget = this.getMainRenderTarget(); - rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX); -+ if (this.gameRenderer != null) - this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight()); - this.mouseHandler.setIgnoreFirstMove(); - } -@@ -1618,6 +_,7 @@ - } - - public void stop() { -+ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown(); - this.running = false; - } - -@@ -1647,10 +_,18 @@ - if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) { - BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; - BlockPos blockpos = blockhitresult.getBlockPos(); -- if (!this.level.getBlockState(blockpos).isAir()) { -+ if (!this.level.isEmptyBlock(blockpos)) { -+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND); -+ if (inputEvent.isCanceled()) { -+ if (inputEvent.shouldSwingHand()) { -+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult); -+ this.player.swing(InteractionHand.MAIN_HAND); -+ } -+ return; -+ } - Direction direction = blockhitresult.getDirection(); -- if (this.gameMode.continueDestroyBlock(blockpos, direction)) { -- this.particleEngine.crack(blockpos, direction); -+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) { -+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult); - this.player.swing(InteractionHand.MAIN_HAND); - } - } -@@ -1679,6 +_,8 @@ - return false; - } else { - boolean flag = false; -+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND); -+ if (!inputEvent.isCanceled()) - switch (this.hitResult.getType()) { - case ENTITY: - this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity()); -@@ -1686,7 +_,7 @@ - case BLOCK: - BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; - BlockPos blockpos = blockhitresult.getBlockPos(); -- if (!this.level.getBlockState(blockpos).isAir()) { -+ if (!this.level.isEmptyBlock(blockpos)) { - this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection()); - if (this.level.getBlockState(blockpos).isAir()) { - flag = true; -@@ -1699,8 +_,10 @@ - } - - this.player.resetAttackStrengthTicker(); -+ net.minecraftforge.common.ForgeHooks.onEmptyLeftClick(this.player); - } - -+ if (inputEvent.shouldSwingHand()) - this.player.swing(InteractionHand.MAIN_HAND); - return flag; - } -@@ -1716,6 +_,11 @@ - } - - for(InteractionHand interactionhand : InteractionHand.values()) { -+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(1, this.options.keyUse, interactionhand); -+ if (inputEvent.isCanceled()) { -+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand); -+ return; -+ } - ItemStack itemstack = this.player.getItemInHand(interactionhand); - if (!itemstack.isItemEnabled(this.level.enabledFeatures())) { - return; -@@ -1736,7 +_,7 @@ ++ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager); + this.window.updateVsync(this.options.enableVsync().get()); + this.window.updateRawMouseInput(this.options.rawMouseInput().get()); + this.window.setDefaultErrorCallback(); +@@ -604,16 +_,17 @@ + GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); + Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay); + this.setOverlay( +- new LoadingOverlay( +- this, reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> { ++ net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay( ++ () -> this, () -> reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> { + if (SharedConstants.IS_RUNNING_IN_IDE) { + this.selfTest(); } - if (interactionresult.consumesAction()) { -- if (interactionresult.shouldSwing()) { -+ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) { - this.player.swing(interactionhand); - } + this.reloadStateTracker.finishReload(); + this.onResourceLoadFinished(minecraft$gameloadcookie); ++ net.minecraftforge.client.loading.ClientModLoader.completeModLoading(); + }), false +- ) ++ ).get() + ); + this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path()); + } +@@ -702,6 +_,7 @@ + StringBuilder stringbuilder = new StringBuilder("Minecraft"); + if (checkModStatus().shouldReportAsModified()) { + stringbuilder.append("*"); ++ stringbuilder.append(" Forge"); + } -@@ -1748,7 +_,7 @@ - int i = itemstack.getCount(); - InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult); - if (interactionresult1.consumesAction()) { -- if (interactionresult1.shouldSwing()) { -+ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) { - this.player.swing(interactionhand); - if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) { - this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand); -@@ -1764,6 +_,9 @@ - } - } + stringbuilder.append(" "); +@@ -725,6 +_,8 @@ + } -+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) -+ net.minecraftforge.common.ForgeHooks.onEmptyClick(this.player, interactionhand); -+ - if (!itemstack.isEmpty()) { - InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand); - if (interactionresult2.consumesAction()) { -@@ -1795,6 +_,8 @@ - --this.rightClickDelay; - } + private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) { ++ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam. ++ return UserApiService.OFFLINE; + return p_193587_.user.user.getType() != User.Type.MSA + ? UserApiService.OFFLINE + : p_193586_.createUserApiService(p_193587_.user.user.getAccessToken()); +@@ -735,7 +_,7 @@ + } -+ net.minecraftforge.event.ForgeEventFactory.onPreClientTick(); -+ - this.profiler.push("gui"); - this.chatListener.tick(); - this.gui.tick(this.pause); -@@ -1887,6 +_,7 @@ + private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) { +- if (this.resourcePackRepository.getSelectedIds().size() > 1) { ++ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any. + this.clearResourcePacksOnError(p_91240_, null, p_299515_); + } else { + Util.throwAsRuntime(p_91240_); +@@ -817,9 +_,12 @@ + } - this.tutorial.tick(); + public void createSearchTrees() { ++ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys(); ++ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys(); ++ for (var nameSearchKey : nameSearchKeys.values()) + this.searchRegistry + .register( +- SearchRegistry.CREATIVE_NAMES, ++ nameSearchKey, + p_231451_ -> new FullTextSearchTree<>( + p_325272_ -> p_325272_.getTooltipLines(Item.TooltipContext.EMPTY, null, TooltipFlag.Default.NORMAL.asCreative()) + .stream() +@@ -829,8 +_,9 @@ + p_231451_ + ) + ); ++ for (var tagSearchKey : tagSearchKeys.values()) + this.searchRegistry +- .register(SearchRegistry.CREATIVE_TAGS, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_)); ++ .register(tagSearchKey, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_)); + this.searchRegistry + .register( + SearchRegistry.RECIPE_COLLECTIONS, +@@ -854,9 +_,12 @@ + p_301514_ + ) + ); +- CreativeModeTabs.searchTab().setSearchTreeBuilder(p_255439_ -> { +- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_); +- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_); ++ nameSearchKeys.forEach((tab, nameSearchKey) -> { ++ var tagSearchKey = tagSearchKeys.get(tab); ++ tab.setSearchTreeBuilder(contents -> { ++ this.populateSearchTree(nameSearchKey, contents); ++ this.populateSearchTree(tagSearchKey, contents); ++ }); + }); + } -+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true); - try { - this.level.tick(() -> { - return true; -@@ -1902,6 +_,7 @@ +@@ -1039,12 +_,6 @@ + LOGGER.error("setScreen called from non-game thread"); + } - throw new ReportedException(crashreport); - } -+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true); - } - - this.profiler.popPush("animateTick"); -@@ -1921,6 +_,8 @@ - this.profiler.popPush("keyboard"); - this.keyboardHandler.tick(); - this.profiler.pop(); -+ -+ net.minecraftforge.event.ForgeEventFactory.onPostClientTick(); - } - - private boolean isMultiplayerServer() { -@@ -2112,6 +_,7 @@ - } - - public void setLevel(ClientLevel p_91157_) { -+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); - ProgressScreen progressscreen = new ProgressScreen(true); - progressscreen.progressStartNoAbort(Component.translatable("connect.joining")); - this.updateScreenAndTick(progressscreen); -@@ -2146,6 +_,7 @@ - IntegratedServer integratedserver = this.singleplayerServer; - this.singleplayerServer = null; - this.gameRenderer.resetData(); -+ net.minecraftforge.client.ForgeHooksClient.firePlayerLogout(this.gameMode, this.player); - this.gameMode = null; - this.narrator.clear(); - this.clientLevelTeardownInProgress = true; -@@ -2153,6 +_,7 @@ - try { - this.updateScreenAndTick(p_91321_); - if (this.level != null) { -+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); - if (integratedserver != null) { - this.profiler.push("waitForServer"); - -@@ -2165,6 +_,7 @@ - - this.gui.onDisconnected(); - this.isLocalServer = false; -+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level); - } - - this.level = null; -@@ -2313,6 +_,7 @@ - - private void pickBlock() { - if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) { -+ if (net.minecraftforge.client.ForgeHooksClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return; - boolean flag = this.player.getAbilities().instabuild; - BlockEntity blockentity = null; - HitResult.Type hitresult$type = this.hitResult.getType(); -@@ -2325,10 +_,7 @@ +- if (this.screen != null) { +- this.screen.removed(); +- } else { +- this.setLastInputType(InputType.NONE); +- } +- + if (p_91153_ == null && this.clientLevelTeardownInProgress) { + throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); + } else { +@@ -1058,6 +_,23 @@ + } } - Block block = blockstate.getBlock(); -- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate); -- if (itemstack.isEmpty()) { -- return; -- } -+ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player); ++ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this); ++ Screen old = this.screen; ++ if (p_91153_ != null) { ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_); ++ if (event == null) return; ++ p_91153_ = event; ++ } ++ ++ if (p_91153_ != old) { ++ if (old != null) { ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old); ++ old.removed(); ++ } else { ++ this.setLastInputType(InputType.NONE); ++ } ++ } ++ + this.screen = p_91153_; + if (this.screen != null) { + this.screen.added(); +@@ -1204,9 +_,12 @@ + this.mouseHandler.handleAccumulatedMovement(); + this.profiler.pop(); + if (!this.noRender) { ++ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile ++ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick); + this.profiler.popPush("gameRenderer"); + this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_); + this.profiler.pop(); ++ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick); + } - if (flag && Screen.hasControlDown() && blockstate.hasBlockEntity()) { - blockentity = this.level.getBlockEntity(blockpos); -@@ -2339,7 +_,7 @@ + if (this.fpsPieResults != null) { +@@ -1240,7 +_,7 @@ + boolean flag1 = this.hasSingleplayerServer() + && (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen()) + && !this.singleplayerServer.isPublished(); +- if (this.pause != flag1) { ++ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) { + if (flag1) { + this.pausePartialTick = this.timer.partialTick; + } else { +@@ -1248,6 +_,7 @@ } - Entity entity = ((EntityHitResult)this.hitResult).getEntity(); -- itemstack = entity.getPickResult(); -+ itemstack = entity.getPickedResult(this.hitResult); - if (itemstack == null) { - return; + this.pause = flag1; ++ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1); + } + + long l = Util.getNanos(); +@@ -1340,10 +_,12 @@ + this.window.setGuiScale((double)i); + if (this.screen != null) { + this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); ++ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); + } + + RenderTarget rendertarget = this.getMainRenderTarget(); + rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX); ++ if (this.gameRenderer != null) + this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight()); + this.mouseHandler.setIgnoreFirstMove(); + } +@@ -1619,6 +_,7 @@ + } + + public void stop() { ++ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown(); + this.running = false; + } + +@@ -1647,10 +_,18 @@ + if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) { + BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; + BlockPos blockpos = blockhitresult.getBlockPos(); +- if (!this.level.getBlockState(blockpos).isAir()) { ++ if (!this.level.isEmptyBlock(blockpos)) { ++ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND); ++ if (inputEvent.isCanceled()) { ++ if (inputEvent.shouldSwingHand()) { ++ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult); ++ this.player.swing(InteractionHand.MAIN_HAND); ++ } ++ return; ++ } + Direction direction = blockhitresult.getDirection(); +- if (this.gameMode.continueDestroyBlock(blockpos, direction)) { +- this.particleEngine.crack(blockpos, direction); ++ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) { ++ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult); + this.player.swing(InteractionHand.MAIN_HAND); + } + } +@@ -1678,6 +_,8 @@ + return false; + } else { + boolean flag = false; ++ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND); ++ if (!inputEvent.isCanceled()) + switch (this.hitResult.getType()) { + case ENTITY: + this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity()); +@@ -1685,7 +_,7 @@ + case BLOCK: + BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; + BlockPos blockpos = blockhitresult.getBlockPos(); +- if (!this.level.getBlockState(blockpos).isAir()) { ++ if (!this.level.isEmptyBlock(blockpos)) { + this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection()); + if (this.level.getBlockState(blockpos).isAir()) { + flag = true; +@@ -1698,8 +_,10 @@ + } + + this.player.resetAttackStrengthTicker(); ++ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player); + } + ++ if (inputEvent.shouldSwingHand()) + this.player.swing(InteractionHand.MAIN_HAND); + return flag; } -@@ -2904,6 +_,19 @@ +@@ -1715,6 +_,12 @@ + } - public void updateMaxMipLevel(int p_91313_) { - this.modelManager.updateMaxMipLevel(p_91313_); -+ } + for (InteractionHand interactionhand : InteractionHand.values()) { ++ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(1, this.options.keyUse, interactionhand); ++ if (inputEvent.isCanceled()) { ++ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand); ++ return; ++ } + -+ public ItemColors getItemColors() { -+ return this.itemColors; -+ } -+ -+ public SearchRegistry getSearchTreeManager() { -+ return this.searchRegistry; -+ } -+ -+ private float realPartialTick; -+ public float getPartialTick() { -+ return this.realPartialTick; - } + ItemStack itemstack = this.player.getItemInHand(interactionhand); + if (!itemstack.isItemEnabled(this.level.enabledFeatures())) { + return; +@@ -1735,7 +_,7 @@ + } - public EntityModelSet getEntityModels() { + if (interactionresult.consumesAction()) { +- if (interactionresult.shouldSwing()) { ++ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) { + this.player.swing(interactionhand); + } + +@@ -1747,7 +_,7 @@ + int i = itemstack.getCount(); + InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult); + if (interactionresult1.consumesAction()) { +- if (interactionresult1.shouldSwing()) { ++ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) { + this.player.swing(interactionhand); + if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) { + this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand); +@@ -1763,6 +_,9 @@ + } + } + ++ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) ++ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, interactionhand); ++ + if (!itemstack.isEmpty()) { + InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand); + if (interactionresult2.consumesAction()) { +@@ -1793,6 +_,8 @@ + this.rightClickDelay--; + } + ++ net.minecraftforge.event.ForgeEventFactory.onPreClientTick(); ++ + this.profiler.push("gui"); + this.chatListener.tick(); + this.gui.tick(this.pause); +@@ -1877,6 +_,7 @@ + + this.tutorial.tick(); + ++ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true); + try { + this.level.tick(() -> true); + } catch (Throwable throwable) { +@@ -1890,6 +_,7 @@ + + throw new ReportedException(crashreport); + } ++ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true); + } + + this.profiler.popPush("animateTick"); +@@ -1909,6 +_,7 @@ + this.profiler.popPush("keyboard"); + this.keyboardHandler.tick(); + this.profiler.pop(); ++ net.minecraftforge.event.ForgeEventFactory.onPostClientTick(); + } + + private boolean isMultiplayerServer() { +@@ -2105,6 +_,7 @@ + } + + public void setLevel(ClientLevel p_91157_, ReceivingLevelScreen.Reason p_335893_) { ++ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); + this.updateScreenAndTick(new ReceivingLevelScreen(() -> false, p_335893_)); + this.level = p_91157_; + this.updateLevelInEngines(p_91157_); +@@ -2142,6 +_,7 @@ + IntegratedServer integratedserver = this.singleplayerServer; + this.singleplayerServer = null; + this.gameRenderer.resetData(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogout(this.gameMode, this.player); + this.gameMode = null; + this.narrator.clear(); + this.clientLevelTeardownInProgress = true; +@@ -2149,6 +_,7 @@ + try { + this.updateScreenAndTick(p_335030_); + if (this.level != null) { ++ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); + if (integratedserver != null) { + this.profiler.push("waitForServer"); + +@@ -2161,6 +_,7 @@ + + this.gui.onDisconnected(); + this.isLocalServer = false; ++ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level); + } + + this.level = null; +@@ -2307,6 +_,7 @@ + + private void pickBlock() { + if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return; + boolean flag = this.player.getAbilities().instabuild; + BlockEntity blockentity = null; + HitResult.Type hitresult$type = this.hitResult.getType(); +@@ -2319,7 +_,7 @@ + } + + Block block = blockstate.getBlock(); +- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate); ++ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player); + if (itemstack.isEmpty()) { + return; + } +@@ -2333,7 +_,7 @@ + } + + Entity entity = ((EntityHitResult)this.hitResult).getEntity(); +- itemstack = entity.getPickResult(); ++ itemstack = entity.getPickedResult(this.hitResult); + if (itemstack == null) { + return; + } +@@ -2931,6 +_,19 @@ + @Nullable + public static String getLauncherBrand() { + return System.getProperty("minecraft.launcher.brand"); ++ } ++ ++ public ItemColors getItemColors() { ++ return this.itemColors; ++ } ++ ++ public SearchRegistry getSearchTreeManager() { ++ return this.searchRegistry; ++ } ++ ++ private float realPartialTick; ++ public float getPartialTick() { ++ return this.realPartialTick; + } + + @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch index 157c2e6008..1448135626 100644 --- a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch @@ -1,86 +1,73 @@ --- a/net/minecraft/client/MouseHandler.java +++ b/net/minecraft/client/MouseHandler.java @@ -74,6 +_,7 @@ - this.activeButton = -1; - } - -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return; - boolean[] aboolean = new boolean[]{false}; - if (this.minecraft.getOverlay() == null) { - if (this.minecraft.screen == null) { -@@ -87,11 +_,19 @@ - if (flag) { - screen.afterMouseAction(); - Screen.wrapScreenError(() -> { -- aboolean[0] = screen.mouseClicked(d0, d1, i); -+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPre(screen, d0, d1, i); -+ if (!aboolean[0]) { -+ aboolean[0] = this.minecraft.screen.mouseClicked(d0, d1, i); -+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]); -+ } - }, "mouseClicked event handler", screen.getClass().getCanonicalName()); - } else { - Screen.wrapScreenError(() -> { -- aboolean[0] = screen.mouseReleased(d0, d1, i); -+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPre(screen, d0, d1, i); -+ if (!aboolean[0]) { -+ aboolean[0] = this.minecraft.screen.mouseReleased(d0, d1, i); -+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]); -+ } - }, "mouseReleased event handler", screen.getClass().getCanonicalName()); - } - } -@@ -116,6 +_,7 @@ - } - } - -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_); - } - } - -@@ -129,8 +_,10 @@ - if (this.minecraft.screen != null) { - double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth(); - double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight(); -- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2); - this.minecraft.screen.afterMouseAction(); -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return; -+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return; -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2); - } else if (this.minecraft.player != null) { - if (this.accumulatedScrollX != 0.0D && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) { - this.accumulatedScrollX = 0.0D; -@@ -151,6 +_,7 @@ - this.accumulatedScrollX -= (double)j; - this.accumulatedScrollY -= (double)i; - int k = i == 0 ? -j : i; -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return; - if (this.minecraft.player.isSpectator()) { - if (this.minecraft.gui.getSpectatorGui().isMenuActive()) { - this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k); -@@ -219,7 +_,9 @@ - double d2 = (p_91563_ - this.xpos) * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth(); - double d3 = (p_91564_ - this.ypos) * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight(); - Screen.wrapScreenError(() -> { -- screen.mouseDragged(d0, d1, this.activeButton, d2, d3); -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPre(screen, d0, d1, this.activeButton, d2, d3)) return; -+ if (screen.mouseDragged(d0, d1, this.activeButton, d2, d3)) return; -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPost(screen, d0, d1, this.activeButton, d2, d3); - }, "mouseDragged event handler", screen.getClass().getCanonicalName()); + this.activeButton = -1; } -@@ -302,6 +_,14 @@ ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return; + boolean[] aboolean = new boolean[]{false}; + if (this.minecraft.getOverlay() == null) { + if (this.minecraft.screen == null) { +@@ -86,9 +_,9 @@ + Screen screen = this.minecraft.screen; + if (flag) { + screen.afterMouseAction(); +- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseClicked(d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName()); ++ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(aboolean, screen, d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName()); + } else { +- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseReleased(d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName()); ++ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(aboolean, screen, d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName()); + } + } + } +@@ -111,6 +_,7 @@ + } + } + } ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_); + } + } - public double ypos() { - return this.ypos; -+ } +@@ -124,7 +_,9 @@ + if (this.minecraft.screen != null) { + double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth(); + double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight(); +- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2); ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return; ++ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return; ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2); + this.minecraft.screen.afterMouseAction(); + } else if (this.minecraft.player != null) { + if (this.accumulatedScrollX != 0.0 && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) { +@@ -146,6 +_,7 @@ + this.accumulatedScrollX -= (double)j; + this.accumulatedScrollY -= (double)i; + int k = i == 0 ? -j : i; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return; + if (this.minecraft.player.isSpectator()) { + if (this.minecraft.gui.getSpectatorGui().isMenuActive()) { + this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k); +@@ -216,7 +_,7 @@ + if (this.activeButton != -1 && this.mousePressedTime > 0.0) { + double d4 = this.accumulatedDX * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth(); + double d5 = this.accumulatedDY * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight(); +- Screen.wrapScreenError(() -> screen.mouseDragged(d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName()); ++ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName()); + } + + screen.afterMouseMove(); +@@ -283,6 +_,14 @@ + + public double ypos() { + return this.ypos; ++ } + -+ public double getXVelocity() { -+ return this.accumulatedDX; -+ } ++ public double getXVelocity() { ++ return this.accumulatedDX; ++ } + -+ public double getYVelocity() { -+ return this.accumulatedDY; - } ++ public double getYVelocity() { ++ return this.accumulatedDY; + } - public void setIgnoreFirstMove() { + public void setIgnoreFirstMove() { diff --git a/patches/minecraft/net/minecraft/client/Options.java.patch b/patches/minecraft/net/minecraft/client/Options.java.patch index 6e80571053..d339d6a7b3 100644 --- a/patches/minecraft/net/minecraft/client/Options.java.patch +++ b/patches/minecraft/net/minecraft/client/Options.java.patch @@ -1,95 +1,97 @@ --- a/net/minecraft/client/Options.java +++ b/net/minecraft/client/Options.java -@@ -509,7 +_,8 @@ - }, new OptionInstance.LazyEnum<>(() -> { - return Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(); - }, (p_232011_) -> { -- return Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_); -+ // FORGE: fix incorrect string comparison - PR #8767 -+ return Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_); - }, Codec.STRING), "", (p_299350_) -> { - SoundManager soundmanager = Minecraft.getInstance().getSoundManager(); - soundmanager.reload(); -@@ -841,6 +_,7 @@ - } +@@ -680,7 +_,8 @@ + }, + new OptionInstance.LazyEnum<>( + () -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(), +- p_232011_ -> Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ++ // FORGE: fix incorrect string comparison - PR #8767 ++ p_232011_ -> Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) + ? Optional.empty() + : Optional.of(p_232011_), + Codec.STRING +@@ -1044,6 +_,7 @@ + } - public Options(Minecraft p_92138_, File p_92139_) { -+ setForgeKeybindProperties(); - this.minecraft = p_92138_; - this.optionsFile = new File(p_92139_, "options.txt"); - boolean flag = p_92138_.is64Bit(); -@@ -964,11 +_,20 @@ - p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra); - this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility); + public Options(Minecraft p_92138_, File p_92139_) { ++ setForgeKeybindProperties(); + this.minecraft = p_92138_; + this.optionsFile = new File(p_92139_, "options.txt"); + boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L; +@@ -1178,12 +_,22 @@ + p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra); + this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility); + p_168428_.process("menuBackgroundBlurriness", this.menuBackgroundBlurriness); ++ processOptionsForge(p_168428_); ++ } -+ processOptionsForge(p_168428_); -+ } -+ // FORGE: split off to allow reloading options after mod loading is done -+ private void processOptionsForge(Options.FieldAccess p_168428_) -+ { - for(KeyMapping keymapping : this.keyMappings) { -- String s = keymapping.saveString(); -+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : ""); - String s1 = p_168428_.process("key_" + keymapping.getName(), s); - if (!s.equals(s1)) { -- keymapping.setKey(InputConstants.getKey(s1)); -+ if (s1.indexOf(':') != -1) { -+ String[] pts = s1.split(":"); -+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0])); -+ } else -+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1)); - } - } - -@@ -987,6 +_,9 @@ - } - - public void load() { -+ this.load(false); -+ } -+ public void load(boolean limited) { - try { - if (!this.optionsFile.exists()) { - return; -@@ -1015,7 +_,8 @@ ++ // FORGE: split off to allow reloading options after mod loading is done ++ private void processOptionsForge(Options.FieldAccess p_168428_) { + for (KeyMapping keymapping : this.keyMappings) { +- String s = keymapping.saveString(); ++ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : ""); + String s1 = p_168428_.process("key_" + keymapping.getName(), s); + if (!s.equals(s1)) { + keymapping.setKey(InputConstants.getKey(s1)); ++ if (s1.indexOf(':') != -1) { ++ String[] pts = s1.split(":"); ++ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0])); ++ } else { ++ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1)); ++ } } - } + } -- this.processOptions(new Options.FieldAccess() { -+ java.util.function.Consumer processor = limited ? this::processOptionsForge : this::processOptions; -+ processor.accept(new Options.FieldAccess() { - @Nullable - private String getValueOrNull(String p_168459_) { - return compoundtag1.contains(p_168459_) ? compoundtag1.getString(p_168459_) : null; -@@ -1188,6 +_,7 @@ - } +@@ -1201,6 +_,10 @@ + } - public void broadcastOptions() { -+ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted. - if (this.minecraft.player != null) { - this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation())); - } -@@ -1246,6 +_,23 @@ - } - - p_92146_.setSelected(set); -+ } + public void load() { ++ load(false); ++ } + -+ private void setForgeKeybindProperties() { -+ net.minecraftforge.client.settings.KeyConflictContext inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME; -+ keyUp.setKeyConflictContext(inGame); -+ keyLeft.setKeyConflictContext(inGame); -+ keyDown.setKeyConflictContext(inGame); -+ keyRight.setKeyConflictContext(inGame); -+ keyJump.setKeyConflictContext(inGame); -+ keyShift.setKeyConflictContext(inGame); -+ keySprint.setKeyConflictContext(inGame); -+ keyAttack.setKeyConflictContext(inGame); -+ keyChat.setKeyConflictContext(inGame); -+ keyPlayerList.setKeyConflictContext(inGame); -+ keyCommand.setKeyConflictContext(inGame); -+ keyTogglePerspective.setKeyConflictContext(inGame); -+ keySmoothCamera.setKeyConflictContext(inGame); - } ++ public void load(boolean limited) { + try { + if (!this.optionsFile.exists()) { + return; +@@ -1228,7 +_,8 @@ + } + } - public CameraType getCameraType() { +- this.processOptions( ++ java.util.function.Consumer processor = limited ? this::processOptionsForge : this::processOptions; ++ processor.accept( + new Options.FieldAccess() { + @Nullable + private String getValueOrNull(String p_168459_) { +@@ -1422,6 +_,7 @@ + } + + public void broadcastOptions() { ++ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted. + if (this.minecraft.player != null) { + this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation())); + } +@@ -1544,6 +_,23 @@ + + public static Component genericValueLabel(Component p_231901_, int p_231902_) { + return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_))); ++ } ++ ++ private void setForgeKeybindProperties() { ++ var inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME; ++ keyUp.setKeyConflictContext(inGame); ++ keyLeft.setKeyConflictContext(inGame); ++ keyDown.setKeyConflictContext(inGame); ++ keyRight.setKeyConflictContext(inGame); ++ keyJump.setKeyConflictContext(inGame); ++ keyShift.setKeyConflictContext(inGame); ++ keySprint.setKeyConflictContext(inGame); ++ keyAttack.setKeyConflictContext(inGame); ++ keyChat.setKeyConflictContext(inGame); ++ keyPlayerList.setKeyConflictContext(inGame); ++ keyCommand.setKeyConflictContext(inGame); ++ keyTogglePerspective.setKeyConflictContext(inGame); ++ keySmoothCamera.setKeyConflictContext(inGame); + } + + @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/RecipeBookCategories.java.patch b/patches/minecraft/net/minecraft/client/RecipeBookCategories.java.patch index 1da1c9149f..c329f18d54 100644 --- a/patches/minecraft/net/minecraft/client/RecipeBookCategories.java.patch +++ b/patches/minecraft/net/minecraft/client/RecipeBookCategories.java.patch @@ -6,34 +6,40 @@ @OnlyIn(Dist.CLIENT) -public enum RecipeBookCategories { +public enum RecipeBookCategories implements net.minecraftforge.common.IExtensibleEnum { - CRAFTING_SEARCH(new ItemStack(Items.COMPASS)), - CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)), - CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)), -@@ -36,7 +_,7 @@ - public static final List BLAST_FURNACE_CATEGORIES = ImmutableList.of(BLAST_FURNACE_SEARCH, BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC); - public static final List FURNACE_CATEGORIES = ImmutableList.of(FURNACE_SEARCH, FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC); - public static final List CRAFTING_CATEGORIES = ImmutableList.of(CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE); -- public static final Map> AGGREGATE_CATEGORIES = ImmutableMap.of(CRAFTING_SEARCH, ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE), FURNACE_SEARCH, ImmutableList.of(FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC), BLAST_FURNACE_SEARCH, ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC), SMOKER_SEARCH, ImmutableList.of(SMOKER_FOOD)); -+ public static final Map> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories(); - private final List itemIcons; + CRAFTING_SEARCH(new ItemStack(Items.COMPASS)), + CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)), + CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)), +@@ -38,7 +_,7 @@ + public static final List CRAFTING_CATEGORIES = ImmutableList.of( + CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE + ); +- public static final Map> AGGREGATE_CATEGORIES = ImmutableMap.of( ++ public static final Map> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories(ImmutableMap.of( + CRAFTING_SEARCH, + ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE), + FURNACE_SEARCH, +@@ -47,7 +_,7 @@ + ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC), + SMOKER_SEARCH, + ImmutableList.of(SMOKER_FOOD) +- ); ++ )); + private final List itemIcons; - private RecipeBookCategories(ItemStack... p_92267_) { -@@ -59,7 +_,7 @@ - list = SMOKER_CATEGORIES; - break; - default: -- throw new IncompatibleClassChangeError(); -+ return net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_); - } + private RecipeBookCategories(final ItemStack... p_92267_) { +@@ -60,10 +_,15 @@ + case FURNACE -> FURNACE_CATEGORIES; + case BLAST_FURNACE -> BLAST_FURNACE_CATEGORIES; + case SMOKER -> SMOKER_CATEGORIES; ++ default -> net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_); + }; + } - return list; -@@ -67,5 +_,9 @@ - - public List getIconItems() { - return this.itemIcons; -+ } + public List getIconItems() { + return this.itemIcons; ++ } + -+ public static RecipeBookCategories create(String name, ItemStack... icons) { -+ throw new IllegalStateException("Enum not extended"); - } ++ public static RecipeBookCategories create(String name, ItemStack... icons) { ++ throw new IllegalStateException("Enum not extended"); + } } diff --git a/patches/minecraft/net/minecraft/client/Screenshot.java.patch b/patches/minecraft/net/minecraft/client/Screenshot.java.patch index 100c4686ce..8dc41417f8 100644 --- a/patches/minecraft/net/minecraft/client/Screenshot.java.patch +++ b/patches/minecraft/net/minecraft/client/Screenshot.java.patch @@ -1,29 +1,30 @@ --- a/net/minecraft/client/Screenshot.java +++ b/net/minecraft/client/Screenshot.java -@@ -56,13 +_,23 @@ - file2 = new File(file1, p_92307_); - } +@@ -54,14 +_,24 @@ + file2 = new File(file1, p_92307_); + } -+ net.minecraftforge.client.event.ScreenshotEvent event = net.minecraftforge.client.ForgeHooksClient.onScreenshot(nativeimage, file2); -+ if (event.isCanceled()) { -+ p_92311_.accept(event.getCancelMessage()); -+ return; -+ } -+ final File target = event.getScreenshotFile(); ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenshot(nativeimage, file2); ++ if (event.isCanceled()) { ++ p_92311_.accept(event.getCancelMessage()); ++ return; ++ } ++ final File target = event.getScreenshotFile(); + - Util.ioPool().execute(() -> { - try { -- nativeimage.writeToFile(file2); -+ nativeimage.writeToFile(target); - Component component = Component.literal(file2.getName()).withStyle(ChatFormatting.UNDERLINE).withStyle((p_168608_) -> { -- return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath())); -+ return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath())); - }); -- p_92311_.accept(Component.translatable("screenshot.success", component)); -+ if (event.getResultMessage() != null) -+ p_92311_.accept(event.getResultMessage()); -+ else -+ p_92311_.accept(Component.translatable("screenshot.success", component)); - } catch (Exception exception) { - LOGGER.warn("Couldn't save screenshot", (Throwable)exception); - p_92311_.accept(Component.translatable("screenshot.failure", exception.getMessage())); + Util.ioPool() + .execute( + () -> { + try { +- nativeimage.writeToFile(file2); +- Component component = Component.literal(file2.getName()) ++ nativeimage.writeToFile(target); ++ Component component = Component.literal(target.getName()) + .withStyle(ChatFormatting.UNDERLINE) +- .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath()))); ++ .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath()))); ++ if (event.getResultMessage() != null) ++ p_92311_.accept(event.getResultMessage()); ++ else + p_92311_.accept(Component.translatable("screenshot.success", component)); + } catch (Exception exception) { + LOGGER.warn("Couldn't save screenshot", (Throwable)exception); diff --git a/patches/minecraft/net/minecraft/client/ToggleKeyMapping.java.patch b/patches/minecraft/net/minecraft/client/ToggleKeyMapping.java.patch index b51b1d1627..69459c3aea 100644 --- a/patches/minecraft/net/minecraft/client/ToggleKeyMapping.java.patch +++ b/patches/minecraft/net/minecraft/client/ToggleKeyMapping.java.patch @@ -1,19 +1,21 @@ --- a/net/minecraft/client/ToggleKeyMapping.java +++ b/net/minecraft/client/ToggleKeyMapping.java -@@ -16,7 +_,7 @@ +@@ -17,7 +_,7 @@ + @Override + public void setDown(boolean p_92534_) { + if (this.needsToggle.getAsBoolean()) { +- if (p_92534_) { ++ if (p_92534_ && isConflictContextAndModifierActive()) { + super.setDown(!this.isDown()); + } + } else { +@@ -27,5 +_,9 @@ - public void setDown(boolean p_92534_) { - if (this.needsToggle.getAsBoolean()) { -- if (p_92534_) { -+ if (p_92534_ && isConflictContextAndModifierActive()) { - super.setDown(!this.isDown()); - } - } else { -@@ -24,6 +_,7 @@ - } - - } -+ @Override public boolean isDown() { return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean()); } - - protected void reset() { - super.setDown(false); + protected void reset() { + super.setDown(false); ++ } ++ ++ @Override public boolean isDown() { ++ return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean()); + } + } diff --git a/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch b/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch index 46f6897737..a738abee59 100644 --- a/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch +++ b/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch @@ -1,44 +1,44 @@ --- a/net/minecraft/client/color/block/BlockColors.java +++ b/net/minecraft/client/color/block/BlockColors.java -@@ -28,7 +_,8 @@ +@@ -29,7 +_,8 @@ @OnlyIn(Dist.CLIENT) public class BlockColors { - private static final int DEFAULT = -1; -- private final IdMapper blockColors = new IdMapper<>(32); -+ // FORGE: Use registry delegate as non-Vanilla block ids are not constant -+ private final java.util.Map, BlockColor> blockColors = new java.util.HashMap<>(); - private final Map>> coloringStates = Maps.newHashMap(); + private static final int DEFAULT = -1; +- private final IdMapper blockColors = new IdMapper<>(32); ++ // Forge: Use registry delegate as non-Vanilla block ids are not constant ++ private final java.util.Map, BlockColor> blockColors = new java.util.HashMap<>(32); + private final Map>> coloringStates = Maps.newHashMap(); - public static BlockColors createDefault() { -@@ -80,11 +_,12 @@ - blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> { - return p_92597_ != null && p_92598_ != null ? 2129968 : 7455580; - }, Blocks.LILY_PAD); -+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors); - return blockcolors; - } + public static BlockColors createDefault() { +@@ -91,11 +_,12 @@ + }, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); + blockcolors.addColoringState(StemBlock.AGE, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); + blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> p_92597_ != null && p_92598_ != null ? -14647248 : -9321636, Blocks.LILY_PAD); ++ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors); + return blockcolors; + } - public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) { -- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock())); -+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock())); - if (blockcolor != null) { - return blockcolor.getColor(p_92583_, (BlockAndTintGetter)null, (BlockPos)null, 0); - } else { -@@ -94,13 +_,15 @@ - } + public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) { +- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock())); ++ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock())); + if (blockcolor != null) { + return blockcolor.getColor(p_92583_, null, null, 0); + } else { +@@ -105,13 +_,15 @@ + } - public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) { -- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock())); -+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock())); - return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_); - } + public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) { +- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock())); ++ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock())); + return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_); + } -+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */ -+ @Deprecated - public void register(BlockColor p_92590_, Block... p_92591_) { - for(Block block : p_92591_) { -- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block)); -+ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_); - } ++ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */ ++ @Deprecated + public void register(BlockColor p_92590_, Block... p_92591_) { + for (Block block : p_92591_) { +- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block)); ++ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_); + } + } - } diff --git a/patches/minecraft/net/minecraft/client/color/item/ItemColors.java.patch b/patches/minecraft/net/minecraft/client/color/item/ItemColors.java.patch index 163bbe6502..35f507c211 100644 --- a/patches/minecraft/net/minecraft/client/color/item/ItemColors.java.patch +++ b/patches/minecraft/net/minecraft/client/color/item/ItemColors.java.patch @@ -1,35 +1,35 @@ --- a/net/minecraft/client/color/item/ItemColors.java +++ b/net/minecraft/client/color/item/ItemColors.java -@@ -25,7 +_,8 @@ +@@ -26,7 +_,8 @@ @OnlyIn(Dist.CLIENT) public class ItemColors { - private static final int DEFAULT = -1; -- private final IdMapper itemColors = new IdMapper<>(32); -+ // FORGE: Use registry delegate as non-Vanilla item ids are not constant -+ private final java.util.Map, ItemColor> itemColors = new java.util.HashMap<>(); + private static final int DEFAULT = -1; +- private final IdMapper itemColors = new IdMapper<>(32); ++ // Forge: Use registry delegate as non-Vanilla item ids are not constant ++ private final java.util.Map, ItemColor> itemColors = new java.util.HashMap<>(32); - public static ItemColors createDefault(BlockColors p_92684_) { - ItemColors itemcolors = new ItemColors(); -@@ -88,17 +_,20 @@ - itemcolors.register((p_232352_, p_232353_) -> { - return p_232353_ == 0 ? -1 : MapItem.getColor(p_232352_); - }, Items.FILLED_MAP); -+ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_); - return itemcolors; - } + public static ItemColors createDefault(BlockColors p_92684_) { + ItemColors itemcolors = new ItemColors(); +@@ -105,17 +_,20 @@ + : FastColor.ARGB32.opaque(p_325310_.getOrDefault(DataComponents.MAP_COLOR, MapItemColor.DEFAULT).rgb()), + Items.FILLED_MAP + ); ++ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_); + return itemcolors; + } - public int getColor(ItemStack p_92677_, int p_92678_) { -- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem())); -+ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem())); - return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_); - } + public int getColor(ItemStack p_92677_, int p_92678_) { +- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem())); ++ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem())); + return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_); + } -+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */ -+ @Deprecated - public void register(ItemColor p_92690_, ItemLike... p_92691_) { - for(ItemLike itemlike : p_92691_) { -- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem())); -+ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_); - } - - } ++ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */ ++ @Deprecated + public void register(ItemColor p_92690_, ItemLike... p_92691_) { + for (ItemLike itemlike : p_92691_) { +- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem())); ++ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_); + } + } + } diff --git a/patches/minecraft/net/minecraft/client/gui/Font.java.patch b/patches/minecraft/net/minecraft/client/gui/Font.java.patch index b00fb3da5c..1ef74b6d42 100644 --- a/patches/minecraft/net/minecraft/client/gui/Font.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/Font.java.patch @@ -6,15 +6,15 @@ @OnlyIn(Dist.CLIENT) -public class Font { +public class Font implements net.minecraftforge.client.extensions.IForgeFont { - private static final float EFFECT_DEPTH = 0.01F; - private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F); - public static final int ALPHA_CUTOFF = 8; -@@ -202,6 +_,8 @@ - public StringSplitter getSplitter() { - return this.splitter; - } + private static final float EFFECT_DEPTH = 0.01F; + private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F); + public static final int ALPHA_CUTOFF = 8; +@@ -322,6 +_,8 @@ + public StringSplitter getSplitter() { + return this.splitter; + } + -+ @Override public Font self() { return this; } ++ @Override public Font self() { return this; } - @OnlyIn(Dist.CLIENT) - public static enum DisplayMode { + @OnlyIn(Dist.CLIENT) + public static enum DisplayMode { diff --git a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch index 15c17005c6..00f83c0627 100644 --- a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch @@ -1,77 +1,75 @@ --- a/net/minecraft/client/gui/Gui.java +++ b/net/minecraft/client/gui/Gui.java @@ -131,7 +_,7 @@ - public float vignetteBrightness = 1.0F; - protected int toolHighlightTimer; - protected ItemStack lastToolHighlight = ItemStack.EMPTY; -- protected final DebugScreenOverlay debugOverlay; -+ protected DebugScreenOverlay debugOverlay; - protected final SubtitleOverlay subtitleOverlay; - protected final SpectatorGui spectatorGui; - protected final PlayerTabOverlay tabList; -@@ -454,6 +_,8 @@ + public float vignetteBrightness = 1.0F; + private int toolHighlightTimer; + private ItemStack lastToolHighlight = ItemStack.EMPTY; +- private final DebugScreenOverlay debugOverlay; ++ protected DebugScreenOverlay debugOverlay; + private final SubtitleOverlay subtitleOverlay; + private final SpectatorGui spectatorGui; + private final PlayerTabOverlay tabList; +@@ -444,6 +_,8 @@ - for(MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) { - MobEffect mobeffect = mobeffectinstance.getEffect(); -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); -+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue; - if (mobeffectinstance.showIcon()) { - int i = this.screenWidth; - int j = 1; -@@ -482,6 +_,7 @@ - } - } + for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) { + Holder holder = mobeffectinstance.getEffect(); ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); ++ if (!renderer.isVisibleInGui(mobeffectinstance)) continue; + if (mobeffectinstance.showIcon()) { + int i = p_282812_.guiWidth(); + int j = 1; +@@ -473,6 +_,7 @@ + } + } -+ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue; - TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(mobeffect); - int i1 = j; - float f1 = f; -@@ -602,16 +_,21 @@ - } ++ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue; + TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(holder); + int l1 = i; + int i1 = j; +@@ -635,6 +_,10 @@ + } - public void renderSelectedItemName(GuiGraphics p_283501_) { -+ renderSelectedItemName(p_283501_, 0); -+ } + private void renderSelectedItemName(GuiGraphics p_283501_) { ++ renderSelectedItemName(p_283501_, 0); ++ } + -+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) { - this.minecraft.getProfiler().push("selectedItemName"); - if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { -- MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color); -+ MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().getStyleModifier()); - if (this.lastToolHighlight.hasCustomHoverName()) { - mutablecomponent.withStyle(ChatFormatting.ITALIC); - } - -- int i = this.getFont().width(mutablecomponent); -+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent); -+ int i = this.getFont().width(highlightTip); - int j = (this.screenWidth - i) / 2; -- int k = this.screenHeight - 59; -+ int k = this.screenHeight - Math.max(yShift, 59); - if (!this.minecraft.gameMode.canHurtPlayer()) { - k += 14; - } -@@ -623,7 +_,13 @@ - - if (l > 0) { - p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0)); -- p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24)); -+ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME); -+ if (font == null) { -+ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24)); -+ } else { -+ j = (this.screenWidth - font.width(highlightTip)) / 2; -+ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24)); -+ } - } - } - -@@ -1080,7 +_,7 @@ - ItemStack itemstack = this.minecraft.player.getInventory().getSelected(); - if (itemstack.isEmpty()) { - this.toolHighlightTimer = 0; -- } else if (!this.lastToolHighlight.isEmpty() && itemstack.is(this.lastToolHighlight.getItem()) && itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) { -+ } else if (!this.lastToolHighlight.isEmpty() && itemstack.getItem() == this.lastToolHighlight.getItem() && (itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) && itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName())))) { - if (this.toolHighlightTimer > 0) { - --this.toolHighlightTimer; ++ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) { + this.minecraft.getProfiler().push("selectedItemName"); + if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { + MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color()); +@@ -642,9 +_,10 @@ + mutablecomponent.withStyle(ChatFormatting.ITALIC); } + +- int i = this.getFont().width(mutablecomponent); ++ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent); ++ int i = this.getFont().width(highlightTip); + int j = (p_283501_.guiWidth() - i) / 2; +- int k = p_283501_.guiHeight() - 59; ++ int k = p_283501_.guiHeight() - Math.max(yShift, 59); + if (!this.minecraft.gameMode.canHurtPlayer()) { + k += 14; + } +@@ -657,6 +_,13 @@ + if (l > 0) { + p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0)); + p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24)); ++ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME); ++ if (font == null) { ++ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24)); ++ } else { ++ j = (p_283501_.guiWidth() - font.width(highlightTip)) / 2; ++ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24)); ++ } + } + } + +@@ -1155,7 +_,7 @@ + ItemStack itemstack = this.minecraft.player.getInventory().getSelected(); + if (itemstack.isEmpty()) { + this.toolHighlightTimer = 0; +- } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) { ++ } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) || !itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName()))) { + this.toolHighlightTimer = (int)(40.0 * this.minecraft.options.notificationDisplayTime().get()); + } else if (this.toolHighlightTimer > 0) { + this.toolHighlightTimer--; diff --git a/patches/minecraft/net/minecraft/client/gui/GuiGraphics.java.patch b/patches/minecraft/net/minecraft/client/gui/GuiGraphics.java.patch index 1d0e86149a..3e74c17961 100644 --- a/patches/minecraft/net/minecraft/client/gui/GuiGraphics.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/GuiGraphics.java.patch @@ -1,140 +1,138 @@ --- a/net/minecraft/client/gui/GuiGraphics.java +++ b/net/minecraft/client/gui/GuiGraphics.java -@@ -55,7 +_,7 @@ +@@ -56,7 +_,7 @@ import org.joml.Vector2ic; @OnlyIn(Dist.CLIENT) -public class GuiGraphics { +public class GuiGraphics implements net.minecraftforge.client.extensions.IForgeGuiGraphics { - public static final float MAX_GUI_Z = 10000.0F; - public static final float MIN_GUI_Z = -10000.0F; - private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2; -@@ -271,6 +_,11 @@ - } + public static final float MAX_GUI_Z = 10000.0F; + public static final float MIN_GUI_Z = -10000.0F; + private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2; +@@ -280,6 +_,11 @@ + } - public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) { -+ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_); -+ } + public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) { ++ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_); ++ } + -+ // Forge: Add float variant for x,y coordinates -+ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) { - if (p_281896_ == null) { - return 0; - } else { -@@ -285,6 +_,11 @@ - } ++ // Forge: Add float variant for x,y coordinates ++ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) { + if (p_281896_ == null) { + return 0; + } else { +@@ -306,6 +_,11 @@ + } - public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) { -+ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_); -+ } + public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) { ++ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_); ++ } + -+ // Forge: Add float variant for x,y coordinates -+ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) { - int i = p_282636_.drawInBatch(p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_, this.pose.last().pose(), this.bufferSource, Font.DisplayMode.NORMAL, 0, 15728880); - this.flushIfUnmanaged(); - return i; -@@ -515,6 +_,7 @@ - crashreportcategory.setDetail("Item Type", () -> { - return String.valueOf((Object)p_281675_.getItem()); - }); -+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem()))); - crashreportcategory.setDetail("Item Damage", () -> { - return String.valueOf(p_281675_.getDamageValue()); - }); -@@ -562,18 +_,26 @@ - } - - this.pose.popPose(); -+ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_); - } - } -+ -+ private ItemStack tooltipStack = ItemStack.EMPTY; - - public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) { -+ this.tooltipStack = p_282781_; - this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_); -+ this.tooltipStack = ItemStack.EMPTY; -+ } -+ -+ public void renderTooltip(Font font, List textComponents, Optional tooltipComponent, ItemStack stack, int mouseX, int mouseY) { -+ this.tooltipStack = stack; -+ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY); -+ this.tooltipStack = ItemStack.EMPTY; - } - - public void renderTooltip(Font p_283128_, List p_282716_, Optional p_281682_, int p_283678_, int p_281696_) { -- List list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Collectors.toList()); -- p_281682_.ifPresent((p_282969_) -> { -- list.add(1, ClientTooltipComponent.create(p_282969_)); -- }); -+ List list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_); - this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE); - } - -@@ -582,7 +_,15 @@ - } - - public void renderComponentTooltip(Font p_282739_, List p_281832_, int p_282191_, int p_282446_) { -- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_); -+ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_); -+ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE); -+ } -+ -+ public void renderComponentTooltip(Font font, List tooltips, int mouseX, int mouseY, ItemStack stack) { -+ this.tooltipStack = stack; -+ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font); -+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE); -+ this.tooltipStack = ItemStack.EMPTY; - } - - public void renderTooltip(Font p_282192_, List p_282297_, int p_281680_, int p_283325_) { -@@ -595,11 +_,13 @@ - - private void renderTooltipInternal(Font p_282675_, List p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) { - if (!p_282615_.isEmpty()) { -+ net.minecraftforge.client.event.RenderTooltipEvent.Pre preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_); -+ if (preEvent.isCanceled()) return; - int i = 0; - int j = p_282615_.size() == 1 ? -2 : 0; - - for(ClientTooltipComponent clienttooltipcomponent : p_282615_) { -- int k = clienttooltipcomponent.getWidth(p_282675_); -+ int k = clienttooltipcomponent.getWidth(preEvent.getFont()); - if (k > i) { - i = k; ++ // Forge: Add float variant for x,y coordinates ++ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) { + int i = p_282636_.drawInBatch( + p_281596_, + (float)p_281586_, +@@ -872,6 +_,7 @@ + CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); + crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_281675_.getItem())); ++ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem()))); + crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_281675_.getComponents())); + crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_281675_.hasFoil())); + throw new ReportedException(crashreport); +@@ -912,16 +_,26 @@ } -@@ -609,20 +_,21 @@ - int i2 = i; - int j2 = j; -- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2); -+ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2); - int l = vector2ic.x(); - int i1 = vector2ic.y(); - this.pose.pushPose(); - int j1 = 400; - this.drawManaged(() -> { -- TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400); -+ net.minecraftforge.client.event.RenderTooltipEvent.Color colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_); -+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd()); - }); - this.pose.translate(0.0F, 0.0F, 400.0F); - int k1 = i1; + this.pose.popPose(); ++ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_); + } + } ++ ++ private ItemStack tooltipStack = ItemStack.EMPTY; - for(int l1 = 0; l1 < p_282615_.size(); ++l1) { - ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1); -- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource); -+ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource); - k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0); - } + public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) { ++ this.tooltipStack = p_282781_; + this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_); ++ this.tooltipStack = ItemStack.EMPTY; ++ } ++ ++ public void renderTooltip(Font font, List textComponents, Optional tooltipComponent, ItemStack stack, int mouseX, int mouseY) { ++ this.tooltipStack = stack; ++ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY); ++ this.tooltipStack = ItemStack.EMPTY; + } -@@ -630,7 +_,7 @@ + public void renderTooltip(Font p_283128_, List p_282716_, Optional p_281682_, int p_283678_, int p_281696_) { +- List list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList()); +- p_281682_.ifPresent(p_325321_ -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(p_325321_))); ++ List list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_); + this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE); + } - for(int k2 = 0; k2 < p_282615_.size(); ++k2) { - ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2); -- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this); -+ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this); - k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0); - } +@@ -930,7 +_,15 @@ + } + + public void renderComponentTooltip(Font p_282739_, List p_281832_, int p_282191_, int p_282446_) { +- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_); ++ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_); ++ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE); ++ } ++ ++ public void renderComponentTooltip(Font font, List tooltips, int mouseX, int mouseY, ItemStack stack) { ++ this.tooltipStack = stack; ++ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font); ++ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE); ++ this.tooltipStack = ItemStack.EMPTY; + } + + public void renderTooltip(Font p_282192_, List p_282297_, int p_281680_, int p_283325_) { +@@ -949,11 +_,13 @@ + + private void renderTooltipInternal(Font p_282675_, List p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) { + if (!p_282615_.isEmpty()) { ++ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_); ++ if (preEvent.isCanceled()) return; + int i = 0; + int j = p_282615_.size() == 1 ? -2 : 0; + + for (ClientTooltipComponent clienttooltipcomponent : p_282615_) { +- int k = clienttooltipcomponent.getWidth(p_282675_); ++ int k = clienttooltipcomponent.getWidth(preEvent.getFont()); + if (k > i) { + i = k; + } +@@ -963,18 +_,21 @@ + + int i2 = i; + int j2 = j; +- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2); ++ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2); + int l = vector2ic.x(); + int i1 = vector2ic.y(); + this.pose.pushPose(); + int j1 = 400; +- this.drawManaged(() -> TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400)); ++ this.drawManaged(() -> { ++ var colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_); ++ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd()); ++ }); + this.pose.translate(0.0F, 0.0F, 400.0F); + int k1 = i1; + + for (int l1 = 0; l1 < p_282615_.size(); l1++) { + ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1); +- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource); ++ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource); + k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0); + } + +@@ -982,7 +_,7 @@ + + for (int k2 = 0; k2 < p_282615_.size(); k2++) { + ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2); +- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this); ++ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this); + k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0); + } diff --git a/patches/minecraft/net/minecraft/client/gui/components/AbstractButton.java.patch b/patches/minecraft/net/minecraft/client/gui/components/AbstractButton.java.patch index a2c4aa6f18..67d4556292 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/AbstractButton.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/AbstractButton.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/components/AbstractButton.java +++ b/net/minecraft/client/gui/components/AbstractButton.java -@@ -29,7 +_,7 @@ - RenderSystem.enableDepthTest(); - p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight()); - p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F); -- int i = this.active ? 16777215 : 10526880; -+ int i = getFGColor(); - this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24); - } +@@ -32,7 +_,7 @@ + RenderSystem.enableDepthTest(); + p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight()); + p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F); +- int i = this.active ? 16777215 : 10526880; ++ int i = getFGColor(); + this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24); + } diff --git a/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch b/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch index 339b3b65ff..18e208cc47 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch @@ -1,22 +1,28 @@ --- a/net/minecraft/client/gui/components/AbstractWidget.java +++ b/net/minecraft/client/gui/components/AbstractWidget.java -@@ -233,6 +_,19 @@ - this.focused = p_93693_; - } +@@ -255,6 +_,25 @@ + this.focused = p_93693_; + } -+ public static final int UNSET_FG_COLOR = -1; -+ protected int packedFGColor = UNSET_FG_COLOR; -+ public int getFGColor() { -+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor; -+ return this.active ? 16777215 : 10526880; // White : Light Grey -+ } -+ public void setFGColor(int color) { -+ this.packedFGColor = color; -+ } -+ public void clearFGColor() { -+ this.packedFGColor = UNSET_FG_COLOR; -+ } ++ // Forge start ++ public static final int UNSET_FG_COLOR = -1; + - public NarratableEntry.NarrationPriority narrationPriority() { - if (this.isFocused()) { - return NarratableEntry.NarrationPriority.FOCUSED; ++ protected int packedFGColor = UNSET_FG_COLOR; ++ ++ public int getFGColor() { ++ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor; ++ return this.active ? 16777215 : 10526880; // White : Light Grey ++ } ++ ++ public void setFGColor(int color) { ++ this.packedFGColor = color; ++ } ++ ++ public void clearFGColor() { ++ this.packedFGColor = UNSET_FG_COLOR; ++ } ++ // Forge end ++ + @Override + public NarratableEntry.NarrationPriority narrationPriority() { + if (this.isFocused()) { diff --git a/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch b/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch index ee74fd903c..1384ff556d 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/gui/components/BossHealthOverlay.java +++ b/net/minecraft/client/gui/components/BossHealthOverlay.java -@@ -36,13 +_,16 @@ +@@ -63,13 +_,16 @@ - for(LerpingBossEvent lerpingbossevent : this.events.values()) { - int k = i / 2 - 91; -+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight); -+ if (!event.isCanceled()) { - this.drawBar(p_283175_, k, j, lerpingbossevent); - Component component = lerpingbossevent.getName(); - int l = this.minecraft.font.width(component); - int i1 = i / 2 - l / 2; - int j1 = j - 9; - p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215); -- j += 10 + 9; -+ } -+ j += event.getIncrement(); - if (j >= p_283175_.guiHeight() / 3) { - break; - } + for (LerpingBossEvent lerpingbossevent : this.events.values()) { + int k = i / 2 - 91; ++ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight); ++ if (!event.isCanceled()) { + this.drawBar(p_283175_, k, j, lerpingbossevent); + Component component = lerpingbossevent.getName(); + int l = this.minecraft.font.width(component); + int i1 = i / 2 - l / 2; + int j1 = j - 9; + p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215); +- j += 10 + 9; ++ } ++ j += event.getIncrement(); + if (j >= p_283175_.guiHeight() / 3) { + break; + } diff --git a/patches/minecraft/net/minecraft/client/gui/components/Button.java.patch b/patches/minecraft/net/minecraft/client/gui/components/Button.java.patch index 6e84d256f6..b021bbc94d 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/Button.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/Button.java.patch @@ -1,29 +1,31 @@ --- a/net/minecraft/client/gui/components/Button.java +++ b/net/minecraft/client/gui/components/Button.java -@@ -30,6 +_,11 @@ - this.createNarration = p_259552_; - } +@@ -31,6 +_,12 @@ + this.createNarration = p_259552_; + } -+ protected Button(Builder builder) { -+ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration); -+ setTooltip(builder.tooltip); // Forge: Make use of the Builder tooltip -+ } ++ // Forge (GH-9238) ++ protected Button(Builder builder) { ++ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration); ++ this.setTooltip(builder.tooltip); ++ } + - public void onPress() { - this.onPress.onPress(this); - } -@@ -93,9 +_,11 @@ - } + @Override + public void onPress() { + this.onPress.onPress(this); +@@ -95,9 +_,12 @@ + } - public Button build() { -- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration); -- button.setTooltip(this.tooltip); -- return button; -+ return build(Button::new); -+ } + public Button build() { +- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration); +- button.setTooltip(this.tooltip); +- return button; ++ return build(Button::new); ++ } + -+ public Button build(java.util.function.Function builder) { -+ return builder.apply(this); - } - } ++ // Forge (GH-9238) ++ public Button build(java.util.function.Function builder) { ++ return builder.apply(this); + } + } diff --git a/patches/minecraft/net/minecraft/client/gui/components/DebugScreenOverlay.java.patch b/patches/minecraft/net/minecraft/client/gui/components/DebugScreenOverlay.java.patch index c871f3abb5..6095ad6100 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/DebugScreenOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/DebugScreenOverlay.java.patch @@ -1,92 +1,93 @@ --- a/net/minecraft/client/gui/components/DebugScreenOverlay.java +++ b/net/minecraft/client/gui/components/DebugScreenOverlay.java -@@ -95,9 +_,9 @@ - @Nullable - private CompletableFuture serverChunk; - private boolean renderDebug; -- private boolean renderProfilerChart; -- private boolean renderFpsCharts; -- private boolean renderNetworkCharts; -+ protected boolean renderProfilerChart; -+ protected boolean renderFpsCharts; -+ protected boolean renderNetworkCharts; - private final SampleLogger frameTimeLogger = new SampleLogger(); - private final SampleLogger tickTimeLogger = new SampleLogger(); - private final SampleLogger pingLogger = new SampleLogger(); -@@ -124,14 +_,18 @@ - this.clientChunk = null; - } +@@ -101,9 +_,9 @@ + @Nullable + private CompletableFuture serverChunk; + private boolean renderDebug; +- private boolean renderProfilerChart; +- private boolean renderFpsCharts; +- private boolean renderNetworkCharts; ++ protected boolean renderProfilerChart; ++ protected boolean renderFpsCharts; ++ protected boolean renderNetworkCharts; + private final LocalSampleLogger frameTimeLogger = new LocalSampleLogger(1); + private final LocalSampleLogger tickTimeLogger = new LocalSampleLogger(TpsDebugDimensions.values().length); + private final LocalSampleLogger pingLogger = new LocalSampleLogger(1); +@@ -129,14 +_,18 @@ + this.clientChunk = null; + } -- public void render(GuiGraphics p_281427_) { -- this.minecraft.getProfiler().push("debug"); -+ protected void update() { - Entity entity = this.minecraft.getCameraEntity(); - this.block = entity.pick(20.0D, 0.0F, false); - this.liquid = entity.pick(20.0D, 0.0F, true); -- p_281427_.drawManaged(() -> { -- this.drawGameInformation(p_281427_); -- this.drawSystemInformation(p_281427_); -+ } +- public void render(GuiGraphics p_281427_) { +- this.minecraft.getProfiler().push("debug"); ++ protected void update() { + Entity entity = this.minecraft.getCameraEntity(); + this.block = entity.pick(20.0, 0.0F, false); + this.liquid = entity.pick(20.0, 0.0F, true); +- p_281427_.drawManaged(() -> { ++ } + -+ protected void drawText(GuiGraphics p_281427_) { -+ this.drawGameInformation(p_281427_); -+ this.drawSystemInformation(p_281427_); -+ } ++ protected void drawText(GuiGraphics p_281427_) { + this.drawGameInformation(p_281427_); + this.drawSystemInformation(p_281427_); ++ } + -+ protected void drawFPSCharts(GuiGraphics p_281427_) { - if (this.renderFpsCharts) { - int i = p_281427_.guiWidth(); - int j = i / 2; -@@ -141,7 +_,9 @@ - this.tpsChart.drawChart(p_281427_, i - k, k); ++ protected void drawFPSCharts(GuiGraphics p_281427_) { + if (this.renderFpsCharts) { + int i = p_281427_.guiWidth(); + int j = i / 2; +@@ -146,7 +_,9 @@ + this.tpsChart.drawChart(p_281427_, i - k, k); + } } - } -+ } ++ } -+ protected void drawNetworkCharts(GuiGraphics p_281427_) { - if (this.renderNetworkCharts) { - int l = p_281427_.guiWidth(); - int i1 = l / 2; -@@ -152,17 +_,32 @@ - int j1 = this.pingChart.getWidth(i1); - this.pingChart.drawChart(p_281427_, l - j1, j1); - } -+ } ++ protected void drawNetworkCharts(GuiGraphics p_281427_) { + if (this.renderNetworkCharts) { + int l = p_281427_.guiWidth(); + int i1 = l / 2; +@@ -157,12 +_,21 @@ + int j1 = this.pingChart.getWidth(i1); + this.pingChart.drawChart(p_281427_, l - j1, j1); + } ++ } + -+ public void render(GuiGraphics p_281427_) { -+ this.minecraft.getProfiler().push("debug"); -+ this.update(); -+ p_281427_.drawManaged(() -> { -+ this.drawText(p_281427_); -+ this.drawFPSCharts(p_281427_); -+ this.drawNetworkCharts(p_281427_); ++ public void render(GuiGraphics p_281427_) { ++ this.minecraft.getProfiler().push("debug"); ++ this.update(); ++ p_281427_.drawManaged(() -> { ++ this.drawText(p_281427_); ++ this.drawFPSCharts(p_281427_); ++ this.drawNetworkCharts(p_281427_); + }); + this.minecraft.getProfiler().pop(); + } - }); - this.minecraft.getProfiler().pop(); - } - -- protected void drawGameInformation(GuiGraphics p_281525_) { -- List list = this.getGameInformation(); -+ protected List getOverlayHelp() { -+ List list = Lists.newArrayList(); - list.add(""); - boolean flag = this.minecraft.getSingleplayerServer() != null; - list.add("Debug charts: [F3+1] Profiler " + (this.renderProfilerChart ? "visible" : "hidden") + "; [F3+2] " + (flag ? "FPS + TPS " : "FPS ") + (this.renderFpsCharts ? "visible" : "hidden") + "; [F3+3] " + (!this.minecraft.isLocalServer() ? "Bandwidth + Ping" : "Ping") + (this.renderNetworkCharts ? " visible" : " hidden")); - list.add("For help: press F3 + Q"); -+ return list; -+ } -+ +- protected void drawGameInformation(GuiGraphics p_281525_) { +- List list = this.getGameInformation(); ++ protected List getOverlayHelp() { ++ List list = Lists.newArrayList(); + list.add(""); + boolean flag = this.minecraft.getSingleplayerServer() != null; + list.add( +@@ -176,7 +_,12 @@ + + (this.renderNetworkCharts ? " visible" : " hidden") + ); + list.add("For help: press F3 + Q"); +- this.renderLines(p_281525_, list, true); ++ return list; ++ } + protected void drawGameInformation(GuiGraphics p_281525_) { + List list = this.getGameInformation(); + list.addAll(this.getOverlayHelp()); - this.renderLines(p_281525_, list, true); - } ++ this.renderLines(p_281525_, list, true); + } -@@ -451,6 +_,7 @@ - list.add(""); - list.add(ChatFormatting.UNDERLINE + "Targeted Entity"); - list.add(String.valueOf((Object)BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()))); -+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location())); - } + protected void drawSystemInformation(GuiGraphics p_281261_) { +@@ -529,6 +_,7 @@ + list.add(""); + list.add(ChatFormatting.UNDERLINE + "Targeted Entity"); + list.add(String.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()))); ++ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location())); + } - return list; + return list; diff --git a/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastComponent.java.patch b/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastComponent.java.patch index 920b7d61c9..3e682a3adc 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastComponent.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastComponent.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/components/toasts/ToastComponent.java +++ b/net/minecraft/client/gui/components/toasts/ToastComponent.java -@@ -101,6 +_,7 @@ - } +@@ -97,6 +_,7 @@ + } - public void addToast(Toast p_94923_) { -+ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return; - this.queued.add(p_94923_); - } + public void addToast(Toast p_94923_) { ++ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return; + this.queued.add(p_94923_); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch index 8968974f3a..db2f9d0fde 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch @@ -1,11 +1,10 @@ --- a/net/minecraft/client/gui/screens/ChatScreen.java +++ b/net/minecraft/client/gui/screens/ChatScreen.java -@@ -225,7 +_,7 @@ - this.minecraft.player.connection.sendChat(p_242400_); - } - -- return true; -+ return minecraft.screen == this; // FORGE: Prevent closing the screen if another screen has been opened. - } - } - +@@ -89,6 +_,7 @@ + return true; + } else if (p_95591_ == 257 || p_95591_ == 335) { + this.handleChatInput(this.input.getValue(), true); ++ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened. + this.minecraft.setScreen(null); + return true; + } else if (p_95591_ == 265) { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch index 37213e095f..a25bf46104 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/ConnectScreen.java +++ b/net/minecraft/client/gui/screens/ConnectScreen.java -@@ -85,6 +_,8 @@ - } +@@ -102,6 +_,8 @@ + } - if (optional.isEmpty()) { -+ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost()); -+ net.minecraftforge.network.DualStackUtils.logInitialPreferences(); - p_251955_.execute(() -> { - p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE)); - }); + if (optional.isEmpty()) { ++ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost()); ++ net.minecraftforge.network.DualStackUtils.logInitialPreferences(); + p_251955_.execute( + () -> p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE)) + ); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch index 02b12e39a8..c969051b14 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/client/gui/screens/LoadingOverlay.java +++ b/net/minecraft/client/gui/screens/LoadingOverlay.java -@@ -132,6 +_,7 @@ - } +@@ -131,6 +_,7 @@ + } - if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) { -+ this.fadeOutStart = Util.getMillis(); // Moved up to guard against inf loops caused by callback - try { - this.reload.checkExceptions(); - this.onFinish.accept(Optional.empty()); -@@ -139,7 +_,6 @@ - this.onFinish.accept(Optional.of(throwable)); - } + if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) { ++ this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback + try { + this.reload.checkExceptions(); + this.onFinish.accept(Optional.empty()); +@@ -138,7 +_,6 @@ + this.onFinish.accept(Optional.of(throwable)); + } -- this.fadeOutStart = Util.getMillis(); - if (this.minecraft.screen != null) { - this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight()); - } +- this.fadeOutStart = Util.getMillis(); + if (this.minecraft.screen != null) { + this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight()); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch index 27d68c4a7c..0c698b161a 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch @@ -1,25 +1,20 @@ --- a/net/minecraft/client/gui/screens/MenuScreens.java +++ b/net/minecraft/client/gui/screens/MenuScreens.java -@@ -41,6 +_,10 @@ - private static final Map, MenuScreens.ScreenConstructor> SCREENS = Maps.newHashMap(); +@@ -41,11 +_,16 @@ + private static final Map, MenuScreens.ScreenConstructor> SCREENS = Maps.newHashMap(); - public static void create(@Nullable MenuType p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) { -+ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_)); -+ } + public static void create(MenuType p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) { ++ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_)); ++ } + -+ public static java.util.Optional> getScreenFactory(@Nullable MenuType p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) { - if (p_96202_ == null) { - LOGGER.warn("Trying to open invalid screen with name: {}", (Object)p_96205_.getString()); - } else { -@@ -48,9 +_,10 @@ - if (screenconstructor == null) { - LOGGER.warn("Failed to create screen for menu type: {}", (Object)BuiltInRegistries.MENU.getKey(p_96202_)); - } else { ++ public static java.util.Optional> getScreenFactory(@Nullable MenuType p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) { + MenuScreens.ScreenConstructor screenconstructor = getConstructor(p_96202_); + if (screenconstructor == null) { + LOGGER.warn("Failed to create screen for menu type: {}", BuiltInRegistries.MENU.getKey(p_96202_)); ++ return java.util.Optional.empty(); + } else { - screenconstructor.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_); + return java.util.Optional.of(screenconstructor); - } - } -+ return java.util.Optional.empty(); - } + } + } - @Nullable diff --git a/patches/minecraft/net/minecraft/client/gui/screens/OptionsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/OptionsScreen.java.patch deleted file mode 100644 index b0d09f10d3..0000000000 --- a/patches/minecraft/net/minecraft/client/gui/screens/OptionsScreen.java.patch +++ /dev/null @@ -1,17 +0,0 @@ ---- a/net/minecraft/client/gui/screens/OptionsScreen.java -+++ b/net/minecraft/client/gui/screens/OptionsScreen.java -@@ -150,6 +_,14 @@ - p_283520_.drawCenteredString(this.font, this.title, this.width / 2, 15, 16777215); - } - -+ @Override -+ public void onClose() { -+ // We need to consider 2 potential parent screens here: -+ // 1. From the main menu, in which case display the main menu -+ // 2. From the pause menu, in which case exit back to game -+ this.minecraft.setScreen(this.lastScreen instanceof PauseScreen ? null : this.lastScreen); -+ } -+ - private Button openScreenButton(Component p_261565_, Supplier p_262119_) { - return Button.builder(p_261565_, (p_280808_) -> { - this.minecraft.setScreen(p_262119_.get()); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch index 8a8ffdc0ce..efc44a064e 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/screens/PauseScreen.java +++ b/net/minecraft/client/gui/screens/PauseScreen.java -@@ -87,6 +_,7 @@ - } else { - gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, SocialInteractionsScreen::new)); - } -+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2); +@@ -86,6 +_,7 @@ + } else { + gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this))); + } ++ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2); - Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT; - this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, (p_280815_) -> { + Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT; + this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, p_280815_ -> { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch index 1ebdc4cb85..b773d28aaf 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch @@ -1,74 +1,61 @@ --- a/net/minecraft/client/gui/screens/Screen.java +++ b/net/minecraft/client/gui/screens/Screen.java -@@ -207,7 +_,7 @@ - } +@@ -204,7 +_,7 @@ + } - public void onClose() { -- this.minecraft.setScreen((Screen)null); -+ this.minecraft.popGuiLayer(); - } + public void onClose() { +- this.minecraft.setScreen(null); ++ this.minecraft.popGuiLayer(); + } - protected T addRenderableWidget(T p_169406_) { -@@ -319,7 +_,10 @@ - this.width = p_96608_; - this.height = p_96609_; - if (!this.initialized) { -+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) { - this.init(); -+ } -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget)); - } else { - this.repositionElements(); - } -@@ -332,7 +_,10 @@ - protected void rebuildWidgets() { - this.clearWidgets(); - this.clearFocus(); -+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) { - this.init(); -+ } -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget)); - } + protected T addRenderableWidget(T p_169406_) { +@@ -320,8 +_,10 @@ + this.width = p_96608_; + this.height = p_96609_; + if (!this.initialized) { ++ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) + this.init(); + this.setInitialFocus(); ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget)); + } else { + this.repositionElements(); + } +@@ -334,8 +_,10 @@ + protected void rebuildWidgets() { + this.clearWidgets(); + this.clearFocus(); ++ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) + this.init(); + this.setInitialFocus(); ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget)); + } - public List children() { -@@ -354,6 +_,7 @@ - public void renderBackground(GuiGraphics p_283688_, int p_299421_, int p_298679_, float p_297268_) { - if (this.minecraft.level != null) { - this.renderTransparentBackground(p_283688_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_283688_)); - } else { - this.renderDirtBackground(p_283688_); - } -@@ -369,6 +_,7 @@ - int i = 32; - p_282281_.blit(BACKGROUND_LOCATION, 0, 0, 0, 0.0F, 0.0F, this.width, this.height, 32, 32); - p_282281_.setColor(1.0F, 1.0F, 1.0F, 1.0F); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_282281_)); - } + @Override +@@ -362,6 +_,7 @@ - public boolean isPauseScreen() { -@@ -462,6 +_,10 @@ - public void onFilesDrop(List p_96591_) { - } + this.renderBlurredBackground(p_297268_); + this.renderMenuBackground(p_283688_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_); + } -+ public Minecraft getMinecraft() { -+ return this.minecraft; -+ } + protected void renderBlurredBackground(float p_336041_) { +@@ -492,6 +_,19 @@ + } + + public void onFilesDrop(List p_96591_) { ++ } + - private void scheduleNarration(long p_169381_, boolean p_169382_) { - this.nextNarrationTime = Util.getMillis() + p_169381_; - if (p_169382_) { -@@ -632,5 +_,13 @@ - this.index = p_169425_; - this.priority = p_169426_; - } -+ } ++ @Nullable ++ public Minecraft getMinecraft() { ++ return minecraft; ++ } + -+ private void addEventWidget(GuiEventListener b) { -+ if (b instanceof Renderable r) -+ this.renderables.add(r); -+ if (b instanceof NarratableEntry ne) -+ this.narratables.add(ne); -+ children.add(b); - } - } ++ private void addEventWidget(GuiEventListener guiEventListener) { ++ if (guiEventListener instanceof Renderable r) ++ this.renderables.add(r); ++ if (guiEventListener instanceof NarratableEntry ne) ++ this.narratables.add(ne); ++ this.children.add(guiEventListener); + } + + private void scheduleNarration(long p_169381_, boolean p_169382_) { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch index cad639e7f4..15d457639a 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch @@ -1,67 +1,64 @@ --- a/net/minecraft/client/gui/screens/TitleScreen.java +++ b/net/minecraft/client/gui/screens/TitleScreen.java -@@ -63,6 +_,7 @@ - @Nullable - private TitleScreen.WarningLabel warningLabel; - private final LogoRenderer logoRenderer; -+ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification; +@@ -61,6 +_,7 @@ + @Nullable + private TitleScreen.WarningLabel warningLabel; + private final LogoRenderer logoRenderer; ++ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification; - public TitleScreen() { - this(false); -@@ -113,11 +_,15 @@ - int j = this.width - i - 2; - int k = 24; - int l = this.height / 4 + 48; -+ Button modButton = null; - if (this.minecraft.isDemo()) { - this.createDemoMenuOptions(l, 24); - } else { - this.createNormalMenuOptions(l, 24); -+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))) -+ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build()); - } -+ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton); + public TitleScreen() { + this(false); +@@ -116,11 +_,15 @@ + int j = this.width - i - 2; + int k = 24; + int l = this.height / 4 + 48; ++ Button modButton = null; + if (this.minecraft.isDemo()) { + this.createDemoMenuOptions(l, 24); + } else { + this.createNormalMenuOptions(l, 24); ++ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))) ++ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build()); + } ++ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton); - SpriteIconButton spriteiconbutton = this.addRenderableWidget(CommonButtons.language(20, (p_280830_) -> { - this.minecraft.setScreen(new LanguageSelectScreen(this, this.minecraft.options, this.minecraft.getLanguageManager())); -@@ -163,7 +_,7 @@ - }).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build())).active = flag; - (this.addRenderableWidget(Button.builder(Component.translatable("menu.online"), (p_210872_) -> { - this.realmsButtonClicked(); -- }).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20).tooltip(tooltip).build())).active = flag; -+ }).bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20).tooltip(tooltip).build())).active = flag; - } + SpriteIconButton spriteiconbutton = this.addRenderableWidget( + CommonButtons.language( +@@ -171,7 +_,7 @@ + }).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build()).active = flag; + this.addRenderableWidget( + Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this))) +- .bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20) ++ .bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20) + .tooltip(tooltip) + .build() + ) +@@ -281,6 +_,7 @@ + this.warningLabel.render(p_282860_, i); + } - @Nullable -@@ -243,6 +_,7 @@ - this.warningLabel.render(p_282860_, i); - } ++ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i); + if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) { + this.splash.render(p_282860_, this.width, this.font, i); + } +@@ -296,11 +_,19 @@ + s = s + I18n.get("menu.modded"); + } -+ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i); - if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) { - this.splash.render(p_282860_, this.width, this.font, i); - } -@@ -258,7 +_,14 @@ - s = s + I18n.get("menu.modded"); - } - -- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i); -+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) -> -+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i) -+ ); +- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i); ++ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) -> ++ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i) ++ ); + -+ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) -> -+ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i) -+ ); ++ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) -> ++ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i) ++ ); + + if (this.realmsNotificationsEnabled() && f >= 1.0F) { + RenderSystem.enableDepthTest(); + this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_); + } ++ if (f >= 1.0f) this.modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_); + } + } - for(GuiEventListener guieventlistener : this.children()) { - if (guieventlistener instanceof AbstractWidget) { -@@ -271,6 +_,7 @@ - RenderSystem.enableDepthTest(); - this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_); - } -+ if (f1 >= 1.0f) modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_); - - } - } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch index 02cf704711..77a576f7dd 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch @@ -1,37 +1,37 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java @@ -37,6 +_,7 @@ - private int maxY = Integer.MIN_VALUE; - private float fade; - private boolean centered; -+ private int page; + private int maxY = Integer.MIN_VALUE; + private float fade; + private boolean centered; ++ private int page; - public AdvancementTab(Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_) { - this.minecraft = p_97145_; -@@ -51,6 +_,15 @@ - this.addWidget(this.root, p_297568_.holder()); - } + public AdvancementTab( + Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_ +@@ -53,6 +_,15 @@ + this.addWidget(this.root, p_297568_.holder()); + } -+ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) { -+ this(mc, screen, type, index, adv, info); -+ this.page = page; -+ } ++ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) { ++ this(mc, screen, type, index, adv, info); ++ this.page = page; ++ } + -+ public int getPage() { -+ return page; -+ } ++ public int getPage() { ++ return this.page; ++ } + - public AdvancementTabType getType() { - return this.type; - } -@@ -145,8 +_,8 @@ - return null; - } else { - for(AdvancementTabType advancementtabtype : AdvancementTabType.values()) { -- if (p_97173_ < advancementtabtype.getMax()) { -- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get()); -+ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) { -+ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get()); - } + public AdvancementTabType getType() { + return this.type; + } +@@ -146,8 +_,8 @@ + return null; + } else { + for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) { +- if (p_97173_ < advancementtabtype.getMax()) { +- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get()); ++ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) { ++ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get()); + } - p_97173_ -= advancementtabtype.getMax(); + p_97173_ -= advancementtabtype.getMax(); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java.patch index c2392b8290..e59c5b25e0 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java -@@ -13,6 +_,7 @@ - LEFT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top_selected"), new ResourceLocation("advancements/tab_left_middle_selected"), new ResourceLocation("advancements/tab_left_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top"), new ResourceLocation("advancements/tab_left_middle"), new ResourceLocation("advancements/tab_left_bottom")), 32, 28, 5), - RIGHT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top_selected"), new ResourceLocation("advancements/tab_right_middle_selected"), new ResourceLocation("advancements/tab_right_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top"), new ResourceLocation("advancements/tab_right_middle"), new ResourceLocation("advancements/tab_right_bottom")), 32, 28, 5); +@@ -69,6 +_,7 @@ + 5 + ); -+ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum(); - private final AdvancementTabType.Sprites selectedSprites; - private final AdvancementTabType.Sprites unselectedSprites; - private final int width; ++ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum(); + private final AdvancementTabType.Sprites selectedSprites; + private final AdvancementTabType.Sprites unselectedSprites; + private final int width; diff --git a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch index b20464af7e..bcfeee7b7b 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch @@ -1,74 +1,60 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java -@@ -42,6 +_,7 @@ - @Nullable - private AdvancementTab selectedTab; - private boolean isScrolling; -+ private static int tabPage, maxPages; +@@ -49,6 +_,7 @@ + @Nullable + private AdvancementTab selectedTab; + private boolean isScrolling; ++ private static int tabPage, maxPages; - public AdvancementsScreen(ClientAdvancements p_97340_) { - super(GameNarrator.NO_TITLE); -@@ -58,7 +_,15 @@ - } else { - this.advancements.setSelectedTab(this.selectedTab == null ? null : this.selectedTab.getRootNode().holder(), true); - } -- -+ if (this.tabs.size() > AdvancementTabType.MAX_TABS) { -+ int guiLeft = (this.width - 252) / 2; -+ int guiTop = (this.height - 140) / 2; -+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> tabPage = Math.max(tabPage - 1, 0 )) -+ .pos(guiLeft, guiTop - 50).size(20, 20).build()); -+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> tabPage = Math.min(tabPage + 1, maxPages)) -+ .pos(guiLeft + WINDOW_WIDTH - 20, guiTop - 50).size(20, 20).build()); -+ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS; -+ } - } + public AdvancementsScreen(ClientAdvancements p_97340_) { + this(p_97340_, null); +@@ -62,6 +_,19 @@ - public void removed() { -@@ -76,7 +_,7 @@ - int j = (this.height - 140) / 2; + @Override + protected void init() { ++ if (this.tabs.size() > AdvancementTabType.MAX_TABS) { ++ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS; ++ var pageLayout = new net.minecraft.client.gui.layouts.GridLayout(); ++ var text = new net.minecraft.client.gui.components.StringWidget(Component.literal(String.format("%d / %d", maxPages + 1, maxPages + 1)), this.font); ++ var update = (java.util.function.Consumer)back -> { ++ tabPage = back ? Math.max(tabPage - 1, 0) : Math.min(tabPage + 1, maxPages); ++ text.setMessage(Component.literal(String.format("%d / %d", 1, maxPages + 1))); ++ }; ++ pageLayout.addChild(Button.builder(Component.literal("<"), b -> update.accept(true)).size(20, 20).build(), 0, 0, pageLayout.defaultCellSetting().alignHorizontallyLeft()); ++ pageLayout.addChild(text, 0, 1, pageLayout.defaultCellSetting().alignHorizontallyCenter()); ++ pageLayout.addChild(Button.builder(Component.literal(">"), b -> update.accept(false)).size(20, 20).build(), 0, 2, pageLayout.defaultCellSetting().alignHorizontallyRight()); ++ this.layout.addToHeader(pageLayout); ++ } + this.layout.addTitleHeader(TITLE, this.font); + this.tabs.clear(); + this.selectedTab = null; +@@ -106,7 +_,7 @@ + int j = (this.height - 140) / 2; - for(AdvancementTab advancementtab : this.tabs.values()) { -- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) { -+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) { - this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true); - break; + for (AdvancementTab advancementtab : this.tabs.values()) { +- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) { ++ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) { + this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true); + break; + } +@@ -180,10 +_,12 @@ + p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140); + if (this.tabs.size() > 1) { + for (AdvancementTab advancementtab : this.tabs.values()) { ++ if (advancementtab.getPage() == tabPage) + advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab); } -@@ -100,9 +_,15 @@ - int i = (this.width - 252) / 2; - int j = (this.height - 140) / 2; - this.renderBackground(p_282589_, p_282255_, p_283354_, p_283123_); -+ if (maxPages != 0) { -+ net.minecraft.network.chat.Component page = Component.literal(String.format("%d / %d", tabPage + 1, maxPages + 1)); -+ int width = this.font.width(page); -+ p_282589_.drawString(this.font, page.getVisualOrderText(), i + (252 / 2) - (width / 2), j - 44, -1); -+ } - this.renderInside(p_282589_, p_282255_, p_283354_, i, j); - this.renderWindow(p_282589_, i, j); - this.renderTooltips(p_282589_, p_282255_, p_283354_, i, j); -+ this.renderables.forEach(r -> r.render(p_282589_, p_282255_, p_283354_, p_283123_)); - } - public boolean mouseDragged(double p_97347_, double p_97348_, int p_97349_, double p_97350_, double p_97351_) { -@@ -146,10 +_,12 @@ - p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140); - if (this.tabs.size() > 1) { - for(AdvancementTab advancementtab : this.tabs.values()) { -+ if (advancementtab.getPage() == tabPage) - advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab); - } - - for(AdvancementTab advancementtab1 : this.tabs.values()) { -+ if (advancementtab1.getPage() == tabPage) - advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_); - } - } -@@ -169,7 +_,7 @@ - - if (this.tabs.size() > 1) { - for(AdvancementTab advancementtab : this.tabs.values()) { -- if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) { -+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) { - p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_); + for (AdvancementTab advancementtab1 : this.tabs.values()) { ++ if (advancementtab1.getPage() == tabPage) + advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_); } - } + } +@@ -203,6 +_,7 @@ + + if (this.tabs.size() > 1) { + for (AdvancementTab advancementtab : this.tabs.values()) { ++ if (advancementtab.getPage() == tabPage) + if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) { + p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsList.java.patch index cd80d621af..d270111787 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsList.java.patch @@ -1,44 +1,43 @@ --- a/net/minecraft/client/gui/screens/controls/KeyBindsList.java +++ b/net/minecraft/client/gui/screens/controls/KeyBindsList.java -@@ -64,7 +_,7 @@ - } +@@ -69,6 +_,11 @@ + return 340; + } - protected int getScrollbarPosition() { -- return super.getScrollbarPosition() + 15; -+ return super.getScrollbarPosition() + 15 + 20; - } - - public int getRowWidth() { -@@ -128,11 +_,13 @@ - this.name = p_193917_; - this.changeButton = Button.builder(p_193917_, (p_269618_) -> { - KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_; -+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN); - KeyBindsList.this.resetMappingAndUpdateButtons(); -- }).bounds(0, 0, 75, 20).createNarration((p_253311_) -> { -+ }).bounds(0, 0, 75 + 20 /* Forge: Add space */, 20).createNarration((p_253311_) -> { - return p_193916_.isUnbound() ? Component.translatable("narrator.controls.unbound", p_193917_) : Component.translatable("narrator.controls.bound", p_193917_, p_253311_.get()); - }).build(); - this.resetButton = Button.builder(Component.translatable("controls.reset"), (p_269616_) -> { -+ this.key.setToDefault(); - KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey()); - KeyBindsList.this.resetMappingAndUpdateButtons(); - }).bounds(0, 0, 50, 20).createNarration((p_253313_) -> { -@@ -144,7 +_,7 @@ - public void render(GuiGraphics p_281805_, int p_281298_, int p_282357_, int p_281373_, int p_283433_, int p_281932_, int p_282224_, int p_282053_, boolean p_282605_, float p_281432_) { - int k = p_281373_ + 90 - KeyBindsList.this.maxNameWidth; - p_281805_.drawString(KeyBindsList.this.minecraft.font, this.name, k, p_282357_ + p_281932_ / 2 - 9 / 2, 16777215, false); -- this.resetButton.setX(p_281373_ + 190); -+ this.resetButton.setX(p_281373_ + 190 + 20); - this.resetButton.setY(p_282357_); - this.resetButton.render(p_281805_, p_282224_, p_282053_, p_281432_); - this.changeButton.setX(p_281373_ + 105); -@@ -173,7 +_,7 @@ - MutableComponent mutablecomponent = Component.empty(); - if (!this.key.isUnbound()) { - for(KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) { -- if (keymapping != this.key && this.key.same(keymapping)) { -+ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G - if (this.hasCollision) { - mutablecomponent.append(", "); - } ++ @Override ++ protected int getScrollbarPosition() { ++ return super.getScrollbarPosition() + 20; ++ } ++ + @OnlyIn(Dist.CLIENT) + public class CategoryEntry extends KeyBindsList.Entry { + final Component name; +@@ -153,9 +_,10 @@ + this.name = p_193917_; + this.changeButton = Button.builder(p_193917_, p_269618_ -> { + KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_; ++ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN); + KeyBindsList.this.resetMappingAndUpdateButtons(); + }) +- .bounds(0, 0, 75, 20) ++ .bounds(0, 0, 75 + 20 /* Forge: Add space */, 20) + .createNarration( + p_253311_ -> p_193916_.isUnbound() + ? Component.translatable("narrator.controls.unbound", p_193917_) +@@ -163,6 +_,7 @@ + ) + .build(); + this.resetButton = Button.builder(RESET_BUTTON_TITLE, p_325376_ -> { ++ this.key.setToDefault(); + KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey()); + KeyBindsList.this.resetMappingAndUpdateButtons(); + }).bounds(0, 0, 50, 20).createNarration(p_253313_ -> Component.translatable("narrator.controls.reset", p_193917_)).build(); +@@ -215,7 +_,7 @@ + MutableComponent mutablecomponent = Component.empty(); + if (!this.key.isUnbound()) { + for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) { +- if (keymapping != this.key && this.key.same(keymapping)) { ++ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G + if (this.hasCollision) { + mutablecomponent.append(", "); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java.patch index 914880e925..c6430cdabe 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java.patch @@ -1,46 +1,46 @@ --- a/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java +++ b/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java -@@ -30,7 +_,7 @@ - this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft)); - this.resetButton = this.addRenderableWidget(Button.builder(Component.translatable("controls.resetAll"), (p_269619_) -> { - for(KeyMapping keymapping : this.options.keyMappings) { -- keymapping.setKey(keymapping.getDefaultKey()); -+ keymapping.setToDefault(); - } +@@ -33,7 +_,7 @@ + this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft)); + this.resetButton = Button.builder(Component.translatable("controls.resetAll"), p_269619_ -> { + for (KeyMapping keymapping : this.options.keyMappings) { +- keymapping.setKey(keymapping.getDefaultKey()); ++ keymapping.setToDefault(); + } - this.keyBindsList.resetMappingAndUpdateButtons(); -@@ -54,11 +_,13 @@ - public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) { - if (this.selectedKey != null) { - if (p_193987_ == 256) { -+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN); - this.options.setKey(this.selectedKey, InputConstants.UNKNOWN); - } else { -+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_)); - this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_)); - } -- -+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey())) - this.selectedKey = null; - this.lastKeySelection = Util.getMillis(); - this.keyBindsList.resetMappingAndUpdateButtons(); -@@ -66,6 +_,19 @@ - } else { - return super.keyPressed(p_193987_, p_193988_, p_193989_); - } -+ } + this.keyBindsList.resetMappingAndUpdateButtons(); +@@ -70,11 +_,14 @@ + public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) { + if (this.selectedKey != null) { + if (p_193987_ == 256) { ++ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN); + this.options.setKey(this.selectedKey, InputConstants.UNKNOWN); + } else { ++ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_)); + this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_)); + } + ++ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey())) + this.selectedKey = null; + this.lastKeySelection = Util.getMillis(); + this.keyBindsList.resetMappingAndUpdateButtons(); +@@ -82,6 +_,19 @@ + } else { + return super.keyPressed(p_193987_, p_193988_, p_193989_); + } ++ } + -+ @Override -+ public boolean keyReleased(int keyCode, int scanCode, int modifiers) { -+ // Forge: We wait for a second key above if the first press is a modifier -+ // but if they release the modifier then set it explicitly. -+ var key = InputConstants.getKey(keyCode, scanCode); -+ if (this.selectedKey != null && this.selectedKey.getKey() == key) { -+ this.selectedKey = null; -+ this.lastKeySelection = Util.getMillis(); -+ this.keyBindsList.resetMappingAndUpdateButtons(); -+ } -+ return super.keyReleased(keyCode, scanCode, modifiers); - } ++ @Override ++ public boolean keyReleased(int keyCode, int scanCode, int modifiers) { ++ // Forge: We wait for a second key above if the first press is a modifier ++ // but if they release the modifier then set it explicitly. ++ var key = InputConstants.getKey(keyCode, scanCode); ++ if (this.selectedKey != null && this.selectedKey.getKey() == key) { ++ this.selectedKey = null; ++ this.lastKeySelection = Util.getMillis(); ++ this.keyBindsList.resetMappingAndUpdateButtons(); ++ } ++ return super.keyReleased(keyCode, scanCode, modifiers); + } - public void render(GuiGraphics p_282556_, int p_193992_, int p_193993_, float p_193994_) { + @Override diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch index d7bace152a..2e2ced75b5 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch @@ -1,188 +1,153 @@ --- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java +++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java -@@ -90,6 +_,7 @@ - int i = this.leftPos; - int j = this.topPos; - super.render(p_283479_, p_283661_, p_281248_, p_281886_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Background(this, p_283479_, p_283661_, p_281248_)); - RenderSystem.disableDepthTest(); - p_283479_.pose().pushPose(); - p_283479_.pose().translate((float)i, (float)j, 0.0F); -@@ -106,12 +_,13 @@ - int l = slot.x; - int i1 = slot.y; - if (this.hoveredSlot.isHighlightable()) { -- renderSlotHighlight(p_283479_, l, i1, 0); -+ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k)); +@@ -92,6 +_,7 @@ + int i = this.leftPos; + int j = this.topPos; + super.render(p_283479_, p_283661_, p_281248_, p_281886_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderBackground(this, p_283479_, p_283661_, p_281248_); + RenderSystem.disableDepthTest(); + p_283479_.pose().pushPose(); + p_283479_.pose().translate((float)i, (float)j, 0.0F); +@@ -108,12 +_,13 @@ + int l = slot.x; + int i1 = slot.y; + if (this.hoveredSlot.isHighlightable()) { +- renderSlotHighlight(p_283479_, l, i1, 0); ++ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k)); + } } - } - } + } - this.renderLabels(p_283479_, p_283661_, p_281248_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Foreground(this, p_283479_, p_283661_, p_281248_)); - ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem; - if (!itemstack.isEmpty()) { - int l1 = 8; -@@ -153,13 +_,16 @@ - } + this.renderLabels(p_283479_, p_283661_, p_281248_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderForeground(this, p_283479_, p_283661_, p_281248_); + ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem; + if (!itemstack.isEmpty()) { + int l1 = 8; +@@ -156,13 +_,17 @@ + } - public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) { -- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_); -+ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433); -+ } -+ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) { -+ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_); - } + public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) { +- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_); ++ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433); ++ } ++ ++ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) { ++ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_); + } - protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) { - if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) { - ItemStack itemstack = this.hoveredSlot.getItem(); -- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_); -+ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_); - } + protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) { + if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) { + ItemStack itemstack = this.hoveredSlot.getItem(); +- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_); ++ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_); + } + } - } -@@ -172,7 +_,8 @@ - p_282567_.pose().pushPose(); - p_282567_.pose().translate(0.0F, 0.0F, 232.0F); - p_282567_.renderItem(p_281330_, p_281772_, p_281689_); -- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_); -+ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT); -+ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_); - p_282567_.pose().popPose(); - } +@@ -174,7 +_,8 @@ + p_282567_.pose().pushPose(); + p_282567_.pose().translate(0.0F, 0.0F, 232.0F); + p_282567_.renderItem(p_281330_, p_281772_, p_281689_); +- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_); ++ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT); ++ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_); + p_282567_.pose().popPose(); + } -@@ -280,7 +_,8 @@ - if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) { - return true; - } else { -- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems(); -+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_); -+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey); - Slot slot = this.findSlot(p_97748_, p_97749_); - long i = Util.getMillis(); - this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_; -@@ -291,6 +_,7 @@ - int j = this.leftPos; - int k = this.topPos; - boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_); -+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries - int l = -1; - if (slot != null) { - l = slot.index; -@@ -316,7 +_,7 @@ - } - } else if (!this.isQuickCrafting) { - if (this.menu.getCarried().isEmpty()) { -- if (flag) { -+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, l, p_97750_, ClickType.CLONE); - } else { - boolean flag2 = l != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344)); -@@ -340,7 +_,7 @@ - this.quickCraftingType = 0; - } else if (p_97750_ == 1) { - this.quickCraftingType = 1; -- } else if (flag) { -+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.quickCraftingType = 2; - } - } -@@ -409,10 +_,13 @@ - } - - public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) { -+ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons - Slot slot = this.findSlot(p_97812_, p_97813_); - int i = this.leftPos; - int j = this.topPos; - boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_); -+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries -+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_); - int k = -1; - if (slot != null) { - k = slot.index; -@@ -426,7 +_,7 @@ - if (hasShiftDown()) { - if (!this.lastQuickMoved.isEmpty()) { - for(Slot slot2 : this.menu.slots) { -- if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.container == slot.container && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) { -+ if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.isSameInventory(slot) && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) { - this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE); - } - } -@@ -489,7 +_,7 @@ - - this.slotClicked((Slot)null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT); - } else if (!this.menu.getCarried().isEmpty()) { -- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) { -+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, k, p_97814_, ClickType.CLONE); - } else { - boolean flag1 = k != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344)); -@@ -540,34 +_,39 @@ - } - - public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) { -+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_); - if (super.keyPressed(p_97765_, p_97766_, p_97767_)) { - return true; -- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) { -+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) { - this.onClose(); - return true; - } else { -- this.checkHotbarKeyPressed(p_97765_, p_97766_); -+ boolean handled = this.checkHotbarKeyPressed(p_97765_, p_97766_);// Forge MC-146650: Needs to return true when the key is handled - if (this.hoveredSlot != null && this.hoveredSlot.hasItem()) { -- if (this.minecraft.options.keyPickItem.matches(p_97765_, p_97766_)) { -+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 0, ClickType.CLONE); -- } else if (this.minecraft.options.keyDrop.matches(p_97765_, p_97766_)) { -+ handled = true; -+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) { - this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, hasControlDown() ? 1 : 0, ClickType.THROW); -+ handled = true; - } -+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) { -+ handled = true; // Forge MC-146650: Emulate MC bug, so we don't drop from hotbar when pressing drop without hovering over a item. - } - -- return true; -+ return handled; - } - } - - protected boolean checkHotbarKeyPressed(int p_97806_, int p_97807_) { - if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null) { -- if (this.minecraft.options.keySwapOffhand.matches(p_97806_, p_97807_)) { -+ if (this.minecraft.options.keySwapOffhand.isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) { - this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 40, ClickType.SWAP); +@@ -282,7 +_,8 @@ + if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) { return true; - } + } else { +- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems(); ++ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_); ++ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey); + Slot slot = this.findSlot(p_97748_, p_97749_); + long i = Util.getMillis(); + this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_; +@@ -293,6 +_,7 @@ + int j = this.leftPos; + int k = this.topPos; + boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_); ++ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + int l = -1; + if (slot != null) { + l = slot.index; +@@ -318,7 +_,7 @@ + } + } else if (!this.isQuickCrafting) { + if (this.menu.getCarried().isEmpty()) { +- if (flag) { ++ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + this.slotClicked(slot, l, p_97750_, ClickType.CLONE); + } else { + boolean flag2 = l != -999 +@@ -346,7 +_,7 @@ + this.quickCraftingType = 0; + } else if (p_97750_ == 1) { + this.quickCraftingType = 1; +- } else if (flag) { ++ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + this.quickCraftingType = 2; + } + } +@@ -425,10 +_,13 @@ - for(int i = 0; i < 9; ++i) { -- if (this.minecraft.options.keyHotbarSlots[i].matches(p_97806_, p_97807_)) { -+ if (this.minecraft.options.keyHotbarSlots[i].isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) { - this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, i, ClickType.SWAP); - return true; - } -@@ -602,6 +_,18 @@ + @Override + public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) { ++ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons + Slot slot = this.findSlot(p_97812_, p_97813_); + int i = this.leftPos; + int j = this.topPos; + boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_); ++ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries ++ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_); + int k = -1; + if (slot != null) { + k = slot.index; +@@ -445,7 +_,7 @@ + if (slot2 != null + && slot2.mayPickup(this.minecraft.player) + && slot2.hasItem() +- && slot2.container == slot.container ++ && slot2.isSameInventory(slot) + && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) { + this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE); + } +@@ -509,7 +_,7 @@ - public T getMenu() { - return this.menu; -+ } + this.slotClicked(null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT); + } else if (!this.menu.getCarried().isEmpty()) { +- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) { ++ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + this.slotClicked(slot, k, p_97814_, ClickType.CLONE); + } else { + boolean flag1 = k != -999 +@@ -568,9 +_,10 @@ + + @Override + public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) { ++ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_); + if (super.keyPressed(p_97765_, p_97766_, p_97767_)) { + return true; +- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) { ++ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) { + this.onClose(); + return true; + } else { +@@ -639,5 +_,17 @@ + public void onClose() { + this.minecraft.player.closeContainer(); + super.onClose(); ++ } + -+ @org.jetbrains.annotations.Nullable -+ public Slot getSlotUnderMouse() { return this.hoveredSlot; } -+ public int getGuiLeft() { return leftPos; } -+ public int getGuiTop() { return topPos; } -+ public int getXSize() { return imageWidth; } -+ public int getYSize() { return imageHeight; } ++ @org.jetbrains.annotations.Nullable ++ public Slot getSlotUnderMouse() { return this.hoveredSlot; } ++ public int getGuiLeft() { return leftPos; } ++ public int getGuiTop() { return topPos; } ++ public int getXSize() { return imageWidth; } ++ public int getYSize() { return imageHeight; } + -+ protected int slotColor = -2130706433; -+ public int getSlotColor(int index) { -+ return slotColor; - } - - public void onClose() { ++ protected int slotColor = -2130706433; ++ public int getSlotColor(int index) { ++ return slotColor; + } + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch index 950e15f1b1..3154d6980d 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch @@ -1,288 +1,291 @@ --- a/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java +++ b/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java -@@ -79,6 +_,8 @@ - private boolean hasClickedOutside; - private final Set> visibleTags = new HashSet<>(); - private final boolean displayOperatorCreativeTab; -+ private final List pages = new java.util.ArrayList<>(); -+ private net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>()); +@@ -112,6 +_,8 @@ + private boolean hasClickedOutside; + private final Set> visibleTags = new HashSet<>(); + private final boolean displayOperatorCreativeTab; ++ private final List pages = new java.util.ArrayList<>(); ++ private net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>()); - public CreativeModeInventoryScreen(Player p_259788_, FeatureFlagSet p_260074_, boolean p_259569_) { - super(new CreativeModeInventoryScreen.ItemPickerMenu(p_259788_), p_259788_.getInventory(), CommonComponents.EMPTY); -@@ -112,7 +_,7 @@ - private void refreshCurrentTabContents(Collection p_261591_) { - int i = this.menu.getRowIndexForScroll(this.scrollOffs); - (this.menu).items.clear(); -- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { -+ if (selectedTab.hasSearchBar()) { - this.refreshSearchResults(); - } else { - (this.menu).items.addAll(p_261591_); -@@ -266,6 +_,34 @@ - protected void init() { - if (this.minecraft.gameMode.hasInfiniteItems()) { - super.init(); -+ this.pages.clear(); -+ int tabIndex = 0; -+ List currentPage = new java.util.ArrayList<>(); -+ for (CreativeModeTab sortedCreativeModeTab : net.minecraftforge.common.CreativeModeTabRegistry.getSortedCreativeModeTabs()) { -+ currentPage.add(sortedCreativeModeTab); -+ tabIndex++; -+ if (tabIndex == 10) { -+ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage)); -+ currentPage = new java.util.ArrayList<>(); -+ tabIndex = 0; + public CreativeModeInventoryScreen(Player p_259788_, FeatureFlagSet p_260074_, boolean p_259569_) { + super(new CreativeModeInventoryScreen.ItemPickerMenu(p_259788_), p_259788_.getInventory(), CommonComponents.EMPTY); +@@ -144,7 +_,7 @@ + private void refreshCurrentTabContents(Collection p_261591_) { + int i = this.menu.getRowIndexForScroll(this.scrollOffs); + this.menu.items.clear(); +- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { ++ if (selectedTab.hasSearchBar()) { + this.refreshSearchResults(); + } else { + this.menu.items.addAll(p_261591_); +@@ -307,6 +_,35 @@ + protected void init() { + if (this.minecraft.gameMode.hasInfiniteItems()) { + super.init(); ++ this.pages.clear(); ++ int tabIndex = 0; ++ List currentPage = new java.util.ArrayList<>(); ++ for (CreativeModeTab sortedCreativeModeTab : net.minecraftforge.common.CreativeModeTabRegistry.getSortedCreativeModeTabs()) { ++ currentPage.add(sortedCreativeModeTab); ++ tabIndex++; ++ if (tabIndex == 10) { ++ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage)); ++ currentPage = new java.util.ArrayList<>(); ++ tabIndex = 0; ++ } + } -+ } -+ if (tabIndex != 0) { -+ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage)); -+ } -+ if (this.pages.isEmpty()) { -+ this.currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>()); -+ } else { -+ this.currentPage = this.pages.get(0); -+ } -+ if (this.pages.size() > 1) { -+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> setCurrentPage(this.pages.get(Math.max(this.pages.indexOf(this.currentPage) - 1, 0)))).pos(leftPos, topPos - 50).size(20, 20).build()); -+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> setCurrentPage(this.pages.get(Math.min(this.pages.indexOf(this.currentPage) + 1, this.pages.size() - 1)))).pos(leftPos + imageWidth - 20, topPos - 50).size(20, 20).build()); -+ } -+ this.currentPage = this.pages.stream().filter(page -> page.getVisibleTabs().contains(selectedTab)).findFirst().orElse(this.currentPage); -+ if (!this.currentPage.getVisibleTabs().contains(selectedTab)) { -+ selectedTab = this.currentPage.getVisibleTabs().get(0); -+ } - this.searchBox = new EditBox(this.font, this.leftPos + 82, this.topPos + 6, 80, 9, Component.translatable("itemGroup.search")); - this.searchBox.setMaxLength(50); - this.searchBox.setBordered(false); -@@ -311,7 +_,7 @@ - public boolean charTyped(char p_98521_, int p_98522_) { - if (this.ignoreTextInput) { - return false; -- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { -+ } else if (!selectedTab.hasSearchBar()) { - return false; - } else { - String s = this.searchBox.getValue(); -@@ -329,7 +_,7 @@ ++ if (tabIndex != 0) { ++ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage)); ++ } ++ if (this.pages.isEmpty()) { ++ this.currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>()); ++ } else { ++ this.currentPage = this.pages.get(0); ++ } ++ if (this.pages.size() > 1) { ++ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> setCurrentPage(this.pages.get(Math.max(this.pages.indexOf(this.currentPage) - 1, 0)))).pos(leftPos, topPos - 50).size(20, 20).build()); ++ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> setCurrentPage(this.pages.get(Math.min(this.pages.indexOf(this.currentPage) + 1, this.pages.size() - 1)))).pos(leftPos + imageWidth - 20, topPos - 50).size(20, 20).build()); ++ } ++ this.currentPage = this.pages.stream().filter(page -> page.getVisibleTabs().contains(selectedTab)).findFirst().orElse(this.currentPage); ++ if (!this.currentPage.getVisibleTabs().contains(selectedTab)) { ++ selectedTab = this.currentPage.getVisibleTabs().get(0); ++ } ++ + this.searchBox = new EditBox(this.font, this.leftPos + 82, this.topPos + 6, 80, 9, Component.translatable("itemGroup.search")); + this.searchBox.setMaxLength(50); + this.searchBox.setBordered(false); +@@ -353,7 +_,7 @@ + public boolean charTyped(char p_98521_, int p_98522_) { + if (this.ignoreTextInput) { + return false; +- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { ++ } else if (!selectedTab.hasSearchBar()) { + return false; + } else { + String s = this.searchBox.getValue(); +@@ -372,7 +_,7 @@ + @Override + public boolean keyPressed(int p_98547_, int p_98548_, int p_98549_) { + this.ignoreTextInput = false; +- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { ++ if (!selectedTab.hasSearchBar()) { + if (this.minecraft.options.keyChat.matches(p_98547_, p_98548_)) { + this.ignoreTextInput = true; + this.selectTab(CreativeModeTabs.searchTab()); +@@ -408,6 +_,7 @@ + } - public boolean keyPressed(int p_98547_, int p_98548_, int p_98549_) { - this.ignoreTextInput = false; -- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { -+ if (!selectedTab.hasSearchBar()) { - if (this.minecraft.options.keyChat.matches(p_98547_, p_98548_)) { - this.ignoreTextInput = true; - this.selectTab(CreativeModeTabs.searchTab()); -@@ -364,6 +_,7 @@ - } - - private void refreshSearchResults() { -+ if (!selectedTab.hasSearchBar()) return; - (this.menu).items.clear(); - this.visibleTags.clear(); - String s = this.searchBox.getValue(); -@@ -373,10 +_,10 @@ - SearchTree searchtree; - if (s.startsWith("#")) { - s = s.substring(1); -- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_TAGS); -+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); - this.updateVisibleTags(s); - } else { -- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_NAMES); -+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); - } - - (this.menu).items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT))); -@@ -408,7 +_,8 @@ - - protected void renderLabels(GuiGraphics p_283168_, int p_281774_, int p_281466_) { - if (selectedTab.showTitle()) { -- p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, 4210752, false); -+ com.mojang.blaze3d.systems.RenderSystem.disableBlend(); -+ p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, selectedTab.getLabelColor(), false); - } - - } -@@ -418,7 +_,7 @@ - double d0 = p_98531_ - (double)this.leftPos; - double d1 = p_98532_ - (double)this.topPos; - -- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(creativemodetab, d0, d1)) { - return true; + private void refreshSearchResults() { ++ if (!selectedTab.hasSearchBar()) return; + this.menu.items.clear(); + this.visibleTags.clear(); + String s = this.searchBox.getValue(); +@@ -417,10 +_,10 @@ + SearchTree searchtree; + if (s.startsWith("#")) { + s = s.substring(1); +- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_TAGS); ++ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); + this.updateVisibleTags(s); + } else { +- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_NAMES); ++ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); } -@@ -439,7 +_,7 @@ - double d1 = p_98623_ - (double)this.topPos; - this.scrolling = false; -- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(creativemodetab, d0, d1)) { - this.selectTab(creativemodetab); - return true; -@@ -457,6 +_,7 @@ - private void selectTab(CreativeModeTab p_98561_) { - CreativeModeTab creativemodetab = selectedTab; - selectedTab = p_98561_; -+ slotColor = p_98561_.getSlotColor(); - this.quickCraftSlots.clear(); - (this.menu).items.clear(); - this.clearDraggingState(); -@@ -533,13 +_,15 @@ - this.originalSlots = null; - } + this.menu.items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT))); +@@ -447,7 +_,8 @@ + @Override + protected void renderLabels(GuiGraphics p_283168_, int p_281774_, int p_281466_) { + if (selectedTab.showTitle()) { +- p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, 4210752, false); ++ com.mojang.blaze3d.systems.RenderSystem.disableBlend(); ++ p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, selectedTab.getLabelColor(), false); + } + } -- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { -+ if (selectedTab.hasSearchBar()) { - this.searchBox.setVisible(true); - this.searchBox.setCanLoseFocus(false); - this.searchBox.setFocused(true); - if (creativemodetab != p_98561_) { - this.searchBox.setValue(""); - } -+ this.searchBox.setWidth(selectedTab.getSearchBarWidth()); -+ this.searchBox.setX(this.leftPos + (82 /*default left*/ + 89 /*default width*/) - this.searchBox.getWidth()); +@@ -457,7 +_,7 @@ + double d0 = p_98531_ - (double)this.leftPos; + double d1 = p_98532_ - (double)this.topPos; - this.refreshSearchResults(); - } else { -@@ -595,7 +_,7 @@ - public void render(GuiGraphics p_283000_, int p_281317_, int p_282770_, float p_281295_) { - super.render(p_283000_, p_281317_, p_282770_, p_281295_); +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(creativemodetab, d0, d1)) { + return true; + } +@@ -479,7 +_,7 @@ + double d1 = p_98623_ - (double)this.topPos; + this.scrolling = false; -- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) { - break; - } -@@ -605,13 +_,22 @@ - p_283000_.renderTooltip(this.font, TRASH_SLOT_TOOLTIP, p_281317_, p_282770_); - } +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(creativemodetab, d0, d1)) { + this.selectTab(creativemodetab); + return true; +@@ -497,6 +_,7 @@ + private void selectTab(CreativeModeTab p_98561_) { + CreativeModeTab creativemodetab = selectedTab; + selectedTab = p_98561_; ++ slotColor = p_98561_.getSlotColor(); + this.quickCraftSlots.clear(); + this.menu.items.clear(); + this.clearDraggingState(); +@@ -573,13 +_,15 @@ + this.originalSlots = null; + } -+ if (this.pages.size() != 1) { -+ Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size())); -+ p_283000_.pose().pushPose(); -+ p_283000_.pose().translate(0F, 0F, 300F); -+ p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1); -+ p_283000_.pose().popPose(); -+ } -+ -+ com.mojang.blaze3d.systems.RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); - this.renderTooltip(p_283000_, p_281317_, p_282770_); - } - - public List getTooltipFromContainerItem(ItemStack p_281769_) { - boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot; - boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY; -- boolean flag2 = selectedTab.getType() == CreativeModeTab.Type.SEARCH; -+ boolean flag2 = selectedTab.hasSearchBar(); - TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL; - TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default; - List list = p_281769_.getTooltipLines(this.minecraft.player, tooltipflag); -@@ -631,7 +_,7 @@ - int i = 1; - - for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(p_281769_)) { -+ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(p_281769_)) { - list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); +- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { ++ if (selectedTab.hasSearchBar()) { + this.searchBox.setVisible(true); + this.searchBox.setCanLoseFocus(false); + this.searchBox.setFocused(true); + if (creativemodetab != p_98561_) { + this.searchBox.setValue(""); } - } -@@ -641,13 +_,13 @@ - } ++ this.searchBox.setWidth(selectedTab.getSearchBarWidth()); ++ this.searchBox.setX(this.leftPos + (82 /*default left*/ + 89 /*default width*/) - this.searchBox.getWidth()); - protected void renderBg(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) { -- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (creativemodetab != selectedTab) { - this.renderTabButton(p_282663_, creativemodetab); - } - } + this.refreshSearchResults(); + } else { +@@ -642,7 +_,7 @@ + public void render(GuiGraphics p_283000_, int p_281317_, int p_282770_, float p_281295_) { + super.render(p_283000_, p_281317_, p_282770_, p_281295_); -- p_282663_.blit(new ResourceLocation("textures/gui/container/creative_inventory/tab_" + selectedTab.getBackgroundSuffix()), this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight); -+ p_282663_.blit(selectedTab.getBackgroundLocation(), this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight); - this.searchBox.render(p_282663_, p_282089_, p_282249_, p_282504_); - int j = this.leftPos + 175; - int k = this.topPos + 18; -@@ -657,6 +_,7 @@ - p_282663_.blitSprite(resourcelocation, j, k + (int)((float)(i - k - 17) * this.scrollOffs), 12, 15); - } +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) { + break; + } +@@ -653,7 +_,15 @@ + && this.isHovering(this.destroyItemSlot.x, this.destroyItemSlot.y, 16, 16, (double)p_281317_, (double)p_282770_)) { + p_283000_.renderTooltip(this.font, TRASH_SLOT_TOOLTIP, p_281317_, p_282770_); + } ++ if (this.pages.size() != 1) { ++ Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size())); ++ p_283000_.pose().pushPose(); ++ p_283000_.pose().translate(0F, 0F, 300F); ++ p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1); ++ p_283000_.pose().popPose(); ++ } -+ if (currentPage.getVisibleTabs().contains(selectedTab)) //Forge: only display tab selection when the selected tab is on the current page - this.renderTabButton(p_282663_, selectedTab); - if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) { - InventoryScreen.renderEntityInInventoryFollowsMouse(p_282663_, this.leftPos + 73, this.topPos + 6, this.leftPos + 105, this.topPos + 49, 20, 0.0625F, (float)p_282089_, (float)p_282249_, this.minecraft.player); -@@ -665,7 +_,7 @@ - } ++ com.mojang.blaze3d.systems.RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + this.renderTooltip(p_283000_, p_281317_, p_282770_); + } - private int getTabX(CreativeModeTab p_260136_) { -- int i = p_260136_.column(); -+ int i = currentPage.getColumn(p_260136_); - int j = 27; - int k = 27 * i; - if (p_260136_.isAlignedRight()) { -@@ -677,7 +_,7 @@ +@@ -661,7 +_,7 @@ + public List getTooltipFromContainerItem(ItemStack p_281769_) { + boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot; + boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY; +- boolean flag2 = selectedTab.getType() == CreativeModeTab.Type.SEARCH; ++ boolean flag2 =selectedTab.hasSearchBar(); + TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL; + TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default; + List list = p_281769_.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipflag); +@@ -680,7 +_,7 @@ + int i = 1; - private int getTabY(CreativeModeTab p_260181_) { - int i = 0; -- if (p_260181_.row() == CreativeModeTab.Row.TOP) { -+ if (currentPage.isTop(p_260181_)) { - i -= 32; - } else { - i += this.imageHeight; -@@ -705,8 +_,8 @@ + for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { +- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(p_281769_)) { ++ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(p_281769_)) { + list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); + } + } +@@ -691,14 +_,14 @@ - protected void renderTabButton(GuiGraphics p_283590_, CreativeModeTab p_283489_) { - boolean flag = p_283489_ == selectedTab; -- boolean flag1 = p_283489_.row() == CreativeModeTab.Row.TOP; -- int i = p_283489_.column(); -+ boolean flag1 = currentPage.isTop(p_283489_); -+ int i = currentPage.getColumn(p_283489_); - int j = this.leftPos + this.getTabX(p_283489_); - int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4)); - ResourceLocation[] aresourcelocation; -@@ -716,6 +_,7 @@ - aresourcelocation = flag ? SELECTED_BOTTOM_TABS : UNSELECTED_BOTTOM_TABS; - } + @Override + protected void renderBg(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) { +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (creativemodetab != selectedTab) { + this.renderTabButton(p_282663_, creativemodetab); + } + } -+ com.mojang.blaze3d.systems.RenderSystem.enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border. - p_283590_.blitSprite(aresourcelocation[Mth.clamp(i, 0, aresourcelocation.length)], j, k, 26, 32); - p_283590_.pose().pushPose(); - p_283590_.pose().translate(0.0F, 0.0F, 100.0F); -@@ -759,6 +_,14 @@ + p_282663_.blit( +- new ResourceLocation("textures/gui/container/creative_inventory/tab_" + selectedTab.getBackgroundSuffix()), ++ selectedTab.getBackgroundLocation(), + this.leftPos, + this.topPos, + 0, +@@ -715,6 +_,7 @@ + p_282663_.blitSprite(resourcelocation, j, k + (int)((float)(i - k - 17) * this.scrollOffs), 12, 15); + } - } ++ if (currentPage.getVisibleTabs().contains(selectedTab)) //Forge: only display tab selection when the selected tab is on the current page + this.renderTabButton(p_282663_, selectedTab); + if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) { + InventoryScreen.renderEntityInInventoryFollowsMouse( +@@ -733,7 +_,7 @@ + } -+ public net.minecraftforge.client.gui.CreativeTabsScreenPage getCurrentPage() { -+ return currentPage; -+ } + private int getTabX(CreativeModeTab p_260136_) { +- int i = p_260136_.column(); ++ int i = currentPage.getColumn(p_260136_); + int j = 27; + int k = 27 * i; + if (p_260136_.isAlignedRight()) { +@@ -745,7 +_,7 @@ + + private int getTabY(CreativeModeTab p_260181_) { + int i = 0; +- if (p_260181_.row() == CreativeModeTab.Row.TOP) { ++ if (currentPage.isTop(p_260181_)) { + i -= 32; + } else { + i += this.imageHeight; +@@ -773,8 +_,8 @@ + + protected void renderTabButton(GuiGraphics p_283590_, CreativeModeTab p_283489_) { + boolean flag = p_283489_ == selectedTab; +- boolean flag1 = p_283489_.row() == CreativeModeTab.Row.TOP; +- int i = p_283489_.column(); ++ boolean flag1 = currentPage.isTop(p_283489_); ++ int i = currentPage.getColumn(p_283489_); + int j = this.leftPos + this.getTabX(p_283489_); + int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4)); + ResourceLocation[] aresourcelocation; +@@ -784,6 +_,7 @@ + aresourcelocation = flag ? SELECTED_BOTTOM_TABS : UNSELECTED_BOTTOM_TABS; + } + ++ com.mojang.blaze3d.systems.RenderSystem.enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border. + p_283590_.blitSprite(aresourcelocation[Mth.clamp(i, 0, aresourcelocation.length)], j, k, 26, 32); + p_283590_.pose().pushPose(); + p_283590_.pose().translate(0.0F, 0.0F, 100.0F); +@@ -825,6 +_,14 @@ + } + } + ++ public net.minecraftforge.client.gui.CreativeTabsScreenPage getCurrentPage() { ++ return currentPage; ++ } + -+ public void setCurrentPage(net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage) { -+ this.currentPage = currentPage; -+ } ++ public void setCurrentPage(net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage) { ++ this.currentPage = currentPage; ++ } + - @OnlyIn(Dist.CLIENT) - static class CustomCreativeSlot extends Slot { - public CustomCreativeSlot(Container p_98633_, int p_98634_, int p_98635_, int p_98636_) { -@@ -926,6 +_,22 @@ - - public boolean mayPickup(Player p_98665_) { - return this.target.mayPickup(p_98665_); -+ } + @OnlyIn(Dist.CLIENT) + static class CustomCreativeSlot extends Slot { + public CustomCreativeSlot(Container p_98633_, int p_98634_, int p_98635_, int p_98636_) { +@@ -1009,6 +_,22 @@ + @Override + public boolean mayPickup(Player p_98665_) { + return this.target.mayPickup(p_98665_); ++ } + -+ @Override -+ public int getSlotIndex() { -+ return this.target.getSlotIndex(); -+ } ++ @Override ++ public int getSlotIndex() { ++ return this.target.getSlotIndex(); ++ } + -+ @Override -+ public boolean isSameInventory(Slot other) { -+ return this.target.isSameInventory(other); -+ } ++ @Override ++ public boolean isSameInventory(Slot other) { ++ return this.target.isSameInventory(other); ++ } + -+ @Override -+ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) { -+ this.target.setBackground(atlas, sprite); -+ return this; - } - } ++ @Override ++ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) { ++ this.target.setBackground(atlas, sprite); ++ return this; + } + } } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java.patch index 17625f1336..c7c8d832b6 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java.patch @@ -1,45 +1,44 @@ --- a/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java +++ b/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java -@@ -45,12 +_,17 @@ - Collection collection = this.minecraft.player.getActiveEffects(); - if (!collection.isEmpty() && j >= 32) { - boolean flag = j >= 120; -+ var event = net.minecraftforge.client.ForgeHooksClient.onScreenPotionSize(this, j, !flag, i); -+ if (event.isCanceled()) return; -+ flag = !event.isCompact(); -+ i = event.getHorizontalOffset(); - int k = 33; - if (collection.size() > 5) { - k = 132 / (collection.size() - 1); - } +@@ -47,12 +_,16 @@ + Collection collection = this.minecraft.player.getActiveEffects(); + if (!collection.isEmpty() && j >= 32) { + boolean flag = j >= 120; ++ var event = net.minecraftforge.client.ForgeHooksClient.onScreenPotionSize(this, j, !flag, i); ++ if (event.isCanceled()) return; ++ flag = !event.isCompact(); ++ i = event.getHorizontalOffset(); + int k = 33; + if (collection.size() > 5) { + k = 132 / (collection.size() - 1); + } -- Iterable iterable = Ordering.natural().sortedCopy(collection); -+ -+ Iterable iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().collect(java.util.stream.Collectors.toList()); - this.renderBackgrounds(p_281945_, i, k, iterable, flag); - this.renderIcons(p_281945_, i, k, iterable, flag); - if (flag) { -@@ -96,6 +_,11 @@ - int i = this.topPos; +- Iterable iterable = Ordering.natural().sortedCopy(collection); ++ Iterable iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList(); + this.renderBackgrounds(p_281945_, i, k, iterable, flag); + this.renderIcons(p_281945_, i, k, iterable, flag); + if (flag) { +@@ -98,6 +_,11 @@ + int i = this.topPos; - for(MobEffectInstance mobeffectinstance : p_282642_) { -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); -+ if (renderer.renderInventoryIcon(mobeffectinstance, this, p_282745_, p_282521_ + (p_281536_ ? 6 : 7), i, 0)) { -+ i += p_282291_; -+ continue; -+ } - MobEffect mobeffect = mobeffectinstance.getEffect(); - TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(mobeffect); - p_282745_.blit(p_282521_ + (p_281536_ ? 6 : 7), i + 7, 0, 18, 18, textureatlassprite); -@@ -108,6 +_,11 @@ - int i = this.topPos; + for (MobEffectInstance mobeffectinstance : p_282642_) { ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); ++ if (renderer.renderInventoryIcon(mobeffectinstance, this, p_282745_, p_282521_ + (p_281536_ ? 6 : 7), i, 0)) { ++ i += p_282291_; ++ continue; ++ } + Holder holder = mobeffectinstance.getEffect(); + TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(holder); + p_282745_.blit(p_282521_ + (p_281536_ ? 6 : 7), i + 7, 0, 18, 18, textureatlassprite); +@@ -109,6 +_,11 @@ + int i = this.topPos; - for(MobEffectInstance mobeffectinstance : p_281986_) { -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); -+ if (renderer.renderInventoryText(mobeffectinstance, this, p_281462_, p_283484_, i, 0)) { -+ i += p_282057_; -+ continue; -+ } - Component component = this.getEffectName(mobeffectinstance); - p_281462_.drawString(this.font, component, p_283484_ + 10 + 18, i + 6, 16777215); - Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate()); + for (MobEffectInstance mobeffectinstance : p_281986_) { ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); ++ if (renderer.renderInventoryText(mobeffectinstance, this, p_281462_, p_283484_, i, 0)) { ++ i += p_282057_; ++ continue; ++ } + Component component = this.getEffectName(mobeffectinstance); + p_281462_.drawString(this.font, component, p_283484_ + 10 + 18, i + 6, 16777215); + Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate()); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch index 2310764408..cb6aeac75f 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java +++ b/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java -@@ -93,7 +_,7 @@ - int l1 = 86 - this.font.width(s); - FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1); - int i2 = 6839882; -- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) { -+ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels - p_282430_.blitSprite(ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19); - p_282430_.blitSprite(DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16); - p_282430_.drawWordWrap(this.font, formattedtext, j1, j + 16 + 19 * l, l1, (i2 & 16711422) >> 1); -@@ -154,10 +_,13 @@ - Enchantment enchantment = Enchantment.byId((this.menu).enchantClue[j]); - int l = (this.menu).levelClue[j]; - int i1 = j + 1; -- if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0 && l >= 0 && enchantment != null) { -+ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0) { - List list = Lists.newArrayList(); -- list.add(Component.translatable("container.enchant.clue", enchantment.getFullname(l)).withStyle(ChatFormatting.WHITE)); -- if (!flag) { -+ list.add((Component.translatable("container.enchant.clue", enchantment == null ? "" : enchantment.getFullname(l))).withStyle(ChatFormatting.WHITE)); -+ if (enchantment == null) { -+ list.add(Component.literal("")); -+ list.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED)); -+ } else if (!flag) { - list.add(CommonComponents.EMPTY); - if (this.minecraft.player.experienceLevel < k) { - list.add(Component.translatable("container.enchant.level.requirement", (this.menu).costs[j]).withStyle(ChatFormatting.RED)); +@@ -108,7 +_,7 @@ + int l1 = 86 - this.font.width(s); + FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1); + int i2 = 6839882; +- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) { ++ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{ + RenderSystem.enableBlend(); + p_282430_.blitSprite(ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19); + p_282430_.blitSprite(DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16); +@@ -173,10 +_,13 @@ + Enchantment enchantment = Enchantment.byId(this.menu.enchantClue[j]); + int l = this.menu.levelClue[j]; + int i1 = j + 1; +- if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0 && l >= 0 && enchantment != null) { ++ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0) { + List list = Lists.newArrayList(); +- list.add(Component.translatable("container.enchant.clue", enchantment.getFullname(l)).withStyle(ChatFormatting.WHITE)); +- if (!flag) { ++ list.add((Component.translatable("container.enchant.clue", enchantment == null ? "" : enchantment.getFullname(l))).withStyle(ChatFormatting.WHITE)); ++ if (enchantment == null) { ++ list.add(Component.literal("")); ++ list.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED)); ++ } else if (!flag) { + list.add(CommonComponents.EMPTY); + if (this.minecraft.player.experienceLevel < k) { + list.add(Component.translatable("container.enchant.level.requirement", this.menu.costs[j]).withStyle(ChatFormatting.RED)); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java.patch index b2da8c7254..75ccd25a87 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java +++ b/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java @@ -15,7 +_,7 @@ - private static final Vector3f TEXT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F); - private static final int TEXTURE_WIDTH = 16; - private static final int TEXTURE_HEIGHT = 16; -- private final ResourceLocation texture = new ResourceLocation("textures/gui/hanging_signs/" + this.woodType.name() + ".png"); -+ private final ResourceLocation texture = new ResourceLocation(this.woodType.name() + ".png").withPrefix("textures/gui/hanging_signs/"); + private static final Vector3f TEXT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F); + private static final int TEXTURE_WIDTH = 16; + private static final int TEXTURE_HEIGHT = 16; +- private final ResourceLocation texture = new ResourceLocation("textures/gui/hanging_signs/" + this.woodType.name() + ".png"); ++ private final ResourceLocation texture = new ResourceLocation(this.woodType.name() + ".png").withPrefix("textures/gui/hanging_signs/"); // possibly unnecessary patch(?) -Paint_Ninja - public HangingSignEditScreen(SignBlockEntity p_278017_, boolean p_277942_, boolean p_277778_) { - super(p_278017_, p_277942_, p_277778_, Component.translatable("hanging_sign.edit")); + public HangingSignEditScreen(SignBlockEntity p_278017_, boolean p_277942_, boolean p_277778_) { + super(p_278017_, p_277942_, p_277778_, Component.translatable("hanging_sign.edit")); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/MerchantScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/MerchantScreen.java.patch index 3e44b2f0fa..551b637c82 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/MerchantScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/MerchantScreen.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/client/gui/screens/inventory/MerchantScreen.java +++ b/net/minecraft/client/gui/screens/inventory/MerchantScreen.java -@@ -236,7 +_,12 @@ - p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_, p_283601_); - } else { - p_281357_.renderItemDecorations(this.font, p_282046_, p_282403_, p_283601_, p_282046_.getCount() == 1 ? "1" : null); -- p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_ + 14, p_283601_, p_283466_.getCount() == 1 ? "1" : null); -+ // Forge: fixes Forge-8806, code for count rendering taken from GuiGraphics#renderGuiItemDecorations -+ p_281357_.pose().pushPose(); -+ p_281357_.pose().translate(0.0F, 0.0F, 200.0F); -+ String count = p_283466_.getCount() == 1 ? "1" : String.valueOf(p_283466_.getCount()); -+ font.drawInBatch(count, (float) (p_282403_ + 14) + 19 - 2 - font.width(count), (float)p_283601_ + 6 + 3, 0xFFFFFF, true, p_281357_.pose().last().pose(), p_281357_.bufferSource(), net.minecraft.client.gui.Font.DisplayMode.NORMAL, 0, 15728880, false); -+ p_281357_.pose().popPose(); - p_281357_.pose().pushPose(); - p_281357_.pose().translate(0.0F, 0.0F, 300.0F); - p_281357_.blitSprite(DISCOUNT_STRIKETHRUOGH_SPRITE, p_282403_ + 7, p_283601_ + 12, 0, 9, 2); +@@ -234,7 +_,12 @@ + p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_, p_283601_); + } else { + p_281357_.renderItemDecorations(this.font, p_282046_, p_282403_, p_283601_, p_282046_.getCount() == 1 ? "1" : null); +- p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_ + 14, p_283601_, p_283466_.getCount() == 1 ? "1" : null); ++ // Forge: fixes Forge-8806, code for count rendering taken from GuiGraphics#renderGuiItemDecorations ++ p_281357_.pose().pushPose(); ++ p_281357_.pose().translate(0.0F, 0.0F, 200.0F); ++ String count = p_283466_.getCount() == 1 ? "1" : String.valueOf(p_283466_.getCount()); ++ font.drawInBatch(count, (float) (p_282403_ + 14) + 19 - 2 - font.width(count), (float)p_283601_ + 6 + 3, 0xFFFFFF, true, p_281357_.pose().last().pose(), p_281357_.bufferSource(), net.minecraft.client.gui.Font.DisplayMode.NORMAL, 0, 15728880, false); ++ p_281357_.pose().popPose(); + p_281357_.pose().pushPose(); + p_281357_.pose().translate(0.0F, 0.0F, 300.0F); + p_281357_.blitSprite(DISCOUNT_STRIKETHRUOGH_SPRITE, p_282403_ + 7, p_283601_ + 12, 0, 9, 2); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch index 7ba003737e..6df9e74b6c 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java +++ b/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java @@ -20,6 +_,8 @@ - if (p_169951_ instanceof BundleTooltip) { - return new ClientBundleTooltip((BundleTooltip)p_169951_); - } else { -+ ClientTooltipComponent result = net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(p_169951_); -+ if (result != null) return result; - throw new IllegalArgumentException("Unknown TooltipComponent"); - } - } + if (p_169951_ instanceof BundleTooltip bundletooltip) { + return new ClientBundleTooltip(bundletooltip.contents()); + } else { ++ ClientTooltipComponent result = net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(p_169951_); ++ if (result != null) return result; + throw new IllegalArgumentException("Unknown TooltipComponent"); + } + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java.patch index 27e7ae25c0..647a25f15c 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java.patch @@ -1,49 +1,40 @@ --- a/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java +++ b/net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.java -@@ -17,16 +_,22 @@ - private static final int BORDER_COLOR_BOTTOM = 1344798847; +@@ -17,16 +_,21 @@ + private static final int BORDER_COLOR_BOTTOM = 1344798847; - public static void renderTooltipBackground(GuiGraphics p_282666_, int p_281901_, int p_281846_, int p_281559_, int p_283336_, int p_283422_) { -+ renderTooltipBackground(p_282666_, p_281901_, p_281846_, p_281559_, p_283336_, p_283422_, BACKGROUND_COLOR, BACKGROUND_COLOR, BORDER_COLOR_TOP, BORDER_COLOR_BOTTOM); -+ } + public static void renderTooltipBackground(GuiGraphics p_282666_, int p_281901_, int p_281846_, int p_281559_, int p_283336_, int p_283422_) { ++ renderTooltipBackground(p_282666_, p_281901_, p_281846_, p_281559_, p_283336_, p_283422_, BACKGROUND_COLOR, BACKGROUND_COLOR, BORDER_COLOR_TOP, BORDER_COLOR_BOTTOM); ++ } + -+ // Forge: Allow specifying colors for the inner border gradient and a gradient instead of a single color for the background and outer border -+ public static void renderTooltipBackground(GuiGraphics p_282666_, int p_281901_, int p_281846_, int p_281559_, int p_283336_, int p_283422_, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) -+ { - int i = p_281901_ - 3; - int j = p_281846_ - 3; - int k = p_281559_ + 3 + 3; - int l = p_283336_ + 3 + 3; -- renderHorizontalLine(p_282666_, i, j - 1, k, p_283422_, -267386864); -- renderHorizontalLine(p_282666_, i, j + l, k, p_283422_, -267386864); -- renderRectangle(p_282666_, i, j, k, l, p_283422_, -267386864); -- renderVerticalLine(p_282666_, i - 1, j, l, p_283422_, -267386864); -- renderVerticalLine(p_282666_, i + k, j, l, p_283422_, -267386864); -- renderFrameGradient(p_282666_, i, j + 1, k, l, p_283422_, 1347420415, 1344798847); -+ renderHorizontalLine(p_282666_, i, j - 1, k, p_283422_, backgroundTop); -+ renderHorizontalLine(p_282666_, i, j + l, k, p_283422_, backgroundBottom); -+ renderRectangle(p_282666_, i, j, k, l, p_283422_, backgroundTop, backgroundBottom); -+ renderVerticalLineGradient(p_282666_, i - 1, j, l, p_283422_, backgroundTop, backgroundBottom); -+ renderVerticalLineGradient(p_282666_, i + k, j, l, p_283422_, backgroundTop, backgroundBottom); -+ renderFrameGradient(p_282666_, i, j + 1, k, l, p_283422_, borderTop, borderBottom); - } ++ // Forge: Allow specifying colors for the inner border gradient and a gradient instead of a single color for the background and outer border ++ public static void renderTooltipBackground(GuiGraphics p_282666_, int p_281901_, int p_281846_, int p_281559_, int p_283336_, int p_283422_, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + int i = p_281901_ - 3; + int j = p_281846_ - 3; + int k = p_281559_ + 3 + 3; + int l = p_283336_ + 3 + 3; +- renderHorizontalLine(p_282666_, i, j - 1, k, p_283422_, -267386864); +- renderHorizontalLine(p_282666_, i, j + l, k, p_283422_, -267386864); +- renderRectangle(p_282666_, i, j, k, l, p_283422_, -267386864); +- renderVerticalLine(p_282666_, i - 1, j, l, p_283422_, -267386864); +- renderVerticalLine(p_282666_, i + k, j, l, p_283422_, -267386864); +- renderFrameGradient(p_282666_, i, j + 1, k, l, p_283422_, 1347420415, 1344798847); ++ renderHorizontalLine(p_282666_, i, j - 1, k, p_283422_, backgroundTop); ++ renderHorizontalLine(p_282666_, i, j + l, k, p_283422_, backgroundBottom); ++ renderRectangleGradient(p_282666_, i, j, k, l, p_283422_, backgroundTop, backgroundBottom); ++ renderVerticalLineGradient(p_282666_, i - 1, j, l, p_283422_, backgroundTop, backgroundBottom); ++ renderVerticalLineGradient(p_282666_, i + k, j, l, p_283422_, backgroundTop, backgroundBottom); ++ renderFrameGradient(p_282666_, i, j + 1, k, l, p_283422_, borderTop, borderBottom); + } - private static void renderFrameGradient(GuiGraphics p_282000_, int p_282055_, int p_281580_, int p_283284_, int p_282599_, int p_283432_, int p_282907_, int p_283153_) { -@@ -48,7 +_,16 @@ - p_282981_.fill(p_282028_, p_282141_, p_282028_ + p_281771_, p_282141_ + 1, p_282734_, p_281979_); - } + private static void renderFrameGradient( +@@ -52,5 +_,9 @@ -+ /** -+ * @deprecated Forge: Use gradient overload instead -+ */ -+ @Deprecated - private static void renderRectangle(GuiGraphics p_281392_, int p_282294_, int p_283353_, int p_282640_, int p_281964_, int p_283211_, int p_282349_) { -- p_281392_.fill(p_282294_, p_283353_, p_282294_ + p_282640_, p_283353_ + p_281964_, p_283211_, p_282349_); -+ renderRectangle(p_281392_, p_282294_, p_283353_, p_282640_, p_281964_, p_283211_, p_282349_, p_282349_); -+ } + private static void renderRectangle(GuiGraphics p_281392_, int p_282294_, int p_283353_, int p_282640_, int p_281964_, int p_283211_, int p_282349_) { + p_281392_.fill(p_282294_, p_283353_, p_282294_ + p_282640_, p_283353_ + p_281964_, p_283211_, p_282349_); ++ } + -+ // Forge: Allow specifying a gradient instead of a single color for the background -+ private static void renderRectangle(GuiGraphics p_281392_, int p_282294_, int p_283353_, int p_282640_, int p_281964_, int p_283211_, int p_282349_, int colorTo) { -+ p_281392_.fillGradient(p_282294_, p_283353_, p_282294_ + p_282640_, p_283353_ + p_281964_, p_283211_, p_282349_, colorTo); - } ++ private static void renderRectangleGradient(GuiGraphics p_281392_, int p_282294_, int p_283353_, int p_282640_, int p_281964_, int p_283211_, int p_282349_, int colorTo) { ++ p_281392_.fillGradient(p_282294_, p_283353_, p_282294_ + p_282640_, p_283353_ + p_281964_, p_283211_, p_282349_, colorTo); + } } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/JoinMultiplayerScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/JoinMultiplayerScreen.java.patch deleted file mode 100644 index 16368a93f0..0000000000 --- a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/JoinMultiplayerScreen.java.patch +++ /dev/null @@ -1,14 +0,0 @@ ---- a/net/minecraft/client/gui/screens/multiplayer/JoinMultiplayerScreen.java -+++ b/net/minecraft/client/gui/screens/multiplayer/JoinMultiplayerScreen.java -@@ -281,6 +_,11 @@ - - } - -+ @Override -+ public void onClose() { -+ this.minecraft.setScreen(this.lastScreen); -+ } -+ - public ServerStatusPinger getPinger() { - return this.pinger; - } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch index 44323c868f..54a177cf52 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java +++ b/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java -@@ -342,6 +_,8 @@ - this.screen.setToolTip(list1); - } +@@ -372,6 +_,8 @@ + this.screen.setTooltipForNextRenderPass(Lists.transform(this.onlinePlayersTooltip, Component::getVisualOrderText)); + } -+ net.minecraftforge.client.ForgeHooksClient.drawForgePingInfo(this.screen, serverData, p_281406_, p_281363_, p_282921_, p_283596_, l, i1); ++ net.minecraftforge.client.ForgeHooksClient.drawForgePingInfo(this.screen, serverData, p_281406_, p_281363_, p_282921_, p_283596_, p_283567_ - p_281363_, p_282864_ - p_282921_); + - if (this.minecraft.options.touchscreen().get() || p_282999_) { - p_281406_.fill(p_281363_, p_282921_, p_281363_ + 32, p_282921_ + 32, -1601138544); - int j1 = p_283567_ - p_281363_; + if (this.minecraft.options.touchscreen().get() || p_282999_) { + p_281406_.fill(p_281363_, p_282921_, p_281363_ + 32, p_282921_ + 32, -1601138544); + int l = p_283567_ - p_281363_; diff --git a/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionModel.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionModel.java.patch index c63246ce22..48508ec11a 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionModel.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionModel.java.patch @@ -1,23 +1,25 @@ --- a/net/minecraft/client/gui/screens/packs/PackSelectionModel.java +++ b/net/minecraft/client/gui/screens/packs/PackSelectionModel.java -@@ -110,6 +_,8 @@ - boolean canMoveUp(); +@@ -106,6 +_,10 @@ + boolean canMoveUp(); - boolean canMoveDown(); + boolean canMoveDown(); + -+ default boolean notHidden() { return true; } - } ++ default boolean notHidden() { ++ return true; ++ } + } - @OnlyIn(Dist.CLIENT) -@@ -198,6 +_,11 @@ - - public void moveDown() { - this.move(1); -+ } + @OnlyIn(Dist.CLIENT) +@@ -205,6 +_,11 @@ + @Override + public void moveDown() { + this.move(1); ++ } + -+ @Override -+ public boolean notHidden() { -+ return !pack.isHidden(); - } - } ++ @Override ++ public boolean notHidden() { ++ return !this.pack.isHidden(); + } + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java.patch index 9fc9cfe631..8eb61408a9 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java +++ b/net/minecraft/client/gui/screens/packs/PackSelectionScreen.java -@@ -136,7 +_,7 @@ - TransferableSelectionList.PackEntry transferableselectionlist$packentry = p_100014_.getSelected(); - String s = transferableselectionlist$packentry == null ? "" : transferableselectionlist$packentry.getPackId(); - p_100014_.setSelected((TransferableSelectionList.PackEntry)null); -- p_100015_.forEach((p_308207_) -> { -+ p_100015_.filter(PackSelectionModel.Entry::notHidden).forEach((p_308207_) -> { - TransferableSelectionList.PackEntry transferableselectionlist$packentry1 = new TransferableSelectionList.PackEntry(this.minecraft, p_100014_, p_308207_); - p_100014_.children().add(transferableselectionlist$packentry1); - if (p_308207_.getId().equals(s)) { +@@ -159,7 +_,7 @@ + TransferableSelectionList.PackEntry transferableselectionlist$packentry = p_100014_.getSelected(); + String s = transferableselectionlist$packentry == null ? "" : transferableselectionlist$packentry.getPackId(); + p_100014_.setSelected(null); +- p_100015_.forEach( ++ p_100015_.filter(PackSelectionModel.Entry::notHidden).forEach( + p_325390_ -> { + TransferableSelectionList.PackEntry transferableselectionlist$packentry1 = new TransferableSelectionList.PackEntry( + this.minecraft, p_100014_, p_325390_ diff --git a/patches/minecraft/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java.patch index 2bec5f81c6..2a0e291b60 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java +++ b/net/minecraft/client/gui/screens/recipebook/RecipeBookComponent.java -@@ -107,7 +_,7 @@ - this.initFilterButtonTextures(); - this.tabButtons.clear(); +@@ -116,7 +_,7 @@ + this.initFilterButtonTextures(); + this.tabButtons.clear(); -- for(RecipeBookCategories recipebookcategories : RecipeBookCategories.getCategories(this.menu.getRecipeBookType())) { -+ for(RecipeBookCategories recipebookcategories : this.menu.getRecipeBookCategories()) { - this.tabButtons.add(new RecipeBookTabButton(recipebookcategories)); - } +- for (RecipeBookCategories recipebookcategories : RecipeBookCategories.getCategories(this.menu.getRecipeBookType())) { ++ for (RecipeBookCategories recipebookcategories : this.menu.getRecipeBookCategories()) { + this.tabButtons.add(new RecipeBookTabButton(recipebookcategories)); + } -@@ -296,7 +_,7 @@ - } +@@ -291,7 +_,7 @@ + } - if (itemstack != null && this.minecraft.screen != null) { -- p_282776_.renderComponentTooltip(this.minecraft.font, Screen.getTooltipFromItem(this.minecraft, itemstack), p_282948_, p_283050_); -+ p_282776_.renderComponentTooltip(this.minecraft.font, Screen.getTooltipFromItem(this.minecraft, itemstack), p_282948_, p_283050_, itemstack); - } + if (itemstack != null && this.minecraft.screen != null) { +- p_282776_.renderComponentTooltip(this.minecraft.font, Screen.getTooltipFromItem(this.minecraft, itemstack), p_282948_, p_283050_); ++ p_282776_.renderComponentTooltip(this.minecraft.font, Screen.getTooltipFromItem(this.minecraft, itemstack), p_282948_, p_283050_, itemstack); + } + } - } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch index 36e988ffbe..da15366dc6 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch @@ -1,27 +1,27 @@ --- a/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java +++ b/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java -@@ -121,6 +_,7 @@ - public static void openFresh(Minecraft p_232897_, @Nullable Screen p_232898_) { - queueLoadScreen(p_232897_, PREPARING_WORLD_DATA); - PackRepository packrepository = new PackRepository(new ServerPacksSource(p_232897_.directoryValidator())); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.event.AddPackFindersEvent(net.minecraft.server.packs.PackType.SERVER_DATA, packrepository::addPackFinder)); - WorldLoader.InitConfig worldloader$initconfig = createDefaultLoadConfig(packrepository, WorldDataConfiguration.DEFAULT); - CompletableFuture completablefuture = WorldLoader.load(worldloader$initconfig, (p_247792_) -> { - return new WorldLoader.DataLoadOutput<>(new CreateWorldScreen.DataPackReloadCookie(new WorldGenSettings(WorldOptions.defaultWithRandomSeed(), WorldPresets.createNormalWorldDimensions(p_247792_.datapackWorldgen())), p_247792_.dataConfiguration()), p_247792_.datapackDimensions()); -@@ -364,7 +_,7 @@ - if (p_269627_) { - p_270552_.accept(this.uiState.getSettings().dataConfiguration()); - } else { -- p_270552_.accept(WorldDataConfiguration.DEFAULT); -+ p_270552_.accept(new WorldDataConfiguration(new DataPackConfig(ImmutableList.of("vanilla"), ImmutableList.of()), FeatureFlags.DEFAULT_FLAGS)); // FORGE: Revert to *actual* vanilla data - } - - }, Component.translatable("dataPack.validation.failed"), CommonComponents.EMPTY, Component.translatable("dataPack.validation.back"), Component.translatable("dataPack.validation.reset"))); -@@ -478,6 +_,7 @@ - if (path != null) { - if (this.tempDataPackRepository == null) { - this.tempDataPackRepository = ServerPacksSource.createPackRepository(path, this.packValidator); -+ net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(this.tempDataPackRepository, false); - this.tempDataPackRepository.reload(); - } +@@ -119,6 +_,7 @@ + public static void openFresh(Minecraft p_232897_, @Nullable Screen p_232898_) { + queueLoadScreen(p_232897_, PREPARING_WORLD_DATA); + PackRepository packrepository = new PackRepository(new ServerPacksSource(p_232897_.directoryValidator())); ++ net.minecraftforge.event.ForgeEventFactory.addPackFindersServer(packrepository::addPackFinder); + WorldLoader.InitConfig worldloader$initconfig = createDefaultLoadConfig(packrepository, WorldDataConfiguration.DEFAULT); + CompletableFuture completablefuture = WorldLoader.load( + worldloader$initconfig, +@@ -419,7 +_,7 @@ + if (p_269627_) { + p_270552_.accept(this.uiState.getSettings().dataConfiguration()); + } else { +- p_270552_.accept(WorldDataConfiguration.DEFAULT); ++ p_270552_.accept(new WorldDataConfiguration(new DataPackConfig(ImmutableList.of("vanilla"), ImmutableList.of()), FeatureFlags.DEFAULT_FLAGS)); // FORGE: Revert to *actual* vanilla data + } + }, + Component.translatable("dataPack.validation.failed"), +@@ -537,6 +_,7 @@ + if (path != null) { + if (this.tempDataPackRepository == null) { + this.tempDataPackRepository = ServerPacksSource.createPackRepository(path, this.packValidator); ++ net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(this.tempDataPackRepository, false); + this.tempDataPackRepository.reload(); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch index 99720ea42b..fe2dd36152 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/gui/screens/worldselection/PresetEditor.java +++ b/net/minecraft/client/gui/screens/worldselection/PresetEditor.java -@@ -28,6 +_,10 @@ +@@ -29,6 +_,10 @@ @OnlyIn(Dist.CLIENT) public interface PresetEditor { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.client.PresetEditorManager#get(ResourceKey)} instead. -+ */ -+ @Deprecated - Map>, PresetEditor> EDITORS = Map.of(Optional.of(WorldPresets.FLAT), (p_232974_, p_232975_) -> { - ChunkGenerator chunkgenerator = p_232975_.selectedDimensions().overworld(); - RegistryAccess registryaccess = p_232975_.worldgenLoadContext(); ++ /** ++ * @deprecated Forge: Use {@link net.minecraftforge.client.PresetEditorManager#get(ResourceKey)} instead. ++ */ ++ @Deprecated + Map>, PresetEditor> EDITORS = Map.of( + Optional.of(WorldPresets.FLAT), + (p_232974_, p_232975_) -> { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java.patch index 0f6f66edf8..758bc0a72d 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldCreationContext.java -@@ -38,6 +_,10 @@ - return new WorldCreationContext(this.options, this.datapackDimensions, p_250676_.apply(this.worldgenLoadContext(), this.selectedDimensions), this.worldgenRegistries, this.dataPackResources, this.dataConfiguration); - } +@@ -62,6 +_,10 @@ + ); + } -+ public WorldCreationContext withDataConfiguration(WorldDataConfiguration dataConfiguration) { -+ return new WorldCreationContext(this.options, this.datapackDimensions, this.selectedDimensions, this.worldgenRegistries, this.dataPackResources, dataConfiguration); -+ } ++ public WorldCreationContext withDataConfiguration(WorldDataConfiguration dataConfiguration) { ++ return new WorldCreationContext(this.options, this.datapackDimensions, this.selectedDimensions, this.worldgenRegistries, this.dataPackResources, dataConfiguration); ++ } + - public RegistryAccess.Frozen worldgenLoadContext() { - return this.worldgenRegistries.compositeAccess(); - } + public RegistryAccess.Frozen worldgenLoadContext() { + return this.worldgenRegistries.compositeAccess(); + } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch index 40161f4a70..bd4f8b3e64 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java -@@ -226,7 +_,7 @@ - @Nullable - public PresetEditor getPresetEditor() { - Holder holder = this.getWorldType().preset(); -- return holder != null ? PresetEditor.EDITORS.get(holder.unwrapKey()) : null; -+ return holder != null ? holder.unwrapKey().map(net.minecraftforge.client.PresetEditorManager::get).orElse(null) : null; // FORGE: redirect lookup to expanded map - } +@@ -225,7 +_,7 @@ + @Nullable + public PresetEditor getPresetEditor() { + Holder holder = this.getWorldType().preset(); +- return holder != null ? PresetEditor.EDITORS.get(holder.unwrapKey()) : null; ++ return holder != null ? holder.unwrapKey().map(net.minecraftforge.client.PresetEditorManager::get).orElse(null) : null; // FORGE: redirect lookup to expanded map + } - public List getNormalPresetList() { + public List getNormalPresetList() { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch index f5772bf7f7..f51edab783 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch @@ -1,47 +1,11 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java -@@ -280,12 +_,19 @@ - } +@@ -321,6 +_,8 @@ + this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("selectWorld.resource_load"))); + PackRepository packrepository = ServerPacksSource.createPackRepository(p_333651_); - private void loadLevel(LevelStorageSource.LevelStorageAccess p_309733_, Dynamic p_312455_, boolean p_310657_, boolean p_309504_, Runnable p_309915_) { -+ loadLevel(p_309733_, p_312455_, p_310657_, p_309504_, p_309915_, false); -+ } ++ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(p_333651_, p_333651_.getLevelDirectory()); + -+ private void loadLevel(LevelStorageSource.LevelStorageAccess p_309733_, Dynamic p_312455_, boolean p_310657_, boolean p_309504_, Runnable p_309915_, boolean confirmExperimentalWarning) { - this.minecraft.forceSetScreen(new GenericDirtMessageScreen(Component.translatable("selectWorld.resource_load"))); - PackRepository packrepository = ServerPacksSource.createPackRepository(p_309733_); - -+ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(p_309733_, p_309733_.getLevelDirectory()); -+ - WorldStem worldstem; - try { - worldstem = this.loadWorldStem(p_312455_, p_310657_, packrepository); -+ if (confirmExperimentalWarning && worldstem.worldData() instanceof PrimaryLevelData pld) pld.withConfirmedWarning(true); - } catch (Exception exception) { - LOGGER.warn("Failed to load level data or datapacks, can't proceed with server load", (Throwable)exception); - if (!p_310657_) { -@@ -305,7 +_,8 @@ - - WorldData worlddata = worldstem.worldData(); - boolean flag = worlddata.worldGenOptions().isOldCustomizedWorld(); -- boolean flag1 = worlddata.worldGenSettingsLifecycle() != Lifecycle.stable(); -+ boolean skipConfirmation = worlddata instanceof PrimaryLevelData pld && pld.hasConfirmedExperimentalWarning(); -+ boolean flag1 = worlddata.worldGenSettingsLifecycle() != Lifecycle.stable() && !skipConfirmation; - if (!p_309504_ || !flag && !flag1) { - DownloadedPackSource downloadedpacksource = this.minecraft.getDownloadedPackSource(); - this.loadBundledResourcePack(downloadedpacksource, p_309733_).thenApply((p_233177_) -> { -@@ -328,12 +_,14 @@ - return null; - }); - } else { -+ if (flag) // Forge: For legacy world options, let vanilla handle it. - this.askForBackup(p_309733_, flag, () -> { - this.loadLevel(p_309733_, p_312455_, p_310657_, false, p_309915_); - }, () -> { - p_309733_.safeClose(); - p_309915_.run(); - }); -+ else net.minecraftforge.client.ForgeHooksClient.createWorldConfirmationScreen(() -> this.loadLevel(p_309733_, p_312455_, p_310657_, false, p_309915_, true)); - worldstem.close(); - } - } + WorldStem worldstem; + try { + worldstem = this.loadWorldStem(p_332568_, p_334192_, packrepository); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch index c3b27b7eb5..adffba10e2 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch @@ -1,38 +1,38 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java -@@ -76,6 +_,7 @@ - static final ResourceLocation JOIN_SPRITE = new ResourceLocation("world_list/join"); - static final Logger LOGGER = LogUtils.getLogger(); - private static final ResourceLocation ICON_MISSING = new ResourceLocation("textures/misc/unknown_server.png"); -+ private static final ResourceLocation FORGE_EXPERIMENTAL_WARNING_ICON = new ResourceLocation("forge","textures/gui/experimental_warning.png"); - static final Component FROM_NEWER_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.fromNewerVersion1").withStyle(ChatFormatting.RED); - static final Component FROM_NEWER_TOOLTIP_2 = Component.translatable("selectWorld.tooltip.fromNewerVersion2").withStyle(ChatFormatting.RED); - static final Component SNAPSHOT_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.snapshot1").withStyle(ChatFormatting.GOLD); -@@ -372,6 +_,7 @@ - RenderSystem.enableBlend(); - p_281612_.blit(this.icon.textureLocation(), p_282820_, p_283181_, 0.0F, 0.0F, 32, 32, 32, 32); - RenderSystem.disableBlend(); -+ renderExperimentalWarning(p_281612_, p_283204_, p_283025_, p_283181_, p_282820_); - if (this.minecraft.options.touchscreen().get() || p_283396_) { - p_281612_.fill(p_282820_, p_283181_, p_282820_ + 32, p_283181_ + 32, -1601138544); - int j = p_283204_ - p_282820_; -@@ -579,6 +_,19 @@ - - public String getLevelName() { - return this.summary.getLevelName(); -+ } +@@ -75,6 +_,7 @@ + static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = new ResourceLocation("world_list/join_highlighted"); + static final ResourceLocation JOIN_SPRITE = new ResourceLocation("world_list/join"); + static final Logger LOGGER = LogUtils.getLogger(); ++ private static final ResourceLocation FORGE_EXPERIMENTAL_WARNING_ICON = new ResourceLocation("forge","textures/gui/experimental_warning.png"); + static final Component FROM_NEWER_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.fromNewerVersion1").withStyle(ChatFormatting.RED); + static final Component FROM_NEWER_TOOLTIP_2 = Component.translatable("selectWorld.tooltip.fromNewerVersion2").withStyle(ChatFormatting.RED); + static final Component SNAPSHOT_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.snapshot1").withStyle(ChatFormatting.GOLD); +@@ -402,6 +_,7 @@ + RenderSystem.enableBlend(); + p_281612_.blit(this.icon.textureLocation(), p_282820_, p_283181_, 0.0F, 0.0F, 32, 32, 32, 32); + RenderSystem.disableBlend(); ++ renderExperimentalWarning(p_281612_, p_283204_, p_283025_, p_283181_, p_282820_); + if (this.minecraft.options.touchscreen().get() || p_283396_) { + p_281612_.fill(p_282820_, p_283181_, p_282820_ + 32, p_283181_ + 32, -1601138544); + int j = p_283204_ - p_282820_; +@@ -448,6 +_,19 @@ + p_281612_.blitSprite(resourcelocation, p_282820_, p_283181_, 32, 32); + } + } ++ } + -+ // FORGE: Patch in experimental warning icon for worlds in the world selection screen -+ private void renderExperimentalWarning(GuiGraphics guiGraphics, int mouseX, int mouseY, int top, int left) { -+ if (this.summary.isLifecycleExperimental()) { -+ int leftStart = left + WorldSelectionList.this.getRowWidth(); -+ guiGraphics.blit(WorldSelectionList.FORGE_EXPERIMENTAL_WARNING_ICON, leftStart - 36, top, 0.0F, 0.0F, 32, 32, 32, 32); -+ if (WorldSelectionList.this.getEntryAtPosition(mouseX, mouseY) == this && mouseX > leftStart - 36 && mouseX < leftStart) { -+ var font = Minecraft.getInstance().font; -+ List tooltip = font.split(Component.translatable("forge.experimentalsettings.tooltip"), 200); -+ guiGraphics.renderTooltip(font, tooltip, mouseX, mouseY); -+ } -+ } - } - } - } ++ // FORGE: Patch in experimental warning icon for worlds in the world selection screen ++ private void renderExperimentalWarning(GuiGraphics guiGraphics, int mouseX, int mouseY, int top, int left) { ++ if (this.summary.isLifecycleExperimental()) { ++ int leftStart = left + WorldSelectionList.this.getRowWidth(); ++ guiGraphics.blit(WorldSelectionList.FORGE_EXPERIMENTAL_WARNING_ICON, leftStart - 36, top, 0.0F, 0.0F, 32, 32, 32, 32); ++ if (WorldSelectionList.this.getEntryAtPosition(mouseX, mouseY) == this && mouseX > leftStart - 36 && mouseX < leftStart) { ++ var font = Minecraft.getInstance().font; ++ List tooltip = font.split(Component.translatable("forge.experimentalsettings.tooltip"), 200); ++ guiGraphics.renderTooltip(font, tooltip, mouseX, mouseY); ++ } ++ } + } + + @Override diff --git a/patches/minecraft/net/minecraft/client/main/Main.java.patch b/patches/minecraft/net/minecraft/client/main/Main.java.patch index da7d302ba9..9a930dae40 100644 --- a/patches/minecraft/net/minecraft/client/main/Main.java.patch +++ b/patches/minecraft/net/minecraft/client/main/Main.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/client/main/Main.java +++ b/net/minecraft/client/main/Main.java -@@ -152,8 +_,8 @@ - CrashReport.preload(); +@@ -154,8 +_,8 @@ + CrashReport.preload(); - try { -- Bootstrap.bootStrap(); - GameLoadTimesEvent.INSTANCE.setBootstrapTime(Bootstrap.bootstrapDuration.get()); -+ net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(()->Bootstrap.bootStrap(), net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); - Bootstrap.validate(); - } catch (Throwable throwable2) { - CrashReport crashreport = CrashReport.forThrowable(throwable2, "Bootstrap"); + try { +- Bootstrap.bootStrap(); + GameLoadTimesEvent.INSTANCE.setBootstrapTime(Bootstrap.bootstrapDuration.get()); ++ net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(Bootstrap::bootStrap, net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); + Bootstrap.validate(); + } catch (Throwable throwable2) { + CrashReport crashreport = CrashReport.forThrowable(throwable2, "Bootstrap"); diff --git a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch index 9aea27ffa1..54ee4894d7 100644 --- a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch +++ b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch @@ -1,59 +1,58 @@ --- a/net/minecraft/client/model/HumanoidModel.java +++ b/net/minecraft/client/model/HumanoidModel.java -@@ -272,6 +_,8 @@ - case TOOT_HORN: - this.rightArm.xRot = Mth.clamp(this.head.xRot, -1.2F, 1.2F) - 1.4835298F; - this.rightArm.yRot = this.head.yRot - ((float)Math.PI / 6F); -+ default: -+ this.rightArmPose.applyTransform(this, p_102876_, net.minecraft.world.entity.HumanoidArm.RIGHT); - } +@@ -308,6 +_,8 @@ + case BRUSH: + this.rightArm.xRot = this.rightArm.xRot * 0.5F - (float) (Math.PI / 5); + this.rightArm.yRot = 0.0F; ++ default: ++ this.rightArmPose.applyTransform(this, p_102876_, net.minecraft.world.entity.HumanoidArm.RIGHT); + } + } - } -@@ -315,6 +_,8 @@ - case TOOT_HORN: - this.leftArm.xRot = Mth.clamp(this.head.xRot, -1.2F, 1.2F) - 1.4835298F; - this.leftArm.yRot = this.head.yRot + ((float)Math.PI / 6F); -+ default: -+ this.leftArmPose.applyTransform(this, p_102879_, net.minecraft.world.entity.HumanoidArm.LEFT); - } +@@ -352,6 +_,8 @@ + case BRUSH: + this.leftArm.xRot = this.leftArm.xRot * 0.5F - (float) (Math.PI / 5); + this.leftArm.yRot = 0.0F; ++ default: ++ this.leftArmPose.applyTransform(this, p_102879_, net.minecraft.world.entity.HumanoidArm.LEFT); + } + } - } -@@ -412,7 +_,7 @@ - } +@@ -451,7 +_,7 @@ + } - @OnlyIn(Dist.CLIENT) -- public static enum ArmPose { -+ public static enum ArmPose implements net.minecraftforge.common.IExtensibleEnum { - EMPTY(false), - ITEM(false), - BLOCK(false), -@@ -428,10 +_,29 @@ + @OnlyIn(Dist.CLIENT) +- public static enum ArmPose { ++ public static enum ArmPose implements net.minecraftforge.common.IExtensibleEnum { + EMPTY(false), + ITEM(false), + BLOCK(false), +@@ -467,10 +_,28 @@ - private ArmPose(boolean p_102896_) { - this.twoHanded = p_102896_; -+ this.forgeArmPose = null; - } + private ArmPose(final boolean p_102896_) { + this.twoHanded = p_102896_; ++ this.forgeArmPose = null; + } - public boolean isTwoHanded() { - return this.twoHanded; - } -+ // FORGE START -+ @javax.annotation.Nullable -+ private final net.minecraftforge.client.IArmPoseTransformer forgeArmPose; + public boolean isTwoHanded() { + return this.twoHanded; ++ } + -+ private ArmPose(boolean twoHanded, @javax.annotation.Nonnull net.minecraftforge.client.IArmPoseTransformer forgeArmPose) { -+ this.twoHanded = twoHanded; -+ com.google.common.base.Preconditions.checkNotNull(forgeArmPose, "Cannot create new ArmPose with null transformer!"); -+ this.forgeArmPose = forgeArmPose; -+ } ++ @javax.annotation.Nullable ++ private final net.minecraftforge.client.IArmPoseTransformer forgeArmPose; + -+ public static ArmPose create(String name, boolean twoHanded, @javax.annotation.Nonnull net.minecraftforge.client.IArmPoseTransformer forgeArmPose) { -+ throw new IllegalStateException("Enum not extended"); -+ } ++ private ArmPose(boolean twoHanded, @javax.annotation.Nonnull net.minecraftforge.client.IArmPoseTransformer forgeArmPose) { ++ this.twoHanded = twoHanded; ++ com.google.common.base.Preconditions.checkNotNull(forgeArmPose, "Cannot create new ArmPose with null transformer!"); ++ this.forgeArmPose = forgeArmPose; ++ } + -+ public void applyTransform(HumanoidModel model, T entity, net.minecraft.world.entity.HumanoidArm arm) { -+ if (this.forgeArmPose != null) this.forgeArmPose.applyTransform(model, entity, arm); -+ } -+ // FORGE END - } ++ public static ArmPose create(String name, boolean twoHanded, @javax.annotation.Nonnull net.minecraftforge.client.IArmPoseTransformer forgeArmPose) { ++ throw new IllegalStateException("Enum not extended"); ++ } ++ ++ public void applyTransform(HumanoidModel model, T entity, net.minecraft.world.entity.HumanoidArm arm) { ++ if (this.forgeArmPose != null) this.forgeArmPose.applyTransform(model, entity, arm); + } + } } diff --git a/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch b/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch index 7bc6d9693f..aa7a0b8d3d 100644 --- a/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch +++ b/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/model/geom/LayerDefinitions.java +++ b/net/minecraft/client/model/geom/LayerDefinitions.java -@@ -325,6 +_,7 @@ - WoodType.values().forEach((p_247864_) -> { - builder.put(ModelLayers.createHangingSignModelName(p_247864_), layerdefinition24); - }); -+ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(builder); - ImmutableMap immutablemap = builder.build(); - List list = ModelLayers.getKnownLocations().filter((p_171117_) -> { - return !immutablemap.containsKey(p_171117_); +@@ -328,6 +_,7 @@ + WoodType.values().forEach(p_171114_ -> builder.put(ModelLayers.createSignModelName(p_171114_), layerdefinition23)); + LayerDefinition layerdefinition24 = HangingSignRenderer.createHangingSignLayer(); + WoodType.values().forEach(p_247864_ -> builder.put(ModelLayers.createHangingSignModelName(p_247864_), layerdefinition24)); ++ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(builder); + ImmutableMap immutablemap = builder.build(); + List list = ModelLayers.getKnownLocations().filter(p_171117_ -> !immutablemap.containsKey(p_171117_)).collect(Collectors.toList()); + if (!list.isEmpty()) { diff --git a/patches/minecraft/net/minecraft/client/model/geom/ModelLayers.java.patch b/patches/minecraft/net/minecraft/client/model/geom/ModelLayers.java.patch deleted file mode 100644 index a9c32eed1e..0000000000 --- a/patches/minecraft/net/minecraft/client/model/geom/ModelLayers.java.patch +++ /dev/null @@ -1,18 +0,0 @@ ---- a/net/minecraft/client/model/geom/ModelLayers.java -+++ b/net/minecraft/client/model/geom/ModelLayers.java -@@ -224,11 +_,13 @@ - } - - public static ModelLayerLocation createSignModelName(WoodType p_171292_) { -- return createLocation("sign/" + p_171292_.name(), "main"); -+ ResourceLocation location = new ResourceLocation(p_171292_.name()); -+ return new ModelLayerLocation(new ResourceLocation(location.getNamespace(), "sign/" + location.getPath()), "main"); - } - - public static ModelLayerLocation createHangingSignModelName(WoodType p_252225_) { -- return createLocation("hanging_sign/" + p_252225_.name(), "main"); -+ ResourceLocation location = new ResourceLocation(p_252225_.name()); -+ return new ModelLayerLocation(new ResourceLocation(location.getNamespace(), "hanging_sign/" + location.getPath()), "main"); - } - - public static Stream getKnownLocations() { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch index 01ea9afdbe..6b8bb5b98a 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java +++ b/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java -@@ -75,6 +_,8 @@ - this.writeProfileKeyPair(profilekeypair); - return Optional.of(profilekeypair); - } catch (CryptException | MinecraftClientException | IOException ioexception) { -+ // Forge: The offline user api service always returns a null profile key pair, so let's hide this useless exception if in dev -+ if (net.minecraftforge.fml.loading.FMLLoader.isProduction() || this.userApiService != UserApiService.OFFLINE) - LOGGER.error("Failed to retrieve profile key pair", (Throwable)ioexception); - this.writeProfileKeyPair((ProfileKeyPair)null); - return p_254074_; +@@ -74,6 +_,8 @@ + this.writeProfileKeyPair(profilekeypair); + return Optional.ofNullable(profilekeypair); + } catch (CryptException | MinecraftClientException | IOException ioexception) { ++ // Forge: The offline user api service always returns a null profile key pair, so let's hide this useless exception if in dev ++ if (net.minecraftforge.fml.loading.FMLLoader.isProduction() || this.userApiService != UserApiService.OFFLINE) + LOGGER.error("Failed to retrieve profile key pair", (Throwable)ioexception); + this.writeProfileKeyPair(null); + return p_254074_; diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch index 3fe7968a48..fddcd362fe 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/client/multiplayer/ClientChunkCache.java +++ b/net/minecraft/client/multiplayer/ClientChunkCache.java -@@ -60,6 +_,7 @@ - int i = this.storage.getIndex(p_298665_.x, p_298665_.z); - LevelChunk levelchunk = this.storage.getChunk(i); - if (isValidChunk(levelchunk, p_298665_.x, p_298665_.z)) { -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(levelchunk)); - this.storage.replace(i, levelchunk, (LevelChunk)null); - } +@@ -61,6 +_,7 @@ + int i = this.storage.getIndex(p_298665_.x, p_298665_.z); + LevelChunk levelchunk = this.storage.getChunk(i); + if (isValidChunk(levelchunk, p_298665_.x, p_298665_.z)) { ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(levelchunk)); + this.storage.replace(i, levelchunk, null); + } + } +@@ -121,6 +_,7 @@ + } -@@ -115,6 +_,7 @@ - } - - this.level.onChunkLoaded(chunkpos); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(levelchunk, false)); - return levelchunk; - } - } + this.level.onChunkLoaded(chunkpos); ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(levelchunk, false)); + return levelchunk; + } + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch index fc930b1905..3efd8334cb 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java -@@ -93,6 +_,7 @@ - } +@@ -116,6 +_,7 @@ - public void handleCustomPayload(ClientboundCustomPayloadPacket p_298103_) { -+ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_, this.connection)) return; - CustomPacketPayload custompacketpayload = p_298103_.payload(); - if (!(custompacketpayload instanceof DiscardedPayload)) { - PacketUtils.ensureRunningOnSameThread(p_298103_, this, this.minecraft); + @Override + public void handleCustomPayload(ClientboundCustomPayloadPacket p_298103_) { ++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_, this.connection)) return; + CustomPacketPayload custompacketpayload = p_298103_.payload(); + if (!(custompacketpayload instanceof DiscardedPayload)) { + PacketUtils.ensureRunningOnSameThread(p_298103_, this, this.minecraft); diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch index 7f51541f14..b45a7740da 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java -@@ -72,6 +_,7 @@ - this.connection.setListener(new ClientPacketListener(this.minecraft, this.connection, new CommonListenerCookie(this.localGameProfile, this.telemetryManager, this.receivedRegistries, this.enabledFeatures, this.serverBrand, this.serverData, this.postDisconnectScreen))); - this.connection.resumeInboundAfterProtocolChange(); - this.connection.send(new ServerboundFinishConfigurationPacket()); -+ net.minecraftforge.common.ForgeHooks.handleClientConfigurationComplete(this.connection); - } +@@ -141,6 +_,7 @@ + ); + this.connection.send(ServerboundFinishConfigurationPacket.INSTANCE); + this.connection.setupOutboundProtocol(GameProtocols.SERVERBOUND.bind(RegistryFriendlyByteBuf.decorator(registryaccess$frozen))); ++ net.minecraftforge.common.ForgeHooks.handleClientConfigurationComplete(this.connection); + } - public void tick() { + @Override diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch index f067beb58d..c48ead2ba0 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java -@@ -157,6 +_,7 @@ - public void onDisconnect(Component p_104543_) { - if (this.serverData != null && this.serverData.isRealm()) { - this.minecraft.setScreen(new DisconnectedRealmsScreen(this.parent, CommonComponents.CONNECT_FAILED, p_104543_)); -+ } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.connection, this.minecraft, this.parent, p_104543_)) { - } else { - this.minecraft.setScreen(new DisconnectedScreen(this.parent, CommonComponents.CONNECT_FAILED, p_104543_)); - } -@@ -179,6 +_,7 @@ - } +@@ -205,6 +_,7 @@ + Component component = this.wasTransferredTo ? CommonComponents.TRANSFER_CONNECT_FAILED : CommonComponents.CONNECT_FAILED; + if (this.serverData != null && this.serverData.isRealm()) { + this.minecraft.setScreen(new DisconnectedRealmsScreen(this.parent, component, p_104543_)); ++ } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.connection, this.minecraft, this.parent, p_104543_)) { + } else { + this.minecraft.setScreen(new DisconnectedScreen(this.parent, component, p_104543_)); + } +@@ -229,6 +_,7 @@ - public void handleCustomQuery(ClientboundCustomQueryPacket p_104545_) { -+ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_104545_, this.connection)) return; - this.updateStatus.accept(Component.translatable("connect.negotiating")); - this.connection.send(new ServerboundCustomQueryAnswerPacket(p_104545_.transactionId(), (CustomQueryAnswerPayload)null)); - } + @Override + public void handleCustomQuery(ClientboundCustomQueryPacket p_104545_) { ++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_104545_, this.connection)) return; + this.updateStatus.accept(Component.translatable("connect.negotiating")); + this.connection.send(new ServerboundCustomQueryAnswerPacket(p_104545_.transactionId(), null)); + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch index 291e99d127..6d0bbf458b 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch @@ -1,127 +1,132 @@ --- a/net/minecraft/client/multiplayer/ClientLevel.java +++ b/net/minecraft/client/multiplayer/ClientLevel.java -@@ -118,12 +_,15 @@ - p_194170_.put(BiomeColors.WATER_COLOR_RESOLVER, new BlockTintCache((p_194168_) -> { - return this.calculateBlockTint(p_194168_, BiomeColors.WATER_COLOR_RESOLVER); - })); -+ net.minecraftforge.client.ColorResolverManager.registerBlockTintCaches(ClientLevel.this, p_194170_); - }); - private final ClientChunkCache chunkSource; - private final Deque lightUpdateQueue = Queues.newArrayDeque(); - private int serverSimulationDistance; - private final BlockStatePredictionHandler blockStatePredictionHandler = new BlockStatePredictionHandler(); - private static final Set MARKER_PARTICLE_ITEMS = Set.of(Items.BARRIER, Items.LIGHT); -+ private final it.unimi.dsi.fastutil.ints.Int2ObjectMap> partEntities = new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(); -+ private final net.minecraftforge.client.model.data.ModelDataManager modelDataManager = new net.minecraftforge.client.model.data.ModelDataManager(this); +@@ -113,12 +_,15 @@ + p_194170_.put(BiomeColors.GRASS_COLOR_RESOLVER, new BlockTintCache(p_194181_ -> this.calculateBlockTint(p_194181_, BiomeColors.GRASS_COLOR_RESOLVER))); + p_194170_.put(BiomeColors.FOLIAGE_COLOR_RESOLVER, new BlockTintCache(p_194177_ -> this.calculateBlockTint(p_194177_, BiomeColors.FOLIAGE_COLOR_RESOLVER))); + p_194170_.put(BiomeColors.WATER_COLOR_RESOLVER, new BlockTintCache(p_194168_ -> this.calculateBlockTint(p_194168_, BiomeColors.WATER_COLOR_RESOLVER))); ++ net.minecraftforge.client.ColorResolverManager.registerBlockTintCaches(ClientLevel.this, p_194170_); + }); + private final ClientChunkCache chunkSource; + private final Deque lightUpdateQueue = Queues.newArrayDeque(); + private int serverSimulationDistance; + private final BlockStatePredictionHandler blockStatePredictionHandler = new BlockStatePredictionHandler(); + private static final Set MARKER_PARTICLE_ITEMS = Set.of(Items.BARRIER, Items.LIGHT); ++ private final it.unimi.dsi.fastutil.ints.Int2ObjectMap> partEntities = new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(); ++ private final net.minecraftforge.client.model.data.ModelDataManager modelDataManager = new net.minecraftforge.client.model.data.ModelDataManager(this); - public void handleBlockChangedAck(int p_233652_) { - this.blockStatePredictionHandler.endPredictionsUpTo(p_233652_, this); -@@ -178,6 +_,8 @@ - this.serverSimulationDistance = p_205510_; - this.updateSkyBrightness(); - this.prepareWeather(); -+ this.gatherCapabilities(); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.LevelEvent.Load(this)); - } + public void handleBlockChangedAck(int p_233652_) { + this.blockStatePredictionHandler.endPredictionsUpTo(p_233652_, this); +@@ -183,6 +_,8 @@ + this.serverSimulationDistance = p_205510_; + this.updateSkyBrightness(); + this.prepareWeather(); ++ this.gatherCapabilities(); ++ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(this); + } - public void queueLightUpdate(Runnable p_194172_) { -@@ -271,6 +_,7 @@ - this.getProfiler().push(() -> { - return BuiltInRegistries.ENTITY_TYPE.getKey(p_104640_.getType()).toString(); - }); -+ if (p_104640_.canUpdate()) - p_104640_.tick(); - this.getProfiler().pop(); + public void queueLightUpdate(Runnable p_194172_) { +@@ -273,6 +_,7 @@ + p_104640_.setOldPosAndRot(); + p_104640_.tickCount++; + this.getProfiler().push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(p_104640_.getType()).toString()); ++ if (p_104640_.canUpdate()) + p_104640_.tick(); + this.getProfiler().pop(); -@@ -326,8 +_,10 @@ - } +@@ -321,8 +_,10 @@ + } - public void addEntity(Entity p_104741_) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityJoinLevelEvent(p_104741_, this))) return; - this.removeEntity(p_104741_.getId(), Entity.RemovalReason.DISCARDED); - this.entityStorage.addEntity(p_104741_); -+ p_104741_.onAddedToWorld(); - } + public void addEntity(Entity p_104741_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onEntityJoinLevel(p_104741_, this)) return; + this.removeEntity(p_104741_.getId(), Entity.RemovalReason.DISCARDED); + this.entityStorage.addEntity(p_104741_); ++ p_104741_.onAddedToWorld(); + } - public void removeEntity(int p_171643_, Entity.RemovalReason p_171644_) { -@@ -457,6 +_,12 @@ - } + public void removeEntity(int p_171643_, Entity.RemovalReason p_171644_) { +@@ -493,6 +_,12 @@ + float p_263349_, + long p_263408_ + ) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtPosition(this, p_263372_, p_263404_, p_263365_, p_263335_, p_263417_, p_263416_, p_263349_); ++ if (event.isCanceled() || event.getSound() == null) return; ++ p_263335_ = event.getSound(); ++ p_263417_ = event.getSource(); ++ p_263416_ = event.getNewVolume(); ++ p_263349_ = event.getNewPitch(); + if (p_263381_ == this.minecraft.player) { + this.playSound(p_263372_, p_263404_, p_263365_, p_263335_.value(), p_263417_, p_263416_, p_263349_, false, p_263408_); + } +@@ -502,6 +_,12 @@ + public void playSeededSound( + @Nullable Player p_263514_, Entity p_263536_, Holder p_263518_, SoundSource p_263487_, float p_263538_, float p_263524_, long p_263509_ + ) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(p_263536_, p_263518_, p_263487_, p_263538_, p_263524_); ++ if (event.isCanceled() || event.getSound() == null) return; ++ p_263518_ = event.getSound(); ++ p_263487_ = event.getSource(); ++ p_263538_ = event.getNewVolume(); ++ p_263524_ = event.getNewPitch(); + if (p_263514_ == this.minecraft.player) { + this.minecraft.getSoundManager().play(new EntityBoundSoundInstance(p_263518_.value(), p_263487_, p_263538_, p_263524_, p_263536_, p_263509_)); + } +@@ -927,6 +_,24 @@ + return this.connection.potionBrewing(); + } - public void playSeededSound(@Nullable Player p_263381_, double p_263372_, double p_263404_, double p_263365_, Holder p_263335_, SoundSource p_263417_, float p_263416_, float p_263349_, long p_263408_) { -+ net.minecraftforge.event.PlayLevelSoundEvent.AtPosition event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtPosition(this, p_263372_, p_263404_, p_263365_, p_263335_, p_263417_, p_263416_, p_263349_); -+ if (event.isCanceled() || event.getSound() == null) return; -+ p_263335_ = event.getSound(); -+ p_263417_ = event.getSource(); -+ p_263416_ = event.getNewVolume(); -+ p_263349_ = event.getNewPitch(); - if (p_263381_ == this.minecraft.player) { - this.playSound(p_263372_, p_263404_, p_263365_, p_263335_.value(), p_263417_, p_263416_, p_263349_, false, p_263408_); - } -@@ -464,6 +_,12 @@ - } ++ @Override ++ public java.util.Collection> getPartEntities() { ++ return this.partEntities.values(); ++ } ++ ++ @Override ++ public net.minecraftforge.client.model.data.ModelDataManager getModelDataManager() { ++ return modelDataManager; ++ } ++ ++ @Override ++ public float getShade(float normalX, float normalY, float normalZ, boolean shade) { ++ boolean constantAmbientLight = this.effects().constantAmbientLight(); ++ if (!shade) ++ return constantAmbientLight ? 0.9F : 1.0F; ++ return net.minecraftforge.client.model.lighting.QuadLighter.calculateShade(normalX, normalY, normalZ, constantAmbientLight); ++ } ++ + @OnlyIn(Dist.CLIENT) + public static class ClientLevelData implements WritableLevelData { + private final boolean hardcore; +@@ -1022,6 +_,7 @@ + } - public void playSeededSound(@Nullable Player p_263514_, Entity p_263536_, Holder p_263518_, SoundSource p_263487_, float p_263538_, float p_263524_, long p_263509_) { -+ net.minecraftforge.event.PlayLevelSoundEvent.AtEntity event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(p_263536_, p_263518_, p_263487_, p_263538_, p_263524_); -+ if (event.isCanceled() || event.getSound() == null) return; -+ p_263518_ = event.getSound(); -+ p_263487_ = event.getSource(); -+ p_263538_ = event.getNewVolume(); -+ p_263524_ = event.getNewPitch(); - if (p_263514_ == this.minecraft.player) { - this.minecraft.getSoundManager().play(new EntityBoundSoundInstance(p_263518_.value(), p_263487_, p_263538_, p_263524_, p_263536_, p_263509_)); - } -@@ -909,6 +_,7 @@ - } + public void setDifficulty(Difficulty p_104852_) { ++ net.minecraftforge.event.ForgeEventFactory.onDifficultyChange(p_104852_, this.difficulty); + this.difficulty = p_104852_; + } - public void setDifficulty(Difficulty p_104852_) { -+ net.minecraftforge.common.ForgeHooks.onDifficultyChange(p_104852_, this.difficulty); - this.difficulty = p_104852_; - } - -@@ -946,14 +_,46 @@ - ClientLevel.this.players.add((AbstractClientPlayer)p_171712_); - } - -+ if (p_171712_.isMultipartEntity()) { -+ for (net.minecraftforge.entity.PartEntity part : p_171712_.getParts()) { -+ ClientLevel.this.partEntities.put(part.getId(), part); +@@ -1058,11 +_,26 @@ + if (p_171712_ instanceof AbstractClientPlayer) { + ClientLevel.this.players.add((AbstractClientPlayer)p_171712_); + } ++ ++ if (p_171712_.isMultipartEntity()) { ++ for (var part : p_171712_.getParts()) { ++ ClientLevel.this.partEntities.put(part.getId(), part); ++ } + } -+ } - } + } - public void onTrackingEnd(Entity p_171716_) { - p_171716_.unRide(); - ClientLevel.this.players.remove(p_171716_); + public void onTrackingEnd(Entity p_171716_) { + p_171716_.unRide(); + ClientLevel.this.players.remove(p_171716_); + -+ p_171716_.onRemovedFromWorld(); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityLeaveLevelEvent(p_171716_, ClientLevel.this)); ++ p_171716_.onRemovedFromWorld(); ++ net.minecraftforge.event.ForgeEventFactory.onEntityLeaveLevel(p_171716_, ClientLevel.this); + -+ if (p_171716_.isMultipartEntity()) { -+ for (net.minecraftforge.entity.PartEntity part : p_171716_.getParts()) { -+ ClientLevel.this.partEntities.remove(part.getId()); ++ if (p_171716_.isMultipartEntity()) { ++ for (var part : p_171716_.getParts()) { ++ ClientLevel.this.partEntities.remove(part.getId()); ++ } + } -+ } - } + } - public void onSectionChange(Entity p_233660_) { - } -+ } -+ -+ @Override -+ public java.util.Collection> getPartEntities() { -+ return this.partEntities.values(); -+ } -+ -+ @Override -+ public net.minecraftforge.client.model.data.ModelDataManager getModelDataManager() { -+ return modelDataManager; -+ } -+ -+ @Override -+ public float getShade(float normalX, float normalY, float normalZ, boolean shade) { -+ boolean constantAmbientLight = this.effects().constantAmbientLight(); -+ if (!shade) -+ return constantAmbientLight ? 0.9F : 1.0F; -+ return net.minecraftforge.client.model.lighting.QuadLighter.calculateShade(normalX, normalY, normalZ, constantAmbientLight); - } - } + public void onSectionChange(Entity p_233660_) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch index 6926099f0d..9f75657bfa 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch @@ -1,78 +1,77 @@ --- a/net/minecraft/client/multiplayer/ClientPacketListener.java +++ b/net/minecraft/client/multiplayer/ClientPacketListener.java -@@ -398,6 +_,7 @@ +@@ -425,6 +_,7 @@ - this.minecraft.debugRenderer.clear(); - this.minecraft.player.resetPos(); -+ net.minecraftforge.client.ForgeHooksClient.firePlayerLogin(this.minecraft.gameMode, this.minecraft.player, this.minecraft.getConnection().connection); - this.minecraft.player.setId(p_105030_.playerId()); - this.level.addEntity(this.minecraft.player); - this.minecraft.player.input = new KeyboardInput(this.minecraft.options); -@@ -1043,7 +_,9 @@ - localplayer1.getAttributes().assignValues(localplayer.getAttributes()); - } + this.minecraft.debugRenderer.clear(); + this.minecraft.player.resetPos(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogin(this.minecraft.gameMode, this.minecraft.player, this.minecraft.getConnection().connection); + this.minecraft.player.setId(p_105030_.playerId()); + this.level.addEntity(this.minecraft.player); + this.minecraft.player.input = new KeyboardInput(this.minecraft.options); +@@ -1159,7 +_,9 @@ + localplayer1.getAttributes().assignValues(localplayer.getAttributes()); + } -+ localplayer1.updateSyncFields(localplayer); // Forge: fix MC-10657 - localplayer1.resetPos(); -+ net.minecraftforge.client.ForgeHooksClient.firePlayerRespawn(this.minecraft.gameMode, localplayer, localplayer1, localplayer1.connection.connection); - this.level.addEntity(localplayer1); - localplayer1.setYRot(-180.0F); - localplayer1.input = new KeyboardInput(this.minecraft.options); -@@ -1152,10 +_,7 @@ - PacketUtils.ensureRunningOnSameThread(p_104976_, this, this.minecraft); - BlockPos blockpos = p_104976_.getPos(); - this.minecraft.level.getBlockEntity(blockpos, p_104976_.getType()).ifPresent((p_205557_) -> { -- CompoundTag compoundtag = p_104976_.getTag(); -- if (compoundtag != null) { -- p_205557_.load(compoundtag); -- } -+ p_205557_.onDataPacket(connection, p_104976_); ++ localplayer1.updateSyncFields(localplayer); // Forge: fix MC-10657 + localplayer1.resetPos(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerRespawn(this.minecraft.gameMode, localplayer, localplayer1, localplayer1.connection.connection); + this.level.addEntity(localplayer1); + localplayer1.setYRot(-180.0F); + localplayer1.input = new KeyboardInput(this.minecraft.options); +@@ -1294,10 +_,7 @@ + PacketUtils.ensureRunningOnSameThread(p_104976_, this, this.minecraft); + BlockPos blockpos = p_104976_.getPos(); + this.minecraft.level.getBlockEntity(blockpos, p_104976_.getType()).ifPresent(p_325478_ -> { +- CompoundTag compoundtag = p_104976_.getTag(); +- if (!compoundtag.isEmpty()) { +- p_325478_.loadWithComponents(compoundtag, this.registryAccess); +- } ++ p_325478_.onDataPacket(connection, p_104976_, this.registryAccess); - if (p_205557_ instanceof CommandBlockEntity && this.minecraft.screen instanceof CommandBlockEditScreen) { - ((CommandBlockEditScreen)this.minecraft.screen).updateGui(); -@@ -1312,7 +_,9 @@ + if (p_325478_ instanceof CommandBlockEntity && this.minecraft.screen instanceof CommandBlockEditScreen) { + ((CommandBlockEditScreen)this.minecraft.screen).updateGui(); +@@ -1464,7 +_,9 @@ + @Override + public void handleCommands(ClientboundCommandsPacket p_104990_) { + PacketUtils.ensureRunningOnSameThread(p_104990_, this, this.minecraft); +- this.commands = new CommandDispatcher<>(p_104990_.getRoot(CommandBuildContext.simple(this.registryAccess, this.enabledFeatures))); ++ var context = CommandBuildContext.simple(this.registryAccess, this.enabledFeatures); ++ this.commands = new CommandDispatcher<>(p_104990_.getRoot(context)); ++ this.commands = net.minecraftforge.client.ClientCommandHandler.mergeServerCommands(this.commands, context); + } - public void handleCommands(ClientboundCommandsPacket p_104990_) { - PacketUtils.ensureRunningOnSameThread(p_104990_, this, this.minecraft); -- this.commands = new CommandDispatcher<>(p_104990_.getRoot(CommandBuildContext.simple(this.registryAccess, this.enabledFeatures))); -+ var context = CommandBuildContext.simple(this.registryAccess, this.enabledFeatures); -+ this.commands = new CommandDispatcher<>(p_104990_.getRoot(context)); -+ this.commands = net.minecraftforge.client.ClientCommandHandler.mergeServerCommands(this.commands, context); - } + @Override +@@ -1486,6 +_,7 @@ + ClientRecipeBook clientrecipebook = this.minecraft.player.getRecipeBook(); + clientrecipebook.setupCollections(this.recipeManager.getOrderedRecipes(), this.minecraft.level.registryAccess()); + this.minecraft.populateSearchTree(SearchRegistry.RECIPE_COLLECTIONS, clientrecipebook.getCollections()); ++ net.minecraftforge.client.ForgeHooksClient.onRecipesUpdated(this.recipeManager); + } - public void handleStopSoundEvent(ClientboundStopSoundPacket p_105116_) { -@@ -1331,6 +_,7 @@ - ClientRecipeBook clientrecipebook = this.minecraft.player.getRecipeBook(); - clientrecipebook.setupCollections(this.recipeManager.getRecipes(), this.minecraft.level.registryAccess()); - this.minecraft.populateSearchTree(SearchRegistry.RECIPE_COLLECTIONS, clientrecipebook.getCollections()); -+ net.minecraftforge.client.ForgeHooksClient.onRecipesUpdated(this.recipeManager); - } + @Override +@@ -1582,6 +_,8 @@ + TagCollector tagcollector = new TagCollector(); + p_298004_.getTags().forEach(tagcollector::append); + tagcollector.updateTags(this.registryAccess, this.connection.isMemoryConnection()); ++ ++ net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.registryAccess, true, this.connection.isMemoryConnection()); + } - public void handleLookAt(ClientboundPlayerLookAtPacket p_105054_) { -@@ -1429,7 +_,8 @@ - Blocks.rebuildCache(); - } + @Override +@@ -2388,6 +_,8 @@ + } -- CreativeModeTabs.searchTab().rebuildSearchTree(); -+ CreativeModeTabs.allTabs().stream().filter(net.minecraft.world.item.CreativeModeTab::hasSearchBar).forEach(net.minecraft.world.item.CreativeModeTab::rebuildSearchTree); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.TagsUpdatedEvent(this.registryAccess, true, connection.isMemoryConnection())); - } + public void sendChat(String p_249888_) { ++ p_249888_ = net.minecraftforge.client.ForgeHooksClient.onClientSendMessage(p_249888_); ++ if (p_249888_.isEmpty()) return; + Instant instant = Instant.now(); + long i = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update lastseenmessagestracker$update = this.lastSeenMessages.generateAndApplyUpdate(); +@@ -2396,6 +_,7 @@ + } - public void handlePlayerCombatEnd(ClientboundPlayerCombatEndPacket p_171771_) { -@@ -2145,6 +_,8 @@ - } - - public void sendChat(String p_249888_) { -+ p_249888_ = net.minecraftforge.client.ForgeHooksClient.onClientSendMessage(p_249888_); -+ if (p_249888_.isEmpty()) return; - Instant instant = Instant.now(); - long i = Crypt.SaltSupplier.getLong(); - LastSeenMessagesTracker.Update lastseenmessagestracker$update = this.lastSeenMessages.generateAndApplyUpdate(); -@@ -2153,6 +_,7 @@ - } - - public void sendCommand(String p_250092_) { -+ if (net.minecraftforge.client.ClientCommandHandler.runCommand(p_250092_)) return; - Instant instant = Instant.now(); - long i = Crypt.SaltSupplier.getLong(); - LastSeenMessagesTracker.Update lastseenmessagestracker$update = this.lastSeenMessages.generateAndApplyUpdate(); + public void sendCommand(String p_250092_) { ++ if (net.minecraftforge.client.ClientCommandHandler.runCommand(p_250092_)) return; + SignableCommand signablecommand = SignableCommand.of(this.parseCommand(p_250092_)); + if (signablecommand.arguments().isEmpty()) { + this.send(new ServerboundChatCommandPacket(p_250092_)); diff --git a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch index 2d7269ec0b..5f0d838be3 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch @@ -1,170 +1,170 @@ --- a/net/minecraft/client/multiplayer/MultiPlayerGameMode.java +++ b/net/minecraft/client/multiplayer/MultiPlayerGameMode.java -@@ -105,6 +_,7 @@ - } +@@ -106,6 +_,7 @@ + } - public boolean destroyBlock(BlockPos p_105268_) { -+ if (minecraft.player.getMainHandItem().onBlockStartBreak(p_105268_, minecraft.player)) return false; - if (this.minecraft.player.blockActionRestricted(this.minecraft.level, p_105268_, this.localPlayerMode)) { - return false; - } else { -@@ -119,9 +_,8 @@ - } else if (blockstate.isAir()) { - return false; - } else { -- block.playerWillDestroy(level, p_105268_, blockstate, this.minecraft.player); - FluidState fluidstate = level.getFluidState(p_105268_); -- boolean flag = level.setBlock(p_105268_, fluidstate.createLegacyBlock(), 11); -+ boolean flag = blockstate.onDestroyedByPlayer(level, p_105268_, minecraft.player, false, fluidstate); - if (flag) { - block.destroy(level, p_105268_, blockstate); - } -@@ -142,6 +_,7 @@ - BlockState blockstate = this.minecraft.level.getBlockState(p_105270_); - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105270_, blockstate, 1.0F); - this.startPrediction(this.minecraft.level, (p_233757_) -> { -+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.minecraft.player, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled()) - this.destroyBlock(p_105270_); - return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233757_); + public boolean destroyBlock(BlockPos p_105268_) { ++ if (minecraft.player.getMainHandItem().onBlockStartBreak(p_105268_, minecraft.player)) return false; + if (this.minecraft.player.blockActionRestricted(this.minecraft.level, p_105268_, this.localPlayerMode)) { + return false; + } else { +@@ -120,9 +_,8 @@ + } else if (blockstate.isAir()) { + return false; + } else { +- block.playerWillDestroy(level, p_105268_, blockstate, this.minecraft.player); + FluidState fluidstate = level.getFluidState(p_105268_); +- boolean flag = level.setBlock(p_105268_, fluidstate.createLegacyBlock(), 11); ++ boolean flag = blockstate.onDestroyedByPlayer(level, p_105268_, minecraft.player, false, fluidstate); + if (flag) { + block.destroy(level, p_105268_, blockstate); + } +@@ -143,6 +_,7 @@ + BlockState blockstate = this.minecraft.level.getBlockState(p_105270_); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105270_, blockstate, 1.0F); + this.startPrediction(this.minecraft.level, p_233757_ -> { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled()) + this.destroyBlock(p_105270_); + return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233757_); + }); +@@ -152,15 +_,18 @@ + this.connection + .send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, this.destroyBlockPos, p_105271_)); + } ++ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); + + BlockState blockstate1 = this.minecraft.level.getBlockState(p_105270_); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105270_, blockstate1, 0.0F); + this.startPrediction(this.minecraft.level, p_233728_ -> { + boolean flag = !blockstate1.isAir(); + if (flag && this.destroyProgress == 0.0F) { ++ if (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY) + blockstate1.attack(this.minecraft.level, p_105270_, this.minecraft.player); + } + ++ if (event.getUseItem() != net.minecraftforge.eventbus.api.Event.Result.DENY) { + if (flag && blockstate1.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), p_105270_) >= 1.0F) { + this.destroyBlock(p_105270_); + } else { +@@ -171,6 +_,7 @@ + this.destroyTicks = 0.0F; + this.minecraft.level.destroyBlockProgress(this.minecraft.player.getId(), this.destroyBlockPos, this.getDestroyStage()); + } ++ } + + return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233728_); + }); +@@ -203,6 +_,7 @@ + BlockState blockstate1 = this.minecraft.level.getBlockState(p_105284_); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105284_, blockstate1, 1.0F); + this.startPrediction(this.minecraft.level, p_233753_ -> { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, p_105284_, p_105285_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled()) + this.destroyBlock(p_105284_); + return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105284_, p_105285_, p_233753_); }); -@@ -150,15 +_,19 @@ - if (this.isDestroying) { - this.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, this.destroyBlockPos, p_105271_)); - } -+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.minecraft.player, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); - - BlockState blockstate1 = this.minecraft.level.getBlockState(p_105270_); - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105270_, blockstate1, 0.0F); - this.startPrediction(this.minecraft.level, (p_233728_) -> { - boolean flag = !blockstate1.isAir(); - if (flag && this.destroyProgress == 0.0F) { -+ if (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY) - blockstate1.attack(this.minecraft.level, p_105270_, this.minecraft.player); - } - -+ ServerboundPlayerActionPacket packet = new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233728_); -+ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return packet; - if (flag && blockstate1.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), p_105270_) >= 1.0F) { - this.destroyBlock(p_105270_); - } else { -@@ -170,7 +_,7 @@ - this.minecraft.level.destroyBlockProgress(this.minecraft.player.getId(), this.destroyBlockPos, this.getDestroyStage()); - } - -- return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233728_); -+ return packet; - }); - } - -@@ -201,6 +_,7 @@ - BlockState blockstate1 = this.minecraft.level.getBlockState(p_105284_); - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105284_, blockstate1, 1.0F); - this.startPrediction(this.minecraft.level, (p_233753_) -> { -+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.minecraft.player, p_105284_, p_105285_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled()) - this.destroyBlock(p_105284_); - return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105284_, p_105285_, p_233753_); - }); -@@ -213,12 +_,13 @@ - } else { - this.destroyProgress += blockstate.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), p_105284_); - if (this.destroyTicks % 4.0F == 0.0F) { -- SoundType soundtype = blockstate.getSoundType(); -+ SoundType soundtype = blockstate.getSoundType(this.minecraft.level, p_105284_, this.minecraft.player); - this.minecraft.getSoundManager().play(new SimpleSoundInstance(soundtype.getHitSound(), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 8.0F, soundtype.getPitch() * 0.5F, SoundInstance.createUnseededRandom(), p_105284_)); - } - - ++this.destroyTicks; - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105284_, blockstate, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); -+ if (net.minecraftforge.common.ForgeHooks.onClientMineHold(this.minecraft.player, p_105284_, p_105285_).getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return true; - if (this.destroyProgress >= 1.0F) { - this.isDestroying = false; - this.startPrediction(this.minecraft.level, (p_233739_) -> { -@@ -248,7 +_,7 @@ - } - - public float getPickRange() { -- return Player.getPickRange(this.localPlayerMode.isCreative()); -+ return (float) this.minecraft.player.getBlockReach(); - } - - public void tick() { -@@ -263,7 +_,7 @@ - - private boolean sameDestroyTarget(BlockPos p_105282_) { - ItemStack itemstack = this.minecraft.player.getMainHandItem(); -- return p_105282_.equals(this.destroyBlockPos) && ItemStack.isSameItemSameTags(itemstack, this.destroyingItem); -+ return p_105282_.equals(this.destroyBlockPos) && ItemStack.isSameItemSameTags(itemstack, this.destroyingItem) && !destroyingItem.shouldCauseBlockBreakReset(itemstack); - } - - private void ensureHasSentCarriedItem() { -@@ -292,25 +_,38 @@ - private InteractionResult performUseItemOn(LocalPlayer p_233747_, InteractionHand p_233748_, BlockHitResult p_233749_) { - BlockPos blockpos = p_233749_.getBlockPos(); - ItemStack itemstack = p_233747_.getItemInHand(p_233748_); -+ net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock event = net.minecraftforge.common.ForgeHooks.onRightClickBlock(p_233747_, p_233748_, blockpos, p_233749_); -+ if (event.isCanceled()) { -+ return event.getCancellationResult(); -+ } - if (this.localPlayerMode == GameType.SPECTATOR) { - return InteractionResult.SUCCESS; - } else { -- boolean flag = !p_233747_.getMainHandItem().isEmpty() || !p_233747_.getOffhandItem().isEmpty(); -+ UseOnContext useoncontext = new UseOnContext(p_233747_, p_233748_, p_233749_); -+ if (event.getUseItem() != net.minecraftforge.eventbus.api.Event.Result.DENY) { -+ InteractionResult result = itemstack.onItemUseFirst(useoncontext); -+ if (result != InteractionResult.PASS) { -+ return result; -+ } -+ } -+ boolean flag = !p_233747_.getMainHandItem().doesSneakBypassUse(p_233747_.level(), blockpos, p_233747_) || !p_233747_.getOffhandItem().doesSneakBypassUse(p_233747_.level(), blockpos, p_233747_); - boolean flag1 = p_233747_.isSecondaryUseActive() && flag; -- if (!flag1) { - BlockState blockstate = this.minecraft.level.getBlockState(blockpos); - if (!this.connection.isFeatureEnabled(blockstate.getBlock().requiredFeatures())) { - return InteractionResult.FAIL; - } - -+ if (event.getUseBlock() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY && !flag1)) { - InteractionResult interactionresult = blockstate.use(this.minecraft.level, p_233747_, p_233748_, p_233749_); - if (interactionresult.consumesAction()) { - return interactionresult; - } - } - -- if (!itemstack.isEmpty() && !p_233747_.getCooldowns().isOnCooldown(itemstack.getItem())) { -- UseOnContext useoncontext = new UseOnContext(p_233747_, p_233748_, p_233749_); -+ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) { -+ return InteractionResult.PASS; -+ } -+ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (!itemstack.isEmpty() && !p_233747_.getCooldowns().isOnCooldown(itemstack.getItem()))) { - InteractionResult interactionresult1; - if (this.localPlayerMode.isCreative()) { - int i = itemstack.getCount(); -@@ -341,10 +_,17 @@ - mutableobject.setValue(InteractionResult.PASS); - return serverbounduseitempacket; +@@ -215,7 +_,7 @@ } else { -+ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(p_233722_, p_233723_); -+ if (cancelResult != null) { -+ mutableobject.setValue(cancelResult); -+ return serverbounduseitempacket; + this.destroyProgress = this.destroyProgress + blockstate.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), p_105284_); + if (this.destroyTicks % 4.0F == 0.0F) { +- SoundType soundtype = blockstate.getSoundType(); ++ SoundType soundtype = blockstate.getSoundType(this.minecraft.level, p_105284_, this.minecraft.player); + this.minecraft + .getSoundManager() + .play( +@@ -232,6 +_,7 @@ + + this.destroyTicks++; + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, p_105284_, blockstate, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); ++ if (net.minecraftforge.event.ForgeEventFactory.onLeftClickBlockHold(this.minecraft.player, p_105284_, p_105285_).getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return true; + if (this.destroyProgress >= 1.0F) { + this.isDestroying = false; + this.startPrediction(this.minecraft.level, p_233739_ -> { +@@ -270,7 +_,7 @@ + + private boolean sameDestroyTarget(BlockPos p_105282_) { + ItemStack itemstack = this.minecraft.player.getMainHandItem(); +- return p_105282_.equals(this.destroyBlockPos) && ItemStack.isSameItemSameComponents(itemstack, this.destroyingItem); ++ return p_105282_.equals(this.destroyBlockPos) && !destroyingItem.shouldCauseBlockBreakReset(itemstack); + } + + private void ensureHasSentCarriedItem() { +@@ -298,12 +_,23 @@ + private InteractionResult performUseItemOn(LocalPlayer p_233747_, InteractionHand p_233748_, BlockHitResult p_233749_) { + BlockPos blockpos = p_233749_.getBlockPos(); + ItemStack itemstack = p_233747_.getItemInHand(p_233748_); ++ var event = net.minecraftforge.event.ForgeEventFactory.onRightClickBlock(p_233747_, p_233748_, blockpos, p_233749_); ++ if (event.isCanceled()) { ++ return event.getCancellationResult(); ++ } + if (this.localPlayerMode == GameType.SPECTATOR) { + return InteractionResult.SUCCESS; + } else { +- boolean flag = !p_233747_.getMainHandItem().isEmpty() || !p_233747_.getOffhandItem().isEmpty(); ++ UseOnContext useoncontext = new UseOnContext(p_233747_, p_233748_, p_233749_); ++ if (event.getUseItem() != net.minecraftforge.eventbus.api.Event.Result.DENY) { ++ InteractionResult result = itemstack.onItemUseFirst(useoncontext); ++ if (result != InteractionResult.PASS) { ++ return result; + } - InteractionResultHolder interactionresultholder = itemstack.use(this.minecraft.level, p_233722_, p_233723_); - ItemStack itemstack1 = interactionresultholder.getObject(); - if (itemstack1 != itemstack) { - p_233722_.setItemInHand(p_233723_, itemstack1); -+ if (itemstack1.isEmpty()) -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(p_233722_, itemstack, p_233723_); - } ++ } ++ boolean flag = !p_233747_.getMainHandItem().doesSneakBypassUse(p_233747_.level(), blockpos, p_233747_) || !p_233747_.getOffhandItem().doesSneakBypassUse(p_233747_.level(), blockpos, p_233747_); + boolean flag1 = p_233747_.isSecondaryUseActive() && flag; +- if (!flag1) { ++ if (event.getUseBlock() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY && !flag1)) { + BlockState blockstate = this.minecraft.level.getBlockState(blockpos); + if (!this.connection.isFeatureEnabled(blockstate.getBlock().requiredFeatures())) { + return InteractionResult.FAIL; +@@ -324,8 +_,10 @@ + } + } - mutableobject.setValue(interactionresultholder.getResult()); -@@ -383,6 +_,9 @@ - this.ensureHasSentCarriedItem(); - Vec3 vec3 = p_105233_.getLocation().subtract(p_105232_.getX(), p_105232_.getY(), p_105232_.getZ()); - this.connection.send(ServerboundInteractPacket.createInteractionPacket(p_105232_, p_105231_.isShiftKeyDown(), p_105234_, vec3)); -+ if (this.localPlayerMode == GameType.SPECTATOR) return InteractionResult.PASS; // don't fire for spectators to match non-specific EntityInteract -+ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onInteractEntityAt(p_105231_, p_105232_, p_105233_, p_105234_); -+ if(cancelResult != null) return cancelResult; - return this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : p_105232_.interactAt(p_105231_, vec3, p_105234_); - } +- if (!itemstack.isEmpty() && !p_233747_.getCooldowns().isOnCooldown(itemstack.getItem())) { +- UseOnContext useoncontext = new UseOnContext(p_233747_, p_233748_, p_233749_); ++ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) { ++ return InteractionResult.PASS; ++ } ++ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (!itemstack.isEmpty() && !p_233747_.getCooldowns().isOnCooldown(itemstack.getItem()))) { + InteractionResult interactionresult1; + if (this.localPlayerMode.isCreative()) { + int i = itemstack.getCount(); +@@ -361,10 +_,18 @@ + mutableobject.setValue(InteractionResult.PASS); + return serverbounduseitempacket; + } else { ++ var event = net.minecraftforge.event.ForgeEventFactory.onRightClickItem(p_233722_, p_233723_); ++ if (event.isCanceled()) { ++ mutableobject.setValue(event.getCancellationResult()); ++ return serverbounduseitempacket; ++ } + InteractionResultHolder interactionresultholder = itemstack.use(this.minecraft.level, p_233722_, p_233723_); + ItemStack itemstack1 = interactionresultholder.getObject(); + if (itemstack1 != itemstack) { + p_233722_.setItemInHand(p_233723_, itemstack1); ++ if (itemstack1.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(p_233722_, itemstack, p_233723_); ++ } + } + + mutableobject.setValue(interactionresultholder.getResult()); +@@ -395,6 +_,10 @@ + public InteractionResult interact(Player p_105227_, Entity p_105228_, InteractionHand p_105229_) { + this.ensureHasSentCarriedItem(); + this.connection.send(ServerboundInteractPacket.createInteractionPacket(p_105228_, p_105227_.isShiftKeyDown(), p_105229_)); ++ if (this.localPlayerMode != GameType.SPECTATOR) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEntityInteract(p_105227_, p_105228_, p_105229_); ++ if (event.isCanceled()) return event.getCancellationResult(); ++ } + return this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : p_105227_.interactOn(p_105228_, p_105229_); + } + +@@ -402,6 +_,10 @@ + this.ensureHasSentCarriedItem(); + Vec3 vec3 = p_105233_.getLocation().subtract(p_105232_.getX(), p_105232_.getY(), p_105232_.getZ()); + this.connection.send(ServerboundInteractPacket.createInteractionPacket(p_105232_, p_105231_.isShiftKeyDown(), p_105234_, vec3)); ++ if (this.localPlayerMode != GameType.SPECTATOR) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEntityInteractSpecific(p_105231_, p_105232_, p_105234_, vec3); ++ if (event.isCanceled()) return event.getCancellationResult(); ++ } + return this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : p_105232_.interactAt(p_105231_, vec3, p_105234_); + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/PlayerInfo.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/PlayerInfo.java.patch index ff5a3676bf..fa8302a828 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/PlayerInfo.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/PlayerInfo.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/multiplayer/PlayerInfo.java +++ b/net/minecraft/client/multiplayer/PlayerInfo.java -@@ -89,6 +_,7 @@ - } +@@ -85,6 +_,7 @@ + } - protected void setGameMode(GameType p_105318_) { -+ net.minecraftforge.client.ForgeHooksClient.onClientChangeGameType(this, this.gameMode, p_105318_); - this.gameMode = p_105318_; - } + protected void setGameMode(GameType p_105318_) { ++ net.minecraftforge.client.ForgeHooksClient.onClientChangeGameType(this, this.gameMode, p_105318_); + this.gameMode = p_105318_; + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ServerData.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ServerData.java.patch index 8805182f74..3f0aa160ed 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ServerData.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ServerData.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/multiplayer/ServerData.java +++ b/net/minecraft/client/multiplayer/ServerData.java -@@ -35,6 +_,7 @@ - private byte[] iconBytes; - private ServerData.Type type; - private boolean enforcesSecureChat; -+ public net.minecraftforge.client.ExtendedServerListData forgeData = null; +@@ -34,6 +_,7 @@ + private byte[] iconBytes; + private ServerData.Type type; + private ServerData.State state = ServerData.State.INITIAL; ++ public net.minecraftforge.client.ExtendedServerListData forgeData = null; - public ServerData(String p_105375_, String p_105376_, ServerData.Type p_297678_) { - this.name = p_105375_; + public ServerData(String p_105375_, String p_105376_, ServerData.Type p_297678_) { + this.name = p_105375_; diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch index 49b9dde926..a3fac87d9d 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/multiplayer/ServerStatusPinger.java +++ b/net/minecraft/client/multiplayer/ServerStatusPinger.java -@@ -103,6 +_,7 @@ - } - - }); -+ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(serverstatus, p_105460_); - this.pingStart = Util.getMillis(); - connection.send(new ServerboundPingRequestPacket(this.pingStart)); - this.success = true; +@@ -98,6 +_,7 @@ + p_105461_.run(); + } + }); ++ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(serverstatus, p_105460_); + this.pingStart = Util.getMillis(); + connection.send(new ServerboundPingRequestPacket(this.pingStart)); + this.success = true; diff --git a/patches/minecraft/net/minecraft/client/multiplayer/TagCollector.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/TagCollector.java.patch new file mode 100644 index 0000000000..7f6bb6942d --- /dev/null +++ b/patches/minecraft/net/minecraft/client/multiplayer/TagCollector.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/client/multiplayer/TagCollector.java ++++ b/net/minecraft/client/multiplayer/TagCollector.java +@@ -23,7 +_,7 @@ + } + + private static void refreshCommonTagDependentData() { +- CreativeModeTabs.searchTab().rebuildSearchTree(); ++ CreativeModeTabs.allTabs().stream().filter(tab -> tab.hasSearchBar()).forEach(tab -> tab.rebuildSearchTree()); + } + + private static void refreshBuiltInTagDependentData() { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch index ccf0c86b17..e664db0f04 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch @@ -1,41 +1,41 @@ --- a/net/minecraft/client/multiplayer/chat/ChatListener.java +++ b/net/minecraft/client/multiplayer/chat/ChatListener.java -@@ -119,7 +_,9 @@ - Instant instant = Instant.now(); - this.handleMessage((MessageSignature)null, () -> { - Component component = p_251256_.decorate(p_250375_); -- this.minecraft.gui.getChat().addMessage(component); -+ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientChat(p_251256_, component, Util.NIL_UUID); -+ if (forgeComponent == null) return false; -+ this.minecraft.gui.getChat().addMessage(forgeComponent); - this.narrateChatMessage(p_251256_, p_250375_); - this.logSystemMessage(component, instant); - this.previousMessageTime = Util.getMillis(); -@@ -136,12 +_,16 @@ - MessageSignature messagesignature = p_249430_.signature(); - FilterMask filtermask = p_249430_.filterMask(); - if (filtermask.isEmpty()) { -- this.minecraft.gui.getChat().addMessage(p_249231_, messagesignature, guimessagetag); -+ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(p_251766_, p_249231_, p_249430_, p_249430_.sender()); +@@ -118,7 +_,9 @@ + Instant instant = Instant.now(); + this.handleMessage(null, () -> { + Component component = p_251256_.decorate(p_250375_); +- this.minecraft.gui.getChat().addMessage(component); ++ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientChat(p_251256_, component, Util.NIL_UUID); + if (forgeComponent == null) return false; -+ this.minecraft.gui.getChat().addMessage(forgeComponent, messagesignature, guimessagetag); - this.narrateChatMessage(p_251766_, p_249430_.decoratedContent()); - } else { - Component component = filtermask.applyWithFormatting(p_249430_.signedContent()); - if (component != null) { -- this.minecraft.gui.getChat().addMessage(p_251766_.decorate(component), messagesignature, guimessagetag); -+ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(p_251766_, p_251766_.decorate(component), p_249430_, p_249430_.sender()); -+ if (forgeComponent == null) return false; -+ this.minecraft.gui.getChat().addMessage(forgeComponent, messagesignature, guimessagetag); - this.narrateChatMessage(p_251766_, component); ++ this.minecraft.gui.getChat().addMessage(forgeComponent); + this.narrateChatMessage(p_251256_, p_250375_); + this.logSystemMessage(component, instant); + this.previousMessageTime = Util.getMillis(); +@@ -137,12 +_,16 @@ + MessageSignature messagesignature = p_249430_.signature(); + FilterMask filtermask = p_249430_.filterMask(); + if (filtermask.isEmpty()) { +- this.minecraft.gui.getChat().addMessage(p_249231_, messagesignature, guimessagetag); ++ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(p_251766_, p_249231_, p_249430_, p_249430_.sender()); ++ if (forgeComponent == null) return false; ++ this.minecraft.gui.getChat().addMessage(forgeComponent, messagesignature, guimessagetag); + this.narrateChatMessage(p_251766_, p_249430_.decoratedContent()); + } else { + Component component = filtermask.applyWithFormatting(p_249430_.signedContent()); + if (component != null) { +- this.minecraft.gui.getChat().addMessage(p_251766_.decorate(component), messagesignature, guimessagetag); ++ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(p_251766_, p_251766_.decorate(component), p_249430_, p_249430_.sender()); ++ if (forgeComponent == null) return false; ++ this.minecraft.gui.getChat().addMessage(forgeComponent, messagesignature, guimessagetag); + this.narrateChatMessage(p_251766_, component); + } } - } -@@ -174,6 +_,8 @@ +@@ -175,6 +_,8 @@ - public void handleSystemMessage(Component p_240522_, boolean p_240642_) { - if (!this.minecraft.options.hideMatchedNames().get() || !this.minecraft.isBlocked(this.guessChatUUID(p_240522_))) { -+ p_240522_ = net.minecraftforge.client.ForgeHooksClient.onClientSystemChat(p_240522_, p_240642_); -+ if (p_240522_ == null) return; - if (p_240642_) { - this.minecraft.gui.setOverlayMessage(p_240522_, false); - } else { + public void handleSystemMessage(Component p_240522_, boolean p_240642_) { + if (!this.minecraft.options.hideMatchedNames().get() || !this.minecraft.isBlocked(this.guessChatUUID(p_240522_))) { ++ p_240522_ = net.minecraftforge.client.ForgeHooksClient.onClientSystemChat(p_240522_, p_240642_, this.minecraft.level.registryAccess()); ++ if (p_240522_ == null) return; + if (p_240642_) { + this.minecraft.gui.setOverlayMessage(p_240522_, false); + } else { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch index 4071d19c54..877930652d 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/multiplayer/resolver/AddressCheck.java +++ b/net/minecraft/client/multiplayer/resolver/AddressCheck.java @@ -16,7 +_,7 @@ - boolean isAllowed(ServerAddress p_171830_); + boolean isAllowed(ServerAddress p_171830_); - static AddressCheck createFromService() { -- final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class)).map(BlockListSupplier::createBlockList).filter(Objects::nonNull).collect(ImmutableList.toImmutableList()); -+ final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class, net.minecraftforge.fml.loading.FMLLoader.class.getClassLoader())).map(BlockListSupplier::createBlockList).filter(Objects::nonNull).collect(ImmutableList.toImmutableList()); - return new AddressCheck() { - public boolean isAllowed(ResolvedServerAddress p_171835_) { - String s = p_171835_.getHostName(); + static AddressCheck createFromService() { +- final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class)) ++ final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class, net.minecraftforge.fml.loading.FMLLoader.class.getClassLoader())) + .map(BlockListSupplier::createBlockList) + .filter(Objects::nonNull) + .collect(ImmutableList.toImmutableList()); diff --git a/patches/minecraft/net/minecraft/client/particle/BreakingItemParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/BreakingItemParticle.java.patch index bf9bb99bb0..a6d25a2790 100644 --- a/patches/minecraft/net/minecraft/client/particle/BreakingItemParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/BreakingItemParticle.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/client/particle/BreakingItemParticle.java +++ b/net/minecraft/client/particle/BreakingItemParticle.java -@@ -31,7 +_,8 @@ +@@ -33,7 +_,8 @@ - protected BreakingItemParticle(ClientLevel p_105665_, double p_105666_, double p_105667_, double p_105668_, ItemStack p_105669_) { - super(p_105665_, p_105666_, p_105667_, p_105668_, 0.0D, 0.0D, 0.0D); -- this.setSprite(Minecraft.getInstance().getItemRenderer().getModel(p_105669_, p_105665_, (LivingEntity)null, 0).getParticleIcon()); -+ var model = Minecraft.getInstance().getItemRenderer().getModel(p_105669_, p_105665_, (LivingEntity)null, 0); -+ this.setSprite(model.getOverrides().resolve(model, p_105669_, p_105665_, null, 0).getParticleIcon(net.minecraftforge.client.model.data.ModelData.EMPTY)); - this.gravity = 1.0F; - this.quadSize /= 2.0F; - this.uo = this.random.nextFloat() * 3.0F; + protected BreakingItemParticle(ClientLevel p_105665_, double p_105666_, double p_105667_, double p_105668_, ItemStack p_105669_) { + super(p_105665_, p_105666_, p_105667_, p_105668_, 0.0, 0.0, 0.0); +- this.setSprite(Minecraft.getInstance().getItemRenderer().getModel(p_105669_, p_105665_, null, 0).getParticleIcon()); ++ var model = Minecraft.getInstance().getItemRenderer().getModel(p_105669_, p_105665_, null, 0); ++ this.setSprite(model.getOverrides().resolve(model, p_105669_, p_105665_, null, 0).getParticleIcon(net.minecraftforge.client.model.data.ModelData.EMPTY)); + this.gravity = 1.0F; + this.quadSize /= 2.0F; + this.uo = this.random.nextFloat() * 3.0F; diff --git a/patches/minecraft/net/minecraft/client/particle/EnchantmentTableParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/EnchantmentTableParticle.java.patch deleted file mode 100644 index 3b544f4de4..0000000000 --- a/patches/minecraft/net/minecraft/client/particle/EnchantmentTableParticle.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/client/particle/EnchantmentTableParticle.java -+++ b/net/minecraft/client/particle/EnchantmentTableParticle.java -@@ -73,6 +_,7 @@ - this.x = this.xStart + this.xd * (double)f; - this.y = this.yStart + this.yd * (double)f - (double)(f1 * 1.2F); - this.z = this.zStart + this.zd * (double)f; -+ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box - } - } - diff --git a/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch index ab8e661bec..dc8fb908f3 100644 --- a/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch @@ -1,31 +1,13 @@ --- a/net/minecraft/client/particle/FireworkParticles.java +++ b/net/minecraft/client/particle/FireworkParticles.java -@@ -172,7 +_,7 @@ - } else { - for(int i = 0; i < this.explosions.size(); ++i) { - CompoundTag compoundtag = this.explosions.getCompound(i); -- if (FireworkRocketItem.Shape.byId(compoundtag.getByte("Type")) == FireworkRocketItem.Shape.LARGE_BALL) { -+ if (FireworkRocketItem.Shape.getShape(compoundtag) == FireworkRocketItem.Shape.LARGE_BALL) { - flag1 = true; - break; - } -@@ -192,7 +_,7 @@ - if (this.life % 2 == 0 && this.explosions != null && this.life / 2 < this.explosions.size()) { - int k = this.life / 2; - CompoundTag compoundtag1 = this.explosions.getCompound(k); -- FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.byId(compoundtag1.getByte("Type")); -+ FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.getShape(compoundtag1); - boolean flag4 = compoundtag1.getBoolean("Trail"); - boolean flag2 = compoundtag1.getBoolean("Flicker"); - int[] aint = compoundtag1.getIntArray("Colors"); -@@ -201,6 +_,10 @@ - aint = new int[]{DyeColor.BLACK.getFireworkColor()}; - } +@@ -263,6 +_,10 @@ + intlist = IntList.of(DyeColor.BLACK.getFireworkColor()); + } -+ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(fireworkrocketitem$shape); -+ if (factory != null) -+ factory.build(this, flag4, flag2, aint, aint1); -+ else - switch (fireworkrocketitem$shape) { - case SMALL_BALL: - default: ++ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(fireworkexplosion1.shape()); ++ if (factory != null) ++ factory.build(this, flag3, flag4, intlist.toIntArray(), intlist1.toIntArray()); ++ else + switch (fireworkexplosion1.shape()) { + case SMALL_BALL: + this.createParticleBall(0.25, 2, intlist, intlist1, flag3, flag4); diff --git a/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch new file mode 100644 index 0000000000..40c1bc8c52 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch @@ -0,0 +1,10 @@ +--- a/net/minecraft/client/particle/FlyTowardsPositionParticle.java ++++ b/net/minecraft/client/particle/FlyTowardsPositionParticle.java +@@ -104,6 +_,7 @@ + this.x = this.xStart + this.xd * (double)f; + this.y = this.yStart + this.yd * (double)f - (double)(f1 * 1.2F); + this.z = this.zStart + this.zd * (double)f; ++ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box + } + } + diff --git a/patches/minecraft/net/minecraft/client/particle/Particle.java.patch b/patches/minecraft/net/minecraft/client/particle/Particle.java.patch index 14ac803347..f54bdd700c 100644 --- a/patches/minecraft/net/minecraft/client/particle/Particle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/Particle.java.patch @@ -1,10 +1,9 @@ --- a/net/minecraft/client/particle/Particle.java +++ b/net/minecraft/client/particle/Particle.java -@@ -226,4 +_,16 @@ - public Optional getParticleGroup() { - return Optional.empty(); - } -+ +@@ -243,6 +_,18 @@ + return Optional.empty(); + } + + /** + * Forge added method that controls if a particle should be culled to it's bounding box. + * Default behaviour is culling enabled @@ -16,4 +15,7 @@ + public net.minecraft.world.phys.Vec3 getPos() { + return new net.minecraft.world.phys.Vec3(this.x, this.y, this.z); + } - } ++ + @OnlyIn(Dist.CLIENT) + public static record LifetimeAlpha(float startAlpha, float endAlpha, float startAtNormalizedAge, float endAtNormalizedAge) { + public static final Particle.LifetimeAlpha ALWAYS_OPAQUE = new Particle.LifetimeAlpha(1.0F, 1.0F, 0.0F, 1.0F); diff --git a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch index a732089a88..b8babe3ac5 100644 --- a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch @@ -1,127 +1,124 @@ --- a/net/minecraft/client/particle/ParticleEngine.java +++ b/net/minecraft/client/particle/ParticleEngine.java -@@ -74,11 +_,11 @@ - private static final int MAX_PARTICLES_PER_LAYER = 16384; - private static final List RENDER_ORDER = ImmutableList.of(ParticleRenderType.TERRAIN_SHEET, ParticleRenderType.PARTICLE_SHEET_OPAQUE, ParticleRenderType.PARTICLE_SHEET_LIT, ParticleRenderType.PARTICLE_SHEET_TRANSLUCENT, ParticleRenderType.CUSTOM); - protected ClientLevel level; -- private final Map> particles = Maps.newIdentityHashMap(); -+ private final Map> particles = Maps.newTreeMap(net.minecraftforge.client.ForgeHooksClient.makeParticleRenderTypeComparator(RENDER_ORDER)); - private final Queue trackingEmitters = Queues.newArrayDeque(); - private final TextureManager textureManager; - private final RandomSource random = RandomSource.create(); -- private final Int2ObjectMap> providers = new Int2ObjectOpenHashMap<>(); -+ private final Map> providers = new java.util.HashMap<>(); - private final Queue particlesToAdd = Queues.newArrayDeque(); - private final Map spriteSets = Maps.newHashMap(); - private final TextureAtlas textureAtlas; -@@ -200,10 +_,14 @@ - this.register(ParticleTypes.TRIAL_SPAWNER_DETECTION, TrialSpawnerDetectionParticle.Provider::new); - } +@@ -75,11 +_,11 @@ + ParticleRenderType.TERRAIN_SHEET, ParticleRenderType.PARTICLE_SHEET_OPAQUE, ParticleRenderType.PARTICLE_SHEET_LIT, ParticleRenderType.PARTICLE_SHEET_TRANSLUCENT, ParticleRenderType.CUSTOM + ); + protected ClientLevel level; +- private final Map> particles = Maps.newIdentityHashMap(); ++ private final Map> particles = Maps.newTreeMap(net.minecraftforge.client.ForgeHooksClient.makeParticleRenderTypeComparator(RENDER_ORDER)); + private final Queue trackingEmitters = Queues.newArrayDeque(); + private final TextureManager textureManager; + private final RandomSource random = RandomSource.create(); +- private final Int2ObjectMap> providers = new Int2ObjectOpenHashMap<>(); ++ private final Map> providers = new java.util.HashMap<>(); + private final Queue particlesToAdd = Queues.newArrayDeque(); + private final Map spriteSets = Maps.newHashMap(); + private final TextureAtlas textureAtlas; +@@ -210,10 +_,14 @@ + this.register(ParticleTypes.OMINOUS_SPAWNING, FlyStraightTowardsParticle.OminousSpawnProvider::new); + } -+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ -+ @Deprecated - public void register(ParticleType p_107382_, ParticleProvider p_107383_) { -- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(p_107382_), p_107383_); -+ this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107382_), p_107383_); - } ++ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ ++ @Deprecated + public void register(ParticleType p_107382_, ParticleProvider p_107383_) { +- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(p_107382_), p_107383_); ++ this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107382_), p_107383_); + } -+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ -+ @Deprecated - public void register(ParticleType p_273423_, ParticleProvider.Sprite p_273134_) { - this.register(p_273423_, (p_272320_) -> { - return (p_272323_, p_272324_, p_272325_, p_272326_, p_272327_, p_272328_, p_272329_, p_272330_) -> { -@@ -217,10 +_,12 @@ - }); - } ++ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ ++ @Deprecated + public void register(ParticleType p_273423_, ParticleProvider.Sprite p_273134_) { + this.register( + p_273423_, +@@ -230,10 +_,12 @@ + ); + } -+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ -+ @Deprecated - public void register(ParticleType p_107379_, ParticleEngine.SpriteParticleRegistration p_107380_) { - ParticleEngine.MutableSpriteSet particleengine$mutablespriteset = new ParticleEngine.MutableSpriteSet(); - this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107379_), particleengine$mutablespriteset); -- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(p_107379_), p_107380_.create(particleengine$mutablespriteset)); -+ this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107379_), p_107380_.create(particleengine$mutablespriteset)); - } ++ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ ++ @Deprecated + public void register(ParticleType p_107379_, ParticleEngine.SpriteParticleRegistration p_107380_) { + ParticleEngine.MutableSpriteSet particleengine$mutablespriteset = new ParticleEngine.MutableSpriteSet(); + this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107379_), particleengine$mutablespriteset); +- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(p_107379_), p_107380_.create(particleengine$mutablespriteset)); ++ this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107379_), p_107380_.create(particleengine$mutablespriteset)); + } - public CompletableFuture reload(PreparableReloadListener.PreparationBarrier p_107305_, ResourceManager p_107306_, ProfilerFiller p_107307_, ProfilerFiller p_107308_, Executor p_107309_, Executor p_107310_) { -@@ -319,7 +_,7 @@ + @Override +@@ -359,7 +_,7 @@ + private Particle makeParticle( + T p_107396_, double p_107397_, double p_107398_, double p_107399_, double p_107400_, double p_107401_, double p_107402_ + ) { +- ParticleProvider particleprovider = (ParticleProvider)this.providers.get(BuiltInRegistries.PARTICLE_TYPE.getId(p_107396_.getType())); ++ ParticleProvider particleprovider = (ParticleProvider)this.providers.get(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107396_.getType())); + return particleprovider == null + ? null + : particleprovider.createParticle(p_107396_, this.level, p_107397_, p_107398_, p_107399_, p_107400_, p_107401_, p_107402_); +@@ -435,11 +_,19 @@ + } + } - @Nullable - private Particle makeParticle(T p_107396_, double p_107397_, double p_107398_, double p_107399_, double p_107400_, double p_107401_, double p_107402_) { -- ParticleProvider particleprovider = (ParticleProvider)this.providers.get(BuiltInRegistries.PARTICLE_TYPE.getId(p_107396_.getType())); -+ ParticleProvider particleprovider = (ParticleProvider)this.providers.get(BuiltInRegistries.PARTICLE_TYPE.getKey(p_107396_.getType())); - return particleprovider == null ? null : particleprovider.createParticle(p_107396_, this.level, p_107397_, p_107398_, p_107399_, p_107400_, p_107401_, p_107402_); - } - -@@ -400,15 +_,24 @@ - } - } - -+ /**@deprecated Forge: use {@link #render(PoseStack, MultiBufferSource.BufferSource, LightTexture, Camera, float, net.minecraft.client.renderer.culling.Frustum)} with Frustum as additional parameter*/ -+ @Deprecated - public void render(PoseStack p_107337_, MultiBufferSource.BufferSource p_107338_, LightTexture p_107339_, Camera p_107340_, float p_107341_) { -+ render(p_107337_, p_107338_, p_107339_, p_107340_, p_107341_, null); -+ } + -+ public void render(PoseStack p_107337_, MultiBufferSource.BufferSource p_107338_, LightTexture p_107339_, Camera p_107340_, float p_107341_, @Nullable net.minecraft.client.renderer.culling.Frustum clippingHelper) { - p_107339_.turnOnLightLayer(); - RenderSystem.enableDepthTest(); -+ RenderSystem.activeTexture(org.lwjgl.opengl.GL13.GL_TEXTURE2); -+ RenderSystem.activeTexture(org.lwjgl.opengl.GL13.GL_TEXTURE0); - PoseStack posestack = RenderSystem.getModelViewStack(); - posestack.pushPose(); - posestack.mulPoseMatrix(p_107337_.last().pose()); - RenderSystem.applyModelViewMatrix(); ++ /**@deprecated Forge: use {@link #render(LightTexture, Camera, float, net.minecraft.client.renderer.culling.Frustum)} with Frustum as additional parameter*/ ++ @Deprecated + public void render(LightTexture p_107339_, Camera p_107340_, float p_107341_) { ++ render(p_107339_, p_107340_, p_107341_); ++ } ++ ++ public void render(LightTexture p_107339_, Camera p_107340_, float p_107341_, @Nullable net.minecraft.client.renderer.culling.Frustum frustum) { + p_107339_.turnOnLightLayer(); + RenderSystem.enableDepthTest(); -- for(ParticleRenderType particlerendertype : RENDER_ORDER) { -+ for(ParticleRenderType particlerendertype : this.particles.keySet()) { // Forge: allow custom IParticleRenderType's -+ if (particlerendertype == ParticleRenderType.NO_RENDER) continue; - Iterable iterable = this.particles.get(particlerendertype); - if (iterable != null) { - RenderSystem.setShader(GameRenderer::getParticleShader); -@@ -417,6 +_,7 @@ - particlerendertype.begin(bufferbuilder, this.textureManager); +- for (ParticleRenderType particlerendertype : RENDER_ORDER) { ++ for (ParticleRenderType particlerendertype : this.particles.keySet()) { // Forge: allow custom IParticleRenderType's ++ if (particlerendertype == ParticleRenderType.NO_RENDER) continue; + Iterable iterable = this.particles.get(particlerendertype); + if (iterable != null) { + RenderSystem.setShader(GameRenderer::getParticleShader); +@@ -448,6 +_,7 @@ + particlerendertype.begin(bufferbuilder, this.textureManager); - for(Particle particle : iterable) { -+ if (clippingHelper != null && particle.shouldCull() && !clippingHelper.isVisible(particle.getBoundingBox())) continue; - try { - particle.render(bufferbuilder, p_107340_, p_107341_); - } catch (Throwable throwable) { -@@ -446,7 +_,7 @@ - } + for (Particle particle : iterable) { ++ if (frustum != null && particle.shouldCull() && !frustum.isVisible(particle.getBoundingBox())) continue; + try { + particle.render(bufferbuilder, p_107340_, p_107341_); + } catch (Throwable throwable) { +@@ -475,7 +_,7 @@ + } - public void destroy(BlockPos p_107356_, BlockState p_107357_) { -- if (!p_107357_.isAir() && p_107357_.shouldSpawnTerrainParticles()) { -+ if (!p_107357_.isAir() && !net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_107357_).addDestroyEffects(p_107357_, this.level, p_107356_, this)) { - VoxelShape voxelshape = p_107357_.getShape(this.level, p_107356_); - double d0 = 0.25D; - voxelshape.forAllBoxes((p_172273_, p_172274_, p_172275_, p_172276_, p_172277_, p_172278_) -> { -@@ -466,7 +_,7 @@ - double d7 = d4 * d1 + p_172273_; - double d8 = d5 * d2 + p_172274_; - double d9 = d6 * d3 + p_172275_; -- this.add(new TerrainParticle(this.level, (double)p_107356_.getX() + d7, (double)p_107356_.getY() + d8, (double)p_107356_.getZ() + d9, d4 - 0.5D, d5 - 0.5D, d6 - 0.5D, p_107357_, p_107356_)); -+ this.add(new TerrainParticle(this.level, (double)p_107356_.getX() + d7, (double)p_107356_.getY() + d8, (double)p_107356_.getZ() + d9, d4 - 0.5D, d5 - 0.5D, d6 - 0.5D, p_107357_, p_107356_).updateSprite(p_107357_, p_107356_)); - } - } + public void destroy(BlockPos p_107356_, BlockState p_107357_) { +- if (!p_107357_.isAir() && p_107357_.shouldSpawnTerrainParticles()) { ++ if (!p_107357_.isAir() && !net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_107357_).addDestroyEffects(p_107357_, this.level, p_107356_, this)) { + VoxelShape voxelshape = p_107357_.getShape(this.level, p_107356_); + double d0 = 0.25; + voxelshape.forAllBoxes( +@@ -508,6 +_,7 @@ + p_107357_, + p_107356_ + ) ++ .updateSprite(p_107357_, p_107356_) + ); + } + } +@@ -517,6 +_,13 @@ + } + } + ++ public void addBlockHitEffects(BlockPos pos, net.minecraft.world.phys.BlockHitResult target) { ++ var state = level.getBlockState(pos); ++ if (!net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(state).addHitEffects(state, level, target, this)) ++ crack(pos, target.getDirection()); ++ } ++ ++ @Deprecated // Forge - Use addBlockHitEffects as it has more context and gives more control to modders + public void crack(BlockPos p_107368_, Direction p_107369_) { + BlockState blockstate = this.level.getBlockState(p_107368_); + if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.shouldSpawnTerrainParticles()) { +@@ -552,7 +_,7 @@ + d0 = (double)i + aabb.maxX + 0.1F; } -@@ -510,12 +_,18 @@ - d0 = (double)i + aabb.maxX + (double)0.1F; - } -- this.add((new TerrainParticle(this.level, d0, d1, d2, 0.0D, 0.0D, 0.0D, blockstate, p_107368_)).setPower(0.2F).scale(0.6F)); -+ this.add((new TerrainParticle(this.level, d0, d1, d2, 0.0D, 0.0D, 0.0D, blockstate, p_107368_).updateSprite(blockstate, p_107368_)).setPower(0.2F).scale(0.6F)); - } - } +- this.add(new TerrainParticle(this.level, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, p_107368_).setPower(0.2F).scale(0.6F)); ++ this.add(new TerrainParticle(this.level, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, p_107368_).updateSprite(blockstate, p_107368_).setPower(0.2F).scale(0.6F)); + } + } - public String countParticles() { - return String.valueOf(this.particles.values().stream().mapToInt(Collection::size).sum()); -+ } -+ -+ public void addBlockHitEffects(BlockPos pos, net.minecraft.world.phys.BlockHitResult target) { -+ BlockState state = level.getBlockState(pos); -+ if (!net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(state).addHitEffects(state, level, target, this)) -+ crack(pos, target.getDirection()); - } - - private boolean hasSpaceInParticleLimit(ParticleGroup p_172280_) { diff --git a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch index 54b20e2c35..96641fc25c 100644 --- a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/particle/PortalParticle.java +++ b/net/minecraft/client/particle/PortalParticle.java -@@ -75,6 +_,7 @@ - this.x = this.xStart + this.xd * (double)f2; - this.y = this.yStart + this.yd * (double)f2 + (double)(1.0F - f); - this.z = this.zStart + this.zd * (double)f2; -+ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box - } - } +@@ -80,6 +_,7 @@ + this.x = this.xStart + this.xd * (double)f2; + this.y = this.yStart + this.yd * (double)f2 + (double)(1.0F - f); + this.z = this.zStart + this.zd * (double)f2; ++ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box + } + } diff --git a/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch index c40cefa0c2..3833e0a3f8 100644 --- a/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/particle/ReversePortalParticle.java +++ b/net/minecraft/client/particle/ReversePortalParticle.java -@@ -29,6 +_,7 @@ - this.x += this.xd * (double)f; - this.y += this.yd * (double)f; - this.z += this.zd * (double)f; -+ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box - } - } +@@ -31,6 +_,7 @@ + this.x = this.x + this.xd * (double)f; + this.y = this.y + this.yd * (double)f; + this.z = this.z + this.zd * (double)f; ++ this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box + } + } diff --git a/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch index c12e57f805..9f31fbf65e 100644 --- a/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch @@ -1,26 +1,28 @@ --- a/net/minecraft/client/particle/TerrainParticle.java +++ b/net/minecraft/client/particle/TerrainParticle.java -@@ -28,7 +_,7 @@ - this.rCol = 0.6F; - this.gCol = 0.6F; - this.bCol = 0.6F; -- if (!p_172458_.is(Blocks.GRASS_BLOCK)) { -+ if (net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_172458_).areBreakingParticlesTinted(p_172458_, p_172451_, p_172459_)) { - int i = Minecraft.getInstance().getBlockColors().getColor(p_172458_, p_172451_, p_172459_, 0); - this.rCol *= (float)(i >> 16 & 255) / 255.0F; - this.gCol *= (float)(i >> 8 & 255) / 255.0F; -@@ -69,7 +_,13 @@ - public static class Provider implements ParticleProvider { - public Particle createParticle(BlockParticleOption p_108304_, ClientLevel p_108305_, double p_108306_, double p_108307_, double p_108308_, double p_108309_, double p_108310_, double p_108311_) { - BlockState blockstate = p_108304_.getState(); -- return !blockstate.isAir() && !blockstate.is(Blocks.MOVING_PISTON) && blockstate.shouldSpawnTerrainParticles() ? new TerrainParticle(p_108305_, p_108306_, p_108307_, p_108308_, p_108309_, p_108310_, p_108311_, blockstate) : null; -+ return !blockstate.isAir() && !blockstate.is(Blocks.MOVING_PISTON) ? (new TerrainParticle(p_108305_, p_108306_, p_108307_, p_108308_, p_108309_, p_108310_, p_108311_, blockstate)).updateSprite(blockstate, p_108304_.getPos()) : null; - } -+ } +@@ -41,7 +_,7 @@ + this.rCol = 0.6F; + this.gCol = 0.6F; + this.bCol = 0.6F; +- if (!p_172458_.is(Blocks.GRASS_BLOCK)) { ++ if (net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_172458_).areBreakingParticlesTinted(p_172458_, p_172451_, p_172459_)) { + int i = Minecraft.getInstance().getBlockColors().getColor(p_172458_, p_172451_, p_172459_, 0); + this.rCol *= (float)(i >> 16 & 0xFF) / 255.0F; + this.gCol *= (float)(i >> 8 & 0xFF) / 255.0F; +@@ -97,9 +_,15 @@ + ) { + BlockState blockstate = p_331600_.getState(); + return !blockstate.isAir() && !blockstate.is(Blocks.MOVING_PISTON) && blockstate.shouldSpawnTerrainParticles() +- ? new TerrainParticle(p_334810_, p_328897_, p_329583_, p_331123_, p_333546_, p_335782_, p_335068_, blockstate) ++ ? (TerrainParticle)new TerrainParticle(p_334810_, p_328897_, p_329583_, p_331123_, p_333546_, p_335782_, p_335068_, blockstate).updateSprite(blockstate, p_331600_.getPos()) + : null; + } + -+ public Particle updateSprite(BlockState state, BlockPos pos) { //FORGE: we cannot assume that the x y z of the particles match the block pos of the block. -+ if (pos != null) // There are cases where we are not able to obtain the correct source pos, and need to fallback to the non-model data version -+ this.setSprite(Minecraft.getInstance().getBlockRenderer().getBlockModelShaper().getTexture(state, level, pos)); -+ return this; - } - } ++ public Particle updateSprite(BlockState state, BlockPos pos) { //FORGE: we cannot assume that the x y z of the particles match the block pos of the block. ++ if (pos != null) // There are cases where we are not able to obtain the correct source pos, and need to fallback to the non-model data version ++ this.setSprite(Minecraft.getInstance().getBlockRenderer().getBlockModelShaper().getTexture(state, level, pos)); ++ return this; ++ } + + @OnlyIn(Dist.CLIENT) + public static class DustPillarProvider implements ParticleProvider { diff --git a/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch index a40faef8ef..3f197b20ef 100644 --- a/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/particle/VibrationSignalParticle.java +++ b/net/minecraft/client/particle/VibrationSignalParticle.java -@@ -105,6 +_,7 @@ - this.x = Mth.lerp(d0, this.x, vec3.x()); - this.y = Mth.lerp(d0, this.y, vec3.y()); - this.z = Mth.lerp(d0, this.z, vec3.z()); -+ this.setPos(this.x, this.y, this.z); // FORGE: Update the particle's bounding box - double d1 = this.x - vec3.x(); - double d2 = this.y - vec3.y(); - double d3 = this.z - vec3.z(); +@@ -122,6 +_,7 @@ + this.x = Mth.lerp(d0, this.x, vec3.x()); + this.y = Mth.lerp(d0, this.y, vec3.y()); + this.z = Mth.lerp(d0, this.z, vec3.z()); ++ this.setPos(this.x, this.y, this.z); // FORGE: Update the particle's bounding box + double d1 = this.x - vec3.x(); + double d2 = this.y - vec3.y(); + double d3 = this.z - vec3.z(); diff --git a/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch b/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch index 69a063848c..8747dd2c13 100644 --- a/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/player/AbstractClientPlayer.java +++ b/net/minecraft/client/player/AbstractClientPlayer.java -@@ -93,6 +_,6 @@ - } - } +@@ -96,6 +_,6 @@ + } + } -- return Mth.lerp(Minecraft.getInstance().options.fovEffectScale().get().floatValue(), 1.0F, f); -+ return net.minecraftforge.client.ForgeHooksClient.getFieldOfViewModifier(this, f); - } +- return Mth.lerp(Minecraft.getInstance().options.fovEffectScale().get().floatValue(), 1.0F, f); ++ return net.minecraftforge.client.ForgeHooksClient.getFieldOfViewModifier(this, f); + } } diff --git a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch index 17420a333b..f1dab83f72 100644 --- a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch @@ -1,116 +1,112 @@ --- a/net/minecraft/client/player/LocalPlayer.java +++ b/net/minecraft/client/player/LocalPlayer.java -@@ -150,6 +_,7 @@ - } +@@ -160,6 +_,7 @@ - public boolean hurt(DamageSource p_108662_, float p_108663_) { -+ net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, p_108662_, p_108663_); - return false; - } + @Override + public boolean hurt(DamageSource p_108662_, float p_108663_) { ++ net.minecraftforge.event.ForgeEventFactory.onLivingAttackEntity(this, p_108662_, p_108663_); + return false; + } -@@ -276,6 +_,7 @@ +@@ -303,6 +_,7 @@ + ServerboundPlayerActionPacket.Action serverboundplayeractionpacket$action = p_108701_ + ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS + : ServerboundPlayerActionPacket.Action.DROP_ITEM; ++ if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (p_108701_ || getUseItem().getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the clientside + ItemStack itemstack = this.getInventory().removeFromSelected(p_108701_); + this.connection.send(new ServerboundPlayerActionPacket(serverboundplayeractionpacket$action, BlockPos.ZERO, Direction.DOWN)); + return !itemstack.isEmpty(); +@@ -505,7 +_,11 @@ - public boolean drop(boolean p_108701_) { - ServerboundPlayerActionPacket.Action serverboundplayeractionpacket$action = p_108701_ ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS : ServerboundPlayerActionPacket.Action.DROP_ITEM; -+ if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (p_108701_ || getUseItem().getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the clientside - ItemStack itemstack = this.getInventory().removeFromSelected(p_108701_); - this.connection.send(new ServerboundPlayerActionPacket(serverboundplayeractionpacket$action, BlockPos.ZERO, Direction.DOWN)); - return !itemstack.isEmpty(); -@@ -457,7 +_,14 @@ - } - - public void playSound(SoundEvent p_108651_, float p_108652_, float p_108653_) { -- this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), p_108651_, this.getSoundSource(), p_108652_, p_108653_, false); -+ net.minecraft.core.Holder holder = net.minecraft.core.registries.BuiltInRegistries.SOUND_EVENT.wrapAsHolder(p_108651_); -+ net.minecraftforge.event.PlayLevelSoundEvent.AtEntity event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(this, holder, this.getSoundSource(), p_108652_, p_108653_); -+ if (event.isCanceled() || event.getSound() == null) return; -+ p_108651_ = event.getSound().get(); -+ SoundSource source = event.getSource(); -+ p_108652_ = event.getNewVolume(); -+ p_108653_ = event.getNewPitch(); -+ this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), p_108651_, source, p_108652_, p_108653_, false); - } - - public void playNotifySound(SoundEvent p_108655_, SoundSource p_108656_, float p_108657_, float p_108658_) { -@@ -631,6 +_,7 @@ - this.crouching = !this.getAbilities().flying && !this.isSwimming() && !this.isPassenger() && this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.CROUCHING) && (this.isShiftKeyDown() || !this.isSleeping() && !this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.STANDING)); - float f = Mth.clamp(0.3F + EnchantmentHelper.getSneakingSpeedBonus(this), 0.0F, 1.0F); - this.input.tick(this.isMovingSlowly(), f); -+ net.minecraftforge.client.ForgeHooksClient.onMovementInputUpdate(this, this.input); - this.minecraft.getTutorial().onInput(this.input); - if (this.isUsingItem() && !this.isPassenger()) { - this.input.leftImpulse *= 0.2F; -@@ -659,7 +_,7 @@ - boolean flag4 = this.canStartSprinting(); - boolean flag5 = this.isPassenger() ? this.getVehicle().onGround() : this.onGround(); - boolean flag6 = !flag1 && !flag2; -- if ((flag5 || this.isUnderWater()) && flag6 && flag4) { -+ if ((flag5 || this.isUnderWater() || this.canStartSwimming()) && flag6 && flag4) { - if (this.sprintTriggerTime <= 0 && !this.minecraft.options.keySprint.isDown()) { - this.sprintTriggerTime = 7; - } else { -@@ -667,15 +_,15 @@ - } - } - -- if ((!this.isInWater() || this.isUnderWater()) && flag4 && this.minecraft.options.keySprint.isDown()) { -+ if (!this.isSprinting() && (!(this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType))) || (this.isUnderWater() || this.canStartSwimming())) && this.hasEnoughImpulseToStartSprinting() && flag4 && !this.isUsingItem() && !this.hasEffect(MobEffects.BLINDNESS) && this.minecraft.options.keySprint.isDown()) { - this.setSprinting(true); - } - - if (this.isSprinting()) { - boolean flag7 = !this.input.hasForwardImpulse() || !this.hasEnoughFoodToStartSprinting(); -- boolean flag8 = flag7 || this.horizontalCollision && !this.minorHorizontalCollision || this.isInWater() && !this.isUnderWater(); -+ boolean flag8 = flag7 || this.horizontalCollision && !this.minorHorizontalCollision || this.isInWater() && !this.isUnderWater() || (this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)) && !this.canStartSwimming()); - if (this.isSwimming()) { -- if (!this.onGround() && !this.input.shiftKeyDown && flag7 || !this.isInWater()) { -+ if (!this.onGround() && !this.input.shiftKeyDown && flag7 || !(this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)))) { - this.setSprinting(false); - } - } else if (flag8) { -@@ -705,14 +_,15 @@ - - if (this.input.jumping && !flag9 && !flag && !this.getAbilities().flying && !this.isPassenger() && !this.onClimbable()) { - ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); -- if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack) && this.tryToStartFallFlying()) { -+ if (itemstack.canElytraFly(this) && this.tryToStartFallFlying()) { - this.connection.send(new ServerboundPlayerCommandPacket(this, ServerboundPlayerCommandPacket.Action.START_FALL_FLYING)); - } - } - - this.wasFallFlying = this.isFallFlying(); -- if (this.isInWater() && this.input.shiftKeyDown && this.isAffectedByFluids()) { -- this.goDownInWater(); -+ net.minecraftforge.fluids.FluidType fluidType = this.getMaxHeightFluidType(); -+ if ((this.isInWater() || (!fluidType.isAir() && this.canSwimInFluidType(fluidType))) && this.input.shiftKeyDown && this.isAffectedByFluids()) { -+ this.sinkInFluid(this.isInWater() ? net.minecraftforge.common.ForgeMod.WATER_TYPE.get() : fluidType); - } - - if (this.isEyeInFluid(FluidTags.WATER)) { -@@ -812,6 +_,7 @@ - - public void rideTick() { - super.rideTick(); -+ if (this.wantsToStopRiding() && this.isPassenger()) this.input.shiftKeyDown = false; - this.handsBusy = false; - Entity entity = this.getControlledVehicle(); - if (entity instanceof Boat boat) { -@@ -1044,6 +_,18 @@ - } else { - return super.getRopeHoldPosition(p_108758_); - } -+ } + @Override + public void playSound(SoundEvent p_108651_, float p_108652_, float p_108653_) { +- this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), p_108651_, this.getSoundSource(), p_108652_, p_108653_, false); ++ var holder = net.minecraft.core.registries.BuiltInRegistries.SOUND_EVENT.wrapAsHolder(p_108651_); ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(this, holder, this.getSoundSource(), p_108652_, p_108653_); ++ if (event.isCanceled() || event.getSound() == null) return; ++ this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), event.getSound().get(), event.getSource(), event.getNewVolume(), event.getNewPitch(), false); + -+ public void updateSyncFields(LocalPlayer old) { -+ this.xLast = old.xLast; -+ this.yLast1 = old.yLast1; -+ this.zLast = old.zLast; -+ this.yRotLast = old.yRotLast; -+ this.xRotLast = old.xRotLast; -+ this.lastOnGround = old.lastOnGround; -+ this.wasShiftKeyDown = old.wasShiftKeyDown; -+ this.wasSprinting = old.wasSprinting; -+ this.positionReminder = old.positionReminder; - } + } - public void updateTutorialInventoryAction(ItemStack p_172532_, ItemStack p_172533_, ClickAction p_172534_) { + @Override +@@ -697,6 +_,7 @@ + && (this.isShiftKeyDown() || !this.isSleeping() && !this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.STANDING)); + float f = Mth.clamp(0.3F + EnchantmentHelper.getSneakingSpeedBonus(this), 0.0F, 1.0F); + this.input.tick(this.isMovingSlowly(), f); ++ net.minecraftforge.client.ForgeHooksClient.onMovementInputUpdate(this, this.input); + this.minecraft.getTutorial().onInput(this.input); + if (this.isUsingItem() && !this.isPassenger()) { + this.input.leftImpulse *= 0.2F; +@@ -725,7 +_,7 @@ + boolean flag4 = this.canStartSprinting(); + boolean flag5 = this.isPassenger() ? this.getVehicle().onGround() : this.onGround(); + boolean flag6 = !flag1 && !flag2; +- if ((flag5 || this.isUnderWater()) && flag6 && flag4) { ++ if ((flag5 || this.isUnderWater() || this.canStartSwimming()) && flag6 && flag4) { + if (this.sprintTriggerTime <= 0 && !this.minecraft.options.keySprint.isDown()) { + this.sprintTriggerTime = 7; + } else { +@@ -733,15 +_,15 @@ + } + } + +- if ((!this.isInWater() || this.isUnderWater()) && flag4 && this.minecraft.options.keySprint.isDown()) { ++ if (!this.isSprinting() && (!(this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType))) || (this.isUnderWater() || this.canStartSwimming())) && this.hasEnoughImpulseToStartSprinting() && flag4 && !this.isUsingItem() && !this.hasEffect(MobEffects.BLINDNESS) && this.minecraft.options.keySprint.isDown()) { + this.setSprinting(true); + } + + if (this.isSprinting()) { + boolean flag7 = !this.input.hasForwardImpulse() || !this.hasEnoughFoodToStartSprinting(); +- boolean flag8 = flag7 || this.horizontalCollision && !this.minorHorizontalCollision || this.isInWater() && !this.isUnderWater(); ++ boolean flag8 = flag7 || this.horizontalCollision && !this.minorHorizontalCollision || this.isInWater() && !this.isUnderWater() || (this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)) && !this.canStartSwimming()); + if (this.isSwimming()) { +- if (!this.onGround() && !this.input.shiftKeyDown && flag7 || !this.isInWater()) { ++ if (!this.onGround() && !this.input.shiftKeyDown && flag7 || !(this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)))) { + this.setSprinting(false); + } + } else if (flag8) { +@@ -775,14 +_,15 @@ + + if (this.input.jumping && !flag9 && !flag && !abilities.flying && !this.isPassenger() && !this.onClimbable()) { + ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); +- if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack) && this.tryToStartFallFlying()) { ++ if (itemstack.canElytraFly(this) && this.tryToStartFallFlying()) { + this.connection.send(new ServerboundPlayerCommandPacket(this, ServerboundPlayerCommandPacket.Action.START_FALL_FLYING)); + } + } + + this.wasFallFlying = this.isFallFlying(); +- if (this.isInWater() && this.input.shiftKeyDown && this.isAffectedByFluids()) { +- this.goDownInWater(); ++ var fluidType = this.getMaxHeightFluidType(); ++ if ((this.isInWater() || (!fluidType.isAir() && this.canSwimInFluidType(fluidType))) && this.input.shiftKeyDown && this.isAffectedByFluids()) { ++ this.sinkInFluid(this.isInWater() ? net.minecraftforge.common.ForgeMod.WATER_TYPE.get() : fluidType); + } + + if (this.isEyeInFluid(FluidTags.WATER)) { +@@ -882,6 +_,7 @@ + @Override + public void rideTick() { + super.rideTick(); ++ if (this.wantsToStopRiding() && this.isPassenger()) this.input.shiftKeyDown = false; + this.handsBusy = false; + if (this.getControlledVehicle() instanceof Boat boat) { + boat.setInput(this.input.left, this.input.right, this.input.up, this.input.down); +@@ -1139,5 +_,17 @@ + @Override + public float getVisualRotationYInDegrees() { + return this.getYRot(); ++ } ++ ++ public void updateSyncFields(LocalPlayer old) { ++ this.xLast = old.xLast; ++ this.yLast1 = old.yLast1; ++ this.zLast = old.zLast; ++ this.yRotLast = old.yRotLast; ++ this.xRotLast = old.xRotLast; ++ this.lastOnGround = old.lastOnGround; ++ this.wasShiftKeyDown = old.wasShiftKeyDown; ++ this.wasSprinting = old.wasSprinting; ++ this.positionReminder = old.positionReminder; + } + } diff --git a/patches/minecraft/net/minecraft/client/player/RemotePlayer.java.patch b/patches/minecraft/net/minecraft/client/player/RemotePlayer.java.patch index d52904a72f..9d7b0c2108 100644 --- a/patches/minecraft/net/minecraft/client/player/RemotePlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/RemotePlayer.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/player/RemotePlayer.java +++ b/net/minecraft/client/player/RemotePlayer.java -@@ -32,6 +_,7 @@ - } +@@ -33,6 +_,7 @@ - public boolean hurt(DamageSource p_108772_, float p_108773_) { -+ net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, p_108772_, p_108773_); - return true; - } + @Override + public boolean hurt(DamageSource p_108772_, float p_108773_) { ++ net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, p_108772_, p_108773_); + return true; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/DimensionSpecialEffects.java.patch b/patches/minecraft/net/minecraft/client/renderer/DimensionSpecialEffects.java.patch index 1f27fdd250..2997e80a4c 100644 --- a/patches/minecraft/net/minecraft/client/renderer/DimensionSpecialEffects.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/DimensionSpecialEffects.java.patch @@ -6,15 +6,15 @@ @OnlyIn(Dist.CLIENT) -public abstract class DimensionSpecialEffects { +public abstract class DimensionSpecialEffects implements net.minecraftforge.client.extensions.IForgeDimensionSpecialEffects { - private static final Object2ObjectMap EFFECTS = Util.make(new Object2ObjectArrayMap<>(), (p_108881_) -> { - DimensionSpecialEffects.OverworldEffects dimensionspecialeffects$overworldeffects = new DimensionSpecialEffects.OverworldEffects(); - p_108881_.defaultReturnValue(dimensionspecialeffects$overworldeffects); + private static final Object2ObjectMap EFFECTS = Util.make(new Object2ObjectArrayMap<>(), p_108881_ -> { + DimensionSpecialEffects.OverworldEffects dimensionspecialeffects$overworldeffects = new DimensionSpecialEffects.OverworldEffects(); + p_108881_.defaultReturnValue(dimensionspecialeffects$overworldeffects); @@ -37,7 +_,7 @@ - } + } - public static DimensionSpecialEffects forType(DimensionType p_108877_) { -- return EFFECTS.get(p_108877_.effectsLocation()); -+ return net.minecraftforge.client.DimensionSpecialEffectsManager.getForType(p_108877_.effectsLocation()); - } + public static DimensionSpecialEffects forType(DimensionType p_108877_) { +- return EFFECTS.get(p_108877_.effectsLocation()); ++ return net.minecraftforge.client.DimensionSpecialEffectsManager.getForType(p_108877_.effectsLocation()); + } - @Nullable + @Nullable diff --git a/patches/minecraft/net/minecraft/client/renderer/EffectInstance.java.patch b/patches/minecraft/net/minecraft/client/renderer/EffectInstance.java.patch index 7eceb11dbd..7b4b496515 100644 --- a/patches/minecraft/net/minecraft/client/renderer/EffectInstance.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/EffectInstance.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/client/renderer/EffectInstance.java +++ b/net/minecraft/client/renderer/EffectInstance.java @@ -58,7 +_,8 @@ - private final EffectProgram fragmentProgram; + private final EffectProgram fragmentProgram; - public EffectInstance(ResourceManager p_108941_, String p_108942_) throws IOException { -- ResourceLocation resourcelocation = new ResourceLocation("shaders/program/" + p_108942_ + ".json"); -+ ResourceLocation rl = ResourceLocation.tryParse(p_108942_); -+ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "shaders/program/" + rl.getPath() + ".json"); - this.name = p_108942_; - Resource resource = p_108941_.getResourceOrThrow(resourcelocation); + public EffectInstance(ResourceProvider p_334130_, String p_108942_) throws IOException { +- ResourceLocation resourcelocation = new ResourceLocation("shaders/program/" + p_108942_ + ".json"); ++ ResourceLocation rl = ResourceLocation.tryParse(p_108942_); ++ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "shaders/program/" + rl.getPath() + ".json"); + this.name = p_108942_; + Resource resource = p_334130_.getResourceOrThrow(resourcelocation); @@ -150,7 +_,8 @@ - } else { - EffectProgram effectprogram; - if (program == null) { -- ResourceLocation resourcelocation = new ResourceLocation("shaders/program/" + p_172569_ + p_172568_.getExtension()); -+ ResourceLocation rl = ResourceLocation.tryParse(p_172569_); -+ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "shaders/program/" + rl.getPath() + p_172568_.getExtension()); - Resource resource = p_172567_.getResourceOrThrow(resourcelocation); + } else { + EffectProgram effectprogram; + if (program == null) { +- ResourceLocation resourcelocation = new ResourceLocation("shaders/program/" + p_172569_ + p_172568_.getExtension()); ++ ResourceLocation rl = ResourceLocation.tryParse(p_172569_); ++ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "shaders/program/" + rl.getPath() + p_172568_.getExtension()); + Resource resource = p_331503_.getResourceOrThrow(resourcelocation); - try (InputStream inputstream = resource.open()) { + try (InputStream inputstream = resource.open()) { diff --git a/patches/minecraft/net/minecraft/client/renderer/FogRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/FogRenderer.java.patch index 707e2cc090..7282de92e4 100644 --- a/patches/minecraft/net/minecraft/client/renderer/FogRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/FogRenderer.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/client/renderer/FogRenderer.java +++ b/net/minecraft/client/renderer/FogRenderer.java -@@ -190,6 +_,12 @@ - fogBlue = fogBlue * (1.0F - f7) + fogBlue * f9 * f7; - } +@@ -193,6 +_,12 @@ + fogBlue = fogBlue * (1.0F - f7) + fogBlue * f9 * f7; + } -+ Vector3f fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(p_109019_, p_109020_, p_109021_, p_109022_, p_109023_, fogRed, fogGreen, fogBlue); ++ Vector3f fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(p_109019_, p_109020_, p_109021_, p_109022_, p_109023_, fogRed, fogGreen, fogBlue); + -+ fogRed = fogColor.x(); -+ fogGreen = fogColor.y(); -+ fogBlue = fogColor.z(); ++ fogRed = fogColor.x(); ++ fogGreen = fogColor.y(); ++ fogBlue = fogColor.z(); + - RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0.0F); - } + RenderSystem.clearColor(fogRed, fogGreen, fogBlue, 0.0F); + } -@@ -271,6 +_,7 @@ - RenderSystem.setShaderFogStart(fogrenderer$fogdata.start); - RenderSystem.setShaderFogEnd(fogrenderer$fogdata.end); - RenderSystem.setShaderFogShape(fogrenderer$fogdata.shape); -+ net.minecraftforge.client.ForgeHooksClient.onFogRender(p_234174_, fogtype, p_234173_, p_234177_, p_234175_, fogrenderer$fogdata.start, fogrenderer$fogdata.end, fogrenderer$fogdata.shape); - } +@@ -269,6 +_,7 @@ + RenderSystem.setShaderFogStart(fogrenderer$fogdata.start); + RenderSystem.setShaderFogEnd(fogrenderer$fogdata.end); + RenderSystem.setShaderFogShape(fogrenderer$fogdata.shape); ++ net.minecraftforge.client.ForgeHooksClient.onFogRender(p_234174_, fogtype, p_234173_, p_234177_, p_234175_, fogrenderer$fogdata.start, fogrenderer$fogdata.end, fogrenderer$fogdata.shape); + } - public static void levelFogColor() { + public static void levelFogColor() { diff --git a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch index 35eeb374cd..06c92c308c 100644 --- a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch @@ -1,75 +1,71 @@ --- a/net/minecraft/client/renderer/GameRenderer.java +++ b/net/minecraft/client/renderer/GameRenderer.java -@@ -307,8 +_,11 @@ - this.loadEffect(new ResourceLocation("shaders/post/creeper.json")); - } else if (p_109107_ instanceof Spider) { - this.loadEffect(new ResourceLocation("shaders/post/spider.json")); -+ this.loadEffect(new ResourceLocation("shaders/post/spider.json")); - } else if (p_109107_ instanceof EnderMan) { - this.loadEffect(new ResourceLocation("shaders/post/invert.json")); -+ } else { -+ net.minecraftforge.client.ForgeHooksClient.loadEntityShader(p_109107_, this); - } +@@ -310,6 +_,8 @@ + this.loadEffect(new ResourceLocation("shaders/post/spider.json")); + } else if (p_109107_ instanceof EnderMan) { + this.loadEffect(new ResourceLocation("shaders/post/invert.json")); ++ } else { ++ net.minecraftforge.client.ForgeHooksClient.loadEntityShader(p_109107_, this); + } + } - } -@@ -610,6 +_,7 @@ - list1.add(Pair.of(new ShaderInstance(p_250719_, "rendertype_breeze_wind", DefaultVertexFormat.NEW_ENTITY), (p_308287_) -> { - rendertypeBreezeWindShader = p_308287_; - })); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RegisterShadersEvent(p_250719_, list1)); - } catch (IOException ioexception) { - list1.forEach((p_172729_) -> { - p_172729_.getFirst().close(); -@@ -757,7 +_,7 @@ - d0 *= Mth.lerp(this.minecraft.options.fovEffectScale().get(), 1.0D, (double)0.85714287F); - } - -- return d0; -+ return net.minecraftforge.client.ForgeHooksClient.getFieldOfView(this, p_109142_, p_109143_, d0, p_109144_); - } - } - -@@ -894,12 +_,12 @@ - - Window window = this.minecraft.getWindow(); - RenderSystem.clear(256, Minecraft.ON_OSX); -- Matrix4f matrix4f = (new Matrix4f()).setOrtho(0.0F, (float)((double)window.getWidth() / window.getGuiScale()), (float)((double)window.getHeight() / window.getGuiScale()), 0.0F, 1000.0F, 21000.0F); -+ Matrix4f matrix4f = (new Matrix4f()).setOrtho(0.0F, (float)((double)window.getWidth() / window.getGuiScale()), (float)((double)window.getHeight() / window.getGuiScale()), 0.0F, 1000.0F, net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); - PoseStack posestack = RenderSystem.getModelViewStack(); - posestack.pushPose(); - posestack.setIdentity(); -- posestack.translate(0.0F, 0.0F, -11000.0F); -+ posestack.translate(0.0D, 0.0D, 1000F-net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); - RenderSystem.applyModelViewMatrix(); - Lighting.setupFor3DItems(); - GuiGraphics guigraphics = new GuiGraphics(this.minecraft, this.renderBuffers.bufferSource()); -@@ -935,7 +_,7 @@ +@@ -532,6 +_,7 @@ + Pair.of(new ShaderInstance(p_250719_, "rendertype_gui_ghost_recipe_overlay", DefaultVertexFormat.POSITION_COLOR), p_286147_ -> rendertypeGuiGhostRecipeOverlayShader = p_286147_) + ); + list1.add(Pair.of(new ShaderInstance(p_250719_, "rendertype_breeze_wind", DefaultVertexFormat.NEW_ENTITY), p_308287_ -> rendertypeBreezeWindShader = p_308287_)); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRegisterShaders(p_250719_, list1); + this.loadBlurEffect(p_250719_); + } catch (IOException ioexception) { + list1.forEach(p_172729_ -> p_172729_.getFirst().close()); +@@ -691,7 +_,7 @@ + d0 *= Mth.lerp(this.minecraft.options.fovEffectScale().get(), 1.0, 0.85714287F); } - } else if (flag && this.minecraft.screen != null) { - try { -- this.minecraft.screen.renderWithTooltip(guigraphics, i, j, this.minecraft.getDeltaFrameTime()); -+ net.minecraftforge.client.ForgeHooksClient.drawScreen(this.minecraft.screen, guigraphics, i, j, this.minecraft.getDeltaFrameTime()); - } catch (Throwable throwable1) { - CrashReport crashreport1 = CrashReport.forThrowable(throwable1, "Rendering screen"); - CrashReportCategory crashreportcategory1 = crashreport1.addCategory("Screen render details"); -@@ -1090,12 +_,19 @@ - Matrix4f matrix4f = posestack.last().pose(); - this.resetProjectionMatrix(matrix4f); +- return d0; ++ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeFov(this, p_109142_, p_109143_, d0, p_109144_).getFOV(); + } + } + +@@ -850,12 +_,12 @@ + (float)((double)window.getHeight() / window.getGuiScale()), + 0.0F, + 1000.0F, +- 21000.0F ++ 21000.0f + ); + RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); + Matrix4fStack matrix4fstack = RenderSystem.getModelViewStack(); + matrix4fstack.pushMatrix(); +- matrix4fstack.translation(0.0F, 0.0F, -11000.0F); ++ matrix4fstack.translation(0.0F, 0.0F, 1000F - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); + RenderSystem.applyModelViewMatrix(); + Lighting.setupFor3DItems(); + GuiGraphics guigraphics = new GuiGraphics(this.minecraft, this.renderBuffers.bufferSource()); +@@ -889,7 +_,7 @@ + } + } else if (flag && this.minecraft.screen != null) { + try { +- this.minecraft.screen.renderWithTooltip(guigraphics, i, j, this.minecraft.getDeltaFrameTime()); ++ net.minecraftforge.client.ForgeHooksClient.drawScreen(this.minecraft.screen, guigraphics, i, j, this.minecraft.getDeltaFrameTime()); + } catch (Throwable throwable1) { + CrashReport crashreport1 = CrashReport.forThrowable(throwable1, "Rendering screen"); + CrashReportCategory crashreportcategory1 = crashreport1.addCategory("Screen render details"); +@@ -1064,12 +_,17 @@ + } + + this.resetProjectionMatrix(matrix4f); + -+ net.minecraftforge.client.event.ViewportEvent.ComputeCameraAngles cameraSetup = net.minecraftforge.client.ForgeHooksClient.onCameraSetup(this, camera, p_109090_); -+ camera.setAnglesInternal(cameraSetup.getYaw(), cameraSetup.getPitch()); -+ p_109092_.mulPose(Axis.ZP.rotationDegrees(cameraSetup.getRoll())); -+ - p_109092_.mulPose(Axis.XP.rotationDegrees(camera.getXRot())); - p_109092_.mulPose(Axis.YP.rotationDegrees(camera.getYRot() + 180.0F)); - Matrix3f matrix3f = (new Matrix3f(p_109092_.last().normal())).invert(); - RenderSystem.setInverseViewRotationMatrix(matrix3f); - this.minecraft.levelRenderer.prepareCullFrustum(p_109092_, camera.getPosition(), this.getProjectionMatrix(Math.max(d0, (double)this.minecraft.options.fov().get().intValue()))); - this.minecraft.levelRenderer.renderLevel(p_109092_, p_109090_, p_109091_, flag, camera, this, this.lightTexture, matrix4f); -+ this.minecraft.getProfiler().popPush("forge_render_last"); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_LEVEL.dispatch(this.minecraft.levelRenderer, posestack, matrix4f, this.minecraft.levelRenderer.getTicks(), camera, this.minecraft.levelRenderer.getFrustum()); - this.minecraft.getProfiler().popPush("hand"); - if (this.renderHand) { - RenderSystem.clear(256, Minecraft.ON_OSX); ++ var cameraSetup = net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeCameraAngles(this, camera, p_109090_); ++ camera.setAnglesInternal(cameraSetup.getYaw(), cameraSetup.getPitch()); + Matrix4f matrix4f1 = new Matrix4f() +- .rotationXYZ(camera.getXRot() * (float) (Math.PI / 180.0), camera.getYRot() * (float) (Math.PI / 180.0) + (float) Math.PI, 0.0F); ++ .rotationXYZ(camera.getXRot() * (float) (Math.PI / 180.0), camera.getYRot() * (float) (Math.PI / 180.0) + (float) Math.PI, cameraSetup.getRoll() * (float) (Math.PI / 180.0)); + this.minecraft + .levelRenderer + .prepareCullFrustum(camera.getPosition(), matrix4f1, this.getProjectionMatrix(Math.max(d0, (double)this.minecraft.options.fov().get().intValue()))); + this.minecraft.levelRenderer.renderLevel(p_109090_, p_109091_, flag, camera, this, this.lightTexture, matrix4f1, matrix4f); ++ this.minecraft.getProfiler().popPush("forge_render_last"); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_LEVEL.dispatch(this.minecraft.levelRenderer, posestack.last().pose(), matrix4f, this.minecraft.levelRenderer.getTicks(), camera, this.minecraft.levelRenderer.getFrustum()); + this.minecraft.getProfiler().popPush("hand"); + if (this.renderHand) { + RenderSystem.clear(256, Minecraft.ON_OSX); diff --git a/patches/minecraft/net/minecraft/client/renderer/ItemBlockRenderTypes.java.patch b/patches/minecraft/net/minecraft/client/renderer/ItemBlockRenderTypes.java.patch index c6bb7403e1..582d9284ca 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ItemBlockRenderTypes.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ItemBlockRenderTypes.java.patch @@ -1,129 +1,130 @@ --- a/net/minecraft/client/renderer/ItemBlockRenderTypes.java +++ b/net/minecraft/client/renderer/ItemBlockRenderTypes.java -@@ -19,6 +_,7 @@ +@@ -20,6 +_,7 @@ @OnlyIn(Dist.CLIENT) public class ItemBlockRenderTypes { -+ @Deprecated - private static final Map TYPE_BY_BLOCK = Util.make(Maps.newHashMap(), (p_308288_) -> { - RenderType rendertype = RenderType.tripwire(); - p_308288_.put(Blocks.TRIPWIRE, rendertype); -@@ -334,6 +_,7 @@ - p_308288_.put(Blocks.BUBBLE_COLUMN, rendertype3); - p_308288_.put(Blocks.TINTED_GLASS, rendertype3); - }); -+ @Deprecated - private static final Map TYPE_BY_FLUID = Util.make(Maps.newHashMap(), (p_109290_) -> { - RenderType rendertype = RenderType.translucent(); - p_109290_.put(Fluids.FLOWING_WATER, rendertype); -@@ -341,6 +_,8 @@ - }); - private static boolean renderCutout; ++ @Deprecated + private static final Map TYPE_BY_BLOCK = Util.make(Maps.newHashMap(), p_325496_ -> { + RenderType rendertype = RenderType.tripwire(); + p_325496_.put(Blocks.TRIPWIRE, rendertype); +@@ -336,6 +_,7 @@ + p_325496_.put(Blocks.BUBBLE_COLUMN, rendertype3); + p_325496_.put(Blocks.TINTED_GLASS, rendertype3); + }); ++ @Deprecated + private static final Map TYPE_BY_FLUID = Util.make(Maps.newHashMap(), p_109290_ -> { + RenderType rendertype = RenderType.translucent(); + p_109290_.put(Fluids.FLOWING_WATER, rendertype); +@@ -343,6 +_,8 @@ + }); + private static boolean renderCutout; -+ /** @deprecated Forge: Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ -+ @Deprecated // Note: this method does NOT support model-based render types - public static RenderType getChunkRenderType(BlockState p_109283_) { - Block block = p_109283_.getBlock(); - if (block instanceof LeavesBlock) { -@@ -351,6 +_,8 @@ - } - } ++ /** @deprecated Forge: Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ ++ @Deprecated // Note: this method does NOT support model-based render types + public static RenderType getChunkRenderType(BlockState p_109283_) { + Block block = p_109283_.getBlock(); + if (block instanceof LeavesBlock) { +@@ -353,6 +_,8 @@ + } + } -+ /** @deprecated Forge: Use {@link net.minecraftforge.client.RenderTypeHelper#getMovingBlockRenderType(RenderType)} while iterating through {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ -+ @Deprecated // Note: this method does NOT support model-based render types - public static RenderType getMovingBlockRenderType(BlockState p_109294_) { - Block block = p_109294_.getBlock(); - if (block instanceof LeavesBlock) { -@@ -365,6 +_,8 @@ - } - } ++ /** @deprecated Forge: Use {@link net.minecraftforge.client.RenderTypeHelper#getMovingBlockRenderType(RenderType)} while iterating through {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ ++ @Deprecated // Note: this method does NOT support model-based render types + public static RenderType getMovingBlockRenderType(BlockState p_109294_) { + Block block = p_109294_.getBlock(); + if (block instanceof LeavesBlock) { +@@ -367,6 +_,8 @@ + } + } -+ /** @deprecated Forge: Use {@link net.minecraftforge.client.RenderTypeHelper#getEntityRenderType(RenderType, boolean)} while iterating through {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ -+ @Deprecated // Note: this method does NOT support model-based render types - public static RenderType getRenderType(BlockState p_109285_, boolean p_109286_) { - RenderType rendertype = getChunkRenderType(p_109285_); - if (rendertype == RenderType.translucent()) { -@@ -378,6 +_,8 @@ - } - } ++ /** @deprecated Forge: Use {@link net.minecraftforge.client.RenderTypeHelper#getEntityRenderType(RenderType, boolean)} while iterating through {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ ++ @Deprecated // Note: this method does NOT support model-based render types + public static RenderType getRenderType(BlockState p_109285_, boolean p_109286_) { + RenderType rendertype = getChunkRenderType(p_109285_); + if (rendertype == RenderType.translucent()) { +@@ -380,6 +_,8 @@ + } + } -+ /** @deprecated Forge: Use {@link net.minecraft.client.resources.model.BakedModel#getRenderPasses(ItemStack, boolean)} and {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(ItemStack, boolean)}. */ -+ @Deprecated // Note: this method does NOT support model-based render types - public static RenderType getRenderType(ItemStack p_109280_, boolean p_109281_) { - Item item = p_109280_.getItem(); - if (item instanceof BlockItem) { -@@ -389,8 +_,73 @@ - } ++ /** @deprecated Forge: Use {@link net.minecraft.client.resources.model.BakedModel#getRenderPasses(ItemStack, boolean)} and {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(ItemStack, boolean)}. */ ++ @Deprecated // Note: this method does NOT support model-based render types + public static RenderType getRenderType(ItemStack p_109280_, boolean p_109281_) { + Item item = p_109280_.getItem(); + if (item instanceof BlockItem) { +@@ -391,11 +_,74 @@ + } - public static RenderType getRenderLayer(FluidState p_109288_) { -- RenderType rendertype = TYPE_BY_FLUID.get(p_109288_.getType()); -+ RenderType rendertype = FLUID_RENDER_TYPES.get(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_109288_.getType())); - return rendertype != null ? rendertype : RenderType.solid(); -+ } -+ -+ // FORGE START -+ -+ private static final net.minecraftforge.client.ChunkRenderTypeSet CUTOUT_MIPPED = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.cutoutMipped()); -+ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.solid()); -+ private static final Map, net.minecraftforge.client.ChunkRenderTypeSet> BLOCK_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_BLOCK.size(), 0.5F), map -> { -+ map.defaultReturnValue(SOLID); -+ for(Map.Entry entry : TYPE_BY_BLOCK.entrySet()) { -+ map.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(entry.getKey()), net.minecraftforge.client.ChunkRenderTypeSet.of(entry.getValue())); -+ } -+ }); -+ private static final Map, RenderType> FLUID_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_FLUID.size(), 0.5F), map -> { -+ map.defaultReturnValue(RenderType.solid()); -+ for(Map.Entry entry : TYPE_BY_FLUID.entrySet()) { -+ map.put(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(entry.getKey()), entry.getValue()); -+ } -+ }); -+ -+ /** @deprecated Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ -+ @Deprecated(since = "1.19") -+ public static net.minecraftforge.client.ChunkRenderTypeSet getRenderLayers(BlockState state) { -+ Block block = state.getBlock(); -+ if (block instanceof LeavesBlock) { -+ return renderCutout ? CUTOUT_MIPPED : SOLID; -+ } else { -+ return BLOCK_RENDER_TYPES.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); -+ } -+ } -+ -+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ -+ @Deprecated(since = "1.19") -+ public static void setRenderLayer(Block block, RenderType type) { -+ com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers()."); -+ setRenderLayer(block, net.minecraftforge.client.ChunkRenderTypeSet.of(type)); -+ } -+ -+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ -+ @Deprecated(since = "1.19") -+ public static synchronized void setRenderLayer(Block block, java.util.function.Predicate predicate) { -+ setRenderLayer(block, createSetFromPredicate(predicate)); -+ } -+ -+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ -+ @Deprecated(since = "1.19") -+ public static synchronized void setRenderLayer(Block block, net.minecraftforge.client.ChunkRenderTypeSet layers) { -+ checkClientLoading(); -+ BLOCK_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), layers); -+ } -+ -+ public static synchronized void setRenderLayer(Fluid fluid, RenderType type) { -+ com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers()."); -+ checkClientLoading(); -+ FLUID_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid), type); -+ } -+ -+ private static void checkClientLoading() { -+ com.google.common.base.Preconditions.checkState(net.minecraftforge.client.loading.ClientModLoader.isLoading(), -+ "Render layers can only be set during client loading! " + -+ "This might ideally be done from `FMLClientSetupEvent`." -+ ); -+ } -+ -+ private static net.minecraftforge.client.ChunkRenderTypeSet createSetFromPredicate(java.util.function.Predicate predicate) { -+ return net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.chunkBufferLayers().stream().filter(predicate).toArray(RenderType[]::new)); - } + public static RenderType getRenderLayer(FluidState p_109288_) { +- RenderType rendertype = TYPE_BY_FLUID.get(p_109288_.getType()); ++ RenderType rendertype = FLUID_RENDER_TYPES.get(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_109288_.getType())); + return rendertype != null ? rendertype : RenderType.solid(); + } - public static void setFancy(boolean p_109292_) { + public static void setFancy(boolean p_109292_) { + renderCutout = p_109292_; ++ } ++ ++ private static final net.minecraftforge.client.ChunkRenderTypeSet CUTOUT_MIPPED = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.cutoutMipped()); ++ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.solid()); ++ private static final Map, net.minecraftforge.client.ChunkRenderTypeSet> BLOCK_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_BLOCK.size(), 0.5F), map -> { ++ map.defaultReturnValue(SOLID); ++ for(Map.Entry entry : TYPE_BY_BLOCK.entrySet()) { ++ map.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(entry.getKey()), net.minecraftforge.client.ChunkRenderTypeSet.of(entry.getValue())); ++ } ++ }); ++ private static final Map, RenderType> FLUID_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_FLUID.size(), 0.5F), map -> { ++ map.defaultReturnValue(RenderType.solid()); ++ for(Map.Entry entry : TYPE_BY_FLUID.entrySet()) { ++ map.put(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(entry.getKey()), entry.getValue()); ++ } ++ }); ++ ++ /** @deprecated Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ ++ @Deprecated(since = "1.19") ++ public static net.minecraftforge.client.ChunkRenderTypeSet getRenderLayers(BlockState state) { ++ Block block = state.getBlock(); ++ if (block instanceof LeavesBlock) { ++ return renderCutout ? CUTOUT_MIPPED : SOLID; ++ } else { ++ return BLOCK_RENDER_TYPES.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); ++ } ++ } ++ ++ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ ++ @Deprecated(since = "1.19") ++ public static void setRenderLayer(Block block, RenderType type) { ++ com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers()."); ++ setRenderLayer(block, net.minecraftforge.client.ChunkRenderTypeSet.of(type)); ++ } ++ ++ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ ++ @Deprecated(since = "1.19") ++ public static synchronized void setRenderLayer(Block block, java.util.function.Predicate predicate) { ++ setRenderLayer(block, createSetFromPredicate(predicate)); ++ } ++ ++ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ ++ @Deprecated(since = "1.19") ++ public static synchronized void setRenderLayer(Block block, net.minecraftforge.client.ChunkRenderTypeSet layers) { ++ checkClientLoading(); ++ BLOCK_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), layers); ++ } ++ ++ public static synchronized void setRenderLayer(Fluid fluid, RenderType type) { ++ com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers()."); ++ checkClientLoading(); ++ FLUID_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid), type); ++ } ++ ++ private static void checkClientLoading() { ++ com.google.common.base.Preconditions.checkState(net.minecraftforge.client.loading.ClientModLoader.isLoading(), ++ "Render layers can only be set during client loading! " + ++ "This might ideally be done from `FMLClientSetupEvent`." ++ ); ++ } ++ ++ private static net.minecraftforge.client.ChunkRenderTypeSet createSetFromPredicate(java.util.function.Predicate predicate) { ++ return net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.chunkBufferLayers().stream().filter(predicate).toArray(RenderType[]::new)); + } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch index e84100ab56..84328c4024 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch @@ -1,53 +1,53 @@ --- a/net/minecraft/client/renderer/ItemInHandRenderer.java +++ b/net/minecraft/client/renderer/ItemInHandRenderer.java -@@ -310,12 +_,14 @@ - if (iteminhandrenderer$handrenderselection.renderMainHand) { - float f4 = interactionhand == InteractionHand.MAIN_HAND ? f : 0.0F; - float f5 = 1.0F - Mth.lerp(p_109315_, this.oMainHandHeight, this.mainHandHeight); -+ if(!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f4, f5, this.mainHandItem)) - this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.MAIN_HAND, f4, this.mainHandItem, f5, p_109316_, p_109317_, p_109319_); - } +@@ -331,12 +_,14 @@ + if (iteminhandrenderer$handrenderselection.renderMainHand) { + float f4 = interactionhand == InteractionHand.MAIN_HAND ? f : 0.0F; + float f5 = 1.0F - Mth.lerp(p_109315_, this.oMainHandHeight, this.mainHandHeight); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f4, f5, this.mainHandItem)) + this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.MAIN_HAND, f4, this.mainHandItem, f5, p_109316_, p_109317_, p_109319_); + } - if (iteminhandrenderer$handrenderselection.renderOffHand) { - float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F; - float f7 = 1.0F - Mth.lerp(p_109315_, this.oOffHandHeight, this.offHandHeight); -+ if(!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f6, f7, this.offHandItem)) - this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, p_109316_, p_109317_, p_109319_); - } + if (iteminhandrenderer$handrenderselection.renderOffHand) { + float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F; + float f7 = 1.0F - Mth.lerp(p_109315_, this.oOffHandHeight, this.offHandHeight); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f6, f7, this.mainHandItem)) + this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, p_109316_, p_109317_, p_109319_); + } -@@ -366,7 +_,7 @@ +@@ -402,7 +_,7 @@ + } else { + this.renderOneHandedMap(p_109379_, p_109380_, p_109381_, p_109378_, humanoidarm, p_109376_, p_109377_); + } +- } else if (p_109377_.is(Items.CROSSBOW)) { ++ } else if (p_109377_.getItem() instanceof CrossbowItem) { + boolean flag1 = CrossbowItem.isCharged(p_109377_); + boolean flag2 = humanoidarm == HumanoidArm.RIGHT; + int i = flag2 ? 1 : -1; +@@ -452,6 +_,7 @@ + ); } else { - this.renderOneHandedMap(p_109379_, p_109380_, p_109381_, p_109378_, humanoidarm, p_109376_, p_109377_); - } -- } else if (p_109377_.is(Items.CROSSBOW)) { -+ } else if (p_109377_.getItem() instanceof CrossbowItem) { - boolean flag1 = CrossbowItem.isCharged(p_109377_); - boolean flag2 = humanoidarm == HumanoidArm.RIGHT; - int i = flag2 ? 1 : -1; -@@ -408,6 +_,7 @@ - this.renderItem(p_109372_, p_109377_, flag2 ? ItemDisplayContext.FIRST_PERSON_RIGHT_HAND : ItemDisplayContext.FIRST_PERSON_LEFT_HAND, !flag2, p_109379_, p_109380_, p_109381_); - } else { - boolean flag3 = humanoidarm == HumanoidArm.RIGHT; -+ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_109377_).applyForgeHandTransform(p_109379_, minecraft.player, humanoidarm, p_109377_, p_109373_, p_109378_, p_109376_)) // FORGE: Allow items to define custom arm animation - if (p_109372_.isUsingItem() && p_109372_.getUseItemRemainingTicks() > 0 && p_109372_.getUsedItemHand() == p_109375_) { - int k = flag3 ? 1 : -1; - switch (p_109377_.getUseAnimation()) { -@@ -514,8 +_,16 @@ - this.offHandHeight = Mth.clamp(this.offHandHeight - 0.4F, 0.0F, 1.0F); - } else { - float f = localplayer.getAttackStrengthScale(1.0F); -- this.mainHandHeight += Mth.clamp((this.mainHandItem == itemstack ? f * f * f : 0.0F) - this.mainHandHeight, -0.4F, 0.4F); -- this.offHandHeight += Mth.clamp((float)(this.offHandItem == itemstack1 ? 1 : 0) - this.offHandHeight, -0.4F, 0.4F); -+ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, itemstack, localplayer.getInventory().selected); -+ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, itemstack1, -1); + boolean flag3 = humanoidarm == HumanoidArm.RIGHT; ++ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_109377_).applyForgeHandTransform(p_109379_, minecraft.player, humanoidarm, p_109377_, p_109373_, p_109378_, p_109376_)) // FORGE: Allow items to define custom arm animation + if (p_109372_.isUsingItem() && p_109372_.getUseItemRemainingTicks() > 0 && p_109372_.getUsedItemHand() == p_109375_) { + int k = flag3 ? 1 : -1; + switch (p_109377_.getUseAnimation()) { +@@ -566,8 +_,16 @@ + this.offHandHeight = Mth.clamp(this.offHandHeight - 0.4F, 0.0F, 1.0F); + } else { + float f = localplayer.getAttackStrengthScale(1.0F); +- this.mainHandHeight = this.mainHandHeight + Mth.clamp((this.mainHandItem == itemstack ? f * f * f : 0.0F) - this.mainHandHeight, -0.4F, 0.4F); +- this.offHandHeight = this.offHandHeight + Mth.clamp((float)(this.offHandItem == itemstack1 ? 1 : 0) - this.offHandHeight, -0.4F, 0.4F); ++ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, itemstack, localplayer.getInventory().selected); ++ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, itemstack1, -1); + -+ if (!requipM && this.mainHandItem != itemstack) -+ this.mainHandItem = itemstack; -+ if (!requipO && this.offHandItem != itemstack1) -+ this.offHandItem = itemstack1; ++ if (!requipM && this.mainHandItem != itemstack) ++ this.mainHandItem = itemstack; ++ if (!requipO && this.offHandItem != itemstack1) ++ this.offHandItem = itemstack1; + -+ this.mainHandHeight += Mth.clamp((!requipM ? f * f * f : 0.0F) - this.mainHandHeight, -0.4F, 0.4F); -+ this.offHandHeight += Mth.clamp((float)(!requipO ? 1 : 0) - this.offHandHeight, -0.4F, 0.4F); - } ++ this.mainHandHeight += Mth.clamp((!requipM ? f * f * f : 0.0F) - this.mainHandHeight, -0.4F, 0.4F); ++ this.offHandHeight += Mth.clamp((float)(!requipO ? 1 : 0) - this.offHandHeight, -0.4F, 0.4F); + } - if (this.mainHandHeight < 0.1F) { + if (this.mainHandHeight < 0.1F) { diff --git a/patches/minecraft/net/minecraft/client/renderer/ItemModelShaper.java.patch b/patches/minecraft/net/minecraft/client/renderer/ItemModelShaper.java.patch deleted file mode 100644 index 34323e4dd0..0000000000 --- a/patches/minecraft/net/minecraft/client/renderer/ItemModelShaper.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/client/renderer/ItemModelShaper.java -+++ b/net/minecraft/client/renderer/ItemModelShaper.java -@@ -24,6 +_,7 @@ - - public BakedModel getItemModel(ItemStack p_109407_) { - BakedModel bakedmodel = this.getItemModel(p_109407_.getItem()); -+ // FORGE: Make sure to call the item overrides - return bakedmodel == null ? this.modelManager.getMissingModel() : bakedmodel; - } - diff --git a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch index baa5026a3e..48e4f61de5 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch @@ -1,265 +1,268 @@ --- a/net/minecraft/client/renderer/LevelRenderer.java +++ b/net/minecraft/client/renderer/LevelRenderer.java -@@ -248,6 +_,8 @@ - } +@@ -251,6 +_,9 @@ + } - private void renderSnowAndRain(LightTexture p_109704_, float p_109705_, double p_109706_, double p_109707_, double p_109708_) { -+ if (level.effects().renderSnowAndRain(level, ticks, p_109705_, p_109704_, p_109706_, p_109707_, p_109708_)) -+ return; - float f = this.minecraft.level.getRainLevel(p_109705_); - if (!(f <= 0.0F)) { - p_109704_.turnOnLightLayer(); -@@ -370,6 +_,8 @@ - } + private void renderSnowAndRain(LightTexture p_109704_, float p_109705_, double p_109706_, double p_109707_, double p_109708_) { ++ if (level.effects().renderSnowAndRain(level, ticks, p_109705_, p_109704_, p_109706_, p_109707_, p_109708_)) { ++ return; ++ } + float f = this.minecraft.level.getRainLevel(p_109705_); + if (!(f <= 0.0F)) { + p_109704_.turnOnLightLayer(); +@@ -405,6 +_,9 @@ + } - public void tickRain(Camera p_109694_) { -+ if (level.effects().tickRain(level, ticks, p_109694_)) -+ return; - float f = this.minecraft.level.getRainLevel(1.0F) / (Minecraft.useFancyGraphics() ? 1.0F : 2.0F); - if (!(f <= 0.0F)) { - RandomSource randomsource = RandomSource.create((long)this.ticks * 312987231L); -@@ -894,11 +_,13 @@ - RenderSystem.clear(16640, Minecraft.ON_OSX); - float f1 = p_109605_.getRenderDistance(); - boolean flag1 = this.minecraft.level.effects().isFoggyAt(Mth.floor(d0), Mth.floor(d1)) || this.minecraft.gui.getBossOverlay().shouldCreateWorldFog(); -+ FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_SKY, f, flag1, p_109601_); - profilerfiller.popPush("sky"); - RenderSystem.setShader(GameRenderer::getPositionShader); - this.renderSky(p_109600_, p_254120_, f, p_109604_, flag1, () -> { - FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_SKY, f1, flag1, f); - }); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_SKY.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - profilerfiller.popPush("fog"); - FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_TERRAIN, Math.max(f1, 32.0F), flag1, f); - profilerfiller.popPush("terrain_setup"); -@@ -907,7 +_,9 @@ - this.compileSections(p_109604_); - profilerfiller.popPush("terrain"); - this.renderSectionLayer(RenderType.solid(), p_109600_, d0, d1, d2, p_254120_); -+ this.minecraft.getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS).setBlurMipmap(false, this.minecraft.options.mipmapLevels().get() > 0); // FORGE: fix flickering leaves when mods mess up the blurMipmap settings - this.renderSectionLayer(RenderType.cutoutMipped(), p_109600_, d0, d1, d2, p_254120_); -+ this.minecraft.getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS).restoreLastBlurMipmap(); - this.renderSectionLayer(RenderType.cutout(), p_109600_, d0, d1, d2, p_254120_); - if (this.level.effects().constantAmbientLight()) { - Lighting.setupNetherLevel(p_109600_.last().pose()); -@@ -939,7 +_,7 @@ - for(Entity entity : this.level.entitiesForRendering()) { - if (this.entityRenderDispatcher.shouldRender(entity, frustum, d0, d1, d2) || entity.hasIndirectPassenger(this.minecraft.player)) { - BlockPos blockpos = entity.blockPosition(); -- if ((this.level.isOutsideBuildHeight(blockpos.getY()) || this.isSectionCompiled(blockpos)) && (entity != p_109604_.getEntity() || p_109604_.isDetached() || p_109604_.getEntity() instanceof LivingEntity && ((LivingEntity)p_109604_.getEntity()).isSleeping()) && (!(entity instanceof LocalPlayer) || p_109604_.getEntity() == entity)) { -+ if ((this.level.isOutsideBuildHeight(blockpos.getY()) || this.isSectionCompiled(blockpos)) && (entity != p_109604_.getEntity() || p_109604_.isDetached() || p_109604_.getEntity() instanceof LivingEntity && ((LivingEntity)p_109604_.getEntity()).isSleeping()) && (!(entity instanceof LocalPlayer) || p_109604_.getEntity() == entity || (entity == minecraft.player && !minecraft.player.isSpectator()))) { //FORGE: render local player entity when it is not the renderViewEntity - ++this.renderedEntities; - if (entity.tickCount == 0) { - entity.xOld = entity.getX(); -@@ -955,6 +_,9 @@ - int i = entity.getTeamColor(); - outlinebuffersource.setColor(FastColor.ARGB32.red(i), FastColor.ARGB32.green(i), FastColor.ARGB32.blue(i), 255); - } else { -+ if (this.shouldShowEntityOutlines() && entity.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering -+ flag2 = true; -+ } - multibuffersource = multibuffersource$buffersource; - } + public void tickRain(Camera p_109694_) { ++ if (level.effects().tickRain(level, ticks, p_109694_)) { ++ return; ++ } + float f = this.minecraft.level.getRainLevel(1.0F) / (Minecraft.useFancyGraphics() ? 1.0F : 2.0F); + if (!(f <= 0.0F)) { + RandomSource randomsource = RandomSource.create((long)this.ticks * 312987231L); +@@ -956,9 +_,11 @@ + RenderSystem.clear(16640, Minecraft.ON_OSX); + float f1 = p_109605_.getRenderDistance(); + boolean flag1 = this.minecraft.level.effects().isFoggyAt(Mth.floor(d0), Mth.floor(d1)) || this.minecraft.gui.getBossOverlay().shouldCreateWorldFog(); ++ FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_SKY, f, flag1, p_109601_); + profilerfiller.popPush("sky"); + RenderSystem.setShader(GameRenderer::getPositionShader); + this.renderSky(p_254120_, p_330527_, f, p_109604_, flag1, () -> FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_SKY, f1, flag1, f)); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_SKY.dispatch(this, p_254120_, p_254120_, this.ticks, p_109604_, frustum); + profilerfiller.popPush("fog"); + FogRenderer.setupFog(p_109604_, FogRenderer.FogMode.FOG_TERRAIN, Math.max(f1, 32.0F), flag1, f); + profilerfiller.popPush("terrain_setup"); +@@ -967,7 +_,9 @@ + this.compileSections(p_109604_); + profilerfiller.popPush("terrain"); + this.renderSectionLayer(RenderType.solid(), d0, d1, d2, p_254120_, p_330527_); ++ this.minecraft.getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS).setBlurMipmap(false, this.minecraft.options.mipmapLevels().get() > 0); // FORGE: fix flickering leaves when mods mess up the blurMipmap settings + this.renderSectionLayer(RenderType.cutoutMipped(), d0, d1, d2, p_254120_, p_330527_); ++ this.minecraft.getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS).restoreLastBlurMipmap(); + this.renderSectionLayer(RenderType.cutout(), d0, d1, d2, p_254120_, p_330527_); + if (this.level.effects().constantAmbientLight()) { + Lighting.setupNetherLevel(); +@@ -1010,7 +_,7 @@ + || p_109604_.isDetached() + || p_109604_.getEntity() instanceof LivingEntity && ((LivingEntity)p_109604_.getEntity()).isSleeping() + ) +- && (!(entity instanceof LocalPlayer) || p_109604_.getEntity() == entity)) { ++ && (!(entity instanceof LocalPlayer) || p_109604_.getEntity() == entity || (entity == minecraft.player && !minecraft.player.isSpectator()))) { //FORGE: render local player entity when it is not the renderViewEntity + this.renderedEntities++; + if (entity.tickCount == 0) { + entity.xOld = entity.getX(); +@@ -1026,6 +_,9 @@ + int i = entity.getTeamColor(); + outlinebuffersource.setColor(FastColor.ARGB32.red(i), FastColor.ARGB32.green(i), FastColor.ARGB32.blue(i), 255); + } else { ++ if (this.shouldShowEntityOutlines() && entity.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering ++ flag2 = true; ++ } + multibuffersource = multibuffersource$buffersource; + } -@@ -970,12 +_,14 @@ - multibuffersource$buffersource.endBatch(RenderType.entityCutout(TextureAtlas.LOCATION_BLOCKS)); - multibuffersource$buffersource.endBatch(RenderType.entityCutoutNoCull(TextureAtlas.LOCATION_BLOCKS)); - multibuffersource$buffersource.endBatch(RenderType.entitySmoothCutout(TextureAtlas.LOCATION_BLOCKS)); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_ENTITIES.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - profilerfiller.popPush("blockentities"); +@@ -1041,12 +_,14 @@ + multibuffersource$buffersource.endBatch(RenderType.entityCutout(TextureAtlas.LOCATION_BLOCKS)); + multibuffersource$buffersource.endBatch(RenderType.entityCutoutNoCull(TextureAtlas.LOCATION_BLOCKS)); + multibuffersource$buffersource.endBatch(RenderType.entitySmoothCutout(TextureAtlas.LOCATION_BLOCKS)); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_ENTITIES.dispatch(this, p_254120_, p_254120_, this.ticks, p_109604_, frustum); + profilerfiller.popPush("blockentities"); - for(SectionRenderDispatcher.RenderSection sectionrenderdispatcher$rendersection : this.visibleSections) { - List list = sectionrenderdispatcher$rendersection.getCompiled().getRenderableBlockEntities(); - if (!list.isEmpty()) { - for(BlockEntity blockentity1 : list) { -+ if (!frustum.isVisible(blockentity1.getRenderBoundingBox())) continue; - BlockPos blockpos4 = blockentity1.getBlockPos(); - MultiBufferSource multibuffersource1 = multibuffersource$buffersource; - p_109600_.pushPose(); -@@ -992,6 +_,9 @@ - }; - } - } -+ if (this.shouldShowEntityOutlines() && blockentity1.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering -+ flag2 = true; -+ } + for (SectionRenderDispatcher.RenderSection sectionrenderdispatcher$rendersection : this.visibleSections) { + List list = sectionrenderdispatcher$rendersection.getCompiled().getRenderableBlockEntities(); + if (!list.isEmpty()) { + for (BlockEntity blockentity1 : list) { ++ if (!frustum.isVisible(blockentity1.getRenderBoundingBox())) continue; + BlockPos blockpos4 = blockentity1.getBlockPos(); + MultiBufferSource multibuffersource1 = multibuffersource$buffersource; + posestack.pushPose(); +@@ -1066,6 +_,10 @@ + } + } - this.blockEntityRenderDispatcher.render(blockentity1, f, p_109600_, multibuffersource1); - p_109600_.popPose(); -@@ -1001,9 +_,13 @@ - - synchronized(this.globalBlockEntities) { - for(BlockEntity blockentity : this.globalBlockEntities) { -+ if(!frustum.isVisible(blockentity.getRenderBoundingBox())) continue; - BlockPos blockpos3 = blockentity.getBlockPos(); - p_109600_.pushPose(); - p_109600_.translate((double)blockpos3.getX() - d0, (double)blockpos3.getY() - d1, (double)blockpos3.getZ() - d2); -+ if (this.shouldShowEntityOutlines() && blockentity.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering -+ flag2 = true; -+ } - this.blockEntityRenderDispatcher.render(blockentity, f, p_109600_, multibuffersource$buffersource); - p_109600_.popPose(); - } -@@ -1026,6 +_,7 @@ - this.minecraft.getMainRenderTarget().bindWrite(false); - } - -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_BLOCK_ENTITIES.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - profilerfiller.popPush("destroyProgress"); - - for(Long2ObjectMap.Entry> entry : this.destructionProgress.long2ObjectEntrySet()) { -@@ -1041,7 +_,8 @@ - p_109600_.translate((double)blockpos2.getX() - d0, (double)blockpos2.getY() - d1, (double)blockpos2.getZ() - d2); - PoseStack.Pose posestack$pose1 = p_109600_.last(); - VertexConsumer vertexconsumer1 = new SheetedDecalTextureGenerator(this.renderBuffers.crumblingBufferSource().getBuffer(ModelBakery.DESTROY_TYPES.get(k)), posestack$pose1.pose(), posestack$pose1.normal(), 1.0F); -- this.minecraft.getBlockRenderer().renderBreakingTexture(this.level.getBlockState(blockpos2), blockpos2, this.level, p_109600_, vertexconsumer1); -+ var modelData = level.getModelDataManager().getAt(blockpos2); -+ this.minecraft.getBlockRenderer().renderBreakingTexture(this.level.getBlockState(blockpos2), blockpos2, this.level, p_109600_, vertexconsumer1, modelData == null ? net.minecraftforge.client.model.data.ModelData.EMPTY : modelData); - p_109600_.popPose(); - } - } -@@ -1053,10 +_,13 @@ - profilerfiller.popPush("outline"); - BlockPos blockpos1 = ((BlockHitResult)hitresult).getBlockPos(); - BlockState blockstate = this.level.getBlockState(blockpos1); -+ if (!net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_109600_, multibuffersource$buffersource)) - if (!blockstate.isAir() && this.level.getWorldBorder().isWithinBounds(blockpos1)) { - VertexConsumer vertexconsumer2 = multibuffersource$buffersource.getBuffer(RenderType.lines()); - this.renderHitOutline(p_109600_, vertexconsumer2, p_109604_.getEntity(), d0, d1, d2, blockpos1, blockstate); - } -+ } else if (hitresult != null && hitresult.getType() == HitResult.Type.ENTITY) { -+ net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_109600_, multibuffersource$buffersource); - } - - this.minecraft.debugRenderer.render(p_109600_, multibuffersource$buffersource, d0, d1, d2); -@@ -1088,7 +_,8 @@ - this.particlesTarget.copyDepthFrom(this.minecraft.getMainRenderTarget()); - RenderStateShard.PARTICLES_TARGET.setupRenderState(); - profilerfiller.popPush("particles"); -- this.minecraft.particleEngine.render(p_109600_, multibuffersource$buffersource, p_109606_, p_109604_, f); -+ this.minecraft.particleEngine.render(p_109600_, multibuffersource$buffersource, p_109606_, p_109604_, p_109601_, frustum); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_PARTICLES.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - RenderStateShard.PARTICLES_TARGET.clearRenderState(); - } else { - profilerfiller.popPush("translucent"); -@@ -1102,7 +_,8 @@ - profilerfiller.popPush("string"); - this.renderSectionLayer(RenderType.tripwire(), p_109600_, d0, d1, d2, p_254120_); - profilerfiller.popPush("particles"); -- this.minecraft.particleEngine.render(p_109600_, multibuffersource$buffersource, p_109606_, p_109604_, f); -+ this.minecraft.particleEngine.render(p_109600_, multibuffersource$buffersource, p_109606_, p_109604_, p_109601_, frustum); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_PARTICLES.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - } - - posestack.pushPose(); -@@ -1126,6 +_,7 @@ - RenderStateShard.WEATHER_TARGET.setupRenderState(); - profilerfiller.popPush("weather"); - this.renderSnowAndRain(p_109606_, f, d0, d1, d2); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_WEATHER.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - this.renderWorldBorder(p_109604_); - RenderStateShard.WEATHER_TARGET.clearRenderState(); - this.transparencyChain.process(f); -@@ -1134,6 +_,7 @@ - RenderSystem.depthMask(false); - profilerfiller.popPush("weather"); - this.renderSnowAndRain(p_109606_, f, d0, d1, d2); -+ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_WEATHER.dispatch(this, p_109600_, p_254120_, this.ticks, p_109604_, frustum); - this.renderWorldBorder(p_109604_); - RenderSystem.depthMask(true); - } -@@ -1276,6 +_,7 @@ - shaderinstance.clear(); - VertexBuffer.unbind(); - this.minecraft.getProfiler().pop(); -+ net.minecraftforge.client.ForgeHooksClient.dispatchRenderStage(p_298012_, this, p_298121_, p_297481_, this.ticks, this.minecraft.gameRenderer.getMainCamera(), this.getFrustum()); - p_298012_.clearRenderState(); - } - -@@ -1495,6 +_,8 @@ - } - - public void renderSky(PoseStack p_202424_, Matrix4f p_254034_, float p_202426_, Camera p_202427_, boolean p_202428_, Runnable p_202429_) { -+ if (level.effects().renderSky(level, ticks, p_202426_, p_202424_, p_202427_, p_254034_, p_202428_, p_202429_)) -+ return; - p_202429_.run(); - if (!p_202428_) { - FogType fogtype = p_202427_.getFluidInCamera(); -@@ -1616,6 +_,8 @@ - } - - public void renderClouds(PoseStack p_254145_, Matrix4f p_254537_, float p_254364_, double p_253843_, double p_253663_, double p_253795_) { -+ if (level.effects().renderClouds(level, ticks, p_254364_, p_254145_, p_253843_, p_253663_, p_253795_, p_254537_)) -+ return; - float f = this.level.effects().getCloudHeight(); - if (!Float.isNaN(f)) { - RenderSystem.disableCull(); -@@ -1802,7 +_,7 @@ - boolean flag = false; - if (this.minecraft.options.prioritizeChunkUpdates().get() == PrioritizeChunkUpdates.NEARBY) { - BlockPos blockpos1 = sectionrenderdispatcher$rendersection.getOrigin().offset(8, 8, 8); -- flag = blockpos1.distSqr(blockpos) < 768.0D || sectionrenderdispatcher$rendersection.isDirtyFromPlayer(); -+ flag = !net.minecraftforge.common.ForgeConfig.CLIENT.alwaysSetupTerrainOffThread.get() && (blockpos1.distSqr(blockpos) < 768.0D || sectionrenderdispatcher$rendersection.isDirtyFromPlayer()); // the target is the else block below, so invert the forge addition to get there early - } else if (this.minecraft.options.prioritizeChunkUpdates().get() == PrioritizeChunkUpdates.PLAYER_AFFECTED) { - flag = sectionrenderdispatcher$rendersection.isDirtyFromPlayer(); - } -@@ -2149,7 +_,23 @@ - this.viewArea.setDirty(p_109502_, p_109503_, p_109504_, p_109505_); - } - -+ public Frustum getFrustum() { -+ return this.capturedFrustum != null ? this.capturedFrustum : this.cullingFrustum; -+ } ++ if (this.shouldShowEntityOutlines() && blockentity1.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering ++ flag2 = true; ++ } + -+ public int getTicks() { -+ return this.ticks; -+ } -+ -+ /** -+ * @deprecated Forge: Use item aware function below -+ */ -+ @Deprecated - public void playStreamingMusic(@Nullable SoundEvent p_109515_, BlockPos p_109516_) { -+ this.playStreamingMusic(p_109515_, p_109516_, p_109515_ == null? null : RecordItem.getBySound(p_109515_)); -+ } -+ -+ public void playStreamingMusic(@Nullable SoundEvent p_109515_, BlockPos p_109516_, @Nullable RecordItem musicDiscItem) { - SoundInstance soundinstance = this.playingRecords.get(p_109516_); - if (soundinstance != null) { - this.minecraft.getSoundManager().stop(soundinstance); -@@ -2157,7 +_,7 @@ - } + this.blockEntityRenderDispatcher.render(blockentity1, f, posestack, multibuffersource1); + posestack.popPose(); + } +@@ -1074,9 +_,13 @@ - if (p_109515_ != null) { -- RecordItem recorditem = RecordItem.getBySound(p_109515_); -+ RecordItem recorditem = musicDiscItem; - if (recorditem != null) { - this.minecraft.gui.setNowPlaying(recorditem.getDisplayName()); - } -@@ -2294,7 +_,7 @@ - case 1010: - Item item = Item.byId(p_234307_); - if (item instanceof RecordItem recorditem) { -- this.playStreamingMusic(recorditem.getSound(), p_234306_); -+ this.playStreamingMusic(recorditem.getSound(), p_234306_, recorditem); - } - break; - case 1011: -@@ -2436,7 +_,7 @@ - case 2001: - BlockState blockstate1 = Block.stateById(p_234307_); - if (!blockstate1.isAir()) { -- SoundType soundtype = blockstate1.getSoundType(); -+ SoundType soundtype = blockstate1.getSoundType(this.level, p_234306_, null); - this.level.playLocalSound(p_234306_, soundtype.getBreakSound(), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, false); + synchronized (this.globalBlockEntities) { + for (BlockEntity blockentity : this.globalBlockEntities) { ++ if (!frustum.isVisible(blockentity.getRenderBoundingBox())) continue; + BlockPos blockpos3 = blockentity.getBlockPos(); + posestack.pushPose(); + posestack.translate((double)blockpos3.getX() - d0, (double)blockpos3.getY() - d1, (double)blockpos3.getZ() - d2); ++ if (this.shouldShowEntityOutlines() && blockentity.hasCustomOutlineRendering(this.minecraft.player)) { // FORGE: allow custom outline rendering ++ flag2 = true; ++ } + this.blockEntityRenderDispatcher.render(blockentity, f, posestack, multibuffersource$buffersource); + posestack.popPose(); } +@@ -1099,6 +_,7 @@ + this.minecraft.getMainRenderTarget().bindWrite(false); + } -@@ -2692,7 +_,7 @@ - } else { - int i = p_109538_.getBrightness(LightLayer.SKY, p_109540_); - int j = p_109538_.getBrightness(LightLayer.BLOCK, p_109540_); -- int k = p_109539_.getLightEmission(); -+ int k = p_109539_.getLightEmission(p_109538_, p_109540_); - if (j < k) { - j = k; - } ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_BLOCK_ENTITIES.dispatch(this, p_254120_, p_254120_, this.ticks, p_109604_, frustum); + profilerfiller.popPush("destroyProgress"); + + for (Entry> entry : this.destructionProgress.long2ObjectEntrySet()) { +@@ -1116,7 +_,8 @@ + VertexConsumer vertexconsumer1 = new SheetedDecalTextureGenerator( + this.renderBuffers.crumblingBufferSource().getBuffer(ModelBakery.DESTROY_TYPES.get(k)), posestack$pose1, 1.0F + ); +- this.minecraft.getBlockRenderer().renderBreakingTexture(this.level.getBlockState(blockpos2), blockpos2, this.level, posestack, vertexconsumer1); ++ var modelData = level.getModelDataManager().getAt(blockpos2); ++ this.minecraft.getBlockRenderer().renderBreakingTexture(this.level.getBlockState(blockpos2), blockpos2, this.level, posestack, vertexconsumer1, modelData == null ? net.minecraftforge.client.model.data.ModelData.EMPTY : modelData); + posestack.popPose(); + } + } +@@ -1128,10 +_,13 @@ + profilerfiller.popPush("outline"); + BlockPos blockpos1 = ((BlockHitResult)hitresult).getBlockPos(); + BlockState blockstate = this.level.getBlockState(blockpos1); ++ if (!net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_254120_, multibuffersource$buffersource)) + if (!blockstate.isAir() && this.level.getWorldBorder().isWithinBounds(blockpos1)) { + VertexConsumer vertexconsumer2 = multibuffersource$buffersource.getBuffer(RenderType.lines()); + this.renderHitOutline(posestack, vertexconsumer2, p_109604_.getEntity(), d0, d1, d2, blockpos1, blockstate); + } ++ } else if (hitresult != null && hitresult.getType() == HitResult.Type.ENTITY) { ++ net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_254120_, multibuffersource$buffersource); + } + + this.minecraft.debugRenderer.render(posestack, multibuffersource$buffersource, d0, d1, d2); +@@ -1161,7 +_,8 @@ + this.particlesTarget.copyDepthFrom(this.minecraft.getMainRenderTarget()); + RenderStateShard.PARTICLES_TARGET.setupRenderState(); + profilerfiller.popPush("particles"); +- this.minecraft.particleEngine.render(p_109606_, p_109604_, f); ++ this.minecraft.particleEngine.render(p_109606_, p_109604_, f, frustum); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_PARTICLES.dispatch(this, p_254120_, p_254120_, this.ticks, p_109604_, frustum); + RenderStateShard.PARTICLES_TARGET.clearRenderState(); + } else { + profilerfiller.popPush("translucent"); +@@ -1175,7 +_,8 @@ + profilerfiller.popPush("string"); + this.renderSectionLayer(RenderType.tripwire(), d0, d1, d2, p_254120_, p_330527_); + profilerfiller.popPush("particles"); +- this.minecraft.particleEngine.render(p_109606_, p_109604_, f); ++ this.minecraft.particleEngine.render(p_109606_, p_109604_, f, frustum); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_PARTICLES.dispatch(this, p_254120_, p_254120_, this.ticks, p_109604_, frustum); + } + + if (this.minecraft.options.getCloudsType() != CloudStatus.OFF) { +@@ -1191,6 +_,7 @@ + RenderStateShard.WEATHER_TARGET.setupRenderState(); + profilerfiller.popPush("weather"); + this.renderSnowAndRain(p_109606_, f, d0, d1, d2); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_WEATHER.dispatch(this, posestack.last().pose(), p_254120_, this.ticks, p_109604_, frustum); + this.renderWorldBorder(p_109604_); + RenderStateShard.WEATHER_TARGET.clearRenderState(); + this.transparencyChain.process(f); +@@ -1199,6 +_,7 @@ + RenderSystem.depthMask(false); + profilerfiller.popPush("weather"); + this.renderSnowAndRain(p_109606_, f, d0, d1, d2); ++ net.minecraftforge.client.event.RenderLevelStageEvent.Stage.AFTER_WEATHER.dispatch(this, posestack.last().pose(), p_254120_, this.ticks, p_109604_, frustum); + this.renderWorldBorder(p_109604_); + RenderSystem.depthMask(true); + } +@@ -1344,6 +_,7 @@ + shaderinstance.clear(); + VertexBuffer.unbind(); + this.minecraft.getProfiler().pop(); ++ net.minecraftforge.client.ForgeHooksClient.dispatchRenderStage(p_298012_, this, p_297481_, p_333714_, this.ticks, this.minecraft.gameRenderer.getMainCamera(), this.getFrustum()); + p_298012_.clearRenderState(); + } + +@@ -1604,6 +_,9 @@ + } + + public void renderSky(Matrix4f p_254034_, Matrix4f p_333200_, float p_202426_, Camera p_202427_, boolean p_202428_, Runnable p_202429_) { ++ if (level.effects().renderSky(level, ticks, p_202426_, p_202427_, p_254034_, p_202428_, p_202429_)) { ++ return; ++ } + p_202429_.run(); + if (!p_202428_) { + FogType fogtype = p_202427_.getFluidInCamera(); +@@ -1728,6 +_,9 @@ + } + + public void renderClouds(PoseStack p_254145_, Matrix4f p_254537_, Matrix4f p_330176_, float p_254364_, double p_253843_, double p_253663_, double p_253795_) { ++ if (level.effects().renderClouds(level, ticks, p_254364_, p_254145_, p_253843_, p_253663_, p_253795_, p_254537_)) { ++ return; ++ } + float f = this.level.effects().getCloudHeight(); + if (!Float.isNaN(f)) { + float f1 = 12.0F; +@@ -2017,7 +_,7 @@ + boolean flag = false; + if (this.minecraft.options.prioritizeChunkUpdates().get() == PrioritizeChunkUpdates.NEARBY) { + BlockPos blockpos1 = sectionrenderdispatcher$rendersection.getOrigin().offset(8, 8, 8); +- flag = blockpos1.distSqr(blockpos) < 768.0 || sectionrenderdispatcher$rendersection.isDirtyFromPlayer(); ++ flag = !net.minecraftforge.common.ForgeConfig.CLIENT.alwaysSetupTerrainOffThread.get() && (blockpos1.distSqr(blockpos) < 768.0D || sectionrenderdispatcher$rendersection.isDirtyFromPlayer()); // the target is the else block below, so invert the forge addition to get there early + } else if (this.minecraft.options.prioritizeChunkUpdates().get() == PrioritizeChunkUpdates.PLAYER_AFFECTED) { + flag = sectionrenderdispatcher$rendersection.isDirtyFromPlayer(); + } +@@ -2609,7 +_,23 @@ + this.viewArea.setDirty(p_109502_, p_109503_, p_109504_, p_109505_); + } + ++ public Frustum getFrustum() { ++ return this.capturedFrustum != null ? this.capturedFrustum : this.cullingFrustum; ++ } ++ ++ public int getTicks() { ++ return this.ticks; ++ } ++ ++ /** ++ * @deprecated Forge: Use item aware function below ++ */ ++ @Deprecated + public void playStreamingMusic(@Nullable SoundEvent p_109515_, BlockPos p_109516_) { ++ this.playStreamingMusic(p_109515_, p_109516_, p_109515_ == null? null : RecordItem.getBySound(p_109515_)); ++ } ++ ++ public void playStreamingMusic(@Nullable SoundEvent p_109515_, BlockPos p_109516_, @Nullable RecordItem musicDiscItem) { + SoundInstance soundinstance = this.playingRecords.get(p_109516_); + if (soundinstance != null) { + this.minecraft.getSoundManager().stop(soundinstance); +@@ -2617,7 +_,7 @@ + } + + if (p_109515_ != null) { +- RecordItem recorditem = RecordItem.getBySound(p_109515_); ++ RecordItem recorditem = musicDiscItem; + if (recorditem != null) { + this.minecraft.gui.setNowPlaying(recorditem.getDisplayName()); + } +@@ -2809,7 +_,7 @@ + break; + case 1010: + if (Item.byId(p_234307_) instanceof RecordItem recorditem) { +- this.playStreamingMusic(recorditem.getSound(), p_234306_); ++ this.playStreamingMusic(recorditem.getSound(), p_234306_, recorditem); + } + break; + case 1011: +@@ -3011,7 +_,7 @@ + case 2001: + BlockState blockstate1 = Block.stateById(p_234307_); + if (!blockstate1.isAir()) { +- SoundType soundtype = blockstate1.getSoundType(); ++ SoundType soundtype = blockstate1.getSoundType(this.level, p_234306_, null); + this.level + .playLocalSound( + p_234306_, soundtype.getBreakSound(), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, false +@@ -3466,7 +_,7 @@ + } else { + int i = p_109538_.getBrightness(LightLayer.SKY, p_109540_); + int j = p_109538_.getBrightness(LightLayer.BLOCK, p_109540_); +- int k = p_109539_.getLightEmission(); ++ int k = p_109539_.getLightEmission(p_109538_, p_109540_); + if (j < k) { + j = k; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/LightTexture.java.patch b/patches/minecraft/net/minecraft/client/renderer/LightTexture.java.patch index b846c6931a..72db3bdff6 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LightTexture.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LightTexture.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/renderer/LightTexture.java +++ b/net/minecraft/client/renderer/LightTexture.java -@@ -135,6 +_,8 @@ - } - } +@@ -129,6 +_,8 @@ + } + } -+ clientlevel.effects().adjustLightmapColors(clientlevel, p_109882_, f, f7, f8, j, i, vector3f1); ++ clientlevel.effects().adjustLightmapColors(clientlevel, p_109882_, f, f7, f8, j, i, vector3f1); + - if (f5 > 0.0F) { - float f13 = Math.max(vector3f1.x(), Math.max(vector3f1.y(), vector3f1.z())); - if (f13 < 1.0F) { -@@ -192,7 +_,7 @@ - } + if (f5 > 0.0F) { + float f13 = Math.max(vector3f1.x(), Math.max(vector3f1.y(), vector3f1.z())); + if (f13 < 1.0F) { +@@ -186,7 +_,7 @@ + } - public static int block(int p_109884_) { -- return p_109884_ >> 4 & '\uffff'; -+ return (p_109884_ & 0xFFFF) >> 4; // Forge: Fix fullbright quads showing dark artifacts. Reported as MC-169806 - } + public static int block(int p_109884_) { +- return p_109884_ >> 4 & 65535; ++ return (p_109884_ & 0xFFFF) >> 4; // Forge: Fix fullbright quads showing dark artifacts. Reported as MC-169806 + } - public static int sky(int p_109895_) { + public static int sky(int p_109895_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/PostChain.java.patch b/patches/minecraft/net/minecraft/client/renderer/PostChain.java.patch index 892e044096..e4554ba2c4 100644 --- a/patches/minecraft/net/minecraft/client/renderer/PostChain.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/PostChain.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/renderer/PostChain.java +++ b/net/minecraft/client/renderer/PostChain.java -@@ -157,7 +_,8 @@ - throw new ChainedJsonException("Render target '" + s4 + "' can't be used as depth buffer"); - } +@@ -156,7 +_,8 @@ + throw new ChainedJsonException("Render target '" + s4 + "' can't be used as depth buffer"); + } -- ResourceLocation resourcelocation = new ResourceLocation("textures/effect/" + s4 + ".png"); -+ ResourceLocation rl = ResourceLocation.tryParse(s4); -+ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "textures/effect/" + rl.getPath() + ".png"); - this.resourceManager.getResource(resourcelocation).orElseThrow(() -> { - return new ChainedJsonException("Render target or texture '" + s4 + "' does not exist"); - }); -@@ -260,6 +_,7 @@ - public void addTempTarget(String p_110039_, int p_110040_, int p_110041_) { - RenderTarget rendertarget = new TextureTarget(p_110040_, p_110041_, true, Minecraft.ON_OSX); - rendertarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); -+ if (screenTarget.isStencilEnabled()) { rendertarget.enableStencil(); } - this.customRenderTargets.put(p_110039_, rendertarget); - if (p_110040_ == this.screenWidth && p_110041_ == this.screenHeight) { - this.fullSizedTargets.add(rendertarget); +- ResourceLocation resourcelocation = new ResourceLocation("textures/effect/" + s4 + ".png"); ++ ResourceLocation rl = ResourceLocation.tryParse(s4); ++ ResourceLocation resourcelocation = new ResourceLocation(rl.getNamespace(), "textures/effect/" + rl.getPath() + ".png"); + this.resourceProvider + .getResource(resourcelocation) + .orElseThrow(() -> new ChainedJsonException("Render target or texture '" + s4 + "' does not exist")); +@@ -257,6 +_,7 @@ + public void addTempTarget(String p_110039_, int p_110040_, int p_110041_) { + RenderTarget rendertarget = new TextureTarget(p_110040_, p_110041_, true, Minecraft.ON_OSX); + rendertarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); ++ if (screenTarget.isStencilEnabled()) rendertarget.enableStencil(); + this.customRenderTargets.put(p_110039_, rendertarget); + if (p_110040_ == this.screenWidth && p_110041_ == this.screenHeight) { + this.fullSizedTargets.add(rendertarget); diff --git a/patches/minecraft/net/minecraft/client/renderer/RenderType.java.patch b/patches/minecraft/net/minecraft/client/renderer/RenderType.java.patch index fec77ef1ea..77392ffaae 100644 --- a/patches/minecraft/net/minecraft/client/renderer/RenderType.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/RenderType.java.patch @@ -1,62 +1,62 @@ --- a/net/minecraft/client/renderer/RenderType.java +++ b/net/minecraft/client/renderer/RenderType.java -@@ -323,7 +_,7 @@ - } +@@ -907,7 +_,7 @@ + } - public static RenderType text(ResourceLocation p_110498_) { -- return TEXT.apply(p_110498_); -+ return net.minecraftforge.client.ForgeRenderTypes.getText(p_110498_); - } + public static RenderType text(ResourceLocation p_110498_) { +- return TEXT.apply(p_110498_); ++ return net.minecraftforge.client.ForgeRenderTypes.getText(p_110498_); + } - public static RenderType textBackground() { -@@ -331,19 +_,19 @@ - } + public static RenderType textBackground() { +@@ -915,19 +_,19 @@ + } - public static RenderType textIntensity(ResourceLocation p_173238_) { -- return TEXT_INTENSITY.apply(p_173238_); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensity(p_173238_); - } + public static RenderType textIntensity(ResourceLocation p_173238_) { +- return TEXT_INTENSITY.apply(p_173238_); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensity(p_173238_); + } - public static RenderType textPolygonOffset(ResourceLocation p_181445_) { -- return TEXT_POLYGON_OFFSET.apply(p_181445_); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextPolygonOffset(p_181445_); - } + public static RenderType textPolygonOffset(ResourceLocation p_181445_) { +- return TEXT_POLYGON_OFFSET.apply(p_181445_); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextPolygonOffset(p_181445_); + } - public static RenderType textIntensityPolygonOffset(ResourceLocation p_181447_) { -- return TEXT_INTENSITY_POLYGON_OFFSET.apply(p_181447_); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensityPolygonOffset(p_181447_); - } + public static RenderType textIntensityPolygonOffset(ResourceLocation p_181447_) { +- return TEXT_INTENSITY_POLYGON_OFFSET.apply(p_181447_); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensityPolygonOffset(p_181447_); + } - public static RenderType textSeeThrough(ResourceLocation p_110501_) { -- return TEXT_SEE_THROUGH.apply(p_110501_); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextSeeThrough(p_110501_); - } + public static RenderType textSeeThrough(ResourceLocation p_110501_) { +- return TEXT_SEE_THROUGH.apply(p_110501_); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextSeeThrough(p_110501_); + } - public static RenderType textBackgroundSeeThrough() { -@@ -351,7 +_,7 @@ - } + public static RenderType textBackgroundSeeThrough() { +@@ -935,12 +_,25 @@ + } - public static RenderType textIntensitySeeThrough(ResourceLocation p_173241_) { -- return TEXT_INTENSITY_SEE_THROUGH.apply(p_173241_); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensitySeeThrough(p_173241_); - } + public static RenderType textIntensitySeeThrough(ResourceLocation p_173241_) { +- return TEXT_INTENSITY_SEE_THROUGH.apply(p_173241_); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensitySeeThrough(p_173241_); + } - public static RenderType lightning() { -@@ -678,4 +_,17 @@ - return this.name; - } - } + public static RenderType lightning() { + return LIGHTNING; + } + -+ // FORGE START -+ private int chunkLayerId = -1; -+ /** {@return the unique ID of this {@link RenderType} for chunk rendering purposes, or {@literal -1} if this is not a chunk {@link RenderType}} */ -+ public final int getChunkLayerId() { -+ return chunkLayerId; -+ } -+ static { -+ int i = 0; -+ for (var layer : chunkBufferLayers()) -+ layer.chunkLayerId = i++; -+ } -+ // FORGE END - } ++ // Forge start ++ private int chunkLayerId = -1; ++ /** {@return the unique ID of this {@link RenderType} for chunk rendering purposes, or {@literal -1} if this is not a chunk {@link RenderType}} */ ++ public final int getChunkLayerId() { ++ return chunkLayerId; ++ } ++ static { ++ int i = 0; ++ for (var layer : chunkBufferLayers()) ++ layer.chunkLayerId = i++; ++ } ++ // Forge end + + private static RenderType.CompositeState tripwireState() { + return RenderType.CompositeState.builder() diff --git a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch index b087be5853..806f86e512 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch @@ -1,63 +1,65 @@ --- a/net/minecraft/client/renderer/ScreenEffectRenderer.java +++ b/net/minecraft/client/renderer/ScreenEffectRenderer.java -@@ -30,18 +_,22 @@ - public static void renderScreenEffect(Minecraft p_110719_, PoseStack p_110720_) { - Player player = p_110719_.player; - if (!player.noPhysics) { -- BlockState blockstate = getViewBlockingState(player); -- if (blockstate != null) { -- renderTex(p_110719_.getBlockRenderer().getBlockModelShaper().getParticleIcon(blockstate), p_110720_); -+ org.apache.commons.lang3.tuple.Pair overlay = getOverlayBlock(player); -+ if (overlay != null) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, p_110720_, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) -+ renderTex(p_110719_.getBlockRenderer().getBlockModelShaper().getTexture(overlay.getLeft(), p_110719_.level, overlay.getRight()), p_110720_); - } - } +@@ -31,17 +_,24 @@ + Player player = p_110719_.player; + if (!player.noPhysics) { + BlockState blockstate = getViewBlockingState(player); +- if (blockstate != null) { +- renderTex(p_110719_.getBlockRenderer().getBlockModelShaper().getParticleIcon(blockstate), p_110720_); ++ var overlay = getOverlayBlock(player); ++ if (overlay != null) { ++ if (!net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, p_110720_, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) { ++ renderTex(p_110719_.getBlockRenderer().getBlockModelShaper().getTexture(overlay.getLeft(), p_110719_.level, overlay.getRight()), p_110720_); ++ } + } + } - if (!p_110719_.player.isSpectator()) { - if (p_110719_.player.isEyeInFluid(FluidTags.WATER)) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, p_110720_)) - renderWater(p_110719_, p_110720_); - } -+ else if (!player.getEyeInFluidType().isAir()) net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(p_110719_, p_110720_); + if (!p_110719_.player.isSpectator()) { + if (p_110719_.player.isEyeInFluid(FluidTags.WATER)) { ++ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, p_110720_)) + renderWater(p_110719_, p_110720_); ++ } else if (!player.getEyeInFluidType().isAir()) { ++ net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(p_110719_, p_110720_); + } - if (p_110719_.player.isOnFire()) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, p_110720_)) - renderFire(p_110719_, p_110720_); - } - } -@@ -50,6 +_,11 @@ + if (p_110719_.player.isOnFire()) { ++ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, p_110720_)) + renderFire(p_110719_, p_110720_); + } + } +@@ -49,6 +_,12 @@ - @Nullable - private static BlockState getViewBlockingState(Player p_110717_) { -+ return getOverlayBlock(p_110717_).getLeft(); -+ } + @Nullable + private static BlockState getViewBlockingState(Player p_110717_) { ++ var ret = getOverlayBlock(p_110717_); ++ return ret == null ? null : ret.getLeft(); ++ } + -+ @Nullable -+ private static org.apache.commons.lang3.tuple.Pair getOverlayBlock(Player p_110717_) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); ++ @Nullable ++ private static org.apache.commons.lang3.tuple.Pair getOverlayBlock(Player p_110717_) { + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - for(int i = 0; i < 8; ++i) { -@@ -59,7 +_,7 @@ - blockpos$mutableblockpos.set(d0, d1, d2); - BlockState blockstate = p_110717_.level().getBlockState(blockpos$mutableblockpos); - if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.isViewBlocking(p_110717_.level(), blockpos$mutableblockpos)) { -- return blockstate; -+ return org.apache.commons.lang3.tuple.Pair.of(blockstate, blockpos$mutableblockpos.immutable()); - } - } + for (int i = 0; i < 8; i++) { +@@ -58,7 +_,7 @@ + blockpos$mutableblockpos.set(d0, d1, d2); + BlockState blockstate = p_110717_.level().getBlockState(blockpos$mutableblockpos); + if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.isViewBlocking(p_110717_.level(), blockpos$mutableblockpos)) { +- return blockstate; ++ return org.apache.commons.lang3.tuple.Pair.of(blockstate, blockpos$mutableblockpos.immutable()); + } + } -@@ -90,8 +_,12 @@ - } +@@ -89,8 +_,12 @@ + } - private static void renderWater(Minecraft p_110726_, PoseStack p_110727_) { -+ renderFluid(p_110726_, p_110727_, UNDERWATER_LOCATION); -+ } + private static void renderWater(Minecraft p_110726_, PoseStack p_110727_) { ++ renderFluid(p_110726_, p_110727_, UNDERWATER_LOCATION); ++ } + -+ public static void renderFluid(Minecraft p_110726_, PoseStack p_110727_, ResourceLocation texture) { - RenderSystem.setShader(GameRenderer::getPositionTexShader); -- RenderSystem.setShaderTexture(0, UNDERWATER_LOCATION); -+ RenderSystem.setShaderTexture(0, texture); - BufferBuilder bufferbuilder = Tesselator.getInstance().getBuilder(); - BlockPos blockpos = BlockPos.containing(p_110726_.player.getX(), p_110726_.player.getEyeY(), p_110726_.player.getZ()); - float f = LightTexture.getBrightness(p_110726_.player.level().dimensionType(), p_110726_.player.level().getMaxLocalRawBrightness(blockpos)); ++ public static void renderFluid(Minecraft p_110726_, PoseStack p_110727_, ResourceLocation texture) { + RenderSystem.setShader(GameRenderer::getPositionTexShader); +- RenderSystem.setShaderTexture(0, UNDERWATER_LOCATION); ++ RenderSystem.setShaderTexture(0, texture); + BufferBuilder bufferbuilder = Tesselator.getInstance().getBuilder(); + BlockPos blockpos = BlockPos.containing(p_110726_.player.getX(), p_110726_.player.getEyeY(), p_110726_.player.getZ()); + float f = LightTexture.getBrightness(p_110726_.player.level().dimensionType(), p_110726_.player.level().getMaxLocalRawBrightness(blockpos)); diff --git a/patches/minecraft/net/minecraft/client/renderer/ShaderInstance.java.patch b/patches/minecraft/net/minecraft/client/renderer/ShaderInstance.java.patch index 830643f33f..bf0493bea0 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ShaderInstance.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ShaderInstance.java.patch @@ -1,54 +1,59 @@ --- a/net/minecraft/client/renderer/ShaderInstance.java +++ b/net/minecraft/client/renderer/ShaderInstance.java -@@ -98,10 +_,14 @@ - @Nullable - public final Uniform CHUNK_OFFSET; +@@ -94,10 +_,15 @@ + @Nullable + public final Uniform CHUNK_OFFSET; -+ @Deprecated // FORGE: Use the ResourceLocation variant below - public ShaderInstance(ResourceProvider p_173336_, String p_173337_, VertexFormat p_173338_) throws IOException { -- this.name = p_173337_; -+ this(p_173336_, new ResourceLocation(p_173337_), p_173338_); -+ } -+ public ShaderInstance(ResourceProvider p_173336_, ResourceLocation shaderLocation, VertexFormat p_173338_) throws IOException { -+ this.name = shaderLocation.getNamespace().equals("minecraft") ? shaderLocation.getPath() : shaderLocation.toString(); - this.vertexFormat = p_173338_; -- ResourceLocation resourcelocation = new ResourceLocation("shaders/core/" + p_173337_ + ".json"); -+ ResourceLocation resourcelocation = new ResourceLocation(shaderLocation.getNamespace(), "shaders/core/" + shaderLocation.getPath() + ".json"); ++ @Deprecated // Forge: Use the ResourceLocation variant below + public ShaderInstance(ResourceProvider p_173336_, String p_173337_, VertexFormat p_173338_) throws IOException { +- this.name = p_173337_; ++ this(p_173336_, new ResourceLocation(p_173337_), p_173338_); ++ } ++ ++ public ShaderInstance(ResourceProvider p_173336_, ResourceLocation shaderLocation, VertexFormat p_173338_) throws IOException { ++ this.name = shaderLocation.getNamespace().equals("minecraft") ? shaderLocation.getPath() : shaderLocation.toString(); + this.vertexFormat = p_173338_; +- ResourceLocation resourcelocation = new ResourceLocation("shaders/core/" + p_173337_ + ".json"); ++ ResourceLocation resourcelocation = new ResourceLocation(shaderLocation.getNamespace(), "shaders/core/" + shaderLocation.getPath() + ".json"); - try (Reader reader = p_173336_.openAsReader(resourcelocation)) { - JsonObject jsonobject = GsonHelper.parse(reader); -@@ -208,8 +_,10 @@ - Program program1 = p_173342_.getPrograms().get(p_173343_); - Program program; - if (program1 == null) { -- String s = "shaders/core/" + p_173343_ + p_173342_.getExtension(); -- Resource resource = p_173341_.getResourceOrThrow(new ResourceLocation(s)); -+ ResourceLocation loc = new ResourceLocation(p_173343_); -+ String s = "shaders/core/" + loc.getPath() + p_173342_.getExtension(); -+ ResourceLocation resourcelocation = new ResourceLocation(loc.getNamespace(), s); -+ Resource resource = p_173341_.getResourceOrThrow(resourcelocation); + try (Reader reader = p_173336_.openAsReader(resourcelocation)) { + JsonObject jsonobject = GsonHelper.parse(reader); +@@ -178,8 +_,10 @@ + Program program1 = p_173342_.getPrograms().get(p_173343_); + Program program; + if (program1 == null) { +- String s = "shaders/core/" + p_173343_ + p_173342_.getExtension(); +- Resource resource = p_173341_.getResourceOrThrow(new ResourceLocation(s)); ++ ResourceLocation loc = new ResourceLocation(p_173343_); ++ String s = "shaders/core/" + loc.getPath() + p_173342_.getExtension(); ++ ResourceLocation resourcelocation = new ResourceLocation(loc.getNamespace(), s); ++ Resource resource = p_173341_.getResourceOrThrow(resourcelocation); - try (InputStream inputstream = resource.open()) { - final String s1 = FileUtil.getFullResourcePath(s); -@@ -217,16 +_,17 @@ - private final Set importedPaths = Sets.newHashSet(); + try (InputStream inputstream = resource.open()) { + final String s1 = FileUtil.getFullResourcePath(s); +@@ -188,12 +_,11 @@ - public String applyImport(boolean p_173374_, String p_173375_) { -- p_173375_ = FileUtil.normalizeResourcePath((p_173374_ ? s1 : "shaders/include/") + p_173375_); -- if (!this.importedPaths.add(p_173375_)) { -+ // FORGE: use the mod's namespace to look up resources if specified -+ ResourceLocation resourcelocation = net.minecraftforge.client.ForgeHooksClient.getShaderImportLocation(s1, p_173374_, p_173375_); -+ if (!this.importedPaths.add(resourcelocation.toString())) { - return null; - } else { -- ResourceLocation resourcelocation = new ResourceLocation(p_173375_); + @Override + public String applyImport(boolean p_173374_, String p_173375_) { +- p_173375_ = FileUtil.normalizeResourcePath((p_173374_ ? s1 : "shaders/include/") + p_173375_); +- if (!this.importedPaths.add(p_173375_)) { ++ // Forge: use the mod's namespace to look up resources if specified ++ ResourceLocation resourcelocation = net.minecraftforge.client.ForgeHooksClient.getShaderImportLocation(s1, p_173374_, p_173375_); ++ if (!this.importedPaths.add(resourcelocation.toString())) { + return null; + } else { +- ResourceLocation resourcelocation = new ResourceLocation(p_173375_); +- + try { + String s2; + try (Reader reader = p_173341_.openAsReader(resourcelocation)) { +@@ -202,7 +_,8 @@ - try (Reader reader = p_173341_.openAsReader(resourcelocation)) { - return IOUtils.toString(reader); - } catch (IOException ioexception) { -- ShaderInstance.LOGGER.error("Could not open GLSL import {}: {}", p_173375_, ioexception.getMessage()); -+ // FORGE: specify the namespace of the failed import in case of duplicates from multiple mods -+ ShaderInstance.LOGGER.error("Could not open GLSL import {}: {}", resourcelocation, ioexception.getMessage()); - return "#error " + ioexception.getMessage(); - } - } + return s2; + } catch (IOException ioexception) { +- ShaderInstance.LOGGER.error("Could not open GLSL import {}: {}", p_173375_, ioexception.getMessage()); ++ // Forge: specify the namespace of the failed import in case of duplicates from multiple mods ++ ShaderInstance.LOGGER.error("Could not open GLSL import {}: {}", resourcelocation, ioexception.getMessage()); + return "#error " + ioexception.getMessage(); + } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch b/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch index 8dd89c6adf..c8635260c6 100644 --- a/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch @@ -1,42 +1,42 @@ --- a/net/minecraft/client/renderer/Sheets.java +++ b/net/minecraft/client/renderer/Sheets.java -@@ -146,11 +_,13 @@ - } +@@ -144,11 +_,13 @@ + } - private static Material createSignMaterial(WoodType p_173386_) { -- return new Material(SIGN_SHEET, new ResourceLocation("entity/signs/" + p_173386_.name())); -+ ResourceLocation location = new ResourceLocation(p_173386_.name()); -+ return new Material(SIGN_SHEET, new ResourceLocation(location.getNamespace(), "entity/signs/" + location.getPath())); - } + private static Material createSignMaterial(WoodType p_173386_) { +- return new Material(SIGN_SHEET, new ResourceLocation("entity/signs/" + p_173386_.name())); ++ ResourceLocation location = new ResourceLocation(p_173386_.name()); ++ return new Material(SIGN_SHEET, new ResourceLocation(location.getNamespace(), "entity/signs/" + location.getPath())); + } - private static Material createHangingSignMaterial(WoodType p_251735_) { -- return new Material(SIGN_SHEET, new ResourceLocation("entity/signs/hanging/" + p_251735_.name())); -+ ResourceLocation location = new ResourceLocation(p_251735_.name()); -+ return new Material(SIGN_SHEET, new ResourceLocation(location.getNamespace(), "entity/signs/hanging/" + location.getPath())); - } + private static Material createHangingSignMaterial(WoodType p_251735_) { +- return new Material(SIGN_SHEET, new ResourceLocation("entity/signs/hanging/" + p_251735_.name())); ++ ResourceLocation location = new ResourceLocation(p_251735_.name()); ++ return new Material(SIGN_SHEET, new ResourceLocation(location.getNamespace(), "entity/signs/hanging/" + location.getPath())); + } - public static Material getSignMaterial(WoodType p_173382_) { -@@ -209,6 +_,23 @@ - case SINGLE: - default: - return p_110773_; -+ } -+ } + public static Material getSignMaterial(WoodType p_173382_) { +@@ -207,6 +_,23 @@ + case SINGLE: + default: + return p_110773_; ++ } ++ } + -+ /** -+ * Not threadsafe. Enqueue it in client setup. -+ */ -+ public static void addWoodType(WoodType woodType) { -+ SIGN_MATERIALS.put(woodType, createSignMaterial(woodType)); -+ HANGING_SIGN_MATERIALS.put(woodType, createHangingSignMaterial(woodType)); -+ } ++ /** ++ * Not thread-safe. Enqueue it in client setup. ++ */ ++ public static void addWoodType(WoodType woodType) { ++ SIGN_MATERIALS.put(woodType, createSignMaterial(woodType)); ++ HANGING_SIGN_MATERIALS.put(woodType, createHangingSignMaterial(woodType)); ++ } + -+ static { -+ if (net.minecraftforge.fml.ModLoader.isLoadingStateValid() && !net.minecraftforge.fml.ModLoader.get().hasCompletedState("LOAD_REGISTRIES")) { -+ com.mojang.logging.LogUtils.getLogger().error( -+ "net.minecraft.client.renderer.Sheets loaded too early, modded registry-based materials may not work correctly", -+ new IllegalStateException("net.minecraft.client.renderer.Sheets loaded too early") -+ ); - } - } ++ static { ++ if (net.minecraftforge.fml.ModLoader.isLoadingStateValid() && !net.minecraftforge.fml.ModLoader.get().hasCompletedState("LOAD_REGISTRIES")) { ++ com.mojang.logging.LogUtils.getLogger().error( ++ "net.minecraft.client.renderer.Sheets loaded too early, modded registry-based materials may not work correctly", ++ new IllegalStateException("net.minecraft.client.renderer.Sheets loaded too early") ++ ); + } + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/SpriteCoordinateExpander.java.patch b/patches/minecraft/net/minecraft/client/renderer/SpriteCoordinateExpander.java.patch index f249d04f50..3ac5210830 100644 --- a/patches/minecraft/net/minecraft/client/renderer/SpriteCoordinateExpander.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/SpriteCoordinateExpander.java.patch @@ -1,42 +1,47 @@ --- a/net/minecraft/client/renderer/SpriteCoordinateExpander.java +++ b/net/minecraft/client/renderer/SpriteCoordinateExpander.java -@@ -16,27 +_,33 @@ - } +@@ -17,32 +_,38 @@ - public VertexConsumer vertex(double p_110801_, double p_110802_, double p_110803_) { -- return this.delegate.vertex(p_110801_, p_110802_, p_110803_); -+ this.delegate.vertex(p_110801_, p_110802_, p_110803_); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer vertex(double p_110801_, double p_110802_, double p_110803_) { +- return this.delegate.vertex(p_110801_, p_110802_, p_110803_); ++ this.delegate.vertex(p_110801_, p_110802_, p_110803_); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public VertexConsumer color(int p_110826_, int p_110827_, int p_110828_, int p_110829_) { -- return this.delegate.color(p_110826_, p_110827_, p_110828_, p_110829_); -+ this.delegate.color(p_110826_, p_110827_, p_110828_, p_110829_); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer color(int p_110826_, int p_110827_, int p_110828_, int p_110829_) { +- return this.delegate.color(p_110826_, p_110827_, p_110828_, p_110829_); ++ this.delegate.color(p_110826_, p_110827_, p_110828_, p_110829_); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public VertexConsumer uv(float p_110805_, float p_110806_) { -- return this.delegate.uv(this.sprite.getU(p_110805_), this.sprite.getV(p_110806_)); -+ this.delegate.uv(this.sprite.getU(p_110805_), this.sprite.getV(p_110806_)); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer uv(float p_110805_, float p_110806_) { +- return this.delegate.uv(this.sprite.getU(p_110805_), this.sprite.getV(p_110806_)); ++ this.delegate.uv(this.sprite.getU(p_110805_), this.sprite.getV(p_110806_)); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public VertexConsumer overlayCoords(int p_110823_, int p_110824_) { -- return this.delegate.overlayCoords(p_110823_, p_110824_); -+ this.delegate.overlayCoords(p_110823_, p_110824_); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer overlayCoords(int p_110823_, int p_110824_) { +- return this.delegate.overlayCoords(p_110823_, p_110824_); ++ this.delegate.overlayCoords(p_110823_, p_110824_); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public VertexConsumer uv2(int p_110835_, int p_110836_) { -- return this.delegate.uv2(p_110835_, p_110836_); -+ this.delegate.uv2(p_110835_, p_110836_); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer uv2(int p_110835_, int p_110836_) { +- return this.delegate.uv2(p_110835_, p_110836_); ++ this.delegate.uv2(p_110835_, p_110836_); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public VertexConsumer normal(float p_110831_, float p_110832_, float p_110833_) { -- return this.delegate.normal(p_110831_, p_110832_, p_110833_); -+ this.delegate.normal(p_110831_, p_110832_, p_110833_); -+ return this; //Forge: Fix MC-263524 not working with chained methods - } + @Override + public VertexConsumer normal(float p_110831_, float p_110832_, float p_110833_) { +- return this.delegate.normal(p_110831_, p_110832_, p_110833_); ++ this.delegate.normal(p_110831_, p_110832_, p_110833_); ++ return this; // Forge: Fix MC-263524 not working with chained methods + } - public void endVertex() { + @Override diff --git a/patches/minecraft/net/minecraft/client/renderer/block/BlockModelShaper.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/BlockModelShaper.java.patch index 380eca98a3..2be632c1b7 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/BlockModelShaper.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/BlockModelShaper.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/client/renderer/block/BlockModelShaper.java +++ b/net/minecraft/client/renderer/block/BlockModelShaper.java -@@ -21,8 +_,15 @@ - this.modelManager = p_110880_; - } +@@ -22,8 +_,15 @@ + this.modelManager = p_110880_; + } -+ @Deprecated - public TextureAtlasSprite getParticleIcon(BlockState p_110883_) { -- return this.getBlockModel(p_110883_).getParticleIcon(); -+ return this.getBlockModel(p_110883_).getParticleIcon(net.minecraftforge.client.model.data.ModelData.EMPTY); -+ } ++ @Deprecated + public TextureAtlasSprite getParticleIcon(BlockState p_110883_) { +- return this.getBlockModel(p_110883_).getParticleIcon(); ++ return this.getBlockModel(p_110883_).getParticleIcon(net.minecraftforge.client.model.data.ModelData.EMPTY); ++ } + -+ public TextureAtlasSprite getTexture(BlockState p_110883_, net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) { -+ var data = level.getModelDataManager().getAt(pos); -+ BakedModel model = this.getBlockModel(p_110883_); -+ return model.getParticleIcon(model.getModelData(level, pos, p_110883_, data == null ? net.minecraftforge.client.model.data.ModelData.EMPTY : data)); - } ++ public TextureAtlasSprite getTexture(BlockState p_110883_, net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) { ++ var data = level.getModelDataManager().getAt(pos); ++ BakedModel model = this.getBlockModel(p_110883_); ++ return model.getParticleIcon(model.getModelData(level, pos, p_110883_, data == null ? net.minecraftforge.client.model.data.ModelData.EMPTY : data)); + } - public BakedModel getBlockModel(BlockState p_110894_) { + public BakedModel getBlockModel(BlockState p_110894_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/block/BlockRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/BlockRenderDispatcher.java.patch index a01655c93f..eaedf20bfb 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/BlockRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/BlockRenderDispatcher.java.patch @@ -1,68 +1,100 @@ --- a/net/minecraft/client/renderer/block/BlockRenderDispatcher.java +++ b/net/minecraft/client/renderer/block/BlockRenderDispatcher.java @@ -37,7 +_,7 @@ - this.blockModelShaper = p_173399_; - this.blockEntityRenderer = p_173400_; - this.blockColors = p_173401_; -- this.modelRenderer = new ModelBlockRenderer(this.blockColors); -+ this.modelRenderer = new net.minecraftforge.client.model.lighting.ForgeModelBlockRenderer(this.blockColors); - this.liquidBlockRenderer = new LiquidBlockRenderer(); - } + this.blockModelShaper = p_173399_; + this.blockEntityRenderer = p_173400_; + this.blockColors = p_173401_; +- this.modelRenderer = new ModelBlockRenderer(this.blockColors); ++ this.modelRenderer = new net.minecraftforge.client.model.lighting.ForgeModelBlockRenderer(this.blockColors); + this.liquidBlockRenderer = new LiquidBlockRenderer(); + } -@@ -45,19 +_,27 @@ - return this.blockModelShaper; - } +@@ -45,12 +_,22 @@ + return this.blockModelShaper; + } -+ @Deprecated //Forge: Model data parameter - public void renderBreakingTexture(BlockState p_110919_, BlockPos p_110920_, BlockAndTintGetter p_110921_, PoseStack p_110922_, VertexConsumer p_110923_) { -+ renderBreakingTexture(p_110919_, p_110920_, p_110921_, p_110922_, p_110923_, net.minecraftforge.client.model.data.ModelData.EMPTY); -+ } -+ public void renderBreakingTexture(BlockState p_110919_, BlockPos p_110920_, BlockAndTintGetter p_110921_, PoseStack p_110922_, VertexConsumer p_110923_, net.minecraftforge.client.model.data.ModelData modelData) { - if (p_110919_.getRenderShape() == RenderShape.MODEL) { - BakedModel bakedmodel = this.blockModelShaper.getBlockModel(p_110919_); - long i = p_110919_.getSeed(p_110920_); -- this.modelRenderer.tesselateBlock(p_110921_, bakedmodel, p_110919_, p_110920_, p_110922_, p_110923_, true, this.random, i, OverlayTexture.NO_OVERLAY); -+ this.modelRenderer.tesselateBlock(p_110921_, bakedmodel, p_110919_, p_110920_, p_110922_, p_110923_, true, this.random, i, OverlayTexture.NO_OVERLAY, modelData, null); - } - } ++ @Deprecated //Forge: Model data parameter + public void renderBreakingTexture(BlockState p_110919_, BlockPos p_110920_, BlockAndTintGetter p_110921_, PoseStack p_110922_, VertexConsumer p_110923_) { ++ renderBreakingTexture(p_110919_, p_110920_, p_110921_, p_110922_, p_110923_, net.minecraftforge.client.model.data.ModelData.EMPTY); ++ } ++ ++ public void renderBreakingTexture(BlockState p_110919_, BlockPos p_110920_, BlockAndTintGetter p_110921_, PoseStack p_110922_, VertexConsumer p_110923_, net.minecraftforge.client.model.data.ModelData modelData) { + if (p_110919_.getRenderShape() == RenderShape.MODEL) { + BakedModel bakedmodel = this.blockModelShaper.getBlockModel(p_110919_); + long i = p_110919_.getSeed(p_110920_); +- this.modelRenderer.tesselateBlock(p_110921_, bakedmodel, p_110919_, p_110920_, p_110922_, p_110923_, true, this.random, i, OverlayTexture.NO_OVERLAY); ++ this.modelRenderer.tesselateBlock(p_110921_, bakedmodel, p_110919_, p_110920_, p_110922_, p_110923_, true, this.random, i, OverlayTexture.NO_OVERLAY, modelData, null); + } ++ } ++ ++ @Deprecated //Forge: Model data and render type parameter ++ public void renderBatched(BlockState p_234356_, BlockPos p_234357_, BlockAndTintGetter p_234358_, PoseStack p_234359_, VertexConsumer p_234360_, boolean p_234361_, RandomSource p_234362_) { ++ renderBatched(p_234356_, p_234357_, p_234358_, p_234359_, p_234360_, p_234361_, p_234362_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); + } -+ @Deprecated //Forge: Model data and render type parameter - public void renderBatched(BlockState p_234356_, BlockPos p_234357_, BlockAndTintGetter p_234358_, PoseStack p_234359_, VertexConsumer p_234360_, boolean p_234361_, RandomSource p_234362_) { -+ renderBatched(p_234356_, p_234357_, p_234358_, p_234359_, p_234360_, p_234361_, p_234362_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void renderBatched(BlockState p_234356_, BlockPos p_234357_, BlockAndTintGetter p_234358_, PoseStack p_234359_, VertexConsumer p_234360_, boolean p_234361_, RandomSource p_234362_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { - try { - RenderShape rendershape = p_234356_.getRenderShape(); - if (rendershape == RenderShape.MODEL) { -- this.modelRenderer.tesselateBlock(p_234358_, this.getBlockModel(p_234356_), p_234356_, p_234357_, p_234359_, p_234360_, p_234361_, p_234362_, p_234356_.getSeed(p_234357_), OverlayTexture.NO_OVERLAY); -+ this.modelRenderer.tesselateBlock(p_234358_, this.getBlockModel(p_234356_), p_234356_, p_234357_, p_234359_, p_234360_, p_234361_, p_234362_, p_234356_.getSeed(p_234357_), OverlayTexture.NO_OVERLAY, modelData, renderType); - } + public void renderBatched( +@@ -60,7 +_,9 @@ + PoseStack p_234359_, + VertexConsumer p_234360_, + boolean p_234361_, +- RandomSource p_234362_ ++ RandomSource p_234362_, ++ net.minecraftforge.client.model.data.ModelData modelData, ++ net.minecraft.client.renderer.RenderType renderType + ) { + try { + RenderShape rendershape = p_234356_.getRenderShape(); +@@ -76,7 +_,9 @@ + p_234361_, + p_234362_, + p_234356_.getSeed(p_234357_), +- OverlayTexture.NO_OVERLAY ++ OverlayTexture.NO_OVERLAY, ++ modelData, ++ renderType + ); + } + } catch (Throwable throwable) { +@@ -106,7 +_,12 @@ + return this.blockModelShaper.getBlockModel(p_110911_); + } - } catch (Throwable throwable) { -@@ -87,7 +_,11 @@ - return this.blockModelShaper.getBlockModel(p_110911_); - } - -+ @Deprecated //Forge: Model data and render type parameter - public void renderSingleBlock(BlockState p_110913_, PoseStack p_110914_, MultiBufferSource p_110915_, int p_110916_, int p_110917_) { -+ renderSingleBlock(p_110913_, p_110914_, p_110915_, p_110916_, p_110917_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void renderSingleBlock(BlockState p_110913_, PoseStack p_110914_, MultiBufferSource p_110915_, int p_110916_, int p_110917_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { - RenderShape rendershape = p_110913_.getRenderShape(); - if (rendershape != RenderShape.INVISIBLE) { - switch (rendershape) { -@@ -97,10 +_,12 @@ - float f = (float)(i >> 16 & 255) / 255.0F; - float f1 = (float)(i >> 8 & 255) / 255.0F; - float f2 = (float)(i & 255) / 255.0F; -- this.modelRenderer.renderModel(p_110914_.last(), p_110915_.getBuffer(ItemBlockRenderTypes.getRenderType(p_110913_, false)), p_110913_, bakedmodel, f, f1, f2, p_110916_, p_110917_); -+ for (net.minecraft.client.renderer.RenderType rt : bakedmodel.getRenderTypes(p_110913_, RandomSource.create(42), modelData)) -+ this.modelRenderer.renderModel(p_110914_.last(), p_110915_.getBuffer(renderType != null ? renderType : net.minecraftforge.client.RenderTypeHelper.getEntityRenderType(rt, false)), p_110913_, bakedmodel, f, f1, f2, p_110916_, p_110917_, modelData, rt); - break; - case ENTITYBLOCK_ANIMATED: -- this.blockEntityRenderer.renderByItem(new ItemStack(p_110913_.getBlock()), ItemDisplayContext.NONE, p_110914_, p_110915_, p_110916_, p_110917_); -+ ItemStack stack = new ItemStack(p_110913_.getBlock()); -+ net.minecraftforge.client.extensions.common.IClientItemExtensions.of(stack).getCustomRenderer().renderByItem(stack, ItemDisplayContext.NONE, p_110914_, p_110915_, p_110916_, p_110917_); - } - - } ++ @Deprecated //Forge: Model data and render type parameter + public void renderSingleBlock(BlockState p_110913_, PoseStack p_110914_, MultiBufferSource p_110915_, int p_110916_, int p_110917_) { ++ renderSingleBlock(p_110913_, p_110914_, p_110915_, p_110916_, p_110917_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); ++ } ++ ++ public void renderSingleBlock(BlockState p_110913_, PoseStack p_110914_, MultiBufferSource p_110915_, int p_110916_, int p_110917_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { + RenderShape rendershape = p_110913_.getRenderShape(); + if (rendershape != RenderShape.INVISIBLE) { + switch (rendershape) { +@@ -116,21 +_,26 @@ + float f = (float)(i >> 16 & 0xFF) / 255.0F; + float f1 = (float)(i >> 8 & 0xFF) / 255.0F; + float f2 = (float)(i & 0xFF) / 255.0F; ++ for (var rt : bakedmodel.getRenderTypes(p_110913_, RandomSource.create(42), modelData)) + this.modelRenderer + .renderModel( + p_110914_.last(), +- p_110915_.getBuffer(ItemBlockRenderTypes.getRenderType(p_110913_, false)), ++ p_110915_.getBuffer(renderType != null ? renderType : net.minecraftforge.client.RenderTypeHelper.getEntityRenderType(rt, false)), + p_110913_, + bakedmodel, + f, + f1, + f2, + p_110916_, +- p_110917_ ++ p_110917_, ++ modelData, ++ rt + ); + break; + case ENTITYBLOCK_ANIMATED: +- this.blockEntityRenderer.renderByItem(new ItemStack(p_110913_.getBlock()), ItemDisplayContext.NONE, p_110914_, p_110915_, p_110916_, p_110917_); ++ ItemStack stack = new ItemStack(p_110913_.getBlock()); ++ var renderer = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(stack).getCustomRenderer(); ++ renderer.renderByItem(stack, ItemDisplayContext.NONE, p_110914_, p_110915_, p_110916_, p_110917_); + } + } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/block/LiquidBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/LiquidBlockRenderer.java.patch index b78d0e6870..51a5b8ce9e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/LiquidBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/LiquidBlockRenderer.java.patch @@ -1,102 +1,106 @@ --- a/net/minecraft/client/renderer/block/LiquidBlockRenderer.java +++ b/net/minecraft/client/renderer/block/LiquidBlockRenderer.java -@@ -68,8 +_,9 @@ +@@ -70,8 +_,10 @@ - public void tesselate(BlockAndTintGetter p_234370_, BlockPos p_234371_, VertexConsumer p_234372_, BlockState p_234373_, FluidState p_234374_) { - boolean flag = p_234374_.is(FluidTags.LAVA); -- TextureAtlasSprite[] atextureatlassprite = flag ? this.lavaIcons : this.waterIcons; -- int i = flag ? 16777215 : BiomeColors.getAverageWaterColor(p_234370_, p_234371_); -+ TextureAtlasSprite[] atextureatlassprite = net.minecraftforge.client.ForgeHooksClient.getFluidSprites(p_234370_, p_234371_, p_234374_); -+ int i = net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(p_234374_).getTintColor(p_234374_, p_234370_, p_234371_); -+ float alpha = (float)(i >> 24 & 255) / 255.0F; - float f = (float)(i >> 16 & 255) / 255.0F; - float f1 = (float)(i >> 8 & 255) / 255.0F; - float f2 = (float)(i & 255) / 255.0F; -@@ -178,15 +_,15 @@ - float f52 = f4 * f; - float f30 = f4 * f1; - float f31 = f4 * f2; -- this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f8, d0 + 0.0D, f52, f30, f31, f18, f22, l); -- this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f10, d0 + 1.0D, f52, f30, f31, f19, f23, l); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f9, d0 + 1.0D, f52, f30, f31, f20, f24, l); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f7, d0 + 0.0D, f52, f30, f31, f21, f25, l); -+ this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f8, d0 + 0.0D, f52, f30, f31, alpha, f18, f22, l); -+ this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f10, d0 + 1.0D, f52, f30, f31, alpha, f19, f23, l); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f9, d0 + 1.0D, f52, f30, f31, alpha, f20, f24, l); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f7, d0 + 0.0D, f52, f30, f31, alpha, f21, f25, l); - if (p_234374_.shouldRenderBackwardUpFace(p_234370_, p_234371_.above())) { -- this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f8, d0 + 0.0D, f52, f30, f31, f18, f22, l); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f7, d0 + 0.0D, f52, f30, f31, f21, f25, l); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f9, d0 + 1.0D, f52, f30, f31, f20, f24, l); -- this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f10, d0 + 1.0D, f52, f30, f31, f19, f23, l); -+ this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f8, d0 + 0.0D, f52, f30, f31, alpha, f18, f22, l); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f7, d0 + 0.0D, f52, f30, f31, alpha, f21, f25, l); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f9, d0 + 1.0D, f52, f30, f31, alpha, f20, f24, l); -+ this.vertex(p_234372_, d1 + 0.0D, d2 + (double)f10, d0 + 1.0D, f52, f30, f31, alpha, f19, f23, l); + public void tesselate(BlockAndTintGetter p_234370_, BlockPos p_234371_, VertexConsumer p_234372_, BlockState p_234373_, FluidState p_234374_) { + boolean flag = p_234374_.is(FluidTags.LAVA); +- TextureAtlasSprite[] atextureatlassprite = flag ? this.lavaIcons : this.waterIcons; +- int i = flag ? 16777215 : BiomeColors.getAverageWaterColor(p_234370_, p_234371_); ++ TextureAtlasSprite[] atextureatlassprite = net.minecraftforge.client.ForgeHooksClient.getFluidSprites(p_234370_, p_234371_, p_234374_); ++ int i = net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(p_234374_).getTintColor(p_234374_, p_234370_, p_234371_); ++ float alpha = (float)(i >> 24 & 255) / 255.0F; ++ + float f = (float)(i >> 16 & 0xFF) / 255.0F; + float f1 = (float)(i >> 8 & 0xFF) / 255.0F; + float f2 = (float)(i & 0xFF) / 255.0F; +@@ -181,15 +_,15 @@ + float f52 = f4 * f; + float f30 = f4 * f1; + float f31 = f4 * f2; +- this.vertex(p_234372_, d1 + 0.0, d2 + (double)f8, d0 + 0.0, f52, f30, f31, f18, f22, l); +- this.vertex(p_234372_, d1 + 0.0, d2 + (double)f10, d0 + 1.0, f52, f30, f31, f19, f23, l); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f9, d0 + 1.0, f52, f30, f31, f20, f24, l); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f7, d0 + 0.0, f52, f30, f31, f21, f25, l); ++ this.vertex(p_234372_, d1 + 0.0, d2 + (double)f8, d0 + 0.0, f52, f30, f31, f18, f22, l, alpha); ++ this.vertex(p_234372_, d1 + 0.0, d2 + (double)f10, d0 + 1.0, f52, f30, f31, f19, f23, l, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f9, d0 + 1.0, f52, f30, f31, f20, f24, l, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f7, d0 + 0.0, f52, f30, f31, f21, f25, l, alpha); + if (p_234374_.shouldRenderBackwardUpFace(p_234370_, p_234371_.above())) { +- this.vertex(p_234372_, d1 + 0.0, d2 + (double)f8, d0 + 0.0, f52, f30, f31, f18, f22, l); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f7, d0 + 0.0, f52, f30, f31, f21, f25, l); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f9, d0 + 1.0, f52, f30, f31, f20, f24, l); +- this.vertex(p_234372_, d1 + 0.0, d2 + (double)f10, d0 + 1.0, f52, f30, f31, f19, f23, l); ++ this.vertex(p_234372_, d1 + 0.0, d2 + (double)f8, d0 + 0.0, f52, f30, f31, f18, f22, l, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f7, d0 + 0.0, f52, f30, f31, f21, f25, l, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f9, d0 + 1.0, f52, f30, f31, f20, f24, l, alpha); ++ this.vertex(p_234372_, d1 + 0.0, d2 + (double)f10, d0 + 1.0, f52, f30, f31, f19, f23, l, alpha); + } } - } -@@ -199,10 +_,10 @@ - float f46 = f3 * f; - float f47 = f3 * f1; - float f48 = f3 * f2; -- this.vertex(p_234372_, d1, d2 + (double)f17, d0 + 1.0D, f46, f47, f48, f40, f43, k); -- this.vertex(p_234372_, d1, d2 + (double)f17, d0, f46, f47, f48, f40, f42, k); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f17, d0, f46, f47, f48, f41, f42, k); -- this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f17, d0 + 1.0D, f46, f47, f48, f41, f43, k); -+ this.vertex(p_234372_, d1, d2 + (double)f17, d0 + 1.0D, f46, f47, f48, alpha, f40, f43, k); -+ this.vertex(p_234372_, d1, d2 + (double)f17, d0, f46, f47, f48, alpha, f40, f42, k); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f17, d0, f46, f47, f48, alpha, f41, f42, k); -+ this.vertex(p_234372_, d1 + 1.0D, d2 + (double)f17, d0 + 1.0D, f46, f47, f48, alpha, f41, f43, k); - } - - int j = this.getLightColor(p_234370_, p_234371_); -@@ -256,10 +_,9 @@ - if (flag7 && !isFaceOccludedByNeighbor(p_234370_, p_234371_, direction, Math.max(f44, f45), p_234370_.getBlockState(p_234371_.relative(direction)))) { - BlockPos blockpos = p_234371_.relative(direction); - TextureAtlasSprite textureatlassprite2 = atextureatlassprite[1]; -- if (!flag) { -- Block block = p_234370_.getBlockState(blockpos).getBlock(); -- if (block instanceof HalfTransparentBlock || block instanceof LeavesBlock) { -- textureatlassprite2 = this.waterOverlay; -+ if (atextureatlassprite[2] != null) { -+ if (p_234370_.getBlockState(blockpos).shouldDisplayFluidOverlay(p_234370_, blockpos, p_234374_)) { -+ textureatlassprite2 = atextureatlassprite[2]; - } - } - -@@ -272,15 +_,15 @@ - float f37 = f4 * f36 * f; - float f38 = f4 * f36 * f1; - float f39 = f4 * f36 * f2; -- this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j); -- this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j); -- this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j); -- this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j); -+ this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, alpha, f53, f33, j); -+ this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, alpha, f32, f34, j); -+ this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, alpha, f32, f35, j); -+ this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, alpha, f53, f35, j); - if (textureatlassprite2 != this.waterOverlay) { -- this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j); -- this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j); -- this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j); -- this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j); -+ this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, alpha, f53, f35, j); -+ this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, alpha, f32, f35, j); -+ this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, alpha, f32, f34, j); -+ this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, alpha, f53, f33, j); - } +@@ -202,10 +_,10 @@ + float f46 = f3 * f; + float f47 = f3 * f1; + float f48 = f3 * f2; +- this.vertex(p_234372_, d1, d2 + (double)f17, d0 + 1.0, f46, f47, f48, f40, f43, k); +- this.vertex(p_234372_, d1, d2 + (double)f17, d0, f46, f47, f48, f40, f42, k); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f17, d0, f46, f47, f48, f41, f42, k); +- this.vertex(p_234372_, d1 + 1.0, d2 + (double)f17, d0 + 1.0, f46, f47, f48, f41, f43, k); ++ this.vertex(p_234372_, d1, d2 + (double)f17, d0 + 1.0, f46, f47, f48, f40, f43, k, alpha); ++ this.vertex(p_234372_, d1, d2 + (double)f17, d0, f46, f47, f48, f40, f42, k, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f17, d0, f46, f47, f48, f41, f42, k, alpha); ++ this.vertex(p_234372_, d1 + 1.0, d2 + (double)f17, d0 + 1.0, f46, f47, f48, f41, f43, k, alpha); } - } -@@ -334,8 +_,8 @@ - } - } -- private void vertex(VertexConsumer p_110985_, double p_110986_, double p_110987_, double p_110988_, float p_110989_, float p_110990_, float p_110991_, float p_110992_, float p_110993_, int p_110994_) { -- p_110985_.vertex(p_110986_, p_110987_, p_110988_).color(p_110989_, p_110990_, p_110991_, 1.0F).uv(p_110992_, p_110993_).uv2(p_110994_).normal(0.0F, 1.0F, 0.0F).endVertex(); -+ private void vertex(VertexConsumer p_110985_, double p_110986_, double p_110987_, double p_110988_, float p_110989_, float p_110990_, float p_110991_, float alpha, float p_110992_, float p_110993_, int p_110994_) { -+ p_110985_.vertex(p_110986_, p_110987_, p_110988_).color(p_110989_, p_110990_, p_110991_, alpha).uv(p_110992_, p_110993_).uv2(p_110994_).normal(0.0F, 1.0F, 0.0F).endVertex(); - } + int j = this.getLightColor(p_234370_, p_234371_); +@@ -259,10 +_,9 @@ + if (flag7 && !isFaceOccludedByNeighbor(p_234370_, p_234371_, direction, Math.max(f44, f45), p_234370_.getBlockState(p_234371_.relative(direction)))) { + BlockPos blockpos = p_234371_.relative(direction); + TextureAtlasSprite textureatlassprite2 = atextureatlassprite[1]; +- if (!flag) { +- Block block = p_234370_.getBlockState(blockpos).getBlock(); +- if (block instanceof HalfTransparentBlock || block instanceof LeavesBlock) { +- textureatlassprite2 = this.waterOverlay; ++ if (atextureatlassprite[2] != null) { ++ if (p_234370_.getBlockState(blockpos).shouldDisplayFluidOverlay(p_234370_, blockpos, p_234374_)) { ++ textureatlassprite2 = atextureatlassprite[2]; + } + } - private int getLightColor(BlockAndTintGetter p_110946_, BlockPos p_110947_) { +@@ -275,15 +_,15 @@ + float f37 = f4 * f36 * f; + float f38 = f4 * f36 * f1; + float f39 = f4 * f36 * f2; +- this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j); +- this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j); +- this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j); +- this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j); ++ this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j, alpha); ++ this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j, alpha); ++ this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j, alpha); ++ this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j, alpha); + if (textureatlassprite2 != this.waterOverlay) { +- this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j); +- this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j); +- this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j); +- this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j); ++ this.vertex(p_234372_, d3, d2 + (double)f17, d4, f37, f38, f39, f53, f35, j, alpha); ++ this.vertex(p_234372_, d5, d2 + (double)f17, d6, f37, f38, f39, f32, f35, j, alpha); ++ this.vertex(p_234372_, d5, d2 + (double)f45, d6, f37, f38, f39, f32, f34, j, alpha); ++ this.vertex(p_234372_, d3, d2 + (double)f44, d4, f37, f38, f39, f53, f33, j, alpha); + } + } + } +@@ -345,10 +_,11 @@ + float p_110991_, + float p_110992_, + float p_110993_, +- int p_110994_ ++ int p_110994_, ++ float alpha + ) { + p_110985_.vertex(p_110986_, p_110987_, p_110988_) +- .color(p_110989_, p_110990_, p_110991_, 1.0F) ++ .color(p_110989_, p_110990_, p_110991_, alpha) + .uv(p_110992_, p_110993_) + .uv2(p_110994_) + .normal(0.0F, 1.0F, 0.0F) diff --git a/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch index e493a7c572..0afac40f4b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch @@ -1,137 +1,161 @@ --- a/net/minecraft/client/renderer/block/ModelBlockRenderer.java +++ b/net/minecraft/client/renderer/block/ModelBlockRenderer.java -@@ -40,16 +_,20 @@ - this.blockColors = p_110999_; - } +@@ -40,6 +_,11 @@ + this.blockColors = p_110999_; + } -+ @Deprecated //Forge: Model data and render type parameter - public void tesselateBlock(BlockAndTintGetter p_234380_, BakedModel p_234381_, BlockState p_234382_, BlockPos p_234383_, PoseStack p_234384_, VertexConsumer p_234385_, boolean p_234386_, RandomSource p_234387_, long p_234388_, int p_234389_) { -- boolean flag = Minecraft.useAmbientOcclusion() && p_234382_.getLightEmission() == 0 && p_234381_.useAmbientOcclusion(); -+ tesselateBlock(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void tesselateBlock(BlockAndTintGetter p_234380_, BakedModel p_234381_, BlockState p_234382_, BlockPos p_234383_, PoseStack p_234384_, VertexConsumer p_234385_, boolean p_234386_, RandomSource p_234387_, long p_234388_, int p_234389_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { -+ boolean flag = Minecraft.useAmbientOcclusion() && p_234382_.getLightEmission(p_234380_, p_234383_) == 0 && p_234381_.useAmbientOcclusion(p_234382_, renderType); - Vec3 vec3 = p_234382_.getOffset(p_234380_, p_234383_); - p_234384_.translate(vec3.x, vec3.y, vec3.z); ++ @Deprecated //Forge: Model data and render type parameter ++ public void tesselateBlock(BlockAndTintGetter p_234380_, BakedModel p_234381_, BlockState p_234382_, BlockPos p_234383_, PoseStack p_234384_, VertexConsumer p_234385_, boolean p_234386_, RandomSource p_234387_, long p_234388_, int p_234389_) { ++ tesselateBlock(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); ++ } ++ + public void tesselateBlock( + BlockAndTintGetter p_234380_, + BakedModel p_234381_, +@@ -50,17 +_,19 @@ + boolean p_234386_, + RandomSource p_234387_, + long p_234388_, +- int p_234389_ ++ int p_234389_, ++ net.minecraftforge.client.model.data.ModelData modelData, ++ @Nullable net.minecraft.client.renderer.RenderType renderType + ) { +- boolean flag = Minecraft.useAmbientOcclusion() && p_234382_.getLightEmission() == 0 && p_234381_.useAmbientOcclusion(); ++ boolean flag = Minecraft.useAmbientOcclusion() && p_234382_.getLightEmission(p_234380_, p_234383_) == 0 && p_234381_.useAmbientOcclusion(p_234382_, renderType); + Vec3 vec3 = p_234382_.getOffset(p_234380_, p_234383_); + p_234384_.translate(vec3.x, vec3.y, vec3.z); - try { - if (flag) { -- this.tesselateWithAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_); -+ this.tesselateWithAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, modelData, renderType); - } else { -- this.tesselateWithoutAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_); -+ this.tesselateWithoutAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, modelData, renderType); - } - - } catch (Throwable throwable) { -@@ -61,51 +_,59 @@ - } - } - -+ @Deprecated //Forge: Model data and render type parameter - public void tesselateWithAO(BlockAndTintGetter p_234391_, BakedModel p_234392_, BlockState p_234393_, BlockPos p_234394_, PoseStack p_234395_, VertexConsumer p_234396_, boolean p_234397_, RandomSource p_234398_, long p_234399_, int p_234400_) { -+ tesselateWithAO(p_234391_, p_234392_, p_234393_, p_234394_, p_234395_, p_234396_, p_234397_, p_234398_, p_234399_, p_234400_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void tesselateWithAO(BlockAndTintGetter p_111079_, BakedModel p_111080_, BlockState p_111081_, BlockPos p_111082_, PoseStack p_111083_, VertexConsumer p_111084_, boolean p_111085_, RandomSource p_111086_, long p_111087_, int p_111088_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { - float[] afloat = new float[DIRECTIONS.length * 2]; - BitSet bitset = new BitSet(3); - ModelBlockRenderer.AmbientOcclusionFace modelblockrenderer$ambientocclusionface = new ModelBlockRenderer.AmbientOcclusionFace(); -- BlockPos.MutableBlockPos blockpos$mutableblockpos = p_234394_.mutable(); -+ BlockPos.MutableBlockPos blockpos$mutableblockpos = p_111082_.mutable(); - - for(Direction direction : DIRECTIONS) { -- p_234398_.setSeed(p_234399_); -- List list = p_234392_.getQuads(p_234393_, direction, p_234398_); -+ p_111086_.setSeed(p_111087_); -+ List list = p_111080_.getQuads(p_111081_, direction, p_111086_, modelData, renderType); - if (!list.isEmpty()) { -- blockpos$mutableblockpos.setWithOffset(p_234394_, direction); -- if (!p_234397_ || Block.shouldRenderFace(p_234393_, p_234391_, p_234394_, direction, blockpos$mutableblockpos)) { -- this.renderModelFaceAO(p_234391_, p_234393_, p_234394_, p_234395_, p_234396_, list, afloat, bitset, modelblockrenderer$ambientocclusionface, p_234400_); -+ blockpos$mutableblockpos.setWithOffset(p_111082_, direction); -+ if (!p_111085_ || Block.shouldRenderFace(p_111081_, p_111079_, p_111082_, direction, blockpos$mutableblockpos)) { -+ this.renderModelFaceAO(p_111079_, p_111081_, p_111082_, p_111083_, p_111084_, list, afloat, bitset, modelblockrenderer$ambientocclusionface, p_111088_); + try { + if (flag) { +- this.tesselateWithAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_); ++ this.tesselateWithAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, modelData, renderType); + } else { +- this.tesselateWithoutAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_); ++ this.tesselateWithoutAO(p_234380_, p_234381_, p_234382_, p_234383_, p_234384_, p_234385_, p_234386_, p_234387_, p_234388_, p_234389_, modelData, renderType); } - } - } + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "Tesselating block model"); +@@ -71,6 +_,11 @@ + } + } -- p_234398_.setSeed(p_234399_); -- List list1 = p_234392_.getQuads(p_234393_, (Direction)null, p_234398_); -+ p_111086_.setSeed(p_111087_); -+ List list1 = p_111080_.getQuads(p_111081_, (Direction)null, p_111086_, modelData, renderType); - if (!list1.isEmpty()) { -- this.renderModelFaceAO(p_234391_, p_234393_, p_234394_, p_234395_, p_234396_, list1, afloat, bitset, modelblockrenderer$ambientocclusionface, p_234400_); -+ this.renderModelFaceAO(p_111079_, p_111081_, p_111082_, p_111083_, p_111084_, list1, afloat, bitset, modelblockrenderer$ambientocclusionface, p_111088_); - } ++ @Deprecated //Forge: Model data and render type parameter ++ public void tesselateWithAO(BlockAndTintGetter p_234391_, BakedModel p_234392_, BlockState p_234393_, BlockPos p_234394_, PoseStack p_234395_, VertexConsumer p_234396_, boolean p_234397_, RandomSource p_234398_, long p_234399_, int p_234400_) { ++ tesselateWithAO(p_234391_, p_234392_, p_234393_, p_234394_, p_234395_, p_234396_, p_234397_, p_234398_, p_234399_, p_234400_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); ++ } ++ + public void tesselateWithAO( + BlockAndTintGetter p_234391_, + BakedModel p_234392_, +@@ -81,7 +_,9 @@ + boolean p_234397_, + RandomSource p_234398_, + long p_234399_, +- int p_234400_ ++ int p_234400_, ++ net.minecraftforge.client.model.data.ModelData modelData, ++ @Nullable net.minecraft.client.renderer.RenderType renderType + ) { + float[] afloat = new float[DIRECTIONS.length * 2]; + BitSet bitset = new BitSet(3); +@@ -90,7 +_,7 @@ - } + for (Direction direction : DIRECTIONS) { + p_234398_.setSeed(p_234399_); +- List list = p_234392_.getQuads(p_234393_, direction, p_234398_); ++ List list = p_234392_.getQuads(p_234393_, direction, p_234398_, modelData, renderType); + if (!list.isEmpty()) { + blockpos$mutableblockpos.setWithOffset(p_234394_, direction); + if (!p_234397_ || Block.shouldRenderFace(p_234393_, p_234391_, p_234394_, direction, blockpos$mutableblockpos)) { +@@ -102,12 +_,17 @@ + } -+ @Deprecated //Forge: Model data and render type parameter - public void tesselateWithoutAO(BlockAndTintGetter p_234402_, BakedModel p_234403_, BlockState p_234404_, BlockPos p_234405_, PoseStack p_234406_, VertexConsumer p_234407_, boolean p_234408_, RandomSource p_234409_, long p_234410_, int p_234411_) { -+ tesselateWithoutAO(p_234402_, p_234403_, p_234404_, p_234405_, p_234406_, p_234407_, p_234408_, p_234409_, p_234410_, p_234411_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void tesselateWithoutAO(BlockAndTintGetter p_111091_, BakedModel p_111092_, BlockState p_111093_, BlockPos p_111094_, PoseStack p_111095_, VertexConsumer p_111096_, boolean p_111097_, RandomSource p_111098_, long p_111099_, int p_111100_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { - BitSet bitset = new BitSet(3); -- BlockPos.MutableBlockPos blockpos$mutableblockpos = p_234405_.mutable(); -+ BlockPos.MutableBlockPos blockpos$mutableblockpos = p_111094_.mutable(); + p_234398_.setSeed(p_234399_); +- List list1 = p_234392_.getQuads(p_234393_, null, p_234398_); ++ List list1 = p_234392_.getQuads(p_234393_, null, p_234398_, modelData, renderType); + if (!list1.isEmpty()) { + this.renderModelFaceAO(p_234391_, p_234393_, p_234394_, p_234395_, p_234396_, list1, afloat, bitset, modelblockrenderer$ambientocclusionface, p_234400_); + } + } - for(Direction direction : DIRECTIONS) { -- p_234409_.setSeed(p_234410_); -- List list = p_234403_.getQuads(p_234404_, direction, p_234409_); -+ p_111098_.setSeed(p_111099_); -+ List list = p_111092_.getQuads(p_111093_, direction, p_111098_, modelData, renderType); - if (!list.isEmpty()) { -- blockpos$mutableblockpos.setWithOffset(p_234405_, direction); -- if (!p_234408_ || Block.shouldRenderFace(p_234404_, p_234402_, p_234405_, direction, blockpos$mutableblockpos)) { -- int i = LevelRenderer.getLightColor(p_234402_, p_234404_, blockpos$mutableblockpos); -- this.renderModelFaceFlat(p_234402_, p_234404_, p_234405_, i, p_234411_, false, p_234406_, p_234407_, list, bitset); -+ blockpos$mutableblockpos.setWithOffset(p_111094_, direction); -+ if (!p_111097_ || Block.shouldRenderFace(p_111093_, p_111091_, p_111094_, direction, blockpos$mutableblockpos)) { -+ int i = LevelRenderer.getLightColor(p_111091_, p_111093_, blockpos$mutableblockpos); -+ this.renderModelFaceFlat(p_111091_, p_111093_, p_111094_, i, p_111100_, false, p_111095_, p_111096_, list, bitset); - } - } - } ++ @Deprecated //Forge: Model data and render type parameter ++ public void tesselateWithoutAO(BlockAndTintGetter p_234402_, BakedModel p_234403_, BlockState p_234404_, BlockPos p_234405_, PoseStack p_234406_, VertexConsumer p_234407_, boolean p_234408_, RandomSource p_234409_, long p_234410_, int p_234411_) { ++ tesselateWithoutAO(p_234402_, p_234403_, p_234404_, p_234405_, p_234406_, p_234407_, p_234408_, p_234409_, p_234410_, p_234411_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); ++ } ++ + public void tesselateWithoutAO( + BlockAndTintGetter p_234402_, + BakedModel p_234403_, +@@ -118,14 +_,16 @@ + boolean p_234408_, + RandomSource p_234409_, + long p_234410_, +- int p_234411_ ++ int p_234411_, ++ net.minecraftforge.client.model.data.ModelData modelData, ++ @Nullable net.minecraft.client.renderer.RenderType renderType + ) { + BitSet bitset = new BitSet(3); + BlockPos.MutableBlockPos blockpos$mutableblockpos = p_234405_.mutable(); -- p_234409_.setSeed(p_234410_); -- List list1 = p_234403_.getQuads(p_234404_, (Direction)null, p_234409_); -+ p_111098_.setSeed(p_111099_); -+ List list1 = p_111092_.getQuads(p_111093_, (Direction)null, p_111098_, modelData, renderType); - if (!list1.isEmpty()) { -- this.renderModelFaceFlat(p_234402_, p_234404_, p_234405_, -1, p_234411_, true, p_234406_, p_234407_, list1, bitset); -+ this.renderModelFaceFlat(p_111091_, p_111093_, p_111094_, -1, p_111100_, true, p_111095_, p_111096_, list1, bitset); - } + for (Direction direction : DIRECTIONS) { + p_234409_.setSeed(p_234410_); +- List list = p_234403_.getQuads(p_234404_, direction, p_234409_); ++ List list = p_234403_.getQuads(p_234404_, direction, p_234409_, modelData, renderType); + if (!list.isEmpty()) { + blockpos$mutableblockpos.setWithOffset(p_234405_, direction); + if (!p_234408_ || Block.shouldRenderFace(p_234404_, p_234402_, p_234405_, direction, blockpos$mutableblockpos)) { +@@ -136,7 +_,7 @@ + } - } -@@ -113,6 +_,7 @@ - private void renderModelFaceAO(BlockAndTintGetter p_111013_, BlockState p_111014_, BlockPos p_111015_, PoseStack p_111016_, VertexConsumer p_111017_, List p_111018_, float[] p_111019_, BitSet p_111020_, ModelBlockRenderer.AmbientOcclusionFace p_111021_, int p_111022_) { - for(BakedQuad bakedquad : p_111018_) { - this.calculateShape(p_111013_, p_111014_, p_111015_, bakedquad.getVertices(), bakedquad.getDirection(), p_111019_, p_111020_); -+ if (!net.minecraftforge.client.ForgeHooksClient.calculateFaceWithoutAO(p_111013_, p_111014_, p_111015_, bakedquad, p_111020_.get(0), p_111021_.brightness, p_111021_.lightmap)) - p_111021_.calculate(p_111013_, p_111014_, p_111015_, bakedquad.getDirection(), p_111019_, p_111020_, bakedquad.isShade()); - this.putQuadData(p_111013_, p_111014_, p_111015_, p_111017_, p_111016_.last(), bakedquad, p_111021_.brightness[0], p_111021_.brightness[1], p_111021_.brightness[2], p_111021_.brightness[3], p_111021_.lightmap[0], p_111021_.lightmap[1], p_111021_.lightmap[2], p_111021_.lightmap[3], p_111022_); - } -@@ -217,17 +_,21 @@ + p_234409_.setSeed(p_234410_); +- List list1 = p_234403_.getQuads(p_234404_, null, p_234409_); ++ List list1 = p_234403_.getQuads(p_234404_, null, p_234409_, modelData, renderType); + if (!list1.isEmpty()) { + this.renderModelFaceFlat(p_234402_, p_234404_, p_234405_, -1, p_234411_, true, p_234406_, p_234407_, list1, bitset); + } +@@ -156,6 +_,7 @@ + ) { + for (BakedQuad bakedquad : p_111018_) { + this.calculateShape(p_111013_, p_111014_, p_111015_, bakedquad.getVertices(), bakedquad.getDirection(), p_111019_, p_111020_); ++ if (!net.minecraftforge.client.ForgeHooksClient.calculateFaceWithoutAO(p_111013_, p_111014_, p_111015_, bakedquad, p_111020_.get(0), p_111021_.brightness, p_111021_.lightmap)) + p_111021_.calculate(p_111013_, p_111014_, p_111015_, bakedquad.getDirection(), p_111019_, p_111020_, bakedquad.isShade()); + this.putQuadData( + p_111013_, +@@ -321,6 +_,11 @@ + } + } - } ++ @Deprecated //Forge: Model data and render type parameter ++ public void renderModel(PoseStack.Pose p_111068_, VertexConsumer p_111069_, @Nullable BlockState p_111070_, BakedModel p_111071_, float p_111072_, float p_111073_, float p_111074_, int p_111075_, int p_111076_) { ++ renderModel(p_111068_, p_111069_, p_111070_, p_111071_, p_111072_, p_111073_, p_111074_, p_111075_, p_111076_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); ++ } ++ + public void renderModel( + PoseStack.Pose p_111068_, + VertexConsumer p_111069_, +@@ -330,18 +_,20 @@ + float p_111073_, + float p_111074_, + int p_111075_, +- int p_111076_ ++ int p_111076_, ++ net.minecraftforge.client.model.data.ModelData modelData, ++ @Nullable net.minecraft.client.renderer.RenderType renderType + ) { + RandomSource randomsource = RandomSource.create(); + long i = 42L; -+ @Deprecated //Forge: Model data and render type parameter - public void renderModel(PoseStack.Pose p_111068_, VertexConsumer p_111069_, @Nullable BlockState p_111070_, BakedModel p_111071_, float p_111072_, float p_111073_, float p_111074_, int p_111075_, int p_111076_) { -+ renderModel(p_111068_, p_111069_, p_111070_, p_111071_, p_111072_, p_111073_, p_111074_, p_111075_, p_111076_, net.minecraftforge.client.model.data.ModelData.EMPTY, null); -+ } -+ public void renderModel(PoseStack.Pose p_111068_, VertexConsumer p_111069_, @Nullable BlockState p_111070_, BakedModel p_111071_, float p_111072_, float p_111073_, float p_111074_, int p_111075_, int p_111076_, net.minecraftforge.client.model.data.ModelData modelData, net.minecraft.client.renderer.RenderType renderType) { - RandomSource randomsource = RandomSource.create(); - long i = 42L; + for (Direction direction : DIRECTIONS) { + randomsource.setSeed(42L); +- renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, direction, randomsource), p_111075_, p_111076_); ++ renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, direction, randomsource, modelData, renderType), p_111075_, p_111076_); + } - for(Direction direction : DIRECTIONS) { - randomsource.setSeed(42L); -- renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, direction, randomsource), p_111075_, p_111076_); -+ renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, direction, randomsource, modelData, renderType), p_111075_, p_111076_); - } + randomsource.setSeed(42L); +- renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, null, randomsource), p_111075_, p_111076_); ++ renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, null, randomsource, modelData, renderType), p_111075_, p_111076_); + } - randomsource.setSeed(42L); -- renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, (Direction)null, randomsource), p_111075_, p_111076_); -+ renderQuadList(p_111068_, p_111069_, p_111072_, p_111073_, p_111074_, p_111071_.getQuads(p_111070_, (Direction)null, randomsource, modelData, renderType), p_111075_, p_111076_); - } - - private static void renderQuadList(PoseStack.Pose p_111059_, VertexConsumer p_111060_, float p_111061_, float p_111062_, float p_111063_, List p_111064_, int p_111065_, int p_111066_) { + private static void renderQuadList( diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/BakedQuad.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/BakedQuad.java.patch index de77b734fa..c44486e544 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/BakedQuad.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/BakedQuad.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/client/renderer/block/model/BakedQuad.java +++ b/net/minecraft/client/renderer/block/model/BakedQuad.java @@ -12,13 +_,19 @@ - protected final Direction direction; - protected final TextureAtlasSprite sprite; - private final boolean shade; -+ private final boolean hasAmbientOcclusion; + protected final Direction direction; + protected final TextureAtlasSprite sprite; + private final boolean shade; ++ private final boolean hasAmbientOcclusion; - public BakedQuad(int[] p_111298_, int p_111299_, Direction p_111300_, TextureAtlasSprite p_111301_, boolean p_111302_) { -+ this(p_111298_, p_111299_, p_111300_, p_111301_, p_111302_, true); -+ } + public BakedQuad(int[] p_111298_, int p_111299_, Direction p_111300_, TextureAtlasSprite p_111301_, boolean p_111302_) { ++ this(p_111298_, p_111299_, p_111300_, p_111301_, p_111302_, true); ++ } + -+ public BakedQuad(int[] p_111298_, int p_111299_, Direction p_111300_, TextureAtlasSprite p_111301_, boolean p_111302_, boolean hasAmbientOcclusion) { - this.vertices = p_111298_; - this.tintIndex = p_111299_; - this.direction = p_111300_; - this.sprite = p_111301_; - this.shade = p_111302_; -+ this.hasAmbientOcclusion = hasAmbientOcclusion; - } ++ public BakedQuad(int[] p_111298_, int p_111299_, Direction p_111300_, TextureAtlasSprite p_111301_, boolean p_111302_, boolean hasAmbientOcclusion) { + this.vertices = p_111298_; + this.tintIndex = p_111299_; + this.direction = p_111300_; + this.sprite = p_111301_; + this.shade = p_111302_; ++ this.hasAmbientOcclusion = hasAmbientOcclusion; + } - public TextureAtlasSprite getSprite() { + public TextureAtlasSprite getSprite() { @@ -43,5 +_,9 @@ - public boolean isShade() { - return this.shade; -+ } + public boolean isShade() { + return this.shade; ++ } + -+ public boolean hasAmbientOcclusion() { -+ return this.hasAmbientOcclusion; - } ++ public boolean hasAmbientOcclusion() { ++ return this.hasAmbientOcclusion; + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElement.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElement.java.patch index c454dc177e..07dea24a97 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElement.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElement.java.patch @@ -1,48 +1,50 @@ --- a/net/minecraft/client/renderer/block/model/BlockElement.java +++ b/net/minecraft/client/renderer/block/model/BlockElement.java -@@ -28,14 +_,21 @@ - public final Map faces; - public final BlockElementRotation rotation; - public final boolean shade; -+ private net.minecraftforge.client.model.ForgeFaceData faceData; +@@ -29,16 +_,23 @@ + public final Map faces; + public final BlockElementRotation rotation; + public final boolean shade; ++ private net.minecraftforge.client.model.ForgeFaceData faceData; - public BlockElement(Vector3f p_253626_, Vector3f p_254426_, Map p_254454_, @Nullable BlockElementRotation p_254229_, boolean p_253661_) { -+ this(p_253626_, p_254426_, p_254454_, p_254229_, p_253661_, net.minecraftforge.client.model.ForgeFaceData.DEFAULT); -+ } + public BlockElement( + Vector3f p_253626_, Vector3f p_254426_, Map p_254454_, @Nullable BlockElementRotation p_254229_, boolean p_253661_ + ) { ++ this(p_253626_, p_254426_, p_254454_, p_254229_, p_253661_, net.minecraftforge.client.model.ForgeFaceData.DEFAULT); ++ } + -+ public BlockElement(Vector3f p_253626_, Vector3f p_254426_, Map p_254454_, @Nullable BlockElementRotation p_254229_, boolean p_253661_, net.minecraftforge.client.model.ForgeFaceData faceData) { - this.from = p_253626_; - this.to = p_254426_; - this.faces = p_254454_; - this.rotation = p_254229_; - this.shade = p_253661_; - this.fillUvs(); -+ this.setFaceData(faceData); -+ this.faces.values().forEach(face -> face.parent = this); - } ++ public BlockElement(Vector3f p_253626_, Vector3f p_254426_, Map p_254454_, @Nullable BlockElementRotation p_254229_, boolean p_253661_, net.minecraftforge.client.model.ForgeFaceData faceData) { + this.from = p_253626_; + this.to = p_254426_; + this.faces = p_254454_; + this.rotation = p_254229_; + this.shade = p_253661_; + this.fillUvs(); ++ this.setFaceData(faceData); ++ this.faces.values().forEach(face -> face.parent = this); + } - private void fillUvs() { -@@ -78,7 +_,8 @@ - throw new JsonParseException("Expected shade to be a Boolean"); - } else { - boolean flag = GsonHelper.getAsBoolean(jsonobject, "shade", true); -- return new BlockElement(vector3f, vector3f1, map, blockelementrotation, flag); -+ var faceData = net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), net.minecraftforge.client.model.ForgeFaceData.DEFAULT); -+ return new BlockElement(vector3f, vector3f1, map, blockelementrotation, flag, faceData); - } - } + private void fillUvs() { +@@ -66,6 +_,14 @@ + } + } -@@ -179,5 +_,13 @@ - return new Vector3f(afloat[0], afloat[1], afloat[2]); - } - } -+ } ++ public net.minecraftforge.client.model.ForgeFaceData getFaceData() { ++ return this.faceData; ++ } + -+ public net.minecraftforge.client.model.ForgeFaceData getFaceData() { -+ return this.faceData; -+ } ++ public void setFaceData(net.minecraftforge.client.model.ForgeFaceData faceData) { ++ this.faceData = java.util.Objects.requireNonNull(faceData); ++ } + -+ public void setFaceData(net.minecraftforge.client.model.ForgeFaceData faceData) { -+ this.faceData = java.util.Objects.requireNonNull(faceData); - } - } + @OnlyIn(Dist.CLIENT) + public static class Deserializer implements JsonDeserializer { + private static final boolean DEFAULT_SHADE = true; +@@ -80,7 +_,7 @@ + throw new JsonParseException("Expected shade to be a Boolean"); + } else { + boolean flag = GsonHelper.getAsBoolean(jsonobject, "shade", true); +- return new BlockElement(vector3f, vector3f1, map, blockelementrotation, flag); ++ return new BlockElement(vector3f, vector3f1, map, blockelementrotation, flag, net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), net.minecraftforge.client.model.ForgeFaceData.DEFAULT)); + } + } + diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElementFace.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElementFace.java.patch index 4159702079..c2a12abc4f 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElementFace.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockElementFace.java.patch @@ -1,43 +1,43 @@ --- a/net/minecraft/client/renderer/block/model/BlockElementFace.java +++ b/net/minecraft/client/renderer/block/model/BlockElementFace.java -@@ -19,12 +_,30 @@ - public final int tintIndex; - public final String texture; - public final BlockFaceUV uv; -+ @Nullable -+ private final net.minecraftforge.client.model.ForgeFaceData faceData; // If null, we defer to the parent BlockElement's ForgeFaceData, which is not nullable. -+ @Nullable -+ BlockElement parent; // Parent canot be set by the constructor due to instantiation ordering. This shouldn't really ever be null, but it could theoretically be. +@@ -19,13 +_,31 @@ + public final int tintIndex; + public final String texture; + public final BlockFaceUV uv; ++ @Nullable ++ private final net.minecraftforge.client.model.ForgeFaceData faceData; // If null, we defer to the parent BlockElement's ForgeFaceData, which is not nullable. ++ @Nullable ++ BlockElement parent; // Parent canot be set by the constructor due to instantiation ordering. This shouldn't really ever be null, but it could theoretically be. - public BlockElementFace(@Nullable Direction p_111359_, int p_111360_, String p_111361_, BlockFaceUV p_111362_) { -+ this(p_111359_, p_111360_, p_111361_, p_111362_, null); -+ } + public BlockElementFace(@Nullable Direction p_111359_, int p_111360_, String p_111361_, BlockFaceUV p_111362_) { ++ this(p_111359_, p_111360_, p_111361_, p_111362_, null); ++ } + -+ public BlockElementFace(@Nullable Direction p_111359_, int p_111360_, String p_111361_, BlockFaceUV p_111362_, @Nullable net.minecraftforge.client.model.ForgeFaceData faceData) { - this.cullForDirection = p_111359_; - this.tintIndex = p_111360_; - this.texture = p_111361_; - this.uv = p_111362_; -+ this.faceData = faceData; -+ } ++ public BlockElementFace(@Nullable Direction p_111359_, int p_111360_, String p_111361_, BlockFaceUV p_111362_, @Nullable net.minecraftforge.client.model.ForgeFaceData faceData) { + this.cullForDirection = p_111359_; + this.tintIndex = p_111360_; + this.texture = p_111361_; + this.uv = p_111362_; ++ this.faceData = faceData; + } + -+ public net.minecraftforge.client.model.ForgeFaceData getFaceData() { -+ if(this.faceData != null) { -+ return this.faceData; -+ } else if(this.parent != null) { -+ return this.parent.getFaceData(); -+ } -+ return net.minecraftforge.client.model.ForgeFaceData.DEFAULT; - } ++ public net.minecraftforge.client.model.ForgeFaceData getFaceData() { ++ if (this.faceData != null) { ++ return this.faceData; ++ } else if (this.parent != null) { ++ return this.parent.getFaceData(); ++ } ++ return net.minecraftforge.client.model.ForgeFaceData.DEFAULT; ++ } - @OnlyIn(Dist.CLIENT) -@@ -37,7 +_,8 @@ - int i = this.getTintIndex(jsonobject); - String s = this.getTexture(jsonobject); - BlockFaceUV blockfaceuv = p_111367_.deserialize(jsonobject, BlockFaceUV.class); -- return new BlockElementFace(direction, i, s, blockfaceuv); -+ var faceData = net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), null); -+ return new BlockElementFace(direction, i, s, blockfaceuv, faceData); - } + @OnlyIn(Dist.CLIENT) + public static class Deserializer implements JsonDeserializer { +@@ -37,7 +_,7 @@ + int i = this.getTintIndex(jsonobject); + String s = this.getTexture(jsonobject); + BlockFaceUV blockfaceuv = p_111367_.deserialize(jsonobject, BlockFaceUV.class); +- return new BlockElementFace(direction, i, s, blockfaceuv); ++ return new BlockElementFace(direction, i, s, blockfaceuv, net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), null)); + } - protected int getTintIndex(JsonObject p_111369_) { + protected int getTintIndex(JsonObject p_111369_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockModel.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockModel.java.patch index d4300e68ed..a4c4d82b78 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/BlockModel.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/BlockModel.java.patch @@ -1,100 +1,114 @@ --- a/net/minecraft/client/renderer/block/model/BlockModel.java +++ b/net/minecraft/client/renderer/block/model/BlockModel.java -@@ -68,9 +_,10 @@ - public BlockModel parent; - @Nullable - protected ResourceLocation parentLocation; -+ public final net.minecraftforge.client.model.geometry.BlockGeometryBakingContext customData = new net.minecraftforge.client.model.geometry.BlockGeometryBakingContext(this); +@@ -77,9 +_,10 @@ + public BlockModel parent; + @Nullable + protected ResourceLocation parentLocation; ++ public final net.minecraftforge.client.model.geometry.BlockGeometryBakingContext customData = new net.minecraftforge.client.model.geometry.BlockGeometryBakingContext(this); - public static BlockModel fromStream(Reader p_111462_) { -- return GsonHelper.fromJson(GSON, p_111462_, BlockModel.class); -+ return GsonHelper.fromJson(net.minecraftforge.client.model.ExtendedBlockModelDeserializer.INSTANCE, p_111462_, BlockModel.class); - } + public static BlockModel fromStream(Reader p_111462_) { +- return GsonHelper.fromJson(GSON, p_111462_, BlockModel.class); ++ return GsonHelper.fromJson(net.minecraftforge.client.model.ExtendedBlockModelDeserializer.INSTANCE, p_111462_, BlockModel.class); + } - public static BlockModel fromString(String p_111464_) { -@@ -87,10 +_,15 @@ - this.overrides = p_273099_; - } + public static BlockModel fromString(String p_111464_) { +@@ -104,10 +_,17 @@ + this.overrides = p_273099_; + } -+ @Deprecated - public List getElements() { -+ if (customData.hasCustomGeometry()) return java.util.Collections.emptyList(); - return this.elements.isEmpty() && this.parent != null ? this.parent.getElements() : this.elements; - } ++ @Deprecated + public List getElements() { ++ if (customData.hasCustomGeometry()) return java.util.Collections.emptyList(); + return this.elements.isEmpty() && this.parent != null ? this.parent.getElements() : this.elements; + } -+ @Nullable -+ public ResourceLocation getParentLocation() { return parentLocation; } ++ @Nullable ++ public ResourceLocation getParentLocation() { ++ return parentLocation; ++ } + - public boolean hasAmbientOcclusion() { - if (this.hasAmbientOcclusion != null) { - return this.hasAmbientOcclusion; -@@ -119,6 +_,10 @@ - return this.overrides.isEmpty() ? ItemOverrides.EMPTY : new ItemOverrides(p_250138_, p_251800_, this.overrides); - } + public boolean hasAmbientOcclusion() { + if (this.hasAmbientOcclusion != null) { + return this.hasAmbientOcclusion; +@@ -136,6 +_,10 @@ + return this.overrides.isEmpty() ? ItemOverrides.EMPTY : new ItemOverrides(p_250138_, p_251800_, this.overrides); + } -+ public ItemOverrides getOverrides(ModelBaker p_250138_, BlockModel p_251800_, Function spriteGetter) { -+ return this.overrides.isEmpty() ? ItemOverrides.EMPTY : new ItemOverrides(p_250138_, p_251800_, this.overrides, spriteGetter); -+ } ++ public ItemOverrides getOverrides(ModelBaker p_250138_, BlockModel p_251800_, Function spriteGetter) { ++ return this.overrides.isEmpty() ? ItemOverrides.EMPTY : new ItemOverrides(p_250138_, p_251800_, this.overrides, spriteGetter); ++ } + - public Collection getDependencies() { - Set set = Sets.newHashSet(); + @Override + public Collection getDependencies() { + Set set = Sets.newHashSet(); +@@ -184,6 +_,10 @@ + blockmodel.parent = (BlockModel)unbakedmodel; + } -@@ -160,6 +_,10 @@ - blockmodel.parent = (BlockModel)unbakedmodel; - } - -+ if (customData.hasCustomGeometry()) { -+ customData.getCustomGeometry().resolveParents(p_249059_, customData); -+ } ++ if (customData.hasCustomGeometry()) { ++ customData.getCustomGeometry().resolveParents(p_249059_, customData); ++ } + - this.overrides.forEach((p_247932_) -> { - UnbakedModel unbakedmodel1 = p_249059_.apply(p_247932_.getModel()); - if (!Objects.equals(unbakedmodel1, this)) { -@@ -168,11 +_,18 @@ - }); - } + this.overrides.forEach(p_247932_ -> { + UnbakedModel unbakedmodel1 = p_249059_.apply(p_247932_.getModel()); + if (!Objects.equals(unbakedmodel1, this)) { +@@ -192,18 +_,27 @@ + }); + } -+ /** -+ * @deprecated Forge: Use {@link #bake(ModelBaker, BlockModel, Function, ModelState, ResourceLocation, boolean)}. -+ */ -+ @Deprecated - public BakedModel bake(ModelBaker p_252120_, Function p_250023_, ModelState p_251130_, ResourceLocation p_252208_) { - return this.bake(p_252120_, this, p_250023_, p_251130_, p_252208_, true); - } ++ /** ++ * @deprecated Forge: Use {@link #bake(ModelBaker, BlockModel, Function, ModelState, ResourceLocation, boolean)}. ++ */ ++ @Deprecated + @Override + public BakedModel bake(ModelBaker p_252120_, Function p_250023_, ModelState p_251130_, ResourceLocation p_252208_) { + return this.bake(p_252120_, this, p_250023_, p_251130_, p_252208_, true); + } - public BakedModel bake(ModelBaker p_249720_, BlockModel p_111451_, Function p_111452_, ModelState p_111453_, ResourceLocation p_111454_, boolean p_111455_) { -+ return net.minecraftforge.client.model.geometry.UnbakedGeometryHelper.bake(this, p_249720_, p_111451_, p_111452_, p_111453_, p_111454_, p_111455_); -+ } -+ private BakedModel bakeVanilla(ModelBaker p_249720_, BlockModel p_111451_, Function p_111452_, ModelState p_111453_, ResourceLocation p_111454_, boolean p_111455_, net.minecraftforge.client.RenderTypeGroup renderTypes) { - TextureAtlasSprite textureatlassprite = p_111452_.apply(this.getMaterial("particle")); - if (this.getRootModel() == ModelBakery.BLOCK_ENTITY_MARKER) { - return new BuiltInModel(this.getTransforms(), this.getItemOverrides(p_249720_, p_111451_), textureatlassprite, this.getGuiLight().lightLikeBlock()); -@@ -255,7 +_,18 @@ - ItemTransform itemtransform5 = this.getTransform(ItemDisplayContext.GUI); - ItemTransform itemtransform6 = this.getTransform(ItemDisplayContext.GROUND); - ItemTransform itemtransform7 = this.getTransform(ItemDisplayContext.FIXED); -- return new ItemTransforms(itemtransform, itemtransform1, itemtransform2, itemtransform3, itemtransform4, itemtransform5, itemtransform6, itemtransform7); ++ public BakedModel bake(ModelBaker p_249720_, BlockModel p_111451_, Function p_111452_, ModelState p_111453_, ResourceLocation p_111454_, boolean p_111455_) { ++ return net.minecraftforge.client.model.geometry.UnbakedGeometryHelper.bake(this, p_249720_, p_111451_, p_111452_, p_111453_, p_111454_, p_111455_); ++ } + -+ var builder = com.google.common.collect.ImmutableMap.builder(); -+ for(ItemDisplayContext type : ItemDisplayContext.values()) { -+ if (type.isModded()) { -+ var transform = this.getTransform(type); -+ if (transform != ItemTransform.NO_TRANSFORM) { -+ builder.put(type, transform); -+ } -+ } -+ } + public BakedModel bake( + ModelBaker p_249720_, + BlockModel p_111451_, + Function p_111452_, + ModelState p_111453_, + ResourceLocation p_111454_, +- boolean p_111455_ ++ boolean p_111455_, ++ net.minecraftforge.client.RenderTypeGroup renderTypes + ) { + TextureAtlasSprite textureatlassprite = p_111452_.apply(this.getMaterial("particle")); + if (this.getRootModel() == ModelBakery.BLOCK_ENTITY_MARKER) { +@@ -295,7 +_,18 @@ + ItemTransform itemtransform5 = this.getTransform(ItemDisplayContext.GUI); + ItemTransform itemtransform6 = this.getTransform(ItemDisplayContext.GROUND); + ItemTransform itemtransform7 = this.getTransform(ItemDisplayContext.FIXED); +- return new ItemTransforms(itemtransform, itemtransform1, itemtransform2, itemtransform3, itemtransform4, itemtransform5, itemtransform6, itemtransform7); + -+ return new ItemTransforms(itemtransform, itemtransform1, itemtransform2, itemtransform3, itemtransform4, itemtransform5, itemtransform6, itemtransform7, builder.build()); - } - - private ItemTransform getTransform(ItemDisplayContext p_270662_) { -@@ -373,6 +_,8 @@ - public boolean lightLikeBlock() { - return this == SIDE; - } ++ var builder = com.google.common.collect.ImmutableMap.builder(); ++ for (ItemDisplayContext type : ItemDisplayContext.values()) { ++ if (type.isModded()) { ++ var transform = this.getTransform(type); ++ if (transform != ItemTransform.NO_TRANSFORM) { ++ builder.put(type, transform); ++ } ++ } ++ } + -+ public String getSerializedName() { return name; } - } ++ return new ItemTransforms(itemtransform, itemtransform1, itemtransform2, itemtransform3, itemtransform4, itemtransform5, itemtransform6, itemtransform7, builder.build()); + } + + private ItemTransform getTransform(ItemDisplayContext p_270662_) { +@@ -413,6 +_,10 @@ + + public boolean lightLikeBlock() { + return this == SIDE; ++ } ++ ++ public String getSerializedName() { ++ return name; + } + } - @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/FaceBakery.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/FaceBakery.java.patch index 82f1ed3749..8e0301642c 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/FaceBakery.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/FaceBakery.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/client/renderer/block/model/FaceBakery.java +++ b/net/minecraft/client/renderer/block/model/FaceBakery.java -@@ -50,7 +_,14 @@ - this.recalculateWinding(aint, direction); - } +@@ -59,7 +_,14 @@ + this.recalculateWinding(aint, direction); + } -- return new BakedQuad(aint, p_111603_.tintIndex, direction, p_111604_, p_111608_); -+ net.minecraftforge.client.ForgeHooksClient.fillNormal(aint, direction, p_111603_.getFaceData().calculateNormals()); -+ var data = p_111603_.getFaceData(); -+ var quad = new BakedQuad(aint, p_111603_.tintIndex, direction, p_111604_, p_111608_, data.ambientOcclusion()); -+ if (!net.minecraftforge.client.model.ForgeFaceData.DEFAULT.equals(data)) { -+ net.minecraftforge.client.model.QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); -+ net.minecraftforge.client.model.QuadTransformers.applyingColor(data.color()).processInPlace(quad); -+ } -+ return quad; - } +- return new BakedQuad(aint, p_111603_.tintIndex, direction, p_111604_, p_111608_); ++ net.minecraftforge.client.ForgeHooksClient.fillNormal(aint, direction, p_111603_.getFaceData().calculateNormals()); ++ var data = p_111603_.getFaceData(); ++ var quad = new BakedQuad(aint, p_111603_.tintIndex, direction, p_111604_, p_111608_, data.ambientOcclusion()); ++ if (!net.minecraftforge.client.model.ForgeFaceData.DEFAULT.equals(data)) { ++ net.minecraftforge.client.model.QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); ++ net.minecraftforge.client.model.QuadTransformers.applyingColor(data.color()).processInPlace(quad); ++ } ++ return quad; + } - public static BlockFaceUV recomputeUVs(BlockFaceUV p_111582_, Direction p_111583_, Transformation p_111584_, ResourceLocation p_111585_) { + public static BlockFaceUV recomputeUVs(BlockFaceUV p_111582_, Direction p_111583_, Transformation p_111584_, ResourceLocation p_111585_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemModelGenerator.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemModelGenerator.java.patch index 801edaf8ca..0c2a9b043a 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemModelGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemModelGenerator.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/block/model/ItemModelGenerator.java +++ b/net/minecraft/client/renderer/block/model/ItemModelGenerator.java -@@ -40,6 +_,8 @@ - map.put("particle", p_111672_.hasTexture("particle") ? Either.left(p_111672_.getMaterial("particle")) : map.get("layer0")); - BlockModel blockmodel = new BlockModel((ResourceLocation)null, list, map, false, p_111672_.getGuiLight(), p_111672_.getTransforms(), p_111672_.getOverrides()); - blockmodel.name = p_111672_.name; -+ blockmodel.customData.copyFrom(p_111672_.customData); -+ blockmodel.customData.setGui3d(false); - return blockmodel; - } +@@ -39,6 +_,8 @@ + map.put("particle", p_111672_.hasTexture("particle") ? Either.left(p_111672_.getMaterial("particle")) : map.get("layer0")); + BlockModel blockmodel = new BlockModel(null, list, map, false, p_111672_.getGuiLight(), p_111672_.getTransforms(), p_111672_.getOverrides()); + blockmodel.name = p_111672_.name; ++ blockmodel.customData.copyFrom(p_111672_.customData); ++ blockmodel.customData.setGui3d(false); + return blockmodel; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemOverrides.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemOverrides.java.patch index bb4d83a4e5..ec4087f3f0 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemOverrides.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemOverrides.java.patch @@ -1,50 +1,50 @@ --- a/net/minecraft/client/renderer/block/model/ItemOverrides.java +++ b/net/minecraft/client/renderer/block/model/ItemOverrides.java -@@ -32,7 +_,15 @@ - this.properties = new ResourceLocation[0]; - } +@@ -31,7 +_,15 @@ + this.properties = new ResourceLocation[0]; + } -+ /** -+ * @deprecated Forge: Use {@link #ItemOverrides(ModelBaker, UnbakedModel, List, java.util.function.Function)} -+ */ -+ @Deprecated - public ItemOverrides(ModelBaker p_251211_, BlockModel p_111741_, List p_111743_) { -+ this(p_251211_, p_111741_, p_111743_, p_251211_.getModelTextureGetter()); -+ } ++ /** ++ * @deprecated Forge: Use {@link #ItemOverrides(ModelBaker, UnbakedModel, List, java.util.function.Function)} ++ */ ++ @Deprecated + public ItemOverrides(ModelBaker p_251211_, BlockModel p_111741_, List p_111743_) { ++ this(p_251211_, p_111741_, p_111743_, p_251211_.getModelTextureGetter()); ++ } + -+ public ItemOverrides(ModelBaker p_251211_, UnbakedModel p_111741_, List p_111743_, java.util.function.Function spriteGetter) { - this.properties = p_111743_.stream().flatMap(ItemOverride::getPredicates).map(ItemOverride.Predicate::getProperty).distinct().toArray((p_173479_) -> { - return new ResourceLocation[p_173479_]; - }); -@@ -46,7 +_,7 @@ ++ public ItemOverrides(ModelBaker p_251211_, UnbakedModel p_111741_, List p_111743_, java.util.function.Function spriteGetter) { + this.properties = p_111743_.stream().flatMap(ItemOverride::getPredicates).map(ItemOverride.Predicate::getProperty).distinct().toArray(ResourceLocation[]::new); + Object2IntMap object2intmap = new Object2IntOpenHashMap<>(); - for(int j = p_111743_.size() - 1; j >= 0; --j) { - ItemOverride itemoverride = p_111743_.get(j); -- BakedModel bakedmodel = this.bakeModel(p_251211_, p_111741_, itemoverride); -+ BakedModel bakedmodel = this.bakeModel(p_251211_, p_111741_, itemoverride, spriteGetter); - ItemOverrides.PropertyMatcher[] aitemoverrides$propertymatcher = itemoverride.getPredicates().map((p_173477_) -> { - int k = object2intmap.getInt(p_173477_.getProperty()); - return new ItemOverrides.PropertyMatcher(k, p_173477_.getValue()); -@@ -60,9 +_,9 @@ - } +@@ -43,7 +_,7 @@ - @Nullable -- private BakedModel bakeModel(ModelBaker p_249483_, BlockModel p_251965_, ItemOverride p_250816_) { -+ private BakedModel bakeModel(ModelBaker p_249483_, UnbakedModel p_251965_, ItemOverride p_250816_, java.util.function.Function spriteGetter) { - UnbakedModel unbakedmodel = p_249483_.getModel(p_250816_.getModel()); -- return Objects.equals(unbakedmodel, p_251965_) ? null : p_249483_.bake(p_250816_.getModel(), BlockModelRotation.X0_Y0); -+ return Objects.equals(unbakedmodel, p_251965_) ? null : p_249483_.bake(p_250816_.getModel(), BlockModelRotation.X0_Y0, spriteGetter); - } + for (int j = p_111743_.size() - 1; j >= 0; j--) { + ItemOverride itemoverride = p_111743_.get(j); +- BakedModel bakedmodel = this.bakeModel(p_251211_, p_111741_, itemoverride); ++ BakedModel bakedmodel = this.bakeModel(p_251211_, p_111741_, itemoverride, spriteGetter); + ItemOverrides.PropertyMatcher[] aitemoverrides$propertymatcher = itemoverride.getPredicates().map(p_173477_ -> { + int k = object2intmap.getInt(p_173477_.getProperty()); + return new ItemOverrides.PropertyMatcher(k, p_173477_.getValue()); +@@ -55,9 +_,9 @@ + } - @Nullable -@@ -95,6 +_,10 @@ - } + @Nullable +- private BakedModel bakeModel(ModelBaker p_249483_, BlockModel p_251965_, ItemOverride p_250816_) { ++ private BakedModel bakeModel(ModelBaker p_249483_, UnbakedModel p_251965_, ItemOverride p_250816_, java.util.function.Function spriteGetter) { + UnbakedModel unbakedmodel = p_249483_.getModel(p_250816_.getModel()); +- return Objects.equals(unbakedmodel, p_251965_) ? null : p_249483_.bake(p_250816_.getModel(), BlockModelRotation.X0_Y0); ++ return Objects.equals(unbakedmodel, p_251965_) ? null : p_249483_.bake(p_250816_.getModel(), BlockModelRotation.X0_Y0, spriteGetter); + } - return p_173465_; -+ } + @Nullable +@@ -89,6 +_,10 @@ + } + + return p_173465_; ++ } + -+ public com.google.common.collect.ImmutableList getOverrides() { -+ return com.google.common.collect.ImmutableList.copyOf(overrides); - } ++ public com.google.common.collect.ImmutableList getOverrides() { ++ return com.google.common.collect.ImmutableList.copyOf(overrides); + } - @OnlyIn(Dist.CLIENT) + @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransform.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransform.java.patch index c20eb88287..ab59daaf96 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransform.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransform.java.patch @@ -1,38 +1,29 @@ --- a/net/minecraft/client/renderer/block/model/ItemTransform.java +++ b/net/minecraft/client/renderer/block/model/ItemTransform.java -@@ -22,11 +_,17 @@ - public final Vector3f rotation; - public final Vector3f translation; - public final Vector3f scale; -+ public final Vector3f rightRotation; +@@ -21,11 +_,17 @@ + public final Vector3f rotation; + public final Vector3f translation; + public final Vector3f scale; ++ public final Vector3f rightRotation; - public ItemTransform(Vector3f p_254427_, Vector3f p_254496_, Vector3f p_254022_) { -+ this(p_254427_, p_254496_, p_254022_, new Vector3f()); -+ } + public ItemTransform(Vector3f p_254427_, Vector3f p_254496_, Vector3f p_254022_) { ++ this(p_254427_, p_254496_, p_254022_, new Vector3f()); ++ } + -+ public ItemTransform(Vector3f p_254427_, Vector3f p_254496_, Vector3f p_254022_, Vector3f rightRotation) { - this.rotation = new Vector3f((Vector3fc)p_254427_); - this.translation = new Vector3f((Vector3fc)p_254496_); - this.scale = new Vector3f((Vector3fc)p_254022_); -+ this.rightRotation = new Vector3f(rightRotation); - } ++ public ItemTransform(Vector3f p_254427_, Vector3f p_254496_, Vector3f p_254022_, Vector3f rightRotation) { + this.rotation = new Vector3f(p_254427_); + this.translation = new Vector3f(p_254496_); + this.scale = new Vector3f(p_254022_); ++ this.rightRotation = new Vector3f(rightRotation); + } - public void apply(boolean p_111764_, PoseStack p_111765_) { -@@ -43,6 +_,7 @@ - p_111765_.translate((float)i * this.translation.x(), this.translation.y(), this.translation.z()); - p_111765_.mulPose((new Quaternionf()).rotationXYZ(f * ((float)Math.PI / 180F), f1 * ((float)Math.PI / 180F), f2 * ((float)Math.PI / 180F))); - p_111765_.scale(this.scale.x(), this.scale.y(), this.scale.z()); -+ p_111765_.mulPose(net.minecraftforge.common.util.TransformationHelper.quatFromXYZ(rightRotation.x(), rightRotation.y() * (p_111764_ ? -1 : 1), rightRotation.z() * (p_111764_ ? -1 : 1), true)); - } - } + public void apply(boolean p_111764_, PoseStack p_111765_) { +@@ -82,7 +_,7 @@ + vector3f1.set(Mth.clamp(vector3f1.x, -5.0F, 5.0F), Mth.clamp(vector3f1.y, -5.0F, 5.0F), Mth.clamp(vector3f1.z, -5.0F, 5.0F)); + Vector3f vector3f2 = this.getVector3f(jsonobject, "scale", DEFAULT_SCALE); + vector3f2.set(Mth.clamp(vector3f2.x, -4.0F, 4.0F), Mth.clamp(vector3f2.y, -4.0F, 4.0F), Mth.clamp(vector3f2.z, -4.0F, 4.0F)); +- return new ItemTransform(vector3f, vector3f1, vector3f2); ++ return new ItemTransform(vector3f, vector3f1, vector3f2, this.getVector3f(jsonobject, "right_rotation", DEFAULT_ROTATION)); + } -@@ -79,7 +_,8 @@ - vector3f1.set(Mth.clamp(vector3f1.x, -5.0F, 5.0F), Mth.clamp(vector3f1.y, -5.0F, 5.0F), Mth.clamp(vector3f1.z, -5.0F, 5.0F)); - Vector3f vector3f2 = this.getVector3f(jsonobject, "scale", DEFAULT_SCALE); - vector3f2.set(Mth.clamp(vector3f2.x, -4.0F, 4.0F), Mth.clamp(vector3f2.y, -4.0F, 4.0F), Mth.clamp(vector3f2.z, -4.0F, 4.0F)); -- return new ItemTransform(vector3f, vector3f1, vector3f2); -+ Vector3f rightRotation = this.getVector3f(jsonobject, "right_rotation", DEFAULT_ROTATION); -+ return new ItemTransform(vector3f, vector3f1, vector3f2, rightRotation); - } - - private Vector3f getVector3f(JsonObject p_111779_, String p_111780_, Vector3f p_253777_) { + private Vector3f getVector3f(JsonObject p_111779_, String p_111780_, Vector3f p_253777_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransforms.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransforms.java.patch index 6dfdc749df..479bb8a726 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransforms.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/ItemTransforms.java.patch @@ -1,75 +1,83 @@ --- a/net/minecraft/client/renderer/block/model/ItemTransforms.java +++ b/net/minecraft/client/renderer/block/model/ItemTransforms.java -@@ -21,11 +_,13 @@ - public final ItemTransform gui; - public final ItemTransform ground; - public final ItemTransform fixed; -+ public final com.google.common.collect.ImmutableMap moddedTransforms; +@@ -21,6 +_,7 @@ + public final ItemTransform gui; + public final ItemTransform ground; + public final ItemTransform fixed; ++ public final com.google.common.collect.ImmutableMap moddedTransforms; - private ItemTransforms() { - this(ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM, ItemTransform.NO_TRANSFORM); - } + private ItemTransforms() { + this( +@@ -35,6 +_,7 @@ + ); + } -+ @Deprecated - public ItemTransforms(ItemTransforms p_111807_) { - this.thirdPersonLeftHand = p_111807_.thirdPersonLeftHand; - this.thirdPersonRightHand = p_111807_.thirdPersonRightHand; -@@ -35,9 +_,16 @@ - this.gui = p_111807_.gui; - this.ground = p_111807_.ground; - this.fixed = p_111807_.fixed; -+ this.moddedTransforms = p_111807_.moddedTransforms; - } - -+ @Deprecated - public ItemTransforms(ItemTransform p_111798_, ItemTransform p_111799_, ItemTransform p_111800_, ItemTransform p_111801_, ItemTransform p_111802_, ItemTransform p_111803_, ItemTransform p_111804_, ItemTransform p_111805_) { -+ this(p_111798_, p_111799_, p_111800_, p_111801_, p_111802_, p_111803_, p_111804_, p_111805_, com.google.common.collect.ImmutableMap.of()); -+ } ++ @Deprecated + public ItemTransforms(ItemTransforms p_111807_) { + this.thirdPersonLeftHand = p_111807_.thirdPersonLeftHand; + this.thirdPersonRightHand = p_111807_.thirdPersonRightHand; +@@ -44,6 +_,12 @@ + this.gui = p_111807_.gui; + this.ground = p_111807_.ground; + this.fixed = p_111807_.fixed; ++ this.moddedTransforms = p_111807_.moddedTransforms; ++ } + -+ public ItemTransforms(ItemTransform p_111798_, ItemTransform p_111799_, ItemTransform p_111800_, ItemTransform p_111801_, ItemTransform p_111802_, ItemTransform p_111803_, ItemTransform p_111804_, ItemTransform p_111805_, -+ com.google.common.collect.ImmutableMap moddedTransforms) { - this.thirdPersonLeftHand = p_111798_; - this.thirdPersonRightHand = p_111799_; - this.firstPersonLeftHand = p_111800_; -@@ -46,6 +_,7 @@ - this.gui = p_111803_; - this.ground = p_111804_; - this.fixed = p_111805_; -+ this.moddedTransforms = moddedTransforms; - } ++ @Deprecated ++ public ItemTransforms(ItemTransform p_111798_, ItemTransform p_111799_, ItemTransform p_111800_, ItemTransform p_111801_, ItemTransform p_111802_, ItemTransform p_111803_, ItemTransform p_111804_, ItemTransform p_111805_) { ++ this(p_111798_, p_111799_, p_111800_, p_111801_, p_111802_, p_111803_, p_111804_, p_111805_, com.google.common.collect.ImmutableMap.of()); + } - public ItemTransform getTransform(ItemDisplayContext p_270619_) { + public ItemTransforms( +@@ -54,7 +_,8 @@ + ItemTransform p_111802_, + ItemTransform p_111803_, + ItemTransform p_111804_, +- ItemTransform p_111805_ ++ ItemTransform p_111805_, ++ com.google.common.collect.ImmutableMap moddedTransforms + ) { + this.thirdPersonLeftHand = p_111798_; + this.thirdPersonRightHand = p_111799_; +@@ -64,6 +_,7 @@ + this.gui = p_111803_; + this.ground = p_111804_; + this.fixed = p_111805_; ++ this.moddedTransforms = moddedTransforms; + } + + public ItemTransform getTransform(ItemDisplayContext p_270619_) { @@ -76,7 +_,7 @@ - itemtransform = this.fixed; - break; - default: -- itemtransform = ItemTransform.NO_TRANSFORM; -+ return moddedTransforms.getOrDefault(p_270619_, ItemTransform.NO_TRANSFORM); - } + case GUI -> this.gui; + case GROUND -> this.ground; + case FIXED -> this.fixed; +- default -> ItemTransform.NO_TRANSFORM; ++ default -> moddedTransforms.getOrDefault(p_270619_, ItemTransform.NO_TRANSFORM); + }; + } - return itemtransform; -@@ -106,7 +_,23 @@ - ItemTransform itemtransform5 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.GUI); - ItemTransform itemtransform6 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.GROUND); - ItemTransform itemtransform7 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.FIXED); -- return new ItemTransforms(itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7); -+ -+ var builder = com.google.common.collect.ImmutableMap.builder(); -+ for (ItemDisplayContext type : ItemDisplayContext.values()) { -+ if (type.isModded()) { -+ var transform = this.getTransform(p_111822_, jsonobject, type); -+ var fallbackType = type; -+ while (transform == ItemTransform.NO_TRANSFORM && fallbackType.fallback() != null) { -+ fallbackType = fallbackType.fallback(); -+ transform = this.getTransform(p_111822_, jsonobject, fallbackType); -+ } -+ if (transform != ItemTransform.NO_TRANSFORM){ -+ builder.put(type, transform); +@@ -104,8 +_,23 @@ + ItemTransform itemtransform5 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.GUI); + ItemTransform itemtransform6 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.GROUND); + ItemTransform itemtransform7 = this.getTransform(p_111822_, jsonobject, ItemDisplayContext.FIXED); ++ var builder = com.google.common.collect.ImmutableMap.builder(); ++ for (ItemDisplayContext type : ItemDisplayContext.values()) { ++ if (type.isModded()) { ++ var transform = this.getTransform(p_111822_, jsonobject, type); ++ var fallbackType = type; ++ while (transform == ItemTransform.NO_TRANSFORM && fallbackType.fallback() != null) { ++ fallbackType = fallbackType.fallback(); ++ transform = this.getTransform(p_111822_, jsonobject, fallbackType); ++ } ++ if (transform != ItemTransform.NO_TRANSFORM){ ++ builder.put(type, transform); ++ } + } + } -+ } + -+ return new ItemTransforms(itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7, builder.build()); - } + return new ItemTransforms( +- itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7 ++ itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7, builder.build() + ); + } - private ItemTransform getTransform(JsonDeserializationContext p_270385_, JsonObject p_270436_, ItemDisplayContext p_270100_) { diff --git a/patches/minecraft/net/minecraft/client/renderer/block/model/MultiVariant.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/model/MultiVariant.java.patch index e4add5f59e..438e617781 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/model/MultiVariant.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/model/MultiVariant.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/block/model/MultiVariant.java +++ b/net/minecraft/client/renderer/block/model/MultiVariant.java @@ -68,7 +_,7 @@ - WeightedBakedModel.Builder weightedbakedmodel$builder = new WeightedBakedModel.Builder(); + WeightedBakedModel.Builder weightedbakedmodel$builder = new WeightedBakedModel.Builder(); - for(Variant variant : this.getVariants()) { -- BakedModel bakedmodel = p_249016_.bake(variant.getModelLocation(), variant); -+ BakedModel bakedmodel = p_249016_.bake(variant.getModelLocation(), variant, p_111851_); - weightedbakedmodel$builder.add(bakedmodel, variant.getWeight()); - } + for (Variant variant : this.getVariants()) { +- BakedModel bakedmodel = p_249016_.bake(variant.getModelLocation(), variant); ++ BakedModel bakedmodel = p_249016_.bake(variant.getModelLocation(), variant, p_111851_); + weightedbakedmodel$builder.add(bakedmodel, variant.getWeight()); + } diff --git a/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch b/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch index 3dfaef75a5..a7aa026710 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java +++ b/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java -@@ -11,7 +_,7 @@ +@@ -12,7 +_,7 @@ @OnlyIn(Dist.CLIENT) public class BlockEntityRenderers { -- private static final Map, BlockEntityRendererProvider> PROVIDERS = Maps.newHashMap(); -+ private static final Map, BlockEntityRendererProvider> PROVIDERS = new java.util.concurrent.ConcurrentHashMap<>(); +- private static final Map, BlockEntityRendererProvider> PROVIDERS = Maps.newHashMap(); ++ private static final Map, BlockEntityRendererProvider> PROVIDERS = new java.util.concurrent.ConcurrentHashMap<>(); - public static void register(BlockEntityType p_173591_, BlockEntityRendererProvider p_173592_) { - PROVIDERS.put(p_173591_, p_173592_); + public static void register(BlockEntityType p_173591_, BlockEntityRendererProvider p_173592_) { + PROVIDERS.put(p_173591_, p_173592_); diff --git a/patches/minecraft/net/minecraft/client/renderer/blockentity/ChestRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/blockentity/ChestRenderer.java.patch index bba6e81663..9b77c7a5a8 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/ChestRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/ChestRenderer.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/client/renderer/blockentity/ChestRenderer.java +++ b/net/minecraft/client/renderer/blockentity/ChestRenderer.java -@@ -117,7 +_,7 @@ - f1 = 1.0F - f1; - f1 = 1.0F - f1 * f1 * f1; - int i = neighborcombineresult.apply(new BrightnessCombiner<>()).applyAsInt(p_112367_); -- Material material = Sheets.chooseMaterial(p_112363_, chesttype, this.xmasTextures); -+ Material material = this.getMaterial(p_112363_, chesttype); - VertexConsumer vertexconsumer = material.buffer(p_112366_, RenderType::entityCutout); - if (flag1) { - if (chesttype == ChestType.LEFT) { -@@ -139,5 +_,9 @@ - p_112372_.render(p_112370_, p_112371_, p_112376_, p_112377_); - p_112373_.render(p_112370_, p_112371_, p_112376_, p_112377_); - p_112374_.render(p_112370_, p_112371_, p_112376_, p_112377_); -+ } +@@ -128,7 +_,7 @@ + f1 = 1.0F - f1; + f1 = 1.0F - f1 * f1 * f1; + int i = neighborcombineresult.apply(new BrightnessCombiner<>()).applyAsInt(p_112367_); +- Material material = Sheets.chooseMaterial(p_112363_, chesttype, this.xmasTextures); ++ Material material = this.getMaterial(p_112363_, chesttype); + VertexConsumer vertexconsumer = material.buffer(p_112366_, RenderType::entityCutout); + if (flag1) { + if (chesttype == ChestType.LEFT) { +@@ -159,5 +_,9 @@ + p_112372_.render(p_112370_, p_112371_, p_112376_, p_112377_); + p_112373_.render(p_112370_, p_112371_, p_112376_, p_112377_); + p_112374_.render(p_112370_, p_112371_, p_112376_, p_112377_); ++ } + -+ protected Material getMaterial(T blockEntity, ChestType chestType) { -+ return Sheets.chooseMaterial(blockEntity, chestType, this.xmasTextures); - } ++ protected Material getMaterial(T blockEntity, ChestType chestType) { ++ return Sheets.chooseMaterial(blockEntity, chestType, this.xmasTextures); + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java.patch index e32fa126ab..2f6182f685 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java.patch @@ -1,15 +1,34 @@ --- a/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java +++ b/net/minecraft/client/renderer/blockentity/PistonHeadRenderer.java -@@ -60,9 +_,12 @@ - } +@@ -65,13 +_,15 @@ + private void renderBlock( + BlockPos p_112459_, BlockState p_112460_, PoseStack p_112461_, MultiBufferSource p_112462_, Level p_112463_, boolean p_112464_, int p_112465_ + ) { +- RenderType rendertype = ItemBlockRenderTypes.getMovingBlockRenderType(p_112460_); +- VertexConsumer vertexconsumer = p_112462_.getBuffer(rendertype); ++ var model = blockRenderer.getBlockModel(p_112460_); ++ var data = net.minecraftforge.client.model.data.ModelData.EMPTY; ++ for (var rendertype : model.getRenderTypes(p_112460_, RandomSource.create(p_112460_.getSeed(p_112459_)), data)) { ++ VertexConsumer vertexconsumer = p_112462_.getBuffer(net.minecraftforge.client.RenderTypeHelper.getMovingBlockRenderType(rendertype)); + this.blockRenderer + .getModelRenderer() + .tesselateBlock( + p_112463_, +- this.blockRenderer.getBlockModel(p_112460_), ++ model, + p_112460_, + p_112459_, + p_112461_, +@@ -79,8 +_,11 @@ + p_112464_, + RandomSource.create(), + p_112460_.getSeed(p_112459_), +- p_112465_ ++ p_112465_, ++ data, ++ rendertype + ); ++ } + } - private void renderBlock(BlockPos p_112459_, BlockState p_112460_, PoseStack p_112461_, MultiBufferSource p_112462_, Level p_112463_, boolean p_112464_, int p_112465_) { -+ net.minecraftforge.client.ForgeHooksClient.renderPistonMovedBlocks(p_112459_, p_112460_, p_112461_, p_112462_, p_112463_, p_112464_, p_112465_, blockRenderer == null ? blockRenderer = net.minecraft.client.Minecraft.getInstance().getBlockRenderer() : blockRenderer); -+ if(false) { - RenderType rendertype = ItemBlockRenderTypes.getMovingBlockRenderType(p_112460_); - VertexConsumer vertexconsumer = p_112462_.getBuffer(rendertype); - this.blockRenderer.getModelRenderer().tesselateBlock(p_112463_, this.blockRenderer.getBlockModel(p_112460_), p_112460_, p_112459_, p_112461_, vertexconsumer, p_112464_, RandomSource.create(), p_112460_.getSeed(p_112459_), p_112465_); -+ } - } - - public int getViewDistance() { + @Override diff --git a/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch index 3941ac956c..0e47d5cd8f 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java +++ b/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java -@@ -53,6 +_,7 @@ - builder.put(SkullBlock.Types.CREEPER, new SkullModel(p_173662_.bakeLayer(ModelLayers.CREEPER_HEAD))); - builder.put(SkullBlock.Types.DRAGON, new DragonHeadModel(p_173662_.bakeLayer(ModelLayers.DRAGON_SKULL))); - builder.put(SkullBlock.Types.PIGLIN, new PiglinHeadModel(p_173662_.bakeLayer(ModelLayers.PIGLIN_HEAD))); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.EntityRenderersEvent.CreateSkullModels(builder, p_173662_)); - return builder.build(); - } +@@ -55,6 +_,7 @@ + builder.put(SkullBlock.Types.CREEPER, new SkullModel(p_173662_.bakeLayer(ModelLayers.CREEPER_HEAD))); + builder.put(SkullBlock.Types.DRAGON, new DragonHeadModel(p_173662_.bakeLayer(ModelLayers.DRAGON_SKULL))); + builder.put(SkullBlock.Types.PIGLIN, new PiglinHeadModel(p_173662_.bakeLayer(ModelLayers.PIGLIN_HEAD))); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.EntityRenderersEvent.CreateSkullModels(builder, p_173662_)); + return builder.build(); + } diff --git a/patches/minecraft/net/minecraft/client/renderer/chunk/RenderChunkRegion.java.patch b/patches/minecraft/net/minecraft/client/renderer/chunk/RenderChunkRegion.java.patch index 6d2a835237..90c7bd555e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/chunk/RenderChunkRegion.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/chunk/RenderChunkRegion.java.patch @@ -1,17 +1,17 @@ --- a/net/minecraft/client/renderer/chunk/RenderChunkRegion.java +++ b/net/minecraft/client/renderer/chunk/RenderChunkRegion.java -@@ -66,4 +_,14 @@ - public int getHeight() { - return this.level.getHeight(); - } +@@ -74,4 +_,14 @@ + public int getHeight() { + return this.level.getHeight(); + } + -+ @Override -+ public float getShade(float normalX, float normalY, float normalZ, boolean shade) { -+ return this.level.getShade(normalX, normalY, normalZ, shade); -+ } ++ @Override ++ public float getShade(float normalX, float normalY, float normalZ, boolean shade) { ++ return this.level.getShade(normalX, normalY, normalZ, shade); ++ } + -+ @Override -+ public net.minecraftforge.client.model.data.ModelDataManager getModelDataManager() { -+ return level.getModelDataManager(); -+ } ++ @Override ++ public net.minecraftforge.client.model.data.ModelDataManager getModelDataManager() { ++ return level.getModelDataManager(); ++ } } diff --git a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java.patch index f75b82166f..eeab014b87 100644 --- a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java.patch @@ -1,117 +1,118 @@ --- a/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java +++ b/net/minecraft/client/renderer/chunk/SectionRenderDispatcher.java -@@ -394,7 +_,7 @@ - if (!sectionrenderdispatcher$compiledsection.hasBlocks.contains(p_301074_)) { - return false; - } else { -- this.lastResortTransparencyTask = new SectionRenderDispatcher.RenderSection.ResortTransparencyTask(this.getDistToPlayerSqr(), sectionrenderdispatcher$compiledsection); -+ this.lastResortTransparencyTask = new SectionRenderDispatcher.RenderSection.ResortTransparencyTask(new net.minecraft.world.level.ChunkPos(getOrigin()), this.getDistToPlayerSqr(), sectionrenderdispatcher$compiledsection); - p_298196_.schedule(this.lastResortTransparencyTask); - return true; - } -@@ -426,7 +_,7 @@ - this.initialCompilationCancelCount.incrementAndGet(); - } - -- this.lastRebuildTask = new SectionRenderDispatcher.RenderSection.RebuildTask(this.getDistToPlayerSqr(), renderchunkregion, !flag1 || this.initialCompilationCancelCount.get() > 2); -+ this.lastRebuildTask = new SectionRenderDispatcher.RenderSection.RebuildTask(new net.minecraft.world.level.ChunkPos(getOrigin()), this.getDistToPlayerSqr(), renderchunkregion, !flag1 || this.initialCompilationCancelCount.get() > 2); - return this.lastRebuildTask; - } - -@@ -464,10 +_,20 @@ - protected final double distAtCreation; - protected final AtomicBoolean isCancelled = new AtomicBoolean(false); - protected final boolean isHighPriority; -+ protected java.util.Map modelData; - - public CompileTask(double p_300617_, boolean p_299251_) { -+ this(null, p_300617_, p_299251_); -+ } -+ -+ public CompileTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_300617_, boolean p_299251_) { - this.distAtCreation = p_300617_; - this.isHighPriority = p_299251_; -+ if (pos == null) { -+ this.modelData = java.util.Collections.emptyMap(); -+ } else { -+ this.modelData = net.minecraft.client.Minecraft.getInstance().level.getModelDataManager().getAt(pos); -+ } - } - - public abstract CompletableFuture doTask(SectionBufferBuilderPack p_300298_); -@@ -479,6 +_,10 @@ - public int compareTo(SectionRenderDispatcher.RenderSection.CompileTask p_298947_) { - return Doubles.compare(this.distAtCreation, p_298947_.distAtCreation); - } -+ -+ public net.minecraftforge.client.model.data.ModelData getModelData(net.minecraft.core.BlockPos pos) { -+ return modelData.getOrDefault(pos, net.minecraftforge.client.model.data.ModelData.EMPTY); -+ } - } - - @OnlyIn(Dist.CLIENT) -@@ -486,8 +_,13 @@ - @Nullable - protected RenderChunkRegion region; - -+ @Deprecated - public RebuildTask(double p_301300_, @Nullable RenderChunkRegion p_300496_, boolean p_299891_) { -- super(p_301300_, p_299891_); -+ this(null, p_301300_, p_300496_, p_299891_); -+ } -+ -+ public RebuildTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_301300_, @Nullable RenderChunkRegion p_300496_, boolean p_299891_) { -+ super(pos, p_301300_, p_299891_); - this.region = p_300496_; - } - -@@ -583,7 +_,10 @@ - } - - if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { -- RenderType rendertype2 = ItemBlockRenderTypes.getChunkRenderType(blockstate); -+ var model = blockrenderdispatcher.getBlockModel(blockstate); -+ var modelData = model.getModelData(renderchunkregion, blockpos2, blockstate, getModelData(blockpos2)); -+ randomsource.setSeed(blockstate.getSeed(blockpos2)); -+ for (RenderType rendertype2 : model.getRenderTypes(blockstate, randomsource, modelData)) { - BufferBuilder bufferbuilder2 = p_300020_.builder(rendertype2); - if (set.add(rendertype2)) { - RenderSection.this.beginLayer(bufferbuilder2); -@@ -591,8 +_,9 @@ - - posestack.pushPose(); - posestack.translate((float)(blockpos2.getX() & 15), (float)(blockpos2.getY() & 15), (float)(blockpos2.getZ() & 15)); -- blockrenderdispatcher.renderBatched(blockstate, blockpos2, renderchunkregion, posestack, bufferbuilder2, true, randomsource); -+ blockrenderdispatcher.renderBatched(blockstate, blockpos2, renderchunkregion, posestack, bufferbuilder2, true, randomsource, modelData, rendertype2); - posestack.popPose(); -+ } - } - } - -@@ -621,10 +_,10 @@ - private void handleBlockEntity(SectionRenderDispatcher.RenderSection.RebuildTask.CompileResults p_297364_, E p_299361_) { - BlockEntityRenderer blockentityrenderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(p_299361_); - if (blockentityrenderer != null) { -- p_297364_.blockEntities.add(p_299361_); - if (blockentityrenderer.shouldRenderOffScreen(p_299361_)) { - p_297364_.globalBlockEntities.add(p_299361_); - } -+ else p_297364_.blockEntities.add(p_299361_); //FORGE: Fix MC-112730 +@@ -402,7 +_,7 @@ + if (!sectionrenderdispatcher$compiledsection.hasBlocks.contains(p_301074_)) { + return false; + } else { +- this.lastResortTransparencyTask = new SectionRenderDispatcher.RenderSection.ResortTransparencyTask(this.getDistToPlayerSqr(), sectionrenderdispatcher$compiledsection); ++ this.lastResortTransparencyTask = new SectionRenderDispatcher.RenderSection.ResortTransparencyTask(new net.minecraft.world.level.ChunkPos(getOrigin()), this.getDistToPlayerSqr(), sectionrenderdispatcher$compiledsection); + p_298196_.schedule(this.lastResortTransparencyTask); + return true; + } +@@ -436,7 +_,7 @@ + this.initialCompilationCancelCount.incrementAndGet(); } - } -@@ -652,8 +_,13 @@ - class ResortTransparencyTask extends SectionRenderDispatcher.RenderSection.CompileTask { - private final SectionRenderDispatcher.CompiledSection compiledSection; +- this.lastRebuildTask = new SectionRenderDispatcher.RenderSection.RebuildTask(this.getDistToPlayerSqr(), renderchunkregion, !flag1 || this.initialCompilationCancelCount.get() > 2); ++ this.lastRebuildTask = new SectionRenderDispatcher.RenderSection.RebuildTask(new net.minecraft.world.level.ChunkPos(getOrigin()), this.getDistToPlayerSqr(), renderchunkregion, !flag1 || this.initialCompilationCancelCount.get() > 2); + return this.lastRebuildTask; + } -+ @Deprecated - public ResortTransparencyTask(double p_300619_, SectionRenderDispatcher.CompiledSection p_297742_) { -- super(p_300619_, true); -+ this(null, p_300619_, p_297742_); -+ } +@@ -476,10 +_,21 @@ + protected final double distAtCreation; + protected final AtomicBoolean isCancelled = new AtomicBoolean(false); + protected final boolean isHighPriority; ++ protected java.util.Map modelData; + ++ @Deprecated + public CompileTask(final double p_300617_, final boolean p_299251_) { ++ this(null, p_300617_, p_299251_); ++ } + -+ public ResortTransparencyTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_300619_, SectionRenderDispatcher.CompiledSection p_297742_) { -+ super(pos, p_300619_, true); - this.compiledSection = p_297742_; - } ++ public CompileTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_300617_, boolean p_299251_) { + this.distAtCreation = p_300617_; + this.isHighPriority = p_299251_; ++ if (pos == null) { ++ this.modelData = java.util.Collections.emptyMap(); ++ } else { ++ this.modelData = net.minecraft.client.Minecraft.getInstance().level.getModelDataManager().getAt(pos); ++ } + } + + public abstract CompletableFuture doTask(SectionBufferBuilderPack p_300298_); +@@ -491,6 +_,10 @@ + public int compareTo(SectionRenderDispatcher.RenderSection.CompileTask p_298947_) { + return Doubles.compare(this.distAtCreation, p_298947_.distAtCreation); + } ++ ++ public net.minecraftforge.client.model.data.ModelData getModelData(net.minecraft.core.BlockPos pos) { ++ return modelData.getOrDefault(pos, net.minecraftforge.client.model.data.ModelData.EMPTY); ++ } + } + + @OnlyIn(Dist.CLIENT) +@@ -498,8 +_,13 @@ + @Nullable + protected RenderChunkRegion region; + ++ @Deprecated + public RebuildTask(final double p_301300_, @Nullable final RenderChunkRegion p_300496_, final boolean p_299891_) { +- super(p_301300_, p_299891_); ++ this(null, p_301300_, p_300496_, p_299891_); ++ } ++ ++ public RebuildTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_301300_, @Nullable RenderChunkRegion p_300496_, boolean p_299891_) { ++ super(pos, p_301300_, p_299891_); + this.region = p_300496_; + } + +@@ -601,7 +_,10 @@ + } + + if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { +- RenderType rendertype2 = ItemBlockRenderTypes.getChunkRenderType(blockstate); ++ var model = blockrenderdispatcher.getBlockModel(blockstate); ++ var modelData = model.getModelData(renderchunkregion, blockpos2, blockstate, getModelData(blockpos2)); ++ randomsource.setSeed(blockstate.getSeed(blockpos2)); ++ for (RenderType rendertype2 : model.getRenderTypes(blockstate, randomsource, modelData)) { + BufferBuilder bufferbuilder2 = p_300020_.builder(rendertype2); + if (set.add(rendertype2)) { + RenderSection.this.beginLayer(bufferbuilder2); +@@ -609,8 +_,9 @@ + + posestack.pushPose(); + posestack.translate((float)(blockpos2.getX() & 15), (float)(blockpos2.getY() & 15), (float)(blockpos2.getZ() & 15)); +- blockrenderdispatcher.renderBatched(blockstate, blockpos2, renderchunkregion, posestack, bufferbuilder2, true, randomsource); ++ blockrenderdispatcher.renderBatched(blockstate, blockpos2, renderchunkregion, posestack, bufferbuilder2, true, randomsource, modelData, rendertype2); + posestack.popPose(); ++ } + } + } + +@@ -643,9 +_,10 @@ + private void handleBlockEntity(SectionRenderDispatcher.RenderSection.RebuildTask.CompileResults p_297364_, E p_299361_) { + BlockEntityRenderer blockentityrenderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(p_299361_); + if (blockentityrenderer != null) { +- p_297364_.blockEntities.add(p_299361_); + if (blockentityrenderer.shouldRenderOffScreen(p_299361_)) { + p_297364_.globalBlockEntities.add(p_299361_); ++ } else { ++ p_297364_.blockEntities.add(p_299361_); //FORGE: Fix MC-112730 + } + } + } +@@ -673,8 +_,13 @@ + class ResortTransparencyTask extends SectionRenderDispatcher.RenderSection.CompileTask { + private final SectionRenderDispatcher.CompiledSection compiledSection; + ++ @Deprecated + public ResortTransparencyTask(final double p_300619_, final SectionRenderDispatcher.CompiledSection p_297742_) { +- super(p_300619_, true); ++ this(null, p_300619_, p_297742_); ++ } ++ ++ public ResortTransparencyTask(@Nullable net.minecraft.world.level.ChunkPos pos, double p_300619_, SectionRenderDispatcher.CompiledSection p_297742_) { ++ super(pos, p_300619_, true); + this.compiledSection = p_297742_; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch b/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch index f8b1536645..ea5f2a5dec 100644 --- a/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/culling/Frustum.java +++ b/net/minecraft/client/renderer/culling/Frustum.java -@@ -59,6 +_,8 @@ - } +@@ -70,6 +_,8 @@ + } - public boolean isVisible(AABB p_113030_) { -+ // FORGE: exit early for infinite bounds, these would otherwise fail in the intersection test at certain camera angles (GH-9321) -+ if (p_113030_.equals(net.minecraftforge.common.extensions.IForgeBlockEntity.INFINITE_EXTENT_AABB)) return true; - return this.cubeInFrustum(p_113030_.minX, p_113030_.minY, p_113030_.minZ, p_113030_.maxX, p_113030_.maxY, p_113030_.maxZ); - } + public boolean isVisible(AABB p_113030_) { ++ // Forge: exit early for infinite bounds, these would otherwise fail in the intersection test at certain camera angles (GH-9321) ++ if (p_113030_.equals(net.minecraftforge.common.extensions.IForgeBlockEntity.INFINITE_EXTENT_AABB)) return true; + return this.cubeInFrustum(p_113030_.minX, p_113030_.minY, p_113030_.minZ, p_113030_.maxX, p_113030_.maxY, p_113030_.maxZ); + } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/BoatRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/BoatRenderer.java.patch index 431fba53ad..92be634708 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/BoatRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/BoatRenderer.java.patch @@ -1,23 +1,24 @@ --- a/net/minecraft/client/renderer/entity/BoatRenderer.java +++ b/net/minecraft/client/renderer/entity/BoatRenderer.java -@@ -73,7 +_,7 @@ - p_113932_.mulPose((new Quaternionf()).setAngleAxis(p_113929_.getBubbleAngle(p_113931_) * ((float)Math.PI / 180F), 1.0F, 0.0F, 1.0F)); - } +@@ -75,7 +_,7 @@ + p_113932_.mulPose(new Quaternionf().setAngleAxis(p_113929_.getBubbleAngle(p_113931_) * (float) (Math.PI / 180.0), 1.0F, 0.0F, 1.0F)); + } -- Pair> pair = this.boatResources.get(p_113929_.getVariant()); -+ Pair> pair = getModelWithLocation(p_113929_); - ResourceLocation resourcelocation = pair.getFirst(); - ListModel listmodel = pair.getSecond(); - p_113932_.scale(-1.0F, -1.0F, 1.0F); -@@ -93,7 +_,10 @@ - super.render(p_113929_, p_113930_, p_113931_, p_113932_, p_113933_, p_113934_); - } +- Pair> pair = this.boatResources.get(p_113929_.getVariant()); ++ Pair> pair = getModelWithLocation(p_113929_); + ResourceLocation resourcelocation = pair.getFirst(); + ListModel listmodel = pair.getSecond(); + p_113932_.scale(-1.0F, -1.0F, 1.0F); +@@ -94,7 +_,12 @@ + super.render(p_113929_, p_113930_, p_113931_, p_113932_, p_113933_, p_113934_); + } -+ @Deprecated // forge: override getModelWithLocation to change the texture / model - public ResourceLocation getTextureLocation(Boat p_113927_) { -- return this.boatResources.get(p_113927_.getVariant()).getFirst(); -+ return getModelWithLocation(p_113927_).getFirst(); - } ++ @Deprecated // forge: override getModelWithLocation to change the texture / model + public ResourceLocation getTextureLocation(Boat p_113927_) { + return this.boatResources.get(p_113927_.getVariant()).getFirst(); ++ } + -+ public Pair> getModelWithLocation(Boat boat) { return this.boatResources.get(boat.getVariant()); } ++ public Pair> getModelWithLocation(Boat boat) { ++ return this.boatResources.get(boat.getVariant()); + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch index 82e883abea..9be449172a 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch @@ -1,32 +1,35 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java +++ b/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java -@@ -172,12 +_,12 @@ - private static void renderHitbox(PoseStack p_114442_, VertexConsumer p_114443_, Entity p_114444_, float p_114445_) { - AABB aabb = p_114444_.getBoundingBox().move(-p_114444_.getX(), -p_114444_.getY(), -p_114444_.getZ()); - LevelRenderer.renderLineBox(p_114442_, p_114443_, aabb, 1.0F, 1.0F, 1.0F, 1.0F); -- if (p_114444_ instanceof EnderDragon) { -+ if (p_114444_.isMultipartEntity()) { - double d0 = -Mth.lerp((double)p_114445_, p_114444_.xOld, p_114444_.getX()); - double d1 = -Mth.lerp((double)p_114445_, p_114444_.yOld, p_114444_.getY()); - double d2 = -Mth.lerp((double)p_114445_, p_114444_.zOld, p_114444_.getZ()); +@@ -190,12 +_,12 @@ + private static void renderHitbox(PoseStack p_114442_, VertexConsumer p_114443_, Entity p_114444_, float p_114445_) { + AABB aabb = p_114444_.getBoundingBox().move(-p_114444_.getX(), -p_114444_.getY(), -p_114444_.getZ()); + LevelRenderer.renderLineBox(p_114442_, p_114443_, aabb, 1.0F, 1.0F, 1.0F, 1.0F); +- if (p_114444_ instanceof EnderDragon) { ++ if (p_114444_.isMultipartEntity()) { + double d0 = -Mth.lerp((double)p_114445_, p_114444_.xOld, p_114444_.getX()); + double d1 = -Mth.lerp((double)p_114445_, p_114444_.yOld, p_114444_.getY()); + double d2 = -Mth.lerp((double)p_114445_, p_114444_.zOld, p_114444_.getZ()); -- for(EnderDragonPart enderdragonpart : ((EnderDragon)p_114444_).getSubEntities()) { -+ for(net.minecraftforge.entity.PartEntity enderdragonpart : p_114444_.getParts()) { - p_114442_.pushPose(); - double d3 = d0 + Mth.lerp((double)p_114445_, enderdragonpart.xOld, enderdragonpart.getX()); - double d4 = d1 + Mth.lerp((double)p_114445_, enderdragonpart.yOld, enderdragonpart.getY()); -@@ -359,9 +_,14 @@ - return this.itemInHandRenderer; - } +- for (EnderDragonPart enderdragonpart : ((EnderDragon)p_114444_).getSubEntities()) { ++ for (var enderdragonpart : p_114444_.getParts()) { + p_114442_.pushPose(); + double d3 = d0 + Mth.lerp((double)p_114445_, enderdragonpart.xOld, enderdragonpart.getX()); + double d4 = d1 + Mth.lerp((double)p_114445_, enderdragonpart.yOld, enderdragonpart.getY()); +@@ -440,6 +_,10 @@ + return this.itemInHandRenderer; + } -+ public Map> getSkinMap() { -+ return java.util.Collections.unmodifiableMap(playerRenderers); -+ } ++ public Map> getSkinMap() { ++ return java.util.Collections.unmodifiableMap(playerRenderers); ++ } + - public void onResourceManagerReload(ResourceManager p_174004_) { - EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context(this, this.itemRenderer, this.blockRenderDispatcher, this.itemInHandRenderer, p_174004_, this.entityModels, this.font); - this.renderers = EntityRenderers.createEntityRenderers(entityrendererprovider$context); - this.playerRenderers = EntityRenderers.createPlayerRenderers(entityrendererprovider$context); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.gatherLayers(renderers, playerRenderers, entityrendererprovider$context); - } + @Override + public void onResourceManagerReload(ResourceManager p_174004_) { + EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context( +@@ -447,5 +_,6 @@ + ); + this.renderers = EntityRenderers.createEntityRenderers(entityrendererprovider$context); + this.playerRenderers = EntityRenderers.createPlayerRenderers(entityrendererprovider$context); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onGatherLayers(renderers, playerRenderers, entityrendererprovider$context); + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch index a0d79963b9..625dd62a65 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch @@ -1,24 +1,23 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderer.java +++ b/net/minecraft/client/renderer/entity/EntityRenderer.java -@@ -63,8 +_,10 @@ - } +@@ -71,8 +_,9 @@ + } - public void render(T p_114485_, float p_114486_, float p_114487_, PoseStack p_114488_, MultiBufferSource p_114489_, int p_114490_) { -- if (this.shouldShowName(p_114485_)) { -- this.renderNameTag(p_114485_, p_114485_.getDisplayName(), p_114488_, p_114489_, p_114490_); -+ var renderNameTagEvent = new net.minecraftforge.client.event.RenderNameTagEvent(p_114485_, p_114485_.getDisplayName(), this, p_114488_, p_114489_, p_114490_, p_114487_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(renderNameTagEvent); -+ if (renderNameTagEvent.getResult() != net.minecraftforge.eventbus.api.Event.Result.DENY && (renderNameTagEvent.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || this.shouldShowName(p_114485_))) { -+ this.renderNameTag(p_114485_, renderNameTagEvent.getContent(), p_114488_, p_114489_, p_114490_); - } - } + public void render(T p_114485_, float p_114486_, float p_114487_, PoseStack p_114488_, MultiBufferSource p_114489_, int p_114490_) { +- if (this.shouldShowName(p_114485_)) { +- this.renderNameTag(p_114485_, p_114485_.getDisplayName(), p_114488_, p_114489_, p_114490_, p_114487_); ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.fireRenderNameTagEvent(p_114485_, p_114485_.getDisplayName(), this, p_114488_, p_114489_, p_114490_, p_114487_); ++ if (event.getResult() != net.minecraftforge.eventbus.api.Event.Result.DENY && (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || this.shouldShowName(p_114485_))) { ++ this.renderNameTag(p_114485_, event.getContent(), p_114488_, p_114489_, p_114490_, p_114487_); + } + } -@@ -80,7 +_,7 @@ +@@ -88,7 +_,7 @@ - protected void renderNameTag(T p_114498_, Component p_114499_, PoseStack p_114500_, MultiBufferSource p_114501_, int p_114502_) { - double d0 = this.entityRenderDispatcher.distanceToSqr(p_114498_); -- if (!(d0 > 4096.0D)) { -+ if (net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(p_114498_, d0)) { - boolean flag = !p_114498_.isDiscrete(); - float f = p_114498_.getNameTagOffsetY(); - int i = "deadmau5".equals(p_114499_.getString()) ? -10 : 0; + protected void renderNameTag(T p_114498_, Component p_114499_, PoseStack p_114500_, MultiBufferSource p_114501_, int p_114502_, float p_334448_) { + double d0 = this.entityRenderDispatcher.distanceToSqr(p_114498_); +- if (!(d0 > 4096.0)) { ++ if (net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(p_114498_, d0)) { + Vec3 vec3 = p_114498_.getAttachments().getNullable(EntityAttachment.NAME_TAG, 0, p_114498_.getViewYRot(p_334448_)); + if (vec3 != null) { + boolean flag = !p_114498_.isDiscrete(); diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/FallingBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/FallingBlockRenderer.java.patch index 8f796542b8..9c3edbaf2a 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/FallingBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/FallingBlockRenderer.java.patch @@ -1,13 +1,31 @@ --- a/net/minecraft/client/renderer/entity/FallingBlockRenderer.java +++ b/net/minecraft/client/renderer/entity/FallingBlockRenderer.java -@@ -34,7 +_,9 @@ - p_114637_.pushPose(); - BlockPos blockpos = BlockPos.containing(p_114634_.getX(), p_114634_.getBoundingBox().maxY, p_114634_.getZ()); - p_114637_.translate(-0.5D, 0.0D, -0.5D); -- this.dispatcher.getModelRenderer().tesselateBlock(level, this.dispatcher.getBlockModel(blockstate), blockstate, blockpos, p_114637_, p_114638_.getBuffer(ItemBlockRenderTypes.getMovingBlockRenderType(blockstate)), false, RandomSource.create(), blockstate.getSeed(p_114634_.getStartPos()), OverlayTexture.NO_OVERLAY); -+ var model = this.dispatcher.getBlockModel(blockstate); -+ for (var renderType : model.getRenderTypes(blockstate, RandomSource.create(blockstate.getSeed(p_114634_.getStartPos())), net.minecraftforge.client.model.data.ModelData.EMPTY)) -+ this.dispatcher.getModelRenderer().tesselateBlock(level, model, blockstate, blockpos, p_114637_, p_114638_.getBuffer(renderType), false, RandomSource.create(), blockstate.getSeed(p_114634_.getStartPos()), OverlayTexture.NO_OVERLAY, net.minecraftforge.client.model.data.ModelData.EMPTY, renderType); - p_114637_.popPose(); - super.render(p_114634_, p_114635_, p_114636_, p_114637_, p_114638_, p_114639_); - } +@@ -34,20 +_,25 @@ + p_114637_.pushPose(); + BlockPos blockpos = BlockPos.containing(p_114634_.getX(), p_114634_.getBoundingBox().maxY, p_114634_.getZ()); + p_114637_.translate(-0.5, 0.0, -0.5); ++ var model = this.dispatcher.getBlockModel(blockstate); ++ for (var renderType : model.getRenderTypes(blockstate, RandomSource.create(blockstate.getSeed(p_114634_.getStartPos())), net.minecraftforge.client.model.data.ModelData.EMPTY)) { + this.dispatcher + .getModelRenderer() + .tesselateBlock( + level, +- this.dispatcher.getBlockModel(blockstate), ++ model, + blockstate, + blockpos, + p_114637_, +- p_114638_.getBuffer(ItemBlockRenderTypes.getMovingBlockRenderType(blockstate)), ++ p_114638_.getBuffer(renderType), + false, + RandomSource.create(), + blockstate.getSeed(p_114634_.getStartPos()), +- OverlayTexture.NO_OVERLAY ++ OverlayTexture.NO_OVERLAY, ++ net.minecraftforge.client.model.data.ModelData.EMPTY, ++ renderType + ); ++ } + p_114637_.popPose(); + super.render(p_114634_, p_114635_, p_114636_, p_114637_, p_114638_, p_114639_); + } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/FishingHookRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/FishingHookRenderer.java.patch index a331f68ac5..8649bf4f60 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/FishingHookRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/FishingHookRenderer.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/entity/FishingHookRenderer.java +++ b/net/minecraft/client/renderer/entity/FishingHookRenderer.java -@@ -49,7 +_,7 @@ - p_114708_.popPose(); - int i = player.getMainArm() == HumanoidArm.RIGHT ? 1 : -1; - ItemStack itemstack = player.getMainHandItem(); -- if (!itemstack.is(Items.FISHING_ROD)) { -+ if (!itemstack.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST)) { +@@ -66,7 +_,7 @@ + private Vec3 getPlayerHandPos(Player p_328037_, float p_328369_, float p_332926_) { + int i = p_328037_.getMainArm() == HumanoidArm.RIGHT ? 1 : -1; + ItemStack itemstack = p_328037_.getMainHandItem(); +- if (!itemstack.is(Items.FISHING_ROD)) { ++ if (!itemstack.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST)) { i = -i; - } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/ItemEntityRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/ItemEntityRenderer.java.patch deleted file mode 100644 index 71458b4a07..0000000000 --- a/patches/minecraft/net/minecraft/client/renderer/entity/ItemEntityRenderer.java.patch +++ /dev/null @@ -1,69 +0,0 @@ ---- a/net/minecraft/client/renderer/entity/ItemEntityRenderer.java -+++ b/net/minecraft/client/renderer/entity/ItemEntityRenderer.java -@@ -61,18 +_,15 @@ - boolean flag = bakedmodel.isGui3d(); - int j = this.getRenderAmount(itemstack); - float f = 0.25F; -- float f1 = Mth.sin(((float)p_115036_.getAge() + p_115038_) / 10.0F + p_115036_.bobOffs) * 0.1F + 0.1F; -+ float f1 = shouldBob() ? Mth.sin(((float)p_115036_.getAge() + p_115038_) / 10.0F + p_115036_.bobOffs) * 0.1F + 0.1F : 0; - float f2 = bakedmodel.getTransforms().getTransform(ItemDisplayContext.GROUND).scale.y(); - p_115039_.translate(0.0F, f1 + 0.25F * f2, 0.0F); - float f3 = p_115036_.getSpin(p_115038_); - p_115039_.mulPose(Axis.YP.rotation(f3)); -- float f4 = bakedmodel.getTransforms().ground.scale.x(); -- float f5 = bakedmodel.getTransforms().ground.scale.y(); -- float f6 = bakedmodel.getTransforms().ground.scale.z(); - if (!flag) { -- float f7 = -0.0F * (float)(j - 1) * 0.5F * f4; -- float f8 = -0.0F * (float)(j - 1) * 0.5F * f5; -- float f9 = -0.09375F * (float)(j - 1) * 0.5F * f6; -+ float f7 = -0.0F * (float)(j - 1) * 0.5F; -+ float f8 = -0.0F * (float)(j - 1) * 0.5F; -+ float f9 = -0.09375F * (float)(j - 1) * 0.5F; - p_115039_.translate(f7, f8, f9); - } - -@@ -83,18 +_,18 @@ - float f11 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F; - float f13 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F; - float f10 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F; -- p_115039_.translate(f11, f13, f10); -+ p_115039_.translate(shouldSpreadItems() ? f11 : 0, shouldSpreadItems() ? f13 : 0, shouldSpreadItems() ? f10 : 0); - } else { - float f12 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F * 0.5F; - float f14 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F * 0.5F; -- p_115039_.translate(f12, f14, 0.0F); -+ p_115039_.translate(shouldSpreadItems() ? f12 : 0, shouldSpreadItems() ? f14 : 0, 0.0D); - } - } - - this.itemRenderer.render(itemstack, ItemDisplayContext.GROUND, false, p_115039_, p_115040_, p_115041_, OverlayTexture.NO_OVERLAY, bakedmodel); - p_115039_.popPose(); - if (!flag) { -- p_115039_.translate(0.0F * f4, 0.0F * f5, 0.09375F * f6); -+ p_115039_.translate(0.0, 0.0, 0.09375F); - } - } - -@@ -105,4 +_,21 @@ - public ResourceLocation getTextureLocation(ItemEntity p_115034_) { - return TextureAtlas.LOCATION_BLOCKS; - } -+ -+ /*==================================== FORGE START ===========================================*/ -+ -+ /** -+ * @return If items should spread out when rendered in 3D -+ */ -+ public boolean shouldSpreadItems() { -+ return true; -+ } -+ -+ /** -+ * @return If items should have a bob effect -+ */ -+ public boolean shouldBob() { -+ return true; -+ } -+ /*==================================== FORGE END =============================================*/ - } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch index d0fc0fe29a..c7a13658e9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch @@ -1,49 +1,27 @@ --- a/net/minecraft/client/renderer/entity/ItemFrameRenderer.java +++ b/net/minecraft/client/renderer/entity/ItemFrameRenderer.java -@@ -70,31 +_,32 @@ - } +@@ -91,6 +_,7 @@ - if (!itemstack.isEmpty()) { -- OptionalInt optionalint = p_115076_.getFramedMapId(); -+ MapItemSavedData mapitemsaveddata = MapItem.getSavedData(itemstack, p_115076_.level()); - if (flag) { - p_115079_.translate(0.0F, 0.0F, 0.5F); - } else { - p_115079_.translate(0.0F, 0.0F, 0.4375F); - } - -- int j = optionalint.isPresent() ? p_115076_.getRotation() % 4 * 2 : p_115076_.getRotation(); -+ int j = mapitemsaveddata != null ? p_115076_.getRotation() % 4 * 2 : p_115076_.getRotation(); - p_115079_.mulPose(Axis.ZP.rotationDegrees((float)j * 360.0F / 8.0F)); -- if (optionalint.isPresent()) { -+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderItemInFrameEvent(p_115076_, this, p_115079_, p_115080_, p_115081_))) { -+ if (mapitemsaveddata != null) { - p_115079_.mulPose(Axis.ZP.rotationDegrees(180.0F)); - float f = 0.0078125F; - p_115079_.scale(0.0078125F, 0.0078125F, 0.0078125F); - p_115079_.translate(-64.0F, -64.0F, 0.0F); -- MapItemSavedData mapitemsaveddata = MapItem.getSavedData(optionalint.getAsInt(), p_115076_.level()); - p_115079_.translate(0.0F, 0.0F, -1.0F); - if (mapitemsaveddata != null) { - int i = this.getLightVal(p_115076_, 15728850, p_115081_); -- Minecraft.getInstance().gameRenderer.getMapRenderer().render(p_115079_, p_115080_, optionalint.getAsInt(), mapitemsaveddata, true, i); -+ Minecraft.getInstance().gameRenderer.getMapRenderer().render(p_115079_, p_115080_, p_115076_.getFramedMapId().getAsInt(), mapitemsaveddata, true, i); + int j = mapid != null ? p_115076_.getRotation() % 4 * 2 : p_115076_.getRotation(); + p_115079_.mulPose(Axis.ZP.rotationDegrees((float)j * 360.0F / 8.0F)); ++ if (!net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderItemInFrame(p_115076_, this, p_115079_, p_115080_, p_115081_)) { + if (mapid != null) { + p_115079_.mulPose(Axis.ZP.rotationDegrees(180.0F)); + float f = 0.0078125F; +@@ -110,6 +_,7 @@ + itemstack, ItemDisplayContext.FIXED, k, OverlayTexture.NO_OVERLAY, p_115079_, p_115080_, p_115076_.level(), p_115076_.getId() + ); } - } else { - int k = this.getLightVal(p_115076_, 15728880, p_115081_); - p_115079_.scale(0.5F, 0.5F, 0.5F); - this.itemRenderer.renderStatic(itemstack, ItemDisplayContext.FIXED, k, OverlayTexture.NO_OVERLAY, p_115079_, p_115080_, p_115076_.level(), p_115076_.getId()); - } -+ } - } ++ } + } - p_115079_.popPose(); -@@ -106,7 +_,7 @@ + p_115079_.popPose(); +@@ -121,7 +_,7 @@ - private ModelResourceLocation getFrameModelResourceLoc(T p_174213_, ItemStack p_174214_) { - boolean flag = p_174213_.getType() == EntityType.GLOW_ITEM_FRAME; -- if (p_174214_.is(Items.FILLED_MAP)) { -+ if (p_174214_.getItem() instanceof MapItem) { - return flag ? GLOW_MAP_FRAME_LOCATION : MAP_FRAME_LOCATION; - } else { - return flag ? GLOW_FRAME_LOCATION : FRAME_LOCATION; + private ModelResourceLocation getFrameModelResourceLoc(T p_174213_, ItemStack p_174214_) { + boolean flag = p_174213_.getType() == EntityType.GLOW_ITEM_FRAME; +- if (p_174214_.is(Items.FILLED_MAP)) { ++ if (p_174214_.getItem() instanceof MapItem) { + return flag ? GLOW_MAP_FRAME_LOCATION : MAP_FRAME_LOCATION; + } else { + return flag ? GLOW_FRAME_LOCATION : FRAME_LOCATION; diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/ItemRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/ItemRenderer.java.patch index 7ff1fe948e..72e3353d43 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/ItemRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/ItemRenderer.java.patch @@ -1,64 +1,63 @@ --- a/net/minecraft/client/renderer/entity/ItemRenderer.java +++ b/net/minecraft/client/renderer/entity/ItemRenderer.java @@ -68,7 +_,7 @@ - public ItemRenderer(Minecraft p_266926_, TextureManager p_266774_, ModelManager p_266850_, ItemColors p_267016_, BlockEntityWithoutLevelRenderer p_267049_) { - this.minecraft = p_266926_; - this.textureManager = p_266774_; -- this.itemModelShaper = new ItemModelShaper(p_266850_); -+ this.itemModelShaper = new net.minecraftforge.client.model.ForgeItemModelShaper(p_266850_); - this.blockEntityRenderer = p_267049_; + public ItemRenderer(Minecraft p_266926_, TextureManager p_266774_, ModelManager p_266850_, ItemColors p_267016_, BlockEntityWithoutLevelRenderer p_267049_) { + this.minecraft = p_266926_; + this.textureManager = p_266774_; +- this.itemModelShaper = new ItemModelShaper(p_266850_); ++ this.itemModelShaper = new net.minecraftforge.client.model.ForgeItemModelShaper(p_266850_);; + this.blockEntityRenderer = p_267049_; - for(Item item : BuiltInRegistries.ITEM) { -@@ -109,7 +_,7 @@ + for (Item item : BuiltInRegistries.ITEM) { +@@ -118,7 +_,7 @@ + } } - } -- p_115151_.getTransforms().getTransform(p_270188_).apply(p_115146_, p_115147_); -+ p_115151_ = net.minecraftforge.client.ForgeHooksClient.handleCameraTransforms(p_115147_, p_115151_, p_270188_, p_115146_); - p_115147_.translate(-0.5F, -0.5F, -0.5F); - if (!p_115151_.isCustomRenderer() && (!p_115144_.is(Items.TRIDENT) || flag)) { - boolean flag1; -@@ -119,8 +_,8 @@ +- p_115151_.getTransforms().getTransform(p_270188_).apply(p_115146_, p_115147_); ++ p_115151_ = p_115151_.applyTransform(p_270188_, p_115147_, p_115146_); + p_115147_.translate(-0.5F, -0.5F, -0.5F); + if (!p_115151_.isCustomRenderer() && (!p_115144_.is(Items.TRIDENT) || flag)) { + boolean flag1; +@@ -129,7 +_,8 @@ + flag1 = true; + } + +- RenderType rendertype = ItemBlockRenderTypes.getRenderType(p_115144_, flag1); ++ for (var model : p_115151_.getRenderPasses(p_115144_, flag1)) { ++ for (var rendertype : model.getRenderTypes(p_115144_, flag1)) { + VertexConsumer vertexconsumer; + if (hasAnimatedTexture(p_115144_) && p_115144_.hasFoil()) { + PoseStack.Pose posestack$pose = p_115147_.last().copy(); +@@ -150,9 +_,11 @@ + vertexconsumer = getFoilBuffer(p_115148_, rendertype, true, p_115144_.hasFoil()); + } + +- this.renderModelLists(p_115151_, p_115144_, p_115149_, p_115150_, p_115147_, vertexconsumer); ++ this.renderModelLists(model, p_115144_, p_115149_, p_115150_, p_115147_, vertexconsumer); ++ } ++ } } else { - flag1 = true; - } -- -- RenderType rendertype = ItemBlockRenderTypes.getRenderType(p_115144_, flag1); -+ for (var model : p_115151_.getRenderPasses(p_115144_, flag1)) { -+ for (var rendertype : model.getRenderTypes(p_115144_, flag1)) { - VertexConsumer vertexconsumer; - if (hasAnimatedTexture(p_115144_) && p_115144_.hasFoil()) { - p_115147_.pushPose(); -@@ -144,9 +_,11 @@ - vertexconsumer = getFoilBuffer(p_115148_, rendertype, true, p_115144_.hasFoil()); +- this.blockEntityRenderer.renderByItem(p_115144_, p_270188_, p_115147_, p_115148_, p_115149_, p_115150_); ++ net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_115144_).getCustomRenderer().renderByItem(p_115144_, p_270188_, p_115147_, p_115148_, p_115149_, p_115150_); } -- this.renderModelLists(p_115151_, p_115144_, p_115149_, p_115150_, p_115147_, vertexconsumer); -+ this.renderModelLists(model, p_115144_, p_115149_, p_115150_, p_115147_, vertexconsumer); -+ } -+ } - } else { -- this.blockEntityRenderer.renderByItem(p_115144_, p_270188_, p_115147_, p_115148_, p_115149_, p_115150_); -+ net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_115144_).getCustomRenderer().renderByItem(p_115144_, p_270188_, p_115147_, p_115148_, p_115149_, p_115150_); - } + p_115147_.popPose(); +@@ -211,7 +_,7 @@ + float f1 = (float)FastColor.ARGB32.red(i) / 255.0F; + float f2 = (float)FastColor.ARGB32.green(i) / 255.0F; + float f3 = (float)FastColor.ARGB32.blue(i) / 255.0F; +- p_115164_.putBulkData(posestack$pose, bakedquad, f1, f2, f3, f, p_115167_, p_115168_); ++ p_115164_.putBulkData(posestack$pose, bakedquad, f1, f2, f3, f, p_115167_, p_115168_, true); + } + } - p_115147_.popPose(); -@@ -194,7 +_,7 @@ - float f = (float)(i >> 16 & 255) / 255.0F; - float f1 = (float)(i >> 8 & 255) / 255.0F; - float f2 = (float)(i & 255) / 255.0F; -- p_115164_.putBulkData(posestack$pose, bakedquad, f, f1, f2, p_115167_, p_115168_); -+ p_115164_.putBulkData(posestack$pose, bakedquad, f, f1, f2, 1.0F, p_115167_, p_115168_, true); - } - - } -@@ -227,5 +_,9 @@ - - public void onResourceManagerReload(ResourceManager p_115105_) { - this.itemModelShaper.rebuildCache(); -+ } +@@ -264,5 +_,9 @@ + @Override + public void onResourceManagerReload(ResourceManager p_115105_) { + this.itemModelShaper.rebuildCache(); ++ } + -+ public BlockEntityWithoutLevelRenderer getBlockEntityRenderer() { -+ return blockEntityRenderer; - } ++ public BlockEntityWithoutLevelRenderer getBlockEntityRenderer() { ++ return blockEntityRenderer; + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch index d1b15436e2..d4ca2fcc5b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch @@ -1,39 +1,38 @@ --- a/net/minecraft/client/renderer/entity/LivingEntityRenderer.java +++ b/net/minecraft/client/renderer/entity/LivingEntityRenderer.java -@@ -50,14 +_,17 @@ - } +@@ -50,14 +_,16 @@ + } - public void render(T p_115308_, float p_115309_, float p_115310_, PoseStack p_115311_, MultiBufferSource p_115312_, int p_115313_) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderLivingEvent.Pre(p_115308_, this, p_115310_, p_115311_, p_115312_, p_115313_))) return; - p_115311_.pushPose(); - this.model.attackTime = this.getAttackAnim(p_115308_, p_115310_); -- this.model.riding = p_115308_.isPassenger(); -+ -+ boolean shouldSit = p_115308_.isPassenger() && (p_115308_.getVehicle() != null && p_115308_.getVehicle().shouldRiderSit()); -+ this.model.riding = shouldSit; - this.model.young = p_115308_.isBaby(); - float f = Mth.rotLerp(p_115310_, p_115308_.yBodyRotO, p_115308_.yBodyRot); - float f1 = Mth.rotLerp(p_115310_, p_115308_.yHeadRotO, p_115308_.yHeadRot); - float f2 = f1 - f; -- if (p_115308_.isPassenger()) { -+ if (shouldSit && p_115308_.getVehicle() instanceof LivingEntity) { - Entity $$14 = p_115308_.getVehicle(); - if ($$14 instanceof LivingEntity) { - LivingEntity livingentity = (LivingEntity)$$14; -@@ -102,7 +_,7 @@ - p_115311_.translate(0.0F, -1.501F, 0.0F); - float f8 = 0.0F; - float f4 = 0.0F; -- if (!p_115308_.isPassenger() && p_115308_.isAlive()) { -+ if (!shouldSit && p_115308_.isAlive()) { - f8 = p_115308_.walkAnimation.speed(p_115310_); - f4 = p_115308_.walkAnimation.position(p_115310_); - if (p_115308_.isBaby()) { -@@ -135,6 +_,7 @@ + public void render(T p_115308_, float p_115309_, float p_115310_, PoseStack p_115311_, MultiBufferSource p_115312_, int p_115313_) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderLivingPre(p_115308_, this, p_115310_, p_115311_, p_115312_, p_115313_)) return; + p_115311_.pushPose(); + this.model.attackTime = this.getAttackAnim(p_115308_, p_115310_); +- this.model.riding = p_115308_.isPassenger(); ++ boolean shouldSit = p_115308_.isPassenger() && (p_115308_.getVehicle() != null && p_115308_.getVehicle().shouldRiderSit()); ++ this.model.riding = shouldSit; + this.model.young = p_115308_.isBaby(); + float f = Mth.rotLerp(p_115310_, p_115308_.yBodyRotO, p_115308_.yBodyRot); + float f1 = Mth.rotLerp(p_115310_, p_115308_.yHeadRotO, p_115308_.yHeadRot); + float f2 = f1 - f; +- if (p_115308_.isPassenger() && p_115308_.getVehicle() instanceof LivingEntity livingentity) { ++ if (shouldSit && p_115308_.getVehicle() instanceof LivingEntity livingentity) { + f = Mth.rotLerp(p_115310_, livingentity.yBodyRotO, livingentity.yBodyRot); + f2 = f1 - f; + float f7 = Mth.wrapDegrees(f2); +@@ -101,7 +_,7 @@ + p_115311_.translate(0.0F, -1.501F, 0.0F); + float f4 = 0.0F; + float f5 = 0.0F; +- if (!p_115308_.isPassenger() && p_115308_.isAlive()) { ++ if (!shouldSit && p_115308_.isAlive()) { + f4 = p_115308_.walkAnimation.speed(p_115310_); + f5 = p_115308_.walkAnimation.position(p_115310_); + if (p_115308_.isBaby()) { +@@ -134,6 +_,7 @@ - p_115311_.popPose(); - super.render(p_115308_, p_115309_, p_115310_, p_115311_, p_115312_, p_115313_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderLivingEvent.Post(p_115308_, this, p_115310_, p_115311_, p_115312_, p_115313_)); - } + p_115311_.popPose(); + super.render(p_115308_, p_115309_, p_115310_, p_115311_, p_115312_, p_115313_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderLivingPost(p_115308_, this, p_115310_, p_115311_, p_115312_, p_115313_); + } - @Nullable + @Nullable diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/layers/ElytraLayer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/layers/ElytraLayer.java.patch index 0207ddb363..45baa9ea04 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/ElytraLayer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/layers/ElytraLayer.java.patch @@ -1,55 +1,55 @@ --- a/net/minecraft/client/renderer/entity/layers/ElytraLayer.java +++ b/net/minecraft/client/renderer/entity/layers/ElytraLayer.java -@@ -34,7 +_,7 @@ - - public void render(PoseStack p_116951_, MultiBufferSource p_116952_, int p_116953_, T p_116954_, float p_116955_, float p_116956_, float p_116957_, float p_116958_, float p_116959_, float p_116960_) { - ItemStack itemstack = p_116954_.getItemBySlot(EquipmentSlot.CHEST); -- if (itemstack.is(Items.ELYTRA)) { -+ if (shouldRender(itemstack, p_116954_)) { - ResourceLocation resourcelocation; - if (p_116954_ instanceof AbstractClientPlayer) { - AbstractClientPlayer abstractclientplayer = (AbstractClientPlayer)p_116954_; -@@ -44,10 +_,10 @@ - } else if (playerskin.capeTexture() != null && abstractclientplayer.isModelPartShown(PlayerModelPart.CAPE)) { - resourcelocation = playerskin.capeTexture(); +@@ -45,7 +_,7 @@ + float p_116960_ + ) { + ItemStack itemstack = p_116954_.getItemBySlot(EquipmentSlot.CHEST); +- if (itemstack.is(Items.ELYTRA)) { ++ if (shouldRender(itemstack, p_116954_)) { + ResourceLocation resourcelocation; + if (p_116954_ instanceof AbstractClientPlayer abstractclientplayer) { + PlayerSkin playerskin = abstractclientplayer.getSkin(); +@@ -54,10 +_,10 @@ + } else if (playerskin.capeTexture() != null && abstractclientplayer.isModelPartShown(PlayerModelPart.CAPE)) { + resourcelocation = playerskin.capeTexture(); + } else { +- resourcelocation = WINGS_LOCATION; ++ resourcelocation = getElytraTexture(itemstack, p_116954_); + } } else { -- resourcelocation = WINGS_LOCATION; -+ resourcelocation = getElytraTexture(itemstack, p_116954_); +- resourcelocation = WINGS_LOCATION; ++ resourcelocation = getElytraTexture(itemstack, p_116954_); } - } else { -- resourcelocation = WINGS_LOCATION; -+ resourcelocation = getElytraTexture(itemstack, p_116954_); - } - p_116951_.pushPose(); -@@ -58,5 +_,30 @@ - this.elytraModel.renderToBuffer(p_116951_, vertexconsumer, p_116953_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F); - p_116951_.popPose(); - } -+ } + p_116951_.pushPose(); +@@ -68,5 +_,30 @@ + this.elytraModel.renderToBuffer(p_116951_, vertexconsumer, p_116953_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F); + p_116951_.popPose(); + } ++ } + -+ /** -+ * Determines if the ElytraLayer should render. -+ * ItemStack and Entity are provided for modder convenience, -+ * For example, using the same ElytraLayer for multiple custom Elytra. -+ * -+ * @param stack The Elytra ItemStack -+ * @param entity The entity being rendered. -+ * @return If the ElytraLayer should render. -+ */ -+ public boolean shouldRender(ItemStack stack, T entity) { -+ return stack.getItem() == Items.ELYTRA; -+ } ++ /** ++ * Determines if the ElytraLayer should render. ++ * ItemStack and Entity are provided for modder convenience, ++ * For example, using the same ElytraLayer for multiple custom Elytra. ++ * ++ * @param stack The Elytra ItemStack ++ * @param entity The entity being rendered. ++ * @return If the ElytraLayer should render. ++ */ ++ public boolean shouldRender(ItemStack stack, T entity) { ++ return stack.getItem() == Items.ELYTRA; ++ } + -+ /** -+ * Gets the texture to use with this ElytraLayer. -+ * This assumes the vanilla Elytra model. -+ * -+ * @param stack The Elytra ItemStack. -+ * @param entity The entity being rendered. -+ * @return The texture. -+ */ -+ public ResourceLocation getElytraTexture(ItemStack stack, T entity) { -+ return WINGS_LOCATION; - } ++ /** ++ * Gets the texture to use with this ElytraLayer. ++ * This assumes the vanilla Elytra model. ++ * ++ * @param stack The Elytra ItemStack. ++ * @param entity The entity being rendered. ++ * @return The texture. ++ */ ++ public ResourceLocation getElytraTexture(ItemStack stack, T entity) { ++ return WINGS_LOCATION; + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch deleted file mode 100644 index 697defd646..0000000000 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch +++ /dev/null @@ -1,114 +0,0 @@ ---- a/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java -+++ b/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java -@@ -54,24 +_,24 @@ - if (armoritem.getEquipmentSlot() == p_117122_) { - this.getParentModel().copyPropertiesTo(p_117124_); - this.setPartVisibility(p_117124_, p_117122_); -+ net.minecraft.client.model.Model model = getArmorModelHook(p_117121_, itemstack, p_117122_, p_117124_); - boolean flag = this.usesInnerModel(p_117122_); -- if (armoritem instanceof DyeableArmorItem) { -- DyeableArmorItem dyeablearmoritem = (DyeableArmorItem)armoritem; -- int i = dyeablearmoritem.getColor(itemstack); -+ if (armoritem instanceof net.minecraft.world.item.DyeableLeatherItem) { -+ int i = ((net.minecraft.world.item.DyeableLeatherItem)armoritem).getColor(itemstack); - float f = (float)(i >> 16 & 255) / 255.0F; - float f1 = (float)(i >> 8 & 255) / 255.0F; - float f2 = (float)(i & 255) / 255.0F; -- this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, p_117124_, flag, f, f1, f2, (String)null); -- this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, p_117124_, flag, 1.0F, 1.0F, 1.0F, "overlay"); -+ this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, model, flag, f, f1, f2, this.getArmorResource(p_117121_, itemstack, p_117122_, null)); -+ this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, model, flag, 1.0F, 1.0F, 1.0F, this.getArmorResource(p_117121_, itemstack, p_117122_, "overlay")); - } else { -- this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, p_117124_, flag, 1.0F, 1.0F, 1.0F, (String)null); -+ this.renderModel(p_117119_, p_117120_, p_117123_, armoritem, model, flag, 1.0F, 1.0F, 1.0F, this.getArmorResource(p_117121_, itemstack, p_117122_, null)); - } - - ArmorTrim.getTrim(p_117121_.level().registryAccess(), itemstack, true).ifPresent((p_289638_) -> { -- this.renderTrim(armoritem.getMaterial(), p_117119_, p_117120_, p_117123_, p_289638_, p_117124_, flag); -+ this.renderTrim(armoritem.getMaterial(), p_117119_, p_117120_, p_117123_, p_289638_, model, flag); - }); - if (itemstack.hasFoil()) { -- this.renderGlint(p_117119_, p_117120_, p_117123_, p_117124_); -+ this.renderGlint(p_117119_, p_117120_, p_117123_, model); - } - - } -@@ -103,17 +_,26 @@ - } - - private void renderModel(PoseStack p_289664_, MultiBufferSource p_289689_, int p_289681_, ArmorItem p_289650_, A p_289658_, boolean p_289668_, float p_289678_, float p_289674_, float p_289693_, @Nullable String p_289682_) { -- VertexConsumer vertexconsumer = p_289689_.getBuffer(RenderType.armorCutoutNoCull(this.getArmorLocation(p_289650_, p_289668_, p_289682_))); -+ renderModel(p_289664_, p_289689_, p_289681_, p_289650_, p_289658_, p_289668_, p_289678_, p_289674_, p_289693_, this.getArmorLocation(p_289650_, p_289668_, p_289682_)); -+ } -+ private void renderModel(PoseStack p_289664_, MultiBufferSource p_289689_, int p_289681_, ArmorItem p_289650_, net.minecraft.client.model.Model p_289658_, boolean p_289668_, float p_289678_, float p_289674_, float p_289693_, ResourceLocation armorResource) { -+ VertexConsumer vertexconsumer = p_289689_.getBuffer(RenderType.armorCutoutNoCull(armorResource)); - p_289658_.renderToBuffer(p_289664_, vertexconsumer, p_289681_, OverlayTexture.NO_OVERLAY, p_289678_, p_289674_, p_289693_, 1.0F); - } - - private void renderTrim(ArmorMaterial p_289690_, PoseStack p_289687_, MultiBufferSource p_289643_, int p_289683_, ArmorTrim p_289692_, A p_289663_, boolean p_289651_) { -+ renderTrim(p_289690_, p_289687_, p_289643_, p_289683_, p_289692_, p_289663_, p_289651_); -+ } -+ private void renderTrim(ArmorMaterial p_289690_, PoseStack p_289687_, MultiBufferSource p_289643_, int p_289683_, ArmorTrim p_289692_, net.minecraft.client.model.Model p_289663_, boolean p_289651_) { - TextureAtlasSprite textureatlassprite = this.armorTrimAtlas.getSprite(p_289651_ ? p_289692_.innerTexture(p_289690_) : p_289692_.outerTexture(p_289690_)); - VertexConsumer vertexconsumer = textureatlassprite.wrap(p_289643_.getBuffer(Sheets.armorTrimsSheet(p_289692_.pattern().value().decal()))); - p_289663_.renderToBuffer(p_289687_, vertexconsumer, p_289683_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F); - } - - private void renderGlint(PoseStack p_289673_, MultiBufferSource p_289654_, int p_289649_, A p_289659_) { -+ renderGlint(p_289673_, p_289654_, p_289649_, p_289659_); -+ } -+ private void renderGlint(PoseStack p_289673_, MultiBufferSource p_289654_, int p_289649_, net.minecraft.client.model.Model p_289659_) { - p_289659_.renderToBuffer(p_289673_, p_289654_.getBuffer(RenderType.armorEntityGlint()), p_289649_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F); - } - -@@ -125,8 +_,50 @@ - return p_117129_ == EquipmentSlot.LEGS; - } - -+ @Deprecated //Use the more sensitive version getArmorResource below - private ResourceLocation getArmorLocation(ArmorItem p_117081_, boolean p_117082_, @Nullable String p_117083_) { - String s = "textures/models/armor/" + p_117081_.getMaterial().getName() + "_layer_" + (p_117082_ ? 2 : 1) + (p_117083_ == null ? "" : "_" + p_117083_) + ".png"; - return ARMOR_LOCATION_CACHE.computeIfAbsent(s, ResourceLocation::new); - } -+ -+ /*=================================== FORGE START =========================================*/ -+ -+ /** -+ * Hook to allow item-sensitive armor model. for HumanoidArmorLayer. -+ */ -+ protected net.minecraft.client.model.Model getArmorModelHook(T entity, ItemStack itemStack, EquipmentSlot slot, A model) { -+ return net.minecraftforge.client.ForgeHooksClient.getArmorModel(entity, itemStack, slot, model); -+ } -+ -+ /** -+ * More generic ForgeHook version of the above function, it allows for Items to have more control over what texture they provide. -+ * -+ * @param entity Entity wearing the armor -+ * @param stack ItemStack for the armor -+ * @param slot Slot ID that the item is in -+ * @param type Subtype, can be null or "overlay" -+ * @return ResourceLocation pointing at the armor's texture -+ */ -+ public ResourceLocation getArmorResource(net.minecraft.world.entity.Entity entity, ItemStack stack, EquipmentSlot slot, @Nullable String type) { -+ ArmorItem item = (ArmorItem)stack.getItem(); -+ String texture = item.getMaterial().getName(); -+ String domain = "minecraft"; -+ int idx = texture.indexOf(':'); -+ if (idx != -1) { -+ domain = texture.substring(0, idx); -+ texture = texture.substring(idx + 1); -+ } -+ String s1 = String.format(java.util.Locale.ROOT, "%s:textures/models/armor/%s_layer_%d%s.png", domain, texture, (usesInnerModel(slot) ? 2 : 1), type == null ? "" : String.format(java.util.Locale.ROOT, "_%s", type)); -+ -+ s1 = net.minecraftforge.client.ForgeHooksClient.getArmorTexture(entity, stack, s1, slot, type); -+ ResourceLocation resourcelocation = ARMOR_LOCATION_CACHE.get(s1); -+ -+ if (resourcelocation == null) { -+ resourcelocation = new ResourceLocation(s1); -+ ARMOR_LOCATION_CACHE.put(s1, resourcelocation); -+ } -+ -+ return resourcelocation; -+ } -+ /*=================================== FORGE END ===========================================*/ - } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/player/PlayerRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/player/PlayerRenderer.java.patch index dbdd3f38f2..65cd8bff5e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/player/PlayerRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/player/PlayerRenderer.java.patch @@ -1,49 +1,51 @@ --- a/net/minecraft/client/renderer/entity/player/PlayerRenderer.java +++ b/net/minecraft/client/renderer/entity/player/PlayerRenderer.java -@@ -61,7 +_,9 @@ +@@ -68,7 +_,9 @@ - public void render(AbstractClientPlayer p_117788_, float p_117789_, float p_117790_, PoseStack p_117791_, MultiBufferSource p_117792_, int p_117793_) { - this.setModelProperties(p_117788_); -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderPlayerEvent.Pre(p_117788_, this, p_117790_, p_117791_, p_117792_, p_117793_))) return; - super.render(p_117788_, p_117789_, p_117790_, p_117791_, p_117792_, p_117793_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderPlayerEvent.Post(p_117788_, this, p_117790_, p_117791_, p_117792_, p_117793_)); - } + public void render(AbstractClientPlayer p_117788_, float p_117789_, float p_117790_, PoseStack p_117791_, MultiBufferSource p_117792_, int p_117793_) { + this.setModelProperties(p_117788_); ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderPlayerPre(p_117788_, this, p_117790_, p_117791_, p_117792_, p_117793_)) return; + super.render(p_117788_, p_117789_, p_117790_, p_117791_, p_117792_, p_117793_); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderPlayerPost(p_117788_, this, p_117790_, p_117791_, p_117792_, p_117793_); + } - public Vec3 getRenderOffset(AbstractClientPlayer p_117785_, float p_117786_) { -@@ -134,10 +_,13 @@ - if (useanim == UseAnim.BRUSH) { - return HumanoidModel.ArmPose.BRUSH; + public Vec3 getRenderOffset(AbstractClientPlayer p_117785_, float p_117786_) { +@@ -140,10 +_,15 @@ + if (useanim == UseAnim.BRUSH) { + return HumanoidModel.ArmPose.BRUSH; + } +- } else if (!p_117795_.swinging && itemstack.is(Items.CROSSBOW) && CrossbowItem.isCharged(itemstack)) { ++ } else if (!p_117795_.swinging && itemstack.getItem() instanceof CrossbowItem && CrossbowItem.isCharged(itemstack)) { + return HumanoidModel.ArmPose.CROSSBOW_HOLD; } -- } else if (!p_117795_.swinging && itemstack.is(Items.CROSSBOW) && CrossbowItem.isCharged(itemstack)) { -+ } else if (!p_117795_.swinging && itemstack.getItem() instanceof CrossbowItem && CrossbowItem.isCharged(itemstack)) { - return HumanoidModel.ArmPose.CROSSBOW_HOLD; - } -+ HumanoidModel.ArmPose forgeArmPose = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemstack).getArmPose(p_117795_, p_117796_, itemstack); -+ if (forgeArmPose != null) return forgeArmPose; ++ var forgeArmPose = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemstack).getArmPose(p_117795_, p_117796_, itemstack); ++ if (forgeArmPose != null) { ++ return forgeArmPose; ++ } + - return HumanoidModel.ArmPose.ITEM; - } - } -@@ -170,10 +_,12 @@ - } + return HumanoidModel.ArmPose.ITEM; + } + } +@@ -185,10 +_,12 @@ + } - public void renderRightHand(PoseStack p_117771_, MultiBufferSource p_117772_, int p_117773_, AbstractClientPlayer p_117774_) { -+ if(!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonArm(p_117771_, p_117772_, p_117773_, p_117774_, HumanoidArm.RIGHT)) - this.renderHand(p_117771_, p_117772_, p_117773_, p_117774_, (this.model).rightArm, (this.model).rightSleeve); - } + public void renderRightHand(PoseStack p_117771_, MultiBufferSource p_117772_, int p_117773_, AbstractClientPlayer p_117774_) { ++ if (!net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderArm(p_117771_, p_117772_, p_117773_, p_117774_, HumanoidArm.RIGHT)) + this.renderHand(p_117771_, p_117772_, p_117773_, p_117774_, this.model.rightArm, this.model.rightSleeve); + } - public void renderLeftHand(PoseStack p_117814_, MultiBufferSource p_117815_, int p_117816_, AbstractClientPlayer p_117817_) { -+ if(!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonArm(p_117814_, p_117815_, p_117816_, p_117817_, HumanoidArm.LEFT)) - this.renderHand(p_117814_, p_117815_, p_117816_, p_117817_, (this.model).leftArm, (this.model).leftSleeve); - } + public void renderLeftHand(PoseStack p_117814_, MultiBufferSource p_117815_, int p_117816_, AbstractClientPlayer p_117817_) { ++ if (!net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderArm(p_117814_, p_117815_, p_117816_, p_117817_, HumanoidArm.LEFT)) + this.renderHand(p_117814_, p_117815_, p_117816_, p_117817_, this.model.leftArm, this.model.leftSleeve); + } -@@ -213,7 +_,7 @@ - } - } else if (f > 0.0F) { - super.setupRotations(p_117802_, p_117803_, p_117804_, p_117805_, p_117806_); -- float f4 = p_117802_.isInWater() ? -90.0F - f1 : -90.0F; -+ float f4 = p_117802_.isInWater() || p_117802_.isInFluidType((fluidType, height) -> p_117802_.canSwimInFluidType(fluidType)) ? -90.0F - p_117802_.getXRot() : -90.0F; - float f5 = Mth.lerp(f, 0.0F, f4); - p_117803_.mulPose(Axis.XP.rotationDegrees(f5)); - if (p_117802_.isVisuallySwimming()) { +@@ -230,7 +_,7 @@ + } + } else if (f > 0.0F) { + super.setupRotations(p_117802_, p_117803_, p_117804_, p_117805_, p_117806_, p_335509_); +- float f4 = p_117802_.isInWater() ? -90.0F - f1 : -90.0F; ++ float f4 = p_117802_.isInWater() || p_117802_.isInFluidType((fluidType, height) -> p_117802_.canSwimInFluidType(fluidType)) ? -90.0F - f1 : -90.0F; + float f5 = Mth.lerp(f, 0.0F, f4); + p_117803_.mulPose(Axis.XP.rotationDegrees(f5)); + if (p_117802_.isVisuallySwimming()) { diff --git a/patches/minecraft/net/minecraft/client/renderer/item/ItemProperties.java.patch b/patches/minecraft/net/minecraft/client/renderer/item/ItemProperties.java.patch index 029803054c..a82cbdded7 100644 --- a/patches/minecraft/net/minecraft/client/renderer/item/ItemProperties.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/item/ItemProperties.java.patch @@ -1,22 +1,24 @@ --- a/net/minecraft/client/renderer/item/ItemProperties.java +++ b/net/minecraft/client/renderer/item/ItemProperties.java -@@ -46,6 +_,9 @@ - private static final Map> PROPERTIES = Maps.newHashMap(); +@@ -42,6 +_,10 @@ + private static final Map> PROPERTIES = Maps.newHashMap(); - private static ClampedItemPropertyFunction registerGeneric(ResourceLocation p_174582_, ClampedItemPropertyFunction p_174583_) { -+ return (ClampedItemPropertyFunction) registerGeneric(p_174582_, (ItemPropertyFunction) p_174583_); -+ } -+ public static ItemPropertyFunction registerGeneric(ResourceLocation p_174582_, ItemPropertyFunction p_174583_) { - GENERIC_PROPERTIES.put(p_174582_, p_174583_); - return p_174583_; - } -@@ -55,6 +_,9 @@ - } + private static ClampedItemPropertyFunction registerGeneric(ResourceLocation p_174582_, ClampedItemPropertyFunction p_174583_) { ++ return (ClampedItemPropertyFunction) registerGeneric(p_174582_, (ItemPropertyFunction) p_174583_); ++ } ++ ++ public static ItemPropertyFunction registerGeneric(ResourceLocation p_174582_, ItemPropertyFunction p_174583_) { + GENERIC_PROPERTIES.put(p_174582_, p_174583_); + return p_174583_; + } +@@ -51,6 +_,10 @@ + } + + private static void register(Item p_174571_, ResourceLocation p_174572_, ClampedItemPropertyFunction p_174573_) { ++ register(p_174571_, p_174572_, (ItemPropertyFunction) p_174573_); ++ } ++ ++ public static void register(Item p_174571_, ResourceLocation p_174572_, ItemPropertyFunction p_174573_) { + PROPERTIES.computeIfAbsent(p_174571_, p_117828_ -> Maps.newHashMap()).put(p_174572_, p_174573_); + } - private static void register(Item p_174571_, ResourceLocation p_174572_, ClampedItemPropertyFunction p_174573_) { -+ register(p_174571_, p_174572_, (ItemPropertyFunction) p_174573_); -+ } -+ public static void register(Item p_174571_, ResourceLocation p_174572_, ItemPropertyFunction p_174573_) { - PROPERTIES.computeIfAbsent(p_174571_, (p_117828_) -> { - return Maps.newHashMap(); - }).put(p_174572_, p_174573_); diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/AbstractTexture.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/AbstractTexture.java.patch index 1ed17f189d..bf404ccb0a 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/AbstractTexture.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/AbstractTexture.java.patch @@ -1,23 +1,21 @@ --- a/net/minecraft/client/renderer/texture/AbstractTexture.java +++ b/net/minecraft/client/renderer/texture/AbstractTexture.java -@@ -36,6 +_,20 @@ - GlStateManager._texParameter(3553, 10240, j); - } - -+ // FORGE: This seems to have been stripped out, but we need it -+ private boolean lastBlur; -+ private boolean lastMipmap; +@@ -76,4 +_,18 @@ + @Override + public void close() { + } + -+ public void setBlurMipmap(boolean blur, boolean mipmap) { -+ this.lastBlur = this.blur; -+ this.lastMipmap = this.mipmap; -+ setFilter(blur, mipmap); -+ } ++ // FORGE: This seems to have been stripped out, but we need it ++ private boolean lastBlur; ++ private boolean lastMipmap; + -+ public void restoreLastBlurMipmap() { -+ setFilter(this.lastBlur, this.lastMipmap); -+ } ++ public void setBlurMipmap(boolean blur, boolean mipmap) { ++ this.lastBlur = this.blur; ++ this.lastMipmap = this.mipmap; ++ setFilter(blur, mipmap); ++ } + - public int getId() { - RenderSystem.assertOnRenderThreadOrInit(); - if (this.id == -1) { ++ public void restoreLastBlurMipmap() { ++ setFilter(this.lastBlur, this.lastMipmap); ++ } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch index de04b06562..932d60a8a0 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch @@ -1,27 +1,28 @@ --- a/net/minecraft/client/renderer/texture/MipmapGenerator.java +++ b/net/minecraft/client/renderer/texture/MipmapGenerator.java -@@ -26,12 +_,15 @@ - anativeimage[0] = p_251300_[0]; - boolean flag = hasTransparentPixel(anativeimage[0]); +@@ -25,12 +_,16 @@ + anativeimage[0] = p_251300_[0]; + boolean flag = hasTransparentPixel(anativeimage[0]); -+ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(anativeimage[0].getWidth(), anativeimage[0].getHeight()); - for(int i = 1; i <= p_252326_; ++i) { - if (i < p_251300_.length) { - anativeimage[i] = p_251300_[i]; - } else { - NativeImage nativeimage = anativeimage[i - 1]; -- NativeImage nativeimage1 = new NativeImage(nativeimage.getWidth() >> 1, nativeimage.getHeight() >> 1, false); -+ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes -+ NativeImage nativeimage1 = new NativeImage(Math.max(1, nativeimage.getWidth() >> 1), Math.max(1, nativeimage.getHeight() >> 1), false); -+ if (i <= maxMipmapLevel) { - int j = nativeimage1.getWidth(); - int k = nativeimage1.getHeight(); ++ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(anativeimage[0].getWidth(), anativeimage[0].getHeight()); + for (int i = 1; i <= p_252326_; i++) { + if (i < p_251300_.length) { + anativeimage[i] = p_251300_[i]; + } else { + NativeImage nativeimage = anativeimage[i - 1]; +- NativeImage nativeimage1 = new NativeImage(nativeimage.getWidth() >> 1, nativeimage.getHeight() >> 1, false); ++ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes ++ NativeImage nativeimage1 = new NativeImage(Math.max(1, nativeimage.getWidth() >> 1), Math.max(1, nativeimage.getHeight() >> 1), false); ++ if (i <= maxMipmapLevel) { ++ + int j = nativeimage1.getWidth(); + int k = nativeimage1.getHeight(); -@@ -39,6 +_,7 @@ - for(int i1 = 0; i1 < k; ++i1) { - nativeimage1.setPixelRGBA(l, i1, alphaBlend(nativeimage.getPixelRGBA(l * 2 + 0, i1 * 2 + 0), nativeimage.getPixelRGBA(l * 2 + 1, i1 * 2 + 0), nativeimage.getPixelRGBA(l * 2 + 0, i1 * 2 + 1), nativeimage.getPixelRGBA(l * 2 + 1, i1 * 2 + 1), flag)); - } -+ } - } +@@ -48,6 +_,7 @@ + ) + ); + } ++ } + } - anativeimage[i] = nativeimage1; + anativeimage[i] = nativeimage1; diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteContents.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteContents.java.patch index 74aeb2df00..f32fe2bd1d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteContents.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteContents.java.patch @@ -1,70 +1,70 @@ --- a/net/minecraft/client/renderer/texture/SpriteContents.java +++ b/net/minecraft/client/renderer/texture/SpriteContents.java @@ -34,8 +_,18 @@ - @Nullable - final SpriteContents.AnimatedTexture animatedTexture; - private final ResourceMetadata metadata; -+ @Nullable -+ public final net.minecraftforge.client.textures.ForgeTextureMetadata forgeMeta; + @Nullable + final SpriteContents.AnimatedTexture animatedTexture; + private final ResourceMetadata metadata; ++ @Nullable ++ public final net.minecraftforge.client.textures.ForgeTextureMetadata forgeMeta; -+ /** -+ * @deprecated Forge: Use the {@linkplain SpriteContents#SpriteContents(ResourceLocation, FrameSize, NativeImage, AnimationMetadataSection, net.minecraftforge.client.textures.ForgeTextureMetadata) overload with Forge metadata parameter} to properly forward custom loaders. -+ */ -+ @Deprecated - public SpriteContents(ResourceLocation p_249787_, FrameSize p_251031_, NativeImage p_252131_, ResourceMetadata p_299427_) { -+ this(p_249787_, p_251031_, p_252131_, p_299427_, null); -+ } ++ /** ++ * @deprecated Forge: Use the {@linkplain SpriteContents#SpriteContents(ResourceLocation, FrameSize, NativeImage, AnimationMetadataSection, net.minecraftforge.client.textures.ForgeTextureMetadata) overload with Forge metadata parameter} to properly forward custom loaders. ++ */ ++ @Deprecated + public SpriteContents(ResourceLocation p_249787_, FrameSize p_251031_, NativeImage p_252131_, ResourceMetadata p_299427_) { ++ this(p_249787_, p_251031_, p_252131_, p_299427_, null); ++ } + -+ public SpriteContents(ResourceLocation p_249787_, FrameSize p_251031_, NativeImage p_252131_, ResourceMetadata p_299427_, @Nullable net.minecraftforge.client.textures.ForgeTextureMetadata forgeMeta) { - this.name = p_249787_; - this.width = p_251031_.width(); - this.height = p_251031_.height(); ++ public SpriteContents(ResourceLocation p_249787_, FrameSize p_251031_, NativeImage p_252131_, ResourceMetadata p_299427_, @Nullable net.minecraftforge.client.textures.ForgeTextureMetadata forgeMeta) { + this.name = p_249787_; + this.width = p_251031_.width(); + this.height = p_251031_.height(); @@ -44,6 +_,7 @@ - this.animatedTexture = this.createAnimatedTexture(p_251031_, p_252131_.getWidth(), p_252131_.getHeight(), animationmetadatasection); - this.originalImage = p_252131_; - this.byMipLevel = new NativeImage[]{this.originalImage}; -+ this.forgeMeta = forgeMeta; - } + this.animatedTexture = this.createAnimatedTexture(p_251031_, p_252131_.getWidth(), p_252131_.getHeight(), animationmetadatasection); + this.originalImage = p_252131_; + this.byMipLevel = new NativeImage[]{this.originalImage}; ++ this.forgeMeta = forgeMeta; + } - public void increaseMipLevel(int p_248864_) { -@@ -128,6 +_,9 @@ + public void increaseMipLevel(int p_248864_) { +@@ -120,6 +_,9 @@ - void upload(int p_248895_, int p_250245_, int p_250458_, int p_251337_, NativeImage[] p_248825_) { - for(int i = 0; i < this.byMipLevel.length; ++i) { -+ // Forge: Skip uploading if the texture would be made invalid by mip level -+ if ((this.width >> i) <= 0 || (this.height >> i) <= 0) -+ break; - p_248825_[i].upload(i, p_248895_ >> i, p_250245_ >> i, p_250458_ >> i, p_251337_ >> i, this.width >> i, this.height >> i, this.byMipLevel.length > 1, false); - } + void upload(int p_248895_, int p_250245_, int p_250458_, int p_251337_, NativeImage[] p_248825_) { + for (int i = 0; i < this.byMipLevel.length; i++) { ++ // Forge: Skip uploading if the texture would be made invalid by mip level ++ if ((this.width >> i) <= 0 || (this.height >> i) <= 0) ++ break; + p_248825_[i] + .upload( + i, +@@ -150,6 +_,10 @@ + return this.name; + } -@@ -145,6 +_,10 @@ - return this.name; - } - -+ public NativeImage getOriginalImage() { -+ return this.originalImage; -+ } ++ public NativeImage getOriginalImage() { ++ return this.originalImage; ++ } + - public IntStream getUniqueFrames() { - return this.animatedTexture != null ? this.animatedTexture.getUniqueFrames() : IntStream.of(1); - } -@@ -249,7 +_,8 @@ - for(int i = 0; i < this.activeFrame.length; ++i) { - int j = SpriteContents.this.width >> i; - int k = SpriteContents.this.height >> i; -- this.activeFrame[i] = new NativeImage(j, k, false); -+ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes -+ this.activeFrame[i] = new NativeImage(Math.max(1, j), Math.max(1, k), false); - } + public IntStream getUniqueFrames() { + return this.animatedTexture != null ? this.animatedTexture.getUniqueFrames() : IntStream.of(1); + } +@@ -252,7 +_,8 @@ + for (int i = 0; i < this.activeFrame.length; i++) { + int j = SpriteContents.this.width >> i; + int k = SpriteContents.this.height >> i; +- this.activeFrame[i] = new NativeImage(j, k, false); ++ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes ++ this.activeFrame[i] = new NativeImage(Math.max(1, j), Math.max(1, k), false); + } + } - } -@@ -265,6 +_,9 @@ - for(int k = 0; k < this.activeFrame.length; ++k) { - int l = SpriteContents.this.width >> k; - int i1 = SpriteContents.this.height >> k; -+ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes -+ if (l < 1 || i1 < 1) -+ continue; +@@ -267,6 +_,9 @@ + for (int k = 0; k < this.activeFrame.length; k++) { + int l = SpriteContents.this.width >> k; + int i1 = SpriteContents.this.height >> k; ++ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes ++ if (l < 1 || i1 < 1) ++ continue; - for(int j1 = 0; j1 < i1; ++j1) { - for(int k1 = 0; k1 < l; ++k1) { + for (int j1 = 0; j1 < i1; j1++) { + for (int k1 = 0; k1 < l; k1++) { diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch index 506adde125..4575645387 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch @@ -1,23 +1,29 @@ --- a/net/minecraft/client/renderer/texture/SpriteLoader.java +++ b/net/minecraft/client/renderer/texture/SpriteLoader.java -@@ -67,7 +_,7 @@ - int j1 = Math.min(j, k); - int k1 = Mth.log2(j1); - int l1; -- if (k1 < p_261919_) { -+ if (false) { // Forge: Do not lower the mipmap level - LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, p_261919_, k1, j1); - l1 = k1; - } else { -@@ -133,6 +_,11 @@ - private Map getStitchedSprites(Stitcher p_276117_, int p_276111_, int p_276112_) { - Map map = new HashMap<>(); - p_276117_.gatherSprites((p_251421_, p_250533_, p_251913_) -> { -+ TextureAtlasSprite sprite = net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, p_251421_, p_276111_, p_276112_, p_250533_, p_251913_, p_251421_.byMipLevel.length - 1); -+ if (sprite != null) { -+ map.put(p_251421_.name(), sprite); -+ return; -+ } - map.put(p_251421_.name(), new TextureAtlasSprite(this.location, p_251421_, p_276111_, p_276112_, p_250533_, p_251913_)); - }); - return map; +@@ -74,7 +_,7 @@ + int j1 = Math.min(j, k); + int k1 = Mth.log2(j1); + int l1; +- if (k1 < p_261919_) { ++ if (false) { // Forge: Do not lower the mipmap level + LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, p_261919_, k1, j1); + l1 = k1; + } else { +@@ -138,9 +_,14 @@ + private Map getStitchedSprites(Stitcher p_276117_, int p_276111_, int p_276112_) { + Map map = new HashMap<>(); + p_276117_.gatherSprites( +- (p_251421_, p_250533_, p_251913_) -> map.put( +- p_251421_.name(), new TextureAtlasSprite(this.location, p_251421_, p_276111_, p_276112_, p_250533_, p_251913_) +- ) ++ (p_251421_, p_250533_, p_251913_) -> { ++ TextureAtlasSprite sprite = net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, p_251421_, p_276111_, p_276112_, p_250533_, p_251913_, p_251421_.byMipLevel.length - 1); ++ if (sprite != null) { ++ map.put(p_251421_.name(), sprite); ++ return; ++ } ++ map.put(p_251421_.name(), new TextureAtlasSprite(this.location, p_251421_, p_276111_, p_276112_, p_250533_, p_251913_)); ++ } + ); + return map; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch index cdf38efea1..0f8a47fcdf 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch @@ -1,35 +1,34 @@ --- a/net/minecraft/client/renderer/texture/Stitcher.java +++ b/net/minecraft/client/renderer/texture/Stitcher.java -@@ -12,6 +_,8 @@ +@@ -12,6 +_,7 @@ @OnlyIn(Dist.CLIENT) public class Stitcher { -+ private static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils.getLogger(); -+ - private static final Comparator> HOLDER_COMPARATOR = Comparator., Integer>comparing((p_118201_) -> { - return -p_118201_.height; - }).thenComparing((p_118199_) -> { -@@ -52,6 +_,14 @@ ++ private static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils.getLogger(); + private static final Comparator> HOLDER_COMPARATOR = Comparator., Integer>comparing(p_118201_ -> -p_118201_.height) + .thenComparing(p_118199_ -> -p_118199_.width) + .thenComparing(p_247945_ -> p_247945_.entry.name()); +@@ -48,6 +_,14 @@ - for(Stitcher.Holder holder : list) { - if (!this.addToStorage(holder)) { -+ if (LOGGER.isInfoEnabled()) { -+ StringBuilder sb = new StringBuilder(); -+ sb.append("Unable to fit: ").append(holder.entry().name()); -+ sb.append(" - size: ").append(holder.entry.width()).append("x").append(holder.entry.height()); -+ sb.append(" - Maybe try a lower resolution resourcepack?\n"); -+ list.forEach(h -> sb.append("\t").append(h).append("\n")); -+ LOGGER.info(sb.toString()); -+ } - throw new StitcherException(holder.entry, list.stream().map((p_247946_) -> { - return p_247946_.entry; - }).collect(ImmutableList.toImmutableList())); -@@ -95,7 +_,7 @@ - boolean flag4 = flag2 && j != l; - boolean flag; - if (flag3 ^ flag4) { -- flag = flag3; -+ flag = !flag3 && flag1; // Forge: Fix stitcher not expanding entire height before growing width, and (potentially) growing larger then the max size. - } else { - flag = flag1 && i <= j; - } + for (Stitcher.Holder holder : list) { + if (!this.addToStorage(holder)) { ++ if (LOGGER.isInfoEnabled()) { ++ StringBuilder sb = new StringBuilder(); ++ sb.append("Unable to fit: ").append(holder.entry().name()); ++ sb.append(" - size: ").append(holder.entry.width()).append("x").append(holder.entry.height()); ++ sb.append(" - Maybe try a lower resolution resourcepack?\n"); ++ list.forEach(h -> sb.append("\t").append(h).append("\n")); ++ LOGGER.info(sb.toString()); ++ } + throw new StitcherException(holder.entry, list.stream().map(p_247946_ -> p_247946_.entry).collect(ImmutableList.toImmutableList())); + } + } +@@ -87,7 +_,7 @@ + boolean flag4 = flag2 && j != l; + boolean flag; + if (flag3 ^ flag4) { +- flag = flag3; ++ flag = !flag3 && flag1; // Forge: Fix stitcher not expanding entire height before growing width, and (potentially) growing larger then the max size. + } else { + flag = flag1 && i <= j; + } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch index c47ede24ec..f9412ff740 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch @@ -1,24 +1,21 @@ --- a/net/minecraft/client/renderer/texture/TextureAtlas.java +++ b/net/minecraft/client/renderer/texture/TextureAtlas.java -@@ -88,6 +_,8 @@ - this.sprites = List.copyOf(list); - this.animatedTextures = List.copyOf(list1); - } -+ -+ net.minecraftforge.client.ForgeHooksClient.onTextureStitchedPost(this); - } +@@ -87,6 +_,7 @@ + this.sprites = List.copyOf(list); + this.animatedTextures = List.copyOf(list1); + } ++ net.minecraftforge.client.ForgeHooksClient.onTextureStitchedPost(this); + } - public void dumpContents(ResourceLocation p_276106_, Path p_276127_) throws IOException { -@@ -164,5 +_,12 @@ + @Override +@@ -172,5 +_,10 @@ - public void updateFilter(SpriteLoader.Preparations p_251993_) { - this.setFilter(false, p_251993_.mipLevel() > 0); -+ } + public void updateFilter(SpriteLoader.Preparations p_251993_) { + this.setFilter(false, p_251993_.mipLevel() > 0); ++ } + -+ /** -+ * {@return the set of sprites in this atlas.} -+ */ -+ public java.util.Set getTextureLocations() { -+ return java.util.Collections.unmodifiableSet(texturesByName.keySet()); - } ++ /** {@return the set of sprites in this atlas} */ ++ public java.util.Set getTextureLocations() { ++ return java.util.Collections.unmodifiableSet(texturesByName.keySet()); + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlasSprite.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlasSprite.java.patch index b14e4b6714..36a57d6f9b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlasSprite.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlasSprite.java.patch @@ -1,17 +1,16 @@ --- a/net/minecraft/client/renderer/texture/TextureAtlasSprite.java +++ b/net/minecraft/client/renderer/texture/TextureAtlasSprite.java -@@ -123,4 +_,14 @@ - - void close(); - } +@@ -137,4 +_,13 @@ + @Override + void close(); + } + -+ // Forge Start -+ public int getPixelRGBA(int frameIndex, int x, int y) { -+ if (this.contents.animatedTexture != null) { -+ x += this.contents.animatedTexture.getFrameX(frameIndex) * this.contents.width; -+ y += this.contents.animatedTexture.getFrameY(frameIndex) * this.contents.height; -+ } ++ public int getPixelRGBA(int frameIndex, int x, int y) { ++ if (this.contents.animatedTexture != null) { ++ x += this.contents.animatedTexture.getFrameX(frameIndex) * this.contents.width; ++ y += this.contents.animatedTexture.getFrameY(frameIndex) * this.contents.height; ++ } + -+ return this.contents.getOriginalImage().getPixelRGBA(x, y); -+ } ++ return this.contents.getOriginalImage().getPixelRGBA(x, y); ++ } } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/TextureManager.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/TextureManager.java.patch deleted file mode 100644 index 98cf725840..0000000000 --- a/patches/minecraft/net/minecraft/client/renderer/texture/TextureManager.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/client/renderer/texture/TextureManager.java -+++ b/net/minecraft/client/renderer/texture/TextureManager.java -@@ -167,6 +_,7 @@ - public void release(ResourceLocation p_118514_) { - AbstractTexture abstracttexture = this.byPath.remove(p_118514_); - if (abstracttexture != null) { -+ this.byPath.remove(p_118514_); // Forge: fix MC-98707 - this.safeClose(p_118514_, abstracttexture); - } - diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch index d4545e7be6..edf931e4c5 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch @@ -1,12 +1,11 @@ --- a/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java +++ b/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java -@@ -44,6 +_,9 @@ - AnimationMetadataSection animationmetadatasection = resourcemetadata.getSection(AnimationMetadataSection.SERIALIZER).orElse(AnimationMetadataSection.EMPTY); - FrameSize framesize = animationmetadatasection.calculateFrameSize(nativeimage.getWidth(), nativeimage.getHeight()); - if (Mth.isMultipleOf(nativeimage.getWidth(), framesize.width()) && Mth.isMultipleOf(nativeimage.getHeight(), framesize.height())) { -+ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(p_296303_, p_296304_, framesize, nativeimage, resourcemetadata); -+ if (contents != null) -+ return contents; - return new SpriteContents(p_296303_, framesize, nativeimage, resourcemetadata); - } else { - LOGGER.error("Image {} size {},{} is not multiple of frame size {},{}", p_296303_, nativeimage.getWidth(), nativeimage.getHeight(), framesize.width(), framesize.height()); +@@ -45,6 +_,8 @@ + .orElse(AnimationMetadataSection.EMPTY); + FrameSize framesize = animationmetadatasection.calculateFrameSize(nativeimage.getWidth(), nativeimage.getHeight()); + if (Mth.isMultipleOf(nativeimage.getWidth(), framesize.width()) && Mth.isMultipleOf(nativeimage.getHeight(), framesize.height())) { ++ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(p_296303_, p_296304_, framesize, nativeimage, resourcemetadata); ++ if (contents != null) return contents; + return new SpriteContents(p_296303_, framesize, nativeimage, resourcemetadata); + } else { + LOGGER.error( diff --git a/patches/minecraft/net/minecraft/client/resources/language/ClientLanguage.java.patch b/patches/minecraft/net/minecraft/client/resources/language/ClientLanguage.java.patch index ded3c29e7f..ba0aece560 100644 --- a/patches/minecraft/net/minecraft/client/resources/language/ClientLanguage.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/language/ClientLanguage.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/client/resources/language/ClientLanguage.java +++ b/net/minecraft/client/resources/language/ClientLanguage.java -@@ -74,4 +_,9 @@ - public FormattedCharSequence getVisualOrder(FormattedText p_118925_) { - return FormattedBidiReorder.reorder(p_118925_, this.defaultRightToLeft); - } +@@ -77,4 +_,9 @@ + public FormattedCharSequence getVisualOrder(FormattedText p_118925_) { + return FormattedBidiReorder.reorder(p_118925_, this.defaultRightToLeft); + } + -+ @Override -+ public Map getLanguageData() { -+ return storage; -+ } ++ @Override ++ public Map getLanguageData() { ++ return this.storage; ++ } } diff --git a/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch b/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch index 8e8099441d..591a2bcf23 100644 --- a/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch @@ -2,9 +2,9 @@ +++ b/net/minecraft/client/resources/language/I18n.java @@ -14,6 +_,7 @@ - static void setLanguage(Language p_118942_) { - language = p_118942_; -+ net.minecraftforge.common.ForgeI18n.loadLanguageData(p_118942_.getLanguageData()); - } + static void setLanguage(Language p_118942_) { + language = p_118942_; ++ net.minecraftforge.common.ForgeI18n.loadLanguageData(p_118942_.getLanguageData()); + } - public static String get(String p_118939_, Object... p_118940_) { + public static String get(String p_118939_, Object... p_118940_) { diff --git a/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch b/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch index 3816422d1e..8f255f3d9d 100644 --- a/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/client/resources/language/LanguageManager.java +++ b/net/minecraft/client/resources/language/LanguageManager.java @@ -28,7 +_,7 @@ - private String currentCode; + private String currentCode; - public LanguageManager(String p_118971_) { -- this.currentCode = p_118971_; -+ setSelected(p_118971_); - } + public LanguageManager(String p_118971_) { +- this.currentCode = p_118971_; ++ setSelected(p_118971_); + } - private static Map extractLanguages(Stream p_118982_) { + private static Map extractLanguages(Stream p_118982_) { @@ -65,8 +_,12 @@ - Language.inject(clientlanguage); - } + Language.inject(clientlanguage); + } -+ private java.util.Locale javaLocale; // Forge: add locale information for modders -+ public java.util.Locale getJavaLocale() { return javaLocale; } - public void setSelected(String p_265224_) { - this.currentCode = p_265224_; -+ final String[] langSplit = p_265224_.split("_", 2); -+ this.javaLocale = langSplit.length == 1 ? new java.util.Locale(langSplit[0]) : new java.util.Locale(langSplit[0], langSplit[1]); - } ++ private java.util.Locale javaLocale; // Forge: add locale information for modders ++ public java.util.Locale getJavaLocale() { return javaLocale; } + public void setSelected(String p_265224_) { + this.currentCode = p_265224_; ++ final String[] langSplit = p_265224_.split("_", 2); ++ this.javaLocale = langSplit.length == 1 ? new java.util.Locale(langSplit[0]) : new java.util.Locale(langSplit[0], langSplit[1]); + } - public String getSelected() { + public String getSelected() { diff --git a/patches/minecraft/net/minecraft/client/resources/model/BakedModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/BakedModel.java.patch index 38cc9d9379..66ca18afa9 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/BakedModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/BakedModel.java.patch @@ -6,23 +6,23 @@ @OnlyIn(Dist.CLIENT) -public interface BakedModel { +public interface BakedModel extends net.minecraftforge.client.extensions.IForgeBakedModel { -+ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#getQuads(BlockState, Direction, RandomSource, net.minecraftforge.client.model.data.ModelData, net.minecraft.client.renderer.RenderType)}*/ -+ @Deprecated - List getQuads(@Nullable BlockState p_235039_, @Nullable Direction p_235040_, RandomSource p_235041_); ++ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#getQuads(BlockState, Direction, RandomSource, net.minecraftforge.client.model.data.ModelData, net.minecraft.client.renderer.RenderType)}*/ ++ @Deprecated + List getQuads(@Nullable BlockState p_235039_, @Nullable Direction p_235040_, RandomSource p_235041_); - boolean useAmbientOcclusion(); + boolean useAmbientOcclusion(); @@ -24,9 +_,13 @@ - boolean isCustomRenderer(); + boolean isCustomRenderer(); -+ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#getParticleIcon(net.minecraftforge.client.model.data.ModelData)}*/ -+ @Deprecated - TextureAtlasSprite getParticleIcon(); ++ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#getParticleIcon(net.minecraftforge.client.model.data.ModelData)}*/ ++ @Deprecated + TextureAtlasSprite getParticleIcon(); -- ItemTransforms getTransforms(); -+ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#applyTransform(ItemTransforms.TransformType, com.mojang.blaze3d.vertex.PoseStack, boolean)} instead */ -+ @Deprecated -+ default ItemTransforms getTransforms() { return ItemTransforms.NO_TRANSFORMS; } +- ItemTransforms getTransforms(); ++ /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBakedModel#applyTransform(ItemTransforms.TransformType, com.mojang.blaze3d.vertex.PoseStack, boolean)} instead */ ++ @Deprecated ++ default ItemTransforms getTransforms() { return ItemTransforms.NO_TRANSFORMS; } - ItemOverrides getOverrides(); + ItemOverrides getOverrides(); } diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch index c2883640f8..8653853b3a 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch @@ -6,12 +6,12 @@ @OnlyIn(Dist.CLIENT) -public interface ModelBaker { +public interface ModelBaker extends net.minecraftforge.client.extensions.IForgeModelBaker { - UnbakedModel getModel(ResourceLocation p_252194_); + UnbakedModel getModel(ResourceLocation p_252194_); -+ /** -+ * @deprecated Forge: Use {@link #bake(ResourceLocation, ModelState, java.util.function.Function)} instead. -+ */ -+ @Deprecated - @Nullable - BakedModel bake(ResourceLocation p_250776_, ModelState p_251280_); ++ /** ++ * @deprecated Forge: Use {@link #bake(ResourceLocation, ModelState, java.util.function.Function)} instead. ++ */ ++ @Deprecated + @Nullable + BakedModel bake(ResourceLocation p_250776_, ModelState p_251280_); } diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelBakery.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelBakery.java.patch index 339f438e69..1e84f24f32 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelBakery.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelBakery.java.patch @@ -1,48 +1,47 @@ --- a/net/minecraft/client/resources/model/ModelBakery.java +++ b/net/minecraft/client/resources/model/ModelBakery.java -@@ -153,6 +_,13 @@ - p_252014_.popPush("special"); - this.loadTopLevel(ItemRenderer.TRIDENT_IN_HAND_MODEL); - this.loadTopLevel(ItemRenderer.SPYGLASS_IN_HAND_MODEL); -+ Set additionalModels = Sets.newHashSet(); -+ net.minecraftforge.client.ForgeHooksClient.onRegisterAdditionalModels(additionalModels); -+ for (ResourceLocation rl : additionalModels) { -+ UnbakedModel unbakedmodel = this.getModel(rl); // loadTopLevel(...), but w/o ModelResourceLocation limitation -+ this.unbakedCache.put(rl, unbakedmodel); -+ this.topLevelModels.put(rl, unbakedmodel); -+ } - this.topLevelModels.values().forEach((p_247954_) -> { - p_247954_.resolveParents(this::getModel); - }); -@@ -452,7 +_,17 @@ - return ModelBakery.this.getModel(p_248568_); - } +@@ -161,6 +_,13 @@ + p_252014_.popPush("special"); + this.loadTopLevel(ItemRenderer.TRIDENT_IN_HAND_MODEL); + this.loadTopLevel(ItemRenderer.SPYGLASS_IN_HAND_MODEL); ++ Set additionalModels = Sets.newHashSet(); ++ net.minecraftforge.client.ForgeHooksClient.onRegisterAdditionalModels(additionalModels); ++ for (ResourceLocation rl : additionalModels) { ++ UnbakedModel unbakedmodel = this.getModel(rl); // loadTopLevel(...), but w/o ModelResourceLocation limitation ++ this.unbakedCache.put(rl, unbakedmodel); ++ this.topLevelModels.put(rl, unbakedmodel); ++ } + this.topLevelModels.values().forEach(p_247954_ -> p_247954_.resolveParents(this::getModel)); + p_252014_.pop(); + } +@@ -478,7 +_,17 @@ + } -+ @Override -+ public Function getModelTextureGetter() { -+ return this.modelTextureGetter; -+ } + @Override ++ public Function getModelTextureGetter() { ++ return this.modelTextureGetter; ++ } + - public BakedModel bake(ResourceLocation p_252176_, ModelState p_249765_) { -+ return bake(p_252176_, p_249765_, this.modelTextureGetter); -+ } ++ @Override + public BakedModel bake(ResourceLocation p_252176_, ModelState p_249765_) { ++ return bake(p_252176_, p_249765_, this.modelTextureGetter); ++ } + -+ @Override -+ public BakedModel bake(ResourceLocation p_252176_, ModelState p_249765_, Function sprites) { - ModelBakery.BakedCacheKey modelbakery$bakedcachekey = new ModelBakery.BakedCacheKey(p_252176_, p_249765_.getRotation(), p_249765_.isUvLocked()); - BakedModel bakedmodel = ModelBakery.this.bakedCache.get(modelbakery$bakedcachekey); - if (bakedmodel != null) { -@@ -462,11 +_,11 @@ - if (unbakedmodel instanceof BlockModel) { - BlockModel blockmodel = (BlockModel)unbakedmodel; - if (blockmodel.getRootModel() == ModelBakery.GENERATION_MARKER) { -- return ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(this.modelTextureGetter, blockmodel).bake(this, blockmodel, this.modelTextureGetter, p_249765_, p_252176_, false); -+ return ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(sprites, blockmodel).bake(this, blockmodel, sprites, p_249765_, p_252176_, false); - } ++ @Override ++ public BakedModel bake(ResourceLocation p_252176_, ModelState p_249765_, Function sprites) { + ModelBakery.BakedCacheKey modelbakery$bakedcachekey = new ModelBakery.BakedCacheKey(p_252176_, p_249765_.getRotation(), p_249765_.isUvLocked()); + BakedModel bakedmodel = ModelBakery.this.bakedCache.get(modelbakery$bakedcachekey); + if (bakedmodel != null) { +@@ -486,10 +_,10 @@ + } else { + UnbakedModel unbakedmodel = this.getModel(p_252176_); + if (unbakedmodel instanceof BlockModel blockmodel && blockmodel.getRootModel() == ModelBakery.GENERATION_MARKER) { +- return ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(this.modelTextureGetter, blockmodel).bake(this, blockmodel, this.modelTextureGetter, p_249765_, p_252176_, false); ++ return ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(sprites, blockmodel).bake(this, blockmodel, sprites, p_249765_, p_252176_, false); + } + +- BakedModel bakedmodel1 = unbakedmodel.bake(this, this.modelTextureGetter, p_249765_, p_252176_); ++ BakedModel bakedmodel1 = unbakedmodel.bake(this, sprites, p_249765_, p_252176_); + ModelBakery.this.bakedCache.put(modelbakery$bakedcachekey, bakedmodel1); + return bakedmodel1; } - -- BakedModel bakedmodel1 = unbakedmodel.bake(this, this.modelTextureGetter, p_249765_, p_252176_); -+ BakedModel bakedmodel1 = unbakedmodel.bake(this, sprites, p_249765_, p_252176_); - ModelBakery.this.bakedCache.put(modelbakery$bakedcachekey, bakedmodel1); - return bakedmodel1; - } diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch index 03aa535b18..50d329af99 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch @@ -1,74 +1,74 @@ --- a/net/minecraft/client/resources/model/ModelManager.java +++ b/net/minecraft/client/resources/model/ModelManager.java -@@ -42,13 +_,14 @@ - public class ModelManager implements PreparableReloadListener, AutoCloseable { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final Map VANILLA_ATLASES = Map.of(Sheets.BANNER_SHEET, new ResourceLocation("banner_patterns"), Sheets.BED_SHEET, new ResourceLocation("beds"), Sheets.CHEST_SHEET, new ResourceLocation("chests"), Sheets.SHIELD_SHEET, new ResourceLocation("shield_patterns"), Sheets.SIGN_SHEET, new ResourceLocation("signs"), Sheets.SHULKER_SHEET, new ResourceLocation("shulker_boxes"), Sheets.ARMOR_TRIMS_SHEET, new ResourceLocation("armor_trims"), Sheets.DECORATED_POT_SHEET, new ResourceLocation("decorated_pot"), TextureAtlas.LOCATION_BLOCKS, new ResourceLocation("blocks")); -- private Map bakedRegistry; -+ private Map bakedRegistry = new java.util.HashMap<>(); - private final AtlasSet atlases; - private final BlockModelShaper blockModelShaper; - private final BlockColors blockColors; - private int maxMipmapLevels; - private BakedModel missingModel; - private Object2IntMap modelGroups; -+ private ModelBakery modelBakery; +@@ -63,13 +_,14 @@ + TextureAtlas.LOCATION_BLOCKS, + new ResourceLocation("blocks") + ); +- private Map bakedRegistry; ++ private Map bakedRegistry = new java.util.HashMap<>(); + private final AtlasSet atlases; + private final BlockModelShaper blockModelShaper; + private final BlockColors blockColors; + private int maxMipmapLevels; + private BakedModel missingModel; + private Object2IntMap modelGroups; ++ private ModelBakery modelBakery; - public ModelManager(TextureManager p_119406_, BlockColors p_119407_, int p_119408_) { - this.blockColors = p_119407_; -@@ -57,6 +_,10 @@ - this.atlases = new AtlasSet(VANILLA_ATLASES, p_119406_); - } + public ModelManager(TextureManager p_119406_, BlockColors p_119407_, int p_119408_) { + this.blockColors = p_119407_; +@@ -78,6 +_,10 @@ + this.atlases = new AtlasSet(VANILLA_ATLASES, p_119406_); + } -+ public BakedModel getModel(ResourceLocation modelLocation) { -+ return this.bakedRegistry.getOrDefault(modelLocation, this.missingModel); -+ } ++ public BakedModel getModel(ResourceLocation modelLocation) { ++ return this.bakedRegistry.getOrDefault(modelLocation, this.missingModel); ++ } + - public BakedModel getModel(ModelResourceLocation p_119423_) { - return this.bakedRegistry.getOrDefault(p_119423_, this.missingModel); - } -@@ -71,6 +_,7 @@ + public BakedModel getModel(ModelResourceLocation p_119423_) { + return this.bakedRegistry.getOrDefault(p_119423_, this.missingModel); + } +@@ -100,6 +_,7 @@ + Executor p_249221_ + ) { + p_250336_.startTick(); ++ net.minecraftforge.client.model.geometry.GeometryLoaderManager.init(); + CompletableFuture> completablefuture = loadBlockModels(p_251134_, p_250550_); + CompletableFuture>> completablefuture1 = loadBlockStates(p_251134_, p_250550_); + CompletableFuture completablefuture2 = completablefuture.thenCombineAsync( +@@ -211,6 +_,8 @@ + .collect(Collectors.joining("\n")) + ) + ); ++ p_252136_.popPush("forge_modify_baking_result"); ++ net.minecraftforge.client.ForgeHooksClient.onModifyBakingResult(p_248945_.getBakedTopLevelModels(), p_248945_); + p_252136_.popPush("dispatch"); + Map map = p_248945_.getBakedTopLevelModels(); + BakedModel bakedmodel = map.get(ModelBakery.MISSING_MODEL_LOCATION); +@@ -240,6 +_,8 @@ + this.bakedRegistry = modelbakery.getBakedTopLevelModels(); + this.modelGroups = modelbakery.getModelGroups(); + this.missingModel = p_248996_.missingModel; ++ this.modelBakery = modelbakery; ++ net.minecraftforge.client.ForgeHooksClient.onModelBake(this, this.bakedRegistry, modelbakery); + p_251960_.popPush("cache"); + this.blockModelShaper.replaceCache(p_248996_.modelCache); + p_251960_.pop(); +@@ -265,6 +_,7 @@ + } - public final CompletableFuture reload(PreparableReloadListener.PreparationBarrier p_249079_, ResourceManager p_251134_, ProfilerFiller p_250336_, ProfilerFiller p_252324_, Executor p_250550_, Executor p_249221_) { - p_250336_.startTick(); -+ net.minecraftforge.client.model.geometry.GeometryLoaderManager.init(); - CompletableFuture> completablefuture = loadBlockModels(p_251134_, p_250550_); - CompletableFuture>> completablefuture1 = loadBlockStates(p_251134_, p_250550_); - CompletableFuture completablefuture2 = completablefuture.thenCombineAsync(completablefuture1, (p_251201_, p_251281_) -> { -@@ -164,6 +_,8 @@ - return " " + p_248692_.atlasLocation() + ":" + p_248692_.texture(); - }).collect(Collectors.joining("\n"))); - }); -+ p_252136_.popPush("forge_modify_baking_result"); -+ net.minecraftforge.client.ForgeHooksClient.onModifyBakingResult(p_248945_.getBakedTopLevelModels(), p_248945_); - p_252136_.popPush("dispatch"); - Map map = p_248945_.getBakedTopLevelModels(); - BakedModel bakedmodel = map.get(ModelBakery.MISSING_MODEL_LOCATION); -@@ -193,6 +_,8 @@ - this.bakedRegistry = modelbakery.getBakedTopLevelModels(); - this.modelGroups = modelbakery.getModelGroups(); - this.missingModel = p_248996_.missingModel; -+ this.modelBakery = modelbakery; -+ net.minecraftforge.client.ForgeHooksClient.onModelBake(this, this.bakedRegistry, modelbakery); - p_251960_.popPush("cache"); - this.blockModelShaper.replaceCache(p_248996_.modelCache); - p_251960_.pop(); -@@ -218,6 +_,7 @@ - } + public TextureAtlas getAtlas(ResourceLocation p_119429_) { ++ if (this.atlases == null) throw new RuntimeException("getAtlasTexture called too early!"); + return this.atlases.getAtlas(p_119429_); + } - public TextureAtlas getAtlas(ResourceLocation p_119429_) { -+ if (this.atlases == null) throw new RuntimeException("getAtlasTexture called too early!"); - return this.atlases.getAtlas(p_119429_); - } +@@ -275,6 +_,10 @@ -@@ -227,6 +_,10 @@ - - public void updateMaxMipLevel(int p_119411_) { - this.maxMipmapLevels = p_119411_; -+ } + public void updateMaxMipLevel(int p_119411_) { + this.maxMipmapLevels = p_119411_; ++ } + -+ public ModelBakery getModelBakery() { -+ return com.google.common.base.Preconditions.checkNotNull(modelBakery, "Attempted to query model bakery before it has been initialized."); - } ++ public ModelBakery getModelBakery() { ++ return com.google.common.base.Preconditions.checkNotNull(modelBakery, "Attempted to query model bakery before it has been initialized."); + } - @OnlyIn(Dist.CLIENT) + @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/resources/model/MultiPartBakedModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/MultiPartBakedModel.java.patch index 65753562dc..bcfef0c097 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/MultiPartBakedModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/MultiPartBakedModel.java.patch @@ -6,110 +6,118 @@ @OnlyIn(Dist.CLIENT) -public class MultiPartBakedModel implements BakedModel { +public class MultiPartBakedModel implements net.minecraftforge.client.model.IDynamicBakedModel { - private final List, BakedModel>> selectors; - protected final boolean hasAmbientOcclusion; - protected final boolean isGui3d; + private final List, BakedModel>> selectors; + protected final boolean hasAmbientOcclusion; + protected final boolean isGui3d; @@ -29,10 +_,12 @@ - protected final ItemTransforms transforms; - protected final ItemOverrides overrides; - private final Map selectorCache = new Reference2ObjectOpenHashMap<>(); -+ private final BakedModel defaultModel; + protected final ItemTransforms transforms; + protected final ItemOverrides overrides; + private final Map selectorCache = new Reference2ObjectOpenHashMap<>(); ++ private final BakedModel defaultModel; - public MultiPartBakedModel(List, BakedModel>> p_119462_) { - this.selectors = p_119462_; - BakedModel bakedmodel = p_119462_.iterator().next().getRight(); -+ this.defaultModel = bakedmodel; - this.hasAmbientOcclusion = bakedmodel.useAmbientOcclusion(); - this.isGui3d = bakedmodel.isGui3d(); - this.usesBlockLight = bakedmodel.usesBlockLight(); -@@ -41,10 +_,7 @@ - this.overrides = bakedmodel.getOverrides(); - } + public MultiPartBakedModel(List, BakedModel>> p_119462_) { + this.selectors = p_119462_; + BakedModel bakedmodel = p_119462_.iterator().next().getRight(); ++ this.defaultModel = bakedmodel; + this.hasAmbientOcclusion = bakedmodel.useAmbientOcclusion(); + this.isGui3d = bakedmodel.isGui3d(); + this.usesBlockLight = bakedmodel.usesBlockLight(); +@@ -41,11 +_,7 @@ + this.overrides = bakedmodel.getOverrides(); + } -- public List getQuads(@Nullable BlockState p_235050_, @Nullable Direction p_235051_, RandomSource p_235052_) { -- if (p_235050_ == null) { -- return Collections.emptyList(); -- } else { -+ public BitSet getSelectors(@Nullable BlockState p_235050_) { - BitSet bitset = this.selectorCache.get(p_235050_); - if (bitset == null) { - bitset = new BitSet(); -@@ -58,17 +_,27 @@ +- @Override +- public List getQuads(@Nullable BlockState p_235050_, @Nullable Direction p_235051_, RandomSource p_235052_) { +- if (p_235050_ == null) { +- return Collections.emptyList(); +- } else { ++ public BitSet getSelectors(@Nullable BlockState p_235050_) { + BitSet bitset = this.selectorCache.get(p_235050_); + if (bitset == null) { + bitset = new BitSet(); +@@ -59,17 +_,27 @@ - this.selectorCache.put(p_235050_, bitset); - } -+ return bitset; -+ } - -- List list = Lists.newArrayList(); -+ // FORGE: Implement our overloads (here and below) so child models can have custom logic -+ public List getQuads(@Nullable BlockState p_235050_, @Nullable Direction p_235051_, RandomSource p_235052_, net.minecraftforge.client.model.data.ModelData modelData, @org.jetbrains.annotations.Nullable net.minecraft.client.renderer.RenderType renderType) { -+ if (p_235050_ == null) { -+ return Collections.emptyList(); -+ } else { -+ BitSet bitset = getSelectors(p_235050_); -+ List> list = Lists.newArrayList(); - long k = p_235052_.nextLong(); - - for(int j = 0; j < bitset.length(); ++j) { - if (bitset.get(j)) { -- list.addAll(this.selectors.get(j).getRight().getQuads(p_235050_, p_235051_, RandomSource.create(k))); -+ var model = this.selectors.get(j).getRight(); -+ if (renderType == null || model.getRenderTypes(p_235050_, p_235052_, modelData).contains(renderType)) // FORGE: Only put quad data if the model is using the render type passed -+ list.add(model.getQuads(p_235050_, p_235051_, RandomSource.create(k), net.minecraftforge.client.model.data.MultipartModelData.resolve(modelData, model), renderType)); + this.selectorCache.put(p_235050_, bitset); } - } ++ return bitset; ++ } -- return list; -+ return net.minecraftforge.common.util.ConcatenatedListView.of(list); - } - } +- List list = Lists.newArrayList(); ++ // FORGE: Implement our overloads (here and below) so child models can have custom logic ++ public List getQuads(@Nullable BlockState p_235050_, @Nullable Direction p_235051_, RandomSource p_235052_, net.minecraftforge.client.model.data.ModelData modelData, @Nullable net.minecraft.client.renderer.RenderType renderType) { ++ if (p_235050_ == null) { ++ return Collections.emptyList(); ++ } else { ++ BitSet bitset = getSelectors(p_235050_); ++ List> list = Lists.newArrayList(); + long k = p_235052_.nextLong(); -@@ -76,6 +_,14 @@ - return this.hasAmbientOcclusion; - } + for (int j = 0; j < bitset.length(); j++) { + if (bitset.get(j)) { +- list.addAll(this.selectors.get(j).getRight().getQuads(p_235050_, p_235051_, RandomSource.create(k))); ++ var model = this.selectors.get(j).getRight(); ++ if (renderType == null || model.getRenderTypes(p_235050_, p_235052_, modelData).contains(renderType)) // FORGE: Only put quad data if the model is using the render type passed ++ list.add(model.getQuads(p_235050_, p_235051_, RandomSource.create(k), net.minecraftforge.client.model.data.MultipartModelData.resolve(modelData, model), renderType)); + } + } -+ public boolean useAmbientOcclusion(BlockState state) { -+ return this.defaultModel.useAmbientOcclusion(state); -+ } +- return list; ++ return net.minecraftforge.common.util.ConcatenatedListView.of(list); + } + } + +@@ -79,6 +_,16 @@ + } + + @Override ++ public boolean useAmbientOcclusion(BlockState state) { ++ return this.defaultModel.useAmbientOcclusion(state); ++ } + -+ public boolean useAmbientOcclusion(BlockState state, net.minecraft.client.renderer.RenderType renderType) { -+ return this.defaultModel.useAmbientOcclusion(state, renderType); -+ } ++ @Override ++ public boolean useAmbientOcclusion(BlockState state, net.minecraft.client.renderer.RenderType renderType) { ++ return this.defaultModel.useAmbientOcclusion(state, renderType); ++ } + - public boolean isGui3d() { - return this.isGui3d; - } -@@ -88,12 +_,32 @@ - return false; - } ++ @Override + public boolean isGui3d() { + return this.isGui3d; + } +@@ -94,14 +_,37 @@ + } -+ @Deprecated - public TextureAtlasSprite getParticleIcon() { - return this.particleIcon; - } + @Override ++ @Deprecated + public TextureAtlasSprite getParticleIcon() { + return this.particleIcon; + } -+ public TextureAtlasSprite getParticleIcon(net.minecraftforge.client.model.data.ModelData modelData) { -+ return this.defaultModel.getParticleIcon(modelData); -+ } ++ public TextureAtlasSprite getParticleIcon(net.minecraftforge.client.model.data.ModelData modelData) { ++ return this.defaultModel.getParticleIcon(modelData); ++ } + -+ @Deprecated - public ItemTransforms getTransforms() { - return this.transforms; -+ } + @Override ++ @Deprecated + public ItemTransforms getTransforms() { + return this.transforms; + } + -+ public BakedModel applyTransform(net.minecraft.world.item.ItemDisplayContext transformType, com.mojang.blaze3d.vertex.PoseStack poseStack, boolean applyLeftHandTransform) { -+ return this.defaultModel.applyTransform(transformType, poseStack, applyLeftHandTransform); -+ } ++ public BakedModel applyTransform(net.minecraft.world.item.ItemDisplayContext transformType, com.mojang.blaze3d.vertex.PoseStack poseStack, boolean applyLeftHandTransform) { ++ return this.defaultModel.applyTransform(transformType, poseStack, applyLeftHandTransform); ++ } + -+ @Override // FORGE: Get render types based on the selectors matched by the given block state -+ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(@org.jetbrains.annotations.NotNull BlockState state, @org.jetbrains.annotations.NotNull RandomSource rand, @org.jetbrains.annotations.NotNull net.minecraftforge.client.model.data.ModelData data) { -+ var renderTypeSets = new java.util.LinkedList(); -+ var selectors = getSelectors(state); -+ for (int i = 0; i < selectors.length(); i++) -+ if (selectors.get(i)) -+ renderTypeSets.add(this.selectors.get(i).getRight().getRenderTypes(state, rand, data)); -+ return net.minecraftforge.client.ChunkRenderTypeSet.union(renderTypeSets); - } ++ @Override // FORGE: Get render types based on the selectors matched by the given block state ++ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource rand, net.minecraftforge.client.model.data.ModelData data) { ++ var renderTypeSets = new java.util.LinkedList(); ++ var selectors = getSelectors(state); ++ for (int i = 0; i < selectors.length(); i++) { ++ if (selectors.get(i)) { ++ renderTypeSets.add(this.selectors.get(i).getRight().getRenderTypes(state, rand, data)); ++ } ++ } ++ ++ return net.minecraftforge.client.ChunkRenderTypeSet.union(renderTypeSets); ++ } - public ItemOverrides getOverrides() { + @Override + public ItemOverrides getOverrides() { diff --git a/patches/minecraft/net/minecraft/client/resources/model/SimpleBakedModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/SimpleBakedModel.java.patch index d8b7c27ab9..e417bfbbbb 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/SimpleBakedModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/SimpleBakedModel.java.patch @@ -1,75 +1,84 @@ --- a/net/minecraft/client/resources/model/SimpleBakedModel.java +++ b/net/minecraft/client/resources/model/SimpleBakedModel.java -@@ -26,8 +_,17 @@ - protected final TextureAtlasSprite particleIcon; - protected final ItemTransforms transforms; - protected final ItemOverrides overrides; -+ protected final net.minecraftforge.client.ChunkRenderTypeSet blockRenderTypes; -+ protected final List itemRenderTypes; -+ protected final List fabulousItemRenderTypes; - -+ /** @deprecated Forge: Use {@linkplain #SimpleBakedModel(List, Map, boolean, boolean, boolean, TextureAtlasSprite, ItemTransforms, ItemOverrides, net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/ -+ @Deprecated - public SimpleBakedModel(List p_119489_, Map> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_) { -+ this(p_119489_, p_119490_, p_119491_, p_119492_, p_119493_, p_119494_, p_119495_, p_119496_, net.minecraftforge.client.RenderTypeGroup.EMPTY); -+ } +@@ -26,6 +_,15 @@ + protected final TextureAtlasSprite particleIcon; + protected final ItemTransforms transforms; + protected final ItemOverrides overrides; ++ protected final net.minecraftforge.client.ChunkRenderTypeSet blockRenderTypes; ++ protected final List itemRenderTypes; ++ protected final List fabulousItemRenderTypes; + -+ public SimpleBakedModel(List p_119489_, Map> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_, net.minecraftforge.client.RenderTypeGroup renderTypes) { - this.unculledFaces = p_119489_; - this.culledFaces = p_119490_; - this.hasAmbientOcclusion = p_119491_; -@@ -36,6 +_,9 @@ - this.particleIcon = p_119494_; - this.transforms = p_119495_; - this.overrides = p_119496_; -+ this.blockRenderTypes = !renderTypes.isEmpty() ? net.minecraftforge.client.ChunkRenderTypeSet.of(renderTypes.block()) : null; -+ this.itemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entity()) : null; -+ this.fabulousItemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entityFabulous()) : null; - } ++ /** @deprecated Forge: Use {@linkplain #SimpleBakedModel(List, Map, boolean, boolean, boolean, TextureAtlasSprite, ItemTransforms, ItemOverrides, net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/ ++ @Deprecated ++ public SimpleBakedModel(List p_119489_, Map> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_) { ++ this(p_119489_, p_119490_, p_119491_, p_119492_, p_119493_, p_119494_, p_119495_, p_119496_, net.minecraftforge.client.RenderTypeGroup.EMPTY); ++ } - public List getQuads(@Nullable BlockState p_235054_, @Nullable Direction p_235055_, RandomSource p_235056_) { -@@ -70,6 +_,25 @@ - return this.overrides; - } + public SimpleBakedModel( + List p_119489_, +@@ -35,7 +_,8 @@ + boolean p_119493_, + TextureAtlasSprite p_119494_, + ItemTransforms p_119495_, +- ItemOverrides p_119496_ ++ ItemOverrides p_119496_, ++ net.minecraftforge.client.RenderTypeGroup renderTypes + ) { + this.unculledFaces = p_119489_; + this.culledFaces = p_119490_; +@@ -45,6 +_,9 @@ + this.particleIcon = p_119494_; + this.transforms = p_119495_; + this.overrides = p_119496_; ++ this.blockRenderTypes = !renderTypes.isEmpty() ? net.minecraftforge.client.ChunkRenderTypeSet.of(renderTypes.block()) : null; ++ this.itemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entity()) : null; ++ this.fabulousItemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entityFabulous()) : null; + } -+ @Override -+ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(@org.jetbrains.annotations.NotNull BlockState state, @org.jetbrains.annotations.NotNull RandomSource rand, @org.jetbrains.annotations.NotNull net.minecraftforge.client.model.data.ModelData data) { -+ if (blockRenderTypes != null) -+ return blockRenderTypes; -+ return BakedModel.super.getRenderTypes(state, rand, data); -+ } -+ -+ @Override -+ public List getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) { -+ if (!fabulous) { -+ if (itemRenderTypes != null) -+ return itemRenderTypes; -+ } else { -+ if (fabulousItemRenderTypes != null) -+ return fabulousItemRenderTypes; -+ } -+ return BakedModel.super.getRenderTypes(itemStack, fabulous); -+ } -+ - @OnlyIn(Dist.CLIENT) - public static class Builder { - private final List unculledFaces = Lists.newArrayList(); -@@ -116,11 +_,17 @@ - return this; - } + @Override +@@ -87,6 +_,25 @@ + return this.overrides; + } -+ /** @deprecated Forge: Use {@linkplain #build(net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/ -+ @Deprecated - public BakedModel build() { -+ return build(net.minecraftforge.client.RenderTypeGroup.EMPTY); -+ } ++ @Override ++ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource rand, net.minecraftforge.client.model.data.ModelData data) { ++ return blockRenderTypes != null ? blockRenderTypes : BakedModel.super.getRenderTypes(state, rand, data); ++ } + -+ public BakedModel build(net.minecraftforge.client.RenderTypeGroup renderTypes) { - if (this.particleIcon == null) { - throw new RuntimeException("Missing particle!"); - } else { -- return new SimpleBakedModel(this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides); -+ return new SimpleBakedModel(this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides, renderTypes); - } - } - } ++ @Override ++ public List getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) { ++ if (!fabulous) { ++ if (itemRenderTypes != null) { ++ return itemRenderTypes; ++ } ++ } else { ++ if (fabulousItemRenderTypes != null) { ++ return fabulousItemRenderTypes; ++ } ++ } ++ return BakedModel.super.getRenderTypes(itemStack, fabulous); ++ } ++ + @OnlyIn(Dist.CLIENT) + public static class Builder { + private final List unculledFaces = Lists.newArrayList(); +@@ -133,12 +_,18 @@ + return this; + } + ++ private net.minecraftforge.client.RenderTypeGroup renderTypes = net.minecraftforge.client.RenderTypeGroup.EMPTY; ++ public SimpleBakedModel.Builder renderTypes(net.minecraftforge.client.RenderTypeGroup renderTypes) { ++ this.renderTypes = renderTypes; ++ return this; ++ } ++ + public BakedModel build() { + if (this.particleIcon == null) { + throw new RuntimeException("Missing particle!"); + } else { + return new SimpleBakedModel( +- this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides ++ this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides, this.renderTypes + ); + } + } diff --git a/patches/minecraft/net/minecraft/client/resources/model/WeightedBakedModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/WeightedBakedModel.java.patch index bb1180e473..1b90ce2d34 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/WeightedBakedModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/WeightedBakedModel.java.patch @@ -6,60 +6,62 @@ @OnlyIn(Dist.CLIENT) -public class WeightedBakedModel implements BakedModel { +public class WeightedBakedModel implements net.minecraftforge.client.model.IDynamicBakedModel { - private final int totalWeight; - private final List> list; - private final BakedModel wrapped; -@@ -28,9 +_,10 @@ - this.wrapped = p_119544_.get(0).getData(); - } + private final int totalWeight; + private final List> list; + private final BakedModel wrapped; +@@ -28,10 +_,11 @@ + this.wrapped = p_119544_.get(0).data(); + } -- public List getQuads(@Nullable BlockState p_235058_, @Nullable Direction p_235059_, RandomSource p_235060_) { -+ // FORGE: Implement our overloads (here and below) so child models can have custom logic -+ public List getQuads(@Nullable BlockState p_235058_, @Nullable Direction p_235059_, RandomSource p_235060_, net.minecraftforge.client.model.data.ModelData modelData, @org.jetbrains.annotations.Nullable net.minecraft.client.renderer.RenderType renderType) { - return WeightedRandom.getWeightedItem(this.list, Math.abs((int)p_235060_.nextLong()) % this.totalWeight).map((p_235065_) -> { -- return p_235065_.getData().getQuads(p_235058_, p_235059_, p_235060_); -+ return p_235065_.getData().getQuads(p_235058_, p_235059_, p_235060_, modelData, renderType); - }).orElse(Collections.emptyList()); - } ++ // FORGE: Implement our overloads (here and below) so child models can have custom logic + @Override +- public List getQuads(@Nullable BlockState p_235058_, @Nullable Direction p_235059_, RandomSource p_235060_) { ++ public List getQuads(@Nullable BlockState p_235058_, @Nullable Direction p_235059_, RandomSource p_235060_, net.minecraftforge.client.model.data.ModelData modelData, @Nullable net.minecraft.client.renderer.RenderType renderType) { + return WeightedRandom.getWeightedItem(this.list, Math.abs((int)p_235060_.nextLong()) % this.totalWeight) +- .map(p_325578_ -> p_325578_.data().getQuads(p_235058_, p_235059_, p_235060_)) ++ .map(p_325578_ -> p_325578_.data().getQuads(p_235058_, p_235059_, p_235060_, modelData, renderType)) + .orElse(Collections.emptyList()); + } -@@ -38,6 +_,16 @@ - return this.wrapped.useAmbientOcclusion(); - } +@@ -41,6 +_,16 @@ + } -+ @Override -+ public boolean useAmbientOcclusion(BlockState state) { -+ return this.wrapped.useAmbientOcclusion(state); -+ } + @Override ++ public boolean useAmbientOcclusion(BlockState state) { ++ return this.wrapped.useAmbientOcclusion(state); ++ } + -+ @Override -+ public boolean useAmbientOcclusion(BlockState state, net.minecraft.client.renderer.RenderType renderType) { -+ return this.wrapped.useAmbientOcclusion(state, renderType); -+ } ++ @Override ++ public boolean useAmbientOcclusion(BlockState state, net.minecraft.client.renderer.RenderType renderType) { ++ return this.wrapped.useAmbientOcclusion(state, renderType); ++ } + - public boolean isGui3d() { - return this.wrapped.isGui3d(); - } -@@ -54,8 +_,23 @@ - return this.wrapped.getParticleIcon(); - } ++ @Override + public boolean isGui3d() { + return this.wrapped.isGui3d(); + } +@@ -61,8 +_,24 @@ + } -+ public TextureAtlasSprite getParticleIcon(net.minecraftforge.client.model.data.ModelData modelData) { -+ return this.wrapped.getParticleIcon(modelData); -+ } + @Override ++ public TextureAtlasSprite getParticleIcon(net.minecraftforge.client.model.data.ModelData modelData) { ++ return this.wrapped.getParticleIcon(modelData); ++ } + - public ItemTransforms getTransforms() { - return this.wrapped.getTransforms(); -+ } ++ @Override + public ItemTransforms getTransforms() { + return this.wrapped.getTransforms(); ++ } + -+ public BakedModel applyTransform(net.minecraft.world.item.ItemDisplayContext transformType, com.mojang.blaze3d.vertex.PoseStack poseStack, boolean applyLeftHandTransform) { -+ return this.wrapped.applyTransform(transformType, poseStack, applyLeftHandTransform); -+ } ++ public BakedModel applyTransform(net.minecraft.world.item.ItemDisplayContext transformType, com.mojang.blaze3d.vertex.PoseStack poseStack, boolean applyLeftHandTransform) { ++ return this.wrapped.applyTransform(transformType, poseStack, applyLeftHandTransform); ++ } + -+ @Override // FORGE: Get render types based on the active weighted model -+ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(@org.jetbrains.annotations.NotNull BlockState state, @org.jetbrains.annotations.NotNull RandomSource rand, @org.jetbrains.annotations.NotNull net.minecraftforge.client.model.data.ModelData data) { -+ return WeightedRandom.getWeightedItem(this.list, Math.abs((int)rand.nextLong()) % this.totalWeight) -+ .map((p_235065_) -> p_235065_.getData().getRenderTypes(state, rand, data)) -+ .orElse(net.minecraftforge.client.ChunkRenderTypeSet.none()); - } ++ @Override // FORGE: Get render types based on the active weighted model ++ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource rand, net.minecraftforge.client.model.data.ModelData data) { ++ return WeightedRandom.getWeightedItem(this.list, Math.abs((int)rand.nextLong()) % this.totalWeight) ++ .map((p_235065_) -> p_235065_.data().getRenderTypes(state, rand, data)) ++ .orElse(net.minecraftforge.client.ChunkRenderTypeSet.none()); + } - public ItemOverrides getOverrides() { + @Override diff --git a/patches/minecraft/net/minecraft/client/resources/sounds/SoundInstance.java.patch b/patches/minecraft/net/minecraft/client/resources/sounds/SoundInstance.java.patch index 54c60398b6..d1bec80ccd 100644 --- a/patches/minecraft/net/minecraft/client/resources/sounds/SoundInstance.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/sounds/SoundInstance.java.patch @@ -1,13 +1,11 @@ --- a/net/minecraft/client/resources/sounds/SoundInstance.java +++ b/net/minecraft/client/resources/sounds/SoundInstance.java -@@ -55,4 +_,10 @@ - NONE, - LINEAR; - } +@@ -55,4 +_,8 @@ + NONE, + LINEAR; + } + -+ /*================================ FORGE START ================================================*/ -+ -+ default java.util.concurrent.CompletableFuture getStream(net.minecraft.client.sounds.SoundBufferLibrary soundBuffers, Sound sound, boolean looping) { -+ return soundBuffers.getStream(sound.getPath(), looping); -+ } ++ default java.util.concurrent.CompletableFuture getStream(net.minecraft.client.sounds.SoundBufferLibrary soundBuffers, Sound sound, boolean looping) { ++ return soundBuffers.getStream(sound.getPath(), looping); ++ } } diff --git a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch index 5c243c9a4f..bee2687ed3 100644 --- a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch +++ b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/client/server/IntegratedServer.java +++ b/net/minecraft/client/server/IntegratedServer.java -@@ -59,11 +_,12 @@ - this.setPvpAllowed(true); - this.setFlightAllowed(true); - this.initializeKeyPair(); -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; - this.loadLevel(); - GameProfile gameprofile = this.getSingleplayerProfile(); - String s = this.getWorldData().getLevelName(); - this.setMotd(gameprofile != null ? gameprofile.getName() + " - " + s : s); -- return true; -+ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); - } +@@ -72,11 +_,12 @@ + this.setPvpAllowed(true); + this.setFlightAllowed(true); + this.initializeKeyPair(); ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; + this.loadLevel(); + GameProfile gameprofile = this.getSingleplayerProfile(); + String s = this.getWorldData().getLevelName(); + this.setMotd(gameprofile != null ? gameprofile.getName() + " - " + s : s); +- return true; ++ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); + } - public boolean isPaused() { -@@ -200,6 +_,7 @@ - } + @Override +@@ -224,6 +_,7 @@ - public void halt(boolean p_120053_) { -+ if (isRunning()) - this.executeBlocking(() -> { - for(ServerPlayer serverplayer : Lists.newArrayList(this.getPlayerList().getPlayers())) { - if (!serverplayer.getUUID().equals(this.uuid)) { + @Override + public void halt(boolean p_120053_) { ++ if (isRunning()) + this.executeBlocking(() -> { + for (ServerPlayer serverplayer : Lists.newArrayList(this.getPlayerList().getPlayers())) { + if (!serverplayer.getUUID().equals(this.uuid)) { diff --git a/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch b/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch index 03547e186e..37aa0993fb 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch @@ -1,24 +1,23 @@ --- a/net/minecraft/client/server/LanServerDetection.java +++ b/net/minecraft/client/server/LanServerDetection.java @@ -33,7 +_,7 @@ - this.setDaemon(true); - this.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LanServerDetection.LOGGER)); - this.socket = new MulticastSocket(4445); -- this.pingGroup = InetAddress.getByName("224.0.2.60"); -+ this.pingGroup = InetAddress.getByName(LanServerPinger.MULTICAST_GROUP); - this.socket.setSoTimeout(5000); - this.socket.joinGroup(this.pingGroup); - } -@@ -87,7 +_,11 @@ - String s = LanServerPinger.parseMotd(p_120097_); - String s1 = LanServerPinger.parseAddress(p_120097_); - if (s1 != null) { -- s1 = p_120098_.getHostAddress() + ":" + s1; -+ if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) { -+ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1; -+ } else { -+ s1 = p_120098_.getHostAddress() + ":" + s1; -+ } - boolean flag = false; + this.setDaemon(true); + this.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LanServerDetection.LOGGER)); + this.socket = new MulticastSocket(4445); +- this.pingGroup = InetAddress.getByName("224.0.2.60"); ++ this.pingGroup = InetAddress.getByName(LanServerPinger.MULTICAST_GROUP); + this.socket.setSoTimeout(5000); + this.socket.joinGroup(this.pingGroup); + } +@@ -89,6 +_,11 @@ + String s1 = LanServerPinger.parseAddress(p_120097_); + if (s1 != null) { + s1 = p_120098_.getHostAddress() + ":" + s1; ++ if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) { ++ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1; ++ } else { ++ s1 = p_120098_.getHostAddress() + ":" + s1; ++ } + boolean flag = false; - for(LanServer lanserver : this.servers) { + for (LanServer lanserver : this.servers) { diff --git a/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch b/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch index 82817b5dab..6d704d9d41 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/client/server/LanServerPinger.java @@ -13,7 +_,7 @@ public class LanServerPinger extends Thread { - private static final AtomicInteger UNIQUE_THREAD_ID = new AtomicInteger(0); - private static final Logger LOGGER = LogUtils.getLogger(); -- public static final String MULTICAST_GROUP = "224.0.2.60"; -+ public static final String MULTICAST_GROUP = net.minecraftforge.network.DualStackUtils.getMulticastGroup(); - public static final int PING_PORT = 4445; - private static final long PING_INTERVAL = 1500L; - private final String motd; -@@ -36,7 +_,7 @@ + private static final AtomicInteger UNIQUE_THREAD_ID = new AtomicInteger(0); + private static final Logger LOGGER = LogUtils.getLogger(); +- public static final String MULTICAST_GROUP = "224.0.2.60"; ++ public static final String MULTICAST_GROUP = net.minecraftforge.network.DualStackUtils.getMulticastGroup(); + public static final int PING_PORT = 4445; + private static final long PING_INTERVAL = 1500L; + private final String motd; +@@ -37,7 +_,7 @@ - while(!this.isInterrupted() && this.isRunning) { - try { -- InetAddress inetaddress = InetAddress.getByName("224.0.2.60"); -+ InetAddress inetaddress = InetAddress.getByName(MULTICAST_GROUP); - DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length, inetaddress, 4445); - this.socket.send(datagrampacket); - } catch (IOException ioexception) { + while (!this.isInterrupted() && this.isRunning) { + try { +- InetAddress inetaddress = InetAddress.getByName("224.0.2.60"); ++ InetAddress inetaddress = InetAddress.getByName(MULTICAST_GROUP); + DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length, inetaddress, 4445); + this.socket.send(datagrampacket); + } catch (IOException ioexception) { diff --git a/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch b/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch index 48b8ac6c23..cd5868519e 100644 --- a/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch @@ -1,51 +1,53 @@ --- a/net/minecraft/client/sounds/SoundEngine.java +++ b/net/minecraft/client/sounds/SoundEngine.java -@@ -76,6 +_,7 @@ - this.soundManager = p_120236_; - this.options = p_120237_; - this.soundBuffers = new SoundBufferLibrary(p_249332_); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); - } +@@ -79,6 +_,7 @@ + this.soundManager = p_120236_; + this.options = p_120237_; + this.soundBuffers = new SoundBufferLibrary(p_249332_); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); + } - public void reload() { -@@ -93,6 +_,7 @@ + public void reload() { +@@ -96,6 +_,7 @@ - this.destroy(); - this.loadLibrary(); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); - } + this.destroy(); + this.loadLibrary(); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); + } - private synchronized void loadLibrary() { -@@ -331,7 +_,8 @@ + private synchronized void loadLibrary() { +@@ -325,7 +_,8 @@ + + public void play(SoundInstance p_120313_) { + if (this.loaded) { +- if (p_120313_.canPlaySound()) { ++ p_120313_ = net.minecraftforge.client.ForgeHooksClient.playSound(this, p_120313_); ++ if (p_120313_ != null && p_120313_.canPlaySound()) { + WeighedSoundEvents weighedsoundevents = p_120313_.resolve(this.soundManager); + ResourceLocation resourcelocation = p_120313_.getLocation(); + if (weighedsoundevents == null) { +@@ -389,19 +_,22 @@ + p_194488_.setSelfPosition(vec3); + p_194488_.setRelative(flag); + }); ++ SoundInstance soundinstance = p_120313_; + if (!flag2) { + this.soundBuffers + .getCompleteBuffer(sound.getPath()) + .thenAccept(p_194501_ -> channelaccess$channelhandle.execute(p_194495_ -> { + p_194495_.attachStaticBuffer(p_194501_); + p_194495_.play(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlaySoundSource(this, soundinstance, p_194495_); + })); + } else { +- this.soundBuffers +- .getStream(sound.getPath(), flag1) ++ soundinstance ++ .getStream(this.soundBuffers, sound, flag1) + .thenAccept(p_194504_ -> channelaccess$channelhandle.execute(p_194498_ -> { + p_194498_.attachBufferStream(p_194504_); + p_194498_.play(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlayStreamingSource(this, soundinstance, p_194498_); + })); + } - public void play(SoundInstance p_120313_) { - if (this.loaded) { -- if (p_120313_.canPlaySound()) { -+ p_120313_ = net.minecraftforge.client.ForgeHooksClient.playSound(this, p_120313_); -+ if (p_120313_ != null && p_120313_.canPlaySound()) { - WeighedSoundEvents weighedsoundevents = p_120313_.resolve(this.soundManager); - ResourceLocation resourcelocation = p_120313_.getLocation(); - if (weighedsoundevents == null) { -@@ -397,18 +_,21 @@ - p_194488_.setSelfPosition(vec3); - p_194488_.setRelative(flag); - }); -+ final SoundInstance soundinstance = p_120313_; - if (!flag2) { - this.soundBuffers.getCompleteBuffer(sound.getPath()).thenAccept((p_194501_) -> { - channelaccess$channelhandle.execute((p_194495_) -> { - p_194495_.attachStaticBuffer(p_194501_); - p_194495_.play(); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlaySoundSource(this, soundinstance, p_194495_); - }); - }); - } else { -- this.soundBuffers.getStream(sound.getPath(), flag1).thenAccept((p_194504_) -> { -+ soundinstance.getStream(this.soundBuffers, sound, flag1).thenAccept((p_194504_) -> { - channelaccess$channelhandle.execute((p_194498_) -> { - p_194498_.attachBufferStream(p_194504_); - p_194498_.play(); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlayStreamingSource(this, soundinstance, p_194498_); - }); - }); - } diff --git a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch index 6fe46e4262..48afb0d1b4 100644 --- a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch +++ b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch @@ -6,6 +6,6 @@ -public class CommandSourceStack implements ExecutionCommandSource, SharedSuggestionProvider { +public class CommandSourceStack implements ExecutionCommandSource, SharedSuggestionProvider, net.minecraftforge.common.extensions.IForgeCommandSourceStack { - public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player")); - public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity")); - public final CommandSource source; + public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player")); + public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity")); + public final CommandSource source; diff --git a/patches/minecraft/net/minecraft/commands/Commands.java.patch b/patches/minecraft/net/minecraft/commands/Commands.java.patch index 3e64d0d1d9..748dc2f837 100644 --- a/patches/minecraft/net/minecraft/commands/Commands.java.patch +++ b/patches/minecraft/net/minecraft/commands/Commands.java.patch @@ -1,48 +1,49 @@ --- a/net/minecraft/commands/Commands.java +++ b/net/minecraft/commands/Commands.java -@@ -210,7 +_,7 @@ - JfrCommand.register(this.dispatcher); - } +@@ -215,7 +_,7 @@ + JfrCommand.register(this.dispatcher); + } -- if (SharedConstants.IS_RUNNING_IN_IDE) { -+ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { - TestCommand.register(this.dispatcher); - ResetChunksCommand.register(this.dispatcher); - RaidCommand.register(this.dispatcher); -@@ -244,6 +_,7 @@ - if (p_230943_.includeIntegrated) { - PublishCommand.register(this.dispatcher); - } -+ net.minecraftforge.event.ForgeEventFactory.onCommandRegister(this.dispatcher, p_230943_, p_230944_); +- if (SharedConstants.IS_RUNNING_IN_IDE) { ++ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { + TestCommand.register(this.dispatcher); + ResetChunksCommand.register(this.dispatcher); + RaidCommand.register(this.dispatcher, p_230944_); +@@ -250,6 +_,7 @@ + if (p_230943_.includeIntegrated) { + PublishCommand.register(this.dispatcher); + } ++ net.minecraftforge.event.ForgeEventFactory.onCommandRegister(this.dispatcher, p_230943_, p_230944_); - this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer()); - } -@@ -264,9 +_,17 @@ - commandsourcestack.getServer().getProfiler().push(() -> { - return "/" + p_242841_; - }); -- ContextChain contextchain = finishParsing(p_242844_, p_242841_, commandsourcestack); + this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer()); + } +@@ -268,9 +_,18 @@ + public void performCommand(ParseResults p_242844_, String p_242841_) { + CommandSourceStack commandsourcestack = p_242844_.getContext().getSource(); + commandsourcestack.getServer().getProfiler().push(() -> "/" + p_242841_); +- ContextChain contextchain = finishParsing(p_242844_, p_242841_, commandsourcestack); - try { -+ var event = new net.minecraftforge.event.CommandEvent(p_242844_); -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) { -+ if (event.getException() instanceof Exception exception) -+ throw exception; -+ else if (event.getException() != null) -+ com.google.common.base.Throwables.throwIfUnchecked(event.getException()); -+ return; -+ } -+ ContextChain contextchain = finishParsing(event.getParseResults(), p_242841_, commandsourcestack); - if (contextchain != null) { - executeCommandInContext(commandsourcestack, (p_308343_) -> { - ExecutionContext.queueInitialCommandExecution(p_308343_, p_242841_, contextchain, commandsourcestack, CommandResultCallback.EMPTY); -@@ -353,7 +_,8 @@ - Map, CommandNode> map = Maps.newHashMap(); - RootCommandNode rootcommandnode = new RootCommandNode<>(); - map.put(this.dispatcher.getRoot(), rootcommandnode); -- this.fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, p_82096_.createCommandSourceStack(), map); -+ // FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551 -+ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, p_82096_.createCommandSourceStack(), ctx -> 0, suggest -> SuggestionProviders.safelySwap((com.mojang.brigadier.suggestion.SuggestionProvider) (com.mojang.brigadier.suggestion.SuggestionProvider) suggest)); - p_82096_.connection.send(new ClientboundCommandsPacket(rootcommandnode)); - } + try { ++ var event = new net.minecraftforge.event.CommandEvent(p_242844_); ++ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) { ++ if (event.getException() instanceof Exception exception) { ++ throw exception; ++ } else if (event.getException() != null) { ++ com.google.common.base.Throwables.throwIfUnchecked(event.getException()); ++ } ++ return; ++ } ++ ContextChain contextchain = finishParsing(event.getParseResults(), p_242841_, commandsourcestack); + if (contextchain != null) { + executeCommandInContext( + commandsourcestack, +@@ -361,7 +_,8 @@ + Map, CommandNode> map = Maps.newHashMap(); + RootCommandNode rootcommandnode = new RootCommandNode<>(); + map.put(this.dispatcher.getRoot(), rootcommandnode); +- this.fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, p_82096_.createCommandSourceStack(), map); ++ // FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551 ++ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, p_82096_.createCommandSourceStack(), ctx -> 0, suggest -> SuggestionProviders.safelySwap((com.mojang.brigadier.suggestion.SuggestionProvider) (com.mojang.brigadier.suggestion.SuggestionProvider) suggest)); + p_82096_.connection.send(new ClientboundCommandsPacket(rootcommandnode)); + } diff --git a/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch index 65bd8024d5..97e2034756 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/commands/arguments/EntityArgument.java +++ b/net/minecraft/commands/arguments/EntityArgument.java @@ -115,7 +_,7 @@ - if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) { - StringReader stringreader = new StringReader(p_91483_.getInput()); - stringreader.setCursor(p_91483_.getStart()); -- EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, sharedsuggestionprovider.hasPermission(2)); -+ EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider)); + if (p_91482_.getSource() instanceof SharedSuggestionProvider sharedsuggestionprovider) { + StringReader stringreader = new StringReader(p_91483_.getInput()); + stringreader.setCursor(p_91483_.getStart()); +- EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, sharedsuggestionprovider.hasPermission(2)); ++ EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider)); - try { - entityselectorparser.parse(); + try { + entityselectorparser.parse(); diff --git a/patches/minecraft/net/minecraft/commands/arguments/MessageArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/MessageArgument.java.patch index 52a5c9398c..67a8fddd25 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/MessageArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/MessageArgument.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/commands/arguments/MessageArgument.java +++ b/net/minecraft/commands/arguments/MessageArgument.java -@@ -95,7 +_,7 @@ - } +@@ -84,7 +_,7 @@ - Component resolveComponent(CommandSourceStack p_232197_) throws CommandSyntaxException { -- return this.toComponent(p_232197_, p_232197_.hasPermission(2)); -+ return this.toComponent(p_232197_, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_232197_)); - } + public static record Message(String text, MessageArgument.Part[] parts) { + Component resolveComponent(CommandSourceStack p_232197_) throws CommandSyntaxException { +- return this.toComponent(p_232197_, p_232197_.hasPermission(2)); ++ return this.toComponent(p_232197_, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_232197_)); + } - public Component toComponent(CommandSourceStack p_96850_, boolean p_96851_) throws CommandSyntaxException { + public Component toComponent(CommandSourceStack p_96850_, boolean p_96851_) throws CommandSyntaxException { diff --git a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch index 9e9538420b..81e5a4aeb4 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/commands/arguments/ObjectiveArgument.java @@ -31,7 +_,7 @@ - public static Objective getObjective(CommandContext p_101961_, String p_101962_) throws CommandSyntaxException { - String s = p_101961_.getArgument(p_101962_, String.class); -- Scoreboard scoreboard = p_101961_.getSource().getServer().getScoreboard(); -+ Scoreboard scoreboard = p_101961_.getSource().getScoreboard(); - Objective objective = scoreboard.getObjective(s); - if (objective == null) { - throw ERROR_OBJECTIVE_NOT_FOUND.create(s); -@@ -56,7 +_,7 @@ - public CompletableFuture listSuggestions(CommandContext p_101974_, SuggestionsBuilder p_101975_) { - S s = p_101974_.getSource(); - if (s instanceof CommandSourceStack commandsourcestack) { -- return SharedSuggestionProvider.suggest(commandsourcestack.getServer().getScoreboard().getObjectiveNames(), p_101975_); -+ return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), p_101975_); - } else if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) { - return sharedsuggestionprovider.customSuggestion(p_101974_); - } else { + public static Objective getObjective(CommandContext p_101961_, String p_101962_) throws CommandSyntaxException { + String s = p_101961_.getArgument(p_101962_, String.class); +- Scoreboard scoreboard = p_101961_.getSource().getServer().getScoreboard(); ++ Scoreboard scoreboard = p_101961_.getSource().getScoreboard(); + Objective objective = scoreboard.getObjective(s); + if (objective == null) { + throw ERROR_OBJECTIVE_NOT_FOUND.create(s); +@@ -57,7 +_,7 @@ + public CompletableFuture listSuggestions(CommandContext p_101974_, SuggestionsBuilder p_101975_) { + S s = p_101974_.getSource(); + if (s instanceof CommandSourceStack commandsourcestack) { +- return SharedSuggestionProvider.suggest(commandsourcestack.getServer().getScoreboard().getObjectiveNames(), p_101975_); ++ return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), p_101975_); + } else { + return s instanceof SharedSuggestionProvider sharedsuggestionprovider ? sharedsuggestionprovider.customSuggestion(p_101974_) : Suggestions.empty(); + } diff --git a/patches/minecraft/net/minecraft/commands/arguments/ResourceLocationArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/ResourceLocationArgument.java.patch index aa65fb3098..654f6dde16 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/ResourceLocationArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/ResourceLocationArgument.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/commands/arguments/ResourceLocationArgument.java +++ b/net/minecraft/commands/arguments/ResourceLocationArgument.java -@@ -39,7 +_,7 @@ +@@ -27,7 +_,7 @@ - public static AdvancementHolder getAdvancement(CommandContext p_106988_, String p_106989_) throws CommandSyntaxException { - ResourceLocation resourcelocation = getId(p_106988_, p_106989_); -- AdvancementHolder advancementholder = p_106988_.getSource().getServer().getAdvancements().get(resourcelocation); -+ AdvancementHolder advancementholder = p_106988_.getSource().getAdvancement(resourcelocation); - if (advancementholder == null) { - throw ERROR_UNKNOWN_ADVANCEMENT.create(resourcelocation); - } else { -@@ -48,7 +_,7 @@ - } + public static AdvancementHolder getAdvancement(CommandContext p_106988_, String p_106989_) throws CommandSyntaxException { + ResourceLocation resourcelocation = getId(p_106988_, p_106989_); +- AdvancementHolder advancementholder = p_106988_.getSource().getServer().getAdvancements().get(resourcelocation); ++ AdvancementHolder advancementholder = p_106988_.getSource().getAdvancement(resourcelocation); + if (advancementholder == null) { + throw ERROR_UNKNOWN_ADVANCEMENT.create(resourcelocation); + } else { +@@ -36,7 +_,7 @@ + } - public static RecipeHolder getRecipe(CommandContext p_106995_, String p_106996_) throws CommandSyntaxException { -- RecipeManager recipemanager = p_106995_.getSource().getServer().getRecipeManager(); -+ RecipeManager recipemanager = p_106995_.getSource().getRecipeManager(); - ResourceLocation resourcelocation = getId(p_106995_, p_106996_); - return recipemanager.byKey(resourcelocation).orElseThrow(() -> { - return ERROR_UNKNOWN_RECIPE.create(resourcelocation); + public static RecipeHolder getRecipe(CommandContext p_106995_, String p_106996_) throws CommandSyntaxException { +- RecipeManager recipemanager = p_106995_.getSource().getServer().getRecipeManager(); ++ RecipeManager recipemanager = p_106995_.getSource().getRecipeManager(); + ResourceLocation resourcelocation = getId(p_106995_, p_106996_); + return recipemanager.byKey(resourcelocation).orElseThrow(() -> ERROR_UNKNOWN_RECIPE.create(resourcelocation)); + } diff --git a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch index 963f524d10..12a11e1853 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/commands/arguments/TeamArgument.java +++ b/net/minecraft/commands/arguments/TeamArgument.java -@@ -28,7 +_,7 @@ +@@ -26,7 +_,7 @@ - public static PlayerTeam getTeam(CommandContext p_112092_, String p_112093_) throws CommandSyntaxException { - String s = p_112092_.getArgument(p_112093_, String.class); -- Scoreboard scoreboard = p_112092_.getSource().getServer().getScoreboard(); -+ Scoreboard scoreboard = p_112092_.getSource().getScoreboard(); - PlayerTeam playerteam = scoreboard.getPlayerTeam(s); - if (playerteam == null) { - throw ERROR_TEAM_NOT_FOUND.create(s); + public static PlayerTeam getTeam(CommandContext p_112092_, String p_112093_) throws CommandSyntaxException { + String s = p_112092_.getArgument(p_112093_, String.class); +- Scoreboard scoreboard = p_112092_.getSource().getServer().getScoreboard(); ++ Scoreboard scoreboard = p_112092_.getSource().getScoreboard(); + PlayerTeam playerteam = scoreboard.getPlayerTeam(s); + if (playerteam == null) { + throw ERROR_TEAM_NOT_FOUND.create(s); diff --git a/patches/minecraft/net/minecraft/commands/arguments/coordinates/BlockPosArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/coordinates/BlockPosArgument.java.patch index 66ec924de0..11bb52a3e4 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/coordinates/BlockPosArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/coordinates/BlockPosArgument.java.patch @@ -2,13 +2,13 @@ +++ b/net/minecraft/commands/arguments/coordinates/BlockPosArgument.java @@ -36,9 +_,9 @@ - public static BlockPos getLoadedBlockPos(CommandContext p_265283_, ServerLevel p_265219_, String p_265677_) throws CommandSyntaxException { - BlockPos blockpos = getBlockPos(p_265283_, p_265677_); -- if (!p_265219_.hasChunkAt(blockpos)) { -+ if (!p_265283_.getSource().getUnsidedLevel().hasChunkAt(blockpos)) { - throw ERROR_NOT_LOADED.create(); -- } else if (!p_265219_.isInWorldBounds(blockpos)) { -+ } else if (!p_265283_.getSource().getUnsidedLevel().isInWorldBounds(blockpos)) { - throw ERROR_OUT_OF_WORLD.create(); - } else { - return blockpos; + public static BlockPos getLoadedBlockPos(CommandContext p_265283_, ServerLevel p_265219_, String p_265677_) throws CommandSyntaxException { + BlockPos blockpos = getBlockPos(p_265283_, p_265677_); +- if (!p_265219_.hasChunkAt(blockpos)) { ++ if (!p_265283_.getSource().getUnsidedLevel().hasChunkAt(blockpos)) { + throw ERROR_NOT_LOADED.create(); +- } else if (!p_265219_.isInWorldBounds(blockpos)) { ++ } else if (!p_265283_.getSource().getUnsidedLevel().isInWorldBounds(blockpos)) { + throw ERROR_OUT_OF_WORLD.create(); + } else { + return blockpos; diff --git a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelector.java.patch b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelector.java.patch index 382249f135..e0637c19f6 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelector.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelector.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/commands/arguments/selector/EntitySelector.java +++ b/net/minecraft/commands/arguments/selector/EntitySelector.java -@@ -89,7 +_,7 @@ - } +@@ -104,7 +_,7 @@ + } - private void checkPermissions(CommandSourceStack p_121169_) throws CommandSyntaxException { -- if (this.usesSelector && !p_121169_.hasPermission(2)) { -+ if (this.usesSelector && !net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_121169_)) { - throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create(); - } - } + private void checkPermissions(CommandSourceStack p_121169_) throws CommandSyntaxException { +- if (this.usesSelector && !p_121169_.hasPermission(2)) { ++ if (this.usesSelector && !net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_121169_)) { + throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create(); + } + } diff --git a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch index d74ab92e53..bb4713b88d 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch @@ -1,20 +1,22 @@ --- a/net/minecraft/commands/arguments/selector/EntitySelectorParser.java +++ b/net/minecraft/commands/arguments/selector/EntitySelectorParser.java -@@ -459,6 +_,9 @@ - } +@@ -453,6 +_,11 @@ + } - this.reader.skip(); -+ EntitySelector forgeSelector = net.minecraftforge.common.command.EntitySelectorManager.parseSelector(this); -+ if (forgeSelector != null) -+ return forgeSelector; - this.parseSelector(); - } else { - this.parseNameOrUUID(); -@@ -474,6 +_,7 @@ - p_121248_.suggest("@r", Component.translatable("argument.entity.selector.randomPlayer")); - p_121248_.suggest("@s", Component.translatable("argument.entity.selector.self")); - p_121248_.suggest("@e", Component.translatable("argument.entity.selector.allEntities")); -+ net.minecraftforge.common.command.EntitySelectorManager.fillSelectorSuggestions(p_121248_); - } + this.reader.skip(); ++ ++ var forgeSelector = net.minecraftforge.common.command.EntitySelectorManager.parseSelector(this); ++ if (forgeSelector != null) { ++ return forgeSelector; ++ } + this.parseSelector(); + } else { + this.parseNameOrUUID(); +@@ -468,6 +_,7 @@ + p_121248_.suggest("@r", Component.translatable("argument.entity.selector.randomPlayer")); + p_121248_.suggest("@s", Component.translatable("argument.entity.selector.self")); + p_121248_.suggest("@e", Component.translatable("argument.entity.selector.allEntities")); ++ net.minecraftforge.common.command.EntitySelectorManager.fillSelectorSuggestions(p_121248_); + } - private CompletableFuture suggestNameOrSelector(SuggestionsBuilder p_121287_, Consumer p_121288_) { + private CompletableFuture suggestNameOrSelector(SuggestionsBuilder p_121287_, Consumer p_121288_) { diff --git a/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypeInfos.java.patch b/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypeInfos.java.patch index 1abe1043a2..a6129070e1 100644 --- a/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypeInfos.java.patch +++ b/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypeInfos.java.patch @@ -1,40 +1,40 @@ --- a/net/minecraft/commands/synchronization/ArgumentTypeInfos.java +++ b/net/minecraft/commands/synchronization/ArgumentTypeInfos.java -@@ -66,6 +_,20 @@ +@@ -68,6 +_,20 @@ public class ArgumentTypeInfos { - private static final Map, ArgumentTypeInfo> BY_CLASS = Maps.newHashMap(); + private static final Map, ArgumentTypeInfo> BY_CLASS = Maps.newHashMap(); -+ /** -+ * Forge: Use this in conjunction with a -+ * {@link net.minecraftforge.registries.DeferredRegister#register(String, java.util.function.Supplier) DeferredRegister#register(String, Supplier)} -+ * call to both populate the {@code BY_CLASS} map and register the argument type info so it can be used in commands. -+ * -+ * @param infoClass the class type of the argument type info -+ * @param argumentTypeInfo the argument type info instance -+ * @return the provided argument type info instance for chaining -+ */ -+ public static synchronized , T extends ArgumentTypeInfo.Template, I extends ArgumentTypeInfo> I registerByClass(Class infoClass, I argumentTypeInfo) { -+ BY_CLASS.put(infoClass, argumentTypeInfo); -+ return argumentTypeInfo; -+ } ++ /** ++ * Forge: Use this in conjunction with a ++ * {@link net.minecraftforge.registries.DeferredRegister#register(String, java.util.function.Supplier) DeferredRegister#register(String, Supplier)} ++ * call to both populate the {@code BY_CLASS} map and register the argument type info so it can be used in commands. ++ * ++ * @param infoClass the class type of the argument type info ++ * @param argumentTypeInfo the argument type info instance ++ * @return the provided argument type info instance for chaining ++ */ ++ public static synchronized , T extends ArgumentTypeInfo.Template, I extends ArgumentTypeInfo> I registerByClass(Class infoClass, I argumentTypeInfo) { ++ BY_CLASS.put(infoClass, argumentTypeInfo); ++ return argumentTypeInfo; ++ } + - private static , T extends ArgumentTypeInfo.Template> ArgumentTypeInfo register(Registry> p_235387_, String p_235388_, Class p_235389_, ArgumentTypeInfo p_235390_) { - BY_CLASS.put(p_235389_, p_235390_); - return Registry.register(p_235387_, p_235388_, p_235390_); -@@ -121,12 +_,14 @@ - register(p_235385_, "template_mirror", TemplateMirrorArgument.class, SingletonArgumentInfo.contextFree(TemplateMirrorArgument::templateMirror)); - register(p_235385_, "template_rotation", TemplateRotationArgument.class, SingletonArgumentInfo.contextFree(TemplateRotationArgument::templateRotation)); - register(p_235385_, "heightmap", HeightmapTypeArgument.class, SingletonArgumentInfo.contextFree(HeightmapTypeArgument::heightmap)); -- if (SharedConstants.IS_RUNNING_IN_IDE) { -+ // Forge: Register before gametest arguments to provide forge server <-> vanilla client interop and matching int ids -+ var uuidInfo = register(p_235385_, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid)); -+ if (true) { // Forge: Always register gametest arguments to prevent issues when connecting from gametest-enabled client/server to non-gametest-enabled client/server - register(p_235385_, "test_argument", TestFunctionArgument.class, SingletonArgumentInfo.contextFree(TestFunctionArgument::testFunctionArgument)); - register(p_235385_, "test_class", TestClassNameArgument.class, SingletonArgumentInfo.contextFree(TestClassNameArgument::testClassName)); - } + private static , T extends ArgumentTypeInfo.Template> ArgumentTypeInfo register( + Registry> p_235387_, String p_235388_, Class p_235389_, ArgumentTypeInfo p_235390_ + ) { +@@ -131,12 +_,14 @@ + p_235385_, "loot_predicate", ResourceOrIdArgument.LootPredicateArgument.class, SingletonArgumentInfo.contextAware(ResourceOrIdArgument::lootPredicate) + ); + register(p_235385_, "loot_modifier", ResourceOrIdArgument.LootModifierArgument.class, SingletonArgumentInfo.contextAware(ResourceOrIdArgument::lootModifier)); +- if (SharedConstants.IS_RUNNING_IN_IDE) { ++ // Forge: Register before gametest arguments to provide forge server <-> vanilla client interop and matching int ids ++ var uuidInfo = register(p_235385_, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid)); ++ if (true) { // Forge: Always register gametest arguments to prevent issues when connecting from gametest-enabled client/server to non-gametest-enabled client/server + register(p_235385_, "test_argument", TestFunctionArgument.class, SingletonArgumentInfo.contextFree(TestFunctionArgument::testFunctionArgument)); + register(p_235385_, "test_class", TestClassNameArgument.class, SingletonArgumentInfo.contextFree(TestClassNameArgument::testClassName)); + } -- return register(p_235385_, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid)); -+ return uuidInfo; - } +- return register(p_235385_, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid)); ++ return uuidInfo; + } - private static > Class fixClassType(Class p_235396_) { + private static > Class fixClassType(Class p_235396_) { diff --git a/patches/minecraft/net/minecraft/core/DefaultedMappedRegistry.java.patch b/patches/minecraft/net/minecraft/core/DefaultedMappedRegistry.java.patch new file mode 100644 index 0000000000..1a6db17495 --- /dev/null +++ b/patches/minecraft/net/minecraft/core/DefaultedMappedRegistry.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/core/DefaultedMappedRegistry.java ++++ b/net/minecraft/core/DefaultedMappedRegistry.java +@@ -44,7 +_,7 @@ + @Override + public T get(@Nullable ResourceLocation p_260004_) { + T t = super.get(p_260004_); +- return t == null ? this.defaultValue.value() : t; ++ return t == null && this.defaultValue != null ? this.defaultValue.value() : t; // Add null check as it errors out in validation + } + + @Override diff --git a/patches/minecraft/net/minecraft/core/Holder.java.patch b/patches/minecraft/net/minecraft/core/Holder.java.patch index 2c3d5d9119..2a0730b6bd 100644 --- a/patches/minecraft/net/minecraft/core/Holder.java.patch +++ b/patches/minecraft/net/minecraft/core/Holder.java.patch @@ -6,32 +6,32 @@ -public interface Holder { +public interface Holder extends java.util.function.Supplier, net.minecraftforge.registries.tags.IReverseTag { -+ @Override -+ default boolean containsTag(TagKey key) { -+ return this.is(key); -+ } ++ @Override ++ default boolean containsTag(TagKey key) { ++ return this.is(key); ++ } + -+ @Override -+ default Stream> getTagKeys() { -+ return this.tags(); -+ } ++ @Override ++ default Stream> getTagKeys() { ++ return this.tags(); ++ } + -+ @Override -+ default T get() { -+ return this.value(); -+ } ++ @Override ++ default T get() { ++ return this.value(); ++ } + - T value(); + T value(); - boolean isBound(); -@@ -193,6 +_,10 @@ - - public Stream> tags() { - return this.tags.stream(); -+ } + boolean isBound(); +@@ -232,6 +_,10 @@ + @Override + public Stream> tags() { + return this.tags.stream(); ++ } + -+ public Type getType() { -+ return this.type; - } ++ public Type getType() { ++ return this.type; + } - public String toString() { + @Override diff --git a/patches/minecraft/net/minecraft/core/HolderSet.java.patch b/patches/minecraft/net/minecraft/core/HolderSet.java.patch index 31459c244a..955724aa6f 100644 --- a/patches/minecraft/net/minecraft/core/HolderSet.java.patch +++ b/patches/minecraft/net/minecraft/core/HolderSet.java.patch @@ -6,29 +6,27 @@ -public interface HolderSet extends Iterable> { +public interface HolderSet extends Iterable>, net.minecraftforge.common.extensions.IForgeHolderSet { - Stream> stream(); + Stream> stream(); - int size(); -@@ -135,6 +_,9 @@ + int size(); +@@ -174,6 +_,7 @@ - public void bind(List> p_205836_) { - this.contents = List.copyOf(p_205836_); -+ for (Runnable runnable : this.invalidationCallbacks) { -+ runnable.run(); // FORGE: invalidate listeners when tags rebind -+ } - } + public void bind(List> p_205836_) { + this.contents = List.copyOf(p_205836_); ++ this.invalidationCallbacks.forEach(Runnable::run); // FORGE: invalidate listeners when tags rebind + } - public TagKey key() { -@@ -163,6 +_,12 @@ - - public boolean canSerializeIn(HolderOwner p_256542_) { - return this.owner.canSerializeIn(p_256542_); -+ } + public TagKey key() { +@@ -208,6 +_,12 @@ + @Override + public boolean canSerializeIn(HolderOwner p_256542_) { + return this.owner.canSerializeIn(p_256542_); ++ } + -+ // FORGE: Keep a list of invalidation callbacks so they can be run when tags rebind -+ private List invalidationCallbacks = new java.util.ArrayList<>(); -+ public void addInvalidationListener(Runnable runnable) { -+ invalidationCallbacks.add(runnable); - } - } ++ // FORGE: Keep a list of invalidation callbacks so they can be run when tags rebind ++ private List invalidationCallbacks = new java.util.ArrayList<>(); ++ public void addInvalidationListener(Runnable runnable) { ++ invalidationCallbacks.add(runnable); + } + } } diff --git a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch index 08b1e7cb15..0cb2f1385d 100644 --- a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch +++ b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch @@ -1,59 +1,58 @@ --- a/net/minecraft/core/MappedRegistry.java +++ b/net/minecraft/core/MappedRegistry.java -@@ -117,7 +_,16 @@ - } - } +@@ -114,6 +_,7 @@ -+ private static final Set KNOWN = new java.util.LinkedHashSet<>(); -+ public static Set getKnownRegistries() { -+ return java.util.Collections.unmodifiableSet(KNOWN); -+ } -+ protected final void markKnown() { -+ KNOWN.add(key().location()); -+ } -+ - public Holder.Reference registerMapping(int p_256563_, ResourceKey p_256594_, T p_256374_, Lifecycle p_256469_) { -+ markKnown(); - this.validateWrite(p_256594_); - Validate.notNull(p_256594_); - Validate.notNull(p_256374_); -@@ -141,6 +_,8 @@ - reference = this.byKey.computeIfAbsent(p_256594_, (p_258168_) -> { - return Holder.Reference.createStandAlone(this.holderOwner(), p_258168_); - }); -+ // Forge: Bind the value immediately so it can be queried while the registry is not frozen -+ reference.bindValue(p_256374_); - } - - this.byKey.put(p_256594_, reference); -@@ -296,14 +_,17 @@ - return this.byKey.containsKey(p_175392_); - } - -+ /** @deprecated Forge: For internal use only. Use the Register events when registering values. */ -+ @Deprecated -+ public void unfreeze() { -+ this.frozen = false; -+ } -+ - public Registry freeze() { - if (this.frozen) { - return this; - } else { - this.frozen = true; -- this.byValue.forEach((p_247989_, p_247990_) -> { -- p_247990_.bindValue(p_247989_); -- }); - List list = this.byKey.entrySet().stream().filter((p_211055_) -> { - return !p_211055_.getValue().isBound(); - }).map((p_211794_) -> { -@@ -317,7 +_,8 @@ - throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values()); - } - -- this.unregisteredIntrusiveHolders = null; -+ // Forge: We freeze/unfreeze vanilla registries more than once, so we need to keep the unregistered intrusive holders map around. -+ // this.unregisteredIntrusiveHolders = null; - } + @Override + public Holder.Reference register(ResourceKey p_256252_, T p_256591_, RegistrationInfo p_329661_) { ++ markKnown(); + this.validateWrite(p_256252_); + Objects.requireNonNull(p_256252_); + Objects.requireNonNull(p_256591_); +@@ -135,6 +_,8 @@ + reference.bindKey(p_256252_); + } else { + reference = this.byKey.computeIfAbsent(p_256252_, p_258168_ -> Holder.Reference.createStandAlone(this.holderOwner(), (ResourceKey)p_258168_)); ++ // Forge: Bind the value immediately so it can be queried while the registry is not frozen ++ reference.bindValue(p_256591_); + } + this.byKey.put(p_256252_, reference); +@@ -322,7 +_,6 @@ return this; + } else { + this.frozen = true; +- this.byValue.forEach((p_247989_, p_247990_) -> p_247990_.bindValue((T)p_247989_)); + List list = this.byKey + .entrySet() + .stream() +@@ -338,7 +_,8 @@ + throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values()); + } + +- this.unregisteredIntrusiveHolders = null; ++ // Forge: We freeze/unfreeze vanilla registries more than once, so we need to keep the unregistered intrusive holders map around. ++ //this.unregisteredIntrusiveHolders = null; + } + + return this; +@@ -435,5 +_,20 @@ + @Override + public HolderLookup.RegistryLookup asLookup() { + return this.lookup; ++ } ++ ++ private static final Set KNOWN = new java.util.LinkedHashSet<>(); ++ public static Set getKnownRegistries() { ++ return java.util.Collections.unmodifiableSet(KNOWN); ++ } ++ ++ protected final void markKnown() { ++ KNOWN.add(key().location()); ++ } ++ ++ /** @deprecated Forge: For internal use only. Use the Register events when registering values. */ ++ @Deprecated ++ public void unfreeze() { ++ this.frozen = false; + } + } diff --git a/patches/minecraft/net/minecraft/core/RegistryCodecs.java.patch b/patches/minecraft/net/minecraft/core/RegistryCodecs.java.patch deleted file mode 100644 index 0eeb35e427..0000000000 --- a/patches/minecraft/net/minecraft/core/RegistryCodecs.java.patch +++ /dev/null @@ -1,12 +0,0 @@ ---- a/net/minecraft/core/RegistryCodecs.java -+++ b/net/minecraft/core/RegistryCodecs.java -@@ -40,7 +_,8 @@ - } - - public static Codec> fullCodec(ResourceKey> p_248884_, Lifecycle p_251810_, Codec p_250169_) { -- Codec, E>> codec = Codec.unboundedMap(ResourceKey.codec(p_248884_), p_250169_); -+ // FORGE: Fix MC-197860 -+ Codec, E>> codec = new net.minecraftforge.common.LenientUnboundedMapCodec<>(ResourceKey.codec(p_248884_), p_250169_); - return codec.xmap((p_258184_) -> { - WritableRegistry writableregistry = new MappedRegistry<>(p_248884_, p_251810_); - p_258184_.forEach((p_258191_, p_258192_) -> { diff --git a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch index 528937b42b..5ca022f762 100644 --- a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch +++ b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch @@ -1,59 +1,54 @@ --- a/net/minecraft/core/RegistrySetBuilder.java +++ b/net/minecraft/core/RegistrySetBuilder.java -@@ -68,6 +_,10 @@ - return this.add(p_256261_, Lifecycle.stable(), p_256010_); - } +@@ -74,6 +_,10 @@ + return this.add(p_256261_, Lifecycle.stable(), p_256010_); + } -+ public List>> getEntryKeys() { -+ return this.entries.stream().map(RegistrySetBuilder.RegistryStub::key).toList(); -+ } ++ public List>> getEntryKeys() { ++ return this.entries.stream().map(RegistrySetBuilder.RegistryStub::key).toList(); ++ } + - private RegistrySetBuilder.BuildState createState(RegistryAccess p_256400_) { - RegistrySetBuilder.BuildState registrysetbuilder$buildstate = RegistrySetBuilder.BuildState.create(p_256400_, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key)); - this.entries.forEach((p_255629_) -> { -@@ -121,18 +_,21 @@ - }; - map.put(resourcekey, lazyholder); - }); -- HolderLookup.RegistryLookup registrylookup1 = p_313198_.lookupOrThrow(p_313093_); -+ HolderLookup.RegistryLookup registrylookup1 = p_313198_.lookup(p_313093_).orElse(null); -+ Lifecycle lifecycle = registrylookup.registryLifecycle(); -+ if (registrylookup1 != null) { - registrylookup1.listElements().forEach((p_308430_) -> { - ResourceKey resourcekey = p_308430_.key(); - map.computeIfAbsent(resourcekey, (p_308437_) -> { - RegistrySetBuilder.LazyHolder lazyholder = new RegistrySetBuilder.LazyHolder<>(p_312548_, resourcekey); - lazyholder.supplier = () -> { -- return cloner.clone((T)p_308430_.value(), p_313198_, p_311605_.getValue()); -+ return cloner.clone((T) p_308430_.value(), p_313198_, p_311605_.getValue()); - }; - return lazyholder; + private RegistrySetBuilder.BuildState createState(RegistryAccess p_256400_) { + RegistrySetBuilder.BuildState registrysetbuilder$buildstate = RegistrySetBuilder.BuildState.create( + p_256400_, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key) +@@ -180,14 +_,16 @@ + throw new NullPointerException("No cloner for " + p_313093_.location()); + } else { + Map, Holder.Reference> map = new HashMap<>(); +- HolderLookup.RegistryLookup registrylookup = p_311682_.lookupOrThrow(p_313093_); ++ HolderLookup.RegistryLookup registrylookup = p_311682_.lookup(p_313093_).orElse(null); + registrylookup.listElements().forEach(p_308453_ -> { + ResourceKey resourcekey = p_308453_.key(); + RegistrySetBuilder.LazyHolder lazyholder = new RegistrySetBuilder.LazyHolder<>(p_312548_, resourcekey); + lazyholder.supplier = () -> cloner.clone((T)p_308453_.value(), p_311682_, p_311605_.getValue()); + map.put(resourcekey, lazyholder); }); - }); -- Lifecycle lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); -+ lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); -+ } - return lookupFromMap(p_313093_, lifecycle, map); - } - } -@@ -168,7 +_,7 @@ - RegistrySetBuilder.UniversalLookup registrysetbuilder$universallookup = new RegistrySetBuilder.UniversalLookup(registrysetbuilder$compositeowner); - ImmutableMap.Builder> builder = ImmutableMap.builder(); - p_255995_.registries().forEach((p_258197_) -> { -- builder.put(p_258197_.key().location(), RegistrySetBuilder.wrapContextLookup(p_258197_.value().asLookup())); -+ builder.put(p_258197_.key().location(), net.minecraftforge.common.ForgeHooks.wrapRegistryLookup(p_258197_.value().asLookup())); - }); - p_256495_.forEach((p_256603_) -> { - builder.put(p_256603_.location(), registrysetbuilder$universallookup); -@@ -189,6 +_,11 @@ - - public HolderGetter lookup(ResourceKey> p_255961_) { - return (HolderGetter) BuildState.this.registries.getOrDefault(p_255961_.location(), BuildState.this.lookup); +- HolderLookup.RegistryLookup registrylookup1 = p_313198_.lookupOrThrow(p_313093_); ++ HolderLookup.RegistryLookup registrylookup1 = p_313198_.lookup(p_313093_).orElse(null); ++ Lifecycle lifecycle = registrylookup.registryLifecycle(); ++ if (registrylookup1 != null) { + registrylookup1.listElements().forEach(p_308430_ -> { + ResourceKey resourcekey = p_308430_.key(); + map.computeIfAbsent(resourcekey, p_308437_ -> { +@@ -196,7 +_,8 @@ + return lazyholder; + }); + }); +- Lifecycle lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); ++ lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); + } + return lookupFromMap(p_313093_, lifecycle, p_312548_, map); + } + } +@@ -266,6 +_,11 @@ + @Override + public HolderGetter lookup(ResourceKey> p_255961_) { + return (HolderGetter)BuildState.this.registries.getOrDefault(p_255961_.location(), BuildState.this.lookup); ++ } + -+ @Override -+ public Optional> registryLookup(ResourceKey> registry) { -+ return Optional.ofNullable((HolderLookup.RegistryLookup) BuildState.this.registries.get(registry.location())); - } - }; - } ++ @Override ++ public Optional> registryLookup(ResourceKey> registry) { ++ return Optional.ofNullable((HolderLookup.RegistryLookup) BuildState.this.registries.get(registry.location())); + } + }; + } diff --git a/patches/minecraft/net/minecraft/core/RegistrySynchronization.java.patch b/patches/minecraft/net/minecraft/core/RegistrySynchronization.java.patch deleted file mode 100644 index 8c14776a4c..0000000000 --- a/patches/minecraft/net/minecraft/core/RegistrySynchronization.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/core/RegistrySynchronization.java -+++ b/net/minecraft/core/RegistrySynchronization.java -@@ -29,7 +_,7 @@ - put(builder, Registries.TRIM_MATERIAL, TrimMaterial.DIRECT_CODEC); - put(builder, Registries.DIMENSION_TYPE, DimensionType.DIRECT_CODEC); - put(builder, Registries.DAMAGE_TYPE, DamageType.CODEC); -- return builder.build(); -+ return net.minecraftforge.registries.DataPackRegistriesHooks.grabNetworkableRegistries(builder); // FORGE: Keep the map so custom registries can be added later - }); - public static final Codec NETWORK_CODEC = makeNetworkCodec(); - diff --git a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch index 4795aa6a37..0febe30724 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java @@ -35,21 +_,22 @@ - double d2 = vec3.y() + (double)((float)direction.getStepY() * 1.125F); - double d3 = vec3.z() + (double)direction.getStepZ() * d0; - BlockPos blockpos = p_123375_.pos().relative(direction); -+ Boat boat = (Boat)(this.isChestBoat ? new ChestBoat(serverlevel, d0, d1, d2) : new Boat(serverlevel, d0, d1, d2)); -+ boat.setVariant(this.type); -+ boat.setYRot(direction.toYRot()); - double d4; -- if (serverlevel.getFluidState(blockpos).is(FluidTags.WATER)) { -+ if (boat.canBoatInFluid(serverlevel.getFluidState(blockpos))) { - d4 = 1.0D; - } else { -- if (!serverlevel.getBlockState(blockpos).isAir() || !serverlevel.getFluidState(blockpos.below()).is(FluidTags.WATER)) { -+ if (!serverlevel.getBlockState(blockpos).isAir() || !boat.canBoatInFluid(serverlevel.getFluidState(blockpos.below()))) { - return this.defaultDispenseItemBehavior.dispense(p_123375_, p_123376_); - } + double d2 = vec3.y() + (double)((float)direction.getStepY() * 1.125F); + double d3 = vec3.z() + (double)direction.getStepZ() * d0; + BlockPos blockpos = p_123375_.pos().relative(direction); ++ Boat boat = (Boat)(this.isChestBoat ? new ChestBoat(serverlevel, d0, d1, d2) : new Boat(serverlevel, d0, d1, d2)); ++ boat.setVariant(this.type); ++ boat.setYRot(direction.toYRot()); + double d4; +- if (serverlevel.getFluidState(blockpos).is(FluidTags.WATER)) { ++ if (boat.canBoatInFluid(serverlevel.getFluidState(blockpos))) { + d4 = 1.0; + } else { +- if (!serverlevel.getBlockState(blockpos).isAir() || !serverlevel.getFluidState(blockpos.below()).is(FluidTags.WATER)) { ++ if (!serverlevel.getBlockState(blockpos).isAir() || !boat.canBoatInFluid(serverlevel.getFluidState(blockpos.below()))) { + return this.defaultDispenseItemBehavior.dispense(p_123375_, p_123376_); + } - d4 = 0.0D; - } + d4 = 0.0; + } -- Boat boat = (Boat)(this.isChestBoat ? new ChestBoat(serverlevel, d1, d2 + d4, d3) : new Boat(serverlevel, d1, d2 + d4, d3)); - EntityType.createDefaultStackConfig(serverlevel, p_123376_, (Player)null).accept(boat); -- boat.setVariant(this.type); -- boat.setYRot(direction.toYRot()); -+ boat.setPos(d1, d2 + d4, d3); - serverlevel.addFreshEntity(boat); - p_123376_.shrink(1); - return p_123376_; +- Boat boat = (Boat)(this.isChestBoat ? new ChestBoat(serverlevel, d1, d2 + d4, d3) : new Boat(serverlevel, d1, d2 + d4, d3)); + EntityType.createDefaultStackConfig(serverlevel, p_123376_, null).accept(boat); +- boat.setVariant(this.type); +- boat.setYRot(direction.toYRot()); ++ boat.setPos(d1, d2 + d4, d3); + serverlevel.addFreshEntity(boat); + p_123376_.shrink(1); + return p_123376_; diff --git a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch index 550b2fa594..a8c8c0a3fe 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch @@ -1,25 +1,26 @@ --- a/net/minecraft/core/dispenser/DispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/DispenseItemBehavior.java -@@ -351,7 +_,7 @@ - DispensibleContainerItem dispensiblecontaineritem = (DispensibleContainerItem)p_123562_.getItem(); - BlockPos blockpos = p_123561_.pos().relative(p_123561_.state().getValue(DispenserBlock.FACING)); - Level level = p_123561_.level(); -- if (dispensiblecontaineritem.emptyContents((Player)null, level, blockpos, (BlockHitResult)null)) { -+ if (dispensiblecontaineritem.emptyContents((Player)null, level, blockpos, (BlockHitResult)null, p_123562_)) { - dispensiblecontaineritem.checkExtraContent((Player)null, level, p_123562_, blockpos); - return new ItemStack(Items.BUCKET); - } else { -@@ -410,9 +_,10 @@ - level.setBlockAndUpdate(blockpos, BaseFireBlock.getState(level, blockpos)); - level.gameEvent((Entity)null, GameEvent.BLOCK_PLACE, blockpos); - } else if (!CampfireBlock.canLight(blockstate) && !CandleBlock.canLight(blockstate) && !CandleCakeBlock.canLight(blockstate)) { -- if (blockstate.getBlock() instanceof TntBlock) { -- TntBlock.explode(level, blockpos); -- level.removeBlock(blockpos, false); -+ if (blockstate.isFlammable(level, blockpos, p_123412_.state().getValue(DispenserBlock.FACING).getOpposite())) { -+ blockstate.onCaughtFire(level, blockpos, p_123412_.state().getValue(DispenserBlock.FACING).getOpposite(), null); -+ if (blockstate.getBlock() instanceof TntBlock) -+ level.removeBlock(blockpos, false); - } else { - this.setSuccess(false); - } +@@ -232,7 +_,7 @@ + DispensibleContainerItem dispensiblecontaineritem = (DispensibleContainerItem)p_333855_.getItem(); + BlockPos blockpos = p_333645_.pos().relative(p_333645_.state().getValue(DispenserBlock.FACING)); + Level level = p_333645_.level(); +- if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null)) { ++ if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null, p_333855_)) { + dispensiblecontaineritem.checkExtraContent(null, level, p_333855_, blockpos); + return new ItemStack(Items.BUCKET); + } else { +@@ -294,9 +_,11 @@ + } else if (CampfireBlock.canLight(blockstate) || CandleBlock.canLight(blockstate) || CandleCakeBlock.canLight(blockstate)) { + level.setBlockAndUpdate(blockpos, blockstate.setValue(BlockStateProperties.LIT, Boolean.valueOf(true))); + level.gameEvent(null, GameEvent.BLOCK_CHANGE, blockpos); +- } else if (blockstate.getBlock() instanceof TntBlock) { +- TntBlock.explode(level, blockpos); +- level.removeBlock(blockpos, false); ++ } else if (blockstate.isFlammable(level, blockpos, p_333039_.state().getValue(DispenserBlock.FACING).getOpposite())) { ++ blockstate.onCaughtFire(level, blockpos, p_333039_.state().getValue(DispenserBlock.FACING).getOpposite(), null); ++ if (blockstate.getBlock() instanceof TntBlock) { ++ level.removeBlock(blockpos, false); ++ } + } else { + this.setSuccess(false); + } diff --git a/patches/minecraft/net/minecraft/core/particles/BlockParticleOption.java.patch b/patches/minecraft/net/minecraft/core/particles/BlockParticleOption.java.patch index 0a4f3c0915..651e4c43f5 100644 --- a/patches/minecraft/net/minecraft/core/particles/BlockParticleOption.java.patch +++ b/patches/minecraft/net/minecraft/core/particles/BlockParticleOption.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/core/particles/BlockParticleOption.java +++ b/net/minecraft/core/particles/BlockParticleOption.java -@@ -51,4 +_,15 @@ - public BlockState getState() { - return this.state; - } +@@ -35,4 +_,15 @@ + public BlockState getState() { + return this.state; + } + -+ //FORGE: Add a source pos property, so we can provide models with additional model data -+ private net.minecraft.core.BlockPos pos; -+ public BlockParticleOption setPos(net.minecraft.core.BlockPos pos) { -+ this.pos = pos; -+ return this; -+ } ++ //FORGE: Add a source pos property, so we can provide models with additional model data ++ private net.minecraft.core.BlockPos pos; ++ public BlockParticleOption setPos(net.minecraft.core.BlockPos pos) { ++ this.pos = pos; ++ return this; ++ } + -+ public net.minecraft.core.BlockPos getPos() { -+ return pos; -+ } ++ public net.minecraft.core.BlockPos getPos() { // should this be annotated with @Nullable? -Paint_Ninja ++ return pos; ++ } } diff --git a/patches/minecraft/net/minecraft/core/particles/ItemParticleOption.java.patch b/patches/minecraft/net/minecraft/core/particles/ItemParticleOption.java.patch index a35361bb7d..43de589407 100644 --- a/patches/minecraft/net/minecraft/core/particles/ItemParticleOption.java.patch +++ b/patches/minecraft/net/minecraft/core/particles/ItemParticleOption.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/core/particles/ItemParticleOption.java +++ b/net/minecraft/core/particles/ItemParticleOption.java -@@ -35,7 +_,7 @@ +@@ -24,7 +_,7 @@ + throw new IllegalArgumentException("Empty stacks are not allowed"); + } else { + this.type = p_123705_; +- this.itemStack = p_123706_; ++ this.itemStack = p_123706_.copy(); // Forge: Fix stack updating after the fact causing particle changes. + } + } - public ItemParticleOption(ParticleType p_123705_, ItemStack p_123706_) { - this.type = p_123705_; -- this.itemStack = p_123706_; -+ this.itemStack = p_123706_.copy(); //Forge: Fix stack updating after the fact causing particle changes. - } - - public void writeToNetwork(FriendlyByteBuf p_123716_) { diff --git a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch index 83f990be13..55d4a8193d 100644 --- a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch +++ b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch @@ -1,310 +1,22 @@ --- a/net/minecraft/core/registries/BuiltInRegistries.java +++ b/net/minecraft/core/registries/BuiltInRegistries.java -@@ -122,41 +_,89 @@ - public static final DefaultedRegistry GAME_EVENT = registerDefaultedWithIntrusiveHolders(Registries.GAME_EVENT, "step", (p_260052_) -> { - return GameEvent.STEP; - }); -- public static final Registry SOUND_EVENT = registerSimple(Registries.SOUND_EVENT, (p_260167_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#SOUND_EVENTS} instead. -+ */ -+ @Deprecated -+ public static final Registry SOUND_EVENT = forge(Registries.SOUND_EVENT, (p_260167_) -> { - return SoundEvents.ITEM_PICKUP; - }); -- public static final DefaultedRegistry FLUID = registerDefaultedWithIntrusiveHolders(Registries.FLUID, "empty", (p_259453_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#FLUIDS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry FLUID = forge(Registries.FLUID, "empty", (p_259453_) -> { - return Fluids.EMPTY; - }); -- public static final Registry MOB_EFFECT = registerSimpleWithIntrusiveHolders(Registries.MOB_EFFECT, (p_259689_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#MOB_EFFECTS} instead. -+ */ -+ @Deprecated -+ public static final Registry MOB_EFFECT = forge(Registries.MOB_EFFECT, (p_259689_) -> { - return MobEffects.LUCK; - }); -- public static final DefaultedRegistry BLOCK = registerDefaultedWithIntrusiveHolders(Registries.BLOCK, "air", (p_259909_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#BLOCKS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry BLOCK = forge(Registries.BLOCK, "air", (p_259909_) -> { - return Blocks.AIR; - }); -- public static final Registry ENCHANTMENT = registerSimpleWithIntrusiveHolders(Registries.ENCHANTMENT, (p_259104_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#ENCHANTMENTS} instead. -+ */ -+ @Deprecated -+ public static final Registry ENCHANTMENT = forge(Registries.ENCHANTMENT, (p_259104_) -> { - return Enchantments.BLOCK_FORTUNE; - }); -- public static final DefaultedRegistry> ENTITY_TYPE = registerDefaultedWithIntrusiveHolders(Registries.ENTITY_TYPE, "pig", (p_259175_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#ENTITY_TYPES} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry> ENTITY_TYPE = forge(Registries.ENTITY_TYPE, "pig", (p_259175_) -> { - return EntityType.PIG; - }); -- public static final DefaultedRegistry ITEM = registerDefaultedWithIntrusiveHolders(Registries.ITEM, "air", (p_260227_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#ITEMS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry ITEM = forge(Registries.ITEM, "air", (p_260227_) -> { - return Items.AIR; - }); -- public static final DefaultedRegistry POTION = registerDefaultedWithIntrusiveHolders(Registries.POTION, "empty", (p_259869_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#POTIONS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry POTION = forge(Registries.POTION, "empty", (p_259869_) -> { - return Potions.EMPTY; - }); -- public static final Registry> PARTICLE_TYPE = registerSimple(Registries.PARTICLE_TYPE, (p_260266_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#PARTICLE_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> PARTICLE_TYPE = forge(Registries.PARTICLE_TYPE, (p_260266_) -> { - return ParticleTypes.BLOCK; - }); -- public static final Registry> BLOCK_ENTITY_TYPE = registerSimpleWithIntrusiveHolders(Registries.BLOCK_ENTITY_TYPE, (p_259434_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#BLOCK_ENTITY_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> BLOCK_ENTITY_TYPE = forge(Registries.BLOCK_ENTITY_TYPE, (p_259434_) -> { - return BlockEntityType.FURNACE; - }); -- public static final DefaultedRegistry PAINTING_VARIANT = registerDefaulted(Registries.PAINTING_VARIANT, "kebab", PaintingVariants::bootstrap); -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#PAINTING_VARIANTS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry PAINTING_VARIANT = forge(Registries.PAINTING_VARIANT, "kebab", PaintingVariants::bootstrap); - public static final Registry CUSTOM_STAT = registerSimple(Registries.CUSTOM_STAT, (p_259833_) -> { - return Stats.JUMP; - }); -- public static final DefaultedRegistry CHUNK_STATUS = registerDefaulted(Registries.CHUNK_STATUS, "empty", (p_259971_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#CHUNK_STATUS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry CHUNK_STATUS = forge(Registries.CHUNK_STATUS, "empty", (p_259971_) -> { - return ChunkStatus.EMPTY; - }); - public static final Registry> RULE_TEST = registerSimple(Registries.RULE_TEST, (p_259641_) -> { -@@ -168,42 +_,90 @@ - public static final Registry> POS_RULE_TEST = registerSimple(Registries.POS_RULE_TEST, (p_259262_) -> { - return PosRuleTestType.ALWAYS_TRUE_TEST; - }); -- public static final Registry> MENU = registerSimple(Registries.MENU, (p_259341_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#MENU_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> MENU = forge(Registries.MENU, (p_259341_) -> { - return MenuType.ANVIL; - }); -- public static final Registry> RECIPE_TYPE = registerSimple(Registries.RECIPE_TYPE, (p_259086_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#RECIPE_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> RECIPE_TYPE = forge(Registries.RECIPE_TYPE, (p_259086_) -> { - return RecipeType.CRAFTING; - }); -- public static final Registry> RECIPE_SERIALIZER = registerSimple(Registries.RECIPE_SERIALIZER, (p_260230_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#RECIPE_SERIALIZERS} instead. -+ */ -+ @Deprecated -+ public static final Registry> RECIPE_SERIALIZER = forge(Registries.RECIPE_SERIALIZER, (p_260230_) -> { - return RecipeSerializer.SHAPELESS_RECIPE; - }); -- public static final Registry ATTRIBUTE = registerSimple(Registries.ATTRIBUTE, (p_260300_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#ATTRIBUTES} instead. -+ */ -+ @Deprecated -+ public static final Registry ATTRIBUTE = forge(Registries.ATTRIBUTE, (p_260300_) -> { - return Attributes.LUCK; - }); - public static final Registry> POSITION_SOURCE_TYPE = registerSimple(Registries.POSITION_SOURCE_TYPE, (p_259113_) -> { - return PositionSourceType.BLOCK; - }); -- public static final Registry> COMMAND_ARGUMENT_TYPE = registerSimple(Registries.COMMAND_ARGUMENT_TYPE, (RegistryBootstrap)ArgumentTypeInfos::bootstrap); -- public static final Registry> STAT_TYPE = registerSimple(Registries.STAT_TYPE, (p_259967_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#COMMAND_ARGUMENT_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> COMMAND_ARGUMENT_TYPE = forge(Registries.COMMAND_ARGUMENT_TYPE, (RegistryBootstrap)ArgumentTypeInfos::bootstrap); -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#STAT_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> STAT_TYPE = forge(Registries.STAT_TYPE, (p_259967_) -> { - return Stats.ITEM_USED; - }); - public static final DefaultedRegistry VILLAGER_TYPE = registerDefaulted(Registries.VILLAGER_TYPE, "plains", (p_259473_) -> { - return VillagerType.PLAINS; - }); -- public static final DefaultedRegistry VILLAGER_PROFESSION = registerDefaulted(Registries.VILLAGER_PROFESSION, "none", (p_259037_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#VILLAGER_PROFESSIONS} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry VILLAGER_PROFESSION = forge(Registries.VILLAGER_PROFESSION, "none", (p_259037_) -> { - return VillagerProfession.NONE; - }); -- public static final Registry POINT_OF_INTEREST_TYPE = registerSimple(Registries.POINT_OF_INTEREST_TYPE, PoiTypes::bootstrap); -- public static final DefaultedRegistry> MEMORY_MODULE_TYPE = registerDefaulted(Registries.MEMORY_MODULE_TYPE, "dummy", (p_259248_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#POI_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry POINT_OF_INTEREST_TYPE = forge(Registries.POINT_OF_INTEREST_TYPE, PoiTypes::bootstrap); -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#MEMORY_MODULE_TYPES} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry> MEMORY_MODULE_TYPE = forge(Registries.MEMORY_MODULE_TYPE, "dummy", (p_259248_) -> { - return MemoryModuleType.DUMMY; - }); -- public static final DefaultedRegistry> SENSOR_TYPE = registerDefaulted(Registries.SENSOR_TYPE, "dummy", (p_259757_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#SENSOR_TYPES} instead. -+ */ -+ @Deprecated -+ public static final DefaultedRegistry> SENSOR_TYPE = forge(Registries.SENSOR_TYPE, "dummy", (p_259757_) -> { - return SensorType.DUMMY; - }); -- public static final Registry SCHEDULE = registerSimple(Registries.SCHEDULE, (p_259540_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#SCHEDULES} instead. -+ */ -+ @Deprecated -+ public static final Registry SCHEDULE = forge(Registries.SCHEDULE, (p_259540_) -> { - return Schedule.EMPTY; - }); -- public static final Registry ACTIVITY = registerSimple(Registries.ACTIVITY, (p_260197_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#ACTIVITIES} instead. -+ */ -+ @Deprecated -+ public static final Registry ACTIVITY = forge(Registries.ACTIVITY, (p_260197_) -> { - return Activity.IDLE; - }); - public static final Registry LOOT_POOL_ENTRY_TYPE = registerSimple(Registries.LOOT_POOL_ENTRY_TYPE, (p_260042_) -> { -@@ -236,10 +_,18 @@ - public static final Registry> BLOCK_PREDICATE_TYPE = registerSimple(Registries.BLOCK_PREDICATE_TYPE, (p_260006_) -> { - return BlockPredicateType.NOT; - }); -- public static final Registry> CARVER = registerSimple(Registries.CARVER, (p_260200_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#WORLD_CARVERS} instead. -+ */ -+ @Deprecated -+ public static final Registry> CARVER = forge(Registries.CARVER, (p_260200_) -> { - return WorldCarver.CAVE; - }); -- public static final Registry> FEATURE = registerSimple(Registries.FEATURE, (p_259143_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#FEATURES} instead. -+ */ -+ @Deprecated -+ public static final Registry> FEATURE = forge(Registries.FEATURE, (p_259143_) -> { - return Feature.ORE; - }); - public static final Registry> STRUCTURE_PLACEMENT = registerSimple(Registries.STRUCTURE_PLACEMENT, (p_259179_) -> { -@@ -254,10 +_,18 @@ - public static final Registry> PLACEMENT_MODIFIER_TYPE = registerSimple(Registries.PLACEMENT_MODIFIER_TYPE, (p_260335_) -> { - return PlacementModifierType.COUNT; - }); -- public static final Registry> BLOCKSTATE_PROVIDER_TYPE = registerSimple(Registries.BLOCK_STATE_PROVIDER_TYPE, (p_259345_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#BLOCK_STATE_PROVIDER_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> BLOCKSTATE_PROVIDER_TYPE = forge(Registries.BLOCK_STATE_PROVIDER_TYPE, (p_259345_) -> { - return BlockStateProviderType.SIMPLE_STATE_PROVIDER; - }); -- public static final Registry> FOLIAGE_PLACER_TYPE = registerSimple(Registries.FOLIAGE_PLACER_TYPE, (p_260329_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#FOLIAGE_PLACER_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> FOLIAGE_PLACER_TYPE = forge(Registries.FOLIAGE_PLACER_TYPE, (p_260329_) -> { - return FoliagePlacerType.BLOB_FOLIAGE_PLACER; - }); - public static final Registry> TRUNK_PLACER_TYPE = registerSimple(Registries.TRUNK_PLACER_TYPE, (p_259690_) -> { -@@ -266,7 +_,11 @@ - public static final Registry> ROOT_PLACER_TYPE = registerSimple(Registries.ROOT_PLACER_TYPE, (p_259493_) -> { - return RootPlacerType.MANGROVE_ROOT_PLACER; - }); -- public static final Registry> TREE_DECORATOR_TYPE = registerSimple(Registries.TREE_DECORATOR_TYPE, (p_259122_) -> { -+ /** -+ * @deprecated Forge: Use {@link net.minecraftforge.registries.ForgeRegistries#TREE_DECORATOR_TYPES} instead. -+ */ -+ @Deprecated -+ public static final Registry> TREE_DECORATOR_TYPE = forge(Registries.TREE_DECORATOR_TYPE, (p_259122_) -> { - return TreeDecoratorType.LEAVE_VINE; - }); - public static final Registry> FEATURE_SIZE_TYPE = registerSimple(Registries.FEATURE_SIZE_TYPE, (p_259370_) -> { -@@ -305,10 +_,18 @@ - return internalRegister(p_297531_, new MappedRegistry<>(p_297531_, Lifecycle.stable(), true), p_298446_, Lifecycle.stable()); - } +@@ -230,7 +_,9 @@ + ) { + Bootstrap.checkBootstrapCalled(() -> "registry " + p_259230_); + ResourceLocation resourcelocation = p_259230_.location(); +- LOADERS.put(resourcelocation, () -> p_259210_.run(p_260327_)); ++ var maybeWrapped = net.minecraftforge.registries.GameData.getWrapper(p_259230_, p_260327_); ++ p_260327_ = maybeWrapped; ++ LOADERS.put(resourcelocation, () -> p_259210_.run(maybeWrapped)); + WRITABLE_REGISTRY.register((ResourceKey)p_259230_, p_260327_, RegistrationInfo.BUILT_IN); + return p_260327_; + } +@@ -265,7 +_,7 @@ -+ private static Registry forge(ResourceKey> key, BuiltInRegistries.RegistryBootstrap def) { -+ return forge(key, Lifecycle.stable(), def); -+ } -+ - private static DefaultedRegistry registerDefaulted(ResourceKey> p_259887_, String p_259325_, BuiltInRegistries.RegistryBootstrap p_259759_) { - return registerDefaulted(p_259887_, p_259325_, Lifecycle.stable(), p_259759_); - } - -+ private static DefaultedRegistry forge(ResourceKey> key, String defKey, BuiltInRegistries.RegistryBootstrap def) { -+ return forge(key, defKey, Lifecycle.stable(), def); -+ } -+ - private static DefaultedRegistry registerDefaultedWithIntrusiveHolders(ResourceKey> p_259296_, String p_259101_, BuiltInRegistries.RegistryBootstrap p_259485_) { - return registerDefaultedWithIntrusiveHolders(p_259296_, p_259101_, Lifecycle.stable(), p_259485_); - } -@@ -317,10 +_,19 @@ - return internalRegister(p_259121_, new MappedRegistry<>(p_259121_, p_259977_, false), p_259874_, p_259977_); - } - -+ private static Registry forge(ResourceKey> key, Lifecycle cycle, BuiltInRegistries.RegistryBootstrap def) { -+ return internalRegister(key, net.minecraftforge.registries.GameData.getWrapper(key, cycle), def, cycle); -+ } -+ - private static DefaultedRegistry registerDefaulted(ResourceKey> p_259400_, String p_259678_, Lifecycle p_259157_, BuiltInRegistries.RegistryBootstrap p_259806_) { - return internalRegister(p_259400_, new DefaultedMappedRegistry<>(p_259678_, p_259400_, p_259157_, false), p_259806_, p_259157_); - } - -+ @SuppressWarnings("unchecked") -+ private static DefaultedRegistry forge(ResourceKey> key, String defKey, Lifecycle cycle, BuiltInRegistries.RegistryBootstrap def) { -+ return (DefaultedRegistry) internalRegister(key, net.minecraftforge.registries.GameData.getWrapper(key, cycle, defKey), def, cycle); -+ } -+ - private static DefaultedRegistry registerDefaultedWithIntrusiveHolders(ResourceKey> p_260010_, String p_260220_, Lifecycle p_260139_, BuiltInRegistries.RegistryBootstrap p_260185_) { - return internalRegister(p_260010_, new DefaultedMappedRegistry<>(p_260220_, p_260010_, p_260139_, true), p_260185_, p_260139_); - } -@@ -369,7 +_,7 @@ - - if (p_259410_ instanceof DefaultedRegistry) { - ResourceLocation resourcelocation = ((DefaultedRegistry)p_259410_).getDefaultKey(); -- Validate.notNull(p_259410_.get(resourcelocation), "Missing default of DefaultedMappedRegistry: " + resourcelocation); -+ Validate.notNull(p_259410_.get(resourcelocation), "Missing default of DefaultedMappedRegistry: " + p_260209_.key() + ", Entry: " + resourcelocation); - } - - }); + if (p_325821_ instanceof DefaultedRegistry) { + ResourceLocation resourcelocation = ((DefaultedRegistry)p_325821_).getDefaultKey(); +- Validate.notNull(p_325821_.get(resourcelocation), "Missing default of DefaultedMappedRegistry: " + resourcelocation); ++ Validate.notNull(p_325821_.get(resourcelocation), "Missing default of DefaultedMappedRegistry: " + p_325821_.key() + " - " + resourcelocation); + } + }); + } diff --git a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch index 1753edcb64..cd596e0048 100644 --- a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch @@ -1,53 +1,54 @@ --- a/net/minecraft/data/DataGenerator.java +++ b/net/minecraft/data/DataGenerator.java @@ -21,6 +_,7 @@ - final Map providersToRun = new LinkedHashMap<>(); - private final WorldVersion version; - private final boolean alwaysGenerate; -+ private final Map providersView = java.util.Collections.unmodifiableMap(this.providersToRun); + final Map providersToRun = new LinkedHashMap<>(); + private final WorldVersion version; + private final boolean alwaysGenerate; ++ private final Map providersView = java.util.Collections.unmodifiableMap(this.providersToRun); - public DataGenerator(Path p_251724_, WorldVersion p_250554_, boolean p_251323_) { - this.rootOutputFolder = p_251724_; + public DataGenerator(Path p_251724_, WorldVersion p_250554_, boolean p_251323_) { + this.rootOutputFolder = p_251724_; @@ -38,6 +_,7 @@ - LOGGER.debug("Generator {} already run for version {}", p_254418_, this.version.getName()); - } else { - LOGGER.info("Starting provider: {}", (Object)p_254418_); -+ net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + p_254418_); - stopwatch1.start(); - hashcache.applyUpdate(hashcache.generateUpdate(p_254418_, p_253750_::run).join()); - stopwatch1.stop(); -@@ -56,6 +_,34 @@ - public DataGenerator.PackGenerator getBuiltinDatapack(boolean p_253826_, String p_254134_) { - Path path = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(p_254134_); - return new DataGenerator.PackGenerator(p_253826_, p_254134_, new PackOutput(path)); -+ } + LOGGER.debug("Generator {} already run for version {}", p_254418_, this.version.getName()); + } else { + LOGGER.info("Starting provider: {}", p_254418_); ++ net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + p_254418_); + stopwatch1.start(); + hashcache.applyUpdate(hashcache.generateUpdate(p_254418_, p_253750_::run).join()); + stopwatch1.stop(); +@@ -56,6 +_,35 @@ + public DataGenerator.PackGenerator getBuiltinDatapack(boolean p_253826_, String p_254134_) { + Path path = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(p_254134_); + return new DataGenerator.PackGenerator(p_253826_, p_254134_, new PackOutput(path)); ++ } ++ public Map getProvidersView() { ++ return this.providersView; ++ } + -+ public Map getProvidersView() { -+ return this.providersView; -+ } ++ public PackOutput getPackOutput() { ++ return this.vanillaPackOutput; ++ } + -+ public PackOutput getPackOutput() { -+ return this.vanillaPackOutput; -+ } ++ public PackOutput getPackOutput(String path) { ++ return new PackOutput(rootOutputFolder.resolve(path)); ++ } + -+ public PackOutput getPackOutput(String path) { -+ return new PackOutput(rootOutputFolder.resolve(path)); -+ } ++ public T addProvider(boolean run, DataProvider.Factory factory) { ++ return addProvider(run, factory.create(this.vanillaPackOutput)); ++ } + -+ public T addProvider(boolean run, DataProvider.Factory factory) { -+ return addProvider(run, factory.create(this.vanillaPackOutput)); -+ } ++ public T addProvider(boolean run, T provider) { ++ String id = provider.getName(); + -+ public T addProvider(boolean run, T provider) { -+ String id = provider.getName(); ++ if (!DataGenerator.this.allProviderIds.add(id)) { ++ throw new IllegalStateException("Duplicate provider: " + id); ++ } + -+ if (!DataGenerator.this.allProviderIds.add(id)) -+ throw new IllegalStateException("Duplicate provider: " + id); ++ if (run) { ++ DataGenerator.this.providersToRun.put(id, provider); ++ } + -+ if (run) -+ DataGenerator.this.providersToRun.put(id, provider); -+ -+ return provider; - } ++ return provider; + } - static { + static { diff --git a/patches/minecraft/net/minecraft/data/HashCache.java.patch b/patches/minecraft/net/minecraft/data/HashCache.java.patch index cc6307e85e..0f4b9a694d 100644 --- a/patches/minecraft/net/minecraft/data/HashCache.java.patch +++ b/patches/minecraft/net/minecraft/data/HashCache.java.patch @@ -1,41 +1,41 @@ --- a/net/minecraft/data/HashCache.java +++ b/net/minecraft/data/HashCache.java -@@ -35,6 +_,7 @@ - private final Path cacheDir; - private final String versionId; - private final Map caches; -+ private final Map originalCaches; - private final Set cachesToWrite = new HashSet<>(); - private final Set cachePaths = new HashSet<>(); - private final int initialCount; -@@ -61,6 +_,7 @@ - } +@@ -39,6 +_,7 @@ + private final Path cacheDir; + private final String versionId; + private final Map caches; ++ private final Map originalCaches; + private final Set cachesToWrite = new HashSet<>(); + final Set cachePaths = new HashSet<>(); + private final int initialCount; +@@ -65,6 +_,7 @@ + } - this.caches = map; -+ this.originalCaches = Map.copyOf(this.caches); - this.initialCount = i; - } + this.caches = map; ++ this.originalCaches = Map.copyOf(this.caches); + this.initialCount = i; + } -@@ -104,6 +_,8 @@ - this.caches.forEach((p_253378_, p_253379_) -> { - if (this.cachesToWrite.contains(p_253378_)) { - Path path = this.getProviderCachePath(p_253378_); -+ // Forge: Only rewrite the cache file if it changed or is missing -+ if (!p_253379_.equals(this.originalCaches.get(p_253378_)) || !Files.exists(path)) - p_253379_.save(this.rootDir, path, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now()) + "\t" + p_253378_); - } - -@@ -208,10 +_,11 @@ - bufferedwriter.write(p_236145_); - bufferedwriter.newLine(); - -- for(Map.Entry entry : this.data.entrySet()) { -+ // Forge: Standardize order of entries -+ for(Map.Entry entry : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { - bufferedwriter.write(entry.getValue().toString()); - bufferedwriter.write(32); -- bufferedwriter.write(p_236143_.relativize(entry.getKey()).toString()); -+ bufferedwriter.write(p_236143_.relativize(entry.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. - bufferedwriter.newLine(); +@@ -106,6 +_,8 @@ + this.caches.forEach((p_253378_, p_253379_) -> { + if (this.cachesToWrite.contains(p_253378_)) { + Path path = this.getProviderCachePath(p_253378_); ++ // Forge: Only rewrite the cache file if it changed or is missing ++ if (!p_253379_.equals(this.originalCaches.get(p_253378_)) || !Files.exists(path)) + p_253379_.save(this.rootDir, path, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now()) + "\t" + p_253378_); } - } catch (IOException ioexception) { + +@@ -222,10 +_,11 @@ + bufferedwriter.write(p_236145_); + bufferedwriter.newLine(); + +- for (Entry entry : this.data.entrySet()) { ++ // Forge: Standardize order of entries ++ for (Entry entry : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { + bufferedwriter.write(entry.getValue().toString()); + bufferedwriter.write(32); +- bufferedwriter.write(p_236143_.relativize(entry.getKey()).toString()); ++ bufferedwriter.write(p_236143_.relativize(entry.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. + bufferedwriter.newLine(); + } + } catch (IOException ioexception) { diff --git a/patches/minecraft/net/minecraft/data/Main.java.patch b/patches/minecraft/net/minecraft/data/Main.java.patch index 30512eecb5..542d84046a 100644 --- a/patches/minecraft/net/minecraft/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/data/Main.java.patch @@ -1,38 +1,41 @@ --- a/net/minecraft/data/Main.java +++ b/net/minecraft/data/Main.java -@@ -79,8 +_,15 @@ - OptionSpec optionspec6 = optionparser.accepts("all", "Include all generators"); - OptionSpec optionspec7 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); - OptionSpec optionspec8 = optionparser.accepts("input", "Input folder").withRequiredArg(); -+ OptionSpec existing = optionparser.accepts("existing", "Existing resource packs that generated resources can reference").withRequiredArg(); -+ OptionSpec existingMod = optionparser.accepts("existing-mod", "Existing mods that generated resources can reference the resource packs of").withRequiredArg(); -+ OptionSpec gameDir = optionparser.accepts("gameDir").withRequiredArg().ofType(java.io.File.class).defaultsTo(new java.io.File(".")).required(); //Need by modlauncher, so lets just eat it -+ OptionSpec mod = optionparser.accepts("mod", "A modid to dump").withRequiredArg().withValuesSeparatedBy(","); -+ OptionSpec flat = optionparser.accepts("flat", "Do not append modid prefix to output directory when generating for multiple mods"); -+ OptionSpec assetIndex = optionparser.accepts("assetIndex").withRequiredArg(); -+ OptionSpec assetsDir = optionparser.accepts("assetsDir").withRequiredArg().ofType(java.io.File.class); - OptionSet optionset = optionparser.parse(p_129669_); -- if (!optionset.has(optionspec) && optionset.hasOptions()) { -+ if (!optionset.has(optionspec) && optionset.hasOptions() && !(optionset.specs().size() == 1 && optionset.has(gameDir))) { - Path path = Paths.get(optionspec7.value(optionset)); - boolean flag = optionset.has(optionspec6); - boolean flag1 = flag || optionset.has(optionspec2); -@@ -88,10 +_,14 @@ - boolean flag3 = flag || optionset.has(optionspec3); - boolean flag4 = flag || optionset.has(optionspec4); - boolean flag5 = flag || optionset.has(optionspec5); -- DataGenerator datagenerator = createStandardGenerator(path, optionset.valuesOf(optionspec8).stream().map((p_129659_) -> { -- return Paths.get(p_129659_); -- }).collect(Collectors.toList()), flag1, flag2, flag3, flag4, flag5, SharedConstants.getCurrentVersion(), true); -- datagenerator.run(); -+ Collection inputs = optionset.valuesOf(optionspec8).stream().map(Paths::get).collect(Collectors.toList()); -+ Collection existingPacks = optionset.valuesOf(existing).stream().map(Paths::get).collect(Collectors.toList()); -+ java.util.Set existingMods = new java.util.HashSet<>(optionset.valuesOf(existingMod)); -+ java.util.Set mods = new java.util.HashSet<>(optionset.valuesOf(mod)); -+ boolean isFlat = mods.isEmpty() || optionset.has(flat); -+ net.minecraftforge.data.loading.DatagenModLoader.begin(mods, path, inputs, existingPacks, existingMods, flag2, flag1, flag3, flag4, flag5, isFlat, optionset.valueOf(assetIndex), optionset.valueOf(assetsDir)); -+ if (mods.contains("minecraft") || mods.isEmpty()) -+ createStandardGenerator(isFlat ? path : path.resolve("minecraft"), inputs, flag1, flag2, flag3, flag4, flag5, SharedConstants.getCurrentVersion(), true).run(); - } else { - optionparser.printHelpOn(System.out); - } +@@ -86,8 +_,15 @@ + OptionSpec optionspec6 = optionparser.accepts("all", "Include all generators"); + OptionSpec optionspec7 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); + OptionSpec optionspec8 = optionparser.accepts("input", "Input folder").withRequiredArg(); ++ OptionSpec existing = optionparser.accepts("existing", "Existing resource packs that generated resources can reference").withRequiredArg(); ++ OptionSpec existingMod = optionparser.accepts("existing-mod", "Existing mods that generated resources can reference the resource packs of").withRequiredArg(); ++ OptionSpec gameDir = optionparser.accepts("gameDir").withRequiredArg().ofType(java.io.File.class).defaultsTo(new java.io.File(".")).required(); //Need by modlauncher, so lets just eat it ++ OptionSpec mod = optionparser.accepts("mod", "A modid to dump").withRequiredArg().withValuesSeparatedBy(","); ++ OptionSpec flat = optionparser.accepts("flat", "Do not append modid prefix to output directory when generating for multiple mods"); ++ OptionSpec assetIndex = optionparser.accepts("assetIndex").withRequiredArg(); ++ OptionSpec assetsDir = optionparser.accepts("assetsDir").withRequiredArg().ofType(java.io.File.class); + OptionSet optionset = optionparser.parse(p_129669_); +- if (!optionset.has(optionspec) && optionset.hasOptions()) { ++ if (!optionset.has(optionspec) && optionset.hasOptions() && !(optionset.specs().size() == 1 && optionset.has(gameDir))) { + Path path = Paths.get(optionspec7.value(optionset)); + boolean flag = optionset.has(optionspec6); + boolean flag1 = flag || optionset.has(optionspec2); +@@ -95,6 +_,13 @@ + boolean flag3 = flag || optionset.has(optionspec3); + boolean flag4 = flag || optionset.has(optionspec4); + boolean flag5 = flag || optionset.has(optionspec5); ++ Collection inputs = optionset.valuesOf(optionspec8).stream().map(Paths::get).collect(Collectors.toList()); ++ Collection existingPacks = optionset.valuesOf(existing).stream().map(Paths::get).collect(Collectors.toList()); ++ java.util.Set existingMods = new java.util.HashSet<>(optionset.valuesOf(existingMod)); ++ java.util.Set mods = new java.util.HashSet<>(optionset.valuesOf(mod)); ++ boolean isFlat = mods.isEmpty() || optionset.has(flat); ++ net.minecraftforge.data.loading.DatagenModLoader.begin(mods, path, inputs, existingPacks, existingMods, flag2, flag1, flag3, flag4, flag5, isFlat, optionset.valueOf(assetIndex), optionset.valueOf(assetsDir)); ++ if (mods.contains("minecraft") || mods.isEmpty()) { + DataGenerator datagenerator = createStandardGenerator( + path, + optionset.valuesOf(optionspec8).stream().map(p_129659_ -> Paths.get(p_129659_)).collect(Collectors.toList()), +@@ -107,6 +_,7 @@ + true + ); + datagenerator.run(); ++ } + } else { + optionparser.printHelpOn(System.out); + } diff --git a/patches/minecraft/net/minecraft/data/advancements/AdvancementProvider.java.patch b/patches/minecraft/net/minecraft/data/advancements/AdvancementProvider.java.patch index bee6d0c608..2522c005c9 100644 --- a/patches/minecraft/net/minecraft/data/advancements/AdvancementProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/advancements/AdvancementProvider.java.patch @@ -10,5 +10,5 @@ + */ +@Deprecated public class AdvancementProvider implements DataProvider { - private final PackOutput.PathProvider pathProvider; - private final List subProviders; + private final PackOutput.PathProvider pathProvider; + private final List subProviders; diff --git a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch index c9e0d80131..7805b397d4 100644 --- a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch @@ -1,19 +1,20 @@ --- a/net/minecraft/data/loot/BlockLootSubProvider.java +++ b/net/minecraft/data/loot/BlockLootSubProvider.java -@@ -265,11 +_,15 @@ +@@ -605,12 +_,16 @@ - protected abstract void generate(); + protected abstract void generate(); -+ protected Iterable getKnownBlocks() { -+ return BuiltInRegistries.BLOCK; -+ } ++ protected Iterable getKnownBlocks() { ++ return BuiltInRegistries.BLOCK; ++ } + - public void generate(BiConsumer p_249322_) { - this.generate(); - Set set = new HashSet<>(); + @Override + public void generate(HolderLookup.Provider p_331289_, BiConsumer, LootTable.Builder> p_249322_) { + this.generate(); + Set> set = new HashSet<>(); -- for(Block block : BuiltInRegistries.BLOCK) { -+ for(Block block : getKnownBlocks()) { - if (block.isEnabled(this.enabledFeatures)) { - ResourceLocation resourcelocation = block.getLootTable(); - if (resourcelocation != BuiltInLootTables.EMPTY && set.add(resourcelocation)) { +- for (Block block : BuiltInRegistries.BLOCK) { ++ for (Block block : getKnownBlocks()) { + if (block.isEnabled(this.enabledFeatures)) { + ResourceKey resourcekey = block.getLootTable(); + if (resourcekey != BuiltInLootTables.EMPTY && set.add(resourcekey)) { diff --git a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch index 8e9b329245..97b9d62722 100644 --- a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch @@ -1,52 +1,30 @@ --- a/net/minecraft/data/loot/EntityLootSubProvider.java +++ b/net/minecraft/data/loot/EntityLootSubProvider.java -@@ -51,23 +_,27 @@ +@@ -58,12 +_,16 @@ - public abstract void generate(); + public abstract void generate(); -+ protected java.util.stream.Stream> getKnownEntityTypes() { -+ return BuiltInRegistries.ENTITY_TYPE.stream(); -+ } ++ protected java.util.stream.Stream> getKnownEntityTypes() { ++ return BuiltInRegistries.ENTITY_TYPE.stream(); ++ } + - public void generate(BiConsumer p_251751_) { - this.generate(); - Set set = Sets.newHashSet(); -- BuiltInRegistries.ENTITY_TYPE.holders().forEach((p_266624_) -> { -- EntityType entitytype = p_266624_.value(); -+ this.getKnownEntityTypes().map(EntityType::builtInRegistryHolder).forEach((p_249003_) -> { -+ EntityType entitytype = p_249003_.value(); - if (entitytype.isEnabled(this.allowed)) { - if (canHaveLootTable(entitytype)) { - Map map = this.map.remove(entitytype); - ResourceLocation resourcelocation = entitytype.getDefaultLootTable(); - if (!resourcelocation.equals(BuiltInLootTables.EMPTY) && entitytype.isEnabled(this.required) && (map == null || !map.containsKey(resourcelocation))) { -- throw new IllegalStateException(String.format(Locale.ROOT, "Missing loottable '%s' for '%s'", resourcelocation, p_266624_.key().location())); -+ throw new IllegalStateException(String.format(Locale.ROOT, "Missing loottable '%s' for '%s'", resourcelocation, p_249003_.key().location())); - } + @Override + public void generate(HolderLookup.Provider p_327798_, BiConsumer, LootTable.Builder> p_251751_) { + this.generate(); + Set> set = new HashSet<>(); +- BuiltInRegistries.ENTITY_TYPE +- .holders() ++ this.getKnownEntityTypes() ++ .map(EntityType::builtInRegistryHolder) + .forEach( + p_266624_ -> { + EntityType entitytype = p_266624_.value(); +@@ -113,7 +_,7 @@ + } + } - if (map != null) { - map.forEach((p_250376_, p_250972_) -> { - if (!set.add(p_250376_)) { -- throw new IllegalStateException(String.format(Locale.ROOT, "Duplicate loottable '%s' for '%s'", p_250376_, p_266624_.key().location())); -+ throw new IllegalStateException(String.format(Locale.ROOT, "Duplicate loottable '%s' for '%s'", p_250376_, p_249003_.key().location())); - } else { - p_251751_.accept(p_250376_, p_250972_); - } -@@ -76,7 +_,7 @@ - } else { - Map map1 = this.map.remove(entitytype); - if (map1 != null) { -- throw new IllegalStateException(String.format(Locale.ROOT, "Weird loottables '%s' for '%s', not a LivingEntity so should not have loot", map1.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(",")), p_266624_.key().location())); -+ throw new IllegalStateException(String.format(Locale.ROOT, "Weird loottables '%s' for '%s', not a LivingEntity so should not have loot", map1.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(",")), p_249003_.key().location())); - } - } - -@@ -87,7 +_,7 @@ - } - } - -- protected static boolean canHaveLootTable(EntityType p_249029_) { -+ protected boolean canHaveLootTable(EntityType p_249029_) { - return SPECIAL_LOOT_TABLE_TYPES.contains(p_249029_) || p_249029_.getCategory() != MobCategory.MISC; - } +- protected static boolean canHaveLootTable(EntityType p_249029_) { ++ protected boolean canHaveLootTable(EntityType p_249029_) { + return SPECIAL_LOOT_TABLE_TYPES.contains(p_249029_) || p_249029_.getCategory() != MobCategory.MISC; + } diff --git a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch index 8f2c4d01e7..09402363e9 100644 --- a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch @@ -1,47 +1,53 @@ --- a/net/minecraft/data/loot/LootTableProvider.java +++ b/net/minecraft/data/loot/LootTableProvider.java -@@ -44,7 +_,7 @@ - public CompletableFuture run(CachedOutput p_254060_) { - final Map map = Maps.newHashMap(); - Map map1 = new Object2ObjectOpenHashMap<>(); -- this.subProviders.forEach((p_288263_) -> { -+ this.getTables().forEach((p_288263_) -> { - p_288263_.provider().get().generate((p_288259_, p_288260_) -> { - ResourceLocation resourcelocation1 = map1.put(RandomSequence.seedForKey(p_288259_), p_288259_); - if (resourcelocation1 != null) { -@@ -65,13 +_,8 @@ - } - }); +@@ -62,7 +_,7 @@ + private CompletableFuture run(CachedOutput p_327970_, HolderLookup.Provider p_331092_) { + WritableRegistry writableregistry = new MappedRegistry<>(Registries.LOOT_TABLE, Lifecycle.experimental()); + Map map = new Object2ObjectOpenHashMap<>(); +- this.subProviders.forEach(p_325858_ -> p_325858_.provider().get().generate(p_331092_, (p_325864_, p_325865_) -> { ++ this.getTables().forEach(p_325858_ -> p_325858_.provider().get().generate(p_331092_, (p_325864_, p_325865_) -> { + ResourceLocation resourcelocation = sequenceIdForLootTable(p_325864_); + ResourceLocation resourcelocation1 = map.put(RandomSequence.seedForKey(resourcelocation), resourcelocation); + if (resourcelocation1 != null) { +@@ -78,18 +_,8 @@ + HolderGetter.Provider holdergetter$provider = new RegistryAccess.ImmutableRegistryAccess(List.of(writableregistry)).freeze().asGetterLookup(); + ValidationContext validationcontext = new ValidationContext(problemreporter$collector, LootContextParamSets.ALL_PARAMS, holdergetter$provider); -- for(ResourceLocation resourcelocation : Sets.difference(this.requiredTables, map.keySet())) { -- problemreporter$collector.report("Missing built-in table: " + resourcelocation); -- } -+ validate(map, validationcontext); +- for (ResourceKey resourcekey : Sets.difference(this.requiredTables, writableregistry.registryKeySet())) { +- problemreporter$collector.report("Missing built-in table: " + resourcekey.location()); +- } ++ validate(writableregistry, validationcontext, problemreporter$collector); -- map.forEach((p_278897_, p_278898_) -> { -- p_278898_.validate(validationcontext.setParams(p_278898_.getParamSet()).enterElement("{" + p_278897_ + "}", new LootDataId<>(LootDataType.TABLE, p_278897_))); -- }); - Multimap multimap = problemreporter$collector.get(); - if (!multimap.isEmpty()) { - multimap.forEach((p_124446_, p_124447_) -> { -@@ -88,6 +_,20 @@ - return new CompletableFuture[p_253403_]; - })); - } -+ } +- writableregistry.holders() +- .forEach( +- p_325854_ -> p_325854_.value() +- .validate( +- validationcontext.setParams(p_325854_.value().getParamSet()) +- .enterElement("{" + p_325854_.key().location() + "}", p_325854_.key()) +- ) +- ); + Multimap multimap = problemreporter$collector.get(); + if (!multimap.isEmpty()) { + multimap.forEach((p_124446_, p_124447_) -> LOGGER.warn("Found validation problem in {}: {}", p_124446_, p_124447_)); +@@ -111,6 +_,21 @@ + @Override + public final String getName() { + return "Loot Tables"; ++ } + -+ public List getTables() { -+ return this.subProviders; -+ } ++ public List getTables() { ++ return this.subProviders; ++ } + -+ protected void validate(Map map, ValidationContext validationcontext) { -+ for(ResourceLocation resourcelocation : Sets.difference(this.requiredTables, map.keySet())) { -+ validationcontext.reportProblem("Missing built-in table: " + resourcelocation); -+ } ++ protected void validate(net.minecraft.core.Registry map, ValidationContext validationcontext, ProblemReporter report) { ++ for (ResourceKey resourcekey : Sets.difference(this.requiredTables, map.registryKeySet())) { ++ report.report("Missing built-in table: " + resourcekey.location()); ++ } + -+ map.forEach((p_278897_, p_278898_) -> { -+ p_278898_.validate(validationcontext.setParams(p_278898_.getParamSet()).enterElement("{" + p_278897_ + "}", new LootDataId<>(LootDataType.TABLE, p_278897_))); -+ }); - } ++ map.holders().forEach(table -> table.value().validate( ++ validationcontext.setParams(table.value().getParamSet()) ++ .enterElement("{" + table.key().location() + "}", table.key()) ++ )); + } - public final String getName() { + public static record SubProviderEntry(Supplier provider, LootContextParamSet paramSet) { diff --git a/patches/minecraft/net/minecraft/data/recipes/RecipeOutput.java.patch b/patches/minecraft/net/minecraft/data/recipes/RecipeOutput.java.patch index 6e4313a92f..db6f969a5e 100644 --- a/patches/minecraft/net/minecraft/data/recipes/RecipeOutput.java.patch +++ b/patches/minecraft/net/minecraft/data/recipes/RecipeOutput.java.patch @@ -1,20 +1,23 @@ --- a/net/minecraft/data/recipes/RecipeOutput.java +++ b/net/minecraft/data/recipes/RecipeOutput.java -@@ -7,7 +_,16 @@ +@@ -7,7 +_,19 @@ import net.minecraft.world.item.crafting.Recipe; public interface RecipeOutput { -- void accept(ResourceLocation p_310578_, Recipe p_312265_, @Nullable AdvancementHolder p_310407_); -+ default void accept(ResourceLocation id, Recipe recipe, @Nullable AdvancementHolder advancement) { -+ if (advancement == null) -+ accept(id, recipe, null, null); -+ else { -+ var json = net.minecraft.Util.getOrThrow(Advancement.CODEC.encodeStart(com.mojang.serialization.JsonOps.INSTANCE, advancement.value()), IllegalStateException::new); -+ accept(id, recipe, advancement.id(), json); -+ } -+ } +- void accept(ResourceLocation p_310578_, Recipe p_312265_, @Nullable AdvancementHolder p_310407_); ++ default void accept(ResourceLocation id, Recipe recipe, @Nullable AdvancementHolder advancement) { ++ if (advancement == null) { ++ accept(id, recipe, null, null); ++ } else { ++ var ops = registry().createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE); ++ var json = Advancement.CODEC.encodeStart(ops, advancement.value()).getOrThrow(IllegalStateException::new); ++ accept(id, recipe, advancement.id(), json); ++ } ++ } + -+ void accept(ResourceLocation id, Recipe recipe, @Nullable ResourceLocation advancementId, @Nullable com.google.gson.JsonElement advancement); ++ void accept(ResourceLocation id, Recipe recipe, @Nullable ResourceLocation advancementId, @Nullable com.google.gson.JsonElement advancement); ++ ++ net.minecraft.core.HolderLookup.Provider registry(); - Advancement.Builder advancement(); + Advancement.Builder advancement(); } diff --git a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch index cbc898cf46..1f8a839f71 100644 --- a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch @@ -1,38 +1,55 @@ --- a/net/minecraft/data/recipes/RecipeProvider.java +++ b/net/minecraft/data/recipes/RecipeProvider.java -@@ -87,13 +_,15 @@ - final Set set = Sets.newHashSet(); - final List> list = new ArrayList<>(); - this.buildRecipes(new RecipeOutput() { -- public void accept(ResourceLocation p_312383_, Recipe p_312007_, @Nullable AdvancementHolder p_311384_) { -+ public void accept(ResourceLocation p_312383_, Recipe p_312007_, @Nullable ResourceLocation advancementId, @Nullable com.google.gson.JsonElement advancement) { - if (!set.add(p_312383_)) { - throw new IllegalStateException("Duplicate recipe " + p_312383_); - } else { - list.add(DataProvider.saveStable(p_254020_, Recipe.CODEC, p_312007_, RecipeProvider.this.recipePathProvider.json(p_312383_))); -- if (p_311384_ != null) { -- list.add(DataProvider.saveStable(p_254020_, Advancement.CODEC, p_311384_.value(), RecipeProvider.this.advancementPathProvider.json(p_311384_.id()))); -+ if (advancement != null) { -+ var saveAdvancementFuture = saveAdvancement(p_254020_, advancementId, advancement); -+ if (saveAdvancementFuture != null) -+ list.add(saveAdvancementFuture); - } - - } -@@ -106,6 +_,16 @@ - return CompletableFuture.allOf(list.toArray((p_253414_) -> { - return new CompletableFuture[p_253414_]; - })); -+ } +@@ -83,21 +_,16 @@ + this.buildRecipes( + new RecipeOutput() { + @Override +- public void accept(ResourceLocation p_312383_, Recipe p_312007_, @Nullable AdvancementHolder p_311384_) { ++ public void accept(ResourceLocation p_312383_, Recipe p_312007_, @Nullable ResourceLocation advancementId, @Nullable com.google.gson.JsonElement advancement) { + if (!set.add(p_312383_)) { + throw new IllegalStateException("Duplicate recipe " + p_312383_); + } else { + list.add(DataProvider.saveStable(p_331109_, p_328892_, Recipe.CODEC, p_312007_, RecipeProvider.this.recipePathProvider.json(p_312383_))); +- if (p_311384_ != null) { +- list.add( +- DataProvider.saveStable( +- p_331109_, +- p_328892_, +- Advancement.CODEC, +- p_311384_.value(), +- RecipeProvider.this.advancementPathProvider.json(p_311384_.id()) +- ) +- ); ++ if (advancement != null) { ++ var saveAdvancementFuture = saveAdvancement(p_331109_, advancementId, advancement); ++ if (saveAdvancementFuture != null) { ++ list.add(saveAdvancementFuture); ++ } + } + } + } +@@ -106,9 +_,24 @@ + public Advancement.Builder advancement() { + return Advancement.Builder.recipeAdvancement().parent(RecipeBuilder.ROOT_RECIPE_ADVANCEMENT); + } + -+ /** -+ * Called every time a recipe is saved to also save the advancement JSON if it exists. -+ * -+ * @return A completable future that saves the advancement to disk, or null to cancel saving the advancement. -+ */ -+ @Nullable -+ protected CompletableFuture saveAdvancement(CachedOutput output, ResourceLocation advancementId, com.google.gson.JsonElement advancement) { -+ return DataProvider.saveStable(output, advancement, this.advancementPathProvider.json(advancementId)); - } ++ @Override ++ public HolderLookup.Provider registry() { ++ return p_328892_; ++ } + } + ); + return CompletableFuture.allOf(list.toArray(CompletableFuture[]::new)); ++ } ++ ++ /** ++ * Called every time a recipe is saved to also save the advancement JSON if it exists. ++ * ++ * @return A completable future that saves the advancement to disk, or null to cancel saving the advancement. ++ */ ++ @Nullable ++ protected CompletableFuture saveAdvancement(CachedOutput output, ResourceLocation advancementId, com.google.gson.JsonElement advancement) { ++ return DataProvider.saveStable(output, advancement, this.advancementPathProvider.json(advancementId)); + } - protected CompletableFuture buildAdvancement(CachedOutput p_253674_, AdvancementHolder p_297687_) { + protected CompletableFuture buildAdvancement(CachedOutput p_253674_, HolderLookup.Provider p_335995_, AdvancementHolder p_297687_) { diff --git a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch index 6e1533edc9..334973dcaa 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch @@ -1,42 +1,46 @@ --- a/net/minecraft/data/registries/RegistriesDatapackGenerator.java +++ b/net/minecraft/data/registries/RegistriesDatapackGenerator.java -@@ -22,16 +_,27 @@ - private static final Logger LOGGER = LogUtils.getLogger(); - private final PackOutput output; - private final CompletableFuture registries; -+ private final java.util.function.Predicate namespacePredicate; +@@ -22,10 +_,21 @@ + private static final Logger LOGGER = LogUtils.getLogger(); + private final PackOutput output; + private final CompletableFuture registries; ++ private final java.util.function.Predicate namespacePredicate; - public RegistriesDatapackGenerator(PackOutput p_256643_, CompletableFuture p_255780_) { -+ this(p_256643_, p_255780_, null); -+ } + public RegistriesDatapackGenerator(PackOutput p_256643_, CompletableFuture p_255780_) { ++ this(p_256643_, p_255780_, null); ++ } + -+ public RegistriesDatapackGenerator(PackOutput p_256643_, CompletableFuture p_255780_, @org.jetbrains.annotations.Nullable java.util.Set modIds) { -+ this.namespacePredicate = modIds == null ? namespace -> true : modIds::contains; - this.registries = p_255780_; - this.output = p_256643_; - } ++ public RegistriesDatapackGenerator(PackOutput p_256643_, CompletableFuture p_255780_, @org.jetbrains.annotations.Nullable java.util.Set modIds) { + this.registries = p_255780_; + this.output = p_256643_; ++ this.namespacePredicate = modIds == null ? namespace -> true : modIds::contains; ++ } ++ ++ /** Forge: Call this to get the registry holder lookup provider that includes elements added via {@link net.minecraftforge.common.data.DatapackBuiltinEntriesProvider} */ ++ public CompletableFuture getRegistryProvider() { ++ return registries; + } -+ /** Forge: Call this to get the registry holder lookup provider that includes elements added via {@link net.minecraftforge.common.data.DatapackBuiltinEntriesProvider} */ -+ public CompletableFuture getRegistryProvider() { -+ return registries; -+ } -+ - public CompletableFuture run(CachedOutput p_255785_) { - return this.registries.thenCompose((p_256533_) -> { - DynamicOps dynamicops = RegistryOps.create(JsonOps.INSTANCE, p_256533_); -- return CompletableFuture.allOf(RegistryDataLoader.WORLDGEN_REGISTRIES.stream().flatMap((p_256552_) -> { -+ return CompletableFuture.allOf(RegistryDataLoader.getWorldGenAndDimensionStream().flatMap((p_256552_) -> { - return this.dumpRegistryCap(p_255785_, p_256533_, dynamicops, p_256552_).stream(); - }).toArray((p_255809_) -> { - return new CompletableFuture[p_255809_]; -@@ -42,8 +_,8 @@ - private Optional> dumpRegistryCap(CachedOutput p_256502_, HolderLookup.Provider p_256492_, DynamicOps p_256000_, RegistryDataLoader.RegistryData p_256449_) { - ResourceKey> resourcekey = p_256449_.key(); - return p_256492_.lookup(resourcekey).map((p_255847_) -> { -- PackOutput.PathProvider packoutput$pathprovider = this.output.createPathProvider(PackOutput.Target.DATA_PACK, resourcekey.location().getPath()); -- return CompletableFuture.allOf(p_255847_.listElements().map((p_256105_) -> { -+ PackOutput.PathProvider packoutput$pathprovider = this.output.createPathProvider(PackOutput.Target.DATA_PACK, net.minecraftforge.common.ForgeHooks.prefixNamespace(resourcekey.location())); -+ return CompletableFuture.allOf(p_255847_.listElements().filter(holder -> this.namespacePredicate.test(holder.key().location().getNamespace())).map((p_256105_) -> { - return dumpValue(packoutput$pathprovider.json(p_256105_.key().location()), p_256502_, p_256000_, p_256449_.elementCodec(), p_256105_.value()); - }).toArray((p_256279_) -> { - return new CompletableFuture[p_256279_]; + @Override +@@ -35,8 +_,7 @@ + p_325918_ -> { + DynamicOps dynamicops = p_325918_.createSerializationContext(JsonOps.INSTANCE); + return CompletableFuture.allOf( +- RegistryDataLoader.WORLDGEN_REGISTRIES +- .stream() ++ RegistryDataLoader.getWorldGenAndDimensionStream() + .flatMap(p_256552_ -> this.dumpRegistryCap(p_255785_, p_325918_, dynamicops, (RegistryDataLoader.RegistryData)p_256552_).stream()) + .toArray(CompletableFuture[]::new) + ); +@@ -52,9 +_,10 @@ + .map( + p_255847_ -> { + PackOutput.PathProvider packoutput$pathprovider = this.output +- .createPathProvider(PackOutput.Target.DATA_PACK, resourcekey.location().getPath()); ++ .createPathProvider(PackOutput.Target.DATA_PACK, net.minecraftforge.common.ForgeHooks.prefixNamespace(resourcekey.location())); + return CompletableFuture.allOf( + p_255847_.listElements() ++ .filter(holder -> this.namespacePredicate.test(holder.key().location().getNamespace())) + .map( + p_256105_ -> dumpValue( + packoutput$pathprovider.json(p_256105_.key().location()), diff --git a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch index ca01c44ae9..a9e6ebe83e 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/data/registries/RegistryPatchGenerator.java +++ b/net/minecraft/data/registries/RegistryPatchGenerator.java -@@ -17,7 +_,7 @@ - return p_310881_.thenApply((p_309945_) -> { - RegistryAccess.Frozen registryaccess$frozen = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); - Cloner.Factory cloner$factory = new Cloner.Factory(); -- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach((p_313050_) -> { -+ RegistryDataLoader.getWorldGenAndDimensionStream().forEach((p_313050_) -> { - p_313050_.runWithArguments(cloner$factory::addCodec); - }); - RegistrySetBuilder.PatchedRegistries registrysetbuilder$patchedregistries = p_310262_.buildPatch(registryaccess$frozen, p_309945_, cloner$factory); +@@ -20,7 +_,7 @@ + p_309945_ -> { + RegistryAccess.Frozen registryaccess$frozen = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); + Cloner.Factory cloner$factory = new Cloner.Factory(); +- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach(p_313050_ -> p_313050_.runWithArguments(cloner$factory::addCodec)); ++ RegistryDataLoader.getWorldGenAndDimensionStream().forEach(p_313050_ -> p_313050_.runWithArguments(cloner$factory::addCodec)); + RegistrySetBuilder.PatchedRegistries registrysetbuilder$patchedregistries = p_310262_.buildPatch( + registryaccess$frozen, p_309945_, cloner$factory + ); diff --git a/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch b/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch index 58f3cdee90..8b05c87b0d 100644 --- a/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/data/registries/VanillaRegistries.java +++ b/net/minecraft/data/registries/VanillaRegistries.java -@@ -36,6 +_,7 @@ +@@ -60,6 +_,7 @@ + .add(Registries.WOLF_VARIANT, WolfVariants::bootstrap) + .add(Registries.DAMAGE_TYPE, DamageTypes::bootstrap) + .add(Registries.BANNER_PATTERN, BannerPatterns::bootstrap); ++ public static final List>> DATAPACK_REGISTRY_KEYS = BUILDER.getEntryKeys(); - public class VanillaRegistries { - private static final RegistrySetBuilder BUILDER = (new RegistrySetBuilder()).add(Registries.DIMENSION_TYPE, DimensionTypes::bootstrap).add(Registries.CONFIGURED_CARVER, (RegistrySetBuilder.RegistryBootstrap)Carvers::bootstrap).add(Registries.CONFIGURED_FEATURE, (RegistrySetBuilder.RegistryBootstrap)FeatureUtils::bootstrap).add(Registries.PLACED_FEATURE, PlacementUtils::bootstrap).add(Registries.STRUCTURE, Structures::bootstrap).add(Registries.STRUCTURE_SET, StructureSets::bootstrap).add(Registries.PROCESSOR_LIST, ProcessorLists::bootstrap).add(Registries.TEMPLATE_POOL, Pools::bootstrap).add(Registries.BIOME, BiomeData::bootstrap).add(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST, MultiNoiseBiomeSourceParameterLists::bootstrap).add(Registries.NOISE, NoiseData::bootstrap).add(Registries.DENSITY_FUNCTION, NoiseRouterData::bootstrap).add(Registries.NOISE_SETTINGS, NoiseGeneratorSettings::bootstrap).add(Registries.WORLD_PRESET, WorldPresets::bootstrap).add(Registries.FLAT_LEVEL_GENERATOR_PRESET, FlatLevelGeneratorPresets::bootstrap).add(Registries.CHAT_TYPE, ChatType::bootstrap).add(Registries.TRIM_PATTERN, TrimPatterns::bootstrap).add(Registries.TRIM_MATERIAL, TrimMaterials::bootstrap).add(Registries.DAMAGE_TYPE, DamageTypes::bootstrap); -+ public static final List>> DATAPACK_REGISTRY_KEYS = BUILDER.getEntryKeys(); - - private static void validateThatAllBiomeFeaturesHaveBiomeFilter(HolderLookup.Provider p_256242_) { - validateThatAllBiomeFeaturesHaveBiomeFilter(p_256242_.lookupOrThrow(Registries.PLACED_FEATURE), p_256242_.lookupOrThrow(Registries.BIOME)); + private static void validateThatAllBiomeFeaturesHaveBiomeFilter(HolderLookup.Provider p_256242_) { + validateThatAllBiomeFeaturesHaveBiomeFilter(p_256242_.lookupOrThrow(Registries.PLACED_FEATURE), p_256242_.lookupOrThrow(Registries.BIOME)); diff --git a/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch index 4e557533f8..1780e78625 100644 --- a/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch @@ -1,16 +1,17 @@ --- a/net/minecraft/data/tags/BannerPatternTagsProvider.java +++ b/net/minecraft/data/tags/BannerPatternTagsProvider.java -@@ -9,8 +_,13 @@ +@@ -9,8 +_,14 @@ import net.minecraft.world.level.block.entity.BannerPatterns; public class BannerPatternTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #BannerPatternTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public BannerPatternTagsProvider(PackOutput p_256451_, CompletableFuture p_256420_) { - super(p_256451_, Registries.BANNER_PATTERN, p_256420_); -+ } -+ public BannerPatternTagsProvider(PackOutput p_256451_, CompletableFuture p_256420_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256451_, Registries.BANNER_PATTERN, p_256420_, modId, existingFileHelper); - } ++ /** @deprecated Forge: Use the {@linkplain #BannerPatternTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ ++ @Deprecated + public BannerPatternTagsProvider(PackOutput p_256451_, CompletableFuture p_256420_) { + super(p_256451_, Registries.BANNER_PATTERN, p_256420_); ++ } ++ ++ public BannerPatternTagsProvider(PackOutput p_256451_, CompletableFuture p_256420_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256451_, Registries.BANNER_PATTERN, p_256420_, modId, existingFileHelper); + } - protected void addTags(HolderLookup.Provider p_255819_) { + @Override diff --git a/patches/minecraft/net/minecraft/data/tags/BiomeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/BiomeTagsProvider.java.patch index 445ddaeaad..4f42d81bad 100644 --- a/patches/minecraft/net/minecraft/data/tags/BiomeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/BiomeTagsProvider.java.patch @@ -1,16 +1,13 @@ --- a/net/minecraft/data/tags/BiomeTagsProvider.java +++ b/net/minecraft/data/tags/BiomeTagsProvider.java -@@ -10,8 +_,13 @@ - import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; +@@ -14,6 +_,10 @@ + super(p_255800_, Registries.BIOME, p_256205_); + } - public class BiomeTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #BiomeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public BiomeTagsProvider(PackOutput p_255800_, CompletableFuture p_256205_) { - super(p_255800_, Registries.BIOME, p_256205_); -+ } -+ public BiomeTagsProvider(PackOutput p_255800_, CompletableFuture p_256205_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_255800_, Registries.BIOME, p_256205_, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_256485_) { ++ public BiomeTagsProvider(PackOutput p_255800_, CompletableFuture p_256205_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_255800_, Registries.BIOME, p_256205_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_256485_) { + this.tag(BiomeTags.IS_DEEP_OCEAN).add(Biomes.DEEP_FROZEN_OCEAN).add(Biomes.DEEP_COLD_OCEAN).add(Biomes.DEEP_OCEAN).add(Biomes.DEEP_LUKEWARM_OCEAN); diff --git a/patches/minecraft/net/minecraft/data/tags/CatVariantTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/CatVariantTagsProvider.java.patch index 71447d76a2..395185634e 100644 --- a/patches/minecraft/net/minecraft/data/tags/CatVariantTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/CatVariantTagsProvider.java.patch @@ -1,16 +1,13 @@ --- a/net/minecraft/data/tags/CatVariantTagsProvider.java +++ b/net/minecraft/data/tags/CatVariantTagsProvider.java -@@ -8,8 +_,13 @@ - import net.minecraft.world.entity.animal.CatVariant; +@@ -12,6 +_,10 @@ + super(p_256547_, Registries.CAT_VARIANT, p_256090_); + } - public class CatVariantTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #CatVariantTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public CatVariantTagsProvider(PackOutput p_256547_, CompletableFuture p_256090_) { - super(p_256547_, Registries.CAT_VARIANT, p_256090_); -+ } -+ public CatVariantTagsProvider(PackOutput p_256547_, CompletableFuture p_256090_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256547_, Registries.CAT_VARIANT, p_256090_, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_256078_) { ++ public CatVariantTagsProvider(PackOutput p_256547_, CompletableFuture p_256090_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256547_, Registries.CAT_VARIANT, p_256090_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_256078_) { + this.tag(CatVariantTags.DEFAULT_SPAWNS) diff --git a/patches/minecraft/net/minecraft/data/tags/DamageTypeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/DamageTypeTagsProvider.java.patch index 655e071368..1422630273 100644 --- a/patches/minecraft/net/minecraft/data/tags/DamageTypeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/DamageTypeTagsProvider.java.patch @@ -1,16 +1,13 @@ --- a/net/minecraft/data/tags/DamageTypeTagsProvider.java +++ b/net/minecraft/data/tags/DamageTypeTagsProvider.java -@@ -9,8 +_,13 @@ - import net.minecraft.world.damagesource.DamageTypes; +@@ -13,6 +_,10 @@ + super(p_270719_, Registries.DAMAGE_TYPE, p_270256_); + } - public class DamageTypeTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #DamageTypeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public DamageTypeTagsProvider(PackOutput p_270719_, CompletableFuture p_270256_) { - super(p_270719_, Registries.DAMAGE_TYPE, p_270256_); -+ } -+ public DamageTypeTagsProvider(PackOutput p_270719_, CompletableFuture p_270256_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_270719_, Registries.DAMAGE_TYPE, p_270256_, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_270108_) { ++ public DamageTypeTagsProvider(PackOutput p_270719_, CompletableFuture p_270256_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_270719_, Registries.DAMAGE_TYPE, p_270256_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_270108_) { + this.tag(DamageTypeTags.DAMAGES_HELMET).add(DamageTypes.FALLING_ANVIL, DamageTypes.FALLING_BLOCK, DamageTypes.FALLING_STALACTITE); diff --git a/patches/minecraft/net/minecraft/data/tags/EnchantmentTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/EnchantmentTagsProvider.java.patch new file mode 100644 index 0000000000..3d25ddb397 --- /dev/null +++ b/patches/minecraft/net/minecraft/data/tags/EnchantmentTagsProvider.java.patch @@ -0,0 +1,15 @@ +--- a/net/minecraft/data/tags/EnchantmentTagsProvider.java ++++ b/net/minecraft/data/tags/EnchantmentTagsProvider.java +@@ -16,7 +_,11 @@ + private final FeatureFlagSet enabledFeatures; + + public EnchantmentTagsProvider(PackOutput p_332794_, CompletableFuture p_331070_, FeatureFlagSet p_328046_) { +- super(p_332794_, Registries.ENCHANTMENT, p_331070_, p_328708_ -> p_328708_.builtInRegistryHolder().key()); ++ this(p_332794_, p_331070_, p_328046_, "vanilla", null); ++ } ++ ++ public EnchantmentTagsProvider(PackOutput p_332794_, CompletableFuture p_331070_, FeatureFlagSet p_328046_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_332794_, Registries.ENCHANTMENT, p_331070_, p_328708_ -> p_328708_.builtInRegistryHolder().key(), modId, existingFileHelper); + this.enabledFeatures = p_328046_; + } + diff --git a/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch index 4d5ef567d8..19153f4363 100644 --- a/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch @@ -1,19 +1,13 @@ --- a/net/minecraft/data/tags/EntityTypeTagsProvider.java +++ b/net/minecraft/data/tags/EntityTypeTagsProvider.java -@@ -8,10 +_,15 @@ - import net.minecraft.world.entity.EntityType; +@@ -12,6 +_,10 @@ + super(p_256095_, Registries.ENTITY_TYPE, p_256572_, p_256665_ -> p_256665_.builtInRegistryHolder().key()); + } - public class EntityTypeTagsProvider extends IntrinsicHolderTagsProvider> { -+ /** @deprecated Forge: Use the {@linkplain #EntityTypeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public EntityTypeTagsProvider(PackOutput p_256095_, CompletableFuture p_256572_) { -+ this(p_256095_, p_256572_, "vanilla", null); -+ } -+ public EntityTypeTagsProvider(PackOutput p_256095_, CompletableFuture p_256572_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - super(p_256095_, Registries.ENTITY_TYPE, p_256572_, (p_256665_) -> { - return p_256665_.builtInRegistryHolder().key(); -- }); -+ }, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_255894_) { ++ public EntityTypeTagsProvider(PackOutput p_256095_, CompletableFuture p_256572_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256095_, Registries.ENTITY_TYPE, p_256572_, p_256665_ -> p_256665_.builtInRegistryHolder().key(), modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_255894_) { + this.tag(EntityTypeTags.SKELETONS).add(EntityType.SKELETON, EntityType.STRAY, EntityType.WITHER_SKELETON, EntityType.SKELETON_HORSE); diff --git a/patches/minecraft/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java.patch index 5c9c2388eb..2b5be808c0 100644 --- a/patches/minecraft/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java.patch @@ -1,16 +1,13 @@ --- a/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java +++ b/net/minecraft/data/tags/FlatLevelGeneratorPresetTagsProvider.java -@@ -9,8 +_,13 @@ - import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorPresets; +@@ -13,6 +_,10 @@ + super(p_256604_, Registries.FLAT_LEVEL_GENERATOR_PRESET, p_255962_); + } - public class FlatLevelGeneratorPresetTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #FlatLevelGeneratorPresetTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public FlatLevelGeneratorPresetTagsProvider(PackOutput p_256604_, CompletableFuture p_255962_) { - super(p_256604_, Registries.FLAT_LEVEL_GENERATOR_PRESET, p_255962_); -+ } -+ public FlatLevelGeneratorPresetTagsProvider(PackOutput p_256604_, CompletableFuture p_255962_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256604_, Registries.FLAT_LEVEL_GENERATOR_PRESET, p_255962_, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_255741_) { ++ public FlatLevelGeneratorPresetTagsProvider(PackOutput p_256604_, CompletableFuture p_255962_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256604_, Registries.FLAT_LEVEL_GENERATOR_PRESET, p_255962_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_255741_) { + this.tag(FlatLevelGeneratorPresetTags.VISIBLE) diff --git a/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch index 8016283748..5735f3d4cb 100644 --- a/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch @@ -1,19 +1,13 @@ --- a/net/minecraft/data/tags/FluidTagsProvider.java +++ b/net/minecraft/data/tags/FluidTagsProvider.java -@@ -9,10 +_,15 @@ - import net.minecraft.world.level.material.Fluids; +@@ -13,6 +_,10 @@ + super(p_255941_, Registries.FLUID, p_256600_, p_256474_ -> p_256474_.builtInRegistryHolder().key()); + } - public class FluidTagsProvider extends IntrinsicHolderTagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #FluidTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public FluidTagsProvider(PackOutput p_255941_, CompletableFuture p_256600_) { -+ this(p_255941_, p_256600_, "vanilla", null); -+ } -+ public FluidTagsProvider(PackOutput p_255941_, CompletableFuture p_256600_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - super(p_255941_, Registries.FLUID, p_256600_, (p_256474_) -> { - return p_256474_.builtInRegistryHolder().key(); -- }); -+ }, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_256366_) { ++ public FluidTagsProvider(PackOutput p_255941_, CompletableFuture p_256600_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_255941_, Registries.FLUID, p_256600_, p_256474_ -> p_256474_.builtInRegistryHolder().key(), modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_256366_) { + this.tag(FluidTags.WATER).add(Fluids.WATER, Fluids.FLOWING_WATER); diff --git a/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch index dd939fe11a..15b9d25987 100644 --- a/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch @@ -1,19 +1,13 @@ --- a/net/minecraft/data/tags/GameEventTagsProvider.java +++ b/net/minecraft/data/tags/GameEventTagsProvider.java -@@ -13,10 +_,15 @@ - @VisibleForTesting - static final GameEvent[] VIBRATIONS_EXCEPT_FLAP = new GameEvent[]{GameEvent.BLOCK_ATTACH, GameEvent.BLOCK_CHANGE, GameEvent.BLOCK_CLOSE, GameEvent.BLOCK_DESTROY, GameEvent.BLOCK_DETACH, GameEvent.BLOCK_OPEN, GameEvent.BLOCK_PLACE, GameEvent.BLOCK_ACTIVATE, GameEvent.BLOCK_DEACTIVATE, GameEvent.CONTAINER_CLOSE, GameEvent.CONTAINER_OPEN, GameEvent.DRINK, GameEvent.EAT, GameEvent.ELYTRA_GLIDE, GameEvent.ENTITY_DAMAGE, GameEvent.ENTITY_DIE, GameEvent.ENTITY_DISMOUNT, GameEvent.ENTITY_INTERACT, GameEvent.ENTITY_MOUNT, GameEvent.ENTITY_PLACE, GameEvent.ENTITY_ACTION, GameEvent.EQUIP, GameEvent.EXPLODE, GameEvent.FLUID_PICKUP, GameEvent.FLUID_PLACE, GameEvent.HIT_GROUND, GameEvent.INSTRUMENT_PLAY, GameEvent.ITEM_INTERACT_FINISH, GameEvent.LIGHTNING_STRIKE, GameEvent.NOTE_BLOCK_PLAY, GameEvent.PRIME_FUSE, GameEvent.PROJECTILE_LAND, GameEvent.PROJECTILE_SHOOT, GameEvent.SHEAR, GameEvent.SPLASH, GameEvent.STEP, GameEvent.SWIM, GameEvent.TELEPORT, GameEvent.UNEQUIP}; +@@ -59,6 +_,10 @@ + super(p_256060_, Registries.GAME_EVENT, p_255621_); + } -+ /** @deprecated Forge: Use the {@linkplain #GameEventTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public GameEventTagsProvider(PackOutput p_256060_, CompletableFuture p_255621_) { -+ this(p_256060_, p_255621_, "vanilla", null); -+ } -+ public GameEventTagsProvider(PackOutput p_256060_, CompletableFuture p_255621_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - super(p_256060_, Registries.GAME_EVENT, p_255621_, (p_256368_) -> { - return p_256368_.builtInRegistryHolder().key(); -- }); -+ }, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_255981_) { ++ public GameEventTagsProvider(PackOutput p_256060_, CompletableFuture p_255621_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256060_, Registries.GAME_EVENT, p_255621_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_255981_) { + this.tag(GameEventTags.VIBRATIONS).addAll(VIBRATIONS_EXCEPT_FLAP).addAll(VibrationSystem.RESONANCE_EVENTS).add(GameEvent.FLAP.key()); diff --git a/patches/minecraft/net/minecraft/data/tags/InstrumentTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/InstrumentTagsProvider.java.patch index be1953cab3..baa6448005 100644 --- a/patches/minecraft/net/minecraft/data/tags/InstrumentTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/InstrumentTagsProvider.java.patch @@ -1,16 +1,13 @@ --- a/net/minecraft/data/tags/InstrumentTagsProvider.java +++ b/net/minecraft/data/tags/InstrumentTagsProvider.java -@@ -9,8 +_,13 @@ - import net.minecraft.world.item.Instruments; +@@ -13,6 +_,10 @@ + super(p_256418_, Registries.INSTRUMENT, p_256038_); + } - public class InstrumentTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #InstrumentTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public InstrumentTagsProvider(PackOutput p_256418_, CompletableFuture p_256038_) { - super(p_256418_, Registries.INSTRUMENT, p_256038_); -+ } -+ public InstrumentTagsProvider(PackOutput p_256418_, CompletableFuture p_256038_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256418_, Registries.INSTRUMENT, p_256038_, modId, existingFileHelper); - } - - protected void addTags(HolderLookup.Provider p_256291_) { ++ public InstrumentTagsProvider(PackOutput p_256418_, CompletableFuture p_256038_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256418_, Registries.INSTRUMENT, p_256038_, modId, existingFileHelper); ++ } ++ + @Override + protected void addTags(HolderLookup.Provider p_256291_) { + this.tag(InstrumentTags.REGULAR_GOAT_HORNS) diff --git a/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch index 4511bc0973..4e851aca45 100644 --- a/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch @@ -1,61 +1,73 @@ --- a/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java +++ b/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java -@@ -13,26 +_,40 @@ +@@ -13,37 +_,50 @@ public abstract class IntrinsicHolderTagsProvider extends TagsProvider { - private final Function> keyExtractor; + private final Function> keyExtractor; -+ /** -+ * @deprecated Forge: Use the {@linkplain #IntrinsicHolderTagsProvider(PackOutput, ResourceKey, CompletableFuture, Function, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ -+ @Deprecated - public IntrinsicHolderTagsProvider(PackOutput p_256164_, ResourceKey> p_256155_, CompletableFuture p_256488_, Function> p_256168_) { -- super(p_256164_, p_256155_, p_256488_); -+ this(p_256164_, p_256155_, p_256488_, p_256168_, "vanilla", null); -+ } -+ public IntrinsicHolderTagsProvider(PackOutput p_256164_, ResourceKey> p_256155_, CompletableFuture p_256488_, Function> p_256168_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256164_, p_256155_, p_256488_, modId, existingFileHelper); - this.keyExtractor = p_256168_; - } - -+ /** -+ * @deprecated Forge: Use the {@linkplain #IntrinsicHolderTagsProvider(PackOutput, ResourceKey, CompletableFuture, CompletableFuture, Function, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ -+ @Deprecated - public IntrinsicHolderTagsProvider(PackOutput p_275304_, ResourceKey> p_275709_, CompletableFuture p_275227_, CompletableFuture> p_275311_, Function> p_275566_) { -- super(p_275304_, p_275709_, p_275227_, p_275311_); -+ this(p_275304_, p_275709_, p_275227_, p_275311_, p_275566_, "vanilla", null); -+ } -+ public IntrinsicHolderTagsProvider(PackOutput p_275304_, ResourceKey> p_275709_, CompletableFuture p_275227_, CompletableFuture> p_275311_, Function> p_275566_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_275304_, p_275709_, p_275227_, p_275311_, modId, existingFileHelper); - this.keyExtractor = p_275566_; - } - - protected IntrinsicHolderTagsProvider.IntrinsicTagAppender tag(TagKey p_255730_) { - TagBuilder tagbuilder = this.getOrCreateRawBuilder(p_255730_); -- return new IntrinsicHolderTagsProvider.IntrinsicTagAppender<>(tagbuilder, this.keyExtractor); -+ return new IntrinsicHolderTagsProvider.IntrinsicTagAppender<>(tagbuilder, this.keyExtractor, this.modId); - } - -- public static class IntrinsicTagAppender extends TagsProvider.TagAppender { -+ public static class IntrinsicTagAppender extends TagsProvider.TagAppender implements net.minecraftforge.common.extensions.IForgeIntrinsicHolderTagAppender { - private final Function> keyExtractor; - -- IntrinsicTagAppender(TagBuilder p_256108_, Function> p_256433_) { -- super(p_256108_); -+ IntrinsicTagAppender(TagBuilder p_256108_, Function> p_256433_, String modId) { -+ super(p_256108_, modId); - this.keyExtractor = p_256433_; - } - -@@ -50,6 +_,11 @@ - public final IntrinsicHolderTagsProvider.IntrinsicTagAppender add(T... p_255868_) { - Stream.of(p_255868_).map(this.keyExtractor).forEach(this::add); - return this; -+ } ++ public IntrinsicHolderTagsProvider(PackOutput p_256164_, ResourceKey> p_256155_, CompletableFuture p_256488_, Function> p_256168_) { ++ this(p_256164_, p_256155_, p_256488_, p_256168_, "vanilla", null); ++ } + -+ @Override -+ public final ResourceKey getKey(T value) { -+ return this.keyExtractor.apply(value); - } - } + public IntrinsicHolderTagsProvider( + PackOutput p_256164_, + ResourceKey> p_256155_, + CompletableFuture p_256488_, +- Function> p_256168_ ++ Function> p_256168_, ++ String modId, ++ @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper + ) { +- super(p_256164_, p_256155_, p_256488_); ++ super(p_256164_, p_256155_, p_256488_, modId, existingFileHelper); + this.keyExtractor = p_256168_; + } + ++ ++ public IntrinsicHolderTagsProvider(PackOutput p_275304_, ResourceKey> p_275709_, CompletableFuture p_275227_, CompletableFuture> p_275311_, Function> p_275566_) { ++ this(p_275304_, p_275709_, p_275227_, p_275311_, p_275566_, "vanilla", null); ++ } ++ + public IntrinsicHolderTagsProvider( + PackOutput p_275304_, + ResourceKey> p_275709_, + CompletableFuture p_275227_, + CompletableFuture> p_275311_, +- Function> p_275566_ ++ Function> p_275566_, ++ String modId, ++ @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper + ) { +- super(p_275304_, p_275709_, p_275227_, p_275311_); ++ super(p_275304_, p_275709_, p_275227_, p_275311_, modId, existingFileHelper); + this.keyExtractor = p_275566_; + } + + protected IntrinsicHolderTagsProvider.IntrinsicTagAppender tag(TagKey p_255730_) { + TagBuilder tagbuilder = this.getOrCreateRawBuilder(p_255730_); +- return new IntrinsicHolderTagsProvider.IntrinsicTagAppender<>(tagbuilder, this.keyExtractor); ++ return new IntrinsicHolderTagsProvider.IntrinsicTagAppender<>(tagbuilder, this.keyExtractor, this.modId); + } + +- public static class IntrinsicTagAppender extends TagsProvider.TagAppender { ++ public static class IntrinsicTagAppender extends TagsProvider.TagAppender implements net.minecraftforge.common.extensions.IForgeIntrinsicHolderTagAppender { + private final Function> keyExtractor; + +- IntrinsicTagAppender(TagBuilder p_256108_, Function> p_256433_) { +- super(p_256108_); ++ IntrinsicTagAppender(TagBuilder p_256108_, Function> p_256433_, String modid) { ++ super(p_256108_, modid); + this.keyExtractor = p_256433_; + } + +@@ -61,6 +_,11 @@ + public final IntrinsicHolderTagsProvider.IntrinsicTagAppender add(T... p_255868_) { + Stream.of(p_255868_).map(this.keyExtractor).forEach(this::add); + return this; ++ } ++ ++ @Override ++ public final ResourceKey getKey(T value) { ++ return this.keyExtractor.apply(value); + } + } } diff --git a/patches/minecraft/net/minecraft/data/tags/ItemTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/ItemTagsProvider.java.patch index e96b2dbe0c..cedc0a5f5d 100644 --- a/patches/minecraft/net/minecraft/data/tags/ItemTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/ItemTagsProvider.java.patch @@ -1,32 +1,36 @@ --- a/net/minecraft/data/tags/ItemTagsProvider.java +++ b/net/minecraft/data/tags/ItemTagsProvider.java -@@ -16,14 +_,28 @@ - private final CompletableFuture> blockTags; - private final Map, TagKey> tagsToCopy = new HashMap<>(); +@@ -19,17 +_,30 @@ + public ItemTagsProvider( + PackOutput p_275343_, CompletableFuture p_275729_, CompletableFuture> p_275322_ + ) { +- super(p_275343_, Registries.ITEM, p_275729_, p_255790_ -> p_255790_.builtInRegistryHolder().key()); ++ this(p_275343_, p_275729_, p_275322_, "vanilla", null); ++ } ++ ++ public ItemTagsProvider( ++ PackOutput p_275343_, CompletableFuture p_275729_, CompletableFuture> p_275322_, ++ String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper ++ ) { ++ super(p_275343_, Registries.ITEM, p_275729_, p_255790_ -> p_255790_.builtInRegistryHolder().key(), modId, existingFileHelper); + this.blockTags = p_275322_; + } -+ /** -+ * @deprecated Forge: Use the {@linkplain #ItemTagsProvider(PackOutput, CompletableFuture, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ -+ @Deprecated - public ItemTagsProvider(PackOutput p_275343_, CompletableFuture p_275729_, CompletableFuture> p_275322_) { -+ this(p_275343_, p_275729_, p_275322_, "vanilla", null); -+ } -+ public ItemTagsProvider(PackOutput p_275343_, CompletableFuture p_275729_, CompletableFuture> p_275322_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - super(p_275343_, Registries.ITEM, p_275729_, (p_255790_) -> { - return p_255790_.builtInRegistryHolder().key(); -- }); -+ }, modId, existingFileHelper); - this.blockTags = p_275322_; - } ++ public ItemTagsProvider(PackOutput p_275204_, CompletableFuture p_275194_, CompletableFuture> p_275207_, CompletableFuture> p_275634_) { ++ this(p_275204_, p_275194_, p_275207_, p_275634_, "vanilla", null); ++ } ++ + public ItemTagsProvider( + PackOutput p_275204_, + CompletableFuture p_275194_, + CompletableFuture> p_275207_, +- CompletableFuture> p_275634_ ++ CompletableFuture> p_275634_, ++ String modId, ++ @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper + ) { +- super(p_275204_, Registries.ITEM, p_275194_, p_275207_, p_274765_ -> p_274765_.builtInRegistryHolder().key()); ++ super(p_275204_, Registries.ITEM, p_275194_, p_275207_, p_274765_ -> p_274765_.builtInRegistryHolder().key(), modId, existingFileHelper); + this.blockTags = p_275634_; + } -+ /** -+ * @deprecated Forge: Use the {@linkplain #ItemTagsProvider(PackOutput, CompletableFuture, CompletableFuture, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ -+ @Deprecated - public ItemTagsProvider(PackOutput p_275204_, CompletableFuture p_275194_, CompletableFuture> p_275207_, CompletableFuture> p_275634_) { -+ this(p_275204_, p_275194_, p_275207_, p_275634_, "vanilla", null); -+ } -+ public ItemTagsProvider(PackOutput p_275204_, CompletableFuture p_275194_, CompletableFuture> p_275207_, CompletableFuture> p_275634_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - super(p_275204_, Registries.ITEM, p_275194_, p_275207_, (p_274765_) -> { - return p_274765_.builtInRegistryHolder().key(); - }); diff --git a/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch index f940879de1..60cd784975 100644 --- a/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch @@ -4,13 +4,13 @@ import net.minecraft.world.entity.decoration.PaintingVariants; public class PaintingVariantTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #PaintingVariantTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public PaintingVariantTagsProvider(PackOutput p_255750_, CompletableFuture p_256184_) { - super(p_255750_, Registries.PAINTING_VARIANT, p_256184_); -+ } -+ public PaintingVariantTagsProvider(PackOutput p_255750_, CompletableFuture p_256184_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_255750_, Registries.PAINTING_VARIANT, p_256184_, modId, existingFileHelper); - } ++ /** @deprecated Forge: Use the {@linkplain #PaintingVariantTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ + public PaintingVariantTagsProvider(PackOutput p_255750_, CompletableFuture p_256184_) { + super(p_255750_, Registries.PAINTING_VARIANT, p_256184_); ++ } ++ ++ public PaintingVariantTagsProvider(PackOutput p_255750_, CompletableFuture p_256184_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_255750_, Registries.PAINTING_VARIANT, p_256184_, modId, existingFileHelper); + } - protected void addTags(HolderLookup.Provider p_256017_) { + @Override diff --git a/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch index 229000879f..ddbedeec2a 100644 --- a/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch @@ -4,13 +4,13 @@ import net.minecraft.world.entity.ai.village.poi.PoiTypes; public class PoiTypeTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #PoiTypeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public PoiTypeTagsProvider(PackOutput p_256012_, CompletableFuture p_256617_) { - super(p_256012_, Registries.POINT_OF_INTEREST_TYPE, p_256617_); -+ } -+ public PoiTypeTagsProvider(PackOutput p_256012_, CompletableFuture p_256617_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256012_, Registries.POINT_OF_INTEREST_TYPE, p_256617_, modId, existingFileHelper); - } ++ /** @deprecated Forge: Use the {@linkplain #PoiTypeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ + public PoiTypeTagsProvider(PackOutput p_256012_, CompletableFuture p_256617_) { + super(p_256012_, Registries.POINT_OF_INTEREST_TYPE, p_256617_); ++ } ++ ++ public PoiTypeTagsProvider(PackOutput p_256012_, CompletableFuture p_256617_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256012_, Registries.POINT_OF_INTEREST_TYPE, p_256617_, modId, existingFileHelper); + } - protected void addTags(HolderLookup.Provider p_256206_) { + @Override diff --git a/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch index 0a0b908a99..8a014741ba 100644 --- a/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch @@ -4,13 +4,13 @@ import net.minecraft.world.level.levelgen.structure.Structure; public class StructureTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #StructureTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public StructureTagsProvider(PackOutput p_256522_, CompletableFuture p_256661_) { - super(p_256522_, Registries.STRUCTURE, p_256661_); -+ } -+ public StructureTagsProvider(PackOutput p_256522_, CompletableFuture p_256661_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_256522_, Registries.STRUCTURE, p_256661_, modId, existingFileHelper); - } ++ /** @deprecated Forge: Use the {@linkplain #StructureTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ + public StructureTagsProvider(PackOutput p_256522_, CompletableFuture p_256661_) { + super(p_256522_, Registries.STRUCTURE, p_256661_); ++ } ++ ++ public StructureTagsProvider(PackOutput p_256522_, CompletableFuture p_256661_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_256522_, Registries.STRUCTURE, p_256661_, modId, existingFileHelper); + } - protected void addTags(HolderLookup.Provider p_256087_) { + @Override diff --git a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch index 207d3ef380..f907d8c118 100644 --- a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch @@ -1,153 +1,168 @@ --- a/net/minecraft/data/tags/TagsProvider.java +++ b/net/minecraft/data/tags/TagsProvider.java -@@ -36,20 +_,48 @@ - private final CompletableFuture> parentProvider; - protected final ResourceKey> registryKey; - protected final Map builders = Maps.newLinkedHashMap(); -+ protected final String modId; -+ @org.jetbrains.annotations.Nullable -+ protected final net.minecraftforge.common.data.ExistingFileHelper existingFileHelper; -+ private final net.minecraftforge.common.data.ExistingFileHelper.IResourceType resourceType; -+ private final net.minecraftforge.common.data.ExistingFileHelper.IResourceType elementResourceType; // FORGE: Resource type for validating required references to datapack registry elements. +@@ -36,26 +_,57 @@ + private final CompletableFuture> parentProvider; + protected final ResourceKey> registryKey; + protected final Map builders = Maps.newLinkedHashMap(); ++ protected final String modId; ++ @org.jetbrains.annotations.Nullable ++ protected final net.minecraftforge.common.data.ExistingFileHelper existingFileHelper; ++ private final net.minecraftforge.common.data.ExistingFileHelper.IResourceType resourceType; ++ private final net.minecraftforge.common.data.ExistingFileHelper.IResourceType elementResourceType; // FORGE: Resource type for validating required references to datapack registry elements. -+ /** -+ * @deprecated Forge: Use the {@linkplain #TagsProvider(PackOutput, ResourceKey, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ - protected TagsProvider(PackOutput p_256596_, ResourceKey> p_255886_, CompletableFuture p_256513_) { -- this(p_256596_, p_255886_, p_256513_, CompletableFuture.completedFuture(TagsProvider.TagLookup.empty())); -+ this(p_256596_, p_255886_, p_256513_, "vanilla", null); -+ } -+ protected TagsProvider(PackOutput p_256596_, ResourceKey> p_255886_, CompletableFuture p_256513_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ this(p_256596_, p_255886_, p_256513_, CompletableFuture.completedFuture(TagsProvider.TagLookup.empty()), modId, existingFileHelper); - } - -+ /** -+ * @deprecated Forge: Use the {@linkplain #TagsProvider(PackOutput, ResourceKey, CompletableFuture, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} -+ */ -+ @Deprecated - protected TagsProvider(PackOutput p_275432_, ResourceKey> p_275476_, CompletableFuture p_275222_, CompletableFuture> p_275565_) { -+ this(p_275432_, p_275476_, p_275222_, p_275565_, "vanilla", null); -+ } -+ protected TagsProvider(PackOutput p_275432_, ResourceKey> p_275476_, CompletableFuture p_275222_, CompletableFuture> p_275565_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { - this.pathProvider = p_275432_.createPathProvider(PackOutput.Target.DATA_PACK, TagManager.getTagDir(p_275476_)); - this.registryKey = p_275476_; - this.parentProvider = p_275565_; - this.lookupProvider = p_275222_; -+ this.modId = modId; -+ this.existingFileHelper = existingFileHelper; -+ this.resourceType = new net.minecraftforge.common.data.ExistingFileHelper.ResourceType(net.minecraft.server.packs.PackType.SERVER_DATA, ".json", TagManager.getTagDir(p_275476_)); -+ this.elementResourceType = new net.minecraftforge.common.data.ExistingFileHelper.ResourceType(net.minecraft.server.packs.PackType.SERVER_DATA, ".json", net.minecraftforge.common.ForgeHooks.prefixNamespace(p_275476_.location())); -+ } ++ /** ++ * @deprecated Forge: Use the {@linkplain #TagsProvider(PackOutput, ResourceKey, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} ++ */ + protected TagsProvider(PackOutput p_256596_, ResourceKey> p_255886_, CompletableFuture p_256513_) { +- this(p_256596_, p_255886_, p_256513_, CompletableFuture.completedFuture(TagsProvider.TagLookup.empty())); ++ this(p_256596_, p_255886_, p_256513_, "vanilla", null); ++ } + -+ // Forge: Allow customizing the path for a given tag or returning null -+ @org.jetbrains.annotations.Nullable -+ protected Path getPath(ResourceLocation id) { -+ return this.pathProvider.json(id); - } ++ protected TagsProvider(PackOutput p_256596_, ResourceKey> p_255886_, CompletableFuture p_256513_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ this(p_256596_, p_255886_, p_256513_, CompletableFuture.completedFuture(TagsProvider.TagLookup.empty()), modId, existingFileHelper); ++ } ++ ++ /** ++ * @deprecated Forge: Use the {@linkplain #TagsProvider(PackOutput, ResourceKey, CompletableFuture, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} ++ */ ++ protected TagsProvider(PackOutput p_275432_, ResourceKey> p_275476_, CompletableFuture p_275222_, CompletableFuture> p_275565_) { ++ this(p_275432_, p_275476_, p_275222_, p_275565_, "vanilla", null); + } - public String getName() { -- return "Tags for " + this.registryKey.location(); -+ return "Tags for " + this.registryKey.location() + " mod id " + this.modId; - } + protected TagsProvider( + PackOutput p_275432_, + ResourceKey> p_275476_, + CompletableFuture p_275222_, +- CompletableFuture> p_275565_ ++ CompletableFuture> p_275565_, ++ String modId, ++ @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper + ) { + this.pathProvider = p_275432_.createPathProvider(PackOutput.Target.DATA_PACK, TagManager.getTagDir(p_275476_)); + this.registryKey = p_275476_; + this.parentProvider = p_275565_; + this.lookupProvider = p_275222_; ++ this.modId = modId; ++ this.existingFileHelper = existingFileHelper; ++ this.resourceType = new net.minecraftforge.common.data.ExistingFileHelper.ResourceType(net.minecraft.server.packs.PackType.SERVER_DATA, ".json", TagManager.getTagDir(p_275476_)); ++ this.elementResourceType = new net.minecraftforge.common.data.ExistingFileHelper.ResourceType(net.minecraft.server.packs.PackType.SERVER_DATA, ".json", net.minecraftforge.common.ForgeHooks.prefixNamespace(p_275476_.location())); ++ } ++ ++ // Forge: Allow customizing the path for a given tag or returning null ++ @org.jetbrains.annotations.Nullable ++ protected Path getPath(ResourceLocation id) { ++ return this.pathProvider.json(id); + } - protected abstract void addTags(HolderLookup.Provider p_256380_); -@@ -64,7 +_,13 @@ + @Override + public String getName() { +- return "Tags for " + this.registryKey.location(); ++ return "Tags for " + this.registryKey.location() + " mod id " + this.modId; + } - return new CombinedData<>(p_274778_, p_274779_); - }).thenCompose((p_274774_) -> { -- HolderLookup.RegistryLookup registrylookup = p_274774_.contents.lookupOrThrow(this.registryKey); -+ HolderLookup.RegistryLookup registrylookup = p_274774_.contents.lookup(this.registryKey).orElseThrow(() -> { -+ // FORGE: Throw a more descriptive error message if this is a Forge registry without tags enabled -+ if (net.minecraftforge.registries.RegistryManager.ACTIVE.getRegistry(this.registryKey) != null) { -+ return new IllegalStateException("Forge registry " + this.registryKey.location() + " does not have support for tags"); + protected abstract void addTags(HolderLookup.Provider p_256380_); +@@ -73,7 +_,13 @@ + .thenCombineAsync(this.parentProvider, (p_274778_, p_274779_) -> new CombinedData<>(p_274778_, (TagsProvider.TagLookup)p_274779_), Util.backgroundExecutor()) + .thenCompose( + p_325926_ -> { +- HolderLookup.RegistryLookup registrylookup = p_325926_.contents.lookupOrThrow(this.registryKey); ++ HolderLookup.RegistryLookup registrylookup = p_325926_.contents.lookup(this.registryKey).orElseThrow(() -> { ++ // FORGE: Throw a more descriptive error message if this is a Forge registry without tags enabled ++ if (net.minecraftforge.registries.RegistryManager.ACTIVE.getRegistry(this.registryKey) != null) { ++ return new IllegalStateException("Forge registry " + this.registryKey.location() + " does not have support for tags"); ++ } ++ return new IllegalStateException("Registry " + this.registryKey.location() + " not found"); ++ }); + Predicate predicate = p_255496_ -> registrylookup.get(ResourceKey.create(this.registryKey, p_255496_)).isPresent(); + Predicate predicate1 = p_274776_ -> this.builders.containsKey(p_274776_) + || p_325926_.parent.contains(TagKey.create(this.registryKey, p_274776_)); +@@ -86,7 +_,7 @@ + ResourceLocation resourcelocation = p_325931_.getKey(); + TagBuilder tagbuilder = p_325931_.getValue(); + List list = tagbuilder.build(); +- List list1 = list.stream().filter(p_274771_ -> !p_274771_.verifyIfPresent(predicate, predicate1)).toList(); ++ List list1 = java.util.stream.Stream.concat(list.stream(), tagbuilder.getRemoveEntries()).filter(p_274771_ -> !p_274771_.verifyIfPresent(predicate, predicate1)).filter(this::missing).toList(); + if (!list1.isEmpty()) { + throw new IllegalArgumentException( + String.format( +@@ -97,8 +_,11 @@ + ) + ); + } else { +- Path path = this.pathProvider.json(resourcelocation); +- return DataProvider.saveStable(p_253684_, p_325926_.contents, TagFile.CODEC, new TagFile(list, false), path); ++ Path path = this.getPath(resourcelocation); ++ if (path == null) { ++ return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags. ++ } ++ return DataProvider.saveStable(p_253684_, p_325926_.contents, TagFile.CODEC, new TagFile(list, tagbuilder.isReplace(), tagbuilder.getRemoveEntries().toList()), path); + } + } + ) +@@ -110,11 +_,16 @@ + + protected TagsProvider.TagAppender tag(TagKey p_206425_) { + TagBuilder tagbuilder = this.getOrCreateRawBuilder(p_206425_); +- return new TagsProvider.TagAppender<>(tagbuilder); ++ return new TagsProvider.TagAppender<>(tagbuilder, modId); + } + + protected TagBuilder getOrCreateRawBuilder(TagKey p_236452_) { +- return this.builders.computeIfAbsent(p_236452_.location(), p_236442_ -> TagBuilder.create()); ++ return this.builders.computeIfAbsent(p_236452_.location(), p_236442_ -> { ++ if (existingFileHelper != null) { ++ existingFileHelper.trackGenerated(p_236442_, resourceType); + } -+ return new IllegalStateException("Registry " + this.registryKey.location() + " not found"); -+ }); - Predicate predicate = (p_255496_) -> { - return registrylookup.get(ResourceKey.create(this.registryKey, p_255496_)).isPresent(); - }; -@@ -75,14 +_,16 @@ - ResourceLocation resourcelocation = p_255499_.getKey(); - TagBuilder tagbuilder = p_255499_.getValue(); - List list = tagbuilder.build(); -- List list1 = list.stream().filter((p_274771_) -> { -+ List list1 = java.util.stream.Stream.concat(list.stream(), tagbuilder.getRemoveEntries()).filter((p_274771_) -> { - return !p_274771_.verifyIfPresent(predicate, predicate1); -- }).toList(); -+ }).filter(this::missing).toList(); // Forge: Add validation via existing resources - if (!list1.isEmpty()) { - throw new IllegalArgumentException(String.format(Locale.ROOT, "Couldn't define tag %s as it is missing following references: %s", resourcelocation, list1.stream().map(Objects::toString).collect(Collectors.joining(",")))); - } else { -- JsonElement jsonelement = TagFile.CODEC.encodeStart(JsonOps.INSTANCE, new TagFile(list, false)).getOrThrow(false, LOGGER::error); -- Path path = this.pathProvider.json(resourcelocation); -+ var removed = tagbuilder.getRemoveEntries().toList(); -+ JsonElement jsonelement = TagFile.CODEC.encodeStart(JsonOps.INSTANCE, new TagFile(list, tagbuilder.isReplace(), removed)).getOrThrow(false, LOGGER::error); -+ Path path = this.getPath(resourcelocation); -+ if (path == null) return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags. - return DataProvider.saveStable(p_253684_, jsonelement, path); - } - }).toArray((p_253442_) -> { -@@ -91,13 +_,25 @@ - }); - } ++ return TagBuilder.create(); ++ }); + } -+ private boolean missing(TagEntry reference) { -+ // Optional tags should not be validated + public CompletableFuture> contentsGetter() { +@@ -129,11 +_,26 @@ + }); + } + +- public static class TagAppender { ++ private boolean missing(TagEntry reference) { ++ // Optional tags should not be validated + -+ if (reference.isRequired()) { -+ return existingFileHelper == null || !existingFileHelper.exists(reference.getId(), reference.isTag() ? resourceType : elementResourceType); -+ } -+ return false; -+ } ++ if (reference.isRequired()) { ++ return existingFileHelper == null || !existingFileHelper.exists(reference.getId(), reference.isTag() ? resourceType : elementResourceType); ++ } ++ return false; ++ } + - protected TagsProvider.TagAppender tag(TagKey p_206425_) { - TagBuilder tagbuilder = this.getOrCreateRawBuilder(p_206425_); -- return new TagsProvider.TagAppender<>(tagbuilder); -+ return new TagsProvider.TagAppender<>(tagbuilder, modId); - } ++ public static class TagAppender implements net.minecraftforge.common.extensions.IForgeTagAppender { + private final TagBuilder builder; ++ private final String modid; - protected TagBuilder getOrCreateRawBuilder(TagKey p_236452_) { - return this.builders.computeIfAbsent(p_236452_.location(), (p_236442_) -> { -+ if (existingFileHelper != null) { -+ existingFileHelper.trackGenerated(p_236442_, resourceType); -+ } - return TagBuilder.create(); - }); - } -@@ -118,11 +_,13 @@ - }); - } - -- public static class TagAppender { -+ public static class TagAppender implements net.minecraftforge.common.extensions.IForgeTagAppender { - private final TagBuilder builder; -+ private final String modId; - -- protected TagAppender(TagBuilder p_256426_) { -- this.builder = p_256426_; -+ protected TagAppender(TagBuilder p_236454_, String modId) { -+ this.builder = p_236454_; -+ this.modId = modId; - } - - public final TagsProvider.TagAppender add(ResourceKey p_256138_) { -@@ -152,6 +_,19 @@ - public TagsProvider.TagAppender addOptionalTag(ResourceLocation p_176842_) { - this.builder.addOptionalTag(p_176842_); - return this; -+ } + protected TagAppender(TagBuilder p_256426_) { ++ this(p_256426_, "vanilla"); ++ } + -+ public TagsProvider.TagAppender add(TagEntry tag) { -+ builder.add(tag); -+ return this; -+ } -+ -+ public TagBuilder getInternalBuilder() { -+ return builder; -+ } -+ -+ public String getModID() { -+ return modId; - } - } ++ protected TagAppender(TagBuilder p_256426_, String modid) { + this.builder = p_256426_; ++ this.modid = modid; + } + + public final TagsProvider.TagAppender add(ResourceKey p_256138_) { +@@ -171,6 +_,19 @@ + public TagsProvider.TagAppender addOptionalTag(ResourceLocation p_176842_) { + this.builder.addOptionalTag(p_176842_); + return this; ++ } ++ ++ public TagsProvider.TagAppender add(TagEntry tag) { ++ builder.add(tag); ++ return this; ++ } ++ ++ public TagBuilder getInternalBuilder() { ++ return builder; ++ } ++ ++ public String getModID() { ++ return modid; + } + } diff --git a/patches/minecraft/net/minecraft/data/tags/WorldPresetTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/WorldPresetTagsProvider.java.patch index aa2aaa4726..aa1a221063 100644 --- a/patches/minecraft/net/minecraft/data/tags/WorldPresetTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/WorldPresetTagsProvider.java.patch @@ -1,16 +1,17 @@ --- a/net/minecraft/data/tags/WorldPresetTagsProvider.java +++ b/net/minecraft/data/tags/WorldPresetTagsProvider.java -@@ -9,8 +_,13 @@ +@@ -9,8 +_,14 @@ import net.minecraft.world.level.levelgen.presets.WorldPresets; public class WorldPresetTagsProvider extends TagsProvider { -+ /** @deprecated Forge: Use the {@linkplain #WorldPresetTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ -+ @Deprecated - public WorldPresetTagsProvider(PackOutput p_255701_, CompletableFuture p_255974_) { - super(p_255701_, Registries.WORLD_PRESET, p_255974_); -+ } -+ public WorldPresetTagsProvider(PackOutput p_255701_, CompletableFuture p_255974_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(p_255701_, Registries.WORLD_PRESET, p_255974_, modId, existingFileHelper); - } ++ /** @deprecated Forge: Use the {@linkplain #WorldPresetTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ ++ @Deprecated + public WorldPresetTagsProvider(PackOutput p_255701_, CompletableFuture p_255974_) { + super(p_255701_, Registries.WORLD_PRESET, p_255974_); ++ } ++ ++ public WorldPresetTagsProvider(PackOutput p_255701_, CompletableFuture p_255974_, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(p_255701_, Registries.WORLD_PRESET, p_255974_, modId, existingFileHelper); + } - protected void addTags(HolderLookup.Provider p_255734_) { + @Override diff --git a/patches/minecraft/net/minecraft/data/worldgen/BootstapContext.java.patch b/patches/minecraft/net/minecraft/data/worldgen/BootstapContext.java.patch deleted file mode 100644 index 4c3238222a..0000000000 --- a/patches/minecraft/net/minecraft/data/worldgen/BootstapContext.java.patch +++ /dev/null @@ -1,9 +0,0 @@ ---- a/net/minecraft/data/worldgen/BootstapContext.java -+++ b/net/minecraft/data/worldgen/BootstapContext.java -@@ -14,4 +_,6 @@ - } - - HolderGetter lookup(ResourceKey> p_256410_); -+ -+ default java.util.Optional> registryLookup(ResourceKey> registry) { return java.util.Optional.empty(); } - } diff --git a/patches/minecraft/net/minecraft/data/worldgen/BootstrapContext.java.patch b/patches/minecraft/net/minecraft/data/worldgen/BootstrapContext.java.patch new file mode 100644 index 0000000000..5778f97604 --- /dev/null +++ b/patches/minecraft/net/minecraft/data/worldgen/BootstrapContext.java.patch @@ -0,0 +1,9 @@ +--- a/net/minecraft/data/worldgen/BootstrapContext.java ++++ b/net/minecraft/data/worldgen/BootstrapContext.java +@@ -14,4 +_,6 @@ + } + + HolderGetter lookup(ResourceKey> p_332059_); ++ ++ default java.util.Optional> registryLookup(ResourceKey> registry) { return java.util.Optional.empty(); } + } diff --git a/patches/minecraft/net/minecraft/data/worldgen/biome/OverworldBiomes.java.patch b/patches/minecraft/net/minecraft/data/worldgen/biome/OverworldBiomes.java.patch deleted file mode 100644 index d432af16f8..0000000000 --- a/patches/minecraft/net/minecraft/data/worldgen/biome/OverworldBiomes.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/data/worldgen/biome/OverworldBiomes.java -+++ b/net/minecraft/data/worldgen/biome/OverworldBiomes.java -@@ -23,6 +_,8 @@ - import net.minecraft.world.level.levelgen.placement.PlacedFeature; - - public class OverworldBiomes { -+ // TODO: getAdditionalOverworldBiomes, likely in this class. -C -+ - protected static final int NORMAL_WATER_COLOR = 4159204; - protected static final int NORMAL_WATER_FOG_COLOR = 329011; - private static final int OVERWORLD_FOG_COLOR = 12638463; diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch index 044136080c..5951ac4dbd 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/gametest/framework/GameTestHelper.java +++ b/net/minecraft/gametest/framework/GameTestHelper.java -@@ -60,7 +_,7 @@ +@@ -61,7 +_,7 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -public class GameTestHelper { +public class GameTestHelper implements net.minecraftforge.common.extensions.IForgeGameTestHelper { - private final GameTestInfo testInfo; - private boolean finalCheckAdded; + private final GameTestInfo testInfo; + private boolean finalCheckAdded; diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch index a9ede7329d..201c694970 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch @@ -1,73 +1,77 @@ --- a/net/minecraft/gametest/framework/GameTestRegistry.java +++ b/net/minecraft/gametest/framework/GameTestRegistry.java -@@ -26,22 +_,31 @@ - private static final Map> AFTER_BATCH_FUNCTIONS = Maps.newHashMap(); - private static final Collection LAST_FAILED_TESTS = Sets.newHashSet(); +@@ -25,22 +_,33 @@ + private static final Map> AFTER_BATCH_FUNCTIONS = Maps.newHashMap(); + private static final Set LAST_FAILED_TESTS = Sets.newHashSet(); -+ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ -+ @Deprecated - public static void register(Class p_177502_) { - Arrays.stream(p_177502_.getDeclaredMethods()).sorted(Comparator.comparing(Method::getName)).forEach(GameTestRegistry::register); - } - -+ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ -+ @Deprecated - public static void register(Method p_177504_) { -+ register(p_177504_, java.util.Set.of()); -+ } + -+ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ -+ @Deprecated -+ public static void register(Method p_177504_, java.util.Set allowed) { - String s = p_177504_.getDeclaringClass().getSimpleName(); - GameTest gametest = p_177504_.getAnnotation(GameTest.class); - if (gametest != null) { -- TEST_FUNCTIONS.add(turnMethodIntoTestFunction(p_177504_)); -- TEST_CLASS_NAMES.add(s); -+ net.minecraftforge.gametest.ForgeGameTestHooks.addTest(TEST_FUNCTIONS, TEST_CLASS_NAMES, allowed, turnMethodIntoTestFunction(p_177504_)); - } ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated + public static void register(Class p_177502_) { + Arrays.stream(p_177502_.getDeclaredMethods()).sorted(Comparator.comparing(Method::getName)).forEach(GameTestRegistry::register); + } - GameTestGenerator gametestgenerator = p_177504_.getAnnotation(GameTestGenerator.class); - if (gametestgenerator != null) { -- TEST_FUNCTIONS.addAll(useTestGeneratorMethod(p_177504_)); -- TEST_CLASS_NAMES.add(s); -+ for (var func : useTestGeneratorMethod(p_177504_)) -+ net.minecraftforge.gametest.ForgeGameTestHooks.addTest(TEST_FUNCTIONS, TEST_CLASS_NAMES, allowed, func); - } ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated + public static void register(Method p_177504_) { ++ register(p_177504_, java.util.Set.of()); ++ } ++ ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated ++ public static void register(Method p_177504_, java.util.Set allowed) { + String s = p_177504_.getDeclaringClass().getSimpleName(); + GameTest gametest = p_177504_.getAnnotation(GameTest.class); + if (gametest != null) { +- TEST_FUNCTIONS.add(turnMethodIntoTestFunction(p_177504_)); +- TEST_CLASS_NAMES.add(s); ++ net.minecraftforge.gametest.ForgeGameTestHooks.addTest(TEST_FUNCTIONS, TEST_CLASS_NAMES, allowed, turnMethodIntoTestFunction(p_177504_)); + } - registerBatchFunction(p_177504_, BeforeBatch.class, BeforeBatch::batch, BEFORE_BATCH_FUNCTIONS); -@@ -105,7 +_,9 @@ + GameTestGenerator gametestgenerator = p_177504_.getAnnotation(GameTestGenerator.class); + if (gametestgenerator != null) { +- TEST_FUNCTIONS.addAll(useTestGeneratorMethod(p_177504_)); +- TEST_CLASS_NAMES.add(s); ++ for (var func : useTestGeneratorMethod(p_177504_)) { ++ net.minecraftforge.gametest.ForgeGameTestHooks.addTest(TEST_FUNCTIONS, TEST_CLASS_NAMES, allowed, func); ++ } + } - private static Collection useTestGeneratorMethod(Method p_177514_) { - try { -- Object object = p_177514_.getDeclaringClass().newInstance(); -+ Object object = null; -+ if (!java.lang.reflect.Modifier.isStatic(p_177514_.getModifiers())) -+ object = p_177514_.getDeclaringClass().newInstance(); - return (Collection)p_177514_.invoke(object); - } catch (ReflectiveOperationException reflectiveoperationexception) { - throw new RuntimeException(reflectiveoperationexception); -@@ -116,9 +_,9 @@ - GameTest gametest = p_177516_.getAnnotation(GameTest.class); - String s = p_177516_.getDeclaringClass().getSimpleName(); - String s1 = s.toLowerCase(); -- String s2 = s1 + "." + p_177516_.getName().toLowerCase(); -- String s3 = gametest.template().isEmpty() ? s2 : s1 + "." + gametest.template(); -- String s4 = gametest.batch(); -+ String s2 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestName(p_177516_, gametest); -+ String s3 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestTemplate(p_177516_, gametest, s2); -+ String s4 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestBatch(p_177516_, gametest); - Rotation rotation = StructureUtils.getRotationForRotationSteps(gametest.rotationSteps()); - return new TestFunction(s4, s2, s3, rotation, gametest.timeoutTicks(), gametest.setupTicks(), gametest.required(), gametest.requiredSuccesses(), gametest.attempts(), (Consumer)turnMethodIntoConsumer(p_177516_)); - } -@@ -126,7 +_,9 @@ - private static Consumer turnMethodIntoConsumer(Method p_177520_) { - return (p_177512_) -> { - try { -- Object object = p_177520_.getDeclaringClass().newInstance(); + registerBatchFunction(p_177504_, BeforeBatch.class, BeforeBatch::batch, BEFORE_BATCH_FUNCTIONS); +@@ -101,7 +_,10 @@ + + private static Collection useTestGeneratorMethod(Method p_177514_) { + try { +- Object object = p_177514_.getDeclaringClass().newInstance(); + Object object = null; -+ if (!java.lang.reflect.Modifier.isStatic(p_177520_.getModifiers())) -+ object = p_177520_.getDeclaringClass().newInstance(); - p_177520_.invoke(object, p_177512_); - } catch (InvocationTargetException invocationtargetexception) { - if (invocationtargetexception.getCause() instanceof RuntimeException) { ++ if (!java.lang.reflect.Modifier.isStatic(p_177514_.getModifiers())) { ++ object = p_177514_.getDeclaringClass().newInstance(); ++ } + return (Collection)p_177514_.invoke(object); + } catch (ReflectiveOperationException reflectiveoperationexception) { + throw new RuntimeException(reflectiveoperationexception); +@@ -112,9 +_,9 @@ + GameTest gametest = p_177516_.getAnnotation(GameTest.class); + String s = p_177516_.getDeclaringClass().getSimpleName(); + String s1 = s.toLowerCase(); +- String s2 = s1 + "." + p_177516_.getName().toLowerCase(); +- String s3 = gametest.template().isEmpty() ? s2 : s1 + "." + gametest.template(); +- String s4 = gametest.batch(); ++ String s2 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestName(p_177516_, gametest); ++ String s3 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestTemplate(p_177516_, gametest, s2); ++ String s4 = net.minecraftforge.gametest.ForgeGameTestHooks.getTestBatch(p_177516_, gametest); + Rotation rotation = StructureUtils.getRotationForRotationSteps(gametest.rotationSteps()); + return new TestFunction( + s4, +@@ -135,7 +_,10 @@ + private static Consumer turnMethodIntoConsumer(Method p_177520_) { + return p_177512_ -> { + try { +- Object object = p_177520_.getDeclaringClass().newInstance(); ++ Object object = null; ++ if (!java.lang.reflect.Modifier.isStatic(p_177520_.getModifiers())) { ++ object = p_177520_.getDeclaringClass().newInstance(); ++ } + p_177520_.invoke(object, p_177512_); + } catch (InvocationTargetException invocationtargetexception) { + if (invocationtargetexception.getCause() instanceof RuntimeException) { diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch deleted file mode 100644 index f2b030d740..0000000000 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch +++ /dev/null @@ -1,18 +0,0 @@ ---- a/net/minecraft/gametest/framework/GameTestServer.java -+++ b/net/minecraft/gametest/framework/GameTestServer.java -@@ -106,13 +_,14 @@ - public boolean initServer() { - this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, 1) { - }); -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; - this.loadLevel(); - ServerLevel serverlevel = this.overworld(); - serverlevel.setDefaultSpawnPos(this.spawnPos, 0.0F); - int i = 20000000; - serverlevel.setWeatherParameters(20000000, 20000000, false, false); - LOGGER.info("Started game test server"); -- return true; -+ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); - } - - public void tickServer(BooleanSupplier p_177619_) { diff --git a/patches/minecraft/net/minecraft/locale/Language.java.patch b/patches/minecraft/net/minecraft/locale/Language.java.patch index cc17717e82..f90eeb3e5b 100644 --- a/patches/minecraft/net/minecraft/locale/Language.java.patch +++ b/patches/minecraft/net/minecraft/locale/Language.java.patch @@ -1,34 +1,33 @@ --- a/net/minecraft/locale/Language.java +++ b/net/minecraft/locale/Language.java -@@ -34,7 +_,8 @@ - ImmutableMap.Builder builder = ImmutableMap.builder(); - BiConsumer biconsumer = builder::put; - parseTranslations(biconsumer, "/assets/minecraft/lang/en_us.json"); -- final Map map = builder.build(); -+ final Map map = new java.util.HashMap<>(builder.build()); -+ net.minecraftforge.server.LanguageHook.captureLanguageMap(map); - return new Language() { - public String getOrDefault(String p_128127_, String p_265421_) { - return map.getOrDefault(p_128127_, p_265421_); -@@ -55,6 +_,11 @@ - }, Style.EMPTY).isPresent(); - }; - } +@@ -37,7 +_,8 @@ + Builder builder = ImmutableMap.builder(); + BiConsumer biconsumer = builder::put; + parseTranslations(biconsumer, "/assets/minecraft/lang/en_us.json"); +- final Map map = builder.build(); ++ final Map map = new java.util.HashMap<>(builder.build()); ++ net.minecraftforge.server.LanguageHook.captureLanguageMap(map); + return new Language() { + @Override + public String getOrDefault(String p_128127_, String p_265421_) { +@@ -62,6 +_,11 @@ + ) + .isPresent(); + } + -+ @Override -+ public Map getLanguageData() { -+ return map; -+ } - }; - } ++ @Override ++ public Map getLanguageData() { ++ return map; ++ } + }; + } -@@ -84,6 +_,9 @@ - public static void inject(Language p_128115_) { - instance = p_128115_; - } +@@ -89,6 +_,8 @@ + public static void inject(Language p_128115_) { + instance = p_128115_; + } + -+ // FORGE START -+ public Map getLanguageData() { return ImmutableMap.of(); } ++ public Map getLanguageData() { return Map.of(); } - public String getOrDefault(String p_128111_) { - return this.getOrDefault(p_128111_, p_128111_); + public String getOrDefault(String p_128111_) { + return this.getOrDefault(p_128111_, p_128111_); diff --git a/patches/minecraft/net/minecraft/nbt/CompoundTag.java.patch b/patches/minecraft/net/minecraft/nbt/CompoundTag.java.patch index 4f72286bd9..5b7b0d539b 100644 --- a/patches/minecraft/net/minecraft/nbt/CompoundTag.java.patch +++ b/patches/minecraft/net/minecraft/nbt/CompoundTag.java.patch @@ -1,21 +1,13 @@ --- a/net/minecraft/nbt/CompoundTag.java +++ b/net/minecraft/nbt/CompoundTag.java -@@ -19,6 +_,10 @@ +@@ -20,6 +_,10 @@ import net.minecraft.ReportedException; public class CompoundTag implements Tag { -+ public static net.minecraftforge.common.util.INBTBuilder.Builder builder() { -+ return (new net.minecraftforge.common.util.INBTBuilder(){}).nbt(); -+ } ++ public static net.minecraftforge.common.util.INBTBuilder.Builder builder() { ++ return (new net.minecraftforge.common.util.INBTBuilder(){}).nbt(); ++ } + - public static final Codec CODEC = Codec.PASSTHROUGH.comapFlatMap((p_308555_) -> { - Tag tag = p_308555_.convert(NbtOps.INSTANCE).getValue(); - if (tag instanceof CompoundTag compoundtag) { -@@ -208,6 +_,7 @@ - - @Nullable - public Tag put(String p_128366_, Tag p_128367_) { -+ if (p_128367_ == null) throw new IllegalArgumentException("Invalid null NBT value with key " + p_128366_); - return this.tags.put(p_128366_, p_128367_); - } - + public static final Codec CODEC = Codec.PASSTHROUGH + .comapFlatMap( + p_308555_ -> { diff --git a/patches/minecraft/net/minecraft/nbt/NbtAccounter.java.patch b/patches/minecraft/net/minecraft/nbt/NbtAccounter.java.patch deleted file mode 100644 index f9a0bc7055..0000000000 --- a/patches/minecraft/net/minecraft/nbt/NbtAccounter.java.patch +++ /dev/null @@ -1,39 +0,0 @@ ---- a/net/minecraft/nbt/NbtAccounter.java -+++ b/net/minecraft/nbt/NbtAccounter.java -@@ -50,6 +_,36 @@ - } - } - -+ /* -+ * UTF8 is not a simple encoding system, each character can be either -+ * 1, 2, or 3 bytes. Depending on where it's numerical value falls. -+ * We have to count up each character individually to see the true -+ * length of the data. -+ * -+ * Basic concept is that it uses the MSB of each byte as a 'read more' signal. -+ * So it has to shift each 7-bit segment. -+ * -+ * This will accurately count the correct byte length to encode this string, plus the 2 bytes for it's length prefix. -+ */ -+ public String readUTF(String data) { -+ accountBytes(2); //Header length -+ if (data == null) -+ return data; -+ -+ int len = data.length(); -+ int utflen = 0; -+ -+ for (int i = 0; i < len; i++) { -+ int c = data.charAt(i); -+ if ((c >= 0x0001) && (c <= 0x007F)) utflen += 1; -+ else if (c > 0x07FF) utflen += 3; -+ else utflen += 2; -+ } -+ accountBytes(utflen); -+ -+ return data; -+ } -+ - @VisibleForTesting - public long getUsage() { - return this.usage; diff --git a/patches/minecraft/net/minecraft/nbt/NbtIo.java.patch b/patches/minecraft/net/minecraft/nbt/NbtIo.java.patch deleted file mode 100644 index d68a83cb9c..0000000000 --- a/patches/minecraft/net/minecraft/nbt/NbtIo.java.patch +++ /dev/null @@ -1,16 +0,0 @@ ---- a/net/minecraft/nbt/NbtIo.java -+++ b/net/minecraft/nbt/NbtIo.java -@@ -168,10 +_,12 @@ - - private static Tag readUnnamedTag(DataInput p_128931_, NbtAccounter p_128933_) throws IOException { - byte b0 = p_128931_.readByte(); -+ p_128933_.accountBytes(1); // Forge: Count everything! - if (b0 == 0) { - return EndTag.INSTANCE; - } else { -- StringTag.skipString(p_128931_); -+ p_128933_.readUTF(p_128931_.readUTF()); //Forge: Count this string. -+ p_128933_.accountBytes(4); //Forge: 4 extra bytes for the object allocation. - return readTagSafe(p_128931_, p_128933_, b0); - } - } diff --git a/patches/minecraft/net/minecraft/nbt/StringTag.java.patch b/patches/minecraft/net/minecraft/nbt/StringTag.java.patch deleted file mode 100644 index 128cbc1b56..0000000000 --- a/patches/minecraft/net/minecraft/nbt/StringTag.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/nbt/StringTag.java -+++ b/net/minecraft/nbt/StringTag.java -@@ -19,7 +_,7 @@ - private static String readAccounted(DataInput p_301750_, NbtAccounter p_301732_) throws IOException { - p_301732_.accountBytes(36L); - String s = p_301750_.readUTF(); -- p_301732_.accountBytes(2L, (long)s.length()); -+ p_301732_.readUTF(s); - return s; - } - diff --git a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch index 14238714c4..cfa08db5a7 100644 --- a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch +++ b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/network/CompressionEncoder.java +++ b/net/minecraft/network/CompressionEncoder.java -@@ -9,6 +_,8 @@ - private final byte[] encodeBuf = new byte[8192]; - private final Deflater deflater; - private int threshold; -+ private static final boolean DISABLE_PACKET_DEBUG = Boolean.parseBoolean(System.getProperty("forge.disablePacketCompressionDebug", "false")); -+ private static final org.apache.logging.log4j.Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(); +@@ -6,6 +_,8 @@ + import java.util.zip.Deflater; - public CompressionEncoder(int p_129448_) { - this.threshold = p_129448_; -@@ -21,6 +_,12 @@ - VarInt.write(p_129454_, 0); - p_129454_.writeBytes(p_129453_); - } else { -+ if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { -+ p_129453_.markReaderIndex(); -+ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", i, net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH, -+ net.minecraftforge.common.util.HexDumper.dump(p_129453_)); -+ p_129453_.resetReaderIndex(); -+ } - byte[] abyte = new byte[i]; - p_129453_.readBytes(abyte); - VarInt.write(p_129454_, abyte.length); + public class CompressionEncoder extends MessageToByteEncoder { ++ private static final boolean DISABLE_PACKET_DEBUG = Boolean.parseBoolean(System.getProperty("forge.disablePacketCompressionDebug", "false")); ++ private static final org.apache.logging.log4j.Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(); + private final byte[] encodeBuf = new byte[8192]; + private final Deflater deflater; + private int threshold; +@@ -24,6 +_,12 @@ + VarInt.write(p_129454_, 0); + p_129454_.writeBytes(p_129453_); + } else { ++ if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { ++ p_129453_.markReaderIndex(); ++ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", i, net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH, ++ net.minecraftforge.common.util.HexDumper.dump(p_129453_)); ++ p_129453_.resetReaderIndex(); ++ } + byte[] abyte = new byte[i]; + p_129453_.readBytes(abyte); + VarInt.write(p_129454_, abyte.length); diff --git a/patches/minecraft/net/minecraft/network/Connection.java.patch b/patches/minecraft/net/minecraft/network/Connection.java.patch index 36ce622918..6d32f09275 100644 --- a/patches/minecraft/net/minecraft/network/Connection.java.patch +++ b/patches/minecraft/net/minecraft/network/Connection.java.patch @@ -1,89 +1,99 @@ --- a/net/minecraft/network/Connection.java +++ b/net/minecraft/network/Connection.java -@@ -102,15 +_,19 @@ - private volatile Component delayedDisconnect; - @Nullable - BandwidthDebugMonitor bandwidthDebugMonitor; -+ private java.util.function.Consumer activationHandler; -+ private final net.minecraftforge.common.util.PacketLogger packetLogger; +@@ -107,9 +_,12 @@ + private volatile Component delayedDisconnect; + @Nullable + BandwidthDebugMonitor bandwidthDebugMonitor; ++ private java.util.function.Consumer activationHandler; ++ private final net.minecraftforge.common.util.PacketLogger packetLogger; - public Connection(PacketFlow p_129482_) { - this.receiving = p_129482_; -+ this.packetLogger = new net.minecraftforge.common.util.PacketLogger(this); - } + public Connection(PacketFlow p_129482_) { + this.receiving = p_129482_; ++ this.packetLogger = new net.minecraftforge.common.util.PacketLogger(this); + } - public void channelActive(ChannelHandlerContext p_129525_) throws Exception { - super.channelActive(p_129525_); - this.channel = p_129525_.channel(); - this.address = this.channel.remoteAddress(); -+ if (activationHandler != null) activationHandler.accept(this); - if (this.delayedDisconnect != null) { - this.disconnect(this.delayedDisconnect); - } + @Override +@@ -117,6 +_,7 @@ + super.channelActive(p_129525_); + this.channel = p_129525_.channel(); + this.address = this.channel.remoteAddress(); ++ if (activationHandler != null) activationHandler.accept(this); + if (this.delayedDisconnect != null) { + this.disconnect(this.delayedDisconnect); + } @@ -169,6 +_,7 @@ - } else { - if (packetlistener.shouldHandleMessage(p_129488_)) { - try { -+ packetLogger.recv(p_129488_); - genericsFtw(p_129488_, packetlistener); - } catch (RunningOnDifferentThreadException runningondifferentthreadexception) { - } catch (RejectedExecutionException rejectedexecutionexception) { -@@ -237,7 +_,8 @@ - this.runOnceConnected((p_296374_) -> { - p_296374_.setClientboundProtocolAfterHandshake(p_297789_); - this.setListener(p_298739_); -- p_296374_.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().getProtocolVersion(), p_300730_, p_300598_, p_297789_), (PacketSendListener)null, true); -+ // TODO: Change this to be a immediately sent login custom payload packet? -+ p_296374_.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().getProtocolVersion(), net.minecraftforge.network.NetworkContext.enhanceHostName(p_300730_), p_300598_, p_297789_), (PacketSendListener)null, true); - }); - } + } else { + if (packetlistener.shouldHandleMessage(p_129488_)) { + try { ++ packetLogger.recv(p_129488_); + genericsFtw(p_129488_, packetlistener); + } catch (RunningOnDifferentThreadException runningondifferentthreadexception) { + } catch (RejectedExecutionException rejectedexecutionexception) { +@@ -249,6 +_,7 @@ + p_326044_ -> p_326044_.pipeline().addAfter("encoder", "unbundler", packetbundleunpacker) + ); + } ++ unconfiguredpipelinehandler$outboundconfigurationtask = unconfiguredpipelinehandler$outboundconfigurationtask.andThen(f -> this.protocol = p_329145_.id()); -@@ -289,6 +_,7 @@ + boolean flag = p_329145_.id() == ConnectionProtocol.LOGIN; + syncAfterConfigurationChange(this.channel.writeAndFlush(unconfiguredpipelinehandler$outboundconfigurationtask.andThen(p_326048_ -> this.sendLoginDisconnect = flag))); +@@ -290,7 +_,8 @@ + this.disconnectListener = p_330656_; + this.runOnceConnected(p_326042_ -> { + this.setupInboundProtocol(p_329827_, p_330656_); +- p_326042_.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().getProtocolVersion(), p_300730_, p_300598_, p_297789_), null, true); ++ // TODO: Change this to be a immediately sent login custom payload packet? ++ p_326042_.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().getProtocolVersion(), net.minecraftforge.network.NetworkContext.enhanceHostName(p_300730_), p_300598_, p_297789_), null, true); + this.setupOutboundProtocol(p_328134_); + }); + } +@@ -333,6 +_,7 @@ - private void doSendPacket(Packet p_243260_, @Nullable PacketSendListener p_243290_, boolean p_299937_) { - ChannelFuture channelfuture = p_299937_ ? this.channel.writeAndFlush(p_243260_) : this.channel.write(p_243260_); -+ channelfuture.addListener(f -> packetLogger.send(p_243260_)); - if (p_243290_ != null) { - channelfuture.addListener((p_243167_) -> { - if (p_243167_.isSuccess()) { -@@ -395,7 +_,7 @@ - if (this.address == null) { - return "local"; - } else { -- return p_298740_ ? this.address.toString() : "IP hidden"; -+ return p_298740_ ? net.minecraftforge.network.DualStackUtils.getAddressString(this.address) : "IP hidden"; - } - } + private void doSendPacket(Packet p_243260_, @Nullable PacketSendListener p_243290_, boolean p_299937_) { + ChannelFuture channelfuture = p_299937_ ? this.channel.writeAndFlush(p_243260_) : this.channel.write(p_243260_); ++ channelfuture.addListener(f -> packetLogger.send(p_243260_)); + if (p_243290_ != null) { + channelfuture.addListener(p_243167_ -> { + if (p_243167_.isSuccess()) { +@@ -415,7 +_,7 @@ + if (this.address == null) { + return "local"; + } else { +- return p_298740_ ? this.address.toString() : "IP hidden"; ++ return p_298740_ ? net.minecraftforge.network.DualStackUtils.getAddressString(this.address) : "IP hidden"; + } + } -@@ -435,6 +_,8 @@ - } +@@ -454,6 +_,8 @@ + } - public static ChannelFuture connect(InetSocketAddress p_290034_, boolean p_290035_, final Connection p_290031_) { -+ net.minecraftforge.network.DualStackUtils.checkIPv6(p_290034_.getAddress()); -+ p_290031_.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; - Class oclass; - EventLoopGroup eventloopgroup; - if (Epoll.isAvailable() && p_290035_) { -@@ -485,6 +_,7 @@ + public static ChannelFuture connect(InetSocketAddress p_290034_, boolean p_290035_, final Connection p_290031_) { ++ net.minecraftforge.network.DualStackUtils.checkIPv6(p_290034_.getAddress()); ++ p_290031_.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; + Class oclass; + EventLoopGroup eventloopgroup; + if (Epoll.isAvailable() && p_290035_) { +@@ -525,6 +_,7 @@ - public static Connection connectToLocalServer(SocketAddress p_129494_) { - final Connection connection = new Connection(PacketFlow.CLIENTBOUND); -+ connection.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; - (new Bootstrap()).group(LOCAL_WORKER_GROUP.get()).handler(new ChannelInitializer() { - protected void initChannel(Channel p_129557_) { - Connection.setInitialProtocolAttributes(p_129557_); -@@ -581,6 +_,14 @@ + public static Connection connectToLocalServer(SocketAddress p_129494_) { + final Connection connection = new Connection(PacketFlow.CLIENTBOUND); ++ connection.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart; + new Bootstrap().group(LOCAL_WORKER_GROUP.get()).handler(new ChannelInitializer() { + @Override + protected void initChannel(Channel p_332618_) { +@@ -616,6 +_,15 @@ - public float getAverageSentPackets() { - return this.averageSentPackets; -+ } + public float getAverageSentPackets() { + return this.averageSentPackets; ++ } + -+ public Channel channel() { -+ return this.channel; -+ } ++ public Channel channel() { ++ return this.channel; ++ } + -+ public ConnectionProtocol getProtocol() { -+ return this.channel.attr(getProtocolKey(getSending())).get().protocol(); - } ++ private ConnectionProtocol protocol = INITIAL_PROTOCOL.id(); ++ public ConnectionProtocol getProtocol() { ++ return protocol; + } - public void setBandwidthLogger(SampleLogger p_300126_) { + public void setBandwidthLogger(LocalSampleLogger p_333554_) { diff --git a/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch b/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch deleted file mode 100644 index 1f65c8b3db..0000000000 --- a/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch +++ /dev/null @@ -1,245 +0,0 @@ ---- a/net/minecraft/network/ConnectionProtocol.java -+++ b/net/minecraft/network/ConnectionProtocol.java -@@ -216,11 +_,237 @@ - import org.slf4j.Logger; - - public enum ConnectionProtocol { -- HANDSHAKING("handshake", protocol().addFlow(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet()).addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ClientIntentionPacket.class, ClientIntentionPacket::new))), -- PLAY("play", protocol().addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).withBundlePacket(ClientboundBundlePacket.class, ClientboundBundlePacket::new).addPacket(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new).addPacket(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new).addPacket(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new).addPacket(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new).addPacket(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new).addPacket(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new).addPacket(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new).addPacket(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new).addPacket(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new).addPacket(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new).addPacket(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new).addPacket(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new).addPacket(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new).addPacket(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new).addPacket(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new).addPacket(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new).addPacket(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new).addPacket(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new).addPacket(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new).addPacket(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new).addPacket(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new).addPacket(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new).addPacket(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new).addPacket(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).addPacket(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new).addPacket(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new).addPacket(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).addPacket(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new).addPacket(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new).addPacket(ClientboundExplodePacket.class, ClientboundExplodePacket::new).addPacket(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new).addPacket(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new).addPacket(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new).addPacket(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new).addPacket(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new).addPacket(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).addPacket(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new).addPacket(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new).addPacket(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new).addPacket(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new).addPacket(ClientboundLoginPacket.class, ClientboundLoginPacket::new).addPacket(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new).addPacket(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new).addPacket(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::read).addPacket(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::read).addPacket(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::read).addPacket(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new).addPacket(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new).addPacket(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new).addPacket(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new).addPacket(ClientboundPingPacket.class, ClientboundPingPacket::new).addPacket(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new).addPacket(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new).addPacket(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new).addPacket(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new).addPacket(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new).addPacket(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new).addPacket(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new).addPacket(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new).addPacket(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new).addPacket(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new).addPacket(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new).addPacket(ClientboundRecipePacket.class, ClientboundRecipePacket::new).addPacket(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new).addPacket(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new).addPacket(ClientboundResetScorePacket.class, ClientboundResetScorePacket::new).addPacket(ClientboundResourcePackPopPacket.class, ClientboundResourcePackPopPacket::new).addPacket(ClientboundResourcePackPushPacket.class, ClientboundResourcePackPushPacket::new).addPacket(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new).addPacket(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new).addPacket(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new).addPacket(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new).addPacket(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new).addPacket(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new).addPacket(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new).addPacket(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new).addPacket(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new).addPacket(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new).addPacket(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new).addPacket(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new).addPacket(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new).addPacket(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new).addPacket(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new).addPacket(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new).addPacket(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new).addPacket(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new).addPacket(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new).addPacket(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new).addPacket(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new).addPacket(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new).addPacket(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new).addPacket(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new).addPacket(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new).addPacket(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new).addPacket(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new).addPacket(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new).addPacket(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new).addPacket(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new).addPacket(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new).addPacket(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new).addPacket(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new).addPacket(ClientboundSoundPacket.class, ClientboundSoundPacket::new).addPacket(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new).addPacket(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new).addPacket(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new).addPacket(ClientboundTabListPacket.class, ClientboundTabListPacket::new).addPacket(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new).addPacket(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new).addPacket(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new).addPacket(ClientboundTickingStatePacket.class, ClientboundTickingStatePacket::new).addPacket(ClientboundTickingStepPacket.class, ClientboundTickingStepPacket::new).addPacket(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new).addPacket(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new).addPacket(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new).addPacket(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new).addPacket(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new).addPacket(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new).addPacket(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new).addPacket(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new).addPacket(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new).addPacket(ServerboundChatPacket.class, ServerboundChatPacket::new).addPacket(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new).addPacket(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new).addPacket(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new).addPacket(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).addPacket(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new).addPacket(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new).addPacket(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new).addPacket(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new).addPacket(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new).addPacket(ServerboundContainerSlotStateChangedPacket.class, ServerboundContainerSlotStateChangedPacket::new).addPacket(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).addPacket(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new).addPacket(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new).addPacket(ServerboundInteractPacket.class, ServerboundInteractPacket::new).addPacket(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new).addPacket(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).addPacket(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new).addPacket(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::read).addPacket(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::read).addPacket(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::read).addPacket(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::read).addPacket(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new).addPacket(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new).addPacket(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new).addPacket(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new).addPacket(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new).addPacket(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new).addPacket(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new).addPacket(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new).addPacket(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new).addPacket(ServerboundPongPacket.class, ServerboundPongPacket::new).addPacket(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new).addPacket(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new).addPacket(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new).addPacket(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new).addPacket(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new).addPacket(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new).addPacket(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new).addPacket(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new).addPacket(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new).addPacket(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new).addPacket(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new).addPacket(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new).addPacket(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new).addPacket(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new).addPacket(ServerboundSwingPacket.class, ServerboundSwingPacket::new).addPacket(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new).addPacket(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new).addPacket(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new))), -- STATUS("status", protocol().addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new).addPacket(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new)).addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new).addPacket(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new))), -- LOGIN("login", protocol().addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new).addPacket(ClientboundHelloPacket.class, ClientboundHelloPacket::new).addPacket(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new).addPacket(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new).addPacket(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new)).addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ServerboundHelloPacket.class, ServerboundHelloPacket::new).addPacket(ServerboundKeyPacket.class, ServerboundKeyPacket::new).addPacket(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::read).addPacket(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new))), -- CONFIGURATION("configuration", protocol().addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).addPacket(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).addPacket(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new).addPacket(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).addPacket(ClientboundPingPacket.class, ClientboundPingPacket::new).addPacket(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new).addPacket(ClientboundResourcePackPopPacket.class, ClientboundResourcePackPopPacket::new).addPacket(ClientboundResourcePackPushPacket.class, ClientboundResourcePackPushPacket::new).addPacket(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new).addPacket(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).addPacket(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).addPacket(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).addPacket(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new).addPacket(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).addPacket(ServerboundPongPacket.class, ServerboundPongPacket::new).addPacket(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new))); -+ HANDSHAKING("handshake", protocol() -+ .addFlow(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet<>()) -+ .addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ClientIntentionPacket.class, ClientIntentionPacket::new) -+ ) -+ ), -+ PLAY("play", protocol() -+ .addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) -+ .withBundlePacket(ClientboundBundlePacket.class, ClientboundBundlePacket::new) -+ .addPacket(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new) -+ .addPacket(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new) -+ .addPacket(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new) -+ .addPacket(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new) -+ .addPacket(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new) -+ .addPacket(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new) -+ .addPacket(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new) -+ .addPacket(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new) -+ .addPacket(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new) -+ .addPacket(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new) -+ .addPacket(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new) -+ .addPacket(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new) -+ .addPacket(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new) -+ .addPacket(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new) -+ .addPacket(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new) -+ .addPacket(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new) -+ .addPacket(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new) -+ .addPacket(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new) -+ .addPacket(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new) -+ .addPacket(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new) -+ .addPacket(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new) -+ .addPacket(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new) -+ .addPacket(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new) -+ .addPacket(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new) -+ .addPacket(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new) -+ .addPacket(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new) -+ .addPacket(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new) -+ .addPacket(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new) -+ .addPacket(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new) -+ .addPacket(ClientboundExplodePacket.class, ClientboundExplodePacket::new) -+ .addPacket(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new) -+ .addPacket(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new) -+ .addPacket(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new) -+ .addPacket(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new) -+ .addPacket(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new) -+ .addPacket(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new) -+ .addPacket(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new) -+ .addPacket(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new) -+ .addPacket(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new) -+ .addPacket(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new) -+ .addPacket(ClientboundLoginPacket.class, ClientboundLoginPacket::new) -+ .addPacket(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new) -+ .addPacket(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new) -+ .addPacket(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::read) -+ .addPacket(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::read) -+ .addPacket(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::read) -+ .addPacket(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new) -+ .addPacket(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new) -+ .addPacket(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new) -+ .addPacket(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new) -+ .addPacket(ClientboundPingPacket.class, ClientboundPingPacket::new) -+ .addPacket(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new) -+ .addPacket(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new) -+ .addPacket(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new) -+ .addPacket(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new) -+ .addPacket(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new) -+ .addPacket(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new) -+ .addPacket(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new) -+ .addPacket(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new) -+ .addPacket(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new) -+ .addPacket(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new) -+ .addPacket(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new) -+ .addPacket(ClientboundRecipePacket.class, ClientboundRecipePacket::new) -+ .addPacket(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new) -+ .addPacket(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new) -+ .addPacket(ClientboundResetScorePacket.class, ClientboundResetScorePacket::new) -+ .addPacket(ClientboundResourcePackPopPacket.class, ClientboundResourcePackPopPacket::new) -+ .addPacket(ClientboundResourcePackPushPacket.class, ClientboundResourcePackPushPacket::new) -+ .addPacket(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new) -+ .addPacket(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new) -+ .addPacket(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new) -+ .addPacket(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new) -+ .addPacket(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new) -+ .addPacket(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new) -+ .addPacket(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new) -+ .addPacket(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new) -+ .addPacket(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new) -+ .addPacket(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new) -+ .addPacket(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new) -+ .addPacket(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new) -+ .addPacket(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new) -+ .addPacket(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new) -+ .addPacket(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new) -+ .addPacket(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new) -+ .addPacket(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new) -+ .addPacket(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new) -+ .addPacket(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new) -+ .addPacket(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new) -+ .addPacket(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new) -+ .addPacket(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new) -+ .addPacket(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new) -+ .addPacket(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new) -+ .addPacket(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new) -+ .addPacket(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new) -+ .addPacket(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new) -+ .addPacket(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new) -+ .addPacket(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new) -+ .addPacket(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new) -+ .addPacket(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new) -+ .addPacket(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new) -+ .addPacket(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new) -+ .addPacket(ClientboundSoundPacket.class, ClientboundSoundPacket::new) -+ .addPacket(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new) -+ .addPacket(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new) -+ .addPacket(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new) -+ .addPacket(ClientboundTabListPacket.class, ClientboundTabListPacket::new) -+ .addPacket(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new) -+ .addPacket(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new) -+ .addPacket(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new) -+ .addPacket(ClientboundTickingStatePacket.class, ClientboundTickingStatePacket::new) -+ .addPacket(ClientboundTickingStepPacket.class, ClientboundTickingStepPacket::new) -+ .addPacket(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new) -+ .addPacket(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new) -+ .addPacket(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new) -+ .addPacket(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new) -+ .addPacket(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new) -+ ) -+ .addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new) -+ .addPacket(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new) -+ .addPacket(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new) -+ .addPacket(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new) -+ .addPacket(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new) -+ .addPacket(ServerboundChatPacket.class, ServerboundChatPacket::new) -+ .addPacket(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new) -+ .addPacket(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new) -+ .addPacket(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new) -+ .addPacket(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new) -+ .addPacket(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new) -+ .addPacket(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new) -+ .addPacket(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new) -+ .addPacket(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new) -+ .addPacket(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new) -+ .addPacket(ServerboundContainerSlotStateChangedPacket.class, ServerboundContainerSlotStateChangedPacket::new) -+ .addPacket(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new) -+ .addPacket(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new) -+ .addPacket(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new) -+ .addPacket(ServerboundInteractPacket.class, ServerboundInteractPacket::new) -+ .addPacket(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new) -+ .addPacket(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new) -+ .addPacket(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new) -+ .addPacket(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::read) -+ .addPacket(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::read) -+ .addPacket(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::read) -+ .addPacket(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::read) -+ .addPacket(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new) -+ .addPacket(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new) -+ .addPacket(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new) -+ .addPacket(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new) -+ .addPacket(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new) -+ .addPacket(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new) -+ .addPacket(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new) -+ .addPacket(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new) -+ .addPacket(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new) -+ .addPacket(ServerboundPongPacket.class, ServerboundPongPacket::new) -+ .addPacket(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new) -+ .addPacket(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new) -+ .addPacket(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new) -+ .addPacket(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new) -+ .addPacket(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new) -+ .addPacket(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new) -+ .addPacket(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new) -+ .addPacket(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new) -+ .addPacket(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new) -+ .addPacket(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new) -+ .addPacket(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new) -+ .addPacket(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new) -+ .addPacket(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new) -+ .addPacket(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new) -+ .addPacket(ServerboundSwingPacket.class, ServerboundSwingPacket::new) -+ .addPacket(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new) -+ .addPacket(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new) -+ .addPacket(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new) -+ ) -+ ), -+ STATUS("status", protocol() -+ .addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new) -+ .addPacket(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new) -+ ) -+ .addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new) -+ .addPacket(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new) -+ ) -+ ), -+ LOGIN("login", protocol() -+ .addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new) -+ .addPacket(ClientboundHelloPacket.class, ClientboundHelloPacket::new) -+ .addPacket(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new) -+ .addPacket(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new) -+ .addPacket(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new) -+ ) -+ .addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ServerboundHelloPacket.class, ServerboundHelloPacket::new) -+ .addPacket(ServerboundKeyPacket.class, ServerboundKeyPacket::new) -+ .addPacket(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::read) -+ .addPacket(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new) -+ ) -+ ), -+ CONFIGURATION("configuration", protocol() -+ .addFlow(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new) -+ .addPacket(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new) -+ .addPacket(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new) -+ .addPacket(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new) -+ .addPacket(ClientboundPingPacket.class, ClientboundPingPacket::new) -+ .addPacket(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new) -+ .addPacket(ClientboundResourcePackPopPacket.class, ClientboundResourcePackPopPacket::new) -+ .addPacket(ClientboundResourcePackPushPacket.class, ClientboundResourcePackPushPacket::new) -+ .addPacket(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new) -+ .addPacket(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new) -+ ) -+ .addFlow(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()) -+ .addPacket(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new) -+ .addPacket(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new) -+ .addPacket(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new) -+ .addPacket(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new) -+ .addPacket(ServerboundPongPacket.class, ServerboundPongPacket::new) -+ .addPacket(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new) -+ ) -+ ); - - public static final int NOT_REGISTERED = -1; - private final String id; diff --git a/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch b/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch deleted file mode 100644 index b0c56449c9..0000000000 --- a/patches/minecraft/net/minecraft/network/FriendlyByteBuf.java.patch +++ /dev/null @@ -1,47 +0,0 @@ ---- a/net/minecraft/network/FriendlyByteBuf.java -+++ b/net/minecraft/network/FriendlyByteBuf.java -@@ -80,7 +_,7 @@ - import org.joml.Quaternionf; - import org.joml.Vector3f; - --public class FriendlyByteBuf extends ByteBuf { -+public class FriendlyByteBuf extends ByteBuf implements net.minecraftforge.common.extensions.IForgeFriendlyByteBuf { - public static final int DEFAULT_NBT_QUOTA = 2097152; - private final ByteBuf source; - public static final short MAX_STRING_LENGTH = Short.MAX_VALUE; -@@ -578,6 +_,15 @@ - } - - public FriendlyByteBuf writeItem(ItemStack p_130056_) { -+ return writeItemStack(p_130056_, true); -+ } -+ -+ /** -+ * Most ItemStack serialization is Server to Client,and doesn't need to know the FULL tag details. -+ * One exception is items from the creative menu, which must be sent from Client to Server with their full NBT. -+ * If you want to send the FULL tag set limitedTag to false -+ */ -+ public FriendlyByteBuf writeItemStack(ItemStack p_130056_, boolean limitedTag) { - if (p_130056_.isEmpty()) { - this.writeBoolean(false); - } else { -@@ -586,8 +_,8 @@ - this.writeId(BuiltInRegistries.ITEM, item); - this.writeByte(p_130056_.getCount()); - CompoundTag compoundtag = null; -- if (item.canBeDepleted() || item.shouldOverrideMultiplayerNbt()) { -- compoundtag = p_130056_.getTag(); -+ if (item.isDamageable(p_130056_) || item.shouldOverrideMultiplayerNbt()) { -+ compoundtag = limitedTag ? p_130056_.getShareTag() : p_130056_.getTag(); - } - - this.writeNbt(compoundtag); -@@ -603,7 +_,7 @@ - Item item = this.readById(BuiltInRegistries.ITEM); - int i = this.readByte(); - ItemStack itemstack = new ItemStack(item, i); -- itemstack.setTag(this.readNbt()); -+ itemstack.readShareTag(this.readNbt()); - return itemstack; - } - } diff --git a/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch b/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch index 96b46f3668..4981978146 100644 --- a/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch +++ b/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/network/chat/contents/TranslatableContents.java +++ b/net/minecraft/network/chat/contents/TranslatableContents.java -@@ -153,6 +_,11 @@ +@@ -140,6 +_,11 @@ + j = l; } - } -+ if (j == 0) { -+ // Forge has some special formatting handlers defined in ForgeI18n, use those if no %s replacements present. -+ j = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, p_237517_, this.args, p_237516_); -+ } ++ if (j == 0) { ++ // Forge has some special formatting handlers defined in ForgeI18n, use those if no %s replacements present. ++ j = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, p_237517_, this.args, p_237516_); ++ } + - if (j < p_237516_.length()) { - String s3 = p_237516_.substring(j); - if (s3.indexOf(37) != -1) { + if (j < p_237516_.length()) { + String s3 = p_237516_.substring(j); + if (s3.indexOf(37) != -1) { diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch index f3ed2bf5e0..b988bc5fb7 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch @@ -1,30 +1,20 @@ --- a/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java -@@ -27,7 +_,7 @@ +@@ -32,7 +_,7 @@ import net.minecraft.network.protocol.common.custom.WorldGenAttemptDebugPayload; import net.minecraft.resources.ResourceLocation; -public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { +public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet, net.minecraftforge.network.ICustomPacket { - private static final int MAX_PAYLOAD_SIZE = 1048576; - private static final Map> KNOWN_TYPES = ImmutableMap.>builder().put(BrandPayload.ID, BrandPayload::new).put(BeeDebugPayload.ID, BeeDebugPayload::new).put(BrainDebugPayload.ID, BrainDebugPayload::new).put(BreezeDebugPayload.ID, BreezeDebugPayload::new).put(GameEventDebugPayload.ID, GameEventDebugPayload::new).put(GameEventListenerDebugPayload.ID, GameEventListenerDebugPayload::new).put(GameTestAddMarkerDebugPayload.ID, GameTestAddMarkerDebugPayload::new).put(GameTestClearMarkersDebugPayload.ID, GameTestClearMarkersDebugPayload::new).put(GoalDebugPayload.ID, GoalDebugPayload::new).put(HiveDebugPayload.ID, HiveDebugPayload::new).put(NeighborUpdatesDebugPayload.ID, NeighborUpdatesDebugPayload::new).put(PathfindingDebugPayload.ID, PathfindingDebugPayload::new).put(PoiAddedDebugPayload.ID, PoiAddedDebugPayload::new).put(PoiRemovedDebugPayload.ID, PoiRemovedDebugPayload::new).put(PoiTicketCountDebugPayload.ID, PoiTicketCountDebugPayload::new).put(RaidsDebugPayload.ID, RaidsDebugPayload::new).put(StructuresDebugPayload.ID, StructuresDebugPayload::new).put(VillageSectionsDebugPayload.ID, VillageSectionsDebugPayload::new).put(WorldGenAttemptDebugPayload.ID, WorldGenAttemptDebugPayload::new).build(); - -@@ -43,8 +_,7 @@ - private static DiscardedPayload readUnknownPayload(ResourceLocation p_299265_, FriendlyByteBuf p_297545_) { - int i = p_297545_.readableBytes(); - if (i >= 0 && i <= 1048576) { -- p_297545_.skipBytes(i); -- return new DiscardedPayload(p_299265_); -+ return new DiscardedPayload(p_299265_, new FriendlyByteBuf(p_297545_.readBytes(i))); - } else { - throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); - } -@@ -58,4 +_,8 @@ - public void handle(ClientCommonPacketListener p_299773_) { - p_299773_.handleCustomPayload(this); - } + private static final int MAX_PAYLOAD_SIZE = 1048576; + public static final StreamCodec GAMEPLAY_STREAM_CODEC = CustomPacketPayload.codec( + p_330149_ -> DiscardedPayload.codec(p_330149_, 1048576), +@@ -77,4 +_,8 @@ + public void handle(ClientCommonPacketListener p_299773_) { + p_299773_.handleCustomPayload(this); + } + -+ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; } -+ @Override public ResourceLocation getName() { return payload.id(); } -+ @Override public int getIndex() { return 0; } ++ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; } ++ @Override public ResourceLocation getName() { return payload.type().id(); } ++ @Override public int getIndex() { return 0; } } diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch index 8751605418..2be1567c83 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch @@ -1,30 +1,20 @@ --- a/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java -@@ -9,7 +_,7 @@ +@@ -12,7 +_,7 @@ import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.resources.ResourceLocation; -public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { +public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet, net.minecraftforge.network.ICustomPacket { - private static final int MAX_PAYLOAD_SIZE = 32767; - private static final Map> KNOWN_TYPES = ImmutableMap.>builder().put(BrandPayload.ID, BrandPayload::new).build(); - -@@ -25,8 +_,7 @@ - private static DiscardedPayload readUnknownPayload(ResourceLocation p_300234_, FriendlyByteBuf p_299925_) { - int i = p_299925_.readableBytes(); - if (i >= 0 && i <= 32767) { -- p_299925_.skipBytes(i); -- return new DiscardedPayload(p_300234_); -+ return new DiscardedPayload(p_300234_, new FriendlyByteBuf(p_299925_.readBytes(i))); - } else { - throw new IllegalArgumentException("Payload may not be larger than 32767 bytes"); - } -@@ -40,4 +_,8 @@ - public void handle(ServerCommonPacketListener p_297991_) { - p_297991_.handleCustomPayload(this); - } + private static final int MAX_PAYLOAD_SIZE = 32767; + public static final StreamCodec STREAM_CODEC = CustomPacketPayload.codec( + p_335203_ -> DiscardedPayload.codec(p_335203_, 32767), +@@ -29,4 +_,8 @@ + public void handle(ServerCommonPacketListener p_297991_) { + p_297991_.handleCustomPayload(this); + } + -+ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; } -+ @Override public ResourceLocation getName() { return payload.id(); } -+ @Override public int getIndex() { return 0; } ++ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; } ++ @Override public ResourceLocation getName() { return payload.type().id(); } ++ @Override public int getIndex() { return 0; } } diff --git a/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch index 35a5bc9c0d..346029f20b 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/custom/DiscardedPayload.java.patch @@ -1,18 +1,30 @@ --- a/net/minecraft/network/protocol/common/custom/DiscardedPayload.java +++ b/net/minecraft/network/protocol/common/custom/DiscardedPayload.java -@@ -3,8 +_,14 @@ - import net.minecraft.network.FriendlyByteBuf; +@@ -4,18 +_,24 @@ + import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; -public record DiscardedPayload(ResourceLocation id) implements CustomPacketPayload { +public record DiscardedPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomPacketPayload { -+ public DiscardedPayload(ResourceLocation id) { -+ this(id, null); -+ } + public static StreamCodec codec(ResourceLocation p_328904_, int p_334650_) { + return CustomPacketPayload.codec((p_330619_, p_329210_) -> { ++ if (p_330619_.data != null) { ++ p_329210_.writeBytes(p_330619_.data.slice()); ++ } + }, p_333509_ -> { + int i = p_333509_.readableBytes(); + if (i >= 0 && i <= p_334650_) { +- p_333509_.skipBytes(i); +- return new DiscardedPayload(p_328904_); ++ return new DiscardedPayload(p_328904_, new FriendlyByteBuf(p_333509_.readBytes(i))); + } else { + throw new IllegalArgumentException("Payload may not be larger than " + p_334650_ + " bytes"); + } + }); ++ } + - public void write(FriendlyByteBuf p_301050_) { -+ if (data != null) -+ p_301050_.writeBytes(data.slice()); - } ++ public DiscardedPayload(ResourceLocation id) { ++ this(id, null); + } - public ResourceLocation id() { + @Override diff --git a/patches/minecraft/net/minecraft/network/protocol/game/ServerboundContainerClickPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/game/ServerboundContainerClickPacket.java.patch deleted file mode 100644 index fb7a7cfa5c..0000000000 --- a/patches/minecraft/net/minecraft/network/protocol/game/ServerboundContainerClickPacket.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/network/protocol/game/ServerboundContainerClickPacket.java -+++ b/net/minecraft/network/protocol/game/ServerboundContainerClickPacket.java -@@ -49,7 +_,7 @@ - p_133961_.writeByte(this.buttonNum); - p_133961_.writeEnum(this.clickType); - p_133961_.writeMap(this.changedSlots, FriendlyByteBuf::writeShort, FriendlyByteBuf::writeItem); -- p_133961_.writeItem(this.carriedItem); -+ p_133961_.writeItemStack(this.carriedItem, false); //Forge: Include full tag for C->S - } - - public void handle(ServerGamePacketListener p_133958_) { diff --git a/patches/minecraft/net/minecraft/network/protocol/game/ServerboundSetCreativeModeSlotPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/game/ServerboundSetCreativeModeSlotPacket.java.patch deleted file mode 100644 index e43ba89d5a..0000000000 --- a/patches/minecraft/net/minecraft/network/protocol/game/ServerboundSetCreativeModeSlotPacket.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/network/protocol/game/ServerboundSetCreativeModeSlotPacket.java -+++ b/net/minecraft/network/protocol/game/ServerboundSetCreativeModeSlotPacket.java -@@ -24,7 +_,7 @@ - - public void write(FriendlyByteBuf p_134563_) { - p_134563_.writeShort(this.slotNum); -- p_134563_.writeItem(this.itemStack); -+ p_134563_.writeItemStack(this.itemStack, false); //Forge: Include full tag for C->S - } - - public int getSlotNum() { diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch index 772ec61e45..271c998112 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java +++ b/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java -@@ -6,7 +_,7 @@ +@@ -8,7 +_,7 @@ import net.minecraft.network.protocol.login.custom.DiscardedQueryPayload; import net.minecraft.resources.ResourceLocation; -public record ClientboundCustomQueryPacket(int transactionId, CustomQueryPayload payload) implements Packet { +public record ClientboundCustomQueryPacket(int transactionId, CustomQueryPayload payload) implements Packet, net.minecraftforge.network.ICustomPacket { - private static final int MAX_PAYLOAD_SIZE = 1048576; - - public ClientboundCustomQueryPacket(FriendlyByteBuf p_179810_) { -@@ -20,8 +_,7 @@ - private static DiscardedQueryPayload readUnknownPayload(ResourceLocation p_299981_, FriendlyByteBuf p_297706_) { - int i = p_297706_.readableBytes(); - if (i >= 0 && i <= 1048576) { -- p_297706_.skipBytes(i); -- return new DiscardedQueryPayload(p_299981_); -+ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i))); - } else { - throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); - } -@@ -36,4 +_,8 @@ - public void handle(ClientLoginPacketListener p_134754_) { - p_134754_.handleCustomQuery(this); - } + public static final StreamCodec STREAM_CODEC = Packet.codec( + ClientboundCustomQueryPacket::write, ClientboundCustomQueryPacket::new + ); +@@ -25,8 +_,7 @@ + private static DiscardedQueryPayload readUnknownPayload(ResourceLocation p_299981_, FriendlyByteBuf p_297706_) { + int i = p_297706_.readableBytes(); + if (i >= 0 && i <= 1048576) { +- p_297706_.skipBytes(i); +- return new DiscardedQueryPayload(p_299981_); ++ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i))); + } else { + throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); + } +@@ -46,4 +_,8 @@ + public void handle(ClientLoginPacketListener p_134754_) { + p_134754_.handleCustomQuery(this); + } + -+ @Override public int getIndex() { return transactionId(); } -+ @Override public ResourceLocation getName() { return this.payload.id(); } -+ @org.jetbrains.annotations.Nullable @Override public FriendlyByteBuf getInternalData() { return ((DiscardedQueryPayload)this.payload).data(); } ++ @Override public int getIndex() { return transactionId(); } ++ @Override public ResourceLocation getName() { return this.payload.id(); } ++ @org.jetbrains.annotations.Nullable @Override public FriendlyByteBuf getInternalData() { return ((DiscardedQueryPayload)this.payload).data(); } } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch index d21e5dd918..87b362ea33 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java +++ b/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java -@@ -6,7 +_,7 @@ +@@ -8,7 +_,7 @@ import net.minecraft.network.protocol.login.custom.CustomQueryAnswerPayload; import net.minecraft.network.protocol.login.custom.DiscardedQueryAnswerPayload; -public record ServerboundCustomQueryAnswerPacket(int transactionId, @Nullable CustomQueryAnswerPayload payload) implements Packet { +public record ServerboundCustomQueryAnswerPacket(int transactionId, @Nullable CustomQueryAnswerPayload payload) implements Packet, net.minecraftforge.network.ICustomPacket { - private static final int MAX_PAYLOAD_SIZE = 1048576; - - public static ServerboundCustomQueryAnswerPacket read(FriendlyByteBuf p_300962_) { -@@ -21,8 +_,7 @@ - private static CustomQueryAnswerPayload readUnknownPayload(FriendlyByteBuf p_299934_) { - int i = p_299934_.readableBytes(); - if (i >= 0 && i <= 1048576) { -- p_299934_.skipBytes(i); -- return DiscardedQueryAnswerPayload.INSTANCE; -+ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i))); - } else { - throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); - } -@@ -38,4 +_,8 @@ - public void handle(ServerLoginPacketListener p_298492_) { - p_298492_.handleCustomQueryPacket(this); - } + public static final StreamCodec STREAM_CODEC = Packet.codec( + ServerboundCustomQueryAnswerPacket::write, ServerboundCustomQueryAnswerPacket::read + ); +@@ -26,8 +_,7 @@ + private static CustomQueryAnswerPayload readUnknownPayload(FriendlyByteBuf p_299934_) { + int i = p_299934_.readableBytes(); + if (i >= 0 && i <= 1048576) { +- p_299934_.skipBytes(i); +- return DiscardedQueryAnswerPayload.INSTANCE; ++ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i))); + } else { + throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); + } +@@ -46,4 +_,8 @@ + public void handle(ServerLoginPacketListener p_298492_) { + p_298492_.handleCustomQueryPacket(this); + } + -+ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.payload instanceof DiscardedQueryAnswerPayload dc ? dc.data() : null; } -+ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.NetworkInitialization.LOGIN_NAME; } -+ @Override public int getIndex() { return transactionId(); } ++ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.payload instanceof DiscardedQueryAnswerPayload dc ? dc.data() : null; } ++ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.NetworkInitialization.LOGIN_NAME; } ++ @Override public int getIndex() { return transactionId(); } } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch index d495c1c630..de96425590 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java.patch @@ -1,19 +1,21 @@ --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java -@@ -2,9 +_,15 @@ +@@ -2,10 +_,17 @@ import net.minecraft.network.FriendlyByteBuf; -public record DiscardedQueryAnswerPayload() implements CustomQueryAnswerPayload { +public record DiscardedQueryAnswerPayload(@javax.annotation.Nullable FriendlyByteBuf data) implements CustomQueryAnswerPayload { - public static final DiscardedQueryAnswerPayload INSTANCE = new DiscardedQueryAnswerPayload(); + public static final DiscardedQueryAnswerPayload INSTANCE = new DiscardedQueryAnswerPayload(); -+ public DiscardedQueryAnswerPayload() { -+ this(null); -+ } ++ public DiscardedQueryAnswerPayload() { ++ this(null); ++ } + - public void write(FriendlyByteBuf p_299186_) { -+ if (this.data != null) -+ p_299186_.writeBytes(this.data.slice()); - } + @Override + public void write(FriendlyByteBuf p_299186_) { ++ if (this.data != null) { ++ p_299186_.writeBytes(this.data.slice()); ++ } + } } diff --git a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch index 25793ba9a5..d47bc82c69 100644 --- a/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java.patch @@ -1,18 +1,23 @@ --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java -@@ -3,8 +_,14 @@ +@@ -3,12 +_,18 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; -public record DiscardedQueryPayload(ResourceLocation id) implements CustomQueryPayload { +public record DiscardedQueryPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomQueryPayload { -+ public DiscardedQueryPayload(ResourceLocation id) { -+ this(id, null); -+ } ++ public DiscardedQueryPayload(ResourceLocation id) { ++ this(id, null); ++ } + - public void write(FriendlyByteBuf p_299949_) { -+ if (this.data != null) -+ p_299949_.writeBytes(this.data.slice()); - } + @Override + public void write(FriendlyByteBuf p_299949_) { ++ if (this.data != null) { ++ p_299949_.writeBytes(this.data.slice()); ++ } + } - public ResourceLocation id() { +- @Override + public ResourceLocation id() { + return this.id; + } diff --git a/patches/minecraft/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java.patch index 57848fa3db..db8640a673 100644 --- a/patches/minecraft/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java.patch @@ -1,22 +1,26 @@ --- a/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java +++ b/net/minecraft/network/protocol/status/ClientboundStatusResponsePacket.java -@@ -3,12 +_,18 @@ - import net.minecraft.network.FriendlyByteBuf; +@@ -5,16 +_,22 @@ import net.minecraft.network.protocol.Packet; + import net.minecraft.network.protocol.PacketType; -public record ClientboundStatusResponsePacket(ServerStatus status) implements Packet { +public record ClientboundStatusResponsePacket(ServerStatus status, @org.jetbrains.annotations.Nullable String cachedStatus) implements Packet { -+ public ClientboundStatusResponsePacket(ServerStatus status) { -+ this(status, null); -+ } + public static final StreamCodec STREAM_CODEC = Packet.codec( + ClientboundStatusResponsePacket::write, ClientboundStatusResponsePacket::new + ); + ++ public ClientboundStatusResponsePacket(ServerStatus status) { ++ this(status, null); ++ } + - public ClientboundStatusResponsePacket(FriendlyByteBuf p_179834_) { - this(p_179834_.readJsonWithCodec(ServerStatus.CODEC)); - } + private ClientboundStatusResponsePacket(FriendlyByteBuf p_179834_) { + this(p_179834_.readJsonWithCodec(ServerStatus.CODEC)); + } - public void write(FriendlyByteBuf p_134899_) { -+ if (cachedStatus != null) p_134899_.writeUtf(cachedStatus); -+ else - p_134899_.writeJsonWithCodec(ServerStatus.CODEC, this.status); - } + private void write(FriendlyByteBuf p_134899_) { ++ if (cachedStatus != null) p_134899_.writeUtf(cachedStatus); ++ else + p_134899_.writeJsonWithCodec(ServerStatus.CODEC, this.status); + } diff --git a/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch b/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch index 9f8646cb76..067e08f8fb 100644 --- a/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch @@ -1,14 +1,22 @@ --- a/net/minecraft/network/protocol/status/ServerStatus.java +++ b/net/minecraft/network/protocol/status/ServerStatus.java -@@ -15,9 +_,9 @@ - import net.minecraft.network.chat.Component; - import net.minecraft.network.chat.ComponentSerialization; - --public record ServerStatus(Component description, Optional players, Optional version, Optional favicon, boolean enforcesSecureChat) { -+public record ServerStatus(Component description, Optional players, Optional version, Optional favicon, boolean enforcesSecureChat, Optional forgeData) { - public static final Codec CODEC = RecordCodecBuilder.create((p_308583_) -> { -- return p_308583_.group(ComponentSerialization.CODEC.optionalFieldOf("description", CommonComponents.EMPTY).forGetter(ServerStatus::description), ServerStatus.Players.CODEC.optionalFieldOf("players").forGetter(ServerStatus::players), ServerStatus.Version.CODEC.optionalFieldOf("version").forGetter(ServerStatus::version), ServerStatus.Favicon.CODEC.optionalFieldOf("favicon").forGetter(ServerStatus::favicon), Codec.BOOL.optionalFieldOf("enforcesSecureChat", Boolean.valueOf(false)).forGetter(ServerStatus::enforcesSecureChat)).apply(p_308583_, ServerStatus::new); -+ return p_308583_.group(ComponentSerialization.CODEC.optionalFieldOf("description", CommonComponents.EMPTY).forGetter(ServerStatus::description), ServerStatus.Players.CODEC.optionalFieldOf("players").forGetter(ServerStatus::players), ServerStatus.Version.CODEC.optionalFieldOf("version").forGetter(ServerStatus::version), ServerStatus.Favicon.CODEC.optionalFieldOf("favicon").forGetter(ServerStatus::favicon), Codec.BOOL.optionalFieldOf("enforcesSecureChat", Boolean.valueOf(false)).forGetter(ServerStatus::enforcesSecureChat), net.minecraftforge.network.ServerStatusPing.CODEC.optionalFieldOf("forgeData").forGetter(ServerStatus::forgeData)).apply(p_308583_, ServerStatus::new); - }); - - public static record Favicon(byte[] iconBytes) { +@@ -21,7 +_,8 @@ + Optional players, + Optional version, + Optional favicon, +- boolean enforcesSecureChat ++ boolean enforcesSecureChat, ++ Optional forgeData + ) { + public static final Codec CODEC = RecordCodecBuilder.create( + p_326135_ -> p_326135_.group( +@@ -29,7 +_,8 @@ + ServerStatus.Players.CODEC.lenientOptionalFieldOf("players").forGetter(ServerStatus::players), + ServerStatus.Version.CODEC.lenientOptionalFieldOf("version").forGetter(ServerStatus::version), + ServerStatus.Favicon.CODEC.lenientOptionalFieldOf("favicon").forGetter(ServerStatus::favicon), +- Codec.BOOL.lenientOptionalFieldOf("enforcesSecureChat", Boolean.valueOf(false)).forGetter(ServerStatus::enforcesSecureChat) ++ Codec.BOOL.lenientOptionalFieldOf("enforcesSecureChat", Boolean.valueOf(false)).forGetter(ServerStatus::enforcesSecureChat), ++ net.minecraftforge.network.ServerStatusPing.CODEC.optionalFieldOf("forgeData").forGetter(ServerStatus::forgeData) + ) + .apply(p_326135_, ServerStatus::new) + ); diff --git a/patches/minecraft/net/minecraft/network/syncher/EntityDataSerializers.java.patch b/patches/minecraft/net/minecraft/network/syncher/EntityDataSerializers.java.patch index dc275ca4bd..58a08ca5b6 100644 --- a/patches/minecraft/net/minecraft/network/syncher/EntityDataSerializers.java.patch +++ b/patches/minecraft/net/minecraft/network/syncher/EntityDataSerializers.java.patch @@ -1,22 +1,21 @@ --- a/net/minecraft/network/syncher/EntityDataSerializers.java +++ b/net/minecraft/network/syncher/EntityDataSerializers.java -@@ -142,16 +_,16 @@ - public static final EntityDataSerializer QUATERNION = EntityDataSerializer.simple(FriendlyByteBuf::writeQuaternion, FriendlyByteBuf::readQuaternion); +@@ -121,15 +_,16 @@ - public static void registerSerializer(EntityDataSerializer p_135051_) { -- SERIALIZERS.add(p_135051_); -+ if (SERIALIZERS.add(p_135051_) >= 256) throw new RuntimeException("Vanilla DataSerializer ID limit exceeded"); - } + public static void registerSerializer(EntityDataSerializer p_135051_) { + SERIALIZERS.add(p_135051_); ++ if (SERIALIZERS.add(p_135051_) >= 256) throw new RuntimeException("Vanilla DataSerializer ID limit exceeded"); + } - @Nullable - public static EntityDataSerializer getSerializer(int p_135049_) { -- return SERIALIZERS.byId(p_135049_); -+ return net.minecraftforge.common.ForgeHooks.getSerializer(p_135049_, SERIALIZERS); - } + @Nullable + public static EntityDataSerializer getSerializer(int p_135049_) { +- return SERIALIZERS.byId(p_135049_); ++ return net.minecraftforge.common.ForgeHooks.getSerializer(p_135049_, SERIALIZERS); + } - public static int getSerializedId(EntityDataSerializer p_135053_) { -- return SERIALIZERS.getId(p_135053_); -+ return net.minecraftforge.common.ForgeHooks.getSerializerId(p_135053_, SERIALIZERS); - } + public static int getSerializedId(EntityDataSerializer p_135053_) { +- return SERIALIZERS.getId(p_135053_); ++ return net.minecraftforge.common.ForgeHooks.getSerializerId(p_135053_, SERIALIZERS); + } - private EntityDataSerializers() { + private EntityDataSerializers() { diff --git a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch index b13f71afc6..6584384f13 100644 --- a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch +++ b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/network/syncher/SynchedEntityData.java +++ b/net/minecraft/network/syncher/SynchedEntityData.java -@@ -36,11 +_,13 @@ - } +@@ -27,11 +_,13 @@ + } - public static EntityDataAccessor defineId(Class p_135354_, EntityDataSerializer p_135355_) { -- if (LOGGER.isDebugEnabled()) { -+ if (true || LOGGER.isDebugEnabled()) { // Forge: This is very useful for mods that register keys on classes that are not their own - try { - Class oclass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); - if (!oclass.equals(p_135354_)) { -- LOGGER.debug("defineId called for: {} from {}", p_135354_, oclass, new RuntimeException()); -+ // Forge: log at warn, mods should not add to classes that they don't own, and only add stacktrace when in debug is enabled as it is mostly not needed and consumes time -+ if (LOGGER.isDebugEnabled()) LOGGER.warn("defineId called for: {} from {}", p_135354_, oclass, new RuntimeException()); -+ else LOGGER.warn("defineId called for: {} from {}", p_135354_, oclass); + public static EntityDataAccessor defineId(Class p_135354_, EntityDataSerializer p_135355_) { +- if (LOGGER.isDebugEnabled()) { ++ if (true) { // Forge: This is very useful for mods that register keys on classes that are not their own + try { + Class oclass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); + if (!oclass.equals(p_135354_)) { +- LOGGER.debug("defineId called for: {} from {}", p_135354_, oclass, new RuntimeException()); ++ // Forge: log at warn, mods should not add to classes that they don't own, and only add stacktrace when in debug is enabled as it is mostly not needed and consumes time ++ if (LOGGER.isDebugEnabled()) LOGGER.warn("defineId called for: {} from {}", p_135354_, oclass, new RuntimeException()); ++ else LOGGER.warn("defineId called for: {} from {}", p_135354_, oclass); + } + } catch (ClassNotFoundException classnotfoundexception) { } - } catch (ClassNotFoundException classnotfoundexception) { - } diff --git a/patches/minecraft/net/minecraft/recipebook/PlaceRecipe.java.patch b/patches/minecraft/net/minecraft/recipebook/PlaceRecipe.java.patch index e0b3d195e0..1d50f967b3 100644 --- a/patches/minecraft/net/minecraft/recipebook/PlaceRecipe.java.patch +++ b/patches/minecraft/net/minecraft/recipebook/PlaceRecipe.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/recipebook/PlaceRecipe.java +++ b/net/minecraft/recipebook/PlaceRecipe.java -@@ -11,9 +_,9 @@ - int i = p_135409_; - int j = p_135410_; - Recipe recipe = p_298822_.value(); -- if (recipe instanceof ShapedRecipe shapedrecipe) { -- i = shapedrecipe.getWidth(); -- j = shapedrecipe.getHeight(); -+ if (recipe instanceof net.minecraftforge.common.crafting.IShapedRecipe shapedrecipe) { -+ i = shapedrecipe.getRecipeWidth(); -+ j = shapedrecipe.getRecipeHeight(); - } +@@ -9,9 +_,9 @@ + default void placeRecipe(int p_135409_, int p_135410_, int p_135411_, RecipeHolder p_298822_, Iterator p_135413_, int p_135414_) { + int i = p_135409_; + int j = p_135410_; +- if (p_298822_.value() instanceof ShapedRecipe shapedrecipe) { +- i = shapedrecipe.getWidth(); +- j = shapedrecipe.getHeight(); ++ if (p_298822_.value() instanceof net.minecraftforge.common.crafting.IShapedRecipe shapedrecipe) { ++ i = shapedrecipe.getRecipeWidth(); ++ j = shapedrecipe.getRecipeHeight(); + } - int k1 = 0; + int k1 = 0; diff --git a/patches/minecraft/net/minecraft/resources/DelegatingOps.java.patch b/patches/minecraft/net/minecraft/resources/DelegatingOps.java.patch index 01053cdbb7..204d236add 100644 --- a/patches/minecraft/net/minecraft/resources/DelegatingOps.java.patch +++ b/patches/minecraft/net/minecraft/resources/DelegatingOps.java.patch @@ -1,40 +1,33 @@ --- a/net/minecraft/resources/DelegatingOps.java +++ b/net/minecraft/resources/DelegatingOps.java -@@ -160,4 +_,37 @@ - public RecordBuilder mapBuilder() { - return new RecordBuilder.MapBuilder<>(this); - } +@@ -216,11 +_,29 @@ + + @Override + public ListBuilder listBuilder() { +- return new Builder<>(this); ++ return new ListBuilder.Builder<>(this); + } + + @Override + public RecordBuilder mapBuilder() { + return new MapBuilder<>(this); ++ } + -+ java.util.Map ctx; -+ public R getContext(ResourceLocation rl) { -+ return (R)this.ctx.get(rl); -+ } ++ // Forge start ++ java.util.Map ctx = new java.util.HashMap<>(); + -+ public static > Builder builder(java.util.function.Supplier root) { -+ return new Builder(root); -+ } ++ @SuppressWarnings("unchecked") ++ public R getContext(ResourceLocation rl) { ++ var ret = (R)this.ctx.get(rl); ++ if (ret == null && this.delegate instanceof DelegatingOps parent) { ++ return (R)parent.getContext(rl); ++ } ++ return ret; ++ } + -+ public static Builder> builder(DynamicOps ops) { -+ return builder(() -> new DelegatingOps<>(ops) {}); -+ } -+ -+ public static class Builder> { -+ private final java.util.function.Supplier func; -+ private final java.util.Map ctx = new java.util.HashMap<>(); -+ -+ private Builder(java.util.function.Supplier func) { -+ this.func = func; -+ } -+ -+ public Builder with(ResourceLocation key, Object ctx) { -+ this.ctx.put(key, ctx); -+ return this; -+ } -+ -+ public R build() { -+ var ret = this.func.get(); -+ ret.ctx = this.ctx; -+ return ret; -+ } -+ } ++ @SuppressWarnings("unchecked") ++ public R withContext(ResourceLocation key, Object ctx) { ++ this.ctx.put(key, ctx); ++ return (R)this; + } } diff --git a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch index a0c4ec91e1..c459573e61 100644 --- a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch +++ b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch @@ -1,45 +1,51 @@ --- a/net/minecraft/resources/HolderSetCodec.java +++ b/net/minecraft/resources/HolderSetCodec.java @@ -21,6 +_,8 @@ - private final Codec> elementCodec; - private final Codec>> homogenousListCodec; - private final Codec, List>>> registryAwareCodec; -+ private final Codec> forgeDispatchCodec; -+ private final Codec, Either, List>>>> combinedCodec; + private final Codec> elementCodec; + private final Codec>> homogenousListCodec; + private final Codec, List>>> registryAwareCodec; ++ private final Codec> forgeDispatchCodec; ++ private final Codec, Either, List>>>> combinedCodec; - private static Codec>> homogenousList(Codec> p_206668_, boolean p_206669_) { - Codec>> codec = ExtraCodecs.validate(p_206668_.listOf(), ExtraCodecs.ensureHomogenous(Holder::kind)); + private static Codec>> homogenousList(Codec> p_206668_, boolean p_206669_) { + Codec>> codec = p_206668_.listOf().validate(ExtraCodecs.ensureHomogenous(Holder::kind)); @@ -42,6 +_,10 @@ - this.elementCodec = p_206661_; - this.homogenousListCodec = homogenousList(p_206661_, p_206662_); - this.registryAwareCodec = Codec.either(TagKey.hashedCodec(p_206660_), this.homogenousListCodec); -+ // FORGE: make registry-specific dispatch codec and make forge-or-vanilla either codec -+ this.forgeDispatchCodec = ExtraCodecs.lazyInitializedCodec(() -> net.minecraftforge.registries.ForgeRegistries.HOLDER_SET_TYPES.get().getCodec()) -+ .dispatch(net.minecraftforge.registries.holdersets.ICustomHolderSet::type, type -> type.makeCodec(p_206660_, p_206661_, p_206662_)); -+ this.combinedCodec = new ExtraCodecs.EitherCodec<>(this.forgeDispatchCodec, this.registryAwareCodec); - } + this.elementCodec = p_206661_; + this.homogenousListCodec = homogenousList(p_206661_, p_206662_); + this.registryAwareCodec = Codec.either(TagKey.hashedCodec(p_206660_), this.homogenousListCodec); ++ // FORGE: make registry-specific dispatch codec and make forge-or-vanilla either codec ++ this.forgeDispatchCodec = Codec.lazyInitialized(() -> net.minecraftforge.registries.ForgeRegistries.HOLDER_SET_TYPES.get().getCodec()) ++ .dispatch(net.minecraftforge.registries.holdersets.ICustomHolderSet::type, type -> type.makeCodec(p_206660_, p_206661_, p_206662_)); ++ this.combinedCodec = Codec.either(this.forgeDispatchCodec, this.registryAwareCodec); + } - public DataResult, T>> decode(DynamicOps p_206696_, T p_206697_) { -@@ -49,9 +_,10 @@ - Optional> optional = registryops.getter(this.registryKey); - if (optional.isPresent()) { - HolderGetter holdergetter = optional.get(); -- return this.registryAwareCodec.decode(p_206696_, p_206697_).map((p_206682_) -> { -+ // FORGE: use the wrapped codec to decode custom/tag/list instead of just tag/list -+ return this.combinedCodec.decode(p_206696_, p_206697_).map((p_206682_) -> { - return p_206682_.mapFirst((p_206679_) -> { -- return p_206679_.map(holdergetter::getOrThrow, HolderSet::direct); -+ return p_206679_.map(java.util.function.Function.identity(), tagOrList -> tagOrList.map(holdergetter::getOrThrow, HolderSet::direct)); - }); - }); - } -@@ -70,6 +_,9 @@ - }); - } + @Override +@@ -50,14 +_,17 @@ + Optional> optional = registryops.getter(this.registryKey); + if (optional.isPresent()) { + HolderGetter holdergetter = optional.get(); +- return this.registryAwareCodec ++ return this.combinedCodec + .decode(p_206696_, p_206697_) + .flatMap( + p_326147_ -> { + DataResult> dataresult = p_326147_.getFirst() ++ .map(custom -> DataResult.success(custom), ++ tagOrList -> tagOrList + .map( + p_326145_ -> lookupTag(holdergetter, (TagKey)p_326145_), + p_326140_ -> DataResult.success(HolderSet.direct((List>)p_326140_)) ++ ) + ); + return dataresult.map(p_326149_ -> Pair.of((HolderSet)p_326149_, (T)p_326147_.getSecond())); + } +@@ -106,6 +_,9 @@ + } -+ // FORGE: use the dispatch codec to encode custom holdersets, otherwise fall back to vanilla tag/list -+ if (p_206674_ instanceof net.minecraftforge.registries.holdersets.ICustomHolderSet customHolderSet) -+ return this.forgeDispatchCodec.encode(customHolderSet, p_206675_, p_206676_); - return this.registryAwareCodec.encode(p_206674_.unwrap().mapRight(List::copyOf), p_206675_, p_206676_); - } - } + private DataResult encodeWithoutRegistry(HolderSet p_206690_, DynamicOps p_206691_, T p_206692_) { ++ // FORGE: use the dispatch codec to encode custom holdersets, otherwise fall back to vanilla tag/list ++ if (p_206690_ instanceof net.minecraftforge.registries.holdersets.ICustomHolderSet customHolderSet) ++ return this.forgeDispatchCodec.encode(customHolderSet, p_206691_, p_206692_); + return this.homogenousListCodec.encode(p_206690_.stream().toList(), p_206691_, p_206692_); + } + } diff --git a/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch b/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch index 5ca2734aea..7e208d4438 100644 --- a/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch +++ b/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch @@ -1,61 +1,101 @@ --- a/net/minecraft/resources/RegistryDataLoader.java +++ b/net/minecraft/resources/RegistryDataLoader.java -@@ -51,9 +_,13 @@ +@@ -66,7 +_,7 @@ + Lifecycle lifecycle = p_326161_.map(KnownPack::isVanilla).map(p_326166_ -> Lifecycle.stable()).orElse(Lifecycle.experimental()); + return new RegistrationInfo(p_326161_, lifecycle); + }); +- public static final List> WORLDGEN_REGISTRIES = List.of( ++ public static final List> WORLDGEN_REGISTRIES = net.minecraftforge.registries.DataPackRegistriesHooks.grabWorldgenRegistries( + new RegistryDataLoader.RegistryData<>(Registries.DIMENSION_TYPE, DimensionType.DIRECT_CODEC), + new RegistryDataLoader.RegistryData<>(Registries.BIOME, Biome.DIRECT_CODEC), + new RegistryDataLoader.RegistryData<>(Registries.CHAT_TYPE, ChatType.DIRECT_CODEC), +@@ -103,6 +_,10 @@ + new RegistryDataLoader.RegistryData<>(Registries.BANNER_PATTERN, BannerPattern.DIRECT_CODEC) + ); - public class RegistryDataLoader { - private static final Logger LOGGER = LogUtils.getLogger(); -- public static final List> WORLDGEN_REGISTRIES = List.of(new RegistryDataLoader.RegistryData<>(Registries.DIMENSION_TYPE, DimensionType.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.BIOME, Biome.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.CHAT_TYPE, ChatType.CODEC), new RegistryDataLoader.RegistryData<>(Registries.CONFIGURED_CARVER, ConfiguredWorldCarver.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.CONFIGURED_FEATURE, ConfiguredFeature.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.PLACED_FEATURE, PlacedFeature.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.STRUCTURE, Structure.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.STRUCTURE_SET, StructureSet.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.PROCESSOR_LIST, StructureProcessorType.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TEMPLATE_POOL, StructureTemplatePool.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.NOISE_SETTINGS, NoiseGeneratorSettings.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.NOISE, NormalNoise.NoiseParameters.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.DENSITY_FUNCTION, DensityFunction.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.WORLD_PRESET, WorldPreset.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.FLAT_LEVEL_GENERATOR_PRESET, FlatLevelGeneratorPreset.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TRIM_PATTERN, TrimPattern.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TRIM_MATERIAL, TrimMaterial.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.DAMAGE_TYPE, DamageType.CODEC), new RegistryDataLoader.RegistryData<>(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST, MultiNoiseBiomeSourceParameterList.DIRECT_CODEC)); -+ public static final List> WORLDGEN_REGISTRIES = net.minecraftforge.registries.DataPackRegistriesHooks.grabWorldgenRegistries(new RegistryDataLoader.RegistryData<>(Registries.DIMENSION_TYPE, DimensionType.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.BIOME, Biome.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.CHAT_TYPE, ChatType.CODEC), new RegistryDataLoader.RegistryData<>(Registries.CONFIGURED_CARVER, ConfiguredWorldCarver.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.CONFIGURED_FEATURE, ConfiguredFeature.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.PLACED_FEATURE, PlacedFeature.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.STRUCTURE, Structure.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.STRUCTURE_SET, StructureSet.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.PROCESSOR_LIST, StructureProcessorType.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TEMPLATE_POOL, StructureTemplatePool.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.NOISE_SETTINGS, NoiseGeneratorSettings.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.NOISE, NormalNoise.NoiseParameters.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.DENSITY_FUNCTION, DensityFunction.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.WORLD_PRESET, WorldPreset.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.FLAT_LEVEL_GENERATOR_PRESET, FlatLevelGeneratorPreset.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TRIM_PATTERN, TrimPattern.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TRIM_MATERIAL, TrimMaterial.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.DAMAGE_TYPE, DamageType.CODEC), new RegistryDataLoader.RegistryData<>(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST, MultiNoiseBiomeSourceParameterList.DIRECT_CODEC)); - public static final List> DIMENSION_REGISTRIES = List.of(new RegistryDataLoader.RegistryData<>(Registries.LEVEL_STEM, LevelStem.CODEC)); - -+ public static java.util.stream.Stream> getWorldGenAndDimensionStream() { -+ return java.util.stream.Stream.concat(RegistryDataLoader.WORLDGEN_REGISTRIES.stream(), RegistryDataLoader.DIMENSION_REGISTRIES.stream()); -+ } ++ public static java.util.stream.Stream> getWorldGenAndDimensionStream() { ++ return java.util.stream.Stream.concat(RegistryDataLoader.WORLDGEN_REGISTRIES.stream(), RegistryDataLoader.DIMENSION_REGISTRIES.stream()); ++ } + - public static RegistryAccess.Frozen load(ResourceManager p_252046_, RegistryAccess p_249916_, List> p_250344_) { - Map, Exception> map = new HashMap<>(); - List, RegistryDataLoader.Loader>> list = p_250344_.stream().map((p_250249_) -> { -@@ -75,7 +_,9 @@ - }); - if (!map.isEmpty()) { - logErrors(map); -- throw new IllegalStateException("Failed to load registries due to above errors"); -+ var buf = new StringBuilder("Failed to load registries, see debug.log for more details:"); -+ map.forEach((k,v) -> buf.append("\n\t").append(k.toString()).append(": ").append(v.getMessage())); -+ throw new IllegalStateException(buf.toString()); - } else { - return (new RegistryAccess.ImmutableRegistryAccess(list.stream().map(Pair::getFirst).toList())).freeze(); - } -@@ -124,13 +_,16 @@ - } + public static RegistryAccess.Frozen load(ResourceManager p_252046_, RegistryAccess p_249916_, List> p_250344_) { + return load((p_326156_, p_326157_) -> p_326156_.loadFromResources(p_252046_, p_326157_), p_249916_, p_250344_); + } +@@ -136,7 +_,9 @@ + }); + if (!map.isEmpty()) { + logErrors(map); +- throw new IllegalStateException("Failed to load registries due to above errors"); ++ var buf = new StringBuilder("Failed to load registries, see debug.log for more details:"); ++ map.forEach((k,v) -> buf.append("\n\t").append(k.toString()).append(": ").append(v.getMessage())); ++ throw new IllegalStateException(buf.toString()); + } else { + return new RegistryAccess.ImmutableRegistryAccess(list.stream().map(RegistryDataLoader.Loader::registry).toList()).freeze(); + } +@@ -184,12 +_,12 @@ + } - private static String registryDirPath(ResourceLocation p_252033_) { -- return p_252033_.getPath(); -+ return net.minecraftforge.common.ForgeHooks.prefixNamespace(p_252033_); // FORGE: add non-vanilla registry namespace to loader directory, same format as tag directory (see net.minecraft.tags.TagManager#getTagDir(ResourceKey)) - } + private static String registryDirPath(ResourceLocation p_252033_) { +- return p_252033_.getPath(); ++ return net.minecraftforge.common.ForgeHooks.prefixNamespace(p_252033_); // FORGE: add non-vanilla registry namespace to loader directory, same format as tag directory (see net.minecraft.tags.TagManager#getTagDir(ResourceKey)) + } - static void loadRegistryContents(RegistryOps.RegistryInfoLookup p_256369_, ResourceManager p_256349_, ResourceKey> p_255792_, WritableRegistry p_256211_, Decoder p_256232_, Map, Exception> p_255884_) { - String s = registryDirPath(p_255792_.location()); - FileToIdConverter filetoidconverter = FileToIdConverter.json(s); -- RegistryOps registryops = RegistryOps.create(JsonOps.INSTANCE, p_256369_); -+ RegistryOps registryops = RegistryOps.builder(JsonOps.INSTANCE, p_256369_) -+ .with(net.minecraftforge.common.crafting.conditions.ICondition.IContext.KEY, net.minecraftforge.common.crafting.conditions.ICondition.IContext.TAGS_INVALID) -+ .build(); -+ Decoder> conditional = net.minecraftforge.common.crafting.conditions.ConditionCodec.wrap(p_256232_); - - for(Map.Entry entry : filetoidconverter.listMatchingResources(p_256349_).entrySet()) { - ResourceLocation resourcelocation = entry.getKey(); -@@ -139,7 +_,12 @@ - - try (Reader reader = resource.openAsReader()) { + private static void loadElementFromResource( + WritableRegistry p_330991_, +- Decoder p_333909_, ++ Decoder> p_333909_, + RegistryOps p_332135_, + ResourceKey p_332850_, + Resource p_335244_, +@@ -197,7 +_,14 @@ + ) throws IOException { + try (Reader reader = p_335244_.openAsReader()) { JsonElement jsonelement = JsonParser.parseReader(reader); -- DataResult dataresult = p_256232_.parse(registryops, jsonelement); -+ var result = conditional.decode(registryops, jsonelement); +- DataResult dataresult = p_333909_.parse(p_332135_, jsonelement); ++ ++ var result = p_333909_.decode(p_332135_, jsonelement); + if (result.result().map(p -> p.getFirst()).isEmpty()) { -+ LOGGER.debug("Skipping {} conditions not met", resourcelocation); -+ continue; ++ LOGGER.debug("Skipping {} conditions not met", p_332850_); ++ return; + } + DataResult dataresult = result.map(p -> p.mapFirst(Optional::get)).map(p -> p.getFirst()); - E e = dataresult.getOrThrow(false, (p_248715_) -> { - }); - p_256211_.register(resourcekey, e, resource.isBuiltin() ? Lifecycle.stable() : dataresult.lifecycle()); ++ + E e = dataresult.getOrThrow(); + p_330991_.register(p_332850_, e, p_332222_); + } +@@ -213,6 +_,7 @@ + String s = registryDirPath(p_331358_.key().location()); + FileToIdConverter filetoidconverter = FileToIdConverter.json(s); + RegistryOps registryops = RegistryOps.create(JsonOps.INSTANCE, p_333035_); ++ Decoder> conditional = net.minecraftforge.common.crafting.conditions.ConditionCodec.wrap(p_329404_); + + for (Entry entry : filetoidconverter.listMatchingResources(p_335634_).entrySet()) { + ResourceLocation resourcelocation = entry.getKey(); +@@ -221,7 +_,7 @@ + RegistrationInfo registrationinfo = REGISTRATION_INFO_CACHE.apply(resource.knownPackInfo()); + + try { +- loadElementFromResource(p_331358_, p_329404_, registryops, resourcekey, resource, registrationinfo); ++ loadElementFromResource(p_331358_, conditional, registryops, resourcekey, resource, registrationinfo); + } catch (Exception exception) { + p_335074_.put( + resourcekey, +@@ -242,7 +_,9 @@ + List list = p_331925_.get(p_332518_.key()); + if (list != null) { + RegistryOps registryops = RegistryOps.create(NbtOps.INSTANCE, p_329253_); +- RegistryOps registryops1 = RegistryOps.create(JsonOps.INSTANCE, p_329253_); ++ RegistryOps registryops1 = RegistryOps.create(JsonOps.INSTANCE, p_329253_) ++ .withContext(net.minecraftforge.common.crafting.conditions.ICondition.IContext.KEY, net.minecraftforge.common.crafting.conditions.ICondition.IContext.TAGS_INVALID); ++ Decoder> conditional = net.minecraftforge.common.crafting.conditions.ConditionCodec.wrap(p_328898_); + String s = registryDirPath(p_332518_.key().location()); + FileToIdConverter filetoidconverter = FileToIdConverter.json(s); + +@@ -265,7 +_,7 @@ + + try { + Resource resource = p_332010_.getResourceOrThrow(resourcelocation); +- loadElementFromResource(p_332518_, p_328898_, registryops1, resourcekey, resource, NETWORK_REGISTRATION_INFO); ++ loadElementFromResource(p_332518_, conditional, registryops1, resourcekey, resource, NETWORK_REGISTRATION_INFO); + } catch (Exception exception1) { + p_335768_.put(resourcekey, new IllegalStateException("Failed to parse local data", exception1)); + } diff --git a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch index 222bc00484..13a649f606 100644 --- a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch +++ b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch @@ -1,44 +1,25 @@ --- a/net/minecraft/resources/RegistryOps.java +++ b/net/minecraft/resources/RegistryOps.java -@@ -41,11 +_,20 @@ - return new RegistryOps<>(p_256278_, p_256479_); - } +@@ -76,6 +_,22 @@ + .forGetter(p_255526_ -> null); + } -+ public static DelegatingOps.Builder> builder(DynamicOps parent, RegistryOps.RegistryInfoLookup lookup) { -+ return DelegatingOps.builder(() -> create(parent, lookup)); -+ } ++ public static com.mojang.serialization.MapCodec> retrieveRegistryLookup(ResourceKey> resourceKey) { ++ return ExtraCodecs.retrieveContext(ops -> { ++ if (!(ops instanceof RegistryOps registryOps)) { ++ return DataResult.error(() -> "Not a registry ops"); ++ } + - private RegistryOps(DynamicOps p_256313_, RegistryOps.RegistryInfoLookup p_255799_) { - super(p_256313_); - this.lookupProvider = p_255799_; - } - -+ public RegistryOps(RegistryOps parent) { -+ super(parent); -+ this.lookupProvider = parent.lookupProvider; -+ } ++ return registryOps.lookupProvider.lookup(resourceKey).map(registryInfo -> { ++ if (!(registryInfo.owner() instanceof HolderLookup.RegistryLookup registryLookup)) { ++ return DataResult.>error(() -> "Found holder getter but was not a registry lookup for " + resourceKey); ++ } + - public Optional> owner(ResourceKey> p_255757_) { - return this.lookupProvider.lookup(p_255757_).map(RegistryOps.RegistryInfo::owner); - } -@@ -71,6 +_,20 @@ - } - }).forGetter((p_255526_) -> { - return null; -+ }); -+ } ++ return DataResult.success(registryLookup, registryInfo.elementsLifecycle()); ++ }).orElseGet(() -> DataResult.error(() -> "Unknown registry: " + resourceKey)); ++ }); ++ } + -+ public static com.mojang.serialization.MapCodec> retrieveRegistryLookup(ResourceKey> resourceKey) { -+ return ExtraCodecs.retrieveContext(ops -> { -+ if (!(ops instanceof RegistryOps registryOps)) -+ return DataResult.error(() -> "Not a registry ops"); -+ -+ return registryOps.lookupProvider.lookup(resourceKey).map(registryInfo -> { -+ if (!(registryInfo.owner() instanceof HolderLookup.RegistryLookup registryLookup)) -+ return DataResult.>error(() -> "Found holder getter but was not a registry lookup for " + resourceKey); -+ -+ return DataResult.success(registryLookup, registryInfo.elementsLifecycle()); -+ }).orElseGet(() -> DataResult.error(() -> "Unknown registry: " + resourceKey)); - }); - } - + public static RecordCodecBuilder> retrieveElement(ResourceKey p_256347_) { + ResourceKey> resourcekey = ResourceKey.createRegistryKey(p_256347_.registry()); + return ExtraCodecs.retrieveContext( diff --git a/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch b/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch index d1a4d83ea6..fa40c7ab19 100644 --- a/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch +++ b/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/resources/ResourceKey.java +++ b/net/minecraft/resources/ResourceKey.java -@@ -7,7 +_,7 @@ - import net.minecraft.core.Registry; +@@ -9,7 +_,7 @@ import net.minecraft.core.registries.Registries; + import net.minecraft.network.codec.StreamCodec; -public class ResourceKey { +public class ResourceKey implements Comparable> { - private static final ConcurrentMap> VALUES = (new MapMaker()).weakValues().makeMap(); - private final ResourceLocation registryName; - private final ResourceLocation location; -@@ -55,6 +_,19 @@ + private static final ConcurrentMap> VALUES = new MapMaker().weakValues().makeMap(); + private final ResourceLocation registryName; + private final ResourceLocation location; +@@ -67,5 +_,19 @@ + } - public ResourceLocation registry() { - return this.registryName; -+ } + static record InternKey(ResourceLocation registry, ResourceLocation location) { ++ } + -+ public boolean equals(Object o) { -+ if (this == o) return true; -+ if (o == null || getClass() != o.getClass()) return false; -+ return location.equals(((ResourceKey) o).location) && registryName.equals(((ResourceKey) o).registryName); -+ } ++ // Forge start ++ @Override ++ public boolean equals(Object obj) { ++ if (this == obj) return true; ++ if (!(obj instanceof ResourceKey resourceKey)) return false; ++ return location.equals(resourceKey.location) && registryName.equals(resourceKey.registryName); ++ } + -+ @Override -+ public int compareTo(ResourceKey o) { -+ int ret = this.registry().compareTo(o.registry()); -+ if (ret == 0) ret = this.location().compareTo(o.location()); -+ return ret; - } - - static record InternKey(ResourceLocation registry, ResourceLocation location) { ++ @Override ++ public int compareTo(ResourceKey resourceKey) { ++ int ret = this.registryName.compareTo(resourceKey.registryName); ++ return ret == 0 ? this.location.compareTo(resourceKey.location) : ret; + } + } diff --git a/patches/minecraft/net/minecraft/resources/ResourceLocation.java.patch b/patches/minecraft/net/minecraft/resources/ResourceLocation.java.patch index 530947d669..b6fffd7478 100644 --- a/patches/minecraft/net/minecraft/resources/ResourceLocation.java.patch +++ b/patches/minecraft/net/minecraft/resources/ResourceLocation.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/resources/ResourceLocation.java +++ b/net/minecraft/resources/ResourceLocation.java -@@ -143,6 +_,12 @@ - return i; - } +@@ -147,6 +_,12 @@ + return i; + } -+ // Normal compare sorts by path first, this compares namespace first. -+ public int compareNamespaced(ResourceLocation o) { -+ int ret = this.namespace.compareTo(o.namespace); -+ return ret != 0 ? ret : this.path.compareTo(o.path); -+ } ++ /** Normal compare sorts by path first, this compares namespace first. */ ++ public int compareNamespaced(ResourceLocation o) { ++ int ret = this.namespace.compareTo(o.namespace); ++ return ret != 0 ? ret : this.path.compareTo(o.path); ++ } + - public String toDebugFileName() { - return this.toString().replace('/', '_').replace(':', '_'); - } + public String toDebugFileName() { + return this.toString().replace('/', '_').replace(':', '_'); + } diff --git a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch index b660a5e7b4..cff7b40ec6 100644 --- a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch +++ b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/server/Bootstrap.java +++ b/net/minecraft/server/Bootstrap.java -@@ -54,6 +_,8 @@ - CauldronInteraction.bootStrap(); - BuiltInRegistries.bootStrap(); - CreativeModeTabs.validate(); -+ net.minecraftforge.registries.GameData.vanillaSnapshot(); -+ if (false) // skip redirectOutputToLog, Forge already redirects stdout and stderr output to log so that they print with more context - wrapStreams(); - bootstrapDuration.set(Duration.between(instant, Instant.now()).toMillis()); - } -@@ -127,7 +_,6 @@ - Commands.validate(); - } +@@ -53,6 +_,8 @@ + CauldronInteraction.bootStrap(); + BuiltInRegistries.bootStrap(); + CreativeModeTabs.validate(); ++ net.minecraftforge.registries.GameData.vanillaSnapshot(); ++ if (false) // skip redirectOutputToLog, Forge already redirects stdout and stderr output to log so that they print with more context + wrapStreams(); + bootstrapDuration.set(Duration.between(instant, Instant.now()).toMillis()); + } +@@ -119,7 +_,6 @@ + Commands.validate(); + } -- DefaultAttributes.validate(); - } +- DefaultAttributes.validate(); + } - private static void wrapStreams() { + private static void wrapStreams() { diff --git a/patches/minecraft/net/minecraft/server/Eula.java.patch b/patches/minecraft/net/minecraft/server/Eula.java.patch index 0b794be0a3..918dbc7852 100644 --- a/patches/minecraft/net/minecraft/server/Eula.java.patch +++ b/patches/minecraft/net/minecraft/server/Eula.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/server/Eula.java @@ -16,7 +_,7 @@ - public Eula(Path p_135943_) { - this.file = p_135943_; -- this.agreed = SharedConstants.IS_RUNNING_IN_IDE || this.readFile(); -+ this.agreed = SharedConstants.IS_RUNNING_IN_IDE || net.minecraftforge.gametest.ForgeGameTestHooks.isGametestServer() || this.readFile(); // Forge: Automatically agree to EULA for gametest servers to aid CI - } + public Eula(Path p_135943_) { + this.file = p_135943_; +- this.agreed = SharedConstants.IS_RUNNING_IN_IDE || this.readFile(); ++ this.agreed = SharedConstants.IS_RUNNING_IN_IDE || net.minecraftforge.gametest.ForgeGameTestHooks.isGametestServer() || this.readFile(); // Forge: Automatically agree to EULA for gametest servers to aid CI + } - private boolean readFile() { + private boolean readFile() { diff --git a/patches/minecraft/net/minecraft/server/Main.java.patch b/patches/minecraft/net/minecraft/server/Main.java.patch index e9cbff0410..9b953ae543 100644 --- a/patches/minecraft/net/minecraft/server/Main.java.patch +++ b/patches/minecraft/net/minecraft/server/Main.java.patch @@ -1,117 +1,141 @@ --- a/net/minecraft/server/Main.java +++ b/net/minecraft/server/Main.java -@@ -80,6 +_,15 @@ - OptionSpec optionspec12 = optionparser.accepts("jfrProfile"); - OptionSpec optionspec13 = optionparser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter()); - OptionSpec optionspec14 = optionparser.nonOptions(); -+ optionparser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed -+ optionparser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. -+ final OptionSpec spawnPosOpt; -+ boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer"); -+ if (gametestEnabled) { -+ spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); -+ } else { -+ spawnPosOpt = null; -+ } +@@ -83,6 +_,15 @@ + OptionSpec optionspec13 = optionparser.accepts("jfrProfile"); + OptionSpec optionspec14 = optionparser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter()); + OptionSpec optionspec15 = optionparser.nonOptions(); ++ optionparser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed ++ optionparser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. ++ final OptionSpec spawnPosOpt; ++ boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer"); ++ if (gametestEnabled) { ++ spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); ++ } else { ++ spawnPosOpt = null; ++ } - try { - OptionSet optionset = optionparser.parse(p_129699_); -@@ -87,6 +_,13 @@ - optionparser.printHelpOn(System.err); - return; - } -+ Path path2 = Paths.get("eula.txt"); -+ Eula eula = new Eula(path2); + try { + OptionSet optionset = optionparser.parse(p_129699_); +@@ -91,6 +_,14 @@ + return; + } + ++ Path path2 = Paths.get("eula.txt"); ++ Eula eula = new Eula(path2); + -+ if (!eula.hasAgreedToEULA()) { -+ LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); -+ return; -+ } - - Path path = optionset.valueOf(optionspec13); - if (path != null) { -@@ -102,23 +_,21 @@ - Bootstrap.validate(); - Util.startTimerHackThread(); - Path path1 = Paths.get("server.properties"); -+ if (!optionset.has(optionspec1)) net.minecraftforge.server.loading.ServerModLoader.load(); // Load mods before we load almost anything else anymore. Single spot now. Only loads if they haven't passed the initserver param - DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(path1); - dedicatedserversettings.forceSave(); -- Path path2 = Paths.get("eula.txt"); -- Eula eula = new Eula(path2); - if (optionset.has(optionspec1)) { - LOGGER.info("Initialized '{}' and '{}'", path1.toAbsolutePath(), path2.toAbsolutePath()); - return; - } - -- if (!eula.hasAgreedToEULA()) { -- LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); -- return; -- } -- - File file1 = new File(optionset.valueOf(optionspec8)); - Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), file1); - String s = Optional.ofNullable(optionset.valueOf(optionspec9)).orElse(dedicatedserversettings.getProperties().levelName); -+ if (s == null || s.isEmpty() || new File(file1, s).getAbsolutePath().equals(new File(s).getAbsolutePath())) { -+ LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + s); -+ return; -+ } - LevelStorageSource levelstoragesource = LevelStorageSource.createDefault(file1.toPath()); - LevelStorageSource.LevelStorageAccess levelstoragesource$levelstorageaccess = levelstoragesource.validateAndCreateAccess(s); - Dynamic dynamic; -@@ -165,6 +_,8 @@ - - PackRepository packrepository = ServerPacksSource.createPackRepository(levelstoragesource$levelstorageaccess); - -+ if (dynamic != null) -+ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(levelstoragesource$levelstorageaccess, levelstoragesource$levelstorageaccess.getLevelDirectory()); - WorldStem worldstem; - try { - WorldLoader.InitConfig worldloader$initconfig = loadOrCreateConfig(dedicatedserversettings.getProperties(), dynamic1, flag, packrepository); -@@ -190,6 +_,9 @@ - worlddimensions = dedicatedserverproperties.createDimensions(p_308589_.datapackWorldgen()); - } - -+ //Forge: Do a write-read-cycle to inject modded dimensions on first start of a dedicated server into its generated world dimensions list. -+ net.minecraft.resources.RegistryOps dynamicops = net.minecraft.resources.RegistryOps.create(net.minecraft.nbt.NbtOps.INSTANCE, p_308589_.datapackWorldgen()); -+ worlddimensions = WorldDimensions.CODEC.encoder().encodeStart(dynamicops, worlddimensions).flatMap((writtenPayloadWithModdedDimensions) -> WorldDimensions.CODEC.decoder().parse(dynamicops, writtenPayloadWithModdedDimensions)).resultOrPartial(LOGGER::error).orElse(worlddimensions); - WorldDimensions.Complete worlddimensions$complete = worlddimensions.bake(registry); - Lifecycle lifecycle = worlddimensions$complete.lifecycle().add(p_308589_.datapackWorldgen().allRegistriesLifecycle()); - return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelsettings, worldoptions, worlddimensions$complete.specialWorldProperty(), lifecycle), worlddimensions$complete.dimensionsRegistryAccess()); -@@ -210,21 +_,32 @@ - - WorldData worlddata = worldstem.worldData(); - levelstoragesource$levelstorageaccess.saveDataTag(registryaccess$frozen, worlddata); -- final DedicatedServer dedicatedserver = MinecraftServer.spin((p_296433_) -> { -- DedicatedServer dedicatedserver1 = new DedicatedServer(p_296433_, levelstoragesource$levelstorageaccess, packrepository, worldstem, dedicatedserversettings, DataFixers.getDataFixer(), services, LoggerChunkProgressListener::new); -+ final MinecraftServer dedicatedserver = MinecraftServer.spin((p_129697_) -> { -+ MinecraftServer dedicatedserver1; -+ if (gametestEnabled) { -+ net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests(); -+ var testBatches = net.minecraft.gametest.framework.GameTestRunner.groupTestsIntoBatches(net.minecraft.gametest.framework.GameTestRegistry.getAllTestFunctions()); -+ var spawnPos = optionset.valueOf(spawnPosOpt); -+ dedicatedserver1 = new net.minecraft.gametest.framework.GameTestServer(p_129697_, levelstoragesource$levelstorageaccess, packrepository, worldstem, testBatches, spawnPos); -+ } else { -+ dedicatedserver1 = new DedicatedServer(p_129697_, levelstoragesource$levelstorageaccess, packrepository, worldstem, dedicatedserversettings, DataFixers.getDataFixer(), services, LoggerChunkProgressListener::new); ++ if (!eula.hasAgreedToEULA()) { ++ LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); ++ return; + } - dedicatedserver1.setPort(optionset.valueOf(optionspec10)); - dedicatedserver1.setDemo(optionset.has(optionspec2)); - dedicatedserver1.setId(optionset.valueOf(optionspec11)); - boolean flag1 = !optionset.has(optionspec) && !optionset.valuesOf(optionspec14).contains("nogui"); -- if (flag1 && !GraphicsEnvironment.isHeadless()) { -- dedicatedserver1.showGui(); -+ if (dedicatedserver1 instanceof DedicatedServer dedicatedServer && flag1 && !GraphicsEnvironment.isHeadless()) { -+ dedicatedServer.showGui(); ++ + Path path = optionset.valueOf(optionspec14); + if (path != null) { + writePidFile(path); +@@ -105,24 +_,26 @@ + Bootstrap.validate(); + Util.startTimerHackThread(); + Path path1 = Paths.get("server.properties"); ++ if (!optionset.has(optionspec1)) { ++ // Load mods before we load almost anything else anymore. Single spot now. Only loads if they haven't passed the initserver param ++ net.minecraftforge.server.loading.ServerModLoader.load(); ++ } + DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(path1); + dedicatedserversettings.forceSave(); + RegionFileVersion.configure(dedicatedserversettings.getProperties().regionFileComression); +- Path path2 = Paths.get("eula.txt"); +- Eula eula = new Eula(path2); ++ + if (optionset.has(optionspec1)) { + LOGGER.info("Initialized '{}' and '{}'", path1.toAbsolutePath(), path2.toAbsolutePath()); + return; } - return dedicatedserver1; - }); - Thread thread = new Thread("Server Shutdown Thread") { - public void run() { -+ // FORGE: Halting as GameTestServer will cause issues as it always calls System#exit on both crash and normal exit, so skip it -+ if (!(dedicatedserver instanceof net.minecraft.gametest.framework.GameTestServer)) - dedicatedserver.halt(true); -+ org.apache.logging.log4j.LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end. - } - }; - thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); +- if (!eula.hasAgreedToEULA()) { +- LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); +- return; +- } +- + File file1 = new File(optionset.valueOf(optionspec9)); + Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), file1); + String s = Optional.ofNullable(optionset.valueOf(optionspec10)).orElse(dedicatedserversettings.getProperties().levelName); ++ if (s == null || s.isEmpty() || new File(file1, s).getAbsolutePath().equals(new File(s).getAbsolutePath())) { ++ LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + s); ++ return; ++ } + LevelStorageSource levelstoragesource = LevelStorageSource.createDefault(file1.toPath()); + LevelStorageSource.LevelStorageAccess levelstoragesource$levelstorageaccess = levelstoragesource.validateAndCreateAccess(s); + Dynamic dynamic; +@@ -173,6 +_,10 @@ + + PackRepository packrepository = ServerPacksSource.createPackRepository(levelstoragesource$levelstorageaccess); + ++ if (dynamic != null) { ++ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(levelstoragesource$levelstorageaccess, levelstoragesource$levelstorageaccess.getLevelDirectory()); ++ } ++ + WorldStem worldstem; + try { + WorldLoader.InitConfig worldloader$initconfig = loadOrCreateConfig(dedicatedserversettings.getProperties(), dynamic1, flag, packrepository); +@@ -214,6 +_,16 @@ + worlddimensions = dedicatedserverproperties.createDimensions(p_308589_.datapackWorldgen()); + } + ++ //Forge: Do a write-read-cycle to inject modded dimensions on first start of a dedicated server into its generated world dimensions list. ++ var dynamicops = net.minecraft.resources.RegistryOps.create(net.minecraft.nbt.NbtOps.INSTANCE, p_308589_.datapackWorldgen()); ++ worlddimensions = WorldDimensions.CODEC.encoder() ++ .encodeStart(dynamicops, worlddimensions) ++ .flatMap((writtenPayloadWithModdedDimensions) -> ++ WorldDimensions.CODEC.decoder().parse(dynamicops, writtenPayloadWithModdedDimensions) ++ ) ++ .resultOrPartial(LOGGER::error) ++ .orElse(worlddimensions); ++ + WorldDimensions.Complete worlddimensions$complete = worlddimensions.bake(registry); + Lifecycle lifecycle = worlddimensions$complete.lifecycle().add(p_308589_.datapackWorldgen().allRegistriesLifecycle()); + return new WorldLoader.DataLoadOutput<>( +@@ -244,9 +_,16 @@ + + WorldData worlddata = worldstem.worldData(); + levelstoragesource$levelstorageaccess.saveDataTag(registryaccess$frozen, worlddata); +- final DedicatedServer dedicatedserver = MinecraftServer.spin( ++ final MinecraftServer dedicatedserver = MinecraftServer.spin( + p_296433_ -> { +- DedicatedServer dedicatedserver1 = new DedicatedServer( ++ MinecraftServer dedicatedserver1; ++ if (gametestEnabled) { ++ net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests(); ++ var tests = net.minecraft.gametest.framework.GameTestRegistry.getAllTestFunctions(); ++ var spawnPos = optionset.valueOf(spawnPosOpt); ++ dedicatedserver1 = net.minecraft.gametest.framework.GameTestServer.create(p_296433_, levelstoragesource$levelstorageaccess, packrepository, tests, spawnPos); ++ } else { ++ dedicatedserver1 = new DedicatedServer( + p_296433_, + levelstoragesource$levelstorageaccess, + packrepository, +@@ -256,12 +_,13 @@ + services, + LoggerChunkProgressListener::createFromGameruleRadius + ); ++ } + dedicatedserver1.setPort(optionset.valueOf(optionspec11)); + dedicatedserver1.setDemo(optionset.has(optionspec2)); + dedicatedserver1.setId(optionset.valueOf(optionspec12)); + boolean flag2 = !optionset.has(optionspec) && !optionset.valuesOf(optionspec15).contains("nogui"); +- if (flag2 && !GraphicsEnvironment.isHeadless()) { +- dedicatedserver1.showGui(); ++ if (flag2 && !GraphicsEnvironment.isHeadless() && dedicatedserver1 instanceof DedicatedServer ds) { ++ ds.showGui(); + } + + return dedicatedserver1; +@@ -270,7 +_,10 @@ + Thread thread = new Thread("Server Shutdown Thread") { + @Override + public void run() { ++ // FORGE: Halting as GameTestServer will cause issues as it always calls System#exit on both crash and normal exit, so skip it ++ if (!(dedicatedserver instanceof net.minecraft.gametest.framework.GameTestServer)) + dedicatedserver.halt(true); ++ org.apache.logging.log4j.LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end. + } + }; + thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); diff --git a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch index 38f7c9353e..54af757425 100644 --- a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch +++ b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch @@ -1,244 +1,242 @@ --- a/net/minecraft/server/MinecraftServer.java +++ b/net/minecraft/server/MinecraftServer.java -@@ -252,7 +_,7 @@ +@@ -258,7 +_,7 @@ - public static S spin(Function p_129873_) { - AtomicReference atomicreference = new AtomicReference<>(); -- Thread thread = new Thread(() -> { -+ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, () -> { - atomicreference.get().runServer(); - }, "Server thread"); - thread.setUncaughtExceptionHandler((p_177909_, p_177910_) -> { -@@ -346,6 +_,7 @@ - this.readScoreboard(dimensiondatastorage); - this.commandStorage = new CommandStorage(dimensiondatastorage); - WorldBorder worldborder = serverlevel.getWorldBorder(); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.LevelEvent.Load(levels.get(Level.OVERWORLD))); - if (!serverleveldata.isInitialized()) { - try { - setInitialSpawn(serverlevel, serverleveldata, worldoptions.generateBonusChest(), flag); -@@ -382,6 +_,7 @@ - ServerLevel serverlevel1 = new ServerLevel(this, this.executor, this.storageSource, derivedleveldata, resourcekey1, entry.getValue(), p_129816_, flag, j, ImmutableList.of(), false, randomsequences); - worldborder.addListener(new BorderChangeListener.DelegateBorderChangeListener(serverlevel1.getWorldBorder())); - this.levels.put(resourcekey1, serverlevel1); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.LevelEvent.Load(levels.get(resourcekey))); - } - } - -@@ -393,6 +_,7 @@ - p_177898_.setSpawn(BlockPos.ZERO.above(80), 0.0F); - } else { - ServerChunkCache serverchunkcache = p_177897_.getChunkSource(); -+ if (net.minecraftforge.event.ForgeEventFactory.onCreateWorldSpawn(p_177897_, p_177898_)) return; - ChunkPos chunkpos = new ChunkPos(serverchunkcache.randomState().sampler().findSpawnPosition()); - int i = serverchunkcache.getGenerator().getSpawnHeight(p_177897_); - if (i < p_177897_.getMinBuildHeight()) { -@@ -475,6 +_,7 @@ - ChunkPos chunkpos = new ChunkPos(i); - serverlevel1.getChunkSource().updateChunkForced(chunkpos, true); - } -+ net.minecraftforge.common.world.ForgeChunkManager.reinstatePersistentChunks(serverlevel1, forcedchunkssaveddata); - } - } - -@@ -585,6 +_,7 @@ - for(ServerLevel serverlevel2 : this.getAllLevels()) { - if (serverlevel2 != null) { + public static S spin(Function p_129873_) { + AtomicReference atomicreference = new AtomicReference<>(); +- Thread thread = new Thread(() -> atomicreference.get().runServer(), "Server thread"); ++ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, () -> atomicreference.get().runServer(), "Server thread"); + thread.setUncaughtExceptionHandler((p_177909_, p_177910_) -> LOGGER.error("Uncaught exception in server thread", p_177910_)); + if (Runtime.getRuntime().availableProcessors() > 4) { + thread.setPriority(8); +@@ -361,6 +_,7 @@ + this.readScoreboard(dimensiondatastorage); + this.commandStorage = new CommandStorage(dimensiondatastorage); + WorldBorder worldborder = serverlevel.getWorldBorder(); ++ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(levels.get(Level.OVERWORLD)); + if (!serverleveldata.isInitialized()) { try { -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.LevelEvent.Unload(serverlevel2)); - serverlevel2.close(); - } catch (IOException ioexception1) { - LOGGER.error("Exception closing the level", (Throwable)ioexception1); -@@ -633,9 +_,11 @@ - throw new IllegalStateException("Failed to initialize server"); - } + setInitialSpawn(serverlevel, serverleveldata, worldoptions.generateBonusChest(), flag); +@@ -410,6 +_,7 @@ + ); + worldborder.addListener(new BorderChangeListener.DelegateBorderChangeListener(serverlevel1.getWorldBorder())); + this.levels.put(resourcekey1, serverlevel1); ++ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(serverlevel1); + } + } -+ net.minecraftforge.server.ServerLifecycleHooks.handleServerStarted(this); - this.nextTickTimeNanos = Util.getNanos(); - this.statusIcon = this.loadStatusIcon().orElse((ServerStatus.Favicon)null); - this.status = this.buildServerStatus(); -+ resetStatusCache(status); +@@ -421,6 +_,7 @@ + p_177898_.setSpawn(BlockPos.ZERO.above(80), 0.0F); + } else { + ServerChunkCache serverchunkcache = p_177897_.getChunkSource(); ++ if (net.minecraftforge.event.ForgeEventFactory.onCreateWorldSpawn(p_177897_, p_177898_)) return; + ChunkPos chunkpos = new ChunkPos(serverchunkcache.randomState().sampler().findSpawnPosition()); + int i = serverchunkcache.getGenerator().getSpawnHeight(p_177897_); + if (i < p_177897_.getMinBuildHeight()) { +@@ -502,6 +_,7 @@ + ChunkPos chunkpos = new ChunkPos(k); + serverlevel1.getChunkSource().updateChunkForced(chunkpos, true); + } ++ net.minecraftforge.common.world.ForgeChunkManager.reinstatePersistentChunks(serverlevel1, forcedchunkssaveddata); + } + } - while(this.running) { - long i; -@@ -679,6 +_,8 @@ - this.isReady = true; - JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis); - } -+ net.minecraftforge.server.ServerLifecycleHooks.handleServerStopping(this); -+ net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions - } catch (Throwable throwable1) { - LOGGER.error("Encountered an unexpected exception", throwable1); - CrashReport crashreport = constructOrExtractCrashReport(throwable1); -@@ -690,6 +_,7 @@ - LOGGER.error("We were unable to save this crash report to disk."); - } - -+ net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions - this.onServerCrash(crashreport); - } finally { - try { -@@ -702,6 +_,7 @@ - this.services.profileCache().clearExecutor(); +@@ -609,6 +_,7 @@ + for (ServerLevel serverlevel2 : this.getAllLevels()) { + if (serverlevel2 != null) { + try { ++ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(serverlevel2); + serverlevel2.close(); + } catch (IOException ioexception1) { + LOGGER.error("Exception closing the level", (Throwable)ioexception1); +@@ -655,9 +_,11 @@ + throw new IllegalStateException("Failed to initialize server"); } -+ net.minecraftforge.server.ServerLifecycleHooks.handleServerStopped(this); - this.onServerExit(); - } ++ net.minecraftforge.server.ServerLifecycleHooks.handleServerStarted(this); + this.nextTickTimeNanos = Util.getNanos(); + this.statusIcon = this.loadStatusIcon().orElse(null); + this.status = this.buildServerStatus(); ++ resetStatusCache(status); -@@ -820,12 +_,14 @@ + while (this.running) { + long i; +@@ -702,6 +_,8 @@ + this.isReady = true; + JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis); + } ++ net.minecraftforge.server.ServerLifecycleHooks.handleServerStopping(this); ++ net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions + } catch (Throwable throwable1) { + LOGGER.error("Encountered an unexpected exception", throwable1); + CrashReport crashreport = constructOrExtractCrashReport(throwable1); +@@ -713,6 +_,7 @@ + LOGGER.error("We were unable to save this crash report to disk."); + } - public void tickServer(BooleanSupplier p_129871_) { - long i = Util.getNanos(); -+ net.minecraftforge.event.ForgeEventFactory.onPreServerTick(p_129871_, this); - ++this.tickCount; - this.tickRateManager.tick(); - this.tickChildren(p_129871_); - if (i - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { - this.lastServerStatus = i; - this.status = this.buildServerStatus(); -+ resetStatusCache(status); - } ++ net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions + this.onServerCrash(crashreport); + } finally { + try { +@@ -725,6 +_,7 @@ + this.services.profileCache().clearExecutor(); + } - --this.ticksUntilAutosave; -@@ -848,6 +_,17 @@ - long l = Util.getNanos(); - this.logTickTime(l - i); - this.profiler.pop(); -+ net.minecraftforge.event.ForgeEventFactory.onPostServerTick(p_129871_, this); -+ } ++ net.minecraftforge.server.ServerLifecycleHooks.handleServerStopped(this); + this.onServerExit(); + } + } +@@ -870,12 +_,14 @@ + + public void tickServer(BooleanSupplier p_129871_) { + long i = Util.getNanos(); ++ net.minecraftforge.event.ForgeEventFactory.onPreServerTick(p_129871_, this); + this.tickCount++; + this.tickRateManager.tick(); + this.tickChildren(p_129871_); + if (i - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { + this.lastServerStatus = i; + this.status = this.buildServerStatus(); ++ resetStatusCache(status); + } + + this.ticksUntilAutosave--; +@@ -897,6 +_,7 @@ + this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)j / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; + this.logTickMethodTime(i); + this.profiler.pop(); ++ net.minecraftforge.event.ForgeEventFactory.onPostServerTick(p_129871_, this); + } + + private void logTickMethodTime(long p_331549_) { +@@ -936,7 +_,8 @@ + Optional.of(serverstatus$players), + Optional.of(ServerStatus.Version.current()), + Optional.ofNullable(this.statusIcon), +- this.enforceSecureProfile() ++ this.enforceSecureProfile(), ++ Optional.of(new net.minecraftforge.network.ServerStatusPing()) + ); + } + +@@ -966,7 +_,8 @@ + this.getFunctions().tick(); + this.profiler.popPush("levels"); + +- for (ServerLevel serverlevel : this.getAllLevels()) { ++ for (ServerLevel serverlevel : this.getWorldArray()) { ++ long tickStart = Util.getNanos(); + this.profiler.push(() -> serverlevel + " " + serverlevel.dimension().location()); + if (this.tickCount % 20 == 0) { + this.profiler.push("timeSync"); +@@ -975,6 +_,7 @@ + } + + this.profiler.push("tick"); ++ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(serverlevel, p_129954_); + + try { + serverlevel.tick(p_129954_); +@@ -983,16 +_,18 @@ + serverlevel.fillReportDetails(crashreport); + throw new ReportedException(crashreport); + } ++ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(serverlevel, p_129954_); + + this.profiler.pop(); + this.profiler.pop(); ++ perWorldTickTimes.computeIfAbsent(serverlevel.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; + } + + this.profiler.popPush("connection"); + this.getConnection().tick(); + this.profiler.popPush("players"); + this.playerList.tick(); +- if (SharedConstants.IS_RUNNING_IN_IDE && this.tickRateManager.runsNormally()) { ++ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled() && this.tickRateManager.runsNormally()) { + GameTestTicker.SINGLETON.tick(); + } + +@@ -1088,7 +_,7 @@ + + @DontObfuscate + public String getServerModName() { +- return "vanilla"; ++ return net.minecraftforge.internal.BrandingControl.getServerBranding(); + } + + public SystemReport fillSystemReport(SystemReport p_177936_) { +@@ -1443,6 +_,7 @@ + this.getPlayerList().reloadResources(); + this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); + this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); ++ this.getPlayerList().getPlayers().forEach(this.getPlayerList()::sendPlayerPermissionLevel); //Forge: Fix newly added/modified commands not being sent to the client when commands reload. + }, this); + if (this.isSameThread()) { + this.managedBlock(completablefuture::isDone); +@@ -1452,12 +_,15 @@ + } + + public static WorldDataConfiguration configurePackRepository(PackRepository p_248681_, WorldDataConfiguration p_331931_, boolean p_249869_, boolean p_330480_) { ++ net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(p_248681_, false); + DataPackConfig datapackconfig = p_331931_.dataPacks(); + FeatureFlagSet featureflagset = p_249869_ ? FeatureFlagSet.of() : p_331931_.enabledFeatures(); + FeatureFlagSet featureflagset1 = p_249869_ ? FeatureFlags.REGISTRY.allFlags() : p_331931_.enabledFeatures(); + p_248681_.reload(); ++ DataPackConfig.DEFAULT.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); ++ datapackconfig.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); + if (p_330480_) { +- return configureRepositoryWithSelection(p_248681_, List.of("vanilla"), featureflagset, false); ++ return configureRepositoryWithSelection(p_248681_, net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), featureflagset, false); + } else { + Set set = Sets.newLinkedHashSet(); + +@@ -1921,6 +_,48 @@ + + public PotionBrewing potionBrewing() { + return this.potionBrewing; ++ } + -+ private static final com.google.gson.Gson GSON = new com.google.gson.Gson(); -+ private String cachedServerStatus; // FORGE: cache the server status json in case a client spams requests -+ private void resetStatusCache(ServerStatus status) { -+ this.cachedServerStatus = GSON.toJson(ServerStatus.CODEC.encodeStart(com.mojang.serialization.JsonOps.INSTANCE, status) -+ .result().orElseThrow()); -+ } -+ public String getStatusJson() { -+ return cachedServerStatus; - } - - private int computeNextAutosaveInterval() { -@@ -876,7 +_,7 @@ - - private ServerStatus buildServerStatus() { - ServerStatus.Players serverstatus$players = this.buildPlayerStatus(); -- return new ServerStatus(Component.nullToEmpty(this.motd), Optional.of(serverstatus$players), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), this.enforceSecureProfile()); -+ return new ServerStatus(Component.nullToEmpty(this.motd), Optional.of(serverstatus$players), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), this.enforceSecureProfile(), Optional.of(new net.minecraftforge.network.ServerStatusPing())); - } - - private ServerStatus.Players buildPlayerStatus() { -@@ -907,7 +_,8 @@ - this.getFunctions().tick(); - this.profiler.popPush("levels"); - -- for(ServerLevel serverlevel : this.getAllLevels()) { -+ for(ServerLevel serverlevel : this.getWorldArray()) { -+ long tickStart = Util.getNanos(); - this.profiler.push(() -> { - return serverlevel + " " + serverlevel.dimension().location(); - }); -@@ -918,6 +_,7 @@ - } - - this.profiler.push("tick"); -+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(serverlevel, p_129954_); - - try { - serverlevel.tick(p_129954_); -@@ -926,16 +_,18 @@ - serverlevel.fillReportDetails(crashreport); - throw new ReportedException(crashreport); - } -+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(serverlevel, p_129954_); - - this.profiler.pop(); - this.profiler.pop(); -+ perWorldTickTimes.computeIfAbsent(serverlevel.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; - } - - this.profiler.popPush("connection"); - this.getConnection().tick(); - this.profiler.popPush("players"); - this.playerList.tick(); -- if (SharedConstants.IS_RUNNING_IN_IDE && this.tickRateManager.runsNormally()) { -+ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { - GameTestTicker.SINGLETON.tick(); - } - -@@ -1024,7 +_,7 @@ - - @DontObfuscate - public String getServerModName() { -- return "vanilla"; -+ return net.minecraftforge.internal.BrandingControl.getServerBranding(); - } - - public SystemReport fillSystemReport(SystemReport p_177936_) { -@@ -1373,6 +_,7 @@ - this.getPlayerList().reloadResources(); - this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); - this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); -+ this.getPlayerList().getPlayers().forEach(this.getPlayerList()::sendPlayerPermissionLevel); //Forge: Fix newly added/modified commands not being sent to the client when commands reload. - }, this); - if (this.isSameThread()) { - this.managedBlock(completablefuture::isDone); -@@ -1382,10 +_,13 @@ - } - - public static WorldDataConfiguration configurePackRepository(PackRepository p_248681_, DataPackConfig p_248920_, boolean p_249869_, FeatureFlagSet p_251243_) { -+ net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(p_248681_, false); - p_248681_.reload(); -+ DataPackConfig.DEFAULT.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); -+ p_248920_.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); - if (p_249869_) { -- p_248681_.setSelected(Collections.singleton("vanilla")); -- return WorldDataConfiguration.DEFAULT; -+ p_248681_.setSelected(net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla()); -+ return new WorldDataConfiguration(new DataPackConfig(net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), ImmutableList.of()), FeatureFlags.DEFAULT_FLAGS); - } else { - Set set = Sets.newLinkedHashSet(); - -@@ -1551,6 +_,31 @@ - - public abstract boolean isSingleplayerOwner(GameProfile p_129840_); - -+ private Map, long[]> perWorldTickTimes = Maps.newIdentityHashMap(); -+ @Nullable -+ public long[] getTickTime(ResourceKey dim) { -+ return perWorldTickTimes.get(dim); -+ } ++ private static final com.google.gson.Gson GSON = new com.google.gson.Gson(); ++ private String cachedServerStatus; // FORGE: cache the server status json in case a client spams requests ++ private void resetStatusCache(ServerStatus status) { ++ this.cachedServerStatus = GSON.toJson(ServerStatus.CODEC.encodeStart(com.mojang.serialization.JsonOps.INSTANCE, status).result().orElseThrow()); ++ } + -+ @Deprecated //Forge Internal use Only, You can screw up a lot of things if you mess with this map. -+ public synchronized Map, ServerLevel> forgeGetWorldMap() { -+ return this.levels; -+ } -+ private int worldArrayMarker = 0; -+ private int worldArrayLast = -1; -+ private ServerLevel[] worldArray; -+ @Deprecated //Forge Internal use Only, use to protect against concurrent modifications in the world tick loop. -+ public synchronized void markWorldsDirty() { -+ worldArrayMarker++; -+ } -+ private ServerLevel[] getWorldArray() { -+ if (worldArrayMarker == worldArrayLast && worldArray != null) -+ return worldArray; -+ worldArray = this.levels.values().stream().toArray(x -> new ServerLevel[x]); -+ worldArrayLast = worldArrayMarker; -+ return worldArray; -+ } ++ public String getStatusJson() { ++ return cachedServerStatus; ++ } + - public void dumpServerProperties(Path p_177911_) throws IOException { - } - -@@ -1714,6 +_,10 @@ - - public WorldData getWorldData() { - return this.worldData; -+ } ++ private Map, long[]> perWorldTickTimes = Maps.newIdentityHashMap(); ++ @Nullable ++ public long[] getTickTime(ResourceKey dim) { ++ return perWorldTickTimes.get(dim); ++ } + -+ public MinecraftServer.ReloadableResources getServerResources() { -+ return resources; - } ++ @Deprecated //Forge Internal use Only, You can screw up a lot of things if you mess with this map. ++ public synchronized Map, ServerLevel> forgeGetWorldMap() { ++ return this.levels; ++ } ++ ++ private int worldArrayMarker = 0; ++ private int worldArrayLast = -1; ++ private ServerLevel[] worldArray; ++ ++ @Deprecated //Forge Internal use Only, use to protect against concurrent modifications in the world tick loop. ++ public synchronized void markWorldsDirty() { ++ worldArrayMarker++; ++ } ++ ++ private ServerLevel[] getWorldArray() { ++ if (worldArrayMarker == worldArrayLast && worldArray != null) ++ return worldArray; ++ worldArray = this.levels.values().stream().toArray(ServerLevel[]::new); ++ worldArrayLast = worldArrayMarker; ++ return worldArray; ++ } ++ ++ public MinecraftServer.ReloadableResources getServerResources() { ++ return resources; + } - public RegistryAccess.Frozen registryAccess() { + public static record ReloadableResources(CloseableResourceManager resourceManager, ReloadableServerResources managers) implements AutoCloseable { diff --git a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch index 97a356d84d..071d5d56aa 100644 --- a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch +++ b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch @@ -1,26 +1,26 @@ --- a/net/minecraft/server/PlayerAdvancements.java +++ b/net/minecraft/server/PlayerAdvancements.java -@@ -177,6 +_,7 @@ - this.unregisterListeners(p_298135_); - this.progressChanged.add(p_298135_); - flag = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, p_298135_, advancementprogress, p_135990_); - if (!flag1 && advancementprogress.isDone()) { - p_298135_.value().rewards().grant(this.player); - p_298135_.value().display().ifPresent((p_308592_) -> { -@@ -185,6 +_,7 @@ - } +@@ -173,6 +_,7 @@ + this.unregisterListeners(p_298135_); + this.progressChanged.add(p_298135_); + flag = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, p_298135_, advancementprogress, p_135990_); + if (!flag1 && advancementprogress.isDone()) { + p_298135_.value().rewards().grant(this.player); + p_298135_.value().display().ifPresent(p_326189_ -> { +@@ -180,6 +_,7 @@ + this.playerList.broadcastSystemMessage(p_326189_.getType().createAnnouncement(p_298135_, this.player), false); + } + }); ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementEarned(this.player, p_298135_); + } + } - }); -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementEarned(this.player, p_298135_); - } - } +@@ -198,6 +_,7 @@ + this.registerListeners(p_297905_); + this.progressChanged.add(p_297905_); + flag = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, p_297905_, advancementprogress, p_136000_); + } -@@ -203,6 +_,7 @@ - this.registerListeners(p_297905_); - this.progressChanged.add(p_297905_); - flag = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, p_297905_, advancementprogress, p_136000_); - } - - if (flag1 && !advancementprogress.isDone()) { + if (flag1 && !advancementprogress.isDone()) { diff --git a/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch b/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch index cbf47df2f8..ce7f05cf3a 100644 --- a/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch +++ b/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch @@ -1,62 +1,59 @@ --- a/net/minecraft/server/ReloadableServerResources.java +++ b/net/minecraft/server/ReloadableServerResources.java -@@ -29,10 +_,10 @@ - private static final CompletableFuture DATA_RELOAD_INITIAL_TASK = CompletableFuture.completedFuture(Unit.INSTANCE); - private final CommandBuildContext.Configurable commandBuildContext; - private final Commands commands; -- private final RecipeManager recipes = new RecipeManager(); -+ private final RecipeManager recipes; - private final TagManager tagManager; - private final LootDataManager lootData = new LootDataManager(); -- private final ServerAdvancementManager advancements = new ServerAdvancementManager(this.lootData); -+ private final ServerAdvancementManager advancements; - private final ServerFunctionLibrary functionLibrary; +@@ -39,15 +_,18 @@ + private final TagManager tagManager; + private final ServerAdvancementManager advancements; + private final ServerFunctionLibrary functionLibrary; ++ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; - public ReloadableServerResources(RegistryAccess.Frozen p_206857_, FeatureFlagSet p_250695_, Commands.CommandSelection p_206858_, int p_206859_) { -@@ -41,6 +_,10 @@ - this.commands = new Commands(p_206858_, this.commandBuildContext); - this.commandBuildContext.missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy.CREATE_NEW); - this.functionLibrary = new ServerFunctionLibrary(p_206859_, this.commands.getDispatcher()); -+ // Forge: Create context object and pass it to the recipe manager. -+ this.context = new net.minecraftforge.common.crafting.conditions.ConditionContext(this.tagManager); -+ this.recipes = new RecipeManager(context); -+ this.advancements = new ServerAdvancementManager(this.lootData, context); - } + private ReloadableServerResources(RegistryAccess.Frozen p_206857_, FeatureFlagSet p_250695_, Commands.CommandSelection p_206858_, int p_206859_) { + this.fullRegistryHolder = new ReloadableServerRegistries.Holder(p_206857_); + this.registryLookup = new ReloadableServerResources.ConfigurableRegistryLookup(p_206857_); + this.registryLookup.missingTagAccessPolicy(ReloadableServerResources.MissingTagAccessPolicy.CREATE_NEW); +- this.recipes = new RecipeManager(this.registryLookup); + this.tagManager = new TagManager(p_206857_); + this.commands = new Commands(p_206858_, CommandBuildContext.simple(this.registryLookup, p_250695_)); +- this.advancements = new ServerAdvancementManager(this.registryLookup); ++ // Forge: Create context object and pass it to the recipe manager. ++ this.context = new net.minecraftforge.common.crafting.conditions.ConditionContext(this.tagManager); ++ this.recipes = new RecipeManager(this.registryLookup, this.context); ++ this.advancements = new ServerAdvancementManager(this.registryLookup, this.context); + this.functionLibrary = new ServerFunctionLibrary(p_206859_, this.commands.getDispatcher()); + } - public ServerFunctionLibrary getFunctionLibrary() { -@@ -69,7 +_,9 @@ +@@ -88,8 +_,10 @@ + .thenCompose( + p_326196_ -> { + ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_326196_.compositeAccess(), p_250212_, p_249301_, p_251126_); ++ var listeners = new java.util.ArrayList<>(reloadableserverresources.listeners()); ++ listeners.addAll(net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, p_330376_.compositeAccess())); + return SimpleReloadInstance.create( +- p_248588_, reloadableserverresources.listeners(), p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled() ++ p_248588_, listeners, p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled() + ) + .done() + .whenComplete( +@@ -104,6 +_,7 @@ + this.tagManager.getResult().forEach(p_326197_ -> updateRegistryTags(this.fullRegistryHolder.get(), (TagManager.LoadResult)p_326197_)); + AbstractFurnaceBlockEntity.invalidateCache(); + Blocks.rebuildCache(); ++ net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.fullRegistryHolder.get(), false, false); + } - public static CompletableFuture loadResources(ResourceManager p_248588_, RegistryAccess.Frozen p_251163_, FeatureFlagSet p_250212_, Commands.CommandSelection p_249301_, int p_251126_, Executor p_249136_, Executor p_249601_) { - ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_251163_, p_250212_, p_249301_, p_251126_); -- return SimpleReloadInstance.create(p_248588_, reloadableserverresources.listeners(), p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled()).done().whenComplete((p_255534_, p_255535_) -> { -+ List listeners = new java.util.ArrayList<>(reloadableserverresources.listeners()); -+ listeners.addAll(net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, p_251163_)); -+ return SimpleReloadInstance.create(p_248588_, listeners, p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled()).done().whenComplete((p_214309_, p_214310_) -> { - reloadableserverresources.commandBuildContext.missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy.FAIL); - }).thenApply((p_214306_) -> { - return reloadableserverresources; -@@ -81,6 +_,7 @@ - updateRegistryTags(p_206869_, p_214315_); - }); - Blocks.rebuildCache(); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.TagsUpdatedEvent(p_206869_, false, false)); - } - - private static void updateRegistryTags(RegistryAccess p_206871_, TagManager.LoadResult p_206872_) { -@@ -91,5 +_,16 @@ - return List.copyOf(p_214312_.getValue()); - })); - p_206871_.registryOrThrow(resourcekey).bindTags(map); -+ } + private static void updateRegistryTags(RegistryAccess p_206871_, TagManager.LoadResult p_206872_) { +@@ -115,6 +_,15 @@ + Collectors.toUnmodifiableMap(p_214303_ -> TagKey.create(resourcekey, p_214303_.getKey()), p_214312_ -> List.copyOf(p_214312_.getValue())) + ); + p_206871_.registryOrThrow(resourcekey).bindTags(map); ++ } + -+ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; -+ -+ /** -+ * Exposes the current condition context for usage in other reload listeners.
-+ * This is not useful outside the reloading stage. -+ * @return The condition context for the currently active reload. -+ */ -+ public net.minecraftforge.common.crafting.conditions.ICondition.IContext getConditionContext() { -+ return this.context; - } - } ++ /** ++ * Exposes the current condition context for usage in other reload listeners.
++ * This is not useful outside the reloading stage. ++ * @return The condition context for the currently active reload. ++ */ ++ public net.minecraftforge.common.crafting.conditions.ICondition.IContext getConditionContext() { ++ return this.context; + } + + static class ConfigurableRegistryLookup implements HolderLookup.Provider { diff --git a/patches/minecraft/net/minecraft/server/ServerAdvancementManager.java.patch b/patches/minecraft/net/minecraft/server/ServerAdvancementManager.java.patch index 2eb595c21f..6d013b259d 100644 --- a/patches/minecraft/net/minecraft/server/ServerAdvancementManager.java.patch +++ b/patches/minecraft/net/minecraft/server/ServerAdvancementManager.java.patch @@ -1,34 +1,35 @@ --- a/net/minecraft/server/ServerAdvancementManager.java +++ b/net/minecraft/server/ServerAdvancementManager.java -@@ -32,17 +_,30 @@ - private Map advancements = Map.of(); - private AdvancementTree tree = new AdvancementTree(); - private final LootDataManager lootData; -+ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; //Forge: add context +@@ -34,10 +_,18 @@ + private Map advancements = Map.of(); + private AdvancementTree tree = new AdvancementTree(); + private final HolderLookup.Provider registries; ++ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; //Forge: add context -+ /** @deprecated Forge: use {@linkplain ServerAdvancementManager#ServerAdvancementManager(LootDataManager, net.minecraftforge.common.crafting.conditions.ICondition.IContext) constructor with context}. */ -+ @Deprecated - public ServerAdvancementManager(LootDataManager p_279237_) { -+ this(p_279237_, net.minecraftforge.common.crafting.conditions.ICondition.IContext.EMPTY); -+ } ++ /** @deprecated Forge: use {@linkplain ServerAdvancementManager#ServerAdvancementManager(LootDataManager, net.minecraftforge.common.crafting.conditions.ICondition.IContext) constructor with context}. */ ++ @Deprecated + public ServerAdvancementManager(HolderLookup.Provider p_336198_) { ++ this(p_336198_, net.minecraftforge.common.crafting.conditions.ICondition.IContext.EMPTY); ++ } + -+ public ServerAdvancementManager(LootDataManager p_279237_, net.minecraftforge.common.crafting.conditions.ICondition.IContext context) { - super(GSON, "advancements"); - this.lootData = p_279237_; -+ this.context = context; - } ++ public ServerAdvancementManager(HolderLookup.Provider p_336198_, net.minecraftforge.common.crafting.conditions.ICondition.IContext context) { + super(GSON, "advancements"); + this.registries = p_336198_; ++ this.context = context; + } - protected void apply(Map p_136034_, ResourceManager p_136035_, ProfilerFiller p_136036_) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - p_136034_.forEach((p_308595_, p_308596_) -> { - try { -- Advancement advancement = Util.getOrThrow(Advancement.CODEC.parse(JsonOps.INSTANCE, p_308596_), JsonParseException::new); -+ var json = net.minecraftforge.common.ForgeHooks.readConditionalAdvancement(null, (com.google.gson.JsonObject)p_308596_); -+ if (json == null) { -+ LOGGER.debug("Skipping loading advancement {} as its conditions were not met", p_308595_); -+ return; -+ } -+ Advancement advancement = Util.getOrThrow(Advancement.CODEC.parse(JsonOps.INSTANCE, json), JsonParseException::new); - this.validate(p_308595_, advancement); - builder.put(p_308595_, new AdvancementHolder(p_308595_, advancement)); - } catch (Exception exception) { + protected void apply(Map p_136034_, ResourceManager p_136035_, ProfilerFiller p_136036_) { +@@ -45,7 +_,12 @@ + Builder builder = ImmutableMap.builder(); + p_136034_.forEach((p_326203_, p_326204_) -> { + try { +- Advancement advancement = Advancement.CODEC.parse(registryops, p_326204_).getOrThrow(JsonParseException::new); ++ var json = net.minecraftforge.common.ForgeHooks.readConditionalAdvancement(registryops, (com.google.gson.JsonObject)p_326204_); ++ if (json == null) { ++ LOGGER.debug("Skipping loading advancement {} as its conditions were not met", p_326204_); ++ return; ++ } ++ Advancement advancement = Advancement.CODEC.parse(registryops, json).getOrThrow(JsonParseException::new); + this.validate(p_326203_, advancement); + builder.put(p_326203_, new AdvancementHolder(p_326203_, advancement)); + } catch (Exception exception) { diff --git a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch index 4396b9e6fe..7b7cb87c26 100644 --- a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java +++ b/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java -@@ -64,6 +_,16 @@ - evaluateVisibility(advancementnode, stack, p_265561_, p_265381_); - } +@@ -69,6 +_,16 @@ + evaluateVisibility(advancementnode, stack, p_265561_, p_265381_); + } -+ public static boolean isVisible(AdvancementNode advancement, Predicate test) { -+ Stack stack = new ObjectArrayList<>(); ++ public static boolean isVisible(AdvancementNode advancement, Predicate test) { ++ Stack stack = new ObjectArrayList<>(); + -+ for(int i = 0; i <= 2; ++i) { -+ stack.push(AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE); -+ } ++ for (int i = 0; i <= 2; i++) { ++ stack.push(AdvancementVisibilityEvaluator.VisibilityRule.NO_CHANGE); ++ } + -+ return evaluateVisibility(advancement.root(), stack, test, (node, currentVis) -> {}); -+ } ++ return evaluateVisibility(advancement.root(), stack, test, (node, currentVis) -> {}); ++ } + - @FunctionalInterface - public interface Output { - void accept(AdvancementNode p_298555_, boolean p_265580_); + @FunctionalInterface + public interface Output { + void accept(AdvancementNode p_298555_, boolean p_265580_); diff --git a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch index 6acfdc51cd..34aa9d369a 100644 --- a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch @@ -1,12 +1,23 @@ --- a/net/minecraft/server/commands/SpreadPlayersCommand.java +++ b/net/minecraft/server/commands/SpreadPlayersCommand.java -@@ -175,7 +_,8 @@ - spreadplayerscommand$position = p_138732_[i++]; - } +@@ -257,11 +_,17 @@ + spreadplayerscommand$position = p_138732_[i++]; + } -- entity.teleportTo(p_138731_, (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, (double)spreadplayerscommand$position.getSpawnY(p_138731_, p_138733_), (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D, Set.of(), entity.getYRot(), entity.getXRot()); -+ net.minecraftforge.event.entity.EntityTeleportEvent.SpreadPlayersCommand event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportSpreadPlayersCommand(entity, (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, (double)spreadplayerscommand$position.getSpawnY(p_138731_, p_138733_), (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D); -+ if (!event.isCanceled()) entity.teleportToWithTicket(event.getTargetX(), event.getTargetY(), event.getTargetZ()); - double d2 = Double.MAX_VALUE; - - for(SpreadPlayersCommand.Position spreadplayerscommand$position1 : p_138732_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportSpreadPlayersCommand(entity, ++ (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, ++ (double)spreadplayerscommand$position.getSpawnY(p_138731_, p_138733_), ++ (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D ++ ); ++ if (!event.isCanceled()) + entity.teleportTo( + p_138731_, +- (double)Mth.floor(spreadplayerscommand$position.x) + 0.5, +- (double)spreadplayerscommand$position.getSpawnY(p_138731_, p_138733_), +- (double)Mth.floor(spreadplayerscommand$position.z) + 0.5, ++ event.getTargetX(), ++ event.getTargetY(), ++ event.getTargetZ(), + Set.of(), + entity.getYRot(), + entity.getXRot() diff --git a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch index 80afbb919b..21cfb08708 100644 --- a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/server/commands/TeleportCommand.java +++ b/net/minecraft/server/commands/TeleportCommand.java -@@ -132,6 +_,9 @@ - } - - private static void performTeleport(CommandSourceStack p_139015_, Entity p_139016_, ServerLevel p_139017_, double p_139018_, double p_139019_, double p_139020_, Set p_139021_, float p_139022_, float p_139023_, @Nullable TeleportCommand.LookAt p_139024_) throws CommandSyntaxException { -+ net.minecraftforge.event.entity.EntityTeleportEvent.TeleportCommand event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportCommand(p_139016_, p_139018_, p_139019_, p_139020_); -+ if (event.isCanceled()) return; -+ p_139018_ = event.getTargetX(); p_139019_ = event.getTargetY(); p_139020_ = event.getTargetZ(); - BlockPos blockpos = BlockPos.containing(p_139018_, p_139019_, p_139020_); - if (!Level.isInSpawnableBounds(blockpos)) { - throw INVALID_POSITION.create(); +@@ -269,6 +_,9 @@ + float p_139023_, + @Nullable TeleportCommand.LookAt p_139024_ + ) throws CommandSyntaxException { ++ net.minecraftforge.event.entity.EntityTeleportEvent.TeleportCommand event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportCommand(p_139016_, p_139018_, p_139019_, p_139020_); ++ if (event.isCanceled()) return; ++ p_139018_ = event.getTargetX(); p_139019_ = event.getTargetY(); p_139020_ = event.getTargetZ(); + BlockPos blockpos = BlockPos.containing(p_139018_, p_139019_, p_139020_); + if (!Level.isInSpawnableBounds(blockpos)) { + throw INVALID_POSITION.create(); diff --git a/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch b/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch index 35f96ebc85..7f10326630 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch @@ -1,71 +1,72 @@ --- a/net/minecraft/server/dedicated/DedicatedServer.java +++ b/net/minecraft/server/dedicated/DedicatedServer.java -@@ -68,6 +_,8 @@ - private MinecraftServerGui gui; - @Nullable - private final TextFilterClient textFilterClient; -+ @Nullable -+ private net.minecraft.client.server.LanServerPinger dediLanPinger; +@@ -77,6 +_,8 @@ + private RemoteSampleLogger tickTimeLogger; + @Nullable + private DebugSampleSubscriptionTracker debugSampleSubscriptionTracker; ++ @Nullable ++ private net.minecraft.client.server.LanServerPinger dediLanPinger; - public DedicatedServer(Thread p_214789_, LevelStorageSource.LevelStorageAccess p_214790_, PackRepository p_214791_, WorldStem p_214792_, DedicatedServerSettings p_214793_, DataFixer p_214794_, Services p_214795_, ChunkProgressListenerFactory p_214796_) { - super(p_214789_, p_214790_, p_214791_, p_214792_, Proxy.NO_PROXY, p_214794_, p_214795_, p_214796_); -@@ -79,6 +_,7 @@ - public boolean initServer() throws IOException { - Thread thread = new Thread("Server console handler") { - public void run() { -+ if (net.minecraftforge.server.console.TerminalHandler.handleCommands(DedicatedServer.this)) return; - BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + public DedicatedServer( + Thread p_214789_, +@@ -99,6 +_,7 @@ + Thread thread = new Thread("Server console handler") { + @Override + public void run() { ++ if (net.minecraftforge.server.console.TerminalHandler.handleCommands(DedicatedServer.this)) return; + BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); - String s1; -@@ -156,11 +_,13 @@ - long i = Util.getNanos(); - SkullBlockEntity.setup(this.services, this); - GameProfileCache.setUsesAuthentication(this.usesAuthentication()); -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; - LOGGER.info("Preparing level \"{}\"", (Object)this.getLevelIdName()); - this.loadLevel(); - long j = Util.getNanos() - i; - String s = String.format(Locale.ROOT, "%.3fs", (double)j / 1.0E9D); - LOGGER.info("Done ({})! For help, type \"help\"", (Object)s); -+ this.nextTickTimeNanos = Util.getNanos(); //Forge: Update server time to prevent watchdog/spaming during long load. - if (dedicatedserverproperties.announcePlayerAchievements != null) { - this.getGameRules().getRule(GameRules.RULE_ANNOUNCE_ADVANCEMENTS).set(dedicatedserverproperties.announcePlayerAchievements, this); - } -@@ -188,7 +_,12 @@ - LOGGER.info("JMX monitoring enabled"); - } + String s1; +@@ -179,11 +_,13 @@ + long i = Util.getNanos(); + SkullBlockEntity.setup(this.services, this); + GameProfileCache.setUsesAuthentication(this.usesAuthentication()); ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; + LOGGER.info("Preparing level \"{}\"", this.getLevelIdName()); + this.loadLevel(); + long j = Util.getNanos() - i; + String s = String.format(Locale.ROOT, "%.3fs", (double)j / 1.0E9); + LOGGER.info("Done ({})! For help, type \"help\"", s); ++ this.nextTickTimeNanos = Util.getNanos(); //Forge: Update server time to prevent watchdog/spaming during long load. + if (dedicatedserverproperties.announcePlayerAchievements != null) { + this.getGameRules().getRule(GameRules.RULE_ANNOUNCE_ADVANCEMENTS).set(dedicatedserverproperties.announcePlayerAchievements, this); + } +@@ -211,7 +_,12 @@ + LOGGER.info("JMX monitoring enabled"); + } -- return true; -+ if (net.minecraftforge.common.ForgeConfig.SERVER.advertiseDedicatedServerToLan.get()) { -+ this.dediLanPinger = new net.minecraft.client.server.LanServerPinger(this.getMotd(), String.valueOf(this.getServerPort())); -+ this.dediLanPinger.start(); -+ } +- return true; ++ if (net.minecraftforge.common.ForgeConfig.SERVER.advertiseDedicatedServerToLan.get()) { ++ this.dediLanPinger = new net.minecraft.client.server.LanServerPinger(this.getMotd(), String.valueOf(this.getServerPort())); ++ this.dediLanPinger.start(); ++ } + -+ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); - } - } ++ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); + } + } -@@ -263,6 +_,10 @@ - this.queryThreadGs4.stop(); - } +@@ -289,6 +_,11 @@ + if (this.queryThreadGs4 != null) { + this.queryThreadGs4.stop(); + } ++ ++ if (this.dediLanPinger != null) { ++ this.dediLanPinger.interrupt(); ++ this.dediLanPinger = null; ++ } + } -+ if (this.dediLanPinger != null) { -+ this.dediLanPinger.interrupt(); -+ this.dediLanPinger = null; -+ } - } + @Override +@@ -542,7 +_,12 @@ - public void tickChildren(BooleanSupplier p_139661_) { -@@ -496,7 +_,12 @@ - } - - public void stopServer() { -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.GameShuttingDownEvent()); - super.stopServer(); -+ if (this.dediLanPinger != null) { -+ this.dediLanPinger.interrupt(); -+ this.dediLanPinger = null; -+ } - Util.shutdownExecutors(); - SkullBlockEntity.clear(); - } + @Override + public void stopServer() { ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.GameShuttingDownEvent()); + super.stopServer(); ++ if (this.dediLanPinger != null) { ++ this.dediLanPinger.interrupt(); ++ this.dediLanPinger = null; ++ } + Util.shutdownExecutors(); + SkullBlockEntity.clear(); + } diff --git a/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch b/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch index 52dd1021be..f94c512537 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/dedicated/ServerWatchdog.java +++ b/net/minecraft/server/dedicated/ServerWatchdog.java -@@ -41,7 +_,7 @@ - ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true); - StringBuilder stringbuilder = new StringBuilder(); -- Error error = new Error("Watchdog"); -+ Error error = new Error(String.format(java.util.Locale.ENGLISH, "ServerHangWatchdog detected that a single server tick took %.2f seconds (should be max 0.05)", k / 1000F)); // Forge: don't just make a crash report with a seemingly-inexplicable Error +@@ -48,7 +_,7 @@ + ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); + ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true); + StringBuilder stringbuilder = new StringBuilder(); +- Error error = new Error("Watchdog"); ++ Error error = new Error(String.format(java.util.Locale.ENGLISH, "ServerHangWatchdog detected that a single server tick took %.2f seconds (should be max 0.05)", k / 1000F)); // Forge: don't just make a crash report with a seemingly-inexplicable Error - for(ThreadInfo threadinfo : athreadinfo) { - if (threadinfo.getThreadId() == this.server.getRunningThread().getId()) { + for (ThreadInfo threadinfo : athreadinfo) { + if (threadinfo.getThreadId() == this.server.getRunningThread().getId()) { diff --git a/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch b/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch index cc9b374659..92153141c5 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/dedicated/Settings.java +++ b/net/minecraft/server/dedicated/Settings.java -@@ -55,7 +_,7 @@ +@@ -66,7 +_,7 @@ - public void store(Path p_139877_) { - try (Writer writer = Files.newBufferedWriter(p_139877_, StandardCharsets.UTF_8)) { -- this.properties.store(writer, "Minecraft server properties"); -+ net.minecraftforge.common.util.SortedProperties.store(this.properties, writer, "Minecraft server properties"); - } catch (IOException ioexception) { - LOGGER.error("Failed to store properties to file: {}", (Object)p_139877_); - } + public void store(Path p_139877_) { + try (Writer writer = Files.newBufferedWriter(p_139877_, StandardCharsets.UTF_8)) { +- this.properties.store(writer, "Minecraft server properties"); ++ net.minecraftforge.common.util.SortedProperties.store(this.properties, writer, "Minecraft server properties"); + } catch (IOException ioexception) { + LOGGER.error("Failed to store properties to file: {}", p_139877_); + } diff --git a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch index ba4022a3ac..7460d11383 100644 --- a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch +++ b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/server/gui/MinecraftServerGui.java +++ b/net/minecraft/server/gui/MinecraftServerGui.java -@@ -139,8 +_,10 @@ - return jpanel; - } +@@ -137,8 +_,10 @@ + return jpanel; + } -+ private java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); - public void start() { - this.logAppenderThread.start(); -+ latch.countDown(); - } ++ private final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); + public void start() { + this.logAppenderThread.start(); ++ this.latch.countDown(); + } - public void close() { -@@ -155,6 +_,9 @@ - } + public void close() { +@@ -152,6 +_,9 @@ + } - public void print(JTextArea p_139915_, JScrollPane p_139916_, String p_139917_) { -+ try { -+ latch.await(); -+ } catch (InterruptedException e){} //Prevent logging until after constructor has ended. - if (!SwingUtilities.isEventDispatchThread()) { - SwingUtilities.invokeLater(() -> { - this.print(p_139915_, p_139916_, p_139917_); + public void print(JTextArea p_139915_, JScrollPane p_139916_, String p_139917_) { ++ try { ++ this.latch.await(); ++ } catch (InterruptedException ignored) {} // Prevent logging until after constructor has ended + if (!SwingUtilities.isEventDispatchThread()) { + SwingUtilities.invokeLater(() -> this.print(p_139915_, p_139916_, p_139917_)); + } else { diff --git a/patches/minecraft/net/minecraft/server/level/ChunkHolder.java.patch b/patches/minecraft/net/minecraft/server/level/ChunkHolder.java.patch index 59794e70cb..538cfbdde1 100644 --- a/patches/minecraft/net/minecraft/server/level/ChunkHolder.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ChunkHolder.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/level/ChunkHolder.java +++ b/net/minecraft/server/level/ChunkHolder.java -@@ -63,6 +_,7 @@ - private final ChunkHolder.LevelChangeListener onLevelChange; - private final ChunkHolder.PlayerProvider playerProvider; - private boolean wasAccessibleSinceLastSave; -+ LevelChunk currentlyLoading; // Forge: Used to bypass future chain when loading chunks. - private CompletableFuture pendingFullStateConfirmation = CompletableFuture.completedFuture((Void)null); - private CompletableFuture sendSync = CompletableFuture.completedFuture((Object)null); +@@ -64,6 +_,7 @@ + private boolean wasAccessibleSinceLastSave; + private CompletableFuture pendingFullStateConfirmation = CompletableFuture.completedFuture(null); + private CompletableFuture sendSync = CompletableFuture.completedFuture(null); ++ LevelChunk currentlyLoading; // Forge: Used to bypass future chain when loading chunks. + public ChunkHolder( + ChunkPos p_142986_, diff --git a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch index 167d4b6f25..20a99d89ac 100644 --- a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch @@ -1,50 +1,50 @@ --- a/net/minecraft/server/level/ChunkMap.java +++ b/net/minecraft/server/level/ChunkMap.java -@@ -392,6 +_,7 @@ - this.modified = true; - } +@@ -413,6 +_,7 @@ + this.modified = true; + } -+ net.minecraftforge.event.ForgeEventFactory.fireChunkTicketLevelUpdated(this.level, p_140177_, p_140180_, p_140178_, p_140179_); - return p_140179_; - } - } -@@ -497,6 +_,7 @@ - if (this.pendingUnloads.remove(p_140182_, p_140183_) && p_203002_ != null) { - if (p_203002_ instanceof LevelChunk) { - ((LevelChunk)p_203002_).setLoaded(false); -+ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(p_203002_); - } ++ net.minecraftforge.event.ForgeEventFactory.fireChunkTicketLevelUpdated(this.level, p_140177_, p_140180_, p_140178_, p_140179_); + return p_140179_; + } + } +@@ -521,6 +_,7 @@ + if (this.pendingUnloads.remove(p_140182_, p_140183_) && p_203002_ != null) { + if (p_203002_ instanceof LevelChunk) { + ((LevelChunk)p_203002_).setLoaded(false); ++ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(p_203002_); + } - this.save(p_203002_); -@@ -707,8 +_,14 @@ + this.save(p_203002_); +@@ -717,8 +_,14 @@ levelchunk.runPostLoad(); if (this.entitiesInLevel.add(chunkpos.toLong())) { - levelchunk.setLoaded(true); -+ try { -+ p_140384_.currentlyLoading = levelchunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. - levelchunk.registerAllBlockEntitiesAfterLevelLoad(); - levelchunk.registerTickContainerInLevel(this.level); -+ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelchunk, !(protochunk instanceof ImposterProtoChunk)); -+ } finally { -+ p_140384_.currentlyLoading = null; // Forge - Stop bypassing the future chain. -+ } + levelchunk.setLoaded(true); ++ try { ++ p_140384_.currentlyLoading = levelchunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. + levelchunk.registerAllBlockEntitiesAfterLevelLoad(); + levelchunk.registerTickContainerInLevel(this.level); ++ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelchunk, !(protochunk instanceof ImposterProtoChunk)); ++ } finally { ++ p_140384_.currentlyLoading = null; // Forge - Stop bypassing the future chain. ++ } } return levelchunk; -@@ -823,6 +_,7 @@ +@@ -818,6 +_,7 @@ - this.level.getProfiler().incrementCounter("chunkSave"); - CompoundTag compoundtag = ChunkSerializer.write(this.level, p_140259_); -+ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(p_140259_, p_140259_.getWorldForge() != null ? p_140259_.getWorldForge() : this.level, compoundtag); - this.write(chunkpos, compoundtag); - this.markPosition(chunkpos, chunkstatus.getChunkType()); - return true; -@@ -1118,7 +_,7 @@ - } + this.level.getProfiler().incrementCounter("chunkSave"); + CompoundTag compoundtag = ChunkSerializer.write(this.level, p_140259_); ++ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(p_140259_, p_140259_.getWorldForge() != null ? p_140259_.getWorldForge() : this.level, compoundtag); + this.write(chunkpos, compoundtag).exceptionallyAsync(p_326408_ -> { + this.level.getServer().reportChunkSaveFailure(chunkpos); + return null; +@@ -1136,7 +_,7 @@ + } - protected void addEntity(Entity p_140200_) { -- if (!(p_140200_ instanceof EnderDragonPart)) { -+ if (!(p_140200_ instanceof net.minecraftforge.entity.PartEntity)) { - EntityType entitytype = p_140200_.getType(); - int i = entitytype.clientTrackingRange() * 16; - if (i != 0) { + protected void addEntity(Entity p_140200_) { +- if (!(p_140200_ instanceof EnderDragonPart)) { ++ if (!(p_140200_ instanceof net.minecraftforge.entity.PartEntity)) { + EntityType entitytype = p_140200_.getType(); + int i = entitytype.clientTrackingRange() * 16; + if (i != 0) { diff --git a/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch b/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch index 1d6468f399..707f8f8274 100644 --- a/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch @@ -1,71 +1,74 @@ --- a/net/minecraft/server/level/DistanceManager.java +++ b/net/minecraft/server/level/DistanceManager.java -@@ -54,6 +_,8 @@ - private long ticketTickCounter; - private int simulationDistance = 10; +@@ -53,6 +_,7 @@ + final Executor mainThreadExecutor; + private long ticketTickCounter; + private int simulationDistance = 10; ++ private final Long2ObjectOpenHashMap>> forcedTickets = new Long2ObjectOpenHashMap<>(); -+ private final Long2ObjectOpenHashMap>> forcedTickets = new Long2ObjectOpenHashMap<>(); + protected DistanceManager(Executor p_140774_, Executor p_140775_) { + ProcessorHandle processorhandle = ProcessorHandle.of("player ticket throttler", p_140775_::execute); +@@ -151,6 +_,11 @@ + if (p_140786_.getTicketLevel() < i) { + this.ticketTracker.update(p_140785_, p_140786_.getTicketLevel(), true); + } + - protected DistanceManager(Executor p_140774_, Executor p_140775_) { - ProcessorHandle processorhandle = ProcessorHandle.of("player ticket throttler", p_140775_::execute); - ChunkTaskPriorityQueueSorter chunktaskpriorityqueuesorter = new ChunkTaskPriorityQueueSorter(ImmutableList.of(processorhandle), p_140774_, 4); -@@ -159,6 +_,10 @@ - this.ticketTracker.update(p_140785_, p_140786_.getTicketLevel(), true); - } ++ if (p_140786_.isForceTicks()) { ++ var tickets = forcedTickets.computeIfAbsent(p_140785_, e -> SortedArraySet.create(4)); ++ tickets.addOrGet(ticket); ++ } + } -+ if (p_140786_.isForceTicks()) { -+ SortedArraySet> tickets = forcedTickets.computeIfAbsent(p_140785_, e -> SortedArraySet.create(4)); -+ tickets.addOrGet(ticket); -+ } - } + void removeTicket(long p_140819_, Ticket p_140820_) { +@@ -163,6 +_,14 @@ + } - void removeTicket(long p_140819_, Ticket p_140820_) { -@@ -171,6 +_,13 @@ - } - - this.ticketTracker.update(p_140819_, getTicketLevelAt(sortedarrayset), false); + this.ticketTracker.update(p_140819_, getTicketLevelAt(sortedarrayset), false); + -+ if (p_140820_.isForceTicks()) { -+ SortedArraySet> tickets = forcedTickets.get(p_140819_); -+ if (tickets != null) { -+ tickets.remove(p_140820_); -+ } -+ } - } - - public void addTicket(TicketType p_140793_, ChunkPos p_140794_, int p_140795_, T p_140796_) { -@@ -183,14 +_,20 @@ - } - - public void addRegionTicket(TicketType p_140841_, ChunkPos p_140842_, int p_140843_, T p_140844_) { -- Ticket ticket = new Ticket<>(p_140841_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140843_, p_140844_); -+ addRegionTicket(p_140841_, p_140842_, p_140843_, p_140844_, false); -+ } -+ public void addRegionTicket(TicketType p_140841_, ChunkPos p_140842_, int p_140843_, T p_140844_, boolean forceTicks) { -+ Ticket ticket = new Ticket<>(p_140841_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140843_, p_140844_, forceTicks); - long i = p_140842_.toLong(); - this.addTicket(i, ticket); - this.tickingTicketsTracker.addTicket(i, ticket); - } - - public void removeRegionTicket(TicketType p_140850_, ChunkPos p_140851_, int p_140852_, T p_140853_) { -- Ticket ticket = new Ticket<>(p_140850_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140852_, p_140853_); -+ removeRegionTicket(p_140850_, p_140851_, p_140852_, p_140853_, false); -+ } -+ public void removeRegionTicket(TicketType p_140850_, ChunkPos p_140851_, int p_140852_, T p_140853_, boolean forceTicks) { -+ Ticket ticket = new Ticket<>(p_140850_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140852_, p_140853_, forceTicks); - long i = p_140851_.toLong(); - this.removeTicket(i, ticket); - this.tickingTicketsTracker.removeTicket(i, ticket); -@@ -281,6 +_,11 @@ - - public String getDebugStatus() { - return this.ticketThrottler.getDebugStatus(); -+ } + -+ public boolean shouldForceTicks(long chunkPos) { -+ SortedArraySet> tickets = forcedTickets.get(chunkPos); -+ return tickets != null && !tickets.isEmpty(); - } ++ if (p_140820_.isForceTicks()) { ++ var tickets = forcedTickets.get(p_140819_); ++ if (tickets != null) { ++ tickets.remove(p_140820_); ++ } ++ } + } - private void dumpTickets(String p_143208_) { + public void addTicket(TicketType p_140793_, ChunkPos p_140794_, int p_140795_, T p_140796_) { +@@ -175,14 +_,22 @@ + } + + public void addRegionTicket(TicketType p_140841_, ChunkPos p_140842_, int p_140843_, T p_140844_) { +- Ticket ticket = new Ticket<>(p_140841_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140843_, p_140844_); ++ addRegionTicket(p_140841_, p_140842_, p_140843_, p_140844_, false); ++ } ++ ++ public void addRegionTicket(TicketType p_140841_, ChunkPos p_140842_, int p_140843_, T p_140844_, boolean forceTicks) { ++ Ticket ticket = new Ticket<>(p_140841_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140843_, p_140844_, forceTicks); + long i = p_140842_.toLong(); + this.addTicket(i, ticket); + this.tickingTicketsTracker.addTicket(i, ticket); + } + + public void removeRegionTicket(TicketType p_140850_, ChunkPos p_140851_, int p_140852_, T p_140853_) { +- Ticket ticket = new Ticket<>(p_140850_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140852_, p_140853_); ++ removeRegionTicket(p_140850_, p_140851_, p_140852_, p_140853_, false); ++ } ++ ++ public void removeRegionTicket(TicketType p_140850_, ChunkPos p_140851_, int p_140852_, T p_140853_, boolean forceTicks) { ++ Ticket ticket = new Ticket<>(p_140850_, ChunkLevel.byStatus(FullChunkStatus.FULL) - p_140852_, p_140853_, forceTicks); + long i = p_140851_.toLong(); + this.removeTicket(i, ticket); + this.tickingTicketsTracker.removeTicket(i, ticket); +@@ -266,6 +_,11 @@ + + public String getDebugStatus() { + return this.ticketThrottler.getDebugStatus(); ++ } ++ ++ public boolean shouldForceTicks(long chunkPos) { ++ SortedArraySet> tickets = forcedTickets.get(chunkPos); ++ return tickets != null && !tickets.isEmpty(); + } + + private void dumpTickets(String p_143208_) { diff --git a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch index 7f08234f00..cdd931ffa7 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch @@ -1,39 +1,44 @@ --- a/net/minecraft/server/level/ServerChunkCache.java +++ b/net/minecraft/server/level/ServerChunkCache.java -@@ -160,6 +_,7 @@ - if (chunkholder == null) { - return null; - } else { -+ if (chunkholder.currentlyLoading != null) return chunkholder.currentlyLoading; // Forge: If the requested chunk is loading, bypass the future chain to prevent a deadlock. - Either either = chunkholder.getFutureIfPresent(ChunkStatus.FULL).getNow((Either)null); - if (either == null) { - return null; -@@ -347,7 +_,7 @@ - for(ServerChunkCache.ChunkAndHolder serverchunkcache$chunkandholder : list) { - LevelChunk levelchunk1 = serverchunkcache$chunkandholder.chunk; - ChunkPos chunkpos = levelchunk1.getPos(); -- if (this.level.isNaturalSpawningAllowed(chunkpos) && this.chunkMap.anyPlayerCloseEnoughForSpawning(chunkpos)) { -+ if ((this.level.isNaturalSpawningAllowed(chunkpos) && this.chunkMap.anyPlayerCloseEnoughForSpawning(chunkpos)) || this.distanceManager.shouldForceTicks(chunkpos.toLong())) { - levelchunk1.incrementInhabitedTime(j); - if (flag1 && (this.spawnEnemies || this.spawnFriendlies) && this.level.getWorldBorder().isWithinBounds(chunkpos)) { - NaturalSpawner.spawnForChunk(this.level, levelchunk1, naturalspawner$spawnstate, this.spawnFriendlies, this.spawnEnemies, flag); -@@ -428,11 +_,17 @@ - } +@@ -171,6 +_,10 @@ + if (chunkholder == null) { + return null; + } else { ++ // Forge: If the requested chunk is loading, bypass the future chain to prevent a deadlock. ++ if (chunkholder.currentlyLoading != null) { ++ return chunkholder.currentlyLoading; ++ } + ChunkResult chunkresult = chunkholder.getFutureIfPresent(ChunkStatus.FULL).getNow(null); + if (chunkresult == null) { + return null; +@@ -363,7 +_,7 @@ + for (ServerChunkCache.ChunkAndHolder serverchunkcache$chunkandholder : list) { + LevelChunk levelchunk1 = serverchunkcache$chunkandholder.chunk; + ChunkPos chunkpos = levelchunk1.getPos(); +- if (this.level.isNaturalSpawningAllowed(chunkpos) && this.chunkMap.anyPlayerCloseEnoughForSpawning(chunkpos)) { ++ if ((this.level.isNaturalSpawningAllowed(chunkpos) && this.chunkMap.anyPlayerCloseEnoughForSpawning(chunkpos)) || this.distanceManager.shouldForceTicks(chunkpos.toLong())) { + levelchunk1.incrementInhabitedTime(j); + if (flag1 && (this.spawnEnemies || this.spawnFriendlies) && this.level.getWorldBorder().isWithinBounds(chunkpos)) { + NaturalSpawner.spawnForChunk(this.level, levelchunk1, naturalspawner$spawnstate, this.spawnFriendlies, this.spawnEnemies, flag); +@@ -442,11 +_,19 @@ + } - public void addRegionTicket(TicketType p_8388_, ChunkPos p_8389_, int p_8390_, T p_8391_) { -- this.distanceManager.addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_); -+ addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_, false); -+ } -+ public void addRegionTicket(TicketType p_8388_, ChunkPos p_8389_, int p_8390_, T p_8391_, boolean forceTicks) { -+ this.distanceManager.addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_, forceTicks); - } + public void addRegionTicket(TicketType p_8388_, ChunkPos p_8389_, int p_8390_, T p_8391_) { +- this.distanceManager.addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_); ++ addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_, false); ++ } ++ ++ public void addRegionTicket(TicketType p_8388_, ChunkPos p_8389_, int p_8390_, T p_8391_, boolean forceTicks) { ++ this.distanceManager.addRegionTicket(p_8388_, p_8389_, p_8390_, p_8391_, forceTicks); + } - public void removeRegionTicket(TicketType p_8439_, ChunkPos p_8440_, int p_8441_, T p_8442_) { -- this.distanceManager.removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_); -+ removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_, false); -+ } -+ public void removeRegionTicket(TicketType p_8439_, ChunkPos p_8440_, int p_8441_, T p_8442_, boolean forceTicks) { -+ this.distanceManager.removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_, forceTicks); - } + public void removeRegionTicket(TicketType p_8439_, ChunkPos p_8440_, int p_8441_, T p_8442_) { +- this.distanceManager.removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_); ++ removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_, false); ++ } ++ ++ public void removeRegionTicket(TicketType p_8439_, ChunkPos p_8440_, int p_8441_, T p_8442_, boolean forceTicks) { ++ this.distanceManager.removeRegionTicket(p_8439_, p_8440_, p_8441_, p_8442_, forceTicks); + } - public void updateChunkForced(ChunkPos p_8400_, boolean p_8401_) { + @Override diff --git a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch index 249293e94b..6cd7d89fe1 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch @@ -1,46 +1,18 @@ --- a/net/minecraft/server/level/ServerEntity.java +++ b/net/minecraft/server/level/ServerEntity.java -@@ -95,10 +_,9 @@ - if ($$11 instanceof ItemFrame itemframe) { - if (this.tickCount % 10 == 0) { - ItemStack itemstack = itemframe.getItem(); -- if (itemstack.getItem() instanceof MapItem) { -- Integer integer = MapItem.getMapId(itemstack); -- MapItemSavedData mapitemsaveddata = MapItem.getSavedData(integer, this.level); -- if (mapitemsaveddata != null) { -+ Integer integer = MapItem.getMapId(itemstack); -+ MapItemSavedData mapitemsaveddata = MapItem.getSavedData(itemstack, this.level); -+ if (mapitemsaveddata != null) { - for(ServerPlayer serverplayer : this.level.players()) { - mapitemsaveddata.tickCarriedBy(serverplayer, itemstack); - Packet packet = mapitemsaveddata.getUpdatePacket(integer, serverplayer); -@@ -107,11 +_,12 @@ - } - } - } -- } +@@ -239,6 +_,7 @@ + public void removePairing(ServerPlayer p_8535_) { + this.entity.stopSeenByPlayer(p_8535_); + p_8535_.connection.send(new ClientboundRemoveEntitiesPacket(this.entity.getId())); ++ net.minecraftforge.event.ForgeEventFactory.onStopEntityTracking(this.entity, p_8535_); + } - this.sendDirtyEntityData(); - } - } -+ -+ + public void addPairing(ServerPlayer p_8542_) { +@@ -246,6 +_,7 @@ + this.sendPairingData(p_8542_, list::add); + p_8542_.connection.send(new ClientboundBundlePacket(list)); + this.entity.startSeenByPlayer(p_8542_); ++ net.minecraftforge.event.ForgeEventFactory.onStartEntityTracking(this.entity, p_8542_); + } - if (this.tickCount % this.updateInterval == 0 || this.entity.hasImpulse || this.entity.getEntityData().isDirty()) { - if (this.entity.isPassenger()) { -@@ -218,6 +_,7 @@ - public void removePairing(ServerPlayer p_8535_) { - this.entity.stopSeenByPlayer(p_8535_); - p_8535_.connection.send(new ClientboundRemoveEntitiesPacket(this.entity.getId())); -+ net.minecraftforge.event.ForgeEventFactory.onStopEntityTracking(this.entity, p_8535_); - } - - public void addPairing(ServerPlayer p_8542_) { -@@ -225,6 +_,7 @@ - this.sendPairingData(p_8542_, list::add); - p_8542_.connection.send(new ClientboundBundlePacket(list)); - this.entity.startSeenByPlayer(p_8542_); -+ net.minecraftforge.event.ForgeEventFactory.onStartEntityTracking(this.entity, p_8542_); - } - - public void sendPairingData(ServerPlayer p_289562_, Consumer> p_289563_) { + public void sendPairingData(ServerPlayer p_289562_, Consumer> p_289563_) { diff --git a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch index 504d993dd6..51261cc6a0 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch @@ -1,230 +1,219 @@ --- a/net/minecraft/server/level/ServerLevel.java +++ b/net/minecraft/server/level/ServerLevel.java -@@ -190,11 +_,12 @@ - private final List customSpawners; - @Nullable - private EndDragonFight dragonFight; -- final Int2ObjectMap dragonParts = new Int2ObjectOpenHashMap<>(); -+ final Int2ObjectMap> dragonParts = new Int2ObjectOpenHashMap<>(); - private final StructureManager structureManager; - private final StructureCheck structureCheck; - private final boolean tickTime; - private final RandomSequences randomSequences; -+ private net.minecraftforge.common.util.LevelCapabilityData capabilityData; +@@ -198,11 +_,12 @@ + private final List customSpawners; + @Nullable + private EndDragonFight dragonFight; +- final Int2ObjectMap dragonParts = new Int2ObjectOpenHashMap<>(); ++ final Int2ObjectMap> dragonParts = new Int2ObjectOpenHashMap<>(); + private final StructureManager structureManager; + private final StructureCheck structureCheck; + private final boolean tickTime; + private final RandomSequences randomSequences; ++ private net.minecraftforge.common.util.LevelCapabilityData capabilityData; - public ServerLevel(MinecraftServer p_214999_, Executor p_215000_, LevelStorageSource.LevelStorageAccess p_215001_, ServerLevelData p_215002_, ResourceKey p_215003_, LevelStem p_215004_, ChunkProgressListener p_215005_, boolean p_215006_, long p_215007_, List p_215008_, boolean p_215009_, @Nullable RandomSequences p_288977_) { - super(p_215002_, p_215003_, p_214999_.registryAccess(), p_215004_.type(), p_214999_::getProfiler, false, p_215006_, p_215007_, p_214999_.getMaxChainedNeighborUpdates()); -@@ -234,6 +_,7 @@ - this.randomSequences = Objects.requireNonNullElseGet(p_288977_, () -> { - return this.getDataStorage().computeIfAbsent(RandomSequences.factory(i), "random_sequences"); - }); -+ this.initCapabilities(); - } + public ServerLevel( + MinecraftServer p_214999_, +@@ -285,6 +_,12 @@ + this.sleepStatus = new SleepStatus(); + this.gameEventDispatcher = new GameEventDispatcher(this); + this.randomSequences = Objects.requireNonNullElseGet(p_288977_, () -> this.getDataStorage().computeIfAbsent(RandomSequences.factory(i), "random_sequences")); ++ this.initCapabilities(); ++ } ++ ++ protected void initCapabilities() { ++ this.gatherCapabilities(); ++ capabilityData = net.minecraftforge.common.util.LevelCapabilityData.compute(this.getDataStorage(), getCapabilities()); + } - /** @deprecated */ -@@ -274,8 +_,8 @@ - int i = this.getGameRules().getInt(GameRules.RULE_PLAYERS_SLEEPING_PERCENTAGE); - if (this.sleepStatus.areEnoughSleeping(i) && this.sleepStatus.areEnoughDeepSleeping(i, this.players)) { - if (this.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)) { -- long j = this.levelData.getDayTime() + 24000L; -- this.setDayTime(j - j % 24000L); -+ long j = this.getDayTime() + 24000L; -+ this.setDayTime(net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, j - j % 24000L, this.getDayTime())); - } + @Deprecated +@@ -325,8 +_,8 @@ + int i = this.getGameRules().getInt(GameRules.RULE_PLAYERS_SLEEPING_PERCENTAGE); + if (this.sleepStatus.areEnoughSleeping(i) && this.sleepStatus.areEnoughDeepSleeping(i, this.players)) { + if (this.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)) { +- long j = this.levelData.getDayTime() + 24000L; +- this.setDayTime(j - j % 24000L); ++ long j = this.getDayTime() + 24000L; ++ this.setDayTime(net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, j - j % 24000L, this.getDayTime())); + } - this.wakeUpAllPlayers(); -@@ -313,7 +_,7 @@ + this.wakeUpAllPlayers(); +@@ -364,7 +_,8 @@ - this.handlingTick = false; - profilerfiller.pop(); -- boolean flag1 = !this.players.isEmpty() || !this.getForcedChunks().isEmpty(); -+ boolean flag1 = !this.players.isEmpty() || net.minecraftforge.common.world.ForgeChunkManager.hasForcedChunks(this); //Forge: Replace vanilla's has forced chunk check with forge's that checks both the vanilla and forge added ones - if (flag1) { - this.resetEmptyTime(); - } -@@ -344,6 +_,7 @@ - p_308944_.stopRiding(); - } + this.handlingTick = false; + profilerfiller.pop(); +- boolean flag1 = !this.players.isEmpty() || !this.getForcedChunks().isEmpty(); ++ // Forge: Replace vanilla's has forced chunk check with forge's that checks both the vanilla and forge added ones ++ boolean flag1 = !this.players.isEmpty() || net.minecraftforge.common.world.ForgeChunkManager.hasForcedChunks(this); + if (flag1) { + this.resetEmptyTime(); + } +@@ -395,6 +_,7 @@ + p_308944_.stopRiding(); + } -+ if (p_308944_.isRemoved() || p_308944_ instanceof net.minecraftforge.entity.PartEntity) return; - profilerfiller.push("tick"); - this.guardEntityTick(this::tickNonPassenger, p_308944_); - profilerfiller.pop(); -@@ -478,6 +_,7 @@ - BlockPos blockpos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, p_300602_); - BlockPos blockpos1 = blockpos.below(); - Biome biome = this.getBiome(blockpos).value(); -+ if (this.isAreaLoaded(blockpos1, 1)) // Forge: check area to avoid loading neighbors in unloaded chunks - if (biome.shouldFreeze(this, blockpos1)) { - this.setBlockAndUpdate(blockpos1, Blocks.ICE.defaultBlockState()); - } -@@ -650,15 +_,19 @@ - this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, this.thunderLevel), this.dimension()); - } ++ if (p_308944_.isRemoved() || p_308944_ instanceof net.minecraftforge.entity.PartEntity) return; + profilerfiller.push("tick"); + this.guardEntityTick(this::tickNonPassenger, p_308944_); + profilerfiller.pop(); +@@ -526,6 +_,7 @@ + BlockPos blockpos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, p_300602_); + BlockPos blockpos1 = blockpos.below(); + Biome biome = this.getBiome(blockpos).value(); ++ if (this.isAreaLoaded(blockpos1, 1)) // Forge: check area to avoid loading neighbors in unloaded chunks + if (biome.shouldFreeze(this, blockpos1)) { + this.setBlockAndUpdate(blockpos1, Blocks.ICE.defaultBlockState()); + } +@@ -701,8 +_,8 @@ + this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F)); + } -+ /* The function in use here has been replaced in order to only send the weather info to players in the correct dimension, -+ * rather than to all players on the server. This is what causes the client-side rain, as the -+ * client believes that it has started raining locally, rather than in another dimension. -+ */ - if (flag != this.isRaining()) { - if (flag) { -- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.STOP_RAINING, 0.0F)); -+ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.STOP_RAINING, 0.0F), this.dimension()); - } else { -- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F)); -+ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F), this.dimension()); - } +- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, this.rainLevel)); +- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, this.thunderLevel)); ++ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, this.rainLevel), this.dimension()); ++ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, this.thunderLevel), this.dimension()); + } + } -- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, this.rainLevel)); -- this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, this.thunderLevel)); -+ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, this.rainLevel), this.dimension()); -+ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, this.thunderLevel), this.dimension()); - } - - } -@@ -718,6 +_,7 @@ - return BuiltInRegistries.ENTITY_TYPE.getKey(p_8664_.getType()).toString(); - }); +@@ -755,6 +_,7 @@ + ProfilerFiller profilerfiller = this.getProfiler(); + profilerfiller.push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(p_8664_.getType()).toString()); profilerfiller.incrementCounter("tickPassenger"); + if (p_8664_.canUpdate()) p_8664_.rideTick(); profilerfiller.pop(); -@@ -754,6 +_,7 @@ - this.entityManager.autoSave(); - } - -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.LevelEvent.Save(this)); - } - } - -@@ -846,6 +_,7 @@ - } - - private void addPlayer(ServerPlayer p_8854_) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityJoinLevelEvent(p_8854_, this))) return; - Entity entity = this.getEntities().get(p_8854_.getUUID()); - if (entity != null) { - LOGGER.warn("Force-added player with duplicate UUID {}", (Object)p_8854_.getUUID()); -@@ -853,7 +_,8 @@ - this.removePlayerImmediately((ServerPlayer)entity, Entity.RemovalReason.DISCARDED); - } - -- this.entityManager.addNewEntity(p_8854_); -+ this.entityManager.addNewEntityWithoutEvent(p_8854_); -+ p_8854_.onAddedToWorld(); - } - - private boolean addEntity(Entity p_8873_) { -@@ -861,7 +_,12 @@ - LOGGER.warn("Tried to add entity {} but it was marked as removed already", (Object)EntityType.getKey(p_8873_.getType())); - return false; - } else { -- return this.entityManager.addNewEntity(p_8873_); -+ if (this.entityManager.addNewEntity(p_8873_)) { -+ p_8873_.onAddedToWorld(); -+ return true; -+ } else { -+ return false; -+ } - } - } - -@@ -898,10 +_,22 @@ - } - - public void playSeededSound(@Nullable Player p_263330_, double p_263393_, double p_263369_, double p_263354_, Holder p_263412_, SoundSource p_263338_, float p_263352_, float p_263390_, long p_263403_) { -+ net.minecraftforge.event.PlayLevelSoundEvent.AtPosition event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtPosition(this, p_263393_, p_263369_, p_263354_, p_263412_, p_263338_, p_263352_, p_263390_); -+ if (event.isCanceled() || event.getSound() == null) return; -+ p_263412_ = event.getSound(); -+ p_263338_ = event.getSource(); -+ p_263352_ = event.getNewVolume(); -+ p_263390_ = event.getNewPitch(); - this.server.getPlayerList().broadcast(p_263330_, p_263393_, p_263369_, p_263354_, (double)p_263412_.value().getRange(p_263352_), this.dimension(), new ClientboundSoundPacket(p_263412_, p_263338_, p_263393_, p_263369_, p_263354_, p_263352_, p_263390_, p_263403_)); - } - - public void playSeededSound(@Nullable Player p_263545_, Entity p_263544_, Holder p_263491_, SoundSource p_263542_, float p_263530_, float p_263520_, long p_263490_) { -+ net.minecraftforge.event.PlayLevelSoundEvent.AtEntity event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(p_263544_, p_263491_, p_263542_, p_263530_, p_263520_); -+ if (event.isCanceled() || event.getSound() == null) return; -+ p_263491_ = event.getSound(); -+ p_263542_ = event.getSource(); -+ p_263530_ = event.getNewVolume(); -+ p_263520_ = event.getNewPitch(); - this.server.getPlayerList().broadcast(p_263545_, p_263544_.getX(), p_263544_.getY(), p_263544_.getZ(), (double)p_263491_.value().getRange(p_263530_), this.dimension(), new ClientboundSoundEntityPacket(p_263491_, p_263542_, p_263544_, p_263530_, p_263520_, p_263490_)); - } - -@@ -923,6 +_,7 @@ - } - - public void gameEvent(GameEvent p_215041_, Vec3 p_215042_, GameEvent.Context p_215043_) { -+ if (!net.minecraftforge.common.ForgeHooks.onVanillaGameEvent(this, p_215041_, p_215042_, p_215043_)) return; - this.gameEventDispatcher.post(p_215041_, p_215042_, p_215043_); - } - -@@ -959,10 +_,15 @@ - } - - public void updateNeighborsAt(BlockPos p_215045_, Block p_215046_) { -+ net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_215045_, this.getBlockState(p_215045_), java.util.EnumSet.allOf(Direction.class), false).isCanceled(); - this.neighborUpdater.updateNeighborsAtExceptFromFacing(p_215045_, p_215046_, (Direction)null); - } - - public void updateNeighborsAtExceptFromFacing(BlockPos p_215052_, Block p_215053_, Direction p_215054_) { -+ java.util.EnumSet directions = java.util.EnumSet.allOf(Direction.class); -+ directions.remove(p_215054_); -+ if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_215052_, this.getBlockState(p_215052_), directions, false).isCanceled()) -+ return; - this.neighborUpdater.updateNeighborsAtExceptFromFacing(p_215052_, p_215053_, p_215054_); - } - -@@ -1402,6 +_,11 @@ - }); - } - -+ protected void initCapabilities() { -+ this.gatherCapabilities(); -+ capabilityData = net.minecraftforge.common.util.LevelCapabilityData.compute(this.getDataStorage(), getCapabilities()); -+ } -+ - public LevelEntityGetter getEntities() { - return this.entityManager.getEntityGetter(); - } -@@ -1505,8 +_,8 @@ - ServerLevel.this.navigatingMobs.add(mob); - } - -- if (p_143371_ instanceof EnderDragon enderdragon) { -- for(EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { -+ if (p_143371_.isMultipartEntity()) { -+ for(net.minecraftforge.entity.PartEntity enderdragonpart : p_143371_.getParts()) { - ServerLevel.this.dragonParts.put(enderdragonpart.getId(), enderdragonpart); +@@ -787,6 +_,7 @@ + } else { + this.entityManager.autoSave(); } - } -@@ -1530,17 +_,25 @@ - ServerLevel.this.navigatingMobs.remove(mob); - } ++ net.minecraftforge.event.ForgeEventFactory.onLevelSave(this); + } + } -- if (p_143375_ instanceof EnderDragon enderdragon) { -- for(EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { -+ if (p_143375_.isMultipartEntity()) { -+ for(net.minecraftforge.entity.PartEntity enderdragonpart : p_143375_.getParts()) { - ServerLevel.this.dragonParts.remove(enderdragonpart.getId()); +@@ -880,6 +_,7 @@ + } + + private void addPlayer(ServerPlayer p_8854_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onEntityJoinLevel(p_8854_, this)) return; + Entity entity = this.getEntities().get(p_8854_.getUUID()); + if (entity != null) { + LOGGER.warn("Force-added player with duplicate UUID {}", p_8854_.getUUID()); +@@ -887,7 +_,8 @@ + this.removePlayerImmediately((ServerPlayer)entity, Entity.RemovalReason.DISCARDED); + } + +- this.entityManager.addNewEntity(p_8854_); ++ this.entityManager.addNewEntityWithoutEvent(p_8854_); ++ p_8854_.onAddedToWorld(); + } + + private boolean addEntity(Entity p_8873_) { +@@ -895,7 +_,12 @@ + LOGGER.warn("Tried to add entity {} but it was marked as removed already", EntityType.getKey(p_8873_.getType())); + return false; + } else { +- return this.entityManager.addNewEntity(p_8873_); ++ if (this.entityManager.addNewEntity(p_8873_)) { ++ p_8873_.onAddedToWorld(); ++ return true; ++ } else { ++ return false; ++ } + } + } + +@@ -943,6 +_,12 @@ + float p_263390_, + long p_263403_ + ) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtPosition(this, p_263393_, p_263369_, p_263354_, p_263412_, p_263338_, p_263352_, p_263390_); ++ if (event.isCanceled() || event.getSound() == null) return; ++ p_263412_ = event.getSound(); ++ p_263338_ = event.getSource(); ++ p_263352_ = event.getNewVolume(); ++ p_263390_ = event.getNewPitch(); + this.server + .getPlayerList() + .broadcast( +@@ -960,6 +_,12 @@ + public void playSeededSound( + @Nullable Player p_263545_, Entity p_263544_, Holder p_263491_, SoundSource p_263542_, float p_263530_, float p_263520_, long p_263490_ + ) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlaySoundAtEntity(p_263544_, p_263491_, p_263542_, p_263530_, p_263520_); ++ if (event.isCanceled() || event.getSound() == null) return; ++ p_263491_ = event.getSound(); ++ p_263542_ = event.getSource(); ++ p_263530_ = event.getNewVolume(); ++ p_263520_ = event.getNewPitch(); + this.server + .getPlayerList() + .broadcast( +@@ -1003,6 +_,7 @@ + + @Override + public void gameEvent(Holder p_334475_, Vec3 p_215042_, GameEvent.Context p_215043_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onVanillaGameEvent(this, p_334475_, p_215042_, p_215043_)) return; + this.gameEventDispatcher.post(p_334475_, p_215042_, p_215043_); + } + +@@ -1041,11 +_,17 @@ + + @Override + public void updateNeighborsAt(BlockPos p_215045_, Block p_215046_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_215045_, this.getBlockState(p_215045_), java.util.EnumSet.allOf(Direction.class), false).isCanceled()) return; + this.neighborUpdater.updateNeighborsAtExceptFromFacing(p_215045_, p_215046_, null); + } + + @Override + public void updateNeighborsAtExceptFromFacing(BlockPos p_215052_, Block p_215053_, Direction p_215054_) { ++ java.util.EnumSet directions = java.util.EnumSet.allOf(Direction.class); ++ directions.remove(p_215054_); ++ if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_215052_, this.getBlockState(p_215052_), directions, false).isCanceled()) { ++ return; ++ } + this.neighborUpdater.updateNeighborsAtExceptFromFacing(p_215052_, p_215053_, p_215054_); + } + +@@ -1672,6 +_,11 @@ + return crashreportcategory; + } + ++ @Override ++ public java.util.Collection> getPartEntities() { ++ return this.dragonParts.values(); ++ } ++ + final class EntityCallbacks implements LevelCallback { + public void onCreated(Entity p_143355_) { + } +@@ -1706,8 +_,8 @@ + ServerLevel.this.navigatingMobs.add(mob); } - } - p_143375_.updateDynamicGameEventListener(DynamicGameEventListener::remove); -+ -+ p_143375_.onRemovedFromWorld(); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityLeaveLevelEvent(p_143375_, ServerLevel.this)); - } +- if (p_143371_ instanceof EnderDragon enderdragon) { +- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { ++ if (p_143371_.isMultipartEntity()) { ++ for (var enderdragonpart : p_143371_.getParts()) { + ServerLevel.this.dragonParts.put(enderdragonpart.getId(), enderdragonpart); + } + } +@@ -1733,13 +_,16 @@ + ServerLevel.this.navigatingMobs.remove(mob); + } - public void onSectionChange(Entity p_215086_) { - p_215086_.updateDynamicGameEventListener(DynamicGameEventListener::move); - } -+ } +- if (p_143375_ instanceof EnderDragon enderdragon) { +- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { ++ if (p_143375_.isMultipartEntity()) { ++ for (var enderdragonpart : p_143375_.getParts()) { + ServerLevel.this.dragonParts.remove(enderdragonpart.getId()); + } + } + + p_143375_.updateDynamicGameEventListener(DynamicGameEventListener::remove); + -+ @Override -+ public java.util.Collection> getPartEntities() { -+ return this.dragonParts.values(); - } - } ++ p_143375_.onRemovedFromWorld(); ++ net.minecraftforge.event.ForgeEventFactory.onEntityLeaveLevel(p_143375_, ServerLevel.this); + } + + public void onSectionChange(Entity p_215086_) { diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch index 29814f76e0..61e421bdae 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch @@ -1,308 +1,300 @@ --- a/net/minecraft/server/level/ServerPlayer.java +++ b/net/minecraft/server/level/ServerPlayer.java -@@ -153,7 +_,7 @@ +@@ -161,7 +_,8 @@ import net.minecraft.world.scores.criteria.ObjectiveCriteria; import org.slf4j.Logger; -public class ServerPlayer extends Player { +public class ServerPlayer extends Player implements net.minecraftforge.common.extensions.IForgeServerPlayer { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_XZ = 32; - private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_Y = 10; -@@ -576,6 +_,7 @@ ++ public static final String PERSISTED_NBT_TAG = "PlayerPersisted"; + private static final Logger LOGGER = LogUtils.getLogger(); + private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_XZ = 32; + private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_Y = 10; +@@ -646,6 +_,7 @@ - public void die(DamageSource p_9035_) { - this.gameEvent(GameEvent.ENTITY_DIE); -+ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_9035_)) return; - boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES); - if (flag) { - Component component = this.getCombatTracker().getDeathMessage(); -@@ -720,11 +_,12 @@ - } + @Override + public void die(DamageSource p_9035_) { ++ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_9035_)) return; + this.gameEvent(GameEvent.ENTITY_DIE); + boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES); + if (flag) { +@@ -788,11 +_,12 @@ - @Nullable -- public Entity changeDimension(ServerLevel p_9180_) { -+ public Entity changeDimension(ServerLevel p_9180_, net.minecraftforge.common.util.ITeleporter teleporter) { -+ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_9180_.dimension())) return null; - this.isChangingDimension = true; - ServerLevel serverlevel = this.serverLevel(); - ResourceKey resourcekey = serverlevel.dimension(); -- if (resourcekey == Level.END && p_9180_.dimension() == Level.OVERWORLD) { -+ if (resourcekey == Level.END && p_9180_.dimension() == Level.OVERWORLD && teleporter.isVanilla()) { //Forge: Fix non-vanilla teleporters triggering end credits - this.unRide(); - this.serverLevel().removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); - if (!this.wonGame) { -@@ -741,13 +_,14 @@ - PlayerList playerlist = this.server.getPlayerList(); - playerlist.sendPlayerPermissionLevel(this); - serverlevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); -- this.unsetRemoved(); -- PortalInfo portalinfo = this.findDimensionEntryPoint(p_9180_); -+ this.revive(); -+ PortalInfo portalinfo = teleporter.getPortalInfo(this, p_9180_, this::findDimensionEntryPoint); - if (portalinfo != null) { -+ Entity e = teleporter.placeEntity(this, serverlevel, p_9180_, this.getYRot(), spawnPortal -> {//Forge: Start vanilla logic - serverlevel.getProfiler().push("moving"); - if (resourcekey == Level.OVERWORLD && p_9180_.dimension() == Level.NETHER) { - this.enteredNetherPosition = this.position(); -- } else if (p_9180_.dimension() == Level.END) { -+ } else if (spawnPortal && p_9180_.dimension() == Level.END) { - this.createEndPlatform(p_9180_, BlockPos.containing(portalinfo.pos)); + @Nullable + @Override +- public Entity changeDimension(ServerLevel p_9180_) { ++ public Entity changeDimension(ServerLevel p_9180_, net.minecraftforge.common.util.ITeleporter teleporter) { ++ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_9180_.dimension())) return null; + this.isChangingDimension = true; + ServerLevel serverlevel = this.serverLevel(); + ResourceKey resourcekey = serverlevel.dimension(); +- if (resourcekey == Level.END && p_9180_.dimension() == Level.OVERWORLD) { ++ if (resourcekey == Level.END && p_9180_.dimension() == Level.OVERWORLD && teleporter.isVanilla()) { //Forge: Fix non-vanilla teleporters triggering end credits + this.unRide(); + this.serverLevel().removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); + if (!this.wonGame) { +@@ -809,13 +_,14 @@ + PlayerList playerlist = this.server.getPlayerList(); + playerlist.sendPlayerPermissionLevel(this); + serverlevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); +- this.unsetRemoved(); +- PortalInfo portalinfo = this.findDimensionEntryPoint(p_9180_); ++ this.revive(); ++ PortalInfo portalinfo = teleporter.getPortalInfo(this, p_9180_, this::findDimensionEntryPoint); + if (portalinfo != null) { ++ Entity e = teleporter.placeEntity(this, serverlevel, p_9180_, this.getYRot(), spawnPortal -> {//Forge: Start vanilla logic + serverlevel.getProfiler().push("moving"); + if (resourcekey == Level.OVERWORLD && p_9180_.dimension() == Level.NETHER) { + this.enteredNetherPosition = this.position(); +- } else if (p_9180_.dimension() == Level.END) { ++ } else if (spawnPortal && p_9180_.dimension() == Level.END) { + this.createEndPlatform(p_9180_, BlockPos.containing(portalinfo.pos)); + } + +@@ -828,6 +_,9 @@ + p_9180_.addDuringPortalTeleport(this); + serverlevel.getProfiler().pop(); + this.triggerDimensionChangeTriggers(serverlevel); ++ return this;//forge: this is part of the ITeleporter patch ++ });//Forge: End vanilla logic ++ if (e != this) throw new java.lang.IllegalArgumentException(String.format(java.util.Locale.ENGLISH, "Teleporter %s returned not the player entity but instead %s, expected PlayerEntity %s", teleporter, e, this)); + this.connection.send(new ClientboundPlayerAbilitiesPacket(this.getAbilities())); + playerlist.sendLevelInfo(this, p_9180_); + playerlist.sendAllPlayerInfo(this); +@@ -836,10 +_,12 @@ + this.connection.send(new ClientboundUpdateMobEffectPacket(this.getId(), mobeffectinstance, false)); + } + ++ if (teleporter.playTeleportSound(this, serverlevel, p_9180_)) + this.connection.send(new ClientboundLevelEventPacket(1032, BlockPos.ZERO, 0, false)); + this.lastSentExp = -1; + this.lastSentHealth = -1.0F; + this.lastSentFood = -1; ++ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, resourcekey, p_9180_.dimension()); } -@@ -759,6 +_,9 @@ - p_9180_.addDuringPortalTeleport(this); - serverlevel.getProfiler().pop(); - this.triggerDimensionChangeTriggers(serverlevel); -+ return this;//forge: this is part of the ITeleporter patch -+ });//Forge: End vanilla logic -+ if (e != this) throw new java.lang.IllegalArgumentException(String.format(java.util.Locale.ENGLISH, "Teleporter %s returned not the player entity but instead %s, expected PlayerEntity %s", teleporter, e, this)); - this.connection.send(new ClientboundPlayerAbilitiesPacket(this.getAbilities())); - playerlist.sendLevelInfo(this, p_9180_); - playerlist.sendAllPlayerInfo(this); -@@ -767,10 +_,12 @@ - this.connection.send(new ClientboundUpdateMobEffectPacket(this.getId(), mobeffectinstance)); - } + return this; +@@ -905,6 +_,9 @@ -+ if (teleporter.playTeleportSound(this, serverlevel, p_9180_)) - this.connection.send(new ClientboundLevelEventPacket(1032, BlockPos.ZERO, 0, false)); - this.lastSentExp = -1; - this.lastSentHealth = -1.0F; - this.lastSentFood = -1; -+ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, resourcekey, p_9180_.dimension()); - } - - return this; -@@ -834,6 +_,9 @@ - } - - public Either startSleepInBed(BlockPos p_9115_) { -+ var optAt = java.util.Optional.of(p_9115_); -+ var ret = net.minecraftforge.event.ForgeEventFactory.onPlayerSleepInBed(this, optAt); -+ if (ret != null) return Either.left(ret); - Direction direction = this.level().getBlockState(p_9115_).getValue(HorizontalDirectionalBlock.FACING); - if (!this.isSleeping() && this.isAlive()) { - if (!this.level().dimensionType().natural()) { -@@ -844,7 +_,7 @@ + @Override + public Either startSleepInBed(BlockPos p_9115_) { ++ var optAt = java.util.Optional.of(p_9115_); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onPlayerSleepInBed(this, optAt); ++ if (ret != null) return Either.left(ret); + Direction direction = this.level().getBlockState(p_9115_).getValue(HorizontalDirectionalBlock.FACING); + if (this.isSleeping() || !this.isAlive()) { + return Either.left(Player.BedSleepingProblem.OTHER_PROBLEM); +@@ -916,7 +_,7 @@ return Either.left(Player.BedSleepingProblem.OBSTRUCTED); - } else { + } else { this.setRespawnPosition(this.level().dimension(), p_9115_, this.getYRot(), false, true); - if (this.level().isDay()) { + if (!net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, optAt)) { - return Either.left(Player.BedSleepingProblem.NOT_POSSIBLE_NOW); + return Either.left(Player.BedSleepingProblem.NOT_POSSIBLE_NOW); } else { - if (!this.isCreative()) { -@@ -882,6 +_,7 @@ - } + if (!this.isCreative()) { +@@ -962,6 +_,7 @@ + } - private boolean bedInRange(BlockPos p_9117_, Direction p_9118_) { -+ if (p_9118_ == null) return false; - return this.isReachableBedBlock(p_9117_) || this.isReachableBedBlock(p_9117_.relative(p_9118_.getOpposite())); - } + private boolean bedInRange(BlockPos p_9117_, Direction p_9118_) { ++ if (p_9118_ == null) return false; + return this.isReachableBedBlock(p_9117_) || this.isReachableBedBlock(p_9117_.relative(p_9118_.getOpposite())); + } -@@ -970,6 +_,7 @@ - this.connection.send(new ClientboundOpenScreenPacket(abstractcontainermenu.containerId, abstractcontainermenu.getType(), p_9033_.getDisplayName())); - this.initMenu(abstractcontainermenu); - this.containerMenu = abstractcontainermenu; -+ net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); - return OptionalInt.of(this.containerCounter); - } - } -@@ -988,6 +_,7 @@ - this.connection.send(new ClientboundHorseScreenOpenPacket(this.containerCounter, p_9060_.getContainerSize(), p_9059_.getId())); - this.containerMenu = new HorseInventoryMenu(this.containerCounter, this.getInventory(), p_9060_, p_9059_); - this.initMenu(this.containerMenu); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); - } +@@ -1076,6 +_,7 @@ + this.connection.send(new ClientboundOpenScreenPacket(abstractcontainermenu.containerId, abstractcontainermenu.getType(), p_9033_.getDisplayName())); + this.initMenu(abstractcontainermenu); + this.containerMenu = abstractcontainermenu; ++ net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); + return OptionalInt.of(this.containerCounter); + } + } +@@ -1124,6 +_,7 @@ + public void doCloseContainer() { + this.containerMenu.removed(this); + this.inventoryMenu.transferState(this.containerMenu); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerCloseContainer(this, this.containerMenu); + this.containerMenu = this.inventoryMenu; + } - public void openItemGui(ItemStack p_9082_, InteractionHand p_9083_) { -@@ -1013,6 +_,7 @@ - public void doCloseContainer() { - this.containerMenu.removed(this); - this.inventoryMenu.transferState(this.containerMenu); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerCloseContainer(this, this.containerMenu); - this.containerMenu = this.inventoryMenu; - } - -@@ -1233,6 +_,15 @@ - this.setShoulderEntityLeft(p_9016_.getShoulderEntityLeft()); - this.setShoulderEntityRight(p_9016_.getShoulderEntityRight()); - this.setLastDeathLocation(p_9016_.getLastDeathLocation()); +@@ -1349,6 +_,15 @@ + this.setShoulderEntityLeft(p_9016_.getShoulderEntityLeft()); + this.setShoulderEntityRight(p_9016_.getShoulderEntityRight()); + this.setLastDeathLocation(p_9016_.getLastDeathLocation()); + -+ //Copy over a section of the Entity Data from the old player. -+ //Allows mods to specify data that persists after players respawn. -+ CompoundTag old = p_9016_.getPersistentData(); -+ if (old.contains(PERSISTED_NBT_TAG)) -+ getPersistentData().put(PERSISTED_NBT_TAG, old.get(PERSISTED_NBT_TAG)); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerClone(this, p_9016_, !p_9017_); -+ this.tabListHeader = p_9016_.tabListHeader; -+ this.tabListFooter = p_9016_.tabListFooter; - } ++ //Copy over a section of the Entity Data from the old player. ++ //Allows mods to specify data that persists after players respawn. ++ CompoundTag old = p_9016_.getPersistentData(); ++ if (old.contains(PERSISTED_NBT_TAG)) ++ getPersistentData().put(PERSISTED_NBT_TAG, old.get(PERSISTED_NBT_TAG)); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerClone(this, p_9016_, !p_9017_); ++ this.tabListHeader = p_9016_.tabListHeader; ++ this.tabListFooter = p_9016_.tabListFooter; + } - protected void onEffectAdded(MobEffectInstance p_143393_, @Nullable Entity p_143394_) { -@@ -1313,6 +_,7 @@ - } + @Override +@@ -1449,6 +_,7 @@ + } - public boolean setGameMode(GameType p_143404_) { -+ p_143404_ = net.minecraftforge.common.ForgeHooks.onChangeGameType(this, this.gameMode.getGameModeForPlayer(), p_143404_); - if (!this.gameMode.changeGameModeForPlayer(p_143404_)) { - return false; - } else { -@@ -1447,6 +_,8 @@ - public void setCamera(@Nullable Entity p_9214_) { - Entity entity = this.getCamera(); - this.camera = (Entity)(p_9214_ == null ? this : p_9214_); -+ while (this.camera instanceof net.minecraftforge.entity.PartEntity partEntity) -+ this.camera = partEntity.getParent(); // FORGE: fix MC-46486 - if (entity != this.camera) { - Level level = this.camera.level(); - if (level instanceof ServerLevel) { -@@ -1486,7 +_,11 @@ + public boolean setGameMode(GameType p_143404_) { ++ p_143404_ = net.minecraftforge.common.ForgeHooks.onChangeGameType(this, this.gameMode.getGameModeForPlayer(), p_143404_); + if (!this.gameMode.changeGameModeForPlayer(p_143404_)) { + return false; + } else { +@@ -1591,6 +_,9 @@ + public void setCamera(@Nullable Entity p_9214_) { + Entity entity = this.getCamera(); + this.camera = (Entity)(p_9214_ == null ? this : p_9214_); ++ while (this.camera instanceof net.minecraftforge.entity.PartEntity partEntity) { ++ this.camera = partEntity.getParent(); // FORGE: fix MC-46486 ++ } + if (entity != this.camera) { + if (this.camera.level() instanceof ServerLevel serverlevel) { + this.teleportTo( +@@ -1629,7 +_,11 @@ - @Nullable - public Component getTabListDisplayName() { -- return null; -+ if (!this.hasTabListName) { -+ this.tabListDisplayName = net.minecraftforge.event.ForgeEventFactory.getPlayerTabListDisplayName(this); -+ this.hasTabListName = true; -+ } -+ return this.tabListDisplayName; - } + @Nullable + public Component getTabListDisplayName() { +- return null; ++ if (!this.hasTabListName) { ++ this.tabListDisplayName = net.minecraftforge.event.ForgeEventFactory.getPlayerTabListDisplayName(this); ++ this.hasTabListName = true; ++ } ++ return this.tabListDisplayName; + } - public void swing(InteractionHand p_9031_) { -@@ -1512,20 +_,23 @@ - if (p_9000_ == this.level()) { - this.connection.teleport(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); - } else { -+ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_9000_.dimension())) return; - ServerLevel serverlevel = this.serverLevel(); - LevelData leveldata = p_9000_.getLevelData(); - this.connection.send(new ClientboundRespawnPacket(this.createCommonSpawnInfo(p_9000_), (byte)3)); - this.connection.send(new ClientboundChangeDifficultyPacket(leveldata.getDifficulty(), leveldata.isDifficultyLocked())); - this.server.getPlayerList().sendPlayerPermissionLevel(this); - serverlevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); -- this.unsetRemoved(); -+ this.revive(); - this.moveTo(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); - this.setServerLevel(p_9000_); - p_9000_.addDuringCommandTeleport(this); - this.triggerDimensionChangeTriggers(serverlevel); - this.connection.teleport(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); -+ this.gameMode.setLevel(p_9000_); - this.server.getPlayerList().sendLevelInfo(this, p_9000_); - this.server.getPlayerList().sendAllPlayerInfo(this); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, serverlevel.dimension(), p_9000_.dimension()); - } + @Override +@@ -1656,20 +_,23 @@ + if (p_9000_ == this.level()) { + this.connection.teleport(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); + } else { ++ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_9000_.dimension())) return; + ServerLevel serverlevel = this.serverLevel(); + LevelData leveldata = p_9000_.getLevelData(); + this.connection.send(new ClientboundRespawnPacket(this.createCommonSpawnInfo(p_9000_), (byte)3)); + this.connection.send(new ClientboundChangeDifficultyPacket(leveldata.getDifficulty(), leveldata.isDifficultyLocked())); + this.server.getPlayerList().sendPlayerPermissionLevel(this); + serverlevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); +- this.unsetRemoved(); ++ this.revive(); + this.moveTo(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); + this.setServerLevel(p_9000_); + p_9000_.addDuringCommandTeleport(this); + this.triggerDimensionChangeTriggers(serverlevel); + this.connection.teleport(p_9001_, p_9002_, p_9003_, p_9004_, p_9005_); ++ this.gameMode.setLevel(p_9000_); + this.server.getPlayerList().sendLevelInfo(this, p_9000_); + this.server.getPlayerList().sendAllPlayerInfo(this); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, serverlevel.dimension(), p_9000_.dimension()); + } + } - } -@@ -1548,6 +_,8 @@ - } +@@ -1691,6 +_,9 @@ + } - public void setRespawnPosition(ResourceKey p_9159_, @Nullable BlockPos p_9160_, float p_9161_, boolean p_9162_, boolean p_9163_) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnSet(this, p_9160_ == null ? Level.OVERWORLD : p_9159_, p_9160_, p_9162_)) -+ return; - if (p_9160_ != null) { - boolean flag = p_9160_.equals(this.respawnPosition) && p_9159_.equals(this.respawnDimension); - if (p_9163_ && !flag) { -@@ -1592,6 +_,9 @@ - if (itementity == null) { - return null; - } else { -+ if (captureDrops() != null) -+ captureDrops().add(itementity); -+ else - this.level().addFreshEntity(itementity); - ItemStack itemstack = itementity.getItem(); - if (p_9087_) { -@@ -1606,6 +_,75 @@ - } - } + public void setRespawnPosition(ResourceKey p_9159_, @Nullable BlockPos p_9160_, float p_9161_, boolean p_9162_, boolean p_9163_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnSet(this, p_9160_ == null ? Level.OVERWORLD : p_9159_, p_9160_, p_9162_)) { ++ return; ++ } + if (p_9160_ != null) { + boolean flag = p_9160_.equals(this.respawnPosition) && p_9159_.equals(this.respawnDimension); + if (p_9163_ && !flag) { +@@ -1748,6 +_,9 @@ + if (itementity == null) { + return null; + } else { ++ if (captureDrops() != null) ++ captureDrops().add(itementity); ++ else + this.level().addFreshEntity(itementity); + ItemStack itemstack = itementity.getItem(); + if (p_9087_) { +@@ -1819,9 +_,12 @@ -+ /** -+ * Returns the language last reported by the player as their local language. -+ * Defaults to en_us if the value is unknown. -+ */ -+ public String getLanguage() { -+ return this.language; -+ } -+ -+ private Component tabListHeader = Component.empty(); -+ private Component tabListFooter = Component.empty(); -+ -+ public Component getTabListHeader() { -+ return this.tabListHeader; -+ } -+ -+ /** -+ * Set the tab list header while preserving the footer. -+ * -+ * @param header the new header, or {@link Component#empty()} to clear -+ */ -+ public void setTabListHeader(final Component header) { -+ this.setTabListHeaderFooter(header, this.tabListFooter); -+ } -+ -+ public Component getTabListFooter() { -+ return this.tabListFooter; -+ } -+ -+ /** -+ * Set the tab list footer while preserving the header. -+ * -+ * @param footer the new footer, or {@link Component#empty()} to clear -+ */ -+ public void setTabListFooter(final Component footer) { -+ this.setTabListHeaderFooter(this.tabListHeader, footer); -+ } -+ -+ /** -+ * Set the tab list header and footer at once. -+ * -+ * @param header the new header, or {@link Component#empty()} to clear -+ * @param footer the new footer, or {@link Component#empty()} to clear -+ */ -+ public void setTabListHeaderFooter(final Component header, final Component footer) { -+ if (java.util.Objects.equals(header, this.tabListHeader) -+ && java.util.Objects.equals(footer, this.tabListFooter)) { -+ return; -+ } -+ -+ this.tabListHeader = java.util.Objects.requireNonNull(header, "header"); -+ this.tabListFooter = java.util.Objects.requireNonNull(footer, "footer"); -+ -+ this.connection.send(new net.minecraft.network.protocol.game.ClientboundTabListPacket(header, footer)); -+ } -+ -+ // We need this as tablistDisplayname may be null even if the event was fired. -+ private boolean hasTabListName = false; -+ private Component tabListDisplayName = null; -+ /** -+ * Force the name displayed in the tab list to refresh, by firing {@link net.minecraftforge.event.entity.player.PlayerEvent.TabListNameFormat}. -+ */ -+ public void refreshTabListName() { -+ Component oldName = this.tabListDisplayName; -+ this.tabListDisplayName = net.minecraftforge.event.ForgeEventFactory.getPlayerTabListDisplayName(this); -+ if (!java.util.Objects.equals(oldName, this.tabListDisplayName)) { -+ this.getServer().getPlayerList().broadcastAll(new net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket(net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, this)); -+ } -+ } -+ - public TextFilter getTextFilter() { - return this.textFilter; - } -@@ -1665,11 +_,14 @@ + public boolean drop(boolean p_182295_) { + Inventory inventory = this.getInventory(); ++ ItemStack selected = inventory.getSelected(); ++ if (selected.isEmpty() || !selected.onDroppedByPlayer(this)) return false; ++ if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (p_182295_ || selected.getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the serverside + ItemStack itemstack = inventory.removeFromSelected(p_182295_); + this.containerMenu.findSlot(inventory, inventory.selected).ifPresent(p_287377_ -> this.containerMenu.setRemoteSlot(p_287377_, inventory.getSelected())); +- return this.drop(itemstack, false, true) != null; ++ return net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, itemstack, true) != null; + } - public boolean drop(boolean p_182295_) { - Inventory inventory = this.getInventory(); -+ ItemStack selected = inventory.getSelected(); -+ if (selected.isEmpty() || !selected.onDroppedByPlayer(this)) return false; -+ if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (p_182295_ || selected.getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the serverside - ItemStack itemstack = inventory.removeFromSelected(p_182295_); - this.containerMenu.findSlot(inventory, inventory.selected).ifPresent((p_287377_) -> { - this.containerMenu.setRemoteSlot(p_287377_, inventory.getSelected()); - }); -- return this.drop(itemstack, false, true) != null; -+ return net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, itemstack, true) != null; - } - - public boolean allowsListing() { + public boolean allowsListing() { +@@ -1914,5 +_,74 @@ + @Nullable + public BlockPos getRaidOmenPosition() { + return this.raidOmenPosition; ++ } ++ ++ /** ++ * Returns the language last reported by the player as their local language. ++ * Defaults to en_us if the value is unknown. ++ */ ++ public String getLanguage() { ++ return this.language; ++ } ++ ++ private Component tabListHeader = Component.empty(); ++ private Component tabListFooter = Component.empty(); ++ ++ public Component getTabListHeader() { ++ return this.tabListHeader; ++ } ++ ++ /** ++ * Set the tab list header while preserving the footer. ++ * ++ * @param header the new header, or {@link Component#empty()} to clear ++ */ ++ public void setTabListHeader(final Component header) { ++ this.setTabListHeaderFooter(header, this.tabListFooter); ++ } ++ ++ public Component getTabListFooter() { ++ return this.tabListFooter; ++ } ++ ++ /** ++ * Set the tab list footer while preserving the header. ++ * ++ * @param footer the new footer, or {@link Component#empty()} to clear ++ */ ++ public void setTabListFooter(final Component footer) { ++ this.setTabListHeaderFooter(this.tabListHeader, footer); ++ } ++ ++ /** ++ * Set the tab list header and footer at once. ++ * ++ * @param header the new header, or {@link Component#empty()} to clear ++ * @param footer the new footer, or {@link Component#empty()} to clear ++ */ ++ public void setTabListHeaderFooter(final Component header, final Component footer) { ++ if (java.util.Objects.equals(header, this.tabListHeader) ++ && java.util.Objects.equals(footer, this.tabListFooter)) { ++ return; ++ } ++ ++ this.tabListHeader = java.util.Objects.requireNonNull(header, "header"); ++ this.tabListFooter = java.util.Objects.requireNonNull(footer, "footer"); ++ ++ this.connection.send(new net.minecraft.network.protocol.game.ClientboundTabListPacket(header, footer)); ++ } ++ ++ // We need this as tablistDisplayname may be null even if the event was fired. ++ private boolean hasTabListName = false; ++ private Component tabListDisplayName = null; ++ /** ++ * Force the name displayed in the tab list to refresh, by firing {@link net.minecraftforge.event.entity.player.PlayerEvent.TabListNameFormat}. ++ */ ++ public void refreshTabListName() { ++ Component oldName = this.tabListDisplayName; ++ this.tabListDisplayName = net.minecraftforge.event.ForgeEventFactory.getPlayerTabListDisplayName(this); ++ if (!java.util.Objects.equals(oldName, this.tabListDisplayName)) { ++ this.getServer().getPlayerList().broadcastAll(new net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket(net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, this)); ++ } + } + } diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch index 98ffdba459..4f7ee278e5 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch @@ -1,134 +1,136 @@ --- a/net/minecraft/server/level/ServerPlayerGameMode.java +++ b/net/minecraft/server/level/ServerPlayerGameMode.java -@@ -124,7 +_,11 @@ - } +@@ -129,6 +_,10 @@ + } - public void handleBlockBreakAction(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) { -- if (this.player.getEyePosition().distanceToSqr(Vec3.atCenterOf(p_215120_)) > ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE) { -+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(player, p_215120_, p_215122_, p_215121_); -+ if (event.isCanceled() || (!this.isCreative() && event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY)) { -+ return; -+ } -+ if (!this.player.canReach(p_215120_, 1.5)) { // Vanilla check is eye-to-center distance < 6, so padding is 6 - 4.5 = 1.5 - this.debugLogging(p_215120_, false, p_215124_, "too far"); - } else if (p_215120_.getY() >= p_215123_) { - this.player.connection.send(new ClientboundBlockUpdatePacket(p_215120_, this.level.getBlockState(p_215120_))); -@@ -152,6 +_,7 @@ - float f = 1.0F; - BlockState blockstate = this.level.getBlockState(p_215120_); - if (!blockstate.isAir()) { -+ if (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY) - blockstate.attack(this.level, p_215120_, this.player); - f = blockstate.getDestroyProgress(this.player, this.player.level(), p_215120_); - } -@@ -221,7 +_,8 @@ + public void handleBlockBreakAction(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(player, p_215120_, p_215122_, p_215121_); ++ if (event.isCanceled() || (!this.isCreative() && event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY)) { ++ return; ++ } + if (!this.player.canInteractWithBlock(p_215120_, 1.0)) { + this.debugLogging(p_215120_, false, p_215124_, "too far"); + } else if (p_215120_.getY() >= p_215123_) { +@@ -157,6 +_,7 @@ + float f = 1.0F; + BlockState blockstate = this.level.getBlockState(p_215120_); + if (!blockstate.isAir()) { ++ if (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY) + blockstate.attack(this.level, p_215120_, this.player); + f = blockstate.getDestroyProgress(this.player, this.player.level(), p_215120_); + } +@@ -224,7 +_,8 @@ - public boolean destroyBlock(BlockPos p_9281_) { - BlockState blockstate1 = this.level.getBlockState(p_9281_); -- if (!this.player.getMainHandItem().getItem().canAttackBlock(blockstate1, this.level, p_9281_, this.player)) { -+ int exp = net.minecraftforge.common.ForgeHooks.onBlockBreakEvent(level, gameModeForPlayer, player, p_9281_); -+ if (exp == -1) { - return false; - } else { - BlockEntity blockentity = this.level.getBlockEntity(p_9281_); -@@ -229,30 +_,43 @@ - if (block instanceof GameMasterBlock && !this.player.canUseGameMasterBlocks()) { - this.level.sendBlockUpdated(p_9281_, blockstate1, blockstate1, 3); + public boolean destroyBlock(BlockPos p_9281_) { + BlockState blockstate1 = this.level.getBlockState(p_9281_); +- if (!this.player.getMainHandItem().getItem().canAttackBlock(blockstate1, this.level, p_9281_, this.player)) { ++ int exp = net.minecraftforge.common.ForgeHooks.onBlockBreakEvent(level, gameModeForPlayer, player, p_9281_); ++ if (exp == -1) { return false; -+ } else if (player.getMainHandItem().onBlockStartBreak(p_9281_, player)) { -+ return false; - } else if (this.player.blockActionRestricted(this.level, p_9281_, this.gameModeForPlayer)) { - return false; - } else { -- BlockState blockstate = block.playerWillDestroy(this.level, p_9281_, blockstate1, this.player); -- boolean flag1 = this.level.removeBlock(p_9281_, false); -- if (flag1) { -- block.destroy(this.level, p_9281_, blockstate); -- } -- -+ BlockState blockstate = blockstate1; - if (this.isCreative()) { -+ removeBlock(p_9281_, false); - return true; + } else { + BlockEntity blockentity = this.level.getBlockEntity(p_9281_); +@@ -232,30 +_,47 @@ + if (block instanceof GameMasterBlock && !this.player.canUseGameMasterBlocks()) { + this.level.sendBlockUpdated(p_9281_, blockstate1, blockstate1, 3); + return false; ++ } else if (player.getMainHandItem().onBlockStartBreak(p_9281_, player)) { ++ return false; + } else if (this.player.blockActionRestricted(this.level, p_9281_, this.gameModeForPlayer)) { + return false; } else { - ItemStack itemstack = this.player.getMainHandItem(); - ItemStack itemstack1 = itemstack.copy(); -- boolean flag = this.player.hasCorrectToolForDrops(blockstate); -+ boolean flag = blockstate.canHarvestBlock(this.level, p_9281_, this.player); // previously player.hasCorrectToolForDrops(blockstate) - itemstack.mineBlock(this.level, blockstate, p_9281_, this.player); -+ if (itemstack.isEmpty() && !itemstack1.isEmpty()) -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, itemstack1, InteractionHand.MAIN_HAND); -+ boolean flag1 = removeBlock(p_9281_, flag); +- BlockState blockstate = block.playerWillDestroy(this.level, p_9281_, blockstate1, this.player); +- boolean flag1 = this.level.removeBlock(p_9281_, false); +- if (flag1) { +- block.destroy(this.level, p_9281_, blockstate); +- } +- ++ BlockState blockstate = blockstate1; + if (this.isCreative()) { ++ removeBlock(p_9281_, false); + return true; + } else { + ItemStack itemstack = this.player.getMainHandItem(); + ItemStack itemstack1 = itemstack.copy(); +- boolean flag = this.player.hasCorrectToolForDrops(blockstate); ++ boolean flag = blockstate.canHarvestBlock(this.level, p_9281_, this.player); // previously player.hasCorrectToolForDrops(blockstate) + itemstack.mineBlock(this.level, blockstate, p_9281_, this.player); + - if (flag1 && flag) { - block.playerDestroy(this.level, this.player, p_9281_, blockstate, blockentity, itemstack1); - } ++ if (itemstack.isEmpty() && !itemstack1.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, itemstack1, InteractionHand.MAIN_HAND); ++ } ++ boolean flag1 = removeBlock(p_9281_, flag); ++ + if (flag1 && flag) { + block.playerDestroy(this.level, this.player, p_9281_, blockstate, blockentity, itemstack1); + } -+ if (flag && exp > 0) -+ blockstate1.getBlock().popExperience(level, p_9281_, exp); ++ if (flag && exp > 0) { ++ blockstate1.getBlock().popExperience(level, p_9281_, exp); ++ } + - return true; + return true; + } } - } - } -+ } + } ++ } + -+ private boolean removeBlock(BlockPos p_180235_1_, boolean canHarvest) { -+ BlockState state = this.level.getBlockState(p_180235_1_); -+ boolean removed = state.onDestroyedByPlayer(this.level, p_180235_1_, this.player, canHarvest, this.level.getFluidState(p_180235_1_)); -+ if (removed) -+ state.getBlock().destroy(this.level, p_180235_1_, state); -+ return removed; - } ++ private boolean removeBlock(BlockPos p_180235_1_, boolean canHarvest) { ++ BlockState state = this.level.getBlockState(p_180235_1_); ++ boolean removed = state.onDestroyedByPlayer(this.level, p_180235_1_, this.player, canHarvest, this.level.getFluidState(p_180235_1_)); ++ if (removed) { ++ state.getBlock().destroy(this.level, p_180235_1_, state); ++ } ++ return removed; + } - public InteractionResult useItem(ServerPlayer p_9262_, Level p_9263_, ItemStack p_9264_, InteractionHand p_9265_) { -@@ -261,6 +_,8 @@ - } else if (p_9262_.getCooldowns().isOnCooldown(p_9264_.getItem())) { - return InteractionResult.PASS; - } else { -+ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(p_9262_, p_9265_); -+ if (cancelResult != null) return cancelResult; - int i = p_9264_.getCount(); - int j = p_9264_.getDamageValue(); - InteractionResultHolder interactionresultholder = p_9264_.use(p_9263_, p_9262_, p_9265_); -@@ -299,7 +_,10 @@ - BlockState blockstate = p_9267_.getBlockState(blockpos); - if (!blockstate.getBlock().isEnabled(p_9267_.enabledFeatures())) { - return InteractionResult.FAIL; -- } else if (this.gameModeForPlayer == GameType.SPECTATOR) { -+ } -+ net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock event = net.minecraftforge.common.ForgeHooks.onRightClickBlock(p_9266_, p_9269_, blockpos, p_9270_); -+ if (event.isCanceled()) return event.getCancellationResult(); -+ if (this.gameModeForPlayer == GameType.SPECTATOR) { - MenuProvider menuprovider = blockstate.getMenuProvider(p_9267_, blockpos); - if (menuprovider != null) { - p_9266_.openMenu(menuprovider); -@@ -308,10 +_,15 @@ + public InteractionResult useItem(ServerPlayer p_9262_, Level p_9263_, ItemStack p_9264_, InteractionHand p_9265_) { +@@ -264,6 +_,8 @@ + } else if (p_9262_.getCooldowns().isOnCooldown(p_9264_.getItem())) { return InteractionResult.PASS; - } - } else { -+ UseOnContext useoncontext = new UseOnContext(p_9266_, p_9269_, p_9270_); -+ if (event.getUseItem() != net.minecraftforge.eventbus.api.Event.Result.DENY) { -+ InteractionResult result = p_9268_.onItemUseFirst(useoncontext); -+ if (result != InteractionResult.PASS) return result; -+ } - boolean flag = !p_9266_.getMainHandItem().isEmpty() || !p_9266_.getOffhandItem().isEmpty(); -- boolean flag1 = p_9266_.isSecondaryUseActive() && flag; -+ boolean flag1 = (p_9266_.isSecondaryUseActive() && flag) && !(p_9266_.getMainHandItem().doesSneakBypassUse(p_9267_, blockpos, p_9266_) && p_9266_.getOffhandItem().doesSneakBypassUse(p_9267_, blockpos, p_9266_)); - ItemStack itemstack = p_9268_.copy(); -- if (!flag1) { -+ if (event.getUseBlock() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY && !flag1)) { - InteractionResult interactionresult = blockstate.use(p_9267_, p_9266_, p_9269_, p_9270_); - if (interactionresult.consumesAction()) { - CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(p_9266_, blockpos, itemstack); -@@ -319,8 +_,8 @@ + } else { ++ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(p_9262_, p_9265_); ++ if (cancelResult != null) return cancelResult; + int i = p_9264_.getCount(); + int j = p_9264_.getDamageValue(); + InteractionResultHolder interactionresultholder = p_9264_.use(p_9263_, p_9262_, p_9265_); +@@ -296,6 +_,11 @@ + if (!blockstate.getBlock().isEnabled(p_9267_.enabledFeatures())) { + return InteractionResult.FAIL; + } else if (this.gameModeForPlayer == GameType.SPECTATOR) { ++ } ++ ++ var event = net.minecraftforge.event.ForgeEventFactory.onRightClickBlock(p_9266_, p_9269_, blockpos, p_9270_); ++ if (event.isCanceled()) return event.getCancellationResult(); ++ if (this.gameModeForPlayer == GameType.SPECTATOR) { + MenuProvider menuprovider = blockstate.getMenuProvider(p_9267_, blockpos); + if (menuprovider != null) { + p_9266_.openMenu(menuprovider); +@@ -304,10 +_,16 @@ + return InteractionResult.PASS; + } + } else { ++ UseOnContext useoncontext = new UseOnContext(p_9266_, p_9269_, p_9270_); ++ if (event.getUseItem() != net.minecraftforge.eventbus.api.Event.Result.DENY) { ++ InteractionResult result = p_9268_.onItemUseFirst(useoncontext); ++ if (result != InteractionResult.PASS) return result; ++ } + boolean flag = !p_9266_.getMainHandItem().isEmpty() || !p_9266_.getOffhandItem().isEmpty(); + boolean flag1 = p_9266_.isSecondaryUseActive() && flag; ++ flag1 &= !(p_9266_.getMainHandItem().doesSneakBypassUse(p_9267_, blockpos, p_9266_) && p_9266_.getOffhandItem().doesSneakBypassUse(p_9267_, blockpos, p_9266_)); + ItemStack itemstack = p_9268_.copy(); +- if (!flag1) { ++ if (event.getUseBlock() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (event.getUseBlock() != net.minecraftforge.eventbus.api.Event.Result.DENY && !flag1)) { + ItemInteractionResult iteminteractionresult = blockstate.useItemOn(p_9266_.getItemInHand(p_9269_), p_9267_, p_9266_, p_9269_, p_9270_); + if (iteminteractionresult.consumesAction()) { + CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(p_9266_, blockpos, itemstack); +@@ -323,8 +_,8 @@ + } } - } -- if (!p_9268_.isEmpty() && !p_9266_.getCooldowns().isOnCooldown(p_9268_.getItem())) { -- UseOnContext useoncontext = new UseOnContext(p_9266_, p_9269_, p_9270_); -+ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (!p_9268_.isEmpty() && !p_9266_.getCooldowns().isOnCooldown(p_9268_.getItem()))) { -+ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return InteractionResult.PASS; - InteractionResult interactionresult1; - if (this.isCreative()) { - int i = p_9268_.getCount(); +- if (!p_9268_.isEmpty() && !p_9266_.getCooldowns().isOnCooldown(p_9268_.getItem())) { +- UseOnContext useoncontext = new UseOnContext(p_9266_, p_9269_, p_9270_); ++ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (!p_9268_.isEmpty() && !p_9266_.getCooldowns().isOnCooldown(p_9268_.getItem()))) { ++ if (event.getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return InteractionResult.PASS; + InteractionResult interactionresult1; + if (this.isCreative()) { + int i = p_9268_.getCount(); diff --git a/patches/minecraft/net/minecraft/server/level/Ticket.java.patch b/patches/minecraft/net/minecraft/server/level/Ticket.java.patch index 56f19329de..74a78df937 100644 --- a/patches/minecraft/net/minecraft/server/level/Ticket.java.patch +++ b/patches/minecraft/net/minecraft/server/level/Ticket.java.patch @@ -1,50 +1,54 @@ --- a/net/minecraft/server/level/Ticket.java +++ b/net/minecraft/server/level/Ticket.java -@@ -9,9 +_,14 @@ - private long createdTick; +@@ -6,12 +_,18 @@ + private final TicketType type; + private final int ticketLevel; + private final T key; ++ private final boolean forceTicks; + private long createdTick; - protected Ticket(TicketType p_9425_, int p_9426_, T p_9427_) { -+ this(p_9425_, p_9426_, p_9427_, false); -+ } + protected Ticket(TicketType p_9425_, int p_9426_, T p_9427_) { ++ this(p_9425_, p_9426_, p_9427_, false); ++ } + -+ public Ticket(TicketType p_9425_, int p_9426_, T p_9427_, boolean forceTicks) { - this.type = p_9425_; - this.ticketLevel = p_9426_; - this.key = p_9427_; -+ this.forceTicks = forceTicks; - } ++ public Ticket(TicketType p_9425_, int p_9426_, T p_9427_, boolean forceTicks) { + this.type = p_9425_; + this.ticketLevel = p_9426_; + this.key = p_9427_; ++ this.forceTicks = forceTicks; + } - public int compareTo(Ticket p_9432_) { -@@ -31,16 +_,16 @@ - return false; - } else { - Ticket ticket = (Ticket)p_9439_; -- return this.ticketLevel == ticket.ticketLevel && Objects.equals(this.type, ticket.type) && Objects.equals(this.key, ticket.key); -+ return this.ticketLevel == ticket.ticketLevel && Objects.equals(this.type, ticket.type) && Objects.equals(this.key, ticket.key) && this.forceTicks == ticket.forceTicks; - } - } + public int compareTo(Ticket p_9432_) { +@@ -31,18 +_,18 @@ + } else { + return !(p_9439_ instanceof Ticket ticket) + ? false +- : this.ticketLevel == ticket.ticketLevel && Objects.equals(this.type, ticket.type) && Objects.equals(this.key, ticket.key); ++ : this.ticketLevel == ticket.ticketLevel && Objects.equals(this.type, ticket.type) && Objects.equals(this.key, ticket.key) && this.forceTicks == ticket.forceTicks; + } + } - public int hashCode() { -- return Objects.hash(this.type, this.ticketLevel, this.key); -+ return Objects.hash(this.type, this.ticketLevel, this.key, forceTicks); - } + @Override + public int hashCode() { +- return Objects.hash(this.type, this.ticketLevel, this.key); ++ return Objects.hash(this.type, this.ticketLevel, this.key, this.forceTicks); + } - public String toString() { -- return "Ticket[" + this.type + " " + this.ticketLevel + " (" + this.key + ")] at " + this.createdTick; -+ return "Ticket[" + this.type + " " + this.ticketLevel + " (" + this.key + ")] at " + this.createdTick + " force ticks " + forceTicks; - } + @Override + public String toString() { +- return "Ticket[" + this.type + " " + this.ticketLevel + " (" + this.key + ")] at " + this.createdTick; ++ return "Ticket[" + this.type + " " + this.ticketLevel + " (" + this.key + ")] at " + this.createdTick + " force ticks " + forceTicks; + } - public TicketType getType() { -@@ -58,5 +_,12 @@ - protected boolean timedOut(long p_9435_) { - long i = this.type.timeout(); - return i != 0L && p_9435_ - this.createdTick > i; -+ } + public TicketType getType() { +@@ -51,6 +_,10 @@ + + public int getTicketLevel() { + return this.ticketLevel; ++ } + -+ /* ======================================== FORGE START =====================================*/ -+ private final boolean forceTicks; -+ -+ public boolean isForceTicks() { -+ return forceTicks; - } - } ++ public boolean isForceTicks() { ++ return this.forceTicks; + } + + protected void setCreatedTick(long p_9430_) { diff --git a/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch b/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch index 0623468348..7088fd0b6b 100644 --- a/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch +++ b/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/level/WorldGenRegion.java +++ b/net/minecraft/server/level/WorldGenRegion.java -@@ -297,6 +_,7 @@ - } +@@ -325,6 +_,7 @@ - public boolean addFreshEntity(Entity p_9580_) { -+ if (p_9580_ instanceof net.minecraft.world.entity.Mob mob && mob.isSpawnCancelled()) return false; - int i = SectionPos.blockToSectionCoord(p_9580_.getBlockX()); - int j = SectionPos.blockToSectionCoord(p_9580_.getBlockZ()); - this.getChunk(i, j).addEntity(p_9580_); + @Override + public boolean addFreshEntity(Entity p_9580_) { ++ if (p_9580_ instanceof net.minecraft.world.entity.Mob mob && mob.isSpawnCancelled()) return false; + int i = SectionPos.blockToSectionCoord(p_9580_.getBlockX()); + int j = SectionPos.blockToSectionCoord(p_9580_.getBlockZ()); + this.getChunk(i, j).addEntity(p_9580_); diff --git a/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch index 542c080a24..4a6ae71c38 100644 --- a/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch @@ -4,10 +4,10 @@ import net.minecraft.network.protocol.Packet; public interface ConfigurationTask { -+ default void start(net.minecraftforge.network.config.ConfigurationTaskContext ctx) { -+ start(ctx::send); -+ } ++ default void start(net.minecraftforge.network.config.ConfigurationTaskContext ctx) { ++ start(ctx::send); ++ } + - void start(Consumer> p_299398_); + void start(Consumer> p_299398_); - ConfigurationTask.Type type(); + ConfigurationTask.Type type(); diff --git a/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch index 7b58734727..2fb993558c 100644 --- a/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java +++ b/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java -@@ -17,6 +_,7 @@ - } +@@ -19,6 +_,7 @@ - public void handleIntention(ClientIntentionPacket p_9697_) { -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerLogin(p_9697_, this.connection)) return; - if (p_9697_.intention() != ClientIntent.LOGIN) { - throw new UnsupportedOperationException("Invalid intention " + p_9697_.intention()); - } else { + @Override + public void handleIntention(ClientIntentionPacket p_9697_) { ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerLogin(p_9697_, this.connection)) return; + if (p_9697_.intention() != ClientIntent.LOGIN) { + throw new UnsupportedOperationException("Invalid intention " + p_9697_.intention()); + } else { diff --git a/patches/minecraft/net/minecraft/server/network/PlayerChunkSender.java.patch b/patches/minecraft/net/minecraft/server/network/PlayerChunkSender.java.patch index fd4c826932..151d0e5d14 100644 --- a/patches/minecraft/net/minecraft/server/network/PlayerChunkSender.java.patch +++ b/patches/minecraft/net/minecraft/server/network/PlayerChunkSender.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/server/network/PlayerChunkSender.java +++ b/net/minecraft/server/network/PlayerChunkSender.java -@@ -45,6 +_,7 @@ - public void dropChunk(ServerPlayer p_298166_, ChunkPos p_300687_) { - if (!this.pendingChunks.remove(p_300687_.toLong()) && p_298166_.isAlive()) { - p_298166_.connection.send(new ClientboundForgetLevelChunkPacket(p_300687_)); -+ net.minecraftforge.event.ForgeEventFactory.fireChunkUnWatch(p_298166_, p_300687_, (ServerLevel) p_298166_.level()); - } +@@ -44,6 +_,7 @@ + public void dropChunk(ServerPlayer p_298166_, ChunkPos p_300687_) { + if (!this.pendingChunks.remove(p_300687_.toLong()) && p_298166_.isAlive()) { + p_298166_.connection.send(new ClientboundForgetLevelChunkPacket(p_300687_)); ++ net.minecraftforge.event.ForgeEventFactory.fireChunkUnWatch(p_298166_, p_300687_, (ServerLevel) p_298166_.level()); + } + } - } -@@ -79,6 +_,7 @@ - p_299748_.send(new ClientboundLevelChunkWithLightPacket(p_297712_, p_298120_.getLightEngine(), (BitSet)null, (BitSet)null)); - ChunkPos chunkpos = p_297712_.getPos(); - DebugPackets.sendPoiPacketsForChunk(p_298120_, chunkpos); -+ net.minecraftforge.event.ForgeEventFactory.fireChunkWatch(p_299748_.player, p_297712_, p_298120_); - } +@@ -77,6 +_,7 @@ + p_299748_.send(new ClientboundLevelChunkWithLightPacket(p_297712_, p_298120_.getLightEngine(), null, null)); + ChunkPos chunkpos = p_297712_.getPos(); + DebugPackets.sendPoiPacketsForChunk(p_298120_, chunkpos); ++ net.minecraftforge.event.ForgeEventFactory.fireChunkWatch(p_299748_.player, p_297712_, p_298120_); + } - private List collectChunksToSend(ChunkMap p_298180_, ChunkPos p_298514_) { + private List collectChunksToSend(ChunkMap p_298180_, ChunkPos p_298514_) { diff --git a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch index 39f71db9e4..05df7ed702 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/server/network/ServerCommonPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerCommonPacketListenerImpl.java -@@ -66,6 +_,7 @@ - } +@@ -82,6 +_,7 @@ - public void handleCustomPayload(ServerboundCustomPayloadPacket p_300164_) { -+ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_, this.connection); - } + @Override + public void handleCustomPayload(ServerboundCustomPayloadPacket p_300164_) { ++ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_, this.connection); + } - public void handleResourcePackResponse(ServerboundResourcePackPacket p_300656_) { -@@ -147,5 +_,9 @@ + @Override +@@ -180,5 +_,9 @@ - protected CommonListenerCookie createCookie(ClientInformation p_297318_) { - return new CommonListenerCookie(this.playerProfile(), this.latency, p_297318_); -+ } + protected CommonListenerCookie createCookie(ClientInformation p_297318_) { + return new CommonListenerCookie(this.playerProfile(), this.latency, p_297318_, this.transferred); ++ } + -+ public Connection getConnection() { -+ return this.connection; - } ++ public Connection getConnection() { ++ return this.connection; + } } diff --git a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch index 79ce40bca2..17b976ba3d 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch @@ -1,50 +1,54 @@ --- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java -@@ -36,16 +_,19 @@ - public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements TickablePacketListener, ServerConfigurationPacketListener { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final Component DISCONNECT_REASON_INVALID_DATA = Component.translatable("multiplayer.disconnect.invalid_player_data"); -+ private static final ConfigurationTask.Type VANILLA_START = new ConfigurationTask.Type("vanilla_start"); - private final GameProfile gameProfile; - private final Queue configurationTasks = new ConcurrentLinkedQueue<>(); - @Nullable - private ConfigurationTask currentTask; - private ClientInformation clientInformation; -+ private final net.minecraftforge.network.config.ConfigurationTaskContext taskContext; +@@ -38,6 +_,7 @@ + public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerConfigurationPacketListener, TickablePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + private static final Component DISCONNECT_REASON_INVALID_DATA = Component.translatable("multiplayer.disconnect.invalid_player_data"); ++ private static final ConfigurationTask.Type VANILLA_START = new ConfigurationTask.Type("vanilla_start"); + private final GameProfile gameProfile; + private final Queue configurationTasks = new ConcurrentLinkedQueue<>(); + @Nullable +@@ -45,11 +_,13 @@ + private ClientInformation clientInformation; + @Nullable + private SynchronizeRegistriesTask synchronizeRegistriesTask; ++ private final net.minecraftforge.network.config.ConfigurationTaskContext taskContext; - public ServerConfigurationPacketListenerImpl(MinecraftServer p_301415_, Connection p_298106_, CommonListenerCookie p_301309_) { - super(p_301415_, p_298106_, p_301309_); - this.gameProfile = p_301309_.gameProfile(); - this.clientInformation = p_301309_.clientInformation(); -+ this.taskContext = new net.minecraftforge.network.config.ConfigurationTaskContext(p_298106_, this::send, this::finishCurrentTask); - } + public ServerConfigurationPacketListenerImpl(MinecraftServer p_301415_, Connection p_298106_, CommonListenerCookie p_301309_) { + super(p_301415_, p_298106_, p_301309_); + this.gameProfile = p_301309_.gameProfile(); + this.clientInformation = p_301309_.clientInformation(); ++ this.taskContext = new net.minecraftforge.network.config.ConfigurationTaskContext(p_298106_, this::send, this::finishCurrentTask); + } - protected GameProfile playerProfile() { -@@ -61,12 +_,17 @@ - return this.connection.isConnected(); - } + @Override +@@ -68,13 +_,18 @@ + return this.connection.isConnected(); + } -- public void startConfiguration() { -+ private void vanillaStart() { - this.send(new ClientboundCustomPayloadPacket(new BrandPayload(this.server.getServerModName()))); - LayeredRegistryAccess layeredregistryaccess = this.server.registries(); - this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); - this.send(new ClientboundRegistryDataPacket((new RegistryAccess.ImmutableRegistryAccess(RegistrySynchronization.networkedRegistries(layeredregistryaccess))).freeze())); - this.send(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(layeredregistryaccess))); -+ } +- public void startConfiguration() { ++ public void vanillaStart() { + this.send(new ClientboundCustomPayloadPacket(new BrandPayload(this.server.getServerModName()))); ++ this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); ++ } + -+ public void startConfiguration() { -+ net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.connection, this.configurationTasks::add); -+ this.configurationTasks.add(new net.minecraftforge.network.config.SimpleConfigurationTask(VANILLA_START, this::vanillaStart)); - this.addOptionalTasks(); - this.configurationTasks.add(new JoinWorldTask()); - this.startNextTask(); -@@ -135,7 +_,7 @@ - ConfigurationTask configurationtask = this.configurationTasks.poll(); - if (configurationtask != null) { - this.currentTask = configurationtask; -- configurationtask.start(this::send); -+ configurationtask.start(this.taskContext); - } - - } ++ public void startConfiguration() { ++ net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.connection, this.configurationTasks::add); + LayeredRegistryAccess layeredregistryaccess = this.server.registries(); + List list = this.server.getResourceManager().listPacks().flatMap(p_326454_ -> p_326454_.location().knownPackInfo().stream()).toList(); +- this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); + this.synchronizeRegistriesTask = new SynchronizeRegistriesTask(list, layeredregistryaccess); + this.configurationTasks.add(this.synchronizeRegistriesTask); ++ this.configurationTasks.add(new net.minecraftforge.network.config.SimpleConfigurationTask(VANILLA_START, this::vanillaStart)); + this.addOptionalTasks(); + this.configurationTasks.add(new JoinWorldTask()); + this.startNextTask(); +@@ -153,7 +_,7 @@ + ConfigurationTask configurationtask = this.configurationTasks.poll(); + if (configurationtask != null) { + this.currentTask = configurationtask; +- configurationtask.start(this::send); ++ configurationtask.start(this.taskContext); + } + } + } diff --git a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch index b6c01525d9..1cf7db3895 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch @@ -1,35 +1,35 @@ --- a/net/minecraft/server/network/ServerConnectionListener.java +++ b/net/minecraft/server/network/ServerConnectionListener.java -@@ -49,11 +_,12 @@ +@@ -48,11 +_,12 @@ public class ServerConnectionListener { - private static final Logger LOGGER = LogUtils.getLogger(); -+ private static final int READ_TIMEOUT = Integer.parseInt(System.getProperty("forge.readTimeout", "30")); - public static final Supplier SERVER_EVENT_GROUP = Suppliers.memoize(() -> { -- return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Server IO #%d").setDaemon(true).build()); -+ return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Server IO #%d").setDaemon(true).setThreadFactory(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER).build()); - }); - public static final Supplier SERVER_EPOLL_EVENT_GROUP = Suppliers.memoize(() -> { -- return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Server IO #%d").setDaemon(true).build()); -+ return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Server IO #%d").setDaemon(true).setThreadFactory(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER).build()); - }); - final MinecraftServer server; - public volatile boolean running; -@@ -66,6 +_,8 @@ - } + private static final Logger LOGGER = LogUtils.getLogger(); ++ private static final int READ_TIMEOUT = Integer.parseInt(System.getProperty("forge.readTimeout", "30")); + public static final Supplier SERVER_EVENT_GROUP = Suppliers.memoize( +- () -> new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Server IO #%d").setDaemon(true).build()) ++ () -> new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Server IO #%d").setDaemon(true).setThreadFactory(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER).build()) + ); + public static final Supplier SERVER_EPOLL_EVENT_GROUP = Suppliers.memoize( +- () -> new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Epoll Server IO #%d").setDaemon(true).build()) ++ () -> new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("Netty Epoll Server IO #%d").setDaemon(true).setThreadFactory(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER).build()) + ); + final MinecraftServer server; + public volatile boolean running; +@@ -65,6 +_,8 @@ + } - public void startTcpServerListener(@Nullable InetAddress p_9712_, int p_9713_) throws IOException { -+ if (p_9712_ == null) p_9712_ = new java.net.InetSocketAddress(p_9713_).getAddress(); -+ net.minecraftforge.network.DualStackUtils.checkIPv6(p_9712_); - synchronized(this.channels) { - Class oclass; - EventLoopGroup eventloopgroup; -@@ -88,7 +_,7 @@ - } catch (ChannelException channelexception) { - } + public void startTcpServerListener(@Nullable InetAddress p_9712_, int p_9713_) throws IOException { ++ if (p_9712_ == null) p_9712_ = new java.net.InetSocketAddress(p_9713_).getAddress(); ++ net.minecraftforge.network.DualStackUtils.checkIPv6(p_9712_); + synchronized (this.channels) { + Class oclass; + EventLoopGroup eventloopgroup; +@@ -86,7 +_,7 @@ + } catch (ChannelException channelexception) { + } -- ChannelPipeline channelpipeline = p_9729_.pipeline().addLast("timeout", new ReadTimeoutHandler(30)).addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); -+ ChannelPipeline channelpipeline = p_9729_.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)).addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); - Connection.configureSerialization(channelpipeline, PacketFlow.SERVERBOUND, (BandwidthDebugMonitor)null); - int i = ServerConnectionListener.this.server.getRateLimitPacketsPerSecond(); - Connection connection = (Connection)(i > 0 ? new RateKickingConnection(i) : new Connection(PacketFlow.SERVERBOUND)); +- ChannelPipeline channelpipeline = p_9729_.pipeline().addLast("timeout", new ReadTimeoutHandler(30)); ++ ChannelPipeline channelpipeline = p_9729_.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)); + if (ServerConnectionListener.this.server.repliesToStatus()) { + channelpipeline.addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); + } diff --git a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch index 42e590858c..e5fe2c0c58 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch @@ -1,87 +1,39 @@ --- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java +++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java -@@ -181,6 +_,12 @@ +@@ -437,9 +_,11 @@ + } - public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerGamePacketListener, ServerPlayerConnection, TickablePacketListener { - static final Logger LOGGER = LogUtils.getLogger(); -+ /** -+ * Forge: Deprecated in favor of range/reach attributes. -+ * @see net.minecraftforge.common.ForgeMod#BLOCK_REACH -+ * @see net.minecraftforge.common.ForgeMod#ENTITY_REACH -+ */ -+ @Deprecated - public static final double MAX_INTERACTION_DISTANCE = Mth.square(6.0D); - private static final int NO_BLOCK_UPDATES_TO_ACK = -1; - private static final int TRACKED_MESSAGE_DISCONNECT_THRESHOLD = 4096; -@@ -414,9 +_,11 @@ - } + entity.absMoveTo(d3, d4, d5, f, f1); ++ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving + boolean flag3 = serverlevel.noCollision(entity, entity.getBoundingBox().deflate(0.0625)); + if (flag && (flag2 || !flag3)) { + entity.absMoveTo(d0, d1, d2, f, f1); ++ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving + this.send(new ClientboundMoveVehiclePacket(entity)); + return; + } +@@ -1005,9 +_,10 @@ + switch (serverboundplayeractionpacket$action) { + case SWAP_ITEM_WITH_OFFHAND: + if (!this.player.isSpectator()) { +- ItemStack itemstack = this.player.getItemInHand(InteractionHand.OFF_HAND); +- this.player.setItemInHand(InteractionHand.OFF_HAND, this.player.getItemInHand(InteractionHand.MAIN_HAND)); +- this.player.setItemInHand(InteractionHand.MAIN_HAND, itemstack); ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this.player); ++ if (event.isCanceled()) return; ++ this.player.setItemInHand(InteractionHand.OFF_HAND, event.getItemSwappedToOffHand()); ++ this.player.setItemInHand(InteractionHand.MAIN_HAND, event.getItemSwappedToMainHand()); + this.player.stopUsingItem(); + } - entity.absMoveTo(d3, d4, d5, f, f1); -+ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving - boolean flag3 = serverlevel.noCollision(entity, entity.getBoundingBox().deflate(0.0625D)); - if (flag && (flag2 || !flag3)) { - entity.absMoveTo(d0, d1, d2, f, f1); -+ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving - this.send(new ClientboundMoveVehiclePacket(entity)); - return; - } -@@ -981,8 +_,10 @@ - case SWAP_ITEM_WITH_OFFHAND: - if (!this.player.isSpectator()) { - ItemStack itemstack = this.player.getItemInHand(InteractionHand.OFF_HAND); -- this.player.setItemInHand(InteractionHand.OFF_HAND, this.player.getItemInHand(InteractionHand.MAIN_HAND)); -- this.player.setItemInHand(InteractionHand.MAIN_HAND, itemstack); -+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this.player); -+ if (event.isCanceled()) return; -+ this.player.setItemInHand(InteractionHand.OFF_HAND, event.getItemSwappedToOffHand()); -+ this.player.setItemInHand(InteractionHand.MAIN_HAND, event.getItemSwappedToMainHand()); - this.player.stopUsingItem(); - } +@@ -1192,8 +_,9 @@ + } -@@ -1033,7 +_,7 @@ - Vec3 vec3 = blockhitresult.getLocation(); - BlockPos blockpos = blockhitresult.getBlockPos(); - Vec3 vec31 = Vec3.atCenterOf(blockpos); -- if (!(this.player.getEyePosition().distanceToSqr(vec31) > MAX_INTERACTION_DISTANCE)) { -+ if (this.player.canReach(blockpos, 1.5)) { // Vanilla uses eye-to-center distance < 6, which implies a padding of 1.5 - Vec3 vec32 = vec3.subtract(vec31); - double d0 = 1.0000001D; - if (Math.abs(vec32.x()) < 1.0000001D && Math.abs(vec32.y()) < 1.0000001D && Math.abs(vec32.z()) < 1.0000001D) { -@@ -1041,7 +_,7 @@ - this.player.resetLastActionTime(); - int i = this.player.level().getMaxBuildHeight(); - if (blockpos.getY() < i) { -- if (this.awaitingPositionFromClient == null && this.player.distanceToSqr((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D) < 64.0D && serverlevel.mayInteract(this.player, blockpos)) { -+ if (this.awaitingPositionFromClient == null && serverlevel.mayInteract(this.player, blockpos)) { - InteractionResult interactionresult = this.player.gameMode.useItemOn(this.player, serverlevel, itemstack, interactionhand, blockhitresult); - if (direction == Direction.UP && !interactionresult.consumesAction() && blockpos.getY() >= i - 1 && wasBlockPlacementAttempt(this.player, itemstack)) { - Component component = Component.translatable("build.tooHigh", i - 1).withStyle(ChatFormatting.RED); -@@ -1156,8 +_,9 @@ - } - - CompletableFuture completablefuture = this.filterTextPacket(playerchatmessage.signedContent()); -- Component component = this.server.getChatDecorator().decorate(this.player, playerchatmessage.decoratedContent()); -+ Component component = net.minecraftforge.common.ForgeHooks.onServerChatSubmittedEvent(this.player, playerchatmessage.decoratedContent()); - this.chatMessageChain.append(completablefuture, (p_296589_) -> { -+ if (component == null) return; - PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(p_296589_.mask()); - this.broadcastChatMessage(playerchatmessage1); - }); -@@ -1400,7 +_,7 @@ - } - - AABB aabb = entity.getBoundingBox(); -- if (aabb.distanceToSqr(this.player.getEyePosition()) < MAX_INTERACTION_DISTANCE) { -+ if (this.player.canReach(entity, 3)) { // Vanilla padding is 3.0 (distSq < 6.0 * 6.0) - p_9866_.dispatch(new ServerboundInteractPacket.Handler() { - private void performInteraction(InteractionHand p_143679_, ServerGamePacketListenerImpl.EntityInteraction p_143680_) { - ItemStack itemstack = ServerGamePacketListenerImpl.this.player.getItemInHand(p_143679_); -@@ -1423,6 +_,8 @@ - - public void onInteraction(InteractionHand p_143682_, Vec3 p_143683_) { - this.performInteraction(p_143682_, (p_143686_, p_143687_, p_143688_) -> { -+ InteractionResult onInteractEntityAtResult = net.minecraftforge.common.ForgeHooks.onInteractEntityAt(player, entity, p_143683_, p_143682_); -+ if (onInteractEntityAtResult != null) return onInteractEntityAtResult; - return p_143687_.interactAt(p_143686_, p_143683_, p_143688_); - }); - } + CompletableFuture completablefuture = this.filterTextPacket(playerchatmessage.signedContent()); +- Component component = this.server.getChatDecorator().decorate(this.player, playerchatmessage.decoratedContent()); ++ Component component = net.minecraftforge.common.ForgeHooks.onServerChatSubmittedEvent(this.player, playerchatmessage.decoratedContent()); + this.chatMessageChain.append(completablefuture, p_296589_ -> { ++ if (component == null) return; + PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(p_296589_.mask()); + this.broadcastChatMessage(playerchatmessage1); + }); diff --git a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch index 9bff1ea70d..4612979053 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java +++ b/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java -@@ -21,6 +_,7 @@ - } +@@ -23,6 +_,7 @@ - public void handleIntention(ClientIntentionPacket p_9975_) { -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerLogin(p_9975_, this.connection)) return; - switch (p_9975_.intention()) { - case LOGIN: - this.connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN); -@@ -42,7 +_,7 @@ - ServerStatus serverstatus = this.server.getStatus(); - if (this.server.repliesToStatus() && serverstatus != null) { - this.connection.setClientboundProtocolAfterHandshake(ClientIntent.STATUS); -- this.connection.setListener(new ServerStatusPacketListenerImpl(serverstatus, this.connection)); -+ this.connection.setListener(new ServerStatusPacketListenerImpl(serverstatus, this.connection, this.server.getStatusJson())); - } else { - this.connection.disconnect(IGNORE_STATUS_REASON); - } + @Override + public void handleIntention(ClientIntentionPacket p_9975_) { ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerLogin(p_9975_, this.connection)) return; + switch (p_9975_.intention()) { + case LOGIN: + this.beginLogin(p_9975_, false); +@@ -31,7 +_,7 @@ + ServerStatus serverstatus = this.server.getStatus(); + this.connection.setupOutboundProtocol(StatusProtocols.CLIENTBOUND); + if (this.server.repliesToStatus() && serverstatus != null) { +- this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(serverstatus, this.connection)); ++ this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(serverstatus, this.connection, this.server.getStatusJson())); + } else { + this.connection.disconnect(IGNORE_STATUS_REASON); + } diff --git a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch index 13c21b72b6..3e4993cd53 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java -@@ -175,7 +_,7 @@ - throw new IllegalStateException("Protocol error", cryptexception); - } +@@ -181,7 +_,7 @@ + throw new IllegalStateException("Protocol error", cryptexception); + } -- Thread thread = new Thread("User Authenticator #" + UNIQUE_THREAD_ID.incrementAndGet()) { -+ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, "User Authenticator #" + UNIQUE_THREAD_ID.incrementAndGet()) { - public void run() { - String s1 = Objects.requireNonNull(ServerLoginPacketListenerImpl.this.requestedUsername, "Player name not initialized"); +- Thread thread = new Thread("User Authenticator #" + UNIQUE_THREAD_ID.incrementAndGet()) { ++ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, "User Authenticator #" + UNIQUE_THREAD_ID.incrementAndGet()) { + @Override + public void run() { + String s1 = Objects.requireNonNull(ServerLoginPacketListenerImpl.this.requestedUsername, "Player name not initialized"); +@@ -224,6 +_,7 @@ -@@ -215,6 +_,7 @@ - } + @Override + public void handleCustomQueryPacket(ServerboundCustomQueryAnswerPacket p_297965_) { ++ if (!net.minecraftforge.common.ForgeHooks.onCustomPayload(p_297965_, this.connection)) + this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); + } - public void handleCustomQueryPacket(ServerboundCustomQueryAnswerPacket p_297965_) { -+ if (!net.minecraftforge.common.ForgeHooks.onCustomPayload(p_297965_, this.connection)) - this.disconnect(DISCONNECT_UNEXPECTED_QUERY); - } - -@@ -225,6 +_,11 @@ - this.connection.setListener(serverconfigurationpacketlistenerimpl); - serverconfigurationpacketlistenerimpl.startConfiguration(); - this.state = ServerLoginPacketListenerImpl.State.ACCEPTED; -+ } +@@ -248,6 +_,11 @@ + @Override + public void handleCookieResponse(ServerboundCookieResponsePacket p_333672_) { + this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); ++ } + -+ @Nullable -+ public GameProfile getAuthenticatedProfile() { -+ return this.authenticatedProfile; - } ++ @Nullable ++ public GameProfile getAuthenticatedProfile() { ++ return this.authenticatedProfile; + } - public void fillListenerSpecificCrashDetails(CrashReportCategory p_310682_) { + static enum State { diff --git a/patches/minecraft/net/minecraft/server/network/ServerStatusPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerStatusPacketListenerImpl.java.patch index 864e794581..6e1c6e9a5e 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerStatusPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerStatusPacketListenerImpl.java.patch @@ -1,29 +1,30 @@ --- a/net/minecraft/server/network/ServerStatusPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerStatusPacketListenerImpl.java -@@ -12,12 +_,17 @@ +@@ -12,12 +_,18 @@ public class ServerStatusPacketListenerImpl implements ServerStatusPacketListener { - private static final Component DISCONNECT_REASON = Component.translatable("multiplayer.status.request_handled"); - private final ServerStatus status; -+ private final @org.jetbrains.annotations.Nullable String statusCache; // FORGE: cache status JSON - private final Connection connection; - private boolean hasRequestedStatus; + private static final Component DISCONNECT_REASON = Component.translatable("multiplayer.status.request_handled"); + private final ServerStatus status; ++ private final @org.jetbrains.annotations.Nullable String statusCache; // FORGE: cache status JSON + private final Connection connection; + private boolean hasRequestedStatus; - public ServerStatusPacketListenerImpl(ServerStatus p_272864_, Connection p_273586_) { -+ this(p_272864_, p_273586_, null); -+ } -+ public ServerStatusPacketListenerImpl(ServerStatus p_272864_, Connection p_273586_, @org.jetbrains.annotations.Nullable String statusCache) { - this.status = p_272864_; - this.connection = p_273586_; -+ this.statusCache = statusCache; - } + public ServerStatusPacketListenerImpl(ServerStatus p_272864_, Connection p_273586_) { ++ this(p_272864_, p_273586_, null); ++ } ++ ++ public ServerStatusPacketListenerImpl(ServerStatus p_272864_, Connection p_273586_, @org.jetbrains.annotations.Nullable String statusCache) { + this.status = p_272864_; + this.connection = p_273586_; ++ this.statusCache = statusCache; + } - public void onDisconnect(Component p_10091_) { -@@ -32,7 +_,7 @@ - this.connection.disconnect(DISCONNECT_REASON); - } else { - this.hasRequestedStatus = true; -- this.connection.send(new ClientboundStatusResponsePacket(this.status)); -+ this.connection.send(new ClientboundStatusResponsePacket(this.status, this.statusCache)); - } - } + @Override +@@ -35,7 +_,7 @@ + this.connection.disconnect(DISCONNECT_REASON); + } else { + this.hasRequestedStatus = true; +- this.connection.send(new ClientboundStatusResponsePacket(this.status)); ++ this.connection.send(new ClientboundStatusResponsePacket(this.status, this.statusCache)); + } + } diff --git a/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch b/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch index bf027988c7..17594c2b7c 100644 --- a/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch @@ -1,13 +1,12 @@ --- a/net/minecraft/server/packs/AbstractPackResources.java +++ b/net/minecraft/server/packs/AbstractPackResources.java -@@ -64,4 +_,10 @@ - public boolean isBuiltin() { - return this.isBuiltin; - } +@@ -63,4 +_,9 @@ + public PackLocationInfo location() { + return this.location; + } + -+ @Override -+ public String toString() -+ { -+ return String.format(java.util.Locale.ROOT, "%s: %s", getClass().getName(), this.name); -+ } ++ @Override ++ public String toString() { ++ return String.format(java.util.Locale.ROOT, "%s: %s", getClass().getName(), this.location()); ++ } } diff --git a/patches/minecraft/net/minecraft/server/packs/PackResources.java.patch b/patches/minecraft/net/minecraft/server/packs/PackResources.java.patch index aea4ab3055..db7f011532 100644 --- a/patches/minecraft/net/minecraft/server/packs/PackResources.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/PackResources.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/packs/PackResources.java +++ b/net/minecraft/server/packs/PackResources.java -@@ -9,7 +_,7 @@ - import net.minecraft.server.packs.metadata.MetadataSectionSerializer; +@@ -11,7 +_,7 @@ + import net.minecraft.server.packs.repository.KnownPack; import net.minecraft.server.packs.resources.IoSupplier; -public interface PackResources extends AutoCloseable { +public interface PackResources extends AutoCloseable, net.minecraftforge.common.extensions.IForgePackResources { - String METADATA_EXTENSION = ".mcmeta"; - String PACK_META = "pack.mcmeta"; + String METADATA_EXTENSION = ".mcmeta"; + String PACK_META = "pack.mcmeta"; diff --git a/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch index 03ef637d73..4887867b60 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch @@ -1,50 +1,50 @@ --- a/net/minecraft/server/packs/repository/Pack.java +++ b/net/minecraft/server/packs/repository/Pack.java -@@ -28,6 +_,7 @@ - private final Pack.Position defaultPosition; - private final boolean required; - private final boolean fixedPosition; -+ private final boolean hidden; // Forge: Allow packs to be hidden from the UI entirely - private final PackSource packSource; +@@ -23,6 +_,7 @@ + private final Pack.ResourcesSupplier resources; + private final Pack.Metadata metadata; + private final PackSelectionConfig selectionConfig; ++ private final boolean hidden; // Forge: Allow packs to be hidden from the UI entirely - @Nullable -@@ -50,6 +_,7 @@ - this.defaultPosition = p_251298_; - this.fixedPosition = p_249753_; - this.packSource = p_251608_; -+ this.hidden = p_250162_.hidden(); - } + @Nullable + public static Pack readMetaAndCreate(PackLocationInfo p_333251_, Pack.ResourcesSupplier p_252210_, PackType p_250595_, PackSelectionConfig p_334202_) { +@@ -36,6 +_,7 @@ + this.resources = p_249377_; + this.metadata = p_330761_; + this.selectionConfig = p_334769_; ++ this.hidden = p_330761_.isHidden(); + } - @Nullable -@@ -66,7 +_,7 @@ - PackCompatibility packcompatibility = PackCompatibility.forVersion(inclusiverange, p_299232_); - OverlayMetadataSection overlaymetadatasection = packresources.getMetadataSection(OverlayMetadataSection.TYPE); - List list = overlaymetadatasection != null ? overlaymetadatasection.overlaysForVersion(p_299232_) : List.of(); -- return new Pack.Info(packmetadatasection.description(), packcompatibility, featureflagset, list); -+ return new Pack.Info(packmetadatasection.description(), packcompatibility, featureflagset, list, packresources.isHidden()); - } - } catch (Exception exception) { - LOGGER.warn("Failed to read pack {} metadata", p_250591_, exception); -@@ -135,6 +_,10 @@ - return this.packSource; - } + @Nullable +@@ -55,7 +_,7 @@ + PackCompatibility packcompatibility = PackCompatibility.forVersion(inclusiverange, p_333544_); + OverlayMetadataSection overlaymetadatasection = packresources.getMetadataSection(OverlayMetadataSection.TYPE); + List list = overlaymetadatasection != null ? overlaymetadatasection.overlaysForVersion(p_333544_) : List.of(); +- pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list); ++ pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list, packresources.isHidden()); + } -+ public boolean isHidden() { -+ return hidden; -+ } + return pack$metadata; +@@ -132,6 +_,10 @@ + return this.location.source(); + } + ++ public boolean isHidden() { ++ return this.hidden; ++ } + - public boolean equals(Object p_10448_) { - if (this == p_10448_) { - return true; -@@ -150,7 +_,10 @@ - return this.id.hashCode(); - } + @Override + public boolean equals(Object p_10448_) { + if (this == p_10448_) { +@@ -146,7 +_,10 @@ + return this.location.hashCode(); + } -- public static record Info(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays) { -+ public static record Info(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays, boolean hidden) { -+ public Info(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays) { -+ this(description, compatibility, requestedFeatures, overlays, false); -+ } - } +- public static record Metadata(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays) { ++ public static record Metadata(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays, boolean isHidden) { ++ public Metadata(Component description, PackCompatibility compatibility, FeatureFlagSet requestedFeatures, List overlays) { ++ this(description, compatibility, requestedFeatures, overlays, false); ++ } + } - public static enum Position { + public static enum Position { diff --git a/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch new file mode 100644 index 0000000000..e3f8d3c983 --- /dev/null +++ b/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch @@ -0,0 +1,27 @@ +--- a/net/minecraft/server/packs/repository/PackDetector.java ++++ b/net/minecraft/server/packs/repository/PackDetector.java +@@ -20,6 +_,10 @@ + + @Nullable + public T detectPackResources(Path p_298083_, List p_297322_) throws IOException { ++ return detectPackResources(p_298083_, p_297322_, true); ++ } ++ @Nullable ++ public T detectPackResources(Path p_298083_, List p_297322_, boolean requireMeta) throws IOException { + Path path = p_298083_; + + BasicFileAttributes basicfileattributes; +@@ -44,10 +_,11 @@ + if (!p_297322_.isEmpty()) { + return null; + } else { +- return !Files.isRegularFile(path.resolve("pack.mcmeta")) ? null : this.createDirectoryPack(path); ++ return !Files.isRegularFile(path.resolve("pack.mcmeta")) && requireMeta ? null : this.createDirectoryPack(path); + } + } else { +- return basicfileattributes.isRegularFile() && path.getFileName().toString().endsWith(".zip") ? this.createZipPack(path) : null; ++ var name = path.getFileName().toString(); ++ return basicfileattributes.isRegularFile() && (name.endsWith(".zip") || name.endsWith(".jar")) ? this.createZipPack(path) : null; + } + } + diff --git a/patches/minecraft/net/minecraft/server/packs/repository/PackRepository.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/PackRepository.java.patch index aef68d709f..395fec336e 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/PackRepository.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/PackRepository.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/server/packs/repository/PackRepository.java +++ b/net/minecraft/server/packs/repository/PackRepository.java @@ -23,7 +_,7 @@ - private List selected = ImmutableList.of(); + private List selected = ImmutableList.of(); - public PackRepository(RepositorySource... p_251886_) { -- this.sources = ImmutableSet.copyOf(p_251886_); -+ this.sources = new java.util.LinkedHashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on. - } + public PackRepository(RepositorySource... p_251886_) { +- this.sources = ImmutableSet.copyOf(p_251886_); ++ this.sources = new java.util.LinkedHashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on. + } - public void reload() { -@@ -111,6 +_,10 @@ - @Nullable - public Pack getPack(String p_10508_) { - return this.available.get(p_10508_); -+ } + public static String displayPackList(Collection p_331712_) { +@@ -115,6 +_,10 @@ + @Nullable + public Pack getPack(String p_10508_) { + return this.available.get(p_10508_); ++ } + -+ public synchronized void addPackFinder(RepositorySource packFinder) { -+ this.sources.add(packFinder); - } ++ public synchronized void addPackFinder(RepositorySource packFinder) { ++ this.sources.add(packFinder); + } - public boolean isAvailable(String p_10516_) { + public boolean isAvailable(String p_10516_) { diff --git a/patches/minecraft/net/minecraft/server/packs/repository/ServerPacksSource.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/ServerPacksSource.java.patch index dfa6855773..3d75cba5ad 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/ServerPacksSource.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/ServerPacksSource.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/server/packs/repository/ServerPacksSource.java +++ b/net/minecraft/server/packs/repository/ServerPacksSource.java -@@ -50,7 +_,9 @@ - } +@@ -67,7 +_,9 @@ + } - public static PackRepository createPackRepository(Path p_251569_, DirectoryValidator p_300268_) { -- return new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); -+ var ret = new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.event.AddPackFindersEvent(PackType.SERVER_DATA, ret::addPackFinder)); -+ return ret; - } + public static PackRepository createPackRepository(Path p_251569_, DirectoryValidator p_300268_) { +- return new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); ++ var ret = new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.event.AddPackFindersEvent(PackType.SERVER_DATA, ret::addPackFinder)); ++ return ret; + } - public static PackRepository createVanillaTrustedRepository() { + public static PackRepository createVanillaTrustedRepository() { diff --git a/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch index 180236ecc9..a724fdc81a 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/server/packs/resources/FallbackResourceManager.java +++ b/net/minecraft/server/packs/resources/FallbackResourceManager.java -@@ -98,8 +_,11 @@ +@@ -103,8 +_,11 @@ - for(int i = this.fallbacks.size() - 1; i >= 0; --i) { - FallbackResourceManager.PackEntry fallbackresourcemanager$packentry = this.fallbacks.get(i); -- PackResources packresources = fallbackresourcemanager$packentry.resources; -- if (packresources != null) { -+ PackResources pack = fallbackresourcemanager$packentry.resources; -+ if (pack != null) { -+ var children = pack.getChildren(); -+ var packs = children == null ? List.of(pack) : children; -+ for (final PackResources packresources : packs) { - IoSupplier iosupplier = packresources.getResource(this.type, p_215367_); - if (iosupplier != null) { - IoSupplier iosupplier1; -@@ -113,6 +_,7 @@ - } + for (int i = this.fallbacks.size() - 1; i >= 0; i--) { + FallbackResourceManager.PackEntry fallbackresourcemanager$packentry = this.fallbacks.get(i); +- PackResources packresources = fallbackresourcemanager$packentry.resources; +- if (packresources != null) { ++ PackResources pack = fallbackresourcemanager$packentry.resources; ++ if (pack != null) { ++ var children = pack.getChildren(); ++ var packs = children == null ? List.of(pack) : children; ++ for (final PackResources packresources : packs) { + IoSupplier iosupplier = packresources.getResource(this.type, p_215367_); + if (iosupplier != null) { + IoSupplier iosupplier1; +@@ -118,6 +_,7 @@ + } - list.add(new Resource(packresources, iosupplier, iosupplier1)); -+ } + list.add(new Resource(packresources, iosupplier, iosupplier1)); ++ } + } } - } diff --git a/patches/minecraft/net/minecraft/server/packs/resources/ReloadableResourceManager.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/ReloadableResourceManager.java.patch index 489a4f2393..ab858a6705 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/ReloadableResourceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/ReloadableResourceManager.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/server/packs/resources/ReloadableResourceManager.java +++ b/net/minecraft/server/packs/resources/ReloadableResourceManager.java -@@ -68,4 +_,10 @@ - public Stream listPacks() { - return this.resources.listPacks(); - } +@@ -73,4 +_,10 @@ + public Stream listPacks() { + return this.resources.listPacks(); + } + -+ public void registerReloadListenerIfNotPresent(PreparableReloadListener listener) { -+ if (!this.listeners.contains(listener)) { -+ this.registerReloadListener(listener); -+ } -+ } ++ public void registerReloadListenerIfNotPresent(PreparableReloadListener listener) { ++ if (!this.listeners.contains(listener)) { ++ this.registerReloadListener(listener); ++ } ++ } } diff --git a/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch index 31e01928df..00214f465c 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java +++ b/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java @@ -49,4 +_,8 @@ - } - - } + } + } + } + -+ protected ResourceLocation getPreparedPath(ResourceLocation rl) { -+ return rl.withPath(this.directory + "/" + rl.getPath() + ".json"); -+ } ++ protected ResourceLocation getPreparedPath(ResourceLocation rl) { ++ return rl.withPath(this.directory + "/" + rl.getPath() + ".json"); ++ } } diff --git a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch index 94d1b23124..6b2d6f3142 100644 --- a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch +++ b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch @@ -1,105 +1,97 @@ --- a/net/minecraft/server/players/PlayerList.java +++ b/net/minecraft/server/players/PlayerList.java -@@ -126,6 +_,7 @@ - private boolean allowCheatsForAllPlayers; - private static final boolean ALLOW_LOGOUTIVATOR = false; - private int sendAllPlayerInfoIn; -+ private final List playersView = java.util.Collections.unmodifiableList(players); +@@ -128,6 +_,7 @@ + private boolean allowCommandsForAllPlayers; + private static final boolean ALLOW_LOGOUTIVATOR = false; + private int sendAllPlayerInfoIn; ++ private final List playersView = java.util.Collections.unmodifiableList(players); - public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess p_251844_, PlayerDataStorage p_203844_, int p_203845_) { - this.server = p_203842_; -@@ -171,6 +_,7 @@ - servergamepacketlistenerimpl.send(new ClientboundChangeDifficultyPacket(leveldata.getDifficulty(), leveldata.isDifficultyLocked())); - servergamepacketlistenerimpl.send(new ClientboundPlayerAbilitiesPacket(p_11263_.getAbilities())); - servergamepacketlistenerimpl.send(new ClientboundSetCarriedItemPacket(p_11263_.getInventory().selected)); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, p_11263_)); - servergamepacketlistenerimpl.send(new ClientboundUpdateRecipesPacket(this.server.getRecipeManager().getRecipes())); - this.sendPlayerPermissionLevel(p_11263_); - p_11263_.getStats().markAllDirty(); -@@ -239,6 +_,7 @@ - } + public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess p_251844_, PlayerDataStorage p_203844_, int p_203845_) { + this.server = p_203842_; +@@ -267,6 +_,7 @@ + } - p_11263_.initInventoryMenu(); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedIn( p_11263_ ); - } + p_11263_.initInventoryMenu(); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedIn(p_11263_); + } - protected void updateEntireScoreboard(ServerScoreboard p_11274_, ServerPlayer p_11275_) { -@@ -299,6 +_,7 @@ - compoundtag1 = compoundtag; - p_11225_.load(compoundtag); - LOGGER.debug("loading single player"); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(p_11225_, this.playerIo, p_11225_.getUUID().toString()); - } else { - compoundtag1 = this.playerIo.load(p_11225_); - } -@@ -307,6 +_,7 @@ - } + protected void updateEntireScoreboard(ServerScoreboard p_11274_, ServerPlayer p_11275_) { +@@ -332,6 +_,7 @@ + optional = Optional.of(compoundtag); + p_11225_.load(compoundtag); + LOGGER.debug("loading single player"); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(p_11225_, this.playerIo, p_11225_.getUUID().toString()); + } else { + optional = this.playerIo.load(p_11225_); + } +@@ -340,6 +_,7 @@ + } - protected void save(ServerPlayer p_11277_) { -+ if (p_11277_.connection == null) return; - this.playerIo.save(p_11277_); - ServerStatsCounter serverstatscounter = this.stats.get(p_11277_.getUUID()); - if (serverstatscounter != null) { -@@ -321,6 +_,7 @@ - } + protected void save(ServerPlayer p_11277_) { ++ if (p_11277_.connection == null) return; // Not sure if still needed -Paint_Ninja + this.playerIo.save(p_11277_); + ServerStatsCounter serverstatscounter = this.stats.get(p_11277_.getUUID()); + if (serverstatscounter != null) { +@@ -353,6 +_,7 @@ + } - public void remove(ServerPlayer p_11287_) { -+ net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedOut(p_11287_); - ServerLevel serverlevel = p_11287_.serverLevel(); - p_11287_.awardStat(Stats.LEAVE_GAME); - this.save(p_11287_); -@@ -466,6 +_,7 @@ - this.playersByUUID.put(serverplayer.getUUID(), serverplayer); - serverplayer.initInventoryMenu(); - serverplayer.setHealth(serverplayer.getHealth()); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(serverplayer, p_11238_); - if (flag2) { - serverplayer.connection.send(new ClientboundSoundPacket(SoundEvents.RESPAWN_ANCHOR_DEPLETE, SoundSource.BLOCKS, (double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), 1.0F, 1.0F, serverlevel1.getRandom().nextLong())); - } -@@ -550,6 +_,7 @@ - } + public void remove(ServerPlayer p_11287_) { ++ net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedOut(p_11287_); + ServerLevel serverlevel = p_11287_.serverLevel(); + p_11287_.awardStat(Stats.LEAVE_GAME); + this.save(p_11287_); +@@ -497,6 +_,7 @@ + this.playersByUUID.put(serverplayer.getUUID(), serverplayer); + serverplayer.initInventoryMenu(); + serverplayer.setHealth(serverplayer.getHealth()); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(serverplayer, p_11238_); + if (flag2) { + serverplayer.connection + .send( +@@ -588,6 +_,7 @@ + } - public void op(GameProfile p_11254_) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(p_11254_, this.server.getOperatorUserPermissionLevel(), this)) return; - this.ops.add(new ServerOpListEntry(p_11254_, this.server.getOperatorUserPermissionLevel(), this.ops.canBypassPlayerLimit(p_11254_))); - ServerPlayer serverplayer = this.getPlayer(p_11254_.getId()); - if (serverplayer != null) { -@@ -559,6 +_,7 @@ - } + public void op(GameProfile p_11254_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(p_11254_, this.server.getOperatorUserPermissionLevel(), this)) return; + this.ops.add(new ServerOpListEntry(p_11254_, this.server.getOperatorUserPermissionLevel(), this.ops.canBypassPlayerLimit(p_11254_))); + ServerPlayer serverplayer = this.getPlayer(p_11254_.getId()); + if (serverplayer != null) { +@@ -596,6 +_,7 @@ + } - public void deop(GameProfile p_11281_) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(p_11281_, 0, this)) return; - this.ops.remove(p_11281_); - ServerPlayer serverplayer = this.getPlayer(p_11281_.getId()); - if (serverplayer != null) { -@@ -778,13 +_,6 @@ - if (serverstatscounter == null) { - File file1 = this.server.getWorldPath(LevelResource.PLAYER_STATS_DIR).toFile(); - File file2 = new File(file1, uuid + ".json"); -- if (!file2.exists()) { -- File file3 = new File(file1, p_11240_.getName().getString() + ".json"); -- Path path = file3.toPath(); -- if (FileUtil.isPathNormalized(path) && FileUtil.isPathPortable(path) && path.startsWith(file1.getPath()) && file3.isFile()) { -- file3.renameTo(file2); + public void deop(GameProfile p_11281_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(p_11281_, 0, this)) return; + this.ops.remove(p_11281_); + ServerPlayer serverplayer = this.getPlayer(p_11281_.getId()); + if (serverplayer != null) { +@@ -809,13 +_,6 @@ + if (serverstatscounter == null) { + File file1 = this.server.getWorldPath(LevelResource.PLAYER_STATS_DIR).toFile(); + File file2 = new File(file1, uuid + ".json"); +- if (!file2.exists()) { +- File file3 = new File(file1, p_11240_.getName().getString() + ".json"); +- Path path = file3.toPath(); +- if (FileUtil.isPathNormalized(path) && FileUtil.isPathPortable(path) && path.startsWith(file1.getPath()) && file3.isFile()) { +- file3.renameTo(file2); +- } - } -- } - serverstatscounter = new ServerStatsCounter(this.server, file2); - this.stats.put(uuid, serverstatscounter); -@@ -831,7 +_,7 @@ - } + serverstatscounter = new ServerStatsCounter(this.server, file2); + this.stats.put(uuid, serverstatscounter); +@@ -860,7 +_,7 @@ + } - public List getPlayers() { -- return this.players; -+ return this.playersView; //Unmodifiable view, we don't want people removing things without us knowing. - } + public List getPlayers() { +- return this.players; ++ return this.playersView; //Unmodifiable view, we don't want people removing things without us knowing. + } - @Nullable -@@ -848,6 +_,7 @@ - playeradvancements.reload(this.server.getAdvancements()); - } + @Nullable +@@ -877,6 +_,7 @@ + playeradvancements.reload(this.server.getAdvancements()); + } -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, null)); - this.broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.registries))); - ClientboundUpdateRecipesPacket clientboundupdaterecipespacket = new ClientboundUpdateRecipesPacket(this.server.getRecipeManager().getRecipes()); ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, null)); + this.broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.registries))); + ClientboundUpdateRecipesPacket clientboundupdaterecipespacket = new ClientboundUpdateRecipesPacket(this.server.getRecipeManager().getOrderedRecipes()); diff --git a/patches/minecraft/net/minecraft/server/rcon/RconConsoleSource.java.patch b/patches/minecraft/net/minecraft/server/rcon/RconConsoleSource.java.patch index 36c22456ee..7f77373c9b 100644 --- a/patches/minecraft/net/minecraft/server/rcon/RconConsoleSource.java.patch +++ b/patches/minecraft/net/minecraft/server/rcon/RconConsoleSource.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/rcon/RconConsoleSource.java +++ b/net/minecraft/server/rcon/RconConsoleSource.java @@ -33,7 +_,7 @@ - } - public void sendSystemMessage(Component p_215653_) { -- this.buffer.append(p_215653_.getString()); -+ this.buffer.append(p_215653_.getString()).append("\n"); // FIX MC-7569 - RCON has no newlines in multiline output - } + @Override + public void sendSystemMessage(Component p_215653_) { +- this.buffer.append(p_215653_.getString()); ++ this.buffer.append(p_215653_.getString()).append("\n"); // FIX MC-7569 - RCON has no newlines in multiline output + } - public boolean acceptsSuccess() { + @Override diff --git a/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch b/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch index 3f31ef39d1..a55e85704e 100644 --- a/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch +++ b/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/server/rcon/thread/RconClient.java +++ b/net/minecraft/server/rcon/thread/RconClient.java -@@ -123,13 +_,14 @@ - } +@@ -123,14 +_,11 @@ + } - private void sendCmdResponse(int p_11595_, String p_11596_) throws IOException { -- int i = p_11596_.length(); + private void sendCmdResponse(int p_11595_, String p_11596_) throws IOException { +- int i = p_11596_.length(); - -+ byte[] whole = p_11596_.getBytes(StandardCharsets.UTF_8); -+ int i = whole.length; -+ int start = 0; - do { - int j = 4096 <= i ? 4096 : i; -- this.send(p_11595_, 0, p_11596_.substring(0, j)); -- p_11596_ = p_11596_.substring(j); -- i = p_11596_.length(); -+ this.send(p_11595_, 0, new String(java.util.Arrays.copyOfRange(whole, start, j+start), StandardCharsets.UTF_8)); -+ i -= j; -+ start += j; - } while(0 != i); +- do { +- int j = 4096 <= i ? 4096 : i; +- this.send(p_11595_, 0, p_11596_.substring(0, j)); +- p_11596_ = p_11596_.substring(j); +- i = p_11596_.length(); +- } while (0 != i); ++ // Forge: Actually convert to UTF8 and process bytes accordingly. Why do we do this? UTF8 should be single byte per character ++ byte[] data = p_11596_.getBytes(StandardCharsets.UTF_8); ++ for (int x = 0; x < data.length; x += 4096) { ++ this.send(p_11595_, 0, new String(data, x, Math.min(4096, data.length - x), StandardCharsets.UTF_8)); ++ } + } - } + @Override diff --git a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch index d2062cf62e..dbf7d65162 100644 --- a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch +++ b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch @@ -1,21 +1,31 @@ --- a/net/minecraft/stats/RecipeBookSettings.java +++ b/net/minecraft/stats/RecipeBookSettings.java -@@ -10,7 +_,7 @@ +@@ -11,7 +_,7 @@ import net.minecraft.world.inventory.RecipeBookType; public final class RecipeBookSettings { -- private static final Map> TAG_FIELDS = ImmutableMap.of(RecipeBookType.CRAFTING, Pair.of("isGuiOpen", "isFilteringCraftable"), RecipeBookType.FURNACE, Pair.of("isFurnaceGuiOpen", "isFurnaceFilteringCraftable"), RecipeBookType.BLAST_FURNACE, Pair.of("isBlastingFurnaceGuiOpen", "isBlastingFurnaceFilteringCraftable"), RecipeBookType.SMOKER, Pair.of("isSmokerGuiOpen", "isSmokerFilteringCraftable")); -+ private static final Map> TAG_FIELDS = new java.util.HashMap<>(ImmutableMap.of(RecipeBookType.CRAFTING, Pair.of("isGuiOpen", "isFilteringCraftable"), RecipeBookType.FURNACE, Pair.of("isFurnaceGuiOpen", "isFurnaceFilteringCraftable"), RecipeBookType.BLAST_FURNACE, Pair.of("isBlastingFurnaceGuiOpen", "isBlastingFurnaceFilteringCraftable"), RecipeBookType.SMOKER, Pair.of("isSmokerGuiOpen", "isSmokerFilteringCraftable"))); - private final Map states; +- private static final Map> TAG_FIELDS = ImmutableMap.of( ++ private static final Map> TAG_FIELDS = new java.util.HashMap<>(ImmutableMap.of( + RecipeBookType.CRAFTING, + Pair.of("isGuiOpen", "isFilteringCraftable"), + RecipeBookType.FURNACE, +@@ -20,7 +_,7 @@ + Pair.of("isBlastingFurnaceGuiOpen", "isBlastingFurnaceFilteringCraftable"), + RecipeBookType.SMOKER, + Pair.of("isSmokerGuiOpen", "isSmokerFilteringCraftable") +- ); ++ )); + private final Map states; - private RecipeBookSettings(Map p_12730_) { -@@ -147,5 +_,9 @@ - public String toString() { - return "[open=" + this.open + ", filtering=" + this.filtering + "]"; - } -+ } -+ //FORGE -- called automatically on Enum creation - used for serialization -+ public static void addTagsForType(RecipeBookType type, String openTag, String filteringTag) { -+ TAG_FIELDS.put(type, Pair.of(openTag, filteringTag)); - } + private RecipeBookSettings(Map p_12730_) { +@@ -158,5 +_,10 @@ + public String toString() { + return "[open=" + this.open + ", filtering=" + this.filtering + "]"; + } ++ } ++ ++ // FORGE -- called automatically on Enum creation - used for serialization ++ public static void addTagsForType(RecipeBookType type, String openTag, String filteringTag) { ++ TAG_FIELDS.put(type, Pair.of(openTag, filteringTag)); + } } diff --git a/patches/minecraft/net/minecraft/tags/BlockTags.java.patch b/patches/minecraft/net/minecraft/tags/BlockTags.java.patch index 907ac48020..0d9202d3c3 100644 --- a/patches/minecraft/net/minecraft/tags/BlockTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/BlockTags.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/tags/BlockTags.java +++ b/net/minecraft/tags/BlockTags.java -@@ -184,4 +_,8 @@ - private static TagKey create(String p_203847_) { - return TagKey.create(Registries.BLOCK, new ResourceLocation(p_203847_)); - } +@@ -194,4 +_,8 @@ + private static TagKey create(String p_203847_) { + return TagKey.create(Registries.BLOCK, new ResourceLocation(p_203847_)); + } + -+ public static TagKey create(ResourceLocation name) { -+ return TagKey.create(Registries.BLOCK, name); -+ } ++ public static TagKey create(ResourceLocation name) { ++ return TagKey.create(Registries.BLOCK, name); ++ } } diff --git a/patches/minecraft/net/minecraft/tags/FluidTags.java.patch b/patches/minecraft/net/minecraft/tags/FluidTags.java.patch index c4064c048e..7d847752c0 100644 --- a/patches/minecraft/net/minecraft/tags/FluidTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/FluidTags.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/tags/FluidTags.java +++ b/net/minecraft/tags/FluidTags.java @@ -14,4 +_,8 @@ - private static TagKey create(String p_203851_) { - return TagKey.create(Registries.FLUID, new ResourceLocation(p_203851_)); - } + private static TagKey create(String p_203851_) { + return TagKey.create(Registries.FLUID, new ResourceLocation(p_203851_)); + } + -+ public static TagKey create(ResourceLocation name) { -+ return TagKey.create(Registries.FLUID, name); -+ } ++ public static TagKey create(ResourceLocation name) { ++ return TagKey.create(Registries.FLUID, name); ++ } } diff --git a/patches/minecraft/net/minecraft/tags/ItemTags.java.patch b/patches/minecraft/net/minecraft/tags/ItemTags.java.patch index 12788d42e2..e9d95e3236 100644 --- a/patches/minecraft/net/minecraft/tags/ItemTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/ItemTags.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/tags/ItemTags.java +++ b/net/minecraft/tags/ItemTags.java -@@ -111,4 +_,8 @@ - private static TagKey bind(String p_203855_) { - return TagKey.create(Registries.ITEM, new ResourceLocation(p_203855_)); - } +@@ -160,4 +_,8 @@ + private static TagKey bind(String p_203855_) { + return TagKey.create(Registries.ITEM, new ResourceLocation(p_203855_)); + } + -+ public static TagKey create(final ResourceLocation name) { -+ return TagKey.create(Registries.ITEM, name); -+ } ++ public static TagKey create(final ResourceLocation name) { ++ return TagKey.create(Registries.ITEM, name); ++ } } diff --git a/patches/minecraft/net/minecraft/tags/TagBuilder.java.patch b/patches/minecraft/net/minecraft/tags/TagBuilder.java.patch index 1a4a78df5e..93a23dc3fe 100644 --- a/patches/minecraft/net/minecraft/tags/TagBuilder.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagBuilder.java.patch @@ -1,43 +1,43 @@ --- a/net/minecraft/tags/TagBuilder.java +++ b/net/minecraft/tags/TagBuilder.java -@@ -4,7 +_,17 @@ +@@ -4,7 +_,7 @@ import java.util.List; import net.minecraft.resources.ResourceLocation; -public class TagBuilder { +public class TagBuilder implements net.minecraftforge.common.extensions.IForgeRawTagBuilder { -+ // FORGE: Remove entries are used for datagen. -+ private final List removeEntries = new ArrayList<>(); -+ public java.util.stream.Stream getRemoveEntries() { return this.removeEntries.stream(); } -+ // FORGE: Add an entry to be removed from this tag in datagen. -+ public TagBuilder remove(final TagEntry entry) { -+ this.removeEntries.add(entry); -+ return this; -+ } -+ // FORGE: is this tag set to replace or not? -+ private boolean replace = false; - private final List entries = new ArrayList<>(); + private final List entries = new ArrayList<>(); - public static TagBuilder create() { -@@ -34,5 +_,21 @@ + public static TagBuilder create() { +@@ -34,5 +_,31 @@ - public TagBuilder addOptionalTag(ResourceLocation p_215910_) { - return this.add(TagEntry.optionalTag(p_215910_)); -+ } + public TagBuilder addOptionalTag(ResourceLocation p_215910_) { + return this.add(TagEntry.optionalTag(p_215910_)); ++ } + -+ // FORGE: Set the replace property of this tag. -+ public TagBuilder replace(boolean value) { -+ this.replace = value; -+ return this; -+ } ++ // Forge start ++ /** Forge: Used for datagen */ ++ private final List removeEntries = new ArrayList<>(); ++ private boolean replace = false; + -+ // FORGE: Shorthand version of replace(true) -+ public TagBuilder replace() { -+ return replace(true); -+ } ++ public java.util.stream.Stream getRemoveEntries() { // should this return the List instead? Might end up with mem leaks from unterminated streams otherwise -Paint_Ninja ++ return this.removeEntries.stream(); ++ } + -+ // FORGE: Is this tag set to replace or not? -+ public boolean isReplace() { -+ return this.replace; - } ++ /** Forge: Add an entry to be removed from this tag in datagen */ ++ public TagBuilder remove(TagEntry entry) { ++ this.removeEntries.add(entry); ++ return this; ++ } ++ ++ /** Forge: Set the replace property of this tag */ ++ public TagBuilder replace(boolean value) { ++ this.replace = value; ++ return this; ++ } ++ ++ /** Forge: Is this tag set to replace or not? */ ++ public boolean isReplace() { ++ return this.replace; + } } diff --git a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch index f0d1482ea4..0519e7f3df 100644 --- a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/tags/TagEntry.java +++ b/net/minecraft/tags/TagEntry.java -@@ -113,6 +_,18 @@ - return stringbuilder.toString(); - } +@@ -111,6 +_,18 @@ + return stringbuilder.toString(); + } -+ public ResourceLocation getId() { -+ return id; -+ } ++ public ResourceLocation getId() { ++ return id; ++ } + -+ public boolean isRequired() { -+ return required; -+ } ++ public boolean isRequired() { ++ return required; ++ } + -+ public boolean isTag() { -+ return tag; -+ } ++ public boolean isTag() { ++ return tag; ++ } + - public interface Lookup { - @Nullable - T element(ResourceLocation p_215956_); + public interface Lookup { + @Nullable + T element(ResourceLocation p_215956_); diff --git a/patches/minecraft/net/minecraft/tags/TagFile.java.patch b/patches/minecraft/net/minecraft/tags/TagFile.java.patch index 78246ee5a1..4076757e7c 100644 --- a/patches/minecraft/net/minecraft/tags/TagFile.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagFile.java.patch @@ -1,17 +1,22 @@ --- a/net/minecraft/tags/TagFile.java +++ b/net/minecraft/tags/TagFile.java -@@ -4,8 +_,12 @@ - import com.mojang.serialization.codecs.RecordCodecBuilder; +@@ -5,12 +_,17 @@ + import com.mojang.serialization.codecs.RecordCodecBuilder.Instance; import java.util.List; -public record TagFile(List entries, boolean replace) { +public record TagFile(List entries, boolean replace, List remove) { - public static final Codec CODEC = RecordCodecBuilder.create((p_215967_) -> { -- return p_215967_.group(TagEntry.CODEC.listOf().fieldOf("values").forGetter(TagFile::entries), Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::replace)).apply(p_215967_, TagFile::new); -+ return p_215967_.group(TagEntry.CODEC.listOf().fieldOf("values").forGetter(TagFile::entries), Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::replace), TagEntry.CODEC.listOf().optionalFieldOf("remove", List.of()).forGetter(TagFile::remove)).apply(p_215967_, TagFile::new); - }); + public static final Codec CODEC = RecordCodecBuilder.create( + p_215967_ -> p_215967_.group( + TagEntry.CODEC.listOf().fieldOf("values").forGetter(TagFile::entries), +- Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::replace) ++ Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::replace), ++ TagEntry.CODEC.listOf().optionalFieldOf("remove", List.of()).forGetter(TagFile::remove) + ) + .apply(p_215967_, TagFile::new) + ); + -+ public TagFile(List entries, boolean replace) { -+ this(entries, replace, List.of()); -+ } ++ public TagFile(List entries, boolean replace) { ++ this(entries, replace, List.of()); ++ } } diff --git a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch index 920bb0291f..d30dfc1f4f 100644 --- a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch @@ -1,50 +1,54 @@ --- a/net/minecraft/tags/TagLoader.java +++ b/net/minecraft/tags/TagLoader.java -@@ -59,6 +_,7 @@ - tagfile.entries().forEach((p_215997_) -> { - list.add(new TagLoader.EntryWithSource(p_215997_, s)); - }); -+ tagfile.remove().forEach(e -> list.add(new TagLoader.EntryWithSource(e, s, true))); - } catch (Exception exception) { - LOGGER.error("Couldn't read tag list {} from {} in data pack {}", resourcelocation1, resourcelocation, resource.sourcePackId(), exception); +@@ -57,6 +_,7 @@ + + String s = resource.sourcePackId(); + tagfile.entries().forEach(p_215997_ -> list.add(new TagLoader.EntryWithSource(p_215997_, s))); ++ tagfile.remove().forEach(e -> list.add(new TagLoader.EntryWithSource(e, s, true))); + } catch (Exception exception) { + LOGGER.error("Couldn't read tag list {} from {} in data pack {}", resourcelocation1, resourcelocation, resource.sourcePackId(), exception); + } +@@ -67,16 +_,18 @@ + } + + private Either, Collection> build(TagEntry.Lookup p_215979_, List p_215980_) { +- Builder builder = ImmutableSet.builder(); ++ var builder = new java.util.LinkedHashSet(); // Order is important, as ImmutableSet is ordered and some people rely on that. https://github.com/MinecraftForge/MinecraftForge/issues/9774 + List list = new ArrayList<>(); + + for (TagLoader.EntryWithSource tagloader$entrywithsource : p_215980_) { +- if (!tagloader$entrywithsource.entry().build(p_215979_, builder::add)) { ++ if (!tagloader$entrywithsource.entry().build(p_215979_, tagloader$entrywithsource.remove() ? builder::remove : builder::add)) { ++ if (!tagloader$entrywithsource.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added. ++ + list.add(tagloader$entrywithsource); } -@@ -69,16 +_,17 @@ - } + } - private Either, Collection> build(TagEntry.Lookup p_215979_, List p_215980_) { -- ImmutableSet.Builder builder = ImmutableSet.builder(); -+ var builder = new java.util.LinkedHashSet(); // Order is important, as ImmutableSet is ordered and some people rely on that. https://github.com/MinecraftForge/MinecraftForge/issues/9774 - List list = new ArrayList<>(); +- return list.isEmpty() ? Either.right(builder.build()) : Either.left(list); ++ return list.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(list); + } - for(TagLoader.EntryWithSource tagloader$entrywithsource : p_215980_) { -- if (!tagloader$entrywithsource.entry().build(p_215979_, builder::add)) { -+ if (!tagloader$entrywithsource.entry().build(p_215979_, tagloader$entrywithsource.remove() ? builder::remove : builder::add)) { -+ if (!tagloader$entrywithsource.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added. - list.add(tagloader$entrywithsource); - } - } + public Map> build(Map> p_203899_) { +@@ -104,7 +_,7 @@ + p_215977_ -> LOGGER.error( + "Couldn't load tag {} as it is missing following references: {}", + p_284682_, +- p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", ")) ++ p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", \n\t")) + ) + ) + .ifRight(p_216001_ -> map.put(p_284682_, (Collection)p_216001_)) +@@ -116,7 +_,11 @@ + return this.build(this.load(p_203901_)); + } -- return list.isEmpty() ? Either.right(builder.build()) : Either.left(list); -+ return list.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(list); - } - - public Map> build(Map> p_203899_) { -@@ -100,7 +_,7 @@ - }); - dependencysorter.orderByDependencies((p_284682_, p_284683_) -> { - this.build(lookup, p_284683_.entries).ifLeft((p_215977_) -> { -- LOGGER.error("Couldn't load tag {} as it is missing following references: {}", p_284682_, p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", "))); -+ LOGGER.error("Couldn't load tag {} as it is missing following references: {}", p_284682_, p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", \n\t"))); - }).ifRight((p_216001_) -> { - map.put(p_284682_, p_216001_); - }); -@@ -112,7 +_,8 @@ - return this.build(this.load(p_203901_)); - } - -- public static record EntryWithSource(TagEntry entry, String source) { -+ public static record EntryWithSource(TagEntry entry, String source, boolean remove) { -+ public EntryWithSource(TagEntry entry, String source) { this(entry, source, false); } - public String toString() { - return this.entry + " (from " + this.source + ")"; - } +- public static record EntryWithSource(TagEntry entry, String source) { ++ public static record EntryWithSource(TagEntry entry, String source, boolean remove) { ++ public EntryWithSource(TagEntry entry, String source) { ++ this(entry, source, false); ++ } ++ + @Override + public String toString() { + return this.entry + " (from " + this.source + ")"; diff --git a/patches/minecraft/net/minecraft/tags/TagManager.java.patch b/patches/minecraft/net/minecraft/tags/TagManager.java.patch index 613b4e1400..1f1666d0e2 100644 --- a/patches/minecraft/net/minecraft/tags/TagManager.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagManager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/tags/TagManager.java +++ b/net/minecraft/tags/TagManager.java -@@ -31,7 +_,7 @@ +@@ -42,7 +_,7 @@ - public static String getTagDir(ResourceKey> p_203919_) { - String s = CUSTOM_REGISTRY_DIRECTORIES.get(p_203919_); -- return s != null ? s : "tags/" + p_203919_.location().getPath(); -+ return s != null ? s : "tags/" + net.minecraftforge.common.ForgeHooks.prefixNamespace(p_203919_.location()); - } + public static String getTagDir(ResourceKey> p_203919_) { + String s = CUSTOM_REGISTRY_DIRECTORIES.get(p_203919_); +- return s != null ? s : "tags/" + p_203919_.location().getPath(); ++ return s != null ? s : "tags/" + net.minecraftforge.common.ForgeHooks.prefixNamespace(p_203919_.location()); + } - public CompletableFuture reload(PreparableReloadListener.PreparationBarrier p_13482_, ResourceManager p_13483_, ProfilerFiller p_13484_, ProfilerFiller p_13485_, Executor p_13486_, Executor p_13487_) { + @Override diff --git a/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch b/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch index d3cbacbef8..81f29753b8 100644 --- a/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch +++ b/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/util/SpawnUtil.java +++ b/net/minecraft/util/SpawnUtil.java -@@ -27,7 +_,7 @@ - if (p_216406_.getWorldBorder().isWithinBounds(blockpos$mutableblockpos) && moveToPossibleSpawnPosition(p_216406_, p_216410_, blockpos$mutableblockpos, p_216411_)) { - T t = p_216404_.create(p_216406_, (CompoundTag)null, (Consumer)null, blockpos$mutableblockpos, p_216405_, false, false); - if (t != null) { -- if (t.checkSpawnRules(p_216406_, p_216405_) && t.checkSpawnObstruction(p_216406_)) { -+ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(t, p_216406_, p_216405_)) { - p_216406_.addFreshEntityWithPassengers(t); - return Optional.of(t); - } +@@ -34,7 +_,7 @@ + if (p_216406_.getWorldBorder().isWithinBounds(blockpos$mutableblockpos) && moveToPossibleSpawnPosition(p_216406_, p_216410_, blockpos$mutableblockpos, p_216411_)) { + T t = (T)p_216404_.create(p_216406_, null, blockpos$mutableblockpos, p_216405_, false, false); + if (t != null) { +- if (t.checkSpawnRules(p_216406_, p_216405_) && t.checkSpawnObstruction(p_216406_)) { ++ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(t, p_216406_, p_216405_)) { + p_216406_.addFreshEntityWithPassengers(t); + return Optional.of(t); + } diff --git a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch index 800121934a..046f1724f1 100644 --- a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch +++ b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch @@ -1,13 +1,21 @@ --- a/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java +++ b/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java -@@ -92,7 +_,10 @@ - private Dynamic findUpdatedStructureType(Pair, Dynamic> p_207724_, Dynamic p_207725_) { - String s = p_207724_.getFirst().asString("UNKNOWN").toLowerCase(Locale.ROOT); - StructuresBecomeConfiguredFix.Conversion structuresbecomeconfiguredfix$conversion = CONVERSION_MAP.get(s); -+ if (structuresbecomeconfiguredfix$conversion == null) structuresbecomeconfiguredfix$conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(s); // Forge: hook for mods to register conversions through RegisterStructureConversionsEvent - if (structuresbecomeconfiguredfix$conversion == null) { -+ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(s)) return p_207724_.getSecond().createString(s); // Forge: pass-through structure IDs which have a non-"minecraft" namespace -+ if (true) return p_207724_.getSecond().createString("unknown." + s); // Forge: Pass-through with "unknown." prefix, so deserializer logs and ignores rather than fixer throwing an exception and dropping chunk data - throw new IllegalStateException("Found unknown structure: " + s); - } else { - Dynamic dynamic = p_207724_.getSecond(); +@@ -180,7 +_,17 @@ + String s = p_207725_.asString("UNKNOWN").toLowerCase(Locale.ROOT); + StructuresBecomeConfiguredFix.Conversion structuresbecomeconfiguredfix$conversion = CONVERSION_MAP.get(s); + if (structuresbecomeconfiguredfix$conversion == null) { +- return null; ++ // Forge: hook for mods to register conversions through RegisterStructureConversionsEvent ++ structuresbecomeconfiguredfix$conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(s); ++ } ++ if (structuresbecomeconfiguredfix$conversion == null) { ++ ++ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(s)) { ++ // Forge: pass-through structure IDs which have a non-"minecraft" namespace ++ return p_329413_.createString(s); ++ } ++ // Forge: Pass-through with "unknown." prefix, so deserializer logs and ignores rather than fixer throwing an exception and dropping chunk data ++ return p_329413_.createString("unknown." + s); + } else { + String s1 = structuresbecomeconfiguredfix$conversion.fallback; + if (!structuresbecomeconfiguredfix$conversion.biomeMapping().isEmpty()) { diff --git a/patches/minecraft/net/minecraft/util/datafix/schemas/V2832.java.patch b/patches/minecraft/net/minecraft/util/datafix/schemas/V2832.java.patch index 11a7d716ed..33101426bd 100644 --- a/patches/minecraft/net/minecraft/util/datafix/schemas/V2832.java.patch +++ b/patches/minecraft/net/minecraft/util/datafix/schemas/V2832.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/util/datafix/schemas/V2832.java +++ b/net/minecraft/util/datafix/schemas/V2832.java -@@ -22,7 +_,7 @@ - return DSL.constType(namespacedString()); - }); - p_185234_.registerType(false, References.WORLD_GEN_SETTINGS, () -> { -- return DSL.fields("dimensions", DSL.compoundList(DSL.constType(namespacedString()), DSL.fields("generator", DSL.taggedChoiceLazy("type", DSL.string(), ImmutableMap.of("minecraft:debug", DSL::remainder, "minecraft:flat", () -> { -+ return DSL.fields("dimensions", DSL.compoundList(DSL.constType(namespacedString()), DSL.fields("generator", DSL.or(DSL.taggedChoiceLazy("type", DSL.string(), ImmutableMap.of("minecraft:debug", DSL::remainder, "minecraft:flat", () -> { - return DSL.optionalFields("settings", DSL.optionalFields("biome", References.BIOME.in(p_185234_), "layers", DSL.list(DSL.optionalFields("block", References.BLOCK_NAME.in(p_185234_))))); - }, "minecraft:noise", () -> { - return DSL.optionalFields("biome_source", DSL.taggedChoiceLazy("type", DSL.string(), ImmutableMap.of("minecraft:fixed", () -> { -@@ -32,7 +_,7 @@ - }, "minecraft:checkerboard", () -> { - return DSL.fields("biomes", DSL.list(References.BIOME.in(p_185234_))); - }, "minecraft:the_end", DSL::remainder)), "settings", DSL.or(DSL.constType(DSL.string()), DSL.optionalFields("default_block", References.BLOCK_NAME.in(p_185234_), "default_fluid", References.BLOCK_NAME.in(p_185234_)))); -- }))))); -+ })), DSL.remainder())))); - }); - } - } +@@ -52,7 +_,7 @@ + DSL.constType(namespacedString()), + DSL.fields( + "generator", +- DSL.taggedChoiceLazy( ++ DSL.or(DSL.taggedChoiceLazy( + "type", + DSL.string(), + ImmutableMap.of( +@@ -97,7 +_,7 @@ + ) + ) + ) +- ) ++ ), DSL.remainder()) // Keep data if the generator type can't be found + ) + ) + ) diff --git a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch index 6f45eff1bb..6f7437b1f1 100644 --- a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch +++ b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch @@ -1,51 +1,55 @@ --- a/net/minecraft/world/effect/MobEffect.java +++ b/net/minecraft/world/effect/MobEffect.java -@@ -17,7 +_,7 @@ - import net.minecraft.world.entity.ai.attributes.AttributeMap; - import net.minecraft.world.entity.ai.attributes.AttributeModifier; +@@ -30,7 +_,7 @@ + import net.minecraft.world.flag.FeatureFlagSet; + import net.minecraft.world.flag.FeatureFlags; --public class MobEffect { -+public class MobEffect implements net.minecraftforge.common.extensions.IForgeMobEffect { - private final Map attributeModifiers = Maps.newHashMap(); - private final MobEffectCategory category; - private final int color; -@@ -31,6 +_,7 @@ - protected MobEffect(MobEffectCategory p_19451_, int p_19452_) { - this.category = p_19451_; - this.color = p_19452_; -+ initClient(); - } +-public class MobEffect implements FeatureElement { ++public class MobEffect implements FeatureElement, net.minecraftforge.common.extensions.IForgeMobEffect { + private static final int AMBIENT_ALPHA = Mth.floor(38.25F); + private final Map, MobEffect.AttributeTemplate> attributeModifiers = new Object2ObjectOpenHashMap<>(); + private final MobEffectCategory category; +@@ -49,12 +_,14 @@ + int i = p_326747_.isAmbient() ? AMBIENT_ALPHA : 255; + return ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, FastColor.ARGB32.color(i, p_19452_)); + }; ++ initClient(); + } - public Optional createFactorData() { -@@ -117,6 +_,31 @@ - public boolean isBeneficial() { - return this.category == MobEffectCategory.BENEFICIAL; - } -+ -+ // FORGE START -+ private Object effectRenderer; -+ -+ /* -+ DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE -+ Call RenderProperties.getEffectRenderer instead -+ */ -+ public Object getEffectRendererInternal() { -+ return effectRenderer; -+ } -+ -+ private void initClient() { -+ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen -+ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { -+ initializeClient(properties -> { -+ this.effectRenderer = properties; -+ }); -+ } -+ } -+ -+ public void initializeClient(java.util.function.Consumer consumer) { -+ } -+ // END FORGE -+ + protected MobEffect(MobEffectCategory p_335432_, int p_334901_, ParticleOptions p_331136_) { + this.category = p_335432_; + this.color = p_334901_; + this.particleFactory = p_326745_ -> p_331136_; ++ initClient(); + } - /** @deprecated */ - @Deprecated + public int getBlendDurationTicks() { +@@ -179,4 +_,28 @@ + return new AttributeModifier(this.id, p_331481_ + " " + p_332230_, this.amount * (double)(p_332230_ + 1), this.operation); + } + } ++ ++ // FORGE START ++ private Object effectRenderer; ++ ++ /* ++ DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE ++ Call RenderProperties.getEffectRenderer instead ++ */ ++ public Object getEffectRendererInternal() { ++ return effectRenderer; ++ } ++ ++ private void initClient() { ++ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen ++ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { ++ initializeClient(properties -> { ++ this.effectRenderer = properties; ++ }); ++ } ++ } ++ ++ public void initializeClient(java.util.function.Consumer consumer) { ++ } ++ // END FORGE + } diff --git a/patches/minecraft/net/minecraft/world/effect/MobEffectInstance.java.patch b/patches/minecraft/net/minecraft/world/effect/MobEffectInstance.java.patch deleted file mode 100644 index 0090f9a752..0000000000 --- a/patches/minecraft/net/minecraft/world/effect/MobEffectInstance.java.patch +++ /dev/null @@ -1,77 +0,0 @@ ---- a/net/minecraft/world/effect/MobEffectInstance.java -+++ b/net/minecraft/world/effect/MobEffectInstance.java -@@ -17,7 +_,7 @@ - import net.minecraft.world.entity.LivingEntity; - import org.slf4j.Logger; - --public class MobEffectInstance implements Comparable { -+public class MobEffectInstance implements Comparable, net.minecraftforge.common.extensions.IForgeMobEffectInstance { - private static final Logger LOGGER = LogUtils.getLogger(); - public static final int INFINITE_DURATION = -1; - private static final String TAG_ID = "id"; -@@ -85,6 +_,7 @@ - this.ambient = p_19549_.ambient; - this.visible = p_19549_.visible; - this.showIcon = p_19549_.showIcon; -+ this.curativeItems = p_19549_.curativeItems == null ? null : new java.util.ArrayList(p_19549_.curativeItems); - } - - public boolean update(MobEffectInstance p_19559_) { -@@ -149,7 +_,7 @@ - } - - public MobEffect getEffect() { -- return this.effect; -+ return this.effect == null ? null : net.minecraftforge.registries.ForgeRegistries.MOB_EFFECTS.getDelegateOrThrow(this.effect).get(); - } - - public int getDuration() { -@@ -274,6 +_,7 @@ - this.hiddenEffect.save(compoundtag); - p_19568_.put("hidden_effect", compoundtag); - } -+ writeCurativeItems(p_19568_); - - this.factorData.ifPresent((p_216903_) -> { - MobEffectInstance.FactorData.CODEC.encodeStart(NbtOps.INSTANCE, p_216903_).resultOrPartial(LOGGER::error).ifPresent((p_216906_) -> { -@@ -315,12 +_,38 @@ - optional = Optional.empty(); - } - -- return new MobEffectInstance(p_19546_, j, Math.max(i, 0), flag, flag1, flag2, mobeffectinstance, optional); -+ return readCurativeItems(new MobEffectInstance(p_19546_, j, Math.max(0, i), flag, flag1, flag2, mobeffectinstance, optional), p_19547_); - } - - public int compareTo(MobEffectInstance p_19566_) { - int i = 32147; -- return (this.getDuration() <= 32147 || p_19566_.getDuration() <= 32147) && (!this.isAmbient() || !p_19566_.isAmbient()) ? ComparisonChain.start().compareFalseFirst(this.isAmbient(), p_19566_.isAmbient()).compareFalseFirst(this.isInfiniteDuration(), p_19566_.isInfiniteDuration()).compare(this.getDuration(), p_19566_.getDuration()).compare(this.getEffect().getColor(), p_19566_.getEffect().getColor()).result() : ComparisonChain.start().compare(this.isAmbient(), p_19566_.isAmbient()).compare(this.getEffect().getColor(), p_19566_.getEffect().getColor()).result(); -+ return (this.getDuration() <= 32147 || p_19566_.getDuration() <= 32147) && (!this.isAmbient() || !p_19566_.isAmbient()) ? ComparisonChain.start().compareFalseFirst(this.isAmbient(), p_19566_.isAmbient()).compareFalseFirst(this.isInfiniteDuration(), p_19566_.isInfiniteDuration()).compare(this.getDuration(), p_19566_.getDuration()).compare(this.getEffect().getSortOrder(this), p_19566_.getEffect().getSortOrder(this)).result() : ComparisonChain.start().compare(this.isAmbient(), p_19566_.isAmbient()).compare(this.getEffect().getSortOrder(this), p_19566_.getEffect().getSortOrder(this)).result(); -+ } -+ -+ //======================= FORGE START =========================== -+ private java.util.List curativeItems; -+ -+ @Override -+ public java.util.List getCurativeItems() { -+ if (this.curativeItems == null) //Lazy load this so that we don't create a circular dep on Items. -+ this.curativeItems = getEffect().getCurativeItems(); -+ return this.curativeItems; -+ } -+ @Override -+ public void setCurativeItems(java.util.List curativeItems) { -+ this.curativeItems = curativeItems; -+ } -+ private static MobEffectInstance readCurativeItems(MobEffectInstance effect, CompoundTag nbt) { -+ if (nbt.contains("CurativeItems", net.minecraft.nbt.Tag.TAG_LIST)) { -+ java.util.List items = new java.util.ArrayList(); -+ net.minecraft.nbt.ListTag list = nbt.getList("CurativeItems", net.minecraft.nbt.Tag.TAG_COMPOUND); -+ for (int i = 0; i < list.size(); i++) { -+ items.add(net.minecraft.world.item.ItemStack.of(list.getCompound(i))); -+ } -+ effect.setCurativeItems(items); -+ } -+ -+ return effect; - } - - public static class FactorData { diff --git a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch index def6acc95b..4257ba92d5 100644 --- a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch @@ -1,643 +1,598 @@ --- a/net/minecraft/world/entity/Entity.java +++ b/net/minecraft/world/entity/Entity.java -@@ -123,7 +_,7 @@ - import org.joml.Vector3f; +@@ -126,7 +_,7 @@ + import net.minecraft.world.scores.Team; import org.slf4j.Logger; --public abstract class Entity implements Nameable, EntityAccess, CommandSource, ScoreHolder { -+public abstract class Entity extends net.minecraftforge.common.capabilities.CapabilityProvider implements Nameable, EntityAccess, CommandSource, ScoreHolder, net.minecraftforge.common.extensions.IForgeEntity { - private static final Logger LOGGER = LogUtils.getLogger(); - public static final String ID_TAG = "id"; - public static final String PASSENGERS_TAG = "Passengers"; -@@ -144,6 +_,7 @@ - private static final double LAVA_SLOW_FLOW_SCALE = 0.0023333333333333335D; - public static final String UUID_TAG = "UUID"; - private static double viewScale = 1.0D; -+ @Deprecated // Forge: Use the getter to allow overriding in mods - private final EntityType type; - private int id = ENTITY_COUNTER.incrementAndGet(); - public boolean blocksBuilding; -@@ -190,8 +_,10 @@ - public int tickCount; - private int remainingFireTicks = -this.getFireImmuneTicks(); - protected boolean wasTouchingWater; -+ @Deprecated // Forge: Use forgeFluidTypeHeight instead - protected Object2DoubleMap> fluidHeight = new Object2DoubleArrayMap<>(2); - protected boolean wasEyeInWater; -+ @Deprecated // Forge: Use forgeFluidTypeOnEyes instead - private final Set> fluidOnEyes = new HashSet<>(); - public int invulnerableTime; - protected boolean firstTick = true; -@@ -240,6 +_,7 @@ - private BlockState feetBlockState = null; +-public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess, CommandSource, ScoreHolder { ++public abstract class Entity extends net.minecraftforge.common.capabilities.CapabilityProvider implements SyncedDataHolder, Nameable, EntityAccess, CommandSource, ScoreHolder, net.minecraftforge.common.extensions.IForgeEntity { + private static final Logger LOGGER = LogUtils.getLogger(); + public static final String ID_TAG = "id"; + public static final String PASSENGERS_TAG = "Passengers"; +@@ -147,6 +_,7 @@ + private static final double LAVA_SLOW_FLOW_SCALE = 0.0023333333333333335; + public static final String UUID_TAG = "UUID"; + private static double viewScale = 1.0; ++ @Deprecated // Forge: Use the getter to allow overriding in mods + private final EntityType type; + private int id = ENTITY_COUNTER.incrementAndGet(); + public boolean blocksBuilding; +@@ -192,8 +_,10 @@ + public int tickCount; + private int remainingFireTicks = -this.getFireImmuneTicks(); + protected boolean wasTouchingWater; ++ @Deprecated // Forge: Use forgeFluidTypeHeight instead + protected Object2DoubleMap> fluidHeight = new Object2DoubleArrayMap<>(2); + protected boolean wasEyeInWater; ++ @Deprecated // Forge: Use forgeFluidTypeOnEyes instead + private final Set> fluidOnEyes = new HashSet<>(); + public int invulnerableTime; + protected boolean firstTick = true; +@@ -242,6 +_,7 @@ + private BlockState inBlockState = null; - public Entity(EntityType p_19870_, Level p_19871_) { -+ super(Entity.class); - this.type = p_19870_; - this.level = p_19871_; - this.dimensions = p_19870_.getDimensions(); -@@ -258,6 +_,8 @@ - this.defineSynchedData(); - this.setPos(0.0D, 0.0D, 0.0D); - this.eyeHeight = this.getEyeHeight(Pose.STANDING, this.dimensions); -+ net.minecraftforge.event.ForgeEventFactory.onEntityConstructing(this); -+ this.gatherCapabilities(); - } + public Entity(EntityType p_19870_, Level p_19871_) { ++ super(Entity.class); + this.type = p_19870_; + this.level = p_19871_; + this.dimensions = p_19870_.getDimensions(); +@@ -261,6 +_,8 @@ + this.entityData = synchedentitydata$builder.build(); + this.setPos(0.0, 0.0, 0.0); + this.eyeHeight = this.dimensions.eyeHeight(); ++ net.minecraftforge.event.ForgeEventFactory.onEntityConstructing(this); ++ this.gatherCapabilities(); + } - public boolean isColliding(BlockPos p_20040_, BlockState p_20041_) { -@@ -347,6 +_,7 @@ + public boolean isColliding(BlockPos p_20040_, BlockState p_20041_) { +@@ -348,6 +_,7 @@ - public void remove(Entity.RemovalReason p_146834_) { - this.setRemoved(p_146834_); -+ this.invalidateCaps(); - } + public void remove(Entity.RemovalReason p_146834_) { + this.setRemoved(p_146834_); ++ this.invalidateCaps(); + } - public void onClientRemoval() { + public void onClientRemoval() { @@ -464,7 +_,7 @@ - if (this.isInLava()) { - this.lavaHurt(); -- this.fallDistance *= 0.5F; -+ this.fallDistance *= this.getFluidFallDistanceModifier(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); - } + if (this.isInLava()) { + this.lavaHurt(); +- this.fallDistance *= 0.5F; ++ this.fallDistance *= this.getFluidFallDistanceModifier(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); + } - this.checkBelowWorld(); -@@ -675,7 +_,7 @@ - double d1 = vec3.x; - double d2 = vec3.y; - double d3 = vec3.z; -- this.flyDist += (float)(vec3.length() * 0.6D); -+ this.flyDist = (float)((double)this.flyDist + vec3.length() * 0.6D); - BlockPos blockpos1 = this.getOnPos(); - BlockState blockstate1 = this.level().getBlockState(blockpos1); - boolean flag1 = this.isStateClimbable(blockstate1); -@@ -719,16 +_,16 @@ - this.setRemainingFireTicks(-this.getFireImmuneTicks()); - } + this.checkBelowWorld(); +@@ -672,7 +_,7 @@ + double d1 = vec3.x; + double d2 = vec3.y; + double d3 = vec3.z; +- this.flyDist = this.flyDist + (float)(vec3.length() * 0.6); ++ this.flyDist = (float)((double)this.flyDist + vec3.length() * 0.6D); + BlockPos blockpos1 = this.getOnPos(); + BlockState blockstate1 = this.level().getBlockState(blockpos1); + boolean flag1 = this.isStateClimbable(blockstate1); +@@ -716,12 +_,12 @@ + this.setRemainingFireTicks(-this.getFireImmuneTicks()); + } -- if (this.wasOnFire && (this.isInPowderSnow || this.isInWaterRainOrBubble())) { -+ if (this.wasOnFire && (this.isInPowderSnow || this.isInWaterRainOrBubble() || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { - this.playEntityOnFireExtinguishedSound(); - } +- if (this.wasOnFire && (this.isInPowderSnow || this.isInWaterRainOrBubble())) { ++ if (this.wasOnFire && (this.isInPowderSnow || this.isInWaterRainOrBubble() || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { + this.playEntityOnFireExtinguishedSound(); + } + } + +- if (this.isOnFire() && (this.isInPowderSnow || this.isInWaterRainOrBubble())) { ++ if (this.isOnFire() && (this.isInPowderSnow || this.isInWaterRainOrBubble() || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { + this.setRemainingFireTicks(-this.getFireImmuneTicks()); + } + +@@ -811,9 +_,7 @@ + return blockpos; + } else { + BlockState blockstate = this.level().getBlockState(blockpos); +- return (!((double)p_216987_ <= 0.5) || !blockstate.is(BlockTags.FENCES)) +- && !blockstate.is(BlockTags.WALLS) +- && !(blockstate.getBlock() instanceof FenceGateBlock) ++ return (!((double)p_216987_ <= 0.5) || !blockstate.collisionExtendsVertically(this.level(), blockpos, this)) + ? blockpos.atY(Mth.floor(this.position.y - (double)p_216987_)) + : blockpos; } +@@ -1041,19 +_,19 @@ + return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? p_278049_ : blockpos; + } -- if (this.isOnFire() && (this.isInPowderSnow || this.isInWaterRainOrBubble())) { -+ if (this.isOnFire() && (this.isInPowderSnow || this.isInWaterRainOrBubble() || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { - this.setRemainingFireTicks(-this.getFireImmuneTicks()); - } +- protected void playCombinationStepSounds(BlockState p_277472_, BlockState p_277630_) { +- SoundType soundtype = p_277472_.getSoundType(); ++ protected void playCombinationStepSounds(BlockState p_277472_, BlockState p_277630_, BlockPos primaryPos, BlockPos secondaryPos) { ++ SoundType soundtype = p_277472_.getSoundType(this.level(), primaryPos, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); +- this.playMuffledStepSound(p_277630_); ++ this.playMuffledStepSound(p_277630_, secondaryPos); + } -- this.level().getProfiler().pop(); -+ this.level.getProfiler().pop(); - } - } - } -@@ -816,7 +_,7 @@ - return blockpos; - } else { - BlockState blockstate = this.level().getBlockState(blockpos); -- return (!((double)p_216987_ <= 0.5D) || !blockstate.is(BlockTags.FENCES)) && !blockstate.is(BlockTags.WALLS) && !(blockstate.getBlock() instanceof FenceGateBlock) ? blockpos.atY(Mth.floor(this.position.y - (double)p_216987_)) : blockpos; -+ return (!((double)p_216987_ <= 0.5D) || !blockstate.collisionExtendsVertically(this.level(), blockpos, this)) ? blockpos.atY(Mth.floor(this.position.y - (double)p_216987_)) : blockpos; - } - } else { - int i = Mth.floor(this.position.x); -@@ -887,10 +_,11 @@ - boolean flag1 = p_20273_.y != vec3.y; - boolean flag2 = p_20273_.z != vec3.z; - boolean flag3 = this.onGround() || flag1 && p_20273_.y < 0.0D; -- if (this.maxUpStep() > 0.0F && flag3 && (flag || flag2)) { -- Vec3 vec31 = collideBoundingBox(this, new Vec3(p_20273_.x, (double)this.maxUpStep(), p_20273_.z), aabb, this.level(), list); -- Vec3 vec32 = collideBoundingBox(this, new Vec3(0.0D, (double)this.maxUpStep(), 0.0D), aabb.expandTowards(p_20273_.x, 0.0D, p_20273_.z), this.level(), list); -- if (vec32.y < (double)this.maxUpStep()) { -+ float stepHeight = getStepHeight(); -+ if (stepHeight > 0.0F && flag3 && (flag || flag2)) { -+ Vec3 vec31 = collideBoundingBox(this, new Vec3(p_20273_.x, (double)stepHeight, p_20273_.z), aabb, this.level, list); -+ Vec3 vec32 = collideBoundingBox(this, new Vec3(0.0D, (double)stepHeight, 0.0D), aabb.expandTowards(p_20273_.x, 0.0D, p_20273_.z), this.level, list); -+ if (vec32.y < (double)stepHeight) { - Vec3 vec33 = collideBoundingBox(this, new Vec3(p_20273_.x, 0.0D, p_20273_.z), aabb.move(vec32), this.level(), list).add(vec32); - if (vec33.horizontalDistanceSqr() > vec31.horizontalDistanceSqr()) { - vec31 = vec33; -@@ -1040,19 +_,20 @@ - return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? p_278049_ : blockpos; - } +- protected void playMuffledStepSound(BlockState p_283110_) { +- SoundType soundtype = p_283110_.getSoundType(); ++ protected void playMuffledStepSound(BlockState p_283110_, BlockPos pos) { ++ SoundType soundtype = p_283110_.getSoundType(this.level(), pos, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.05F, soundtype.getPitch() * 0.8F); + } -- protected void playCombinationStepSounds(BlockState p_277472_, BlockState p_277630_) { -- SoundType soundtype = p_277472_.getSoundType(); -+ protected void playCombinationStepSounds(BlockState p_277472_, BlockState p_277630_, BlockPos primaryPos, BlockPos secondaryPos) { -+ SoundType soundtype = p_277472_.getSoundType(this.level, primaryPos, this); -+ SoundType soundtype1 = p_277630_.getSoundType(this.level, secondaryPos, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); -- this.playMuffledStepSound(p_277630_); -+ this.playMuffledStepSound(p_277630_, secondaryPos); - } + protected void playStepSound(BlockPos p_20135_, BlockState p_20136_) { +- SoundType soundtype = p_20136_.getSoundType(); ++ SoundType soundtype = p_20136_.getSoundType(this.level(), p_20135_, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); + } -- protected void playMuffledStepSound(BlockState p_283110_) { -- SoundType soundtype = p_283110_.getSoundType(); -+ protected void playMuffledStepSound(BlockState p_283110_, BlockPos pos) { -+ SoundType soundtype = p_283110_.getSoundType(this.level, pos, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.05F, soundtype.getPitch() * 0.8F); - } +@@ -1204,27 +_,33 @@ - protected void playStepSound(BlockPos p_20135_, BlockState p_20136_) { -- SoundType soundtype = p_20136_.getSoundType(); -+ SoundType soundtype = p_20136_.getSoundType(this.level, p_20135_, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); - } + public void updateSwimming() { + if (this.isSwimming()) { +- this.setSwimming(this.isSprinting() && this.isInWater() && !this.isPassenger()); ++ this.setSwimming(this.isSprinting() && (this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType))) && !this.isPassenger()); + } else { +- this.setSwimming(this.isSprinting() && this.isUnderWater() && !this.isPassenger() && this.level().getFluidState(this.blockPosition).is(FluidTags.WATER)); ++ this.setSwimming(this.isSprinting() && (this.isUnderWater() || this.canStartSwimming()) && !this.isPassenger()); + } + } -@@ -1187,31 +_,38 @@ + protected boolean updateInWaterStateAndDoFluidPushing() { + this.fluidHeight.clear(); ++ this.forgeFluidTypeHeight.clear(); + this.updateInWaterStateAndDoWaterCurrentPushing(); +- double d0 = this.level().dimensionType().ultraWarm() ? 0.007 : 0.0023333333333333335; +- boolean flag = this.updateFluidHeightAndDoFluidPushing(FluidTags.LAVA, d0); +- return this.isInWater() || flag; ++ if (!(this.getVehicle() instanceof Boat)) { ++ this.fallDistance *= this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().filter(e -> !e.getKey().isAir() && !e.getKey().isVanilla()).map(e -> this.getFluidFallDistanceModifier(e.getKey())).min(Float::compare).orElse(1F); ++ if (this.isInFluidType((fluidType, height) -> !fluidType.isAir() && !fluidType.isVanilla() && this.canFluidExtinguish(fluidType))) this.clearFire(); ++ } ++ return this.isInFluidType(); + } - public void updateSwimming() { - if (this.isSwimming()) { -- this.setSwimming(this.isSprinting() && this.isInWater() && !this.isPassenger()); -+ this.setSwimming(this.isSprinting() && (this.isInWater() || this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType))) && !this.isPassenger()); - } else { -- this.setSwimming(this.isSprinting() && this.isUnderWater() && !this.isPassenger() && this.level().getFluidState(this.blockPosition).is(FluidTags.WATER)); -+ this.setSwimming(this.isSprinting() && (this.isUnderWater() || this.canStartSwimming()) && !this.isPassenger()); - } - - } - - protected boolean updateInWaterStateAndDoFluidPushing() { - this.fluidHeight.clear(); -+ this.forgeFluidTypeHeight.clear(); - this.updateInWaterStateAndDoWaterCurrentPushing(); -- double d0 = this.level().dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D; -- boolean flag = this.updateFluidHeightAndDoFluidPushing(FluidTags.LAVA, d0); -- return this.isInWater() || flag; -+ if (!(this.getVehicle() instanceof Boat)) { -+ this.fallDistance *= this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().filter(e -> !e.getKey().isAir() && !e.getKey().isVanilla()).map(e -> this.getFluidFallDistanceModifier(e.getKey())).min(Float::compare).orElse(1F); -+ if (this.isInFluidType((fluidType, height) -> !fluidType.isAir() && !fluidType.isVanilla() && this.canFluidExtinguish(fluidType))) this.clearFire(); -+ } -+ return this.isInFluidType(); - } - - void updateInWaterStateAndDoWaterCurrentPushing() { - Entity entity = this.getVehicle(); -+ java.util.function.BooleanSupplier updateFluidHeight = () -> this.updateFluidHeightAndDoFluidPushing(FluidTags.WATER, 0.014D); - if (entity instanceof Boat boat) { - if (!boat.isUnderWater()) { - this.wasTouchingWater = false; + void updateInWaterStateAndDoWaterCurrentPushing() { ++ java.util.function.BooleanSupplier updateFluidHeight = () -> this.updateFluidHeightAndDoFluidPushing(FluidTags.WATER, 0.014D); + if (this.getVehicle() instanceof Boat boat && !boat.isUnderWater()) { +- this.wasTouchingWater = false; - return; + updateFluidHeight = () -> { -+ this.updateFluidHeightAndDoFluidPushing(state -> this.shouldUpdateFluidWhileBoating(state, boat)); -+ return false; ++ this.updateFluidHeightAndDoFluidPushing(state -> this.shouldUpdateFluidWhileBoating(state, boat)); ++ return false; + }; - } - } + } -- if (this.updateFluidHeightAndDoFluidPushing(FluidTags.WATER, 0.014D)) { -+ if (updateFluidHeight.getAsBoolean()) { - if (!this.wasTouchingWater && !this.firstTick) { - this.doWaterSplashEffect(); - } -@@ -1228,6 +_,7 @@ - private void updateFluidOnEyes() { - this.wasEyeInWater = this.isEyeInFluid(FluidTags.WATER); - this.fluidOnEyes.clear(); -+ this.forgeFluidTypeOnEyes = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); - double d0 = this.getEyeY() - (double)0.11111111F; - Entity entity = this.getVehicle(); - if (entity instanceof Boat boat) { -@@ -1240,7 +_,7 @@ - FluidState fluidstate = this.level().getFluidState(blockpos); - double d1 = (double)((float)blockpos.getY() + fluidstate.getHeight(this.level(), blockpos)); - if (d1 > d0) { -- fluidstate.getTags().forEach(this.fluidOnEyes::add); -+ this.forgeFluidTypeOnEyes = fluidstate.getFluidType(); - } - - } -@@ -1284,12 +_,13 @@ - } - - public boolean canSpawnSprintParticle() { -- return this.isSprinting() && !this.isInWater() && !this.isSpectator() && !this.isCrouching() && !this.isInLava() && this.isAlive(); -+ return this.isSprinting() && !this.isInWater() && !this.isSpectator() && !this.isCrouching() && !this.isInLava() && this.isAlive() && !this.isInFluidType(); - } - - protected void spawnSprintParticle() { - BlockPos blockpos = this.getOnPosLegacy(); - BlockState blockstate = this.level().getBlockState(blockpos); -+ if(!blockstate.addRunningEffects(level, blockpos, this)) - if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { - Vec3 vec3 = this.getDeltaMovement(); - BlockPos blockpos1 = this.blockPosition(); -@@ -1303,17 +_,20 @@ - d1 = Mth.clamp(d1, (double)blockpos.getZ(), (double)blockpos.getZ() + 1.0D); - } - -- this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate), d0, this.getY() + 0.1D, d1, vec3.x * -4.0D, 1.5D, vec3.z * -4.0D); -+ this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate).setPos(blockpos), d0, this.getY() + 0.1D, d1, vec3.x * -4.0D, 1.5D, vec3.z * -4.0D); - } - - } - -+ @Deprecated // Forge: Use isEyeInFluidType instead - public boolean isEyeInFluid(TagKey p_204030_) { -+ if (p_204030_ == FluidTags.WATER) return this.isEyeInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); -+ else if (p_204030_ == FluidTags.LAVA) return this.isEyeInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); - return this.fluidOnEyes.contains(p_204030_); - } - - public boolean isInLava() { -- return !this.firstTick && this.fluidHeight.getDouble(FluidTags.LAVA) > 0.0D; -+ return !this.firstTick && this.forgeFluidTypeHeight.getDouble(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()) > 0.0D; - } - - public void moveRelative(float p_19921_, Vec3 p_19922_) { -@@ -1631,6 +_,8 @@ - p_20241_.putBoolean("HasVisualFire", this.hasVisualFire); - } - -+ p_20241_.putBoolean("CanUpdate", canUpdate); -+ - if (!this.tags.isEmpty()) { - ListTag listtag = new ListTag(); - -@@ -1641,6 +_,10 @@ - p_20241_.put("Tags", listtag); - } - -+ CompoundTag caps = serializeCaps(); -+ if (caps != null) p_20241_.put("ForgeCaps", caps); -+ if (persistentData != null) p_20241_.put("ForgeData", persistentData.copy()); -+ - this.addAdditionalSaveData(p_20241_); - if (this.isVehicle()) { - ListTag listtag1 = new ListTag(); -@@ -1716,6 +_,9 @@ - this.setGlowingTag(p_20259_.getBoolean("Glowing")); - this.setTicksFrozen(p_20259_.getInt("TicksFrozen")); - this.hasVisualFire = p_20259_.getBoolean("HasVisualFire"); -+ if (p_20259_.contains("ForgeData", 10)) persistentData = p_20259_.getCompound("ForgeData"); -+ if (p_20259_.contains("CanUpdate", 99)) this.canUpdate(p_20259_.getBoolean("CanUpdate")); -+ if (p_20259_.contains("ForgeCaps", 10)) deserializeCaps(p_20259_.getCompound("ForgeCaps")); - if (p_20259_.contains("Tags", 9)) { - this.tags.clear(); - ListTag listtag3 = p_20259_.getList("Tags", 8); -@@ -1804,6 +_,8 @@ - } else { - ItemEntity itementity = new ItemEntity(this.level(), this.getX(), this.getY() + (double)p_19986_, this.getZ(), p_19985_); - itementity.setDefaultPickUpDelay(); -+ if (captureDrops() != null) captureDrops().add(itementity); -+ else - this.level().addFreshEntity(itementity); - return itementity; - } -@@ -1840,6 +_,7 @@ - - public void rideTick() { - this.setDeltaMovement(Vec3.ZERO); -+ if (canUpdate()) - this.tick(); - if (this.isPassenger()) { - this.getVehicle().positionRider(this); -@@ -1896,6 +_,7 @@ +- if (this.updateFluidHeightAndDoFluidPushing(FluidTags.WATER, 0.014)) { ++ if (updateFluidHeight.getAsBoolean()) { + if (!this.wasTouchingWater && !this.firstTick) { + this.doWaterSplashEffect(); } - } +@@ -1240,6 +_,7 @@ + private void updateFluidOnEyes() { + this.wasEyeInWater = this.isEyeInFluid(FluidTags.WATER); + this.fluidOnEyes.clear(); ++ this.forgeFluidTypeOnEyes = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); + double d0 = this.getEyeY(); + if (this.getVehicle() instanceof Boat boat && !boat.isUnderWater() && boat.getBoundingBox().maxY >= d0 && boat.getBoundingBox().minY <= d0) { + return; +@@ -1249,7 +_,7 @@ + FluidState fluidstate = this.level().getFluidState(blockpos); + double d1 = (double)((float)blockpos.getY() + fluidstate.getHeight(this.level(), blockpos)); + if (d1 > d0) { +- fluidstate.getTags().forEach(this.fluidOnEyes::add); ++ this.forgeFluidTypeOnEyes = fluidstate.getFluidType(); + } + } -+ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, p_19966_, true)) return false; - if (p_19967_ || this.canRide(p_19966_) && p_19966_.canAddPassenger(this)) { - if (this.isPassenger()) { - this.stopRiding(); -@@ -1930,6 +_,7 @@ - public void removeVehicle() { - if (this.vehicle != null) { - Entity entity = this.vehicle; -+ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entity, false)) return; - this.vehicle = null; - entity.removePassenger(this); - } -@@ -1982,6 +_,8 @@ - return this.passengers.isEmpty(); - } +@@ -1303,12 +_,13 @@ + } -+ /** @deprecated Forge: Use {@link #canBeRiddenUnderFluidType(net.minecraftforge.fluids.FluidType, Entity) rider sensitive version} */ -+ @Deprecated - protected boolean couldAcceptPassenger() { - return true; - } -@@ -2187,7 +_,7 @@ - } + public boolean canSpawnSprintParticle() { +- return this.isSprinting() && !this.isInWater() && !this.isSpectator() && !this.isCrouching() && !this.isInLava() && this.isAlive(); ++ return this.isSprinting() && !this.isInWater() && !this.isSpectator() && !this.isCrouching() && !this.isInLava() && this.isAlive() && !this.isInFluidType(); + } - public boolean isVisuallyCrawling() { -- return this.isVisuallySwimming() && !this.isInWater(); -+ return this.isVisuallySwimming() && !this.isInWater() && !this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)); - } + protected void spawnSprintParticle() { + BlockPos blockpos = this.getOnPosLegacy(); + BlockState blockstate = this.level().getBlockState(blockpos); ++ if (!blockstate.addRunningEffects(level, blockpos, this)) + if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { + Vec3 vec3 = this.getDeltaMovement(); + BlockPos blockpos1 = this.blockPosition(); +@@ -1324,7 +_,7 @@ - public void setSwimming(boolean p_20283_) { -@@ -2297,7 +_,7 @@ - this.setSecondsOnFire(8); - } + this.level() + .addParticle( +- new BlockParticleOption(ParticleTypes.BLOCK, blockstate), ++ new BlockParticleOption(ParticleTypes.BLOCK, blockstate).setPos(blockpos), + d0, + this.getY() + 0.1, + d1, +@@ -1335,12 +_,15 @@ + } + } -- this.hurt(this.damageSources().lightningBolt(), 5.0F); -+ this.hurt(this.damageSources().lightningBolt(), p_19928_.getDamage()); - } ++ @Deprecated // Forge: Use isEyeInFluidType instead + public boolean isEyeInFluid(TagKey p_204030_) { ++ if (p_204030_ == FluidTags.WATER) return this.isEyeInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); ++ else if (p_204030_ == FluidTags.LAVA) return this.isEyeInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); + return this.fluidOnEyes.contains(p_204030_); + } - public void onAboveBubbleCol(boolean p_20313_) { -@@ -2393,7 +_,7 @@ - } + public boolean isInLava() { +- return !this.firstTick && this.fluidHeight.getDouble(FluidTags.LAVA) > 0.0; ++ return !this.firstTick && this.forgeFluidTypeHeight.getDouble(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()) > 0.0; + } - protected Component getTypeName() { -- return this.type.getDescription(); -+ return this.getType().getDescription(); // Forge: Use getter to allow overriding by mods - } + public void moveRelative(float p_19921_, Vec3 p_19922_) { +@@ -1662,6 +_,11 @@ + p_20241_.putBoolean("HasVisualFire", this.hasVisualFire); + } - public boolean is(Entity p_20356_) { -@@ -2449,14 +_,20 @@ ++ p_20241_.putBoolean("CanUpdate", canUpdate); ++ CompoundTag caps = serializeCaps(); ++ if (caps != null) p_20241_.put("ForgeCaps", caps); ++ if (persistentData != null) p_20241_.put("ForgeData", persistentData.copy()); ++ + if (!this.tags.isEmpty()) { + ListTag listtag = new ListTag(); - @Nullable - public Entity changeDimension(ServerLevel p_20118_) { -+ return this.changeDimension(p_20118_, p_20118_.getPortalForcer()); -+ } -+ @Nullable -+ public Entity changeDimension(ServerLevel p_20118_, net.minecraftforge.common.util.ITeleporter teleporter) { -+ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_20118_.dimension())) return null; - if (this.level() instanceof ServerLevel && !this.isRemoved()) { - this.level().getProfiler().push("changeDimension"); - this.unRide(); - this.level().getProfiler().push("reposition"); -- PortalInfo portalinfo = this.findDimensionEntryPoint(p_20118_); -+ PortalInfo portalinfo = teleporter.getPortalInfo(this, p_20118_, this::findDimensionEntryPoint); - if (portalinfo == null) { +@@ -1752,6 +_,9 @@ + this.setGlowingTag(p_20259_.getBoolean("Glowing")); + this.setTicksFrozen(p_20259_.getInt("TicksFrozen")); + this.hasVisualFire = p_20259_.getBoolean("HasVisualFire"); ++ if (p_20259_.contains("ForgeData", 10)) persistentData = p_20259_.getCompound("ForgeData"); ++ if (p_20259_.contains("CanUpdate", 99)) this.canUpdate(p_20259_.getBoolean("CanUpdate")); ++ if (p_20259_.contains("ForgeCaps", 10)) deserializeCaps(p_20259_.getCompound("ForgeCaps")); + if (p_20259_.contains("Tags", 9)) { + this.tags.clear(); + ListTag listtag3 = p_20259_.getList("Tags", 8); +@@ -1836,6 +_,8 @@ + } else { + ItemEntity itementity = new ItemEntity(this.level(), this.getX(), this.getY() + (double)p_19986_, this.getZ(), p_19985_); + itementity.setDefaultPickUpDelay(); ++ if (captureDrops() != null) captureDrops().add(itementity); ++ else + this.level().addFreshEntity(itementity); + return itementity; + } +@@ -1882,6 +_,7 @@ + + public void rideTick() { + this.setDeltaMovement(Vec3.ZERO); ++ if (canUpdate()) + this.tick(); + if (this.isPassenger()) { + this.getVehicle().positionRider(this); +@@ -1940,6 +_,7 @@ + } + } + ++ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, p_19966_, true)) return false; + if (p_19967_ || this.canRide(p_19966_) && p_19966_.canAddPassenger(this)) { + if (this.isPassenger()) { + this.stopRiding(); +@@ -1971,6 +_,7 @@ + public void removeVehicle() { + if (this.vehicle != null) { + Entity entity = this.vehicle; ++ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entity, false)) return; + this.vehicle = null; + entity.removePassenger(this); + } +@@ -2020,6 +_,8 @@ + return this.passengers.isEmpty(); + } + ++ /** @deprecated Forge: Use {@link #canBeRiddenUnderFluidType(net.minecraftforge.fluids.FluidType, Entity) rider sensitive version} */ ++ @Deprecated + protected boolean couldAcceptPassenger() { + return true; + } +@@ -2209,7 +_,7 @@ + } + + public boolean isVisuallyCrawling() { +- return this.isVisuallySwimming() && !this.isInWater(); ++ return this.isVisuallySwimming() && !this.isInWater() && !this.isInFluidType((fluidType, height) -> this.canSwimInFluidType(fluidType)); + } + + public void setSwimming(boolean p_20283_) { +@@ -2318,7 +_,7 @@ + this.igniteForSeconds(8); + } + +- this.hurt(this.damageSources().lightningBolt(), 5.0F); ++ this.hurt(this.damageSources().lightningBolt(), p_19928_.getDamage()); + } + + public void onAboveBubbleCol(boolean p_20313_) { +@@ -2413,7 +_,7 @@ + } + + protected Component getTypeName() { +- return this.type.getDescription(); ++ return this.getType().getDescription(); // Forge: Use getter to allow overriding by mods; + } + + public boolean is(Entity p_20356_) { +@@ -2496,14 +_,21 @@ + + @Nullable + public Entity changeDimension(ServerLevel p_20118_) { +- if (this.level() instanceof ServerLevel && !this.isRemoved()) { ++ return this.changeDimension(p_20118_, p_20118_.getPortalForcer()); ++ } ++ ++ @Nullable ++ public Entity changeDimension(ServerLevel p_20118_, net.minecraftforge.common.util.ITeleporter teleporter) { ++ if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, p_20118_.dimension())) return null; ++ if (this.level() instanceof ServerLevel && !this.isRemoved()) { + this.level().getProfiler().push("changeDimension"); + this.unRide(); + this.level().getProfiler().push("reposition"); +- PortalInfo portalinfo = this.findDimensionEntryPoint(p_20118_); ++ PortalInfo portalinfo = teleporter.getPortalInfo(this, p_20118_, this::findDimensionEntryPoint); + if (portalinfo == null) { + return null; + } else { ++ Entity transportedEntity = teleporter.placeEntity(this, (ServerLevel) this.level, p_20118_, this.yRot, spawnPortal -> { //Forge: Start vanilla logic + this.level().getProfiler().popPush("reloading"); + Entity entity = this.getType().create(p_20118_); + if (entity != null) { +@@ -2513,17 +_,19 @@ + ); + entity.setDeltaMovement(portalinfo.speed); + p_20118_.addDuringTeleport(entity); +- if (p_20118_.dimension() == Level.END) { ++ if (spawnPortal && p_20118_.dimension() == Level.END) { + ServerLevel.makeObsidianPlatform(p_20118_); + } + } ++ return entity; ++ }); //Forge: End vanilla logic + + this.removeAfterChangingDimensions(); + this.level().getProfiler().pop(); + ((ServerLevel)this.level()).resetEmptyTime(); + p_20118_.resetEmptyTime(); + this.level().getProfiler().pop(); +- return entity; ++ return transportedEntity; + } + } else { return null; - } else { -+ Entity transportedEntity = teleporter.placeEntity(this, (ServerLevel) this.level, p_20118_, this.yRot, spawnPortal -> { //Forge: Start vanilla logic - this.level().getProfiler().popPush("reloading"); - Entity entity = this.getType().create(p_20118_); - if (entity != null) { -@@ -2464,17 +_,19 @@ - entity.moveTo(portalinfo.pos.x, portalinfo.pos.y, portalinfo.pos.z, portalinfo.yRot, entity.getXRot()); - entity.setDeltaMovement(portalinfo.speed); - p_20118_.addDuringTeleport(entity); -- if (p_20118_.dimension() == Level.END) { -+ if (spawnPortal && p_20118_.dimension() == Level.END) { - ServerLevel.makeObsidianPlatform(p_20118_); - } - } -+ return entity; -+ }); //Forge: End vanilla logic +@@ -2653,6 +_,7 @@ + return this.stringUUID; + } - this.removeAfterChangingDimensions(); - this.level().getProfiler().pop(); - ((ServerLevel)this.level()).resetEmptyTime(); - p_20118_.resetEmptyTime(); - this.level().getProfiler().pop(); -- return entity; -+ return transportedEntity; - } - } else { - return null; -@@ -2596,6 +_,7 @@ - return this.stringUUID; - } ++ @Deprecated // Forge: Use FluidType sensitive version + public boolean isPushedByFluid() { + return true; + } +@@ -3097,9 +_,17 @@ + this.yRotO = this.getYRot(); + } -+ @Deprecated // Forge: Use FluidType sensitive version - public boolean isPushedByFluid() { - return true; - } -@@ -3015,9 +_,22 @@ - this.yRotO = this.getYRot(); - } - -+ @Deprecated // Forge: Use predicate version instead, only for vanilla Tags - public boolean updateFluidHeightAndDoFluidPushing(TagKey p_204032_, double p_204033_) { -+ this.updateFluidHeightAndDoFluidPushing(); -+ if(p_204032_ == FluidTags.WATER) return this.isInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); -+ else if (p_204032_ == FluidTags.LAVA) return this.isInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); -+ else return false; -+ } ++ @Deprecated // Forge: Use predicate version instead, only for vanilla Tags + public boolean updateFluidHeightAndDoFluidPushing(TagKey p_204032_, double p_204033_) { ++ this.updateFluidHeightAndDoFluidPushing(com.google.common.base.Predicates.alwaysTrue()); ++ if(p_204032_ == FluidTags.WATER) return this.isInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); ++ else if (p_204032_ == FluidTags.LAVA) return this.isInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); ++ else return false; ++ } + -+ @Deprecated(forRemoval = true, since = "1.20.1") -+ public void updateFluidHeightAndDoFluidPushing() { -+ this.updateFluidHeightAndDoFluidPushing(com.google.common.base.Predicates.alwaysTrue()); -+ } -+ -+ public void updateFluidHeightAndDoFluidPushing(Predicate shouldUpdate) { - if (this.touchingUnloadedChunk()) { -- return false; -+ return; - } else { - AABB aabb = this.getBoundingBox().deflate(0.001D); - int i = Mth.floor(aabb.minX); -@@ -3032,25 +_,28 @@ - Vec3 vec3 = Vec3.ZERO; - int k1 = 0; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); -+ it.unimi.dsi.fastutil.objects.Object2ObjectMap> interimCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<>(net.minecraftforge.fluids.FluidType.SIZE.get() - 1); ++ public void updateFluidHeightAndDoFluidPushing(Predicate shouldUpdate) { + if (this.touchingUnloadedChunk()) { +- return false; ++ return; + } else { + AABB aabb = this.getBoundingBox().deflate(0.001); + int i = Mth.floor(aabb.minX); +@@ -3114,25 +_,28 @@ + Vec3 vec3 = Vec3.ZERO; + int k1 = 0; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); ++ var interimCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap>(net.minecraftforge.fluids.FluidType.SIZE.get() - 1); - for(int l1 = i; l1 < j; ++l1) { - for(int i2 = k; i2 < l; ++i2) { - for(int j2 = i1; j2 < j1; ++j2) { - blockpos$mutableblockpos.set(l1, i2, j2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(p_204032_)) { -+ net.minecraftforge.fluids.FluidType fluidType = fluidstate.getFluidType(); -+ if (!fluidType.isAir() && shouldUpdate.test(fluidstate)) { - double d1 = (double)((float)i2 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)); - if (d1 >= aabb.minY) { - flag1 = true; -- d0 = Math.max(d1 - aabb.minY, d0); -- if (flag) { -+ org.apache.commons.lang3.tuple.MutableTriple interim = interimCalcs.computeIfAbsent(fluidType, t -> org.apache.commons.lang3.tuple.MutableTriple.of(0.0D, Vec3.ZERO, 0)); -+ interim.setLeft(Math.max(d1 - aabb.minY, interim.getLeft())); -+ if (this.isPushedByFluid(fluidType)) { - Vec3 vec31 = fluidstate.getFlow(this.level(), blockpos$mutableblockpos); -- if (d0 < 0.4D) { -- vec31 = vec31.scale(d0); -+ if (interim.getLeft() < 0.4D) { -+ vec31 = vec31.scale(interim.getLeft()); - } + for (int l1 = i; l1 < j; l1++) { + for (int i2 = k; i2 < l; i2++) { + for (int j2 = i1; j2 < j1; j2++) { + blockpos$mutableblockpos.set(l1, i2, j2); + FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); +- if (fluidstate.is(p_204032_)) { ++ net.minecraftforge.fluids.FluidType fluidType = fluidstate.getFluidType(); ++ if (!fluidType.isAir() && shouldUpdate.test(fluidstate)) { + double d1 = (double)((float)i2 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)); + if (d1 >= aabb.minY) { + flag1 = true; +- d0 = Math.max(d1 - aabb.minY, d0); +- if (flag) { ++ var interim = interimCalcs.computeIfAbsent(fluidType, t -> org.apache.commons.lang3.tuple.MutableTriple.of(0.0D, Vec3.ZERO, 0)); ++ interim.setLeft(Math.max(d1 - aabb.minY, interim.getLeft())); ++ if (this.isPushedByFluid(fluidType)) { + Vec3 vec31 = fluidstate.getFlow(this.level(), blockpos$mutableblockpos); +- if (d0 < 0.4) { +- vec31 = vec31.scale(d0); ++ if (interim.getLeft() < 0.4D) { ++ vec31 = vec31.scale(interim.getLeft()); + } -- vec3 = vec3.add(vec31); -- ++k1; -+ interim.setMiddle(interim.getMiddle().add(vec31)); -+ interim.setRight(interim.getRight() + 1); +- vec3 = vec3.add(vec31); +- k1++; ++ interim.setMiddle(interim.getMiddle().add(vec31)); ++ interim.setRight(interim.getRight() + 1); + } + } } - } - } -@@ -3058,27 +_,28 @@ - } - } - -- if (vec3.length() > 0.0D) { -- if (k1 > 0) { -- vec3 = vec3.scale(1.0D / (double)k1); -+ interimCalcs.forEach((fluidType, interim) -> { -+ if (interim.getMiddle().length() > 0.0D) { -+ if (interim.getRight() > 0) { -+ interim.setMiddle(interim.getMiddle().scale(1.0D / (double)interim.getRight())); +@@ -3140,27 +_,28 @@ + } } - if (!(this instanceof Player)) { -- vec3 = vec3.normalize(); -+ interim.setMiddle(interim.getMiddle().normalize()); +- if (vec3.length() > 0.0) { +- if (k1 > 0) { +- vec3 = vec3.scale(1.0 / (double)k1); ++ interimCalcs.forEach((fluidType, interim) -> { ++ if (interim.getMiddle().length() > 0.0D) { ++ if (interim.getRight() > 0) { ++ interim.setMiddle(interim.getMiddle().scale(1.0D / (double)interim.getRight())); + } + + if (!(this instanceof Player)) { +- vec3 = vec3.normalize(); ++ interim.setMiddle(interim.getMiddle().normalize()); + } + + Vec3 vec32 = this.getDeltaMovement(); +- vec3 = vec3.scale(p_204033_ * 1.0); ++ interim.setMiddle(interim.getMiddle().scale(this.getFluidMotionScale(fluidType))); + double d2 = 0.003; +- if (Math.abs(vec32.x) < 0.003 && Math.abs(vec32.z) < 0.003 && vec3.length() < 0.0045000000000000005) { +- vec3 = vec3.normalize().scale(0.0045000000000000005); ++ if (Math.abs(vec32.x) < 0.003 && Math.abs(vec32.z) < 0.003 && interim.getMiddle().length() < 0.0045000000000000005) { ++ interim.setMiddle(interim.getMiddle().normalize().scale(0.0045000000000000005)); + } + +- this.setDeltaMovement(this.getDeltaMovement().add(vec3)); ++ this.setDeltaMovement(this.getDeltaMovement().add(interim.getMiddle())); } - Vec3 vec32 = this.getDeltaMovement(); -- vec3 = vec3.scale(p_204033_ * 1.0D); -+ interim.setMiddle(interim.getMiddle().scale(this.getFluidMotionScale(fluidType))); - double d2 = 0.003D; -- if (Math.abs(vec32.x) < 0.003D && Math.abs(vec32.z) < 0.003D && vec3.length() < 0.0045000000000000005D) { -- vec3 = vec3.normalize().scale(0.0045000000000000005D); -+ if (Math.abs(vec32.x) < 0.003D && Math.abs(vec32.z) < 0.003D && interim.getMiddle().length() < 0.0045000000000000005D) { -+ interim.setMiddle(interim.getMiddle().normalize().scale(0.0045000000000000005D)); - } +- this.fluidHeight.put(p_204032_, d0); +- return flag1; ++ this.setFluidTypeHeight(fluidType, interim.getLeft()); ++ }); + } + } -- this.setDeltaMovement(this.getDeltaMovement().add(vec3)); -+ this.setDeltaMovement(this.getDeltaMovement().add(interim.getMiddle())); - } +@@ -3173,7 +_,10 @@ + return !this.level().hasChunksAt(i, k, j, l); + } -- this.fluidHeight.put(p_204032_, d0); -- return flag1; -+ this.setFluidTypeHeight(fluidType, interim.getLeft()); -+ }); - } - } ++ @Deprecated // Forge: Use getFluidTypeHeight instead + public double getFluidHeight(TagKey p_204037_) { ++ if (p_204037_ == FluidTags.WATER) return getFluidTypeHeight(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); ++ else if (p_204037_ == FluidTags.LAVA) return getFluidTypeHeight(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); + return this.fluidHeight.getDouble(p_204037_); + } -@@ -3091,7 +_,10 @@ - return !this.level().hasChunksAt(i, k, j, l); - } +@@ -3189,7 +_,9 @@ + return this.dimensions.height(); + } -+ @Deprecated // Forge: Use getFluidTypeHeight instead - public double getFluidHeight(TagKey p_204037_) { -+ if (p_204037_ == FluidTags.WATER) return getFluidTypeHeight(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); -+ else if (p_204037_ == FluidTags.LAVA) return getFluidTypeHeight(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); - return this.fluidHeight.getDouble(p_204037_); - } ++ private boolean hasExtraSpawnData = this instanceof net.minecraftforge.entity.IEntityAdditionalSpawnData; + public Packet getAddEntityPacket() { ++ if (hasExtraSpawnData) return net.minecraftforge.common.ForgeHooks.getEntitySpawnPacket(this); + return new ClientboundAddEntityPacket(this); + } -@@ -3111,7 +_,9 @@ - return this.getBbHeight() + 0.5F; - } +@@ -3310,6 +_,11 @@ -+ private boolean hasExtraSpawnData = this instanceof net.minecraftforge.entity.IEntityAdditionalSpawnData; - public Packet getAddEntityPacket() { -+ if (hasExtraSpawnData) return net.minecraftforge.common.ForgeHooks.getEntitySpawnPacket(this); - return new ClientboundAddEntityPacket(this); - } + this.levelCallback.onMove(); + } ++ ++ // Forge - ensure target chunk is loaded. ++ if (this.isAddedToWorld() && !this.level.isClientSide && !this.isRemoved()) { ++ this.level.getChunk((int) Math.floor(p_20344_) >> 4, (int) Math.floor(p_20346_) >> 4); ++ } + } -@@ -3227,6 +_,7 @@ + public void checkDespawn() { +@@ -3463,6 +_,100 @@ + float f1 = (float)Mth.lerp(d0, (double)this.getXRot(), p_298926_); + this.setPos(d1, d2, d3); + this.setRot(f, f1); ++ } ++ ++ private boolean canUpdate = true; ++ @Override ++ public void canUpdate(boolean value) { ++ this.canUpdate = value; ++ } ++ ++ @Override ++ public boolean canUpdate() { ++ return this.canUpdate; ++ } ++ ++ private java.util.Collection captureDrops = null; ++ @Override ++ public java.util.Collection captureDrops() { ++ return captureDrops; ++ } ++ ++ @Override ++ public java.util.Collection captureDrops(java.util.Collection value) { ++ java.util.Collection ret = captureDrops; ++ this.captureDrops = value; ++ return ret; ++ } ++ ++ private CompoundTag persistentData; ++ @Override ++ public CompoundTag getPersistentData() { ++ if (persistentData == null) ++ persistentData = new CompoundTag(); ++ return persistentData; ++ } ++ ++ @Override ++ public boolean canTrample(BlockState state, BlockPos pos, float fallDistance) { ++ return level.random.nextFloat() < fallDistance - 0.5F ++ && this instanceof LivingEntity ++ && (this instanceof Player || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this)) ++ && this.getBbWidth() * this.getBbWidth() * this.getBbHeight() > 0.512F; ++ } ++ ++ /** ++ * Internal use for keeping track of entities that are tracked by a world, to ++ * allow guarantees that entity position changes will force a chunk load, avoiding ++ * potential issues with entity desyncing and bad chunk data. ++ */ ++ private boolean isAddedToWorld; ++ ++ @Override ++ public final boolean isAddedToWorld() { return this.isAddedToWorld; } ++ ++ @Override ++ public void onAddedToWorld() { this.isAddedToWorld = true; } ++ ++ @Override ++ public void onRemovedFromWorld() { this.isAddedToWorld = false; } ++ ++ @Override ++ public void revive() { ++ this.unsetRemoved(); ++ this.reviveCaps(); ++ } ++ ++ protected Object2DoubleMap forgeFluidTypeHeight = new Object2DoubleArrayMap<>(net.minecraftforge.fluids.FluidType.SIZE.get()); ++ private net.minecraftforge.fluids.FluidType forgeFluidTypeOnEyes = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); ++ protected final void setFluidTypeHeight(net.minecraftforge.fluids.FluidType type, double height) { ++ this.forgeFluidTypeHeight.put(type, height); ++ } ++ ++ @Override ++ public final double getFluidTypeHeight(net.minecraftforge.fluids.FluidType type) { ++ return this.forgeFluidTypeHeight.getDouble(type); ++ } ++ ++ @Override ++ public final boolean isInFluidType(java.util.function.BiPredicate predicate, boolean forAllTypes) { ++ return forAllTypes ? this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().allMatch(e -> predicate.test(e.getKey(), e.getDoubleValue())) ++ : this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().anyMatch(e -> predicate.test(e.getKey(), e.getDoubleValue())); ++ } ++ ++ @Override ++ public final boolean isInFluidType() { ++ return this.forgeFluidTypeHeight.size() > 0; ++ } ++ ++ @Override ++ public final net.minecraftforge.fluids.FluidType getEyeInFluidType() { ++ return forgeFluidTypeOnEyes; ++ } ++ ++ @Override ++ public net.minecraftforge.fluids.FluidType getMaxHeightFluidType() { ++ return this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().max(java.util.Comparator.comparingDouble(Object2DoubleMap.Entry::getDoubleValue)).map(Object2DoubleMap.Entry::getKey).orElseGet(net.minecraftforge.common.ForgeMod.EMPTY_TYPE); + } - this.levelCallback.onMove(); - } -+ if (this.isAddedToWorld() && !this.level.isClientSide && !this.isRemoved()) this.level.getChunk((int) Math.floor(p_20344_) >> 4, (int) Math.floor(p_20346_) >> 4); // Forge - ensure target chunk is loaded. - - } - -@@ -3299,6 +_,7 @@ - return false; - } - -+ @Deprecated /** Forge: Use {@link net.minecraftforge.common.extensions.IForgeEntity#getStepHeight()} */ - public float maxUpStep() { - return this.maxUpStep; - } -@@ -3354,6 +_,109 @@ - public boolean mayInteract(Level p_146843_, BlockPos p_146844_) { - return true; - } -+ -+ /* ================================== Forge Start =====================================*/ -+ -+ private boolean canUpdate = true; -+ @Override -+ public void canUpdate(boolean value) { -+ this.canUpdate = value; -+ } -+ @Override -+ public boolean canUpdate() { -+ return this.canUpdate; -+ } -+ private java.util.Collection captureDrops = null; -+ @Override -+ public java.util.Collection captureDrops() { -+ return captureDrops; -+ } -+ @Override -+ public java.util.Collection captureDrops(java.util.Collection value) { -+ java.util.Collection ret = captureDrops; -+ this.captureDrops = value; -+ return ret; -+ } -+ private CompoundTag persistentData; -+ @Override -+ public CompoundTag getPersistentData() { -+ if (persistentData == null) -+ persistentData = new CompoundTag(); -+ return persistentData; -+ } -+ @Override -+ public boolean canTrample(BlockState state, BlockPos pos, float fallDistance) { -+ return level.random.nextFloat() < fallDistance - 0.5F -+ && this instanceof LivingEntity -+ && (this instanceof Player || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this)) -+ && this.getBbWidth() * this.getBbWidth() * this.getBbHeight() > 0.512F; -+ } -+ -+ /** -+ * Internal use for keeping track of entities that are tracked by a world, to -+ * allow guarantees that entity position changes will force a chunk load, avoiding -+ * potential issues with entity desyncing and bad chunk data. -+ */ -+ private boolean isAddedToWorld; -+ -+ @Override -+ public final boolean isAddedToWorld() { return this.isAddedToWorld; } -+ -+ @Override -+ public void onAddedToWorld() { this.isAddedToWorld = true; } -+ -+ @Override -+ public void onRemovedFromWorld() { this.isAddedToWorld = false; } -+ -+ @Override -+ public void revive() { -+ this.unsetRemoved(); -+ this.reviveCaps(); -+ } -+ -+ // no AT because of overrides -+ /** -+ * Accessor method for {@link #getEyeHeight(Pose, EntityDimensions)} -+ */ -+ @Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned -+ public float getEyeHeightAccess(Pose pose, EntityDimensions size) { -+ return this.getEyeHeight(pose, size); -+ } -+ -+ protected Object2DoubleMap forgeFluidTypeHeight = new Object2DoubleArrayMap<>(net.minecraftforge.fluids.FluidType.SIZE.get()); -+ private net.minecraftforge.fluids.FluidType forgeFluidTypeOnEyes = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); -+ protected final void setFluidTypeHeight(net.minecraftforge.fluids.FluidType type, double height) { -+ this.forgeFluidTypeHeight.put(type, height); -+ } -+ @Override -+ public final double getFluidTypeHeight(net.minecraftforge.fluids.FluidType type) { -+ return this.forgeFluidTypeHeight.getDouble(type); -+ } -+ @Override -+ public final boolean isInFluidType(java.util.function.BiPredicate predicate, boolean forAllTypes) { -+ return forAllTypes ? this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().allMatch(e -> predicate.test(e.getKey(), e.getDoubleValue())) -+ : this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().anyMatch(e -> predicate.test(e.getKey(), e.getDoubleValue())); -+ } -+ @Override -+ public final boolean isInFluidType() { -+ return this.forgeFluidTypeHeight.size() > 0; -+ } -+ @Override -+ public final net.minecraftforge.fluids.FluidType getEyeInFluidType() { -+ return forgeFluidTypeOnEyes; -+ } -+ @Override -+ public net.minecraftforge.fluids.FluidType getMaxHeightFluidType() { -+ return this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().max(java.util.Comparator.comparingDouble(Object2DoubleMap.Entry::getDoubleValue)).map(Object2DoubleMap.Entry::getKey).orElseGet(net.minecraftforge.common.ForgeMod.EMPTY_TYPE); -+ } -+ -+ @Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned -+ public EntityDimensions getDimensionsForge(Pose pose) { -+ return getDimensions(pose); -+ } -+ -+ /* ================================== Forge End =====================================*/ -+ - - public Level level() { - return this.level; + @FunctionalInterface diff --git a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch index 81d4b779f4..f9697dc56d 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch @@ -1,137 +1,138 @@ --- a/net/minecraft/world/entity/EntityType.java +++ b/net/minecraft/world/entity/EntityType.java -@@ -312,6 +_,11 @@ - private final EntityDimensions dimensions; - private final FeatureFlagSet requiredFeatures; +@@ -740,6 +_,11 @@ + private final float spawnDimensionsScale; + private final FeatureFlagSet requiredFeatures; -+ private final java.util.function.Predicate> velocityUpdateSupplier; -+ private final java.util.function.ToIntFunction> trackingRangeSupplier; -+ private final java.util.function.ToIntFunction> updateIntervalSupplier; -+ private final java.util.function.BiFunction customClientFactory; ++ private final java.util.function.Predicate> velocityUpdateSupplier; ++ private final java.util.function.ToIntFunction> trackingRangeSupplier; ++ private final java.util.function.ToIntFunction> updateIntervalSupplier; ++ private final java.util.function.BiFunction customClientFactory; + - private static EntityType register(String p_20635_, EntityType.Builder p_20636_) { - return Registry.register(BuiltInRegistries.ENTITY_TYPE, p_20635_, p_20636_.build(p_20635_)); - } -@@ -325,17 +_,24 @@ - } + private static EntityType register(String p_20635_, EntityType.Builder p_20636_) { + return Registry.register(BuiltInRegistries.ENTITY_TYPE, p_20635_, p_20636_.build(p_20635_)); + } +@@ -752,6 +_,10 @@ + return BuiltInRegistries.ENTITY_TYPE.getOptional(ResourceLocation.tryParse(p_20633_)); + } - public EntityType(EntityType.EntityFactory p_273268_, MobCategory p_272918_, boolean p_273417_, boolean p_273389_, boolean p_273556_, boolean p_272654_, ImmutableSet p_273631_, EntityDimensions p_272946_, int p_272895_, int p_273451_, FeatureFlagSet p_273518_) { -- this.factory = p_273268_; -- this.category = p_272918_; -- this.canSpawnFarFromPlayer = p_272654_; -- this.serialize = p_273417_; -- this.summon = p_273389_; -- this.fireImmune = p_273556_; -- this.immuneTo = p_273631_; -- this.dimensions = p_272946_; -- this.clientTrackingRange = p_272895_; -- this.updateInterval = p_273451_; -- this.requiredFeatures = p_273518_; -+ this(p_273268_, p_272918_, p_273417_, p_273389_, p_273556_, p_272654_, p_273631_, p_272946_, p_272895_, p_273451_, p_273518_, EntityType::defaultVelocitySupplier, EntityType::defaultTrackingRangeSupplier, EntityType::defaultUpdateIntervalSupplier, null); -+ } -+ public EntityType(EntityType.EntityFactory p_251402_, MobCategory p_251431_, boolean p_251439_, boolean p_251973_, boolean p_252007_, boolean p_250908_, ImmutableSet p_250201_, EntityDimensions p_251742_, int p_250479_, int p_249249_, FeatureFlagSet p_250427_, final java.util.function.Predicate> velocityUpdateSupplier, final java.util.function.ToIntFunction> trackingRangeSupplier, final java.util.function.ToIntFunction> updateIntervalSupplier, final java.util.function.BiFunction customClientFactory) { -+ this.factory = p_251402_; -+ this.category = p_251431_; -+ this.canSpawnFarFromPlayer = p_250908_; -+ this.serialize = p_251439_; -+ this.summon = p_251973_; -+ this.fireImmune = p_252007_; -+ this.immuneTo = p_250201_; -+ this.dimensions = p_251742_; -+ this.clientTrackingRange = p_250479_; -+ this.updateInterval = p_249249_; -+ this.requiredFeatures = p_250427_; -+ this.velocityUpdateSupplier = velocityUpdateSupplier; -+ this.trackingRangeSupplier = trackingRangeSupplier; -+ this.updateIntervalSupplier = updateIntervalSupplier; -+ this.customClientFactory = customClientFactory; - } - - @Nullable -@@ -605,14 +_,23 @@ - } - - public int clientTrackingRange() { -+ return trackingRangeSupplier.applyAsInt(this); -+ } -+ private int defaultTrackingRangeSupplier() { - return this.clientTrackingRange; - } - - public int updateInterval() { -+ return updateIntervalSupplier.applyAsInt(this); -+ } -+ private int defaultUpdateIntervalSupplier() { - return this.updateInterval; - } - - public boolean trackDeltas() { -+ return velocityUpdateSupplier.test(this); -+ } -+ private boolean defaultVelocitySupplier() { - return this != PLAYER && this != LLAMA_SPIT && this != WITHER && this != BAT && this != ITEM_FRAME && this != GLOW_ITEM_FRAME && this != LEASH_KNOT && this != PAINTING && this != END_CRYSTAL && this != EVOKER_FANGS; - } - -@@ -639,6 +_,12 @@ - return this.builtInRegistryHolder; - } - -+ public T customClientSpawn(net.minecraftforge.network.packets.SpawnEntity packet, Level world) { -+ if (customClientFactory == null) return this.create(world); -+ return customClientFactory.apply(packet, world); -+ } -+ public Stream>> getTags() {return this.builtInRegistryHolder().tags();} ++ public EntityType(EntityType.EntityFactory p_273268_, MobCategory p_272918_, boolean p_273417_, boolean p_273389_, boolean p_273556_, boolean p_272654_, ImmutableSet p_273631_, EntityDimensions p_272946_, float p_332711_, int p_272895_, int p_273451_, FeatureFlagSet p_273518_) { ++ this(p_273268_, p_272918_, p_273417_, p_273389_, p_273556_, p_272654_, p_273631_, p_272946_, p_332711_, p_272895_, p_273451_, p_273518_, null); ++ } + - public static class Builder { - private final EntityType.EntityFactory factory; - private final MobCategory category; -@@ -652,6 +_,11 @@ - private EntityDimensions dimensions = EntityDimensions.scalable(0.6F, 1.8F); - private FeatureFlagSet requiredFeatures = FeatureFlags.VANILLA_SET; + public EntityType( + EntityType.EntityFactory p_273268_, + MobCategory p_272918_, +@@ -764,7 +_,8 @@ + float p_332711_, + int p_272895_, + int p_273451_, +- FeatureFlagSet p_273518_ ++ FeatureFlagSet p_273518_, ++ Builder builder + ) { + this.factory = p_273268_; + this.category = p_272918_; +@@ -778,6 +_,10 @@ + this.clientTrackingRange = p_272895_; + this.updateInterval = p_273451_; + this.requiredFeatures = p_273518_; ++ this.velocityUpdateSupplier = builder == null || builder.velocityUpdateSupplier == null ? EntityType::defaultVelocitySupplier : builder.velocityUpdateSupplier; ++ this.trackingRangeSupplier = builder == null || builder.trackingRangeSupplier == null ? EntityType::defaultTrackingRangeSupplier : builder.trackingRangeSupplier; ++ this.updateIntervalSupplier = builder == null || builder.updateIntervalSupplier == null ? EntityType::defaultUpdateIntervalSupplier : builder.updateIntervalSupplier; ++ this.customClientFactory = builder == null ? null : builder.customClientFactory; + } -+ private java.util.function.Predicate> velocityUpdateSupplier = EntityType::defaultVelocitySupplier; -+ private java.util.function.ToIntFunction> trackingRangeSupplier = EntityType::defaultTrackingRangeSupplier; -+ private java.util.function.ToIntFunction> updateIntervalSupplier = EntityType::defaultUpdateIntervalSupplier; -+ private java.util.function.BiFunction customClientFactory; -+ - private Builder(EntityType.EntityFactory p_20696_, MobCategory p_20697_) { - this.factory = p_20696_; - this.category = p_20697_; -@@ -713,12 +_,36 @@ - return this; - } + @Nullable +@@ -1054,14 +_,26 @@ + } -+ public EntityType.Builder setUpdateInterval(int interval) { -+ this.updateIntervalSupplier = t->interval; -+ return this; -+ } + public int clientTrackingRange() { ++ return trackingRangeSupplier.applyAsInt(this); ++ } + -+ public EntityType.Builder setTrackingRange(int range) { -+ this.trackingRangeSupplier = t->range; -+ return this; -+ } -+ -+ public EntityType.Builder setShouldReceiveVelocityUpdates(boolean value) { -+ this.velocityUpdateSupplier = t->value; -+ return this; -+ } -+ -+ /** -+ * By default, entities are spawned clientside via {@link EntityType#create(Level)}}. -+ * If you need finer control over the spawning process, use this to get read access to the spawn packet. -+ */ -+ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) { -+ this.customClientFactory = customClientFactory; -+ return this; -+ } -+ - public EntityType build(String p_20713_) { - if (this.serialize) { - Util.fetchChoiceType(References.ENTITY_TREE, p_20713_); - } ++ private int defaultTrackingRangeSupplier() { + return this.clientTrackingRange; + } -- return new EntityType<>(this.factory, this.category, this.serialize, this.summon, this.fireImmune, this.canSpawnFarFromPlayer, this.immuneTo, this.dimensions, this.clientTrackingRange, this.updateInterval, this.requiredFeatures); -+ return new EntityType<>(this.factory, this.category, this.serialize, this.summon, this.fireImmune, this.canSpawnFarFromPlayer, this.immuneTo, this.dimensions, this.clientTrackingRange, this.updateInterval, this.requiredFeatures, velocityUpdateSupplier, trackingRangeSupplier, updateIntervalSupplier, customClientFactory); - } - } + public int updateInterval() { ++ return updateIntervalSupplier.applyAsInt(this); ++ } ++ ++ private int defaultUpdateIntervalSupplier() { + return this.updateInterval; + } + public boolean trackDeltas() { ++ return velocityUpdateSupplier.test(this); ++ } ++ ++ private boolean defaultVelocitySupplier() { + return this != PLAYER + && this != LLAMA_SPIT + && this != WITHER +@@ -1097,6 +_,12 @@ + return this.builtInRegistryHolder; + } + ++ public T customClientSpawn(net.minecraftforge.network.packets.SpawnEntity packet, Level world) { ++ if (customClientFactory == null) return this.create(world); ++ return customClientFactory.apply(packet, world); ++ } ++ public Stream>> getTags() {return this.builtInRegistryHolder().tags();} ++ + public static class Builder { + private final EntityType.EntityFactory factory; + private final MobCategory category; +@@ -1111,6 +_,10 @@ + private float spawnDimensionsScale = 1.0F; + private EntityAttachments.Builder attachments = EntityAttachments.builder(); + private FeatureFlagSet requiredFeatures = FeatureFlags.VANILLA_SET; ++ private java.util.function.Predicate> velocityUpdateSupplier = EntityType::defaultVelocitySupplier; ++ private java.util.function.ToIntFunction> trackingRangeSupplier = EntityType::defaultTrackingRangeSupplier; ++ private java.util.function.ToIntFunction> updateIntervalSupplier = EntityType::defaultUpdateIntervalSupplier; ++ private java.util.function.BiFunction customClientFactory; + + private Builder(EntityType.EntityFactory p_20696_, MobCategory p_20697_) { + this.factory = p_20696_; +@@ -1219,6 +_,30 @@ + return this; + } + ++ public EntityType.Builder setUpdateInterval(int interval) { ++ this.updateIntervalSupplier = t->interval; ++ return this; ++ } ++ ++ public EntityType.Builder setTrackingRange(int range) { ++ this.trackingRangeSupplier = t->range; ++ return this; ++ } ++ ++ public EntityType.Builder setShouldReceiveVelocityUpdates(boolean value) { ++ this.velocityUpdateSupplier = t->value; ++ return this; ++ } ++ ++ /** ++ * By default, entities are spawned clientside via {@link EntityType#create(Level)}}. ++ * If you need finer control over the spawning process, use this to get read access to the spawn packet. ++ */ ++ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) { ++ this.customClientFactory = customClientFactory; ++ return this; ++ } ++ + public EntityType build(String p_20713_) { + if (this.serialize) { + Util.fetchChoiceType(References.ENTITY_TREE, p_20713_); +@@ -1236,7 +_,8 @@ + this.spawnDimensionsScale, + this.clientTrackingRange, + this.updateInterval, +- this.requiredFeatures ++ this.requiredFeatures, ++ this + ); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch index 0fae343e1b..180bc1b41c 100644 --- a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch @@ -1,37 +1,37 @@ --- a/net/minecraft/world/entity/ExperienceOrb.java +++ b/net/minecraft/world/entity/ExperienceOrb.java -@@ -90,7 +_,8 @@ - this.move(MoverType.SELF, this.getDeltaMovement()); - float f = 0.98F; - if (this.onGround()) { -- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; -+ BlockPos pos = getBlockPosBelowThatAffectsMyMovement(); -+ f = this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; - } +@@ -107,7 +_,8 @@ + this.move(MoverType.SELF, this.getDeltaMovement()); + float f = 0.98F; + if (this.onGround()) { +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; ++ BlockPos pos = getBlockPosBelowThatAffectsMyMovement(); ++ f = this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; + } - this.setDeltaMovement(this.getDeltaMovement().multiply((double)f, 0.98D, (double)f)); -@@ -172,6 +_,7 @@ - } + this.setDeltaMovement(this.getDeltaMovement().multiply((double)f, 0.98, (double)f)); +@@ -188,6 +_,7 @@ - public boolean hurt(DamageSource p_20785_, float p_20786_) { -+ if (this.level().isClientSide || this.isRemoved()) return false; //Forge: Fixes MC-53850 - if (this.isInvulnerableTo(p_20785_)) { - return false; - } else if (this.level().isClientSide) { -@@ -204,6 +_,7 @@ - public void playerTouch(Player p_20792_) { - if (!this.level().isClientSide) { - if (p_20792_.takeXpDelay == 0) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.PlayerXpEvent.PickupXp(p_20792_, this))) return; - p_20792_.takeXpDelay = 2; - p_20792_.take(this, 1); - int i = this.repairPlayerItems(p_20792_, this.value); -@@ -224,7 +_,7 @@ - Map.Entry entry = EnchantmentHelper.getRandomItemWith(Enchantments.MENDING, p_147093_, ItemStack::isDamaged); - if (entry != null) { - ItemStack itemstack = entry.getValue(); -- int i = Math.min(this.xpToDurability(p_147094_), itemstack.getDamageValue()); -+ int i = Math.min((int) (p_147094_ * itemstack.getXpRepairRatio()), itemstack.getDamageValue()); - itemstack.setDamageValue(itemstack.getDamageValue() - i); - int j = p_147094_ - this.durabilityToXp(i); - return j > 0 ? this.repairPlayerItems(p_147093_, j) : 0; + @Override + public boolean hurt(DamageSource p_20785_, float p_20786_) { ++ if (this.level().isClientSide || this.isRemoved()) return false; //Forge: Fixes MC-53850 + if (this.isInvulnerableTo(p_20785_)) { + return false; + } else if (this.level().isClientSide) { +@@ -223,6 +_,7 @@ + public void playerTouch(Player p_20792_) { + if (!this.level().isClientSide) { + if (p_20792_.takeXpDelay == 0) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPlayerPickupXp(p_20792_, this)) return; + p_20792_.takeXpDelay = 2; + p_20792_.take(this, 1); + int i = this.repairPlayerItems(p_20792_, this.value); +@@ -242,7 +_,7 @@ + Entry entry = EnchantmentHelper.getRandomItemWith(Enchantments.MENDING, p_147093_, ItemStack::isDamaged); + if (entry != null) { + ItemStack itemstack = entry.getValue(); +- int i = Math.min(this.xpToDurability(p_147094_), itemstack.getDamageValue()); ++ int i = Math.min((int)(p_147094_ * itemstack.getXpRepairRatio()), itemstack.getDamageValue()); + itemstack.setDamageValue(itemstack.getDamageValue() - i); + int j = p_147094_ - this.durabilityToXp(i); + return j > 0 ? this.repairPlayerItems(p_147093_, j) : 0; diff --git a/patches/minecraft/net/minecraft/world/entity/FlyingMob.java.patch b/patches/minecraft/net/minecraft/world/entity/FlyingMob.java.patch index db19c0ff6d..b60e5c8aec 100644 --- a/patches/minecraft/net/minecraft/world/entity/FlyingMob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/FlyingMob.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/entity/FlyingMob.java +++ b/net/minecraft/world/entity/FlyingMob.java -@@ -24,15 +_,16 @@ - this.move(MoverType.SELF, this.getDeltaMovement()); - this.setDeltaMovement(this.getDeltaMovement().scale(0.5D)); - } else { -+ BlockPos ground = getBlockPosBelowThatAffectsMyMovement(); - float f = 0.91F; - if (this.onGround()) { -- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.91F; -+ f = this.level().getBlockState(ground).getFriction(this.level(), ground, this) * 0.91F; - } +@@ -26,15 +_,16 @@ + this.move(MoverType.SELF, this.getDeltaMovement()); + this.setDeltaMovement(this.getDeltaMovement().scale(0.5)); + } else { ++ BlockPos ground = getBlockPosBelowThatAffectsMyMovement(); + float f = 0.91F; + if (this.onGround()) { +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.91F; ++ f = this.level().getBlockState(ground).getFriction(this.level(), ground, this) * 0.91F; + } - float f1 = 0.16277137F / (f * f * f); - f = 0.91F; - if (this.onGround()) { -- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.91F; -+ f = this.level().getBlockState(ground).getFriction(this.level(), ground, this) * 0.91F; - } + float f1 = 0.16277137F / (f * f * f); + f = 0.91F; + if (this.onGround()) { +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.91F; ++ f = this.level().getBlockState(ground).getFriction(this.level(), ground, this) * 0.91F; + } - this.moveRelative(this.onGround() ? 0.1F * f1 : 0.02F, p_20818_); + this.moveRelative(this.onGround() ? 0.1F * f1 : 0.02F, p_20818_); diff --git a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch index 5e0a51c5ce..5006d229f1 100644 --- a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch @@ -1,33 +1,33 @@ --- a/net/minecraft/world/entity/LightningBolt.java +++ b/net/minecraft/world/entity/LightningBolt.java -@@ -37,6 +_,7 @@ - private ServerPlayer cause; - private final Set hitEntities = Sets.newHashSet(); - private int blocksSetOnFire; -+ private float damage = 5.0F; +@@ -38,6 +_,7 @@ + private ServerPlayer cause; + private final Set hitEntities = Sets.newHashSet(); + private int blocksSetOnFire; ++ private float damage = 5.0F; - public LightningBolt(EntityType p_20865_, Level p_20866_) { - super(p_20865_, p_20866_); -@@ -72,6 +_,14 @@ + public LightningBolt(EntityType p_20865_, Level p_20866_) { + super(p_20865_, p_20866_); +@@ -65,6 +_,14 @@ + this.cause = p_20880_; + } - } - -+ public void setDamage(float damage) { -+ this.damage = damage; -+ } ++ public void setDamage(float damage) { ++ this.damage = damage; ++ } + -+ public float getDamage() { -+ return this.damage; -+ } ++ public float getDamage() { ++ return this.damage; ++ } + - public void tick() { - super.tick(); - if (this.life == 2) { -@@ -121,6 +_,7 @@ - List list1 = this.level().getEntities(this, new AABB(this.getX() - 3.0D, this.getY() - 3.0D, this.getZ() - 3.0D, this.getX() + 3.0D, this.getY() + 6.0D + 3.0D, this.getZ() + 3.0D), Entity::isAlive); + private void powerLightningRod() { + BlockPos blockpos = this.getStrikePosition(); + BlockState blockstate = this.level().getBlockState(blockpos); +@@ -163,6 +_,7 @@ + ); - for(Entity entity : list1) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onEntityStruckByLightning(entity, this)) - entity.thunderHit((ServerLevel)this.level(), this); - } + for (Entity entity : list1) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onEntityStruckByLightning(entity, this)) + entity.thunderHit((ServerLevel)this.level(), this); + } diff --git a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch index 9cb7214937..7baf0da0fa 100644 --- a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch @@ -1,767 +1,694 @@ --- a/net/minecraft/world/entity/LivingEntity.java +++ b/net/minecraft/world/entity/LivingEntity.java -@@ -119,12 +_,14 @@ - import net.minecraft.world.scores.PlayerTeam; +@@ -126,14 +_,16 @@ + import net.minecraft.world.scores.Scoreboard; import org.slf4j.Logger; -public abstract class LivingEntity extends Entity implements Attackable { +public abstract class LivingEntity extends Entity implements Attackable, net.minecraftforge.common.extensions.IForgeLivingEntity { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final String TAG_ACTIVE_EFFECTS = "active_effects"; - private static final UUID SPEED_MODIFIER_SOUL_SPEED_UUID = UUID.fromString("87f46a96-686f-4796-b035-22e16ee9e038"); - private static final UUID SPEED_MODIFIER_POWDER_SNOW_UUID = UUID.fromString("1eaf83ff-7207-4596-b37a-d7a07b3ec4ce"); -+ private static final UUID SLOW_FALLING_ID = UUID.fromString("A5B6CF2A-2F7C-31EF-9022-7C3E7D5E6ABA"); - private static final AttributeModifier SPEED_MODIFIER_SPRINTING = new AttributeModifier(UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D"), "Sprinting speed boost", (double)0.3F, AttributeModifier.Operation.MULTIPLY_TOTAL); -+ private static final AttributeModifier SLOW_FALLING = new AttributeModifier(SLOW_FALLING_ID, "Slow falling acceleration reduction", -0.07, AttributeModifier.Operation.ADDITION); // Add -0.07 to 0.08 so we get the vanilla default of 0.01 - public static final int HAND_SLOTS = 2; - public static final int ARMOR_SLOTS = 4; - public static final int EQUIPMENT_SLOT_OFFSET = 98; -@@ -238,7 +_,8 @@ - this.yHeadRot = this.getYRot(); - this.setMaxUpStep(0.6F); - NbtOps nbtops = NbtOps.INSTANCE; -- this.brain = this.makeBrain(new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap())))); -+ var dyn = new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap()))); -+ this.brain = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.makeBrain(dyn), dyn); - } + private static final Logger LOGGER = LogUtils.getLogger(); + private static final String TAG_ACTIVE_EFFECTS = "active_effects"; + private static final UUID SPEED_MODIFIER_SOUL_SPEED_UUID = UUID.fromString("87f46a96-686f-4796-b035-22e16ee9e038"); + private static final UUID SPEED_MODIFIER_POWDER_SNOW_UUID = UUID.fromString("1eaf83ff-7207-4596-b37a-d7a07b3ec4ce"); ++ private static final UUID SLOW_FALLING_ID = UUID.fromString("A5B6CF2A-2F7C-31EF-9022-7C3E7D5E6ABA"); + private static final AttributeModifier SPEED_MODIFIER_SPRINTING = new AttributeModifier( + UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D"), "Sprinting speed boost", 0.3F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL + ); ++ private static final AttributeModifier SLOW_FALLING = new AttributeModifier(SLOW_FALLING_ID, "Slow falling acceleration reduction", -0.07, AttributeModifier.Operation.ADD_VALUE); // Add -0.07 to 0.08 so we get the vanilla default of 0.01 + public static final int HAND_SLOTS = 2; + public static final int ARMOR_SLOTS = 4; + public static final int EQUIPMENT_SLOT_OFFSET = 98; +@@ -250,7 +_,8 @@ + this.setYRot((float)(Math.random() * (float) (Math.PI * 2))); + this.yHeadRot = this.getYRot(); + NbtOps nbtops = NbtOps.INSTANCE; +- this.brain = this.makeBrain(new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap())))); ++ var dyn = new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap()))); ++ this.brain = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.makeBrain(dyn), dyn); + } - public Brain getBrain() { -@@ -272,7 +_,7 @@ - } + public Brain getBrain() { +@@ -298,7 +_,9 @@ + .add(Attributes.GRAVITY) + .add(Attributes.SAFE_FALL_DISTANCE) + .add(Attributes.FALL_DAMAGE_MULTIPLIER) +- .add(Attributes.JUMP_STRENGTH); ++ .add(Attributes.JUMP_STRENGTH) ++ .add(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()) ++ .add(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.getHolder().get()); + } - public static AttributeSupplier.Builder createLivingAttributes() { -- return AttributeSupplier.builder().add(Attributes.MAX_HEALTH).add(Attributes.KNOCKBACK_RESISTANCE).add(Attributes.MOVEMENT_SPEED).add(Attributes.ARMOR).add(Attributes.ARMOR_TOUGHNESS).add(Attributes.MAX_ABSORPTION); -+ return AttributeSupplier.builder().add(Attributes.MAX_HEALTH).add(Attributes.KNOCKBACK_RESISTANCE).add(Attributes.MOVEMENT_SPEED).add(Attributes.ARMOR).add(Attributes.ARMOR_TOUGHNESS).add(Attributes.MAX_ABSORPTION).add(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).add(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.get()).add(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()).add(net.minecraftforge.common.ForgeMod.STEP_HEIGHT_ADDITION.get()); - } - - protected void checkFallDamage(double p_20990_, boolean p_20991_, BlockState p_20992_, BlockPos p_20993_) { -@@ -301,7 +_,8 @@ - float f = (float)Mth.ceil(this.fallDistance - 3.0F); - double d4 = Math.min((double)(0.2F + f / 15.0F), 2.5D); - int i = (int)(150.0D * d4); -- ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, p_20992_), d0, d1, d2, i, 0.0D, 0.0D, 0.0D, (double)0.15F); -+ if (!p_20992_.addLandingEffects((ServerLevel) this.level(), p_20993_, p_20992_, this, i)) -+ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, p_20992_).setPos(p_20993_), d0, d1, d2, i, 0.0D, 0.0D, 0.0D, (double)0.15F); - } - - super.checkFallDamage(p_20990_, p_20991_, p_20992_, p_20993_); -@@ -311,6 +_,7 @@ - - } - -+ @Deprecated //FORGE: Use canDrownInFluidType instead - public final boolean canBreatheUnderwater() { - return this.getType().is(EntityTypeTags.CAN_BREATHE_UNDER_WATER); - } -@@ -351,6 +_,9 @@ + @Override +@@ -327,7 +_,8 @@ + float f = (float)Mth.ceil((double)this.fallDistance - d0); + double d5 = Math.min((double)(0.2F + f / 15.0F), 2.5); + int i = (int)(150.0 * d5); +- ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, p_20992_), d1, d2, d3, i, 0.0, 0.0, 0.0, 0.15F); ++ if (!p_20992_.addLandingEffects((ServerLevel) this.level(), p_20993_, p_20992_, this, i)) ++ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, p_20992_).setPos(p_20993_), d1, d2, d3, i, 0.0, 0.0, 0.0, 0.15F); } - } + } -+ int airSupply = this.getAirSupply(); -+ net.minecraftforge.common.ForgeHooks.onLivingBreathe(this, airSupply - decreaseAirSupply(airSupply), increaseAirSupply(airSupply) - airSupply); -+ if (false) // Forge: Handled in ForgeHooks#onLivingBreathe(LivingEntity, int, int) - if (this.isEyeInFluid(FluidTags.WATER) && !this.level().getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { - boolean flag1 = !this.canBreatheUnderwater() && !MobEffectUtil.hasWaterBreathing(this) && (!flag || !((Player)this).getAbilities().invulnerable); - if (flag1) { -@@ -386,7 +_,7 @@ - } - } +@@ -337,6 +_,7 @@ + } + } -- if (this.isAlive() && (this.isInWaterRainOrBubble() || this.isInPowderSnow)) { -+ if (this.isAlive() && (this.isInWaterRainOrBubble() || this.isInPowderSnow || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { - this.extinguishFire(); - } - -@@ -733,7 +_,8 @@ - } - - if (p_21096_.contains("Brain", 10)) { -- this.brain = this.makeBrain(new Dynamic<>(NbtOps.INSTANCE, p_21096_.get("Brain"))); -+ var dyn = new Dynamic<>(NbtOps.INSTANCE, p_21096_.get("Brain")); -+ this.brain = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.makeBrain(dyn), dyn); - } - - } -@@ -748,7 +_,7 @@ - if (!mobeffectinstance.tick(this, () -> { - this.onEffectUpdated(mobeffectinstance, true, (Entity)null); - })) { -- if (!this.level().isClientSide) { -+ if (!this.level().isClientSide && !net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.MobEffectEvent.Expired(this, mobeffectinstance))) { - iterator.remove(); - this.onEffectRemoved(mobeffectinstance); - } -@@ -798,8 +_,10 @@ - this.setInvisible(false); - } else { - Collection collection = this.activeEffects.values(); -- this.entityData.set(DATA_EFFECT_AMBIENCE_ID, areAllEffectsAmbient(collection)); -- this.entityData.set(DATA_EFFECT_COLOR_ID, PotionUtils.getColor(collection)); -+ net.minecraftforge.event.entity.living.PotionColorCalculationEvent event = new net.minecraftforge.event.entity.living.PotionColorCalculationEvent(this, PotionUtils.getColor(collection), areAllEffectsAmbient(collection), collection); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ this.entityData.set(DATA_EFFECT_AMBIENCE_ID, event.areParticlesHidden()); -+ this.entityData.set(DATA_EFFECT_COLOR_ID, event.getColor()); - this.setInvisible(this.hasEffect(MobEffects.INVISIBILITY)); - } - -@@ -836,6 +_,7 @@ - } - } - -+ d0 = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, p_20969_, d0); - return d0; - } - -@@ -878,7 +_,9 @@ - - boolean flag; - for(flag = false; iterator.hasNext(); flag = true) { -- this.onEffectRemoved(iterator.next()); -+ MobEffectInstance effect = iterator.next(); -+ if(net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.MobEffectEvent.Remove(this, effect))) continue; -+ this.onEffectRemoved(effect); - iterator.remove(); - } - -@@ -913,6 +_,7 @@ - } else { - MobEffectInstance mobeffectinstance = this.activeEffects.get(p_147208_.getEffect()); - boolean flag = false; -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.MobEffectEvent.Added(this, mobeffectinstance, p_147208_, p_147209_)); - if (mobeffectinstance == null) { - this.activeEffects.put(p_147208_.getEffect(), p_147208_); - this.onEffectAdded(p_147208_, p_147209_); -@@ -928,6 +_,9 @@ - } - - public boolean canBeAffected(MobEffectInstance p_21197_) { -+ var event = new net.minecraftforge.event.entity.living.MobEffectEvent.Applicable(this, p_21197_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ if (event.getResult() != net.minecraftforge.eventbus.api.Event.Result.DEFAULT) return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW; - if (this.getMobType() == MobType.UNDEAD) { - MobEffect mobeffect = p_21197_.getEffect(); - if (mobeffect == MobEffects.REGENERATION || mobeffect == MobEffects.POISON) { -@@ -960,6 +_,7 @@ - } - - public boolean removeEffect(MobEffect p_21196_) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.MobEffectEvent.Remove(this, p_21196_))) return false; - MobEffectInstance mobeffectinstance = this.removeEffectNoUpdate(p_21196_); - if (mobeffectinstance != null) { - this.onEffectRemoved(mobeffectinstance); -@@ -1041,6 +_,8 @@ - } - - public void heal(float p_21116_) { -+ p_21116_ = net.minecraftforge.event.ForgeEventFactory.onLivingHeal(this, p_21116_); -+ if (p_21116_ <= 0) return; - float f = this.getHealth(); - if (f > 0.0F) { - this.setHealth(f + p_21116_); -@@ -1061,6 +_,7 @@ - } - - public boolean hurt(DamageSource p_21016_, float p_21017_) { -+ if (!net.minecraftforge.common.ForgeHooks.onLivingAttack(this, p_21016_, p_21017_)) return false; - if (this.isInvulnerableTo(p_21016_)) { - return false; - } else if (this.level().isClientSide) { -@@ -1079,9 +_,11 @@ - boolean flag = false; - float f1 = 0.0F; - if (p_21017_ > 0.0F && this.isDamageSourceBlocked(p_21016_)) { -- this.hurtCurrentlyUsedShield(p_21017_); -- f1 = p_21017_; -- p_21017_ = 0.0F; -+ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, p_21016_, p_21017_); -+ if(!ev.isCanceled()) { -+ if(ev.shieldTakesDamage()) this.hurtCurrentlyUsedShield(p_21017_); -+ f1 = ev.getBlockedDamage(); -+ p_21017_ -= ev.getBlockedDamage(); - if (!p_21016_.is(DamageTypeTags.IS_PROJECTILE)) { - Entity entity = p_21016_.getDirectEntity(); - if (entity instanceof LivingEntity) { -@@ -1090,7 +_,8 @@ - } ++ @Deprecated //FORGE: Use canDrownInFluidType instead + public final boolean canBreatheUnderwater() { + return this.getType().is(EntityTypeTags.CAN_BREATHE_UNDER_WATER); + } +@@ -378,6 +_,10 @@ + } } -- flag = true; -+ flag = p_21017_ <= 0; -+ } - } - - if (p_21016_.is(DamageTypeTags.IS_FREEZING) && this.getType().is(EntityTypeTags.FREEZE_HURTS_EXTRA_TYPES)) { -@@ -1133,11 +_,10 @@ - Player player1 = (Player)entity1; - this.lastHurtByPlayerTime = 100; - this.lastHurtByPlayer = player1; -- } else if (entity1 instanceof Wolf) { -- Wolf wolf = (Wolf)entity1; -- if (wolf.isTame()) { -+ } else if (entity1 instanceof net.minecraft.world.entity.TamableAnimal tamableEntity) { -+ if (tamableEntity.isTame()) { - this.lastHurtByPlayerTime = 100; -- LivingEntity livingentity2 = wolf.getOwner(); -+ LivingEntity livingentity2 = tamableEntity.getOwner(); - if (livingentity2 instanceof Player) { - Player player = (Player)livingentity2; - this.lastHurtByPlayer = player; -@@ -1196,7 +_,7 @@ - if (this instanceof ServerPlayer) { - CriteriaTriggers.ENTITY_HURT_PLAYER.trigger((ServerPlayer)this, p_21016_, f, p_21017_, flag); - if (f1 > 0.0F && f1 < 3.4028235E37F) { -- ((ServerPlayer)this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, Math.round(f1 * 10.0F)); -+ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_BLOCKED_BY_SHIELD), Math.round(f1 * 10.0F)); - } - } - -@@ -1224,7 +_,7 @@ - - for(InteractionHand interactionhand : InteractionHand.values()) { - ItemStack itemstack1 = this.getItemInHand(interactionhand); -- if (itemstack1.is(Items.TOTEM_OF_UNDYING)) { -+ if (itemstack1.is(Items.TOTEM_OF_UNDYING) && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, p_21263_, itemstack1, interactionhand)) { - itemstack = itemstack1.copy(); - itemstack1.shrink(1); - break; -@@ -1234,7 +_,7 @@ - if (itemstack != null) { - if (this instanceof ServerPlayer) { - ServerPlayer serverplayer = (ServerPlayer)this; -- serverplayer.awardStat(Stats.ITEM_USED.get(Items.TOTEM_OF_UNDYING)); -+ serverplayer.awardStat(Stats.ITEM_USED.get(Items.TOTEM_OF_UNDYING), 1); - CriteriaTriggers.USED_TOTEM.trigger(serverplayer, itemstack); - this.gameEvent(GameEvent.ITEM_INTERACT_FINISH); - } -@@ -1302,6 +_,7 @@ - } - - public void die(DamageSource p_21014_) { -+ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_21014_)) return; - if (!this.isRemoved() && !this.dead) { - Entity entity = p_21014_.getEntity(); - LivingEntity livingentity = this.getKillCredit(); -@@ -1339,10 +_,10 @@ - if (!this.level().isClientSide) { - boolean flag = false; - if (p_21269_ instanceof WitherBoss) { -- if (this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), p_21269_)) { - BlockPos blockpos = this.blockPosition(); - BlockState blockstate = Blocks.WITHER_ROSE.defaultBlockState(); -- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { -+ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { - this.level().setBlock(blockpos, blockstate, 3); - flag = true; - } -@@ -1359,12 +_,9 @@ - - protected void dropAllDeathLoot(DamageSource p_21192_) { - Entity entity = p_21192_.getEntity(); -- int i; -- if (entity instanceof Player) { -- i = EnchantmentHelper.getMobLooting((LivingEntity)entity); -- } else { -- i = 0; -- } + -+ int i = net.minecraftforge.common.ForgeHooks.getLootingLevel(this, entity, p_21192_); -+ this.captureDrops(new java.util.ArrayList<>()); - - boolean flag = this.lastHurtByPlayerTime > 0; - if (this.shouldDropLoot() && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) { -@@ -1374,6 +_,10 @@ - - this.dropEquipment(); - this.dropExperience(); -+ -+ Collection drops = captureDrops(null); -+ if (!net.minecraftforge.common.ForgeHooks.onLivingDrops(this, p_21192_, drops, i, lastHurtByPlayerTime > 0)) -+ drops.forEach(e -> level().addFreshEntity(e)); - } - - protected void dropEquipment() { -@@ -1381,7 +_,8 @@ - - protected void dropExperience() { - if (this.level() instanceof ServerLevel && !this.wasExperienceConsumed() && (this.isAlwaysExperienceDropper() || this.lastHurtByPlayerTime > 0 && this.shouldDropExperience() && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT))) { -- ExperienceOrb.award((ServerLevel)this.level(), this.position(), this.getExperienceReward()); -+ int reward = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.lastHurtByPlayer, this.getExperienceReward()); -+ ExperienceOrb.award((ServerLevel) this.level(), this.position(), reward); - } - - } -@@ -1410,6 +_,11 @@ - } - - public void knockback(double p_147241_, double p_147242_, double p_147243_) { -+ net.minecraftforge.event.entity.living.LivingKnockBackEvent event = net.minecraftforge.common.ForgeHooks.onLivingKnockBack(this, (float) p_147241_, p_147242_, p_147243_); -+ if(event.isCanceled()) return; -+ p_147241_ = event.getStrength(); -+ p_147242_ = event.getRatioX(); -+ p_147243_ = event.getRatioZ(); - p_147241_ *= 1.0D - this.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); - if (!(p_147241_ <= 0.0D)) { - this.hasImpulse = true; -@@ -1481,15 +_,9 @@ - } else { - BlockPos blockpos = this.blockPosition(); - BlockState blockstate = this.getFeetBlockState(); -- if (blockstate.is(BlockTags.CLIMBABLE)) { -- this.lastClimbablePos = Optional.of(blockpos); -- return true; -- } else if (blockstate.getBlock() instanceof TrapDoorBlock && this.trapdoorUsableAsLadder(blockpos, blockstate)) { -- this.lastClimbablePos = Optional.of(blockpos); -- return true; -- } else { -- return false; -- } -+ Optional ladderPos = net.minecraftforge.common.ForgeHooks.isLivingOnLadder(blockstate, level(), blockpos, this); -+ if (ladderPos.isPresent()) this.lastClimbablePos = ladderPos; -+ return ladderPos.isPresent(); - } - } - -@@ -1509,6 +_,11 @@ - } - - public boolean causeFallDamage(float p_147187_, float p_147188_, DamageSource p_147189_) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_147187_, p_147188_); -+ if (event.isCanceled()) return false; -+ p_147187_ = event.getDistance(); -+ p_147188_ = event.getDamageMultiplier(); -+ - boolean flag = super.causeFallDamage(p_147187_, p_147188_, p_147189_); - int i = this.calculateFallDamage(p_147187_, p_147188_); - if (i > 0) { -@@ -1536,9 +_,10 @@ - int i = Mth.floor(this.getX()); - int j = Mth.floor(this.getY() - (double)0.2F); - int k = Mth.floor(this.getZ()); -- BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); -+ BlockPos pos = new BlockPos(i, j, k); -+ BlockState blockstate = this.level().getBlockState(pos); - if (!blockstate.isAir()) { -- SoundType soundtype = blockstate.getSoundType(); -+ SoundType soundtype = blockstate.getSoundType(level(), pos, this); - this.playSound(soundtype.getFallSound(), soundtype.getVolume() * 0.5F, soundtype.getPitch() * 0.75F); - } - -@@ -1585,9 +_,9 @@ - float f2 = f1 - p_21194_; - if (f2 > 0.0F && f2 < 3.4028235E37F) { - if (this instanceof ServerPlayer) { -- ((ServerPlayer)this).awardStat(Stats.DAMAGE_RESISTED, Math.round(f2 * 10.0F)); -+ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_RESISTED), Math.round(f2 * 10.0F)); - } else if (p_21193_.getEntity() instanceof ServerPlayer) { -- ((ServerPlayer)p_21193_.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f2 * 10.0F)); -+ ((ServerPlayer)p_21193_.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(f2 * 10.0F)); - } ++ int airSupply = this.getAirSupply(); ++ net.minecraftforge.common.ForgeHooks.onLivingBreathe(this, airSupply - decreaseAirSupply(airSupply), increaseAirSupply(airSupply) - airSupply); ++ if (false) // Forge: Handled in ForgeHooks#onLivingBreathe(LivingEntity, int, int) + if (this.isEyeInFluid(FluidTags.WATER) + && !this.level().getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { + boolean flag1 = !this.canBreatheUnderwater() && !MobEffectUtil.hasWaterBreathing(this) && (!flag || !((Player)this).getAbilities().invulnerable); +@@ -423,7 +_,7 @@ } - } -@@ -1609,6 +_,8 @@ + } - protected void actuallyHurt(DamageSource p_21240_, float p_21241_) { - if (!this.isInvulnerableTo(p_21240_)) { -+ p_21241_ = net.minecraftforge.common.ForgeHooks.onLivingHurt(this, p_21240_, p_21241_); -+ if (p_21241_ <= 0) return; - p_21241_ = this.getDamageAfterArmorAbsorb(p_21240_, p_21241_); - p_21241_ = this.getDamageAfterMagicAbsorb(p_21240_, p_21241_); - float f1 = Math.max(p_21241_ - this.getAbsorptionAmount(), 0.0F); -@@ -1622,6 +_,7 @@ +- if (this.isAlive() && (this.isInWaterRainOrBubble() || this.isInPowderSnow)) { ++ if (this.isAlive() && (this.isInWaterRainOrBubble() || this.isInPowderSnow || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType)))) { + this.extinguishFire(); + } + +@@ -808,7 +_,8 @@ + } + + if (p_21096_.contains("Brain", 10)) { +- this.brain = this.makeBrain(new Dynamic<>(NbtOps.INSTANCE, p_21096_.get("Brain"))); ++ var dyn = new Dynamic<>(NbtOps.INSTANCE, p_21096_.get("Brain")); ++ this.brain = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.makeBrain(dyn), dyn); + } + } + +@@ -820,7 +_,7 @@ + Holder holder = iterator.next(); + MobEffectInstance mobeffectinstance = this.activeEffects.get(holder); + if (!mobeffectinstance.tick(this, () -> this.onEffectUpdated(mobeffectinstance, true, null))) { +- if (!this.level().isClientSide) { ++ if (!this.level().isClientSide && !net.minecraftforge.event.ForgeEventFactory.onLivingEffectExpire(this, mobeffectinstance)) { + iterator.remove(); + this.onEffectRemoved(mobeffectinstance); + } +@@ -901,6 +_,7 @@ } - } + } -+ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, p_21240_, f1); - if (f1 != 0.0F) { - this.getCombatTracker().recordDamage(p_21240_, f1); - this.setHealth(this.getHealth() - f1); -@@ -1681,6 +_,8 @@ - } ++ d0 = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, p_20969_, d0); + return d0; + } - public void swing(InteractionHand p_21012_, boolean p_21013_) { -+ ItemStack stack = this.getItemInHand(p_21012_); -+ if (!stack.isEmpty() && stack.onEntitySwing(this)) return; - if (!this.swinging || this.swingTime >= this.getCurrentSwingDuration() / 2 || this.swingTime < 0) { - this.swingTime = -1; - this.swinging = true; -@@ -1791,8 +_,10 @@ +@@ -942,7 +_,11 @@ - private void swapHandItems() { - ItemStack itemstack = this.getItemBySlot(EquipmentSlot.OFFHAND); -- this.setItemSlot(EquipmentSlot.OFFHAND, this.getItemBySlot(EquipmentSlot.MAINHAND)); -- this.setItemSlot(EquipmentSlot.MAINHAND, itemstack); -+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this); -+ if (event.isCanceled()) return; -+ this.setItemSlot(EquipmentSlot.OFFHAND, event.getItemSwappedToOffHand()); -+ this.setItemSlot(EquipmentSlot.MAINHAND, event.getItemSwappedToMainHand()); - } - - protected void onBelowWorld() { -@@ -1982,14 +_,17 @@ - } - - this.hasImpulse = true; -+ net.minecraftforge.common.ForgeHooks.onLivingJump(this); - } - -+ @Deprecated // FORGE: use sinkInFluid instead - protected void goDownInWater() { -- this.setDeltaMovement(this.getDeltaMovement().add(0.0D, (double)-0.04F, 0.0D)); -+ this.sinkInFluid(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); - } - -+ @Deprecated // FORGE: use jumpInFluid instead - protected void jumpInLiquid(TagKey p_204043_) { -- this.setDeltaMovement(this.getDeltaMovement().add(0.0D, (double)0.04F, 0.0D)); -+ this.setDeltaMovement(this.getDeltaMovement().add(0.0D, (double)0.04F * this.getAttribute(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).getValue(), 0.0D)); - } - - protected float getWaterSlowDown() { -@@ -2003,13 +_,19 @@ - public void travel(Vec3 p_21280_) { - if (this.isControlledByLocalInstance()) { - double d0 = 0.08D; -+ AttributeInstance gravity = this.getAttribute(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()); - boolean flag = this.getDeltaMovement().y <= 0.0D; - if (flag && this.hasEffect(MobEffects.SLOW_FALLING)) { -- d0 = 0.01D; -+ if (!gravity.hasModifier(SLOW_FALLING)) -+ gravity.addTransientModifier(SLOW_FALLING); -+ } else if (gravity.hasModifier(SLOW_FALLING)) { -+ gravity.removeModifier(SLOW_FALLING.getId()); - } -+ d0 = gravity.getValue(); - - FluidState fluidstate = this.level().getFluidState(this.blockPosition()); -- if (this.isInWater() && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { -+ if ((this.isInWater() || (this.isInFluidType(fluidstate) && fluidstate.getFluidType() != net.minecraftforge.common.ForgeMod.LAVA_TYPE.get())) && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { -+ if (this.isInWater() || (this.isInFluidType(fluidstate) && !this.moveInFluid(fluidstate, p_21280_, d0))) { - double d9 = this.getY(); - float f4 = this.isSprinting() ? 0.9F : this.getWaterSlowDown(); - float f5 = 0.02F; -@@ -2031,6 +_,7 @@ - f4 = 0.96F; + boolean flag; + for (flag = false; iterator.hasNext(); flag = true) { +- this.onEffectRemoved(iterator.next()); ++ var effect = iterator.next(); ++ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, effect)) { ++ continue; ++ } ++ this.onEffectRemoved(effect); + iterator.remove(); } -+ f5 *= (float)this.getAttribute(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).getValue(); - this.moveRelative(f5, p_21280_); - this.move(MoverType.SELF, this.getDeltaMovement()); - Vec3 vec36 = this.getDeltaMovement(); -@@ -2044,6 +_,7 @@ - if (this.horizontalCollision && this.isFree(vec32.x, vec32.y + (double)0.6F - this.getY() + d9, vec32.z)) { - this.setDeltaMovement(vec32.x, (double)0.3F, vec32.z); - } -+ } - } else if (this.isInLava() && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { - double d8 = this.getY(); - this.moveRelative(0.02F, p_21280_); -@@ -2106,7 +_,7 @@ - } - } else { - BlockPos blockpos = this.getBlockPosBelowThatAffectsMyMovement(); -- float f2 = this.level().getBlockState(blockpos).getBlock().getFriction(); -+ float f2 = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getFriction(level(), this.getBlockPosBelowThatAffectsMyMovement(), this); - float f3 = this.onGround() ? f2 * 0.91F : 0.91F; - Vec3 vec35 = this.handleRelativeFrictionAndCalculateMovement(p_21280_, f2); - double d2 = vec35.y; -@@ -2202,7 +_,7 @@ - double d0 = Mth.clamp(p_21298_.x, (double)-0.15F, (double)0.15F); - double d1 = Mth.clamp(p_21298_.z, (double)-0.15F, (double)0.15F); - double d2 = Math.max(p_21298_.y, (double)-0.15F); -- if (d2 < 0.0D && !this.getFeetBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { -+ if (d2 < 0.0D && !this.getFeetBlockState().isScaffolding(this) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { - d2 = 0.0D; - } +@@ -977,6 +_,7 @@ + } else { + MobEffectInstance mobeffectinstance = this.activeEffects.get(p_147208_.getEffect()); + boolean flag = false; ++ net.minecraftforge.event.ForgeEventFactory.onLivingEffectAdd(this, mobeffectinstance, p_147208_, p_147209_); + if (mobeffectinstance == null) { + this.activeEffects.put(p_147208_.getEffect(), p_147208_); + this.onEffectAdded(p_147208_, p_147209_); +@@ -993,6 +_,10 @@ + } -@@ -2234,6 +_,7 @@ - } + public boolean canBeAffected(MobEffectInstance p_21197_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingEffectCanApply(this, p_21197_); ++ if (event.getResult() != net.minecraftforge.eventbus.api.Event.Result.DEFAULT) { ++ return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW; ++ } + if (this.getType().is(EntityTypeTags.IMMUNE_TO_INFESTED)) { + return !p_21197_.is(MobEffects.INFESTED); + } else if (this.getType().is(EntityTypeTags.IMMUNE_TO_OOZING)) { +@@ -1026,6 +_,9 @@ + } - public void tick() { -+ if (net.minecraftforge.common.ForgeHooks.onLivingTick(this)) return; - super.tick(); - this.updatingUsingItem(); - this.updateSwimAmount(); -@@ -2386,6 +_,7 @@ + public boolean removeEffect(Holder p_335910_) { ++ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, p_335910_.get())) { ++ return false; ++ } + MobEffectInstance mobeffectinstance = this.removeEffectNoUpdate(p_335910_); + if (mobeffectinstance != null) { + this.onEffectRemoved(mobeffectinstance); +@@ -1100,6 +_,10 @@ + } - ItemStack itemstack1 = this.getItemBySlot(equipmentslot); - if (this.equipmentHasChanged(itemstack, itemstack1)) { -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.LivingEquipmentChangeEvent(this, equipmentslot, itemstack, itemstack1)); - if (map == null) { - map = Maps.newEnumMap(EquipmentSlot.class); - } -@@ -2529,6 +_,10 @@ - this.level().getProfiler().push("jump"); - if (this.jumping && this.isAffectedByFluids()) { - double d3; -+ var fluidType = this.getMaxHeightFluidType(); -+ if (!fluidType.isAir()) -+ d3 = this.getFluidTypeHeight(fluidType); -+ else - if (this.isInLava()) { - d3 = this.getFluidHeight(FluidTags.LAVA); - } else { -@@ -2539,15 +_,17 @@ - double d4 = this.getFluidJumpThreshold(); - if (!flag || this.onGround() && !(d3 > d4)) { - if (!this.isInLava() || this.onGround() && !(d3 > d4)) { -+ if (fluidType.isAir() || this.onGround() && !(d3 > d4)) { - if ((this.onGround() || flag && d3 <= d4) && this.noJumpDelay == 0) { - this.jumpFromGround(); - this.noJumpDelay = 10; - } -+ } else this.jumpInFluid(fluidType); - } else { -- this.jumpInLiquid(FluidTags.LAVA); -+ this.jumpInFluid(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); - } - } else { -- this.jumpInLiquid(FluidTags.WATER); -+ this.jumpInFluid(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); - } - } else { - this.noJumpDelay = 0; -@@ -2616,6 +_,8 @@ - boolean flag = this.getSharedFlag(7); - if (flag && !this.onGround() && !this.isPassenger() && !this.hasEffect(MobEffects.LEVITATION)) { - ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); -+ flag = itemstack.canElytraFly(this) && itemstack.elytraFlightTick(this, this.fallFlyTicks); -+ if (false) //Forge: Moved to ElytraItem - if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack)) { - flag = true; - int i = this.fallFlyTicks + 1; -@@ -2865,8 +_,11 @@ + public void heal(float p_21116_) { ++ p_21116_ = net.minecraftforge.event.ForgeEventFactory.onLivingHeal(this, p_21116_); ++ if (p_21116_ <= 0) { ++ return; ++ } + float f = this.getHealth(); + if (f > 0.0F) { + this.setHealth(f + p_21116_); +@@ -1120,6 +_,9 @@ - private void updatingUsingItem() { - if (this.isUsingItem()) { -- if (ItemStack.isSameItem(this.getItemInHand(this.getUsedItemHand()), this.useItem)) { -- this.useItem = this.getItemInHand(this.getUsedItemHand()); -+ ItemStack itemStack = this.getItemInHand(this.getUsedItemHand()); -+ if (net.minecraftforge.common.ForgeHooks.canContinueUsing(this.useItem, itemStack)) { -+ this.useItem = itemStack; -+ } -+ if (itemStack == this.useItem) { - this.updateUsingItem(this.useItem); - } else { - this.stopUsingItem(); -@@ -2876,12 +_,15 @@ - } - - protected void updateUsingItem(ItemStack p_147201_) { -+ if (!p_147201_.isEmpty()) -+ this.useItemRemaining = net.minecraftforge.event.ForgeEventFactory.onItemUseTick(this, p_147201_, this.getUseItemRemainingTicks()); -+ if (this.getUseItemRemainingTicks() > 0) - p_147201_.onUseTick(this.level(), this, this.getUseItemRemainingTicks()); - if (this.shouldTriggerItemUseEffects()) { - this.triggerItemUseEffects(p_147201_, 5); - } - -- if (--this.useItemRemaining == 0 && !this.level().isClientSide && !p_147201_.useOnRelease()) { -+ if (--this.useItemRemaining <= 0 && !this.level().isClientSide && !p_147201_.useOnRelease()) { - this.completeUsingItem(); - } - -@@ -2889,7 +_,7 @@ - - private boolean shouldTriggerItemUseEffects() { - int i = this.getUseItemRemainingTicks(); -- FoodProperties foodproperties = this.useItem.getItem().getFoodProperties(); -+ FoodProperties foodproperties = this.useItem.getFoodProperties(this); - boolean flag = foodproperties != null && foodproperties.isFastFood(); - flag |= i <= this.useItem.getUseDuration() - 7; - return flag && i % 4 == 0; -@@ -2919,8 +_,10 @@ - public void startUsingItem(InteractionHand p_21159_) { - ItemStack itemstack = this.getItemInHand(p_21159_); - if (!itemstack.isEmpty() && !this.isUsingItem()) { -+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration()); -+ if (duration <= 0) return; - this.useItem = itemstack; -- this.useItemRemaining = itemstack.getUseDuration(); -+ this.useItemRemaining = duration; - if (!this.level().isClientSide) { - this.setLivingEntityFlag(1, true); - this.setLivingEntityFlag(2, p_21159_ == InteractionHand.OFF_HAND); -@@ -2981,6 +_,9 @@ - vec31 = vec31.xRot(-this.getXRot() * ((float)Math.PI / 180F)); - vec31 = vec31.yRot(-this.getYRot() * ((float)Math.PI / 180F)); - vec31 = vec31.add(this.getX(), this.getEyeY(), this.getZ()); -+ if (this.level() instanceof ServerLevel) //Forge: Fix MC-2518 spawnParticle is nooped on server, need to use server specific variant -+ ((ServerLevel) this.level()).sendParticles(new ItemParticleOption(ParticleTypes.ITEM, p_21061_), vec31.x, vec31.y, vec31.z, 1, vec3.x, vec3.y + 0.05D, vec3.z, 0.0D); -+ else - this.level().addParticle(new ItemParticleOption(ParticleTypes.ITEM, p_21061_), vec31.x, vec31.y, vec31.z, vec3.x, vec3.y + 0.05D, vec3.z); - } - -@@ -2994,7 +_,8 @@ - } else { - if (!this.useItem.isEmpty() && this.isUsingItem()) { - this.triggerItemUseEffects(this.useItem, 16); -- ItemStack itemstack = this.useItem.finishUsingItem(this.level(), this); -+ ItemStack copy = this.useItem.copy(); -+ ItemStack itemstack = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), this.useItem.finishUsingItem(this.level(), this)); - if (itemstack != this.useItem) { - this.setItemInHand(interactionhand, itemstack); - } -@@ -3020,7 +_,11 @@ - - public void releaseUsingItem() { - if (!this.useItem.isEmpty()) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onUseItemStop(this, useItem, this.getUseItemRemainingTicks())) { -+ ItemStack copy = this instanceof Player ? useItem.copy() : null; - this.useItem.releaseUsing(this.level(), this, this.getUseItemRemainingTicks()); -+ if (copy != null && useItem.isEmpty()) net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem((Player)this, copy, getUsedItemHand()); -+ } - if (this.useItem.useOnRelease()) { - this.updatingUsingItem(); - } -@@ -3030,6 +_,7 @@ - } - - public void stopUsingItem() { -+ if (this.isUsingItem() && !this.useItem.isEmpty()) this.useItem.onStopUsing(this, useItemRemaining); - if (!this.level().isClientSide) { - boolean flag = this.isUsingItem(); - this.setLivingEntityFlag(1, false); -@@ -3045,7 +_,7 @@ - public boolean isBlocking() { - if (this.isUsingItem() && !this.useItem.isEmpty()) { - Item item = this.useItem.getItem(); -- if (item.getUseAnimation(this.useItem) != UseAnim.BLOCK) { -+ if (!this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { + @Override + public boolean hurt(DamageSource p_21016_, float p_21017_) { ++ if (!net.minecraftforge.common.ForgeHooks.onLivingAttack(this, p_21016_, p_21017_)) { ++ return false; ++ } + if (this.isInvulnerableTo(p_21016_)) { return false; - } else { - return item.getUseDuration(this.useItem) - this.useItemRemaining >= 5; -@@ -3177,8 +_,8 @@ - } + } else if (this.level().isClientSide) { +@@ -1138,14 +_,18 @@ + boolean flag = false; + float f1 = 0.0F; + if (p_21017_ > 0.0F && this.isDamageSourceBlocked(p_21016_)) { ++ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, p_21016_, p_21017_); ++ if (!ev.isCanceled()) { ++ if (ev.shieldTakesDamage()) + this.hurtCurrentlyUsedShield(p_21017_); +- f1 = p_21017_; +- p_21017_ = 0.0F; ++ f1 = ev.getBlockedDamage(); ++ p_21017_ -= ev.getBlockedDamage(); + if (!p_21016_.is(DamageTypeTags.IS_PROJECTILE) && p_21016_.getDirectEntity() instanceof LivingEntity livingentity) { + this.blockUsingShield(livingentity); + } - BlockState blockstate = this.level().getBlockState(p_21141_); -- if (blockstate.getBlock() instanceof BedBlock) { -- this.level().setBlock(p_21141_, blockstate.setValue(BedBlock.OCCUPIED, Boolean.valueOf(true)), 3); -+ if (blockstate.isBed(level(), p_21141_, this)) { -+ blockstate.setBedOccupied(level(), p_21141_, this, true); - } - - this.setPose(Pose.SLEEPING); -@@ -3194,16 +_,16 @@ - - private boolean checkBedExists() { - return this.getSleepingPos().map((p_309015_) -> { -- return this.level().getBlockState(p_309015_).getBlock() instanceof BedBlock; -+ return net.minecraftforge.event.ForgeEventFactory.fireSleepingLocationCheck(this, p_309015_); - }).orElse(false); - } - - public void stopSleeping() { - this.getSleepingPos().filter(this.level()::hasChunkAt).ifPresent((p_261435_) -> { - BlockState blockstate = this.level().getBlockState(p_261435_); -- if (blockstate.getBlock() instanceof BedBlock) { -+ if (blockstate.isBed(level(), p_261435_, this)) { - Direction direction = blockstate.getValue(BedBlock.FACING); -- this.level().setBlock(p_261435_, blockstate.setValue(BedBlock.OCCUPIED, Boolean.valueOf(false)), 3); -+ blockstate.setBedOccupied(level(), p_261435_, this, false); - Vec3 vec31 = BedBlock.findStandUpPosition(this.getType(), this.level(), p_261435_, direction, this.getYRot()).orElseGet(() -> { - BlockPos blockpos = p_261435_.above(); - return new Vec3((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.1D, (double)blockpos.getZ() + 0.5D); -@@ -3225,7 +_,9 @@ - @Nullable - public Direction getBedOrientation() { - BlockPos blockpos = this.getSleepingPos().orElse((BlockPos)null); -- return blockpos != null ? BedBlock.getBedOrientation(this.level(), blockpos) : null; -+ if (blockpos == null) return Direction.UP; -+ BlockState state = this.level().getBlockState(blockpos); -+ return !state.isBed(level(), blockpos, this) ? Direction.UP : state.getBedDirection(level(), blockpos); - } - - public boolean isInWall() { -@@ -3241,7 +_,7 @@ - } - - public ItemStack getProjectile(ItemStack p_21272_) { -- return ItemStack.EMPTY; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_21272_, ItemStack.EMPTY); - } - - public ItemStack eat(Level p_21067_, ItemStack p_21068_) { -@@ -3261,7 +_,7 @@ - private void addEatEffect(ItemStack p_21064_, Level p_21065_, LivingEntity p_21066_) { - Item item = p_21064_.getItem(); - if (item.isEdible()) { -- for(Pair pair : item.getFoodProperties().getEffects()) { -+ for(Pair pair : p_21064_.getFoodProperties(this).getEffects()) { - if (!p_21065_.isClientSide && pair.getFirst() != null && p_21065_.random.nextFloat() < pair.getSecond()) { - p_21066_.addEffect(new MobEffectInstance(pair.getFirst())); +- flag = true; ++ flag = p_21017_ <= 0; ++ } } -@@ -3297,6 +_,64 @@ - this.broadcastBreakEvent(p_21191_ == InteractionHand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND); - } -+ /* ==== FORGE START ==== */ -+ /*** -+ * Removes all potion effects that have curativeItem as a curative item for its effect -+ * @param curativeItem The itemstack we are using to cure potion effects -+ */ -+ public boolean curePotionEffects(ItemStack curativeItem) { -+ if (this.level().isClientSide) -+ return false; -+ boolean ret = false; -+ Iterator itr = this.activeEffects.values().iterator(); -+ while (itr.hasNext()) { -+ MobEffectInstance effect = itr.next(); -+ if (effect.isCurativeItem(curativeItem) && !net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.living.MobEffectEvent.Remove(this, effect))) { -+ this.onEffectRemoved(effect); -+ itr.remove(); -+ ret = true; -+ this.effectsDirty = true; -+ } -+ } -+ return ret; -+ } -+ -+ /** -+ * Returns true if the entity's rider (EntityPlayer) should face forward when mounted. -+ * currently only used in vanilla code by pigs. -+ * -+ * @param player The player who is riding the entity. -+ * @return If the player should orient the same direction as this entity. -+ */ -+ public boolean shouldRiderFaceForward(Player player) { -+ return this instanceof net.minecraft.world.entity.animal.Pig; -+ } -+ -+ private net.minecraftforge.common.util.LazyOptional[] handlers = net.minecraftforge.items.wrapper.EntityEquipmentInvWrapper.create(this); -+ -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { -+ if (facing == null) return handlers[2].cast(); -+ else if (facing.getAxis().isVertical()) return handlers[0].cast(); -+ else if (facing.getAxis().isHorizontal()) return handlers[1].cast(); -+ } -+ return super.getCapability(capability, facing); -+ } -+ -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ for (int x = 0; x < handlers.length; x++) -+ handlers[x].invalidate(); -+ } -+ -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ handlers = net.minecraftforge.items.wrapper.EntityEquipmentInvWrapper.create(this); -+ } -+ - public AABB getBoundingBoxForCulling() { - if (this.getItemBySlot(EquipmentSlot.HEAD).is(Items.DRAGON_HEAD)) { - float f = 0.5F; -@@ -3307,6 +_,8 @@ - } + if (p_21016_.is(DamageTypeTags.IS_FREEZING) && this.getType().is(EntityTypeTags.FREEZE_HURTS_EXTRA_TYPES)) { +@@ -1186,7 +_,7 @@ + if (entity instanceof Player player1) { + this.lastHurtByPlayerTime = 100; + this.lastHurtByPlayer = player1; +- } else if (entity instanceof Wolf wolf && wolf.isTame()) { ++ } else if (entity instanceof net.minecraft.world.entity.TamableAnimal wolf && wolf.isTame()) { + this.lastHurtByPlayerTime = 100; + if (wolf.getOwner() instanceof Player player) { + this.lastHurtByPlayer = player; +@@ -1247,7 +_,7 @@ + if (this instanceof ServerPlayer) { + CriteriaTriggers.ENTITY_HURT_PLAYER.trigger((ServerPlayer)this, p_21016_, f, p_21017_, flag); + if (f1 > 0.0F && f1 < 3.4028235E37F) { +- ((ServerPlayer)this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, Math.round(f1 * 10.0F)); ++ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_BLOCKED_BY_SHIELD), Math.round(f1 * 10.0F)); + } + } - public static EquipmentSlot getEquipmentSlotForItem(ItemStack p_147234_) { -+ final EquipmentSlot slot = p_147234_.getEquipmentSlot(); -+ if (slot != null) return slot; // FORGE: Allow modders to set a non-default equipment slot for a stack; e.g. a non-armor chestplate-slot item - Equipable equipable = Equipable.get(p_147234_); - return equipable != null ? equipable.getEquipmentSlot() : EquipmentSlot.MAINHAND; - } +@@ -1275,7 +_,7 @@ + + for (InteractionHand interactionhand : InteractionHand.values()) { + ItemStack itemstack1 = this.getItemInHand(interactionhand); +- if (itemstack1.is(Items.TOTEM_OF_UNDYING)) { ++ if (itemstack1.is(Items.TOTEM_OF_UNDYING) && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, p_21263_, itemstack1, interactionhand)) { + itemstack = itemstack1.copy(); + itemstack1.shrink(1); + break; +@@ -1361,6 +_,7 @@ + } + + public void die(DamageSource p_21014_) { ++ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_21014_)) return; + if (!this.isRemoved() && !this.dead) { + Entity entity = p_21014_.getEntity(); + LivingEntity livingentity = this.getKillCredit(); +@@ -1396,10 +_,10 @@ + if (!this.level().isClientSide) { + boolean flag = false; + if (p_21269_ instanceof WitherBoss) { +- if (this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), p_21269_)) { + BlockPos blockpos = this.blockPosition(); + BlockState blockstate = Blocks.WITHER_ROSE.defaultBlockState(); +- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { ++ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { + this.level().setBlock(blockpos, blockstate, 3); + flag = true; + } +@@ -1422,6 +_,8 @@ + i = 0; + } + ++ i = net.minecraftforge.common.ForgeHooks.getLootingLevel(this, entity, p_21192_); ++ this.captureDrops(new java.util.ArrayList<>()); + boolean flag = this.lastHurtByPlayerTime > 0; + if (this.shouldDropLoot() && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) { + this.dropFromLootTable(p_21192_, flag); +@@ -1430,6 +_,11 @@ + + this.dropEquipment(); + this.dropExperience(); ++ ++ var drops = captureDrops(null); ++ if (!net.minecraftforge.common.ForgeHooks.onLivingDrops(this, p_21192_, drops, i, lastHurtByPlayerTime > 0)) { ++ drops.forEach(e -> level().addFreshEntity(e)); ++ } + } + + protected void dropEquipment() { +@@ -1439,7 +_,8 @@ + if (this.level() instanceof ServerLevel + && !this.wasExperienceConsumed() + && (this.isAlwaysExperienceDropper() || this.lastHurtByPlayerTime > 0 && this.shouldDropExperience() && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT))) { +- ExperienceOrb.award((ServerLevel)this.level(), this.position(), this.getExperienceReward()); ++ int reward = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.lastHurtByPlayer, this.getExperienceReward()); ++ ExperienceOrb.award((ServerLevel) this.level(), this.position(), reward); + } + } + +@@ -1472,6 +_,11 @@ + } + + public void knockback(double p_147241_, double p_147242_, double p_147243_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingKnockBack(this, (float) p_147241_, p_147242_, p_147243_); ++ if (event.isCanceled()) return; ++ p_147241_ = event.getStrength(); ++ p_147242_ = event.getRatioX(); ++ p_147243_ = event.getRatioZ(); + p_147241_ *= 1.0 - this.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); + if (!(p_147241_ <= 0.0)) { + this.hasImpulse = true; +@@ -1547,6 +_,13 @@ + } else { + BlockPos blockpos = this.blockPosition(); + BlockState blockstate = this.getInBlockState(); ++ var ladderPos = net.minecraftforge.common.ForgeHooks.isLivingOnLadder(blockstate, level(), blockpos, this); ++ if (ladderPos.isPresent()) { ++ this.lastClimbablePos = ladderPos; ++ return true; ++ } else if (ladderPos != null) { ++ return false; ++ } + if (blockstate.is(BlockTags.CLIMBABLE)) { + this.lastClimbablePos = Optional.of(blockpos); + return true; +@@ -1586,6 +_,10 @@ + + @Override + public boolean causeFallDamage(float p_147187_, float p_147188_, DamageSource p_147189_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_147187_, p_147188_); ++ if (event.isCanceled()) return false; ++ p_147187_ = event.getDistance(); ++ p_147188_ = event.getDamageMultiplier(); + boolean flag = super.causeFallDamage(p_147187_, p_147188_, p_147189_); + int i = this.calculateFallDamage(p_147187_, p_147188_); + if (i > 0) { +@@ -1613,9 +_,10 @@ + int i = Mth.floor(this.getX()); + int j = Mth.floor(this.getY() - 0.2F); + int k = Mth.floor(this.getZ()); +- BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); ++ BlockPos pos = new BlockPos(i, j, k); ++ BlockState blockstate = this.level().getBlockState(pos); + if (!blockstate.isAir()) { +- SoundType soundtype = blockstate.getSoundType(); ++ SoundType soundtype = blockstate.getSoundType(level(), pos, this); + this.playSound(soundtype.getFallSound(), soundtype.getVolume() * 0.5F, soundtype.getPitch() * 0.75F); + } + } +@@ -1675,9 +_,9 @@ + float f2 = f1 - p_21194_; + if (f2 > 0.0F && f2 < 3.4028235E37F) { + if (this instanceof ServerPlayer) { +- ((ServerPlayer)this).awardStat(Stats.DAMAGE_RESISTED, Math.round(f2 * 10.0F)); ++ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_RESISTED), Math.round(f2 * 10.0F)); + } else if (p_21193_.getEntity() instanceof ServerPlayer) { +- ((ServerPlayer)p_21193_.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f2 * 10.0F)); ++ ((ServerPlayer)p_21193_.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(f2 * 10.0F)); + } + } + } +@@ -1699,6 +_,8 @@ + + protected void actuallyHurt(DamageSource p_21240_, float p_21241_) { + if (!this.isInvulnerableTo(p_21240_)) { ++ p_21241_ = net.minecraftforge.common.ForgeHooks.onLivingHurt(this, p_21240_, p_21241_); ++ if (p_21241_ <= 0) return; + p_21241_ = this.getDamageAfterArmorAbsorb(p_21240_, p_21241_); + p_21241_ = this.getDamageAfterMagicAbsorb(p_21240_, p_21241_); + float f1 = Math.max(p_21241_ - this.getAbsorptionAmount(), 0.0F); +@@ -1708,6 +_,7 @@ + serverplayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(f * 10.0F)); + } + ++ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, p_21240_, f1); + if (f1 != 0.0F) { + this.getCombatTracker().recordDamage(p_21240_, f1); + this.setHealth(this.getHealth() - f1); +@@ -1767,6 +_,8 @@ + } + + public void swing(InteractionHand p_21012_, boolean p_21013_) { ++ ItemStack stack = this.getItemInHand(p_21012_); ++ if (!stack.isEmpty() && stack.onEntitySwing(this)) return; + if (!this.swinging || this.swingTime >= this.getCurrentSwingDuration() / 2 || this.swingTime < 0) { + this.swingTime = -1; + this.swinging = true; +@@ -1878,9 +_,10 @@ + } + + private void swapHandItems() { +- ItemStack itemstack = this.getItemBySlot(EquipmentSlot.OFFHAND); +- this.setItemSlot(EquipmentSlot.OFFHAND, this.getItemBySlot(EquipmentSlot.MAINHAND)); +- this.setItemSlot(EquipmentSlot.MAINHAND, itemstack); ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this); ++ if (event.isCanceled()) return; ++ this.setItemSlot(EquipmentSlot.OFFHAND, event.getItemSwappedToOffHand()); ++ this.setItemSlot(EquipmentSlot.MAINHAND, event.getItemSwappedToMainHand()); + } + + @Override +@@ -2077,15 +_,18 @@ + } + + this.hasImpulse = true; ++ net.minecraftforge.common.ForgeHooks.onLivingJump(this); + } + } + ++ @Deprecated // FORGE: use sinkInFluid instead + protected void goDownInWater() { +- this.setDeltaMovement(this.getDeltaMovement().add(0.0, -0.04F, 0.0)); ++ this.sinkInFluid(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); + } + ++ @Deprecated // FORGE: use jumpInFluid instead + protected void jumpInLiquid(TagKey p_204043_) { +- this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.04F, 0.0)); ++ this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.04F * this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()), 0.0)); + } + + protected float getWaterSlowDown() { +@@ -2110,7 +_,8 @@ + } + + FluidState fluidstate = this.level().getFluidState(this.blockPosition()); +- if (this.isInWater() && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { ++ if ((this.isInWater() || (this.isInFluidType(fluidstate) && fluidstate.getFluidType() != net.minecraftforge.common.ForgeMod.LAVA_TYPE.get())) && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { ++ if (this.isInWater() || (this.isInFluidType(fluidstate) && !this.moveInFluid(fluidstate, p_21280_, d0))) { + double d9 = this.getY(); + float f4 = this.isSprinting() ? 0.9F : this.getWaterSlowDown(); + float f5 = 0.02F; +@@ -2132,6 +_,7 @@ + f4 = 0.96F; + } + ++ f5 *= this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()); + this.moveRelative(f5, p_21280_); + this.move(MoverType.SELF, this.getDeltaMovement()); + Vec3 vec36 = this.getDeltaMovement(); +@@ -2145,6 +_,7 @@ + if (this.horizontalCollision && this.isFree(vec32.x, vec32.y + 0.6F - this.getY() + d9, vec32.z)) { + this.setDeltaMovement(vec32.x, 0.3F, vec32.z); + } ++ } + } else if (this.isInLava() && this.isAffectedByFluids() && !this.canStandOnFluid(fluidstate)) { + double d8 = this.getY(); + this.moveRelative(0.02F, p_21280_); +@@ -2207,7 +_,7 @@ + } + } else { + BlockPos blockpos = this.getBlockPosBelowThatAffectsMyMovement(); +- float f2 = this.level().getBlockState(blockpos).getBlock().getFriction(); ++ float f2 = this.level().getBlockState(blockpos).getFriction(level(), blockpos, this); + float f3 = this.onGround() ? f2 * 0.91F : 0.91F; + Vec3 vec35 = this.handleRelativeFrictionAndCalculateMovement(p_21280_, f2); + double d2 = vec35.y; +@@ -2300,7 +_,7 @@ + double d0 = Mth.clamp(p_21298_.x, -0.15F, 0.15F); + double d1 = Mth.clamp(p_21298_.z, -0.15F, 0.15F); + double d2 = Math.max(p_21298_.y, -0.15F); +- if (d2 < 0.0 && !this.getInBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { ++ if (d2 < 0.0 && !this.getInBlockState().isScaffolding(this) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { + d2 = 0.0; + } + +@@ -2333,6 +_,7 @@ + + @Override + public void tick() { ++ if (net.minecraftforge.common.ForgeHooks.onLivingTick(this)) return; + super.tick(); + this.updatingUsingItem(); + this.updateSwimAmount(); +@@ -2482,6 +_,7 @@ + }; + ItemStack itemstack1 = this.getItemBySlot(equipmentslot); + if (this.equipmentHasChanged(itemstack, itemstack1)) { ++ net.minecraftforge.event.ForgeEventFactory.onLivingEquipmentChange(this, equipmentslot, itemstack, itemstack1); + if (map == null) { + map = Maps.newEnumMap(EquipmentSlot.class); + } +@@ -2641,6 +_,10 @@ + this.level().getProfiler().push("jump"); + if (this.jumping && this.isAffectedByFluids()) { + double d3; ++ var fluidType = this.getMaxHeightFluidType(); ++ if (!fluidType.isAir()) { ++ d3 = this.getFluidTypeHeight(fluidType); ++ } else + if (this.isInLava()) { + d3 = this.getFluidHeight(FluidTags.LAVA); + } else { +@@ -2651,15 +_,19 @@ + double d4 = this.getFluidJumpThreshold(); + if (!flag || this.onGround() && !(d3 > d4)) { + if (!this.isInLava() || this.onGround() && !(d3 > d4)) { ++ if (fluidType.isAir() || this.onGround() && !(d3 > d4)) { + if ((this.onGround() || flag && d3 <= d4) && this.noJumpDelay == 0) { + this.jumpFromGround(); + this.noJumpDelay = 10; + } ++ } else { ++ this.jumpInFluid(fluidType); ++ } + } else { +- this.jumpInLiquid(FluidTags.LAVA); ++ this.jumpInFluid(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get()); + } + } else { +- this.jumpInLiquid(FluidTags.WATER); ++ this.jumpInFluid(net.minecraftforge.common.ForgeMod.WATER_TYPE.get()); + } + } else { + this.noJumpDelay = 0; +@@ -2724,6 +_,8 @@ + boolean flag = this.getSharedFlag(7); + if (flag && !this.onGround() && !this.isPassenger() && !this.hasEffect(MobEffects.LEVITATION)) { + ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); ++ flag = itemstack.canElytraFly(this) && itemstack.elytraFlightTick(this, this.fallFlyTicks); ++ if (false) //Forge: Moved to ElytraItem + if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack)) { + flag = true; + int i = this.fallFlyTicks + 1; +@@ -2982,8 +_,11 @@ + + private void updatingUsingItem() { + if (this.isUsingItem()) { +- if (ItemStack.isSameItem(this.getItemInHand(this.getUsedItemHand()), this.useItem)) { ++ var current = this.getItemInHand(this.getUsedItemHand()); ++ if (net.minecraftforge.common.ForgeHooks.canContinueUsing(this.useItem, current)) { + this.useItem = this.getItemInHand(this.getUsedItemHand()); ++ } ++ if (this.useItem == current) { + this.updateUsingItem(this.useItem); + } else { + this.stopUsingItem(); +@@ -2992,12 +_,16 @@ + } + + protected void updateUsingItem(ItemStack p_147201_) { ++ if (!p_147201_.isEmpty()) { ++ this.useItemRemaining = net.minecraftforge.event.ForgeEventFactory.onItemUseTick(this, p_147201_, this.getUseItemRemainingTicks()); ++ } ++ if (this.getUseItemRemainingTicks() > 0) + p_147201_.onUseTick(this.level(), this, this.getUseItemRemainingTicks()); + if (this.shouldTriggerItemUseEffects()) { + this.triggerItemUseEffects(p_147201_, 5); + } + +- if (--this.useItemRemaining == 0 && !this.level().isClientSide && !p_147201_.useOnRelease()) { ++ if (--this.useItemRemaining <= 0 && !this.level().isClientSide && !p_147201_.useOnRelease()) { + this.completeUsingItem(); + } + } +@@ -3032,8 +_,12 @@ + public void startUsingItem(InteractionHand p_21159_) { + ItemStack itemstack = this.getItemInHand(p_21159_); + if (!itemstack.isEmpty() && !this.isUsingItem()) { ++ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration()); ++ if (duration <= 0) { ++ return; ++ } + this.useItem = itemstack; +- this.useItemRemaining = itemstack.getUseDuration(); ++ this.useItemRemaining = duration; + if (!this.level().isClientSide) { + this.setLivingEntityFlag(1, true); + this.setLivingEntityFlag(2, p_21159_ == InteractionHand.OFF_HAND); +@@ -3097,6 +_,9 @@ + vec31 = vec31.xRot(-this.getXRot() * (float) (Math.PI / 180.0)); + vec31 = vec31.yRot(-this.getYRot() * (float) (Math.PI / 180.0)); + vec31 = vec31.add(this.getX(), this.getEyeY(), this.getZ()); ++ if (this.level() instanceof ServerLevel serverLevel) //Forge: Fix MC-2518 spawnParticle is nooped on server, need to use server specific variant ++ serverLevel.sendParticles(new ItemParticleOption(ParticleTypes.ITEM, p_21061_), vec31.x, vec31.y, vec31.z, 1, vec3.x, vec3.y + 0.05D, vec3.z, 0.0D); ++ else + this.level() + .addParticle( + new ItemParticleOption(ParticleTypes.ITEM, p_21061_), +@@ -3118,7 +_,9 @@ + } else { + if (!this.useItem.isEmpty() && this.isUsingItem()) { + this.triggerItemUseEffects(this.useItem, 16); ++ ItemStack copy = this.useItem.copy(); + ItemStack itemstack = this.useItem.finishUsingItem(this.level(), this); ++ itemstack = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), itemstack); + if (itemstack != this.useItem) { + this.setItemInHand(interactionhand, itemstack); + } +@@ -3143,7 +_,13 @@ + + public void releaseUsingItem() { + if (!this.useItem.isEmpty()) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onUseItemStop(this, useItem, this.getUseItemRemainingTicks())) { ++ ItemStack copy = this instanceof Player ? useItem.copy() : null; + this.useItem.releaseUsing(this.level(), this, this.getUseItemRemainingTicks()); ++ if (copy != null && useItem.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem((Player)this, copy, getUsedItemHand()); ++ } ++ } + if (this.useItem.useOnRelease()) { + this.updatingUsingItem(); + } +@@ -3153,6 +_,7 @@ + } + + public void stopUsingItem() { ++ if (this.isUsingItem() && !this.useItem.isEmpty()) this.useItem.onStopUsing(this, useItemRemaining); + if (!this.level().isClientSide) { + boolean flag = this.isUsingItem(); + this.setLivingEntityFlag(1, false); +@@ -3168,7 +_,8 @@ + public boolean isBlocking() { + if (this.isUsingItem() && !this.useItem.isEmpty()) { + Item item = this.useItem.getItem(); +- return item.getUseAnimation(this.useItem) != UseAnim.BLOCK ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5; ++ boolean canBlock = this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK); ++ return canBlock ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5; + } else { + return false; + } +@@ -3309,8 +_,8 @@ + } + + BlockState blockstate = this.level().getBlockState(p_21141_); +- if (blockstate.getBlock() instanceof BedBlock) { +- this.level().setBlock(p_21141_, blockstate.setValue(BedBlock.OCCUPIED, Boolean.valueOf(true)), 3); ++ if (blockstate.isBed(level(), p_21141_, this)) { ++ blockstate.setBedOccupied(level(), p_21141_, this, true); + } + + this.setPose(Pose.SLEEPING); +@@ -3325,15 +_,15 @@ + } + + private boolean checkBedExists() { +- return this.getSleepingPos().map(p_326778_ -> this.level().getBlockState(p_326778_).getBlock() instanceof BedBlock).orElse(false); ++ return this.getSleepingPos().map(p_326778_ -> net.minecraftforge.event.ForgeEventFactory.fireSleepingLocationCheck(this, p_326778_)).orElse(false); + } + + public void stopSleeping() { + this.getSleepingPos().filter(this.level()::hasChunkAt).ifPresent(p_261435_ -> { + BlockState blockstate = this.level().getBlockState(p_261435_); +- if (blockstate.getBlock() instanceof BedBlock) { ++ if (blockstate.isBed(level(), p_261435_, this)) { + Direction direction = blockstate.getValue(BedBlock.FACING); +- this.level().setBlock(p_261435_, blockstate.setValue(BedBlock.OCCUPIED, Boolean.valueOf(false)), 3); ++ blockstate.setBedOccupied(level(), p_261435_, this, false); + Vec3 vec31 = BedBlock.findStandUpPosition(this.getType(), this.level(), p_261435_, direction, this.getYRot()).orElseGet(() -> { + BlockPos blockpos = p_261435_.above(); + return new Vec3((double)blockpos.getX() + 0.5, (double)blockpos.getY() + 0.1, (double)blockpos.getZ() + 0.5); +@@ -3354,7 +_,9 @@ + @Nullable + public Direction getBedOrientation() { + BlockPos blockpos = this.getSleepingPos().orElse(null); +- return blockpos != null ? BedBlock.getBedOrientation(this.level(), blockpos) : null; ++ if (blockpos == null) return Direction.UP; ++ BlockState state = this.level().getBlockState(blockpos); ++ return !state.isBed(level(), blockpos, this) ? Direction.UP : state.getBedDirection(level(), blockpos); + } + + @Override +@@ -3363,7 +_,7 @@ + } + + public ItemStack getProjectile(ItemStack p_21272_) { +- return ItemStack.EMPTY; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_21272_, ItemStack.EMPTY); + } + + public ItemStack eat(Level p_21067_, ItemStack p_21068_) { +@@ -3428,6 +_,8 @@ + } + + public static EquipmentSlot getEquipmentSlotForItem(ItemStack p_147234_) { ++ final EquipmentSlot slot = p_147234_.getEquipmentSlot(); ++ if (slot != null) return slot; // FORGE: Allow modders to set a non-default equipment slot for a stack; e.g. a non-armor chestplate-slot item + Equipable equipable = Equipable.get(p_147234_); + return equipable != null ? equipable.getEquipmentSlot() : EquipmentSlot.MAINHAND; + } +@@ -3534,5 +_,42 @@ + } + + public static record Fallsounds(SoundEvent small, SoundEvent big) { ++ } ++ ++ /** ++ * Returns true if the entity's rider (EntityPlayer) should face forward when mounted. ++ * currently only used in vanilla code by pigs. ++ * ++ * @param player The player who is riding the entity. ++ * @return If the player should orient the same direction as this entity. ++ */ ++ public boolean shouldRiderFaceForward(Player player) { ++ return this instanceof net.minecraft.world.entity.animal.Pig; ++ } ++ ++ private net.minecraftforge.common.util.LazyOptional[] handlers = net.minecraftforge.items.wrapper.EntityEquipmentInvWrapper.create(this); ++ ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { ++ if (facing == null) return handlers[2].cast(); ++ else if (facing.getAxis().isVertical()) return handlers[0].cast(); ++ else if (facing.getAxis().isHorizontal()) return handlers[1].cast(); ++ } ++ return super.getCapability(capability, facing); ++ } ++ ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ for (int x = 0; x < handlers.length; x++) { ++ handlers[x].invalidate(); ++ } ++ } ++ ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ handlers = net.minecraftforge.items.wrapper.EntityEquipmentInvWrapper.create(this); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch index c5ceb7c780..f542807399 100644 --- a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch @@ -1,168 +1,167 @@ --- a/net/minecraft/world/entity/Mob.java +++ b/net/minecraft/world/entity/Mob.java -@@ -118,6 +_,9 @@ - private CompoundTag leashInfoTag; - private BlockPos restrictCenter = BlockPos.ZERO; - private float restrictRadius = -1.0F; -+ @Nullable -+ private MobSpawnType spawnType; -+ private boolean spawnCancelled = false; +@@ -133,6 +_,9 @@ + private Either delayedLeashInfo; + private BlockPos restrictCenter = BlockPos.ZERO; + private float restrictRadius = -1.0F; ++ @Nullable ++ private MobSpawnType spawnType; ++ private boolean spawnCancelled = false; - protected Mob(EntityType p_21368_, Level p_21369_) { - super(p_21368_, p_21369_); -@@ -232,7 +_,10 @@ - } + protected Mob(EntityType p_21368_, Level p_21369_) { + super(p_21368_, p_21369_); +@@ -239,7 +_,10 @@ + } - public void setTarget(@Nullable LivingEntity p_21544_) { -- this.target = p_21544_; -+ net.minecraftforge.event.entity.living.LivingChangeTargetEvent changeTargetEvent = net.minecraftforge.common.ForgeHooks.onLivingChangeTarget(this, p_21544_, net.minecraftforge.event.entity.living.LivingChangeTargetEvent.LivingTargetType.MOB_TARGET); -+ if(!changeTargetEvent.isCanceled()) { -+ this.target = changeTargetEvent.getNewTarget(); -+ } - } + public void setTarget(@Nullable LivingEntity p_21544_) { +- this.target = p_21544_; ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetMob(this, p_21544_); ++ if (!event.isCanceled()) { ++ this.target = event.getNewTarget(); ++ } + } - public boolean canAttackType(EntityType p_21399_) { -@@ -430,6 +_,9 @@ - p_21484_.putBoolean("NoAI", this.isNoAi()); - } - -+ if (this.spawnType != null) { -+ p_21484_.putString("forge:spawn_type", this.spawnType.name()); -+ } - } - - public void readAdditionalSaveData(CompoundTag p_21450_) { -@@ -482,6 +_,14 @@ - } - - this.setNoAi(p_21450_.getBoolean("NoAI")); + @Override +@@ -444,6 +_,10 @@ + if (this.isNoAi()) { + p_21484_.putBoolean("NoAI", this.isNoAi()); + } + -+ if (p_21450_.contains("forge:spawn_type")) { -+ try { -+ this.spawnType = MobSpawnType.valueOf(p_21450_.getString("forge:spawn_type")); -+ } catch (Exception ex) { -+ p_21450_.remove("forge:spawn_type"); -+ } -+ } - } ++ if (this.spawnType != null) { ++ p_21484_.putString("forge:spawn_type", this.spawnType.name()); ++ } + } - protected void dropFromLootTable(DamageSource p_21389_, boolean p_21390_) { -@@ -521,9 +_,9 @@ - public void aiStep() { - super.aiStep(); - this.level().getProfiler().push("looting"); -- if (!this.level().isClientSide && this.canPickUpLoot() && this.isAlive() && !this.dead && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { - Vec3i vec3i = this.getPickupReach(); + @Override +@@ -510,6 +_,14 @@ + } -+ if (!this.level().isClientSide && this.canPickUpLoot() && this.isAlive() && !this.dead && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { - for(ItemEntity itementity : this.level().getEntitiesOfClass(ItemEntity.class, this.getBoundingBox().inflate((double)vec3i.getX(), (double)vec3i.getY(), (double)vec3i.getZ()))) { - if (!itementity.isRemoved() && !itementity.getItem().isEmpty() && !itementity.hasPickUpDelay() && this.wantsToPickUp(itementity.getItem())) { - this.pickUpItem(itementity); -@@ -699,6 +_,14 @@ - this.discard(); - } else if (!this.isPersistenceRequired() && !this.requiresCustomPersistence()) { - Entity entity = this.level().getNearestPlayer(this, -1.0D); -+ net.minecraftforge.eventbus.api.Event.Result result = net.minecraftforge.event.ForgeEventFactory.canEntityDespawn(this, (ServerLevel) this.level()); -+ if (result == net.minecraftforge.eventbus.api.Event.Result.DENY) { -+ noActionTime = 0; -+ entity = null; -+ } else if (result == net.minecraftforge.eventbus.api.Event.Result.ALLOW) { -+ this.discard(); -+ entity = null; -+ } - if (entity != null) { - double d0 = entity.distanceToSqr(this); - int i = this.getType().getCategory().getDespawnDistance(); -@@ -1032,6 +_,16 @@ + this.setNoAi(p_21450_.getBoolean("NoAI")); ++ ++ if (p_21450_.contains("forge:spawn_type")) { ++ try { ++ this.spawnType = MobSpawnType.valueOf(p_21450_.getString("forge:spawn_type")); ++ } catch (Exception ex) { ++ p_21450_.remove("forge:spawn_type"); ++ } ++ } + } - } + @Override +@@ -561,7 +_,7 @@ + public void aiStep() { + super.aiStep(); + this.level().getProfiler().push("looting"); +- if (!this.level().isClientSide && this.canPickUpLoot() && this.isAlive() && !this.dead && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!this.level().isClientSide && this.canPickUpLoot() && this.isAlive() && !this.dead && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { + Vec3i vec3i = this.getPickupReach(); -+ /** -+ * Forge: Override-Only, call via ForgeEventFactory.onFinalizeSpawn.
-+ * Overrides are allowed. Do not wrap super calls within override (as that will cause stack overflows).
-+ * Vanilla calls are replaced with a transformer, and are not visible in source.
+ for (ItemEntity itementity : this.level() +@@ -730,6 +_,14 @@ + this.discard(); + } else if (!this.isPersistenceRequired() && !this.requiresCustomPersistence()) { + Entity entity = this.level().getNearestPlayer(this, -1.0); ++ var result = net.minecraftforge.event.ForgeEventFactory.canEntityDespawn(this, (ServerLevel)this.level()); ++ if (result == net.minecraftforge.eventbus.api.Event.Result.DENY) { ++ noActionTime = 0; ++ entity = null; ++ } else if (result == net.minecraftforge.eventbus.api.Event.Result.ALLOW) { ++ this.discard(); ++ entity = null; ++ } + if (entity != null) { + double d0 = entity.distanceToSqr(this); + int i = this.getType().getCategory().getDespawnDistance(); +@@ -1127,6 +_,16 @@ + } + } + ++ /** ++ * Forge: Override-Only, call via ForgeEventFactory.onFinalizeSpawn.
++ * Overrides are allowed. Do not wrap super calls within override (as that will cause stack overflows).
++ * Vanilla calls are replaced with a transformer, and are not visible in source.
++ *

++ * Be certain to either call super.finalizeSpawn or set the {@link #spawnType} field from within your override. ++ * @see {@link net.minecraftforge.event.ForgeEventFactory#onFinalizeSpawn onFinalizeSpawn} for additional documentation. ++ */ ++ @Deprecated ++ @org.jetbrains.annotations.ApiStatus.OverrideOnly + @Nullable + public SpawnGroupData finalizeSpawn(ServerLevelAccessor p_21434_, DifficultyInstance p_21435_, MobSpawnType p_21436_, @Nullable SpawnGroupData p_21437_) { + RandomSource randomsource = p_21434_.getRandom(); +@@ -1135,6 +_,7 @@ + new AttributeModifier("Random spawn bonus", randomsource.triangle(0.0, 0.11485000000000001), AttributeModifier.Operation.ADD_MULTIPLIED_BASE) + ); + this.setLeftHanded(randomsource.nextFloat() < 0.05F); ++ this.spawnType = p_21436_; + return p_21437_; + } + +@@ -1521,15 +_,25 @@ + return false; + } + ++ @Deprecated // FORGE: use jumpInFluid instead + @Override + protected void jumpInLiquid(TagKey p_204045_) { ++ this.jumpInLiquidInternal(() -> super.jumpInLiquid(p_204045_)); ++ } ++ ++ private void jumpInLiquidInternal(Runnable onSuper) { + if (this.getNavigation().canFloat()) { +- super.jumpInLiquid(p_204045_); ++ onSuper.run(); + } else { + this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.3, 0.0)); + } + } + ++ @Override ++ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { ++ this.jumpInLiquidInternal(() -> super.jumpInFluid(type)); ++ } ++ + @VisibleForTesting + public void removeFreeWill() { + this.removeAllGoals(p_262562_ -> true); +@@ -1556,5 +_,40 @@ + public ItemStack getPickResult() { + SpawnEggItem spawneggitem = SpawnEggItem.byId(this.getType()); + return spawneggitem == null ? null : new ItemStack(spawneggitem); ++ } ++ ++ /** ++ * Returns the type of spawn that created this mob, if applicable. ++ * If it could not be determined, this will return null. + *

-+ * Be certain to either call super.finalizeSpawn or set the {@link #spawnType} field from within your override. -+ * @see {@link net.minecraftforge.event.ForgeEventFactory#onFinalizeSpawn onFinalizeSpawn} for additional documentation. ++ * This is set via {@link Mob#finalizeSpawn}, so you should not call this from within that method, instead using the parameter. + */ -+ @Deprecated -+ @org.jetbrains.annotations.ApiStatus.OverrideOnly - @Nullable - public SpawnGroupData finalizeSpawn(ServerLevelAccessor p_21434_, DifficultyInstance p_21435_, MobSpawnType p_21436_, @Nullable SpawnGroupData p_21437_, @Nullable CompoundTag p_21438_) { - RandomSource randomsource = p_21434_.getRandom(); -@@ -1042,6 +_,7 @@ - this.setLeftHanded(false); - } - -+ this.spawnType = p_21436_; - return p_21437_; - } - -@@ -1426,15 +_,25 @@ - return false; - } - -+ @Deprecated // FORGE: use jumpInFluid instead - protected void jumpInLiquid(TagKey p_204045_) { -+ this.jumpInLiquidInternal(() -> super.jumpInLiquid(p_204045_)); -+ } ++ @Nullable ++ public final MobSpawnType getSpawnType() { ++ return this.spawnType; ++ } + -+ private void jumpInLiquidInternal(Runnable onSuper) { - if (this.getNavigation().canFloat()) { -- super.jumpInLiquid(p_204045_); -+ onSuper.run(); - } else { - this.setDeltaMovement(this.getDeltaMovement().add(0.0D, 0.3D, 0.0D)); - } - - } - -+ @Override -+ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { -+ this.jumpInLiquidInternal(() -> super.jumpInFluid(type)); -+ } ++ /** ++ * This method exists so that spawns can be cancelled from the {@link net.minecraftforge.event.entity.living.MobSpawnEvent.FinalizeSpawn FinalizeSpawnEvent} ++ * without needing to hook up an additional handler for the {@link net.minecraftforge.event.entity.EntityJoinLevelEvent EntityJoinLevelEvent}. ++ * @return if this mob will be blocked from spawning during {@link Level#addFreshEntity(Entity)} ++ * @apiNote Not public-facing API. ++ */ ++ @org.jetbrains.annotations.ApiStatus.Internal ++ public final boolean isSpawnCancelled() { ++ return this.spawnCancelled; ++ } + - @VisibleForTesting - public void removeFreeWill() { - this.removeAllGoals((p_262562_) -> { -@@ -1462,5 +_,40 @@ - public ItemStack getPickResult() { - SpawnEggItem spawneggitem = SpawnEggItem.byId(this.getType()); - return spawneggitem == null ? null : new ItemStack(spawneggitem); -+ } -+ -+ /** -+ * Returns the type of spawn that created this mob, if applicable. -+ * If it could not be determined, this will return null. -+ *

-+ * This is set via {@link Mob#finalizeSpawn}, so you should not call this from within that method, instead using the parameter. -+ */ -+ @Nullable -+ public final MobSpawnType getSpawnType() { -+ return this.spawnType; -+ } -+ -+ /** -+ * This method exists so that spawns can be cancelled from the {@link net.minecraftforge.event.entity.living.MobSpawnEvent.FinalizeSpawn FinalizeSpawnEvent} -+ * without needing to hook up an additional handler for the {@link net.minecraftforge.event.entity.EntityJoinLevelEvent EntityJoinLevelEvent}. -+ * @return if this mob will be blocked from spawning during {@link Level#addFreshEntity(Entity)} -+ * @apiNote Not public-facing API. -+ */ -+ @org.jetbrains.annotations.ApiStatus.Internal -+ public final boolean isSpawnCancelled() { -+ return this.spawnCancelled; -+ } -+ -+ /** -+ * Marks this mob as being disallowed to spawn during {@link Level#addFreshEntity(Entity)}.

-+ * @throws UnsupportedOperationException if this entity has already been {@link Entity#isAddedToWorld() added to the world}. -+ * @apiNote Not public-facing API. -+ */ -+ @org.jetbrains.annotations.ApiStatus.Internal -+ public final void setSpawnCancelled(boolean cancel) { -+ if (this.isAddedToWorld()) { -+ throw new UnsupportedOperationException("Late invocations of Mob#setSpawnCancelled are not permitted."); -+ } -+ this.spawnCancelled = cancel; - } ++ /** ++ * Marks this mob as being disallowed to spawn during {@link Level#addFreshEntity(Entity)}.

++ * @throws UnsupportedOperationException if this entity has already been {@link Entity#isAddedToWorld() added to the world}. ++ * @apiNote Not public-facing API. ++ */ ++ @org.jetbrains.annotations.ApiStatus.Internal ++ public final void setSpawnCancelled(boolean cancel) { ++ if (this.isAddedToWorld()) { ++ throw new UnsupportedOperationException("Late invocations of Mob#setSpawnCancelled are not permitted."); ++ } ++ this.spawnCancelled = cancel; + } } diff --git a/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch b/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch index 889aaebeec..3d512b3d11 100644 --- a/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch @@ -6,38 +6,37 @@ -public enum MobCategory implements StringRepresentable { +public enum MobCategory implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { - MONSTER("monster", 70, false, false, 128), - CREATURE("creature", 10, true, true, 128), - AMBIENT("ambient", 15, true, false, 128), + MONSTER("monster", 70, false, false, 128), + CREATURE("creature", 10, true, true, 128), + AMBIENT("ambient", 15, true, false, 128), @@ -13,7 +_,8 @@ - WATER_AMBIENT("water_ambient", 20, true, false, 64), - MISC("misc", -1, true, true, 128); + WATER_AMBIENT("water_ambient", 20, true, false, 64), + MISC("misc", -1, true, true, 128); -- public static final Codec CODEC = StringRepresentable.fromEnum(MobCategory::values); -+ public static final Codec CODEC = net.minecraftforge.common.IExtensibleEnum.createCodecForExtensibleEnum(MobCategory::values, MobCategory::byName); -+ private static final java.util.Map BY_NAME = java.util.Arrays.stream(values()).collect(java.util.stream.Collectors.toMap(MobCategory::getName, mobCategory -> mobCategory)); - private final int max; - private final boolean isFriendly; - private final boolean isPersistent; -@@ -47,6 +_,21 @@ +- public static final Codec CODEC = StringRepresentable.fromEnum(MobCategory::values); ++ public static final Codec CODEC = net.minecraftforge.common.IExtensibleEnum.createCodecForExtensibleEnum(MobCategory::values, MobCategory::byName); ++ private static final java.util.Map BY_NAME = java.util.Arrays.stream(values()).collect(java.util.stream.Collectors.toMap(MobCategory::getName, mobCategory -> mobCategory)); + private final int max; + private final boolean isFriendly; + private final boolean isPersistent; +@@ -56,5 +_,20 @@ - public boolean isPersistent() { - return this.isPersistent; -+ } + public int getNoDespawnDistance() { + return 32; ++ } + -+ public static MobCategory create(String name, String id, int maxNumberOfCreatureIn, boolean isPeacefulCreatureIn, boolean isAnimalIn, int despawnDistance) { -+ throw new IllegalStateException("Enum not extended"); -+ } ++ public static MobCategory create(String name, String id, int maxNumberOfCreatureIn, boolean isPeacefulCreatureIn, boolean isAnimalIn, int despawnDistance) { ++ throw new IllegalStateException("Enum not extended"); ++ } + -+ @Override -+ @Deprecated -+ public void init() { -+ BY_NAME.put(this.getName(), this); -+ } ++ @Override ++ @Deprecated ++ public void init() { ++ BY_NAME.put(this.getName(), this); ++ } + -+ // Forge: Access enum members by name -+ public static MobCategory byName(String name) { -+ return BY_NAME.get(name); - } - - public int getDespawnDistance() { ++ // Forge: Access enum members by name ++ public static MobCategory byName(String name) { ++ return BY_NAME.get(name); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch b/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch index 45810abc09..c68ac8e5b5 100644 --- a/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch @@ -1,14 +1,10 @@ --- a/net/minecraft/world/entity/Shearable.java +++ b/net/minecraft/world/entity/Shearable.java -@@ -2,8 +_,11 @@ +@@ -2,6 +_,7 @@ import net.minecraft.sounds.SoundSource; -+@Deprecated // Forge: Use IForgeShearable ++/** @deprecated Use {@link net.minecraftforge.common.IForgeShearable} */ public interface Shearable { -+ @Deprecated // Forge: Use IForgeShearable - void shear(SoundSource p_21749_); + void shear(SoundSource p_21749_); -+ @Deprecated // Forge: Use IForgeShearable - boolean readyForShearing(); - } diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch new file mode 100644 index 0000000000..15661214f4 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/entity/SpawnPlacementTypes.java ++++ b/net/minecraft/world/entity/SpawnPlacementTypes.java +@@ -28,7 +_,7 @@ + BlockPos blockpos = p_332749_.above(); + BlockPos blockpos1 = p_332749_.below(); + BlockState blockstate = p_328923_.getBlockState(blockpos1); +- return !blockstate.isValidSpawn(p_328923_, blockpos1, p_334188_) ++ return !blockstate.isValidSpawn(p_328923_, blockpos1, this, p_334188_) + ? false + : this.isValidEmptySpawnBlock(p_328923_, p_332749_, p_334188_) && this.isValidEmptySpawnBlock(p_328923_, blockpos, p_334188_); + } else { diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch index 8918b50e48..241491793e 100644 --- a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch @@ -1,57 +1,34 @@ --- a/net/minecraft/world/entity/SpawnPlacements.java +++ b/net/minecraft/world/entity/SpawnPlacements.java -@@ -44,6 +_,7 @@ +@@ -46,6 +_,7 @@ public class SpawnPlacements { - private static final Map, SpawnPlacements.Data> DATA_BY_TYPE = Maps.newHashMap(); + private static final Map, SpawnPlacements.Data> DATA_BY_TYPE = Maps.newHashMap(); -+ @Deprecated // FORGE: use SpawnPlacementRegisterEvent to register and modify spawn placements - public static void register(EntityType p_21755_, SpawnPlacements.Type p_21756_, Heightmap.Types p_21757_, SpawnPlacements.SpawnPredicate p_21758_) { - SpawnPlacements.Data spawnplacements$data = DATA_BY_TYPE.put(p_21755_, new SpawnPlacements.Data(p_21757_, p_21756_, p_21758_)); - if (spawnplacements$data != null) { -@@ -63,7 +_,8 @@ ++ /** @deprecated FORGE: use SpawnPlacementRegisterEvent to register and modify spawn placements */ + private static void register( + EntityType p_21755_, SpawnPlacementType p_331557_, Heightmap.Types p_21757_, SpawnPlacements.SpawnPredicate p_21758_ + ) { +@@ -73,7 +_,8 @@ + EntityType p_217075_, ServerLevelAccessor p_217076_, MobSpawnType p_217077_, BlockPos p_217078_, RandomSource p_217079_ + ) { + SpawnPlacements.Data spawnplacements$data = DATA_BY_TYPE.get(p_217075_); +- return spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)p_217075_, p_217076_, p_217077_, p_217078_, p_217079_); ++ boolean vanillaResult = spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)p_217075_, p_217076_, p_217077_, p_217078_, p_217079_); ++ return net.minecraftforge.event.ForgeEventFactory.checkSpawnPlacements(p_217075_, p_217076_, p_217077_, p_217078_, p_217079_, vanillaResult); + } - public static boolean checkSpawnRules(EntityType p_217075_, ServerLevelAccessor p_217076_, MobSpawnType p_217077_, BlockPos p_217078_, RandomSource p_217079_) { - SpawnPlacements.Data spawnplacements$data = DATA_BY_TYPE.get(p_217075_); -- return spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)p_217075_, p_217076_, p_217077_, p_217078_, p_217079_); -+ boolean vanillaResult = spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)p_217075_, p_217076_, p_217077_, p_217078_, p_217079_); -+ return net.minecraftforge.event.ForgeEventFactory.checkSpawnPlacements(p_217075_, p_217076_, p_217077_, p_217078_, p_217079_, vanillaResult); - } - - static { -@@ -158,10 +_,35 @@ - boolean test(EntityType p_217081_, ServerLevelAccessor p_217082_, MobSpawnType p_217083_, BlockPos p_217084_, RandomSource p_217085_); - } - -- public static enum Type { -+ public static enum Type implements net.minecraftforge.common.IExtensibleEnum { - ON_GROUND, - IN_WATER, - NO_RESTRICTIONS, - IN_LAVA; + static { +@@ -159,5 +_,13 @@ + @FunctionalInterface + public interface SpawnPredicate { + boolean test(EntityType p_217081_, ServerLevelAccessor p_217082_, MobSpawnType p_217083_, BlockPos p_217084_, RandomSource p_217085_); ++ } + -+ public static Type create(String name, net.minecraftforge.common.util.TriPredicate> predicate) { -+ throw new IllegalStateException("Enum not extended"); -+ } -+ -+ private net.minecraftforge.common.util.TriPredicate> predicate; -+ private Type() { this(null); } -+ private Type(net.minecraftforge.common.util.TriPredicate> predicate) { -+ this.predicate = predicate; -+ } -+ -+ public boolean canSpawnAt(net.minecraft.world.level.LevelReader world, BlockPos pos, EntityType type) { -+ if (this == NO_RESTRICTIONS) return true; -+ if (predicate == null) return net.minecraft.world.level.NaturalSpawner.canSpawnAtBody(this, world, pos, type); -+ return predicate.test(world, pos, type); -+ } -+ } -+ -+ // ******* FORGE START. INTERNAL USE ONLY! ****** // -+ public static void fireSpawnPlacementEvent() -+ { -+ Map, net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate> map = Maps.newHashMap(); -+ DATA_BY_TYPE.forEach((type, data) -> map.put(type, new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<>(data.predicate, data.placement, data.heightMap))); -+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent(map)); -+ map.forEach(((entityType, merged) -> DATA_BY_TYPE.put(entityType, new SpawnPlacements.Data(merged.getHeightmapType(), merged.getSpawnType(), merged.build())))); - } ++ // ******* FORGE START. INTERNAL USE ONLY! ****** // ++ public static void fireSpawnPlacementEvent() { ++ Map, net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate> map = Maps.newHashMap(); ++ DATA_BY_TYPE.forEach((type, data) -> map.put(type, new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<>(data.predicate, data.placement, data.heightMap))); ++ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent(map)); ++ map.forEach(((entityType, merged) -> DATA_BY_TYPE.put(entityType, new SpawnPlacements.Data(merged.getHeightmapType(), merged.getSpawnType(), merged.build())))); + } } diff --git a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch index 981b16e829..3b20f0d7af 100644 --- a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/TamableAnimal.java +++ b/net/minecraft/world/entity/TamableAnimal.java -@@ -186,11 +_,15 @@ - } +@@ -193,11 +_,14 @@ - public void die(DamageSource p_21809_) { -+ // FORGE: Super moved to top so that death message would be cancelled properly -+ net.minecraft.network.chat.Component deathMessage = this.getCombatTracker().getDeathMessage(); -+ super.die(p_21809_); + @Override + public void die(DamageSource p_21809_) { ++ // FORGE: Super moved to top so that death message would be cancelled properly ++ net.minecraft.network.chat.Component deathMessage = this.getCombatTracker().getDeathMessage(); ++ super.die(p_21809_); + -+ if (this.dead) - if (!this.level().isClientSide && this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES) && this.getOwner() instanceof ServerPlayer) { -- this.getOwner().sendSystemMessage(this.getCombatTracker().getDeathMessage()); -+ this.getOwner().sendSystemMessage(deathMessage); - } ++ if (this.dead) + if (!this.level().isClientSide && this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES) && this.getOwner() instanceof ServerPlayer) { +- this.getOwner().sendSystemMessage(this.getCombatTracker().getDeathMessage()); ++ this.getOwner().sendSystemMessage(deathMessage); + } +- +- super.die(p_21809_); + } -- super.die(p_21809_); - } - - public boolean isOrderedToSit() { + public boolean isOrderedToSit() { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch index 009c463db2..f42e662382 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch @@ -1,33 +1,33 @@ --- a/net/minecraft/world/entity/ai/Brain.java +++ b/net/minecraft/world/entity/ai/Brain.java -@@ -478,6 +_,30 @@ - return builder.build(); - } +@@ -485,6 +_,30 @@ + return builder.build(); + } -+ public net.minecraftforge.common.util.BrainBuilder createBuilder(){ -+ var builder = new net.minecraftforge.common.util.BrainBuilder<>(this); -+ builder.getMemoryTypes().addAll(this.memories.keySet()); -+ builder.getSensorTypes().addAll(this.sensors.keySet()); -+ builder.addAvailableBehaviorsByPriorityFrom(this.availableBehaviorsByPriority); -+ builder.setSchedule(this.getSchedule()); -+ builder.addActivityRequirementsFrom(this.activityRequirements); -+ builder.addActivityMemoriesToEraseWhenStoppedFrom(this.activityMemoriesToEraseWhenStopped); -+ builder.getCoreActivities().addAll(this.coreActivities); -+ builder.setDefaultActivity(this.defaultActivity); -+ builder.setActiveActivites(this.activeActivities); -+ return builder; -+ } ++ public net.minecraftforge.common.util.BrainBuilder createBuilder() { ++ var builder = new net.minecraftforge.common.util.BrainBuilder<>(this); ++ builder.getMemoryTypes().addAll(this.memories.keySet()); ++ builder.getSensorTypes().addAll(this.sensors.keySet()); ++ builder.addAvailableBehaviorsByPriorityFrom(this.availableBehaviorsByPriority); ++ builder.setSchedule(this.getSchedule()); ++ builder.addActivityRequirementsFrom(this.activityRequirements); ++ builder.addActivityMemoriesToEraseWhenStoppedFrom(this.activityMemoriesToEraseWhenStopped); ++ builder.getCoreActivities().addAll(this.coreActivities); ++ builder.setDefaultActivity(this.defaultActivity); ++ builder.setActiveActivites(this.activeActivities); ++ return builder; ++ } + -+ public void copyFromBuilder(net.minecraftforge.common.util.BrainBuilder builder){ -+ builder.addAvailableBehaviorsByPriorityTo(this.availableBehaviorsByPriority); -+ this.setSchedule(builder.getSchedule()); -+ builder.addActivityRequirementsTo(this.activityRequirements); -+ builder.addActivityMemoriesToEraseWhenStoppedTo(this.activityMemoriesToEraseWhenStopped); -+ this.setCoreActivities(builder.getCoreActivities()); -+ this.setDefaultActivity(builder.getDefaultActivity()); -+ this.activeActivities.addAll(builder.getActiveActivites()); -+ } ++ public void copyFromBuilder(net.minecraftforge.common.util.BrainBuilder builder) { ++ builder.addAvailableBehaviorsByPriorityTo(this.availableBehaviorsByPriority); ++ this.setSchedule(builder.getSchedule()); ++ builder.addActivityRequirementsTo(this.activityRequirements); ++ builder.addActivityMemoriesToEraseWhenStoppedTo(this.activityMemoriesToEraseWhenStopped); ++ this.setCoreActivities(builder.getCoreActivities()); ++ this.setDefaultActivity(builder.getDefaultActivity()); ++ this.activeActivities.addAll(builder.getActiveActivites()); ++ } + - static final class MemoryValue { - private final MemoryModuleType type; - private final Optional> value; + static final class MemoryValue { + private final MemoryModuleType type; + private final Optional> value; diff --git a/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch index 57bf648908..d842b1989e 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch @@ -1,33 +1,38 @@ --- a/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java +++ b/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java -@@ -69,6 +_,22 @@ - public static class Builder { - private final Map builder = Maps.newHashMap(); - private boolean instanceFrozen; -+ private final java.util.List others = new java.util.ArrayList<>(); -+ -+ public Builder() { } -+ -+ public Builder(AttributeSupplier attributeMap) { -+ this.builder.putAll(attributeMap.instances); -+ } -+ -+ public void combine(Builder other) { -+ this.builder.putAll(other.builder); -+ others.add(other); -+ } -+ -+ public boolean hasAttribute(Attribute attribute) { -+ return this.builder.containsKey(attribute); -+ } +@@ -66,8 +_,24 @@ + } - private AttributeInstance create(Attribute p_22275_) { - AttributeInstance attributeinstance = new AttributeInstance(p_22275_, (p_258260_) -> { -@@ -93,6 +_,7 @@ + public static class Builder { +- private final ImmutableMap.Builder, AttributeInstance> builder = ImmutableMap.builder(); ++ private final java.util.Map, AttributeInstance> builder = new java.util.HashMap<>(); + private boolean instanceFrozen; ++ private final java.util.List others = new java.util.ArrayList<>(); ++ ++ public Builder() {} ++ ++ public Builder(AttributeSupplier attributeMap) { ++ this.builder.putAll(attributeMap.instances); ++ } ++ ++ public void combine(Builder other) { ++ this.builder.putAll(other.builder); ++ this.others.add(other); ++ } ++ ++ public boolean hasAttribute(Holder attribute) { ++ return this.builder.containsKey(attribute); ++ } - public AttributeSupplier build() { - this.instanceFrozen = true; -+ others.forEach(p_70141_ -> p_70141_.instanceFrozen = true); - return new AttributeSupplier(this.builder); - } - } + private AttributeInstance create(Holder p_334904_) { + AttributeInstance attributeinstance = new AttributeInstance(p_334904_, p_326800_ -> { +@@ -92,7 +_,8 @@ + + public AttributeSupplier build() { + this.instanceFrozen = true; +- return new AttributeSupplier(this.builder.buildKeepingLast()); ++ others.forEach(b -> b.instanceFrozen = true); ++ return new AttributeSupplier(ImmutableMap.copyOf(this.builder)); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch index 55819677e0..92207df0e3 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch @@ -1,17 +1,17 @@ --- a/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java +++ b/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java -@@ -84,11 +_,12 @@ - private static final Map, AttributeSupplier> SUPPLIERS = ImmutableMap., AttributeSupplier>builder().put(EntityType.ALLAY, Allay.createAttributes().build()).put(EntityType.ARMOR_STAND, LivingEntity.createLivingAttributes().build()).put(EntityType.AXOLOTL, Axolotl.createAttributes().build()).put(EntityType.BAT, Bat.createAttributes().build()).put(EntityType.BEE, Bee.createAttributes().build()).put(EntityType.BLAZE, Blaze.createAttributes().build()).put(EntityType.CAT, Cat.createAttributes().build()).put(EntityType.CAMEL, Camel.createAttributes().build()).put(EntityType.CAVE_SPIDER, CaveSpider.createCaveSpider().build()).put(EntityType.CHICKEN, Chicken.createAttributes().build()).put(EntityType.COD, AbstractFish.createAttributes().build()).put(EntityType.COW, Cow.createAttributes().build()).put(EntityType.CREEPER, Creeper.createAttributes().build()).put(EntityType.DOLPHIN, Dolphin.createAttributes().build()).put(EntityType.DONKEY, AbstractChestedHorse.createBaseChestedHorseAttributes().build()).put(EntityType.DROWNED, Zombie.createAttributes().build()).put(EntityType.ELDER_GUARDIAN, ElderGuardian.createAttributes().build()).put(EntityType.ENDERMAN, EnderMan.createAttributes().build()).put(EntityType.ENDERMITE, Endermite.createAttributes().build()).put(EntityType.ENDER_DRAGON, EnderDragon.createAttributes().build()).put(EntityType.EVOKER, Evoker.createAttributes().build()).put(EntityType.BREEZE, Breeze.createAttributes().build()).put(EntityType.FOX, Fox.createAttributes().build()).put(EntityType.FROG, Frog.createAttributes().build()).put(EntityType.GHAST, Ghast.createAttributes().build()).put(EntityType.GIANT, Giant.createAttributes().build()).put(EntityType.GLOW_SQUID, GlowSquid.createAttributes().build()).put(EntityType.GOAT, Goat.createAttributes().build()).put(EntityType.GUARDIAN, Guardian.createAttributes().build()).put(EntityType.HOGLIN, Hoglin.createAttributes().build()).put(EntityType.HORSE, AbstractHorse.createBaseHorseAttributes().build()).put(EntityType.HUSK, Zombie.createAttributes().build()).put(EntityType.ILLUSIONER, Illusioner.createAttributes().build()).put(EntityType.IRON_GOLEM, IronGolem.createAttributes().build()).put(EntityType.LLAMA, Llama.createAttributes().build()).put(EntityType.MAGMA_CUBE, MagmaCube.createAttributes().build()).put(EntityType.MOOSHROOM, Cow.createAttributes().build()).put(EntityType.MULE, AbstractChestedHorse.createBaseChestedHorseAttributes().build()).put(EntityType.OCELOT, Ocelot.createAttributes().build()).put(EntityType.PANDA, Panda.createAttributes().build()).put(EntityType.PARROT, Parrot.createAttributes().build()).put(EntityType.PHANTOM, Monster.createMonsterAttributes().build()).put(EntityType.PIG, Pig.createAttributes().build()).put(EntityType.PIGLIN, Piglin.createAttributes().build()).put(EntityType.PIGLIN_BRUTE, PiglinBrute.createAttributes().build()).put(EntityType.PILLAGER, Pillager.createAttributes().build()).put(EntityType.PLAYER, Player.createAttributes().build()).put(EntityType.POLAR_BEAR, PolarBear.createAttributes().build()).put(EntityType.PUFFERFISH, AbstractFish.createAttributes().build()).put(EntityType.RABBIT, Rabbit.createAttributes().build()).put(EntityType.RAVAGER, Ravager.createAttributes().build()).put(EntityType.SALMON, AbstractFish.createAttributes().build()).put(EntityType.SHEEP, Sheep.createAttributes().build()).put(EntityType.SHULKER, Shulker.createAttributes().build()).put(EntityType.SILVERFISH, Silverfish.createAttributes().build()).put(EntityType.SKELETON, AbstractSkeleton.createAttributes().build()).put(EntityType.SKELETON_HORSE, SkeletonHorse.createAttributes().build()).put(EntityType.SLIME, Monster.createMonsterAttributes().build()).put(EntityType.SNIFFER, Sniffer.createAttributes().build()).put(EntityType.SNOW_GOLEM, SnowGolem.createAttributes().build()).put(EntityType.SPIDER, Spider.createAttributes().build()).put(EntityType.SQUID, Squid.createAttributes().build()).put(EntityType.STRAY, AbstractSkeleton.createAttributes().build()).put(EntityType.STRIDER, Strider.createAttributes().build()).put(EntityType.TADPOLE, Tadpole.createAttributes().build()).put(EntityType.TRADER_LLAMA, Llama.createAttributes().build()).put(EntityType.TROPICAL_FISH, AbstractFish.createAttributes().build()).put(EntityType.TURTLE, Turtle.createAttributes().build()).put(EntityType.VEX, Vex.createAttributes().build()).put(EntityType.VILLAGER, Villager.createAttributes().build()).put(EntityType.VINDICATOR, Vindicator.createAttributes().build()).put(EntityType.WARDEN, Warden.createAttributes().build()).put(EntityType.WANDERING_TRADER, Mob.createMobAttributes().build()).put(EntityType.WITCH, Witch.createAttributes().build()).put(EntityType.WITHER, WitherBoss.createAttributes().build()).put(EntityType.WITHER_SKELETON, AbstractSkeleton.createAttributes().build()).put(EntityType.WOLF, Wolf.createAttributes().build()).put(EntityType.ZOGLIN, Zoglin.createAttributes().build()).put(EntityType.ZOMBIE, Zombie.createAttributes().build()).put(EntityType.ZOMBIE_HORSE, ZombieHorse.createAttributes().build()).put(EntityType.ZOMBIE_VILLAGER, Zombie.createAttributes().build()).put(EntityType.ZOMBIFIED_PIGLIN, ZombifiedPiglin.createAttributes().build()).build(); +@@ -174,11 +_,12 @@ + .build(); - public static AttributeSupplier getSupplier(EntityType p_22298_) { -- return SUPPLIERS.get(p_22298_); -+ AttributeSupplier supplier = net.minecraftforge.common.ForgeHooks.getAttributesView().get(p_22298_); -+ return supplier != null ? supplier : SUPPLIERS.get(p_22298_); - } + public static AttributeSupplier getSupplier(EntityType p_22298_) { +- return SUPPLIERS.get(p_22298_); ++ AttributeSupplier supplier = net.minecraftforge.common.ForgeHooks.getAttributesView().get(p_22298_); ++ return supplier != null ? supplier : SUPPLIERS.get(p_22298_); + } - public static boolean hasSupplier(EntityType p_22302_) { -- return SUPPLIERS.containsKey(p_22302_); -+ return SUPPLIERS.containsKey(p_22302_) || net.minecraftforge.common.ForgeHooks.getAttributesView().containsKey(p_22302_); - } + public static boolean hasSupplier(EntityType p_22302_) { +- return SUPPLIERS.containsKey(p_22302_); ++ return SUPPLIERS.containsKey(p_22302_) || net.minecraftforge.common.ForgeHooks.getAttributesView().containsKey(p_22302_); + } - public static void validate() { + public static void validate() { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch index a8955439ac..c09c20c210 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch @@ -1,38 +1,29 @@ --- a/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java +++ b/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java -@@ -23,7 +_,7 @@ +@@ -25,7 +_,7 @@ - protected boolean checkExtraStartConditions(ServerLevel p_22778_, E p_22779_) { - LivingEntity livingentity = getAttackTarget(p_22779_); -- return p_22779_.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(p_22779_, livingentity) && BehaviorUtils.isWithinAttackRange(p_22779_, livingentity, 0); -+ return p_22779_.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(p_22779_, livingentity) && BehaviorUtils.isWithinAttackRange(p_22779_, livingentity, 0); - } + protected boolean checkExtraStartConditions(ServerLevel p_22778_, E p_22779_) { + LivingEntity livingentity = getAttackTarget(p_22779_); +- return p_22779_.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(p_22779_, livingentity) && BehaviorUtils.isWithinAttackRange(p_22779_, livingentity, 0); ++ return p_22779_.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(p_22779_, livingentity) && BehaviorUtils.isWithinAttackRange(p_22779_, livingentity, 0); + } - protected boolean canStillUse(ServerLevel p_22781_, E p_22782_, long p_22783_) { -@@ -41,7 +_,7 @@ - p_22806_.stopUsingItem(); - } + protected boolean canStillUse(ServerLevel p_22781_, E p_22782_, long p_22783_) { +@@ -43,7 +_,7 @@ + p_22806_.stopUsingItem(); + } -- if (p_22806_.isHolding(Items.CROSSBOW)) { -+ if (p_22806_.isHolding(is -> is.getItem() instanceof CrossbowItem)) { - p_22806_.setChargingCrossbow(false); - CrossbowItem.setCharged(p_22806_.getUseItem(), false); - } -@@ -50,7 +_,7 @@ +- if (p_22806_.isHolding(Items.CROSSBOW)) { ++ if (p_22806_.isHolding(is -> is.getItem() instanceof CrossbowItem)) { + p_22806_.setChargingCrossbow(false); + p_22806_.getUseItem().set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); + } +@@ -51,7 +_,7 @@ - private void crossbowAttack(E p_22787_, LivingEntity p_22788_) { - if (this.crossbowState == CrossbowAttack.CrossbowState.UNCHARGED) { -- p_22787_.startUsingItem(ProjectileUtil.getWeaponHoldingHand(p_22787_, Items.CROSSBOW)); -+ p_22787_.startUsingItem(ProjectileUtil.getWeaponHoldingHand(p_22787_, item -> item instanceof CrossbowItem)); - this.crossbowState = CrossbowAttack.CrossbowState.CHARGING; - p_22787_.setChargingCrossbow(true); - } else if (this.crossbowState == CrossbowAttack.CrossbowState.CHARGING) { -@@ -73,7 +_,7 @@ - } - } else if (this.crossbowState == CrossbowAttack.CrossbowState.READY_TO_ATTACK) { - p_22787_.performRangedAttack(p_22788_, 1.0F); -- ItemStack itemstack1 = p_22787_.getItemInHand(ProjectileUtil.getWeaponHoldingHand(p_22787_, Items.CROSSBOW)); -+ ItemStack itemstack1 = p_22787_.getItemInHand(ProjectileUtil.getWeaponHoldingHand(p_22787_, item -> item instanceof CrossbowItem)); - CrossbowItem.setCharged(itemstack1, false); - this.crossbowState = CrossbowAttack.CrossbowState.UNCHARGED; - } + private void crossbowAttack(E p_22787_, LivingEntity p_22788_) { + if (this.crossbowState == CrossbowAttack.CrossbowState.UNCHARGED) { +- p_22787_.startUsingItem(ProjectileUtil.getWeaponHoldingHand(p_22787_, Items.CROSSBOW)); ++ p_22787_.startUsingItem(ProjectileUtil.getWeaponHoldingHand(p_22787_, item -> item instanceof CrossbowItem)); + this.crossbowState = CrossbowAttack.CrossbowState.CHARGING; + p_22787_.setChargingCrossbow(true); + } else if (this.crossbowState == CrossbowAttack.CrossbowState.CHARGING) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch index 574731d0e4..1af9f965f7 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java +++ b/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java -@@ -40,7 +_,7 @@ - } +@@ -47,7 +_,7 @@ + } - protected boolean checkExtraStartConditions(ServerLevel p_23174_, Villager p_23175_) { -- if (!p_23174_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_23174_, p_23175_)) { - return false; - } else if (p_23175_.getVillagerData().getProfession() != VillagerProfession.FARMER) { - return false; -@@ -115,6 +_,11 @@ - p_23196_.setBlockAndUpdate(this.aboveFarmlandPos, blockstate1); - p_23196_.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(p_23197_, blockstate1)); - flag = true; -+ } else if (itemstack.getItem() instanceof net.minecraftforge.common.IPlantable) { -+ if (((net.minecraftforge.common.IPlantable)itemstack.getItem()).getPlantType(p_23196_, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { -+ p_23196_.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable)itemstack.getItem()).getPlant(p_23196_, aboveFarmlandPos), 3); -+ flag = true; -+ } - } - } + protected boolean checkExtraStartConditions(ServerLevel p_23174_, Villager p_23175_) { +- if (!p_23174_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_23174_, p_23175_)) { + return false; + } else if (p_23175_.getVillagerData().getProfession() != VillagerProfession.FARMER) { + return false; +@@ -118,6 +_,11 @@ + p_23196_.setBlockAndUpdate(this.aboveFarmlandPos, blockstate1); + p_23196_.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(p_23197_, blockstate1)); + flag = true; ++ } else if (itemstack.getItem() instanceof net.minecraftforge.common.IPlantable) { ++ if (((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlantType(p_23196_, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { ++ p_23196_.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlant(p_23196_, aboveFarmlandPos), 3); ++ flag = true; ++ } + } + if (flag) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch index 56c25b9f2b..c12d851169 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/ai/behavior/StartAttacking.java +++ b/net/minecraft/world/entity/ai/behavior/StartAttacking.java @@ -30,7 +_,11 @@ - if (!p_258774_.canAttack(livingentity)) { - return false; - } else { -- p_258778_.set(livingentity); -+ net.minecraftforge.event.entity.living.LivingChangeTargetEvent changeTargetEvent = net.minecraftforge.common.ForgeHooks.onLivingChangeTarget(p_258774_, livingentity, net.minecraftforge.event.entity.living.LivingChangeTargetEvent.LivingTargetType.BEHAVIOR_TARGET); -+ if (changeTargetEvent.isCanceled()) -+ return false; + if (!p_258774_.canAttack(livingentity)) { + return false; + } else { +- p_258778_.set(livingentity); ++ var changeTargetEvent = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetBehavior(p_258774_, livingentity); ++ if (changeTargetEvent.isCanceled()) ++ return false; + -+ p_258778_.set(changeTargetEvent.getNewTarget()); - p_258779_.erase(); - return true; - } ++ p_258778_.set(changeTargetEvent.getNewTarget()); + p_258779_.erase(); + return true; + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/Swim.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/Swim.java.patch index c7acf611a3..d645f277f5 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/Swim.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/Swim.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/ai/behavior/Swim.java +++ b/net/minecraft/world/entity/ai/behavior/Swim.java @@ -14,7 +_,7 @@ - } + } - protected boolean checkExtraStartConditions(ServerLevel p_24388_, Mob p_24389_) { -- return p_24389_.isInWater() && p_24389_.getFluidHeight(FluidTags.WATER) > p_24389_.getFluidJumpThreshold() || p_24389_.isInLava(); -+ return p_24389_.isInWater() && p_24389_.getFluidHeight(FluidTags.WATER) > p_24389_.getFluidJumpThreshold() || p_24389_.isInLava() || p_24389_.isInFluidType((fluidType, height) -> p_24389_.canSwimInFluidType(fluidType) && height > p_24389_.getFluidJumpThreshold()); - } + public static boolean shouldSwim(Mob p_327994_) { +- return p_327994_.isInWater() && p_327994_.getFluidHeight(FluidTags.WATER) > p_327994_.getFluidJumpThreshold() || p_327994_.isInLava(); ++ return p_327994_.isInWater() &&p_327994_.getFluidHeight(FluidTags.WATER) > p_327994_.getFluidJumpThreshold() || p_327994_.isInLava() || p_327994_.isInFluidType((fluidType, height) -> p_327994_.canSwimInFluidType(fluidType) && height > p_327994_.getFluidJumpThreshold()); + } - protected boolean canStillUse(ServerLevel p_24391_, Mob p_24392_, long p_24393_) { + protected boolean checkExtraStartConditions(ServerLevel p_24388_, Mob p_24389_) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/control/MoveControl.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/control/MoveControl.java.patch deleted file mode 100644 index 32b7756a85..0000000000 --- a/patches/minecraft/net/minecraft/world/entity/ai/control/MoveControl.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/entity/ai/control/MoveControl.java -+++ b/net/minecraft/world/entity/ai/control/MoveControl.java -@@ -99,7 +_,7 @@ - BlockPos blockpos = this.mob.blockPosition(); - BlockState blockstate = this.mob.level().getBlockState(blockpos); - VoxelShape voxelshape = blockstate.getCollisionShape(this.mob.level(), blockpos); -- if (d2 > (double)this.mob.maxUpStep() && d0 * d0 + d1 * d1 < (double)Math.max(1.0F, this.mob.getBbWidth()) || !voxelshape.isEmpty() && this.mob.getY() < voxelshape.max(Direction.Axis.Y) + (double)blockpos.getY() && !blockstate.is(BlockTags.DOORS) && !blockstate.is(BlockTags.FENCES)) { -+ if (d2 > (double)this.mob.getStepHeight() && d0 * d0 + d1 * d1 < (double)Math.max(1.0F, this.mob.getBbWidth()) || !voxelshape.isEmpty() && this.mob.getY() < voxelshape.max(Direction.Axis.Y) + (double)blockpos.getY() && !blockstate.is(BlockTags.DOORS) && !blockstate.is(BlockTags.FENCES)) { - this.mob.getJumpControl().jump(); - this.operation = MoveControl.Operation.JUMPING; - } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java.patch index ca964e5f3f..ea19e899b5 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java.patch @@ -1,11 +1,13 @@ --- a/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java +++ b/net/minecraft/world/entity/ai/goal/BreakDoorGoal.java -@@ -30,7 +_,7 @@ - public boolean canUse() { - if (!super.canUse()) { - return false; -- } else if (!this.mob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ } else if (!net.minecraftforge.common.ForgeHooks.canEntityDestroy(this.mob.level(), this.doorPos, this.mob)) { - return false; - } else { - return this.isValidDifficulty(this.mob.level().getDifficulty()) && !this.isOpen(); +@@ -32,9 +_,7 @@ + if (!super.canUse()) { + return false; + } else { +- return !this.mob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) +- ? false +- : this.isValidDifficulty(this.mob.level().getDifficulty()) && !this.isOpen(); ++ return !net.minecraftforge.common.ForgeHooks.canEntityDestroy(this.mob.level(), this.doorPos, this.mob) ? false : this.isValidDifficulty(this.mob.level().getDifficulty()) && !this.isOpen(); + } + } + diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch index c6d0d844f2..47a10c47df 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/ai/goal/EatBlockGoal.java +++ b/net/minecraft/world/entity/ai/goal/EatBlockGoal.java -@@ -60,7 +_,7 @@ - if (this.eatAnimationTick == this.adjustedTickDelay(4)) { - BlockPos blockpos = this.mob.blockPosition(); - if (IS_TALL_GRASS.test(this.level.getBlockState(blockpos))) { -- if (this.level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level, this.mob)) { - this.level.destroyBlock(blockpos, false); - } +@@ -61,7 +_,7 @@ + if (this.eatAnimationTick == this.adjustedTickDelay(4)) { + BlockPos blockpos = this.mob.blockPosition(); + if (IS_TALL_GRASS.test(this.level.getBlockState(blockpos))) { +- if (this.level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level, this.mob)) { + this.level.destroyBlock(blockpos, false); + } -@@ -68,7 +_,7 @@ - } else { - BlockPos blockpos1 = blockpos.below(); - if (this.level.getBlockState(blockpos1).is(Blocks.GRASS_BLOCK)) { -- if (this.level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level, this.mob)) { - this.level.levelEvent(2001, blockpos1, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState())); - this.level.setBlock(blockpos1, Blocks.DIRT.defaultBlockState(), 2); - } +@@ -69,7 +_,7 @@ + } else { + BlockPos blockpos1 = blockpos.below(); + if (this.level.getBlockState(blockpos1).is(Blocks.GRASS_BLOCK)) { +- if (this.level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level, this.mob)) { + this.level.levelEvent(2001, blockpos1, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState())); + this.level.setBlock(blockpos1, Blocks.DIRT.defaultBlockState(), 2); + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/FloatGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/FloatGoal.java.patch index e1becbd84b..89c81c80e2 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/FloatGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/FloatGoal.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/ai/goal/FloatGoal.java +++ b/net/minecraft/world/entity/ai/goal/FloatGoal.java -@@ -14,7 +_,7 @@ - } +@@ -15,7 +_,7 @@ - public boolean canUse() { -- return this.mob.isInWater() && this.mob.getFluidHeight(FluidTags.WATER) > this.mob.getFluidJumpThreshold() || this.mob.isInLava(); -+ return this.mob.isInWater() && this.mob.getFluidHeight(FluidTags.WATER) > this.mob.getFluidJumpThreshold() || this.mob.isInLava() || this.mob.isInFluidType((fluidType, height) -> this.mob.canSwimInFluidType(fluidType) && height > this.mob.getFluidJumpThreshold()); - } + @Override + public boolean canUse() { +- return this.mob.isInWater() && this.mob.getFluidHeight(FluidTags.WATER) > this.mob.getFluidJumpThreshold() || this.mob.isInLava(); ++ return this.mob.isInWater() && this.mob.getFluidHeight(FluidTags.WATER) > this.mob.getFluidJumpThreshold() || this.mob.isInLava() || this.mob.isInFluidType((fluidType, height) -> this.mob.canSwimInFluidType(fluidType) && height > this.mob.getFluidJumpThreshold()); + } - public boolean requiresUpdateEveryTick() { + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch index 4e87dd70ac..20e1bfa81e 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch @@ -1,46 +1,46 @@ --- a/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java +++ b/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java @@ -21,6 +_,8 @@ - private final int attackInterval = 20; - private long lastCanUseCheck; - private static final long COOLDOWN_BETWEEN_CAN_USE_CHECKS = 20L; -+ private int failedPathFindingPenalty = 0; -+ private boolean canPenalize = false; + private final int attackInterval = 20; + private long lastCanUseCheck; + private static final long COOLDOWN_BETWEEN_CAN_USE_CHECKS = 20L; ++ private int failedPathFindingPenalty = 0; ++ private boolean canPenalize = false; - public MeleeAttackGoal(PathfinderMob p_25552_, double p_25553_, boolean p_25554_) { - this.mob = p_25552_; -@@ -41,6 +_,15 @@ - } else if (!livingentity.isAlive()) { - return false; - } else { -+ if (canPenalize) { -+ if (--this.ticksUntilNextPathRecalculation <= 0) { -+ this.path = this.mob.getNavigation().createPath(livingentity, 0); -+ this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); -+ return this.path != null; -+ } else { -+ return true; -+ } -+ } - this.path = this.mob.getNavigation().createPath(livingentity, 0); - if (this.path != null) { - return true; -@@ -98,6 +_,18 @@ - this.pathedTargetZ = livingentity.getZ(); - this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); - double d0 = this.mob.distanceToSqr(livingentity); -+ if (this.canPenalize) { -+ this.ticksUntilNextPathRecalculation += failedPathFindingPenalty; -+ if (this.mob.getNavigation().getPath() != null) { -+ net.minecraft.world.level.pathfinder.Node finalPathPoint = this.mob.getNavigation().getPath().getEndNode(); -+ if (finalPathPoint != null && livingentity.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) -+ failedPathFindingPenalty = 0; -+ else -+ failedPathFindingPenalty += 10; -+ } else { -+ failedPathFindingPenalty += 10; -+ } -+ } - if (d0 > 1024.0D) { - this.ticksUntilNextPathRecalculation += 10; - } else if (d0 > 256.0D) { + public MeleeAttackGoal(PathfinderMob p_25552_, double p_25553_, boolean p_25554_) { + this.mob = p_25552_; +@@ -42,6 +_,15 @@ + } else if (!livingentity.isAlive()) { + return false; + } else { ++ if (canPenalize) { ++ if (--this.ticksUntilNextPathRecalculation <= 0) { ++ this.path = this.mob.getNavigation().createPath(livingentity, 0); ++ this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); ++ return this.path != null; ++ } else { ++ return true; ++ } ++ } + this.path = this.mob.getNavigation().createPath(livingentity, 0); + return this.path != null ? true : this.mob.isWithinMeleeAttackRange(livingentity); + } +@@ -106,6 +_,18 @@ + this.pathedTargetZ = livingentity.getZ(); + this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); + double d0 = this.mob.distanceToSqr(livingentity); ++ if (this.canPenalize) { ++ this.ticksUntilNextPathRecalculation += failedPathFindingPenalty; ++ if (this.mob.getNavigation().getPath() != null) { ++ net.minecraft.world.level.pathfinder.Node finalPathPoint = this.mob.getNavigation().getPath().getEndNode(); ++ if (finalPathPoint != null && livingentity.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) ++ failedPathFindingPenalty = 0; ++ else ++ failedPathFindingPenalty += 10; ++ } else { ++ failedPathFindingPenalty += 10; ++ } ++ } + if (d0 > 1024.0) { + this.ticksUntilNextPathRecalculation += 10; + } else if (d0 > 256.0) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java.patch index 7ab7cc075b..cb4b11de24 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java.patch @@ -1,40 +1,40 @@ --- a/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java +++ b/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java -@@ -10,7 +_,7 @@ +@@ -9,7 +_,7 @@ import net.minecraft.world.item.BowItem; import net.minecraft.world.item.Items; -public class RangedBowAttackGoal extends Goal { +public class RangedBowAttackGoal extends Goal { - private final T mob; - private final double speedModifier; - private int attackIntervalMin; -@@ -21,6 +_,10 @@ - private boolean strafingBackwards; - private int strafingTime = -1; + private final T mob; + private final double speedModifier; + private int attackIntervalMin; +@@ -20,6 +_,10 @@ + private boolean strafingBackwards; + private int strafingTime = -1; -+ public RangedBowAttackGoal(M p_25792_, double p_25793_, int p_25794_, float p_25795_){ -+ this((T) p_25792_, p_25793_, p_25794_, p_25795_); -+ } ++ public RangedBowAttackGoal(M p_25792_, double p_25793_, int p_25794_, float p_25795_){ ++ this((T)p_25792_, p_25793_, p_25794_, p_25795_); ++ } + - public RangedBowAttackGoal(T p_25792_, double p_25793_, int p_25794_, float p_25795_) { - this.mob = p_25792_; - this.speedModifier = p_25793_; + public RangedBowAttackGoal(T p_25792_, double p_25793_, int p_25794_, float p_25795_) { + this.mob = p_25792_; + this.speedModifier = p_25793_; @@ -38,7 +_,7 @@ - } + } - protected boolean isHoldingBow() { -- return this.mob.isHolding(Items.BOW); -+ return this.mob.isHolding(is -> is.getItem() instanceof BowItem); - } + protected boolean isHoldingBow() { +- return this.mob.isHolding(Items.BOW); ++ return this.mob.isHolding(is -> is.getItem() instanceof BowItem); + } - public boolean canContinueToUse() { -@@ -129,7 +_,7 @@ - } + @Override +@@ -132,7 +_,7 @@ + } + } + } else if (--this.attackTime <= 0 && this.seeTime >= -60) { +- this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.BOW)); ++ this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof BowItem)); } - } else if (--this.attackTime <= 0 && this.seeTime >= -60) { -- this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.BOW)); -+ this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof BowItem)); - } - - } + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch index 781ea942e5..556a92b1da 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch @@ -1,29 +1,20 @@ --- a/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java +++ b/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java -@@ -34,7 +_,7 @@ - } +@@ -37,7 +_,7 @@ + } - private boolean isHoldingCrossbow() { -- return this.mob.isHolding(Items.CROSSBOW); -+ return this.mob.isHolding(is -> is.getItem() instanceof CrossbowItem); - } + private boolean isHoldingCrossbow() { +- return this.mob.isHolding(Items.CROSSBOW); ++ return this.mob.isHolding(is -> is.getItem() instanceof CrossbowItem); + } - public boolean canContinueToUse() { -@@ -93,7 +_,7 @@ - this.mob.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); - if (this.crossbowState == RangedCrossbowAttackGoal.CrossbowState.UNCHARGED) { - if (!flag2) { -- this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.CROSSBOW)); -+ this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof CrossbowItem)); - this.crossbowState = RangedCrossbowAttackGoal.CrossbowState.CHARGING; - this.mob.setChargingCrossbow(true); - } -@@ -117,7 +_,7 @@ - } - } else if (this.crossbowState == RangedCrossbowAttackGoal.CrossbowState.READY_TO_ATTACK && flag) { - this.mob.performRangedAttack(livingentity, 1.0F); -- ItemStack itemstack1 = this.mob.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.CROSSBOW)); -+ ItemStack itemstack1 = this.mob.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof CrossbowItem)); - CrossbowItem.setCharged(itemstack1, false); - this.crossbowState = RangedCrossbowAttackGoal.CrossbowState.UNCHARGED; - } + @Override +@@ -99,7 +_,7 @@ + this.mob.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); + if (this.crossbowState == RangedCrossbowAttackGoal.CrossbowState.UNCHARGED) { + if (!flag2) { +- this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.CROSSBOW)); ++ this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof CrossbowItem)); + this.crossbowState = RangedCrossbowAttackGoal.CrossbowState.CHARGING; + this.mob.setChargingCrossbow(true); + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch index bfed25eea5..5e6641597e 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch @@ -1,19 +1,21 @@ --- a/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java +++ b/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java -@@ -34,7 +_,7 @@ - } +@@ -35,7 +_,7 @@ - public boolean canUse() { -- if (!this.removerMob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.removerMob.level(), this.removerMob)) { - return false; - } else if (this.nextStartTick > 0) { - --this.nextStartTick; -@@ -129,6 +_,7 @@ - if (chunkaccess == null) { - return false; - } else { -+ if (!chunkaccess.getBlockState(p_25851_).canEntityDestroy(p_25850_, p_25851_, this.removerMob)) return false; - return chunkaccess.getBlockState(p_25851_).is(this.blockToRemove) && chunkaccess.getBlockState(p_25851_.above()).isAir() && chunkaccess.getBlockState(p_25851_.above(2)).isAir(); - } - } + @Override + public boolean canUse() { +- if (!this.removerMob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.removerMob.level(), this.removerMob)) { + return false; + } else if (this.nextStartTick > 0) { + this.nextStartTick--; +@@ -158,7 +_,8 @@ + ); + return chunkaccess == null + ? false +- : chunkaccess.getBlockState(p_25851_).is(this.blockToRemove) ++ : !chunkaccess.getBlockState(p_25851_).canEntityDestroy(p_25850_, p_25851_, this.removerMob) ? false ++ : chunkaccess.getBlockState(p_25851_).is(this.blockToRemove) + && chunkaccess.getBlockState(p_25851_.above()).isAir() + && chunkaccess.getBlockState(p_25851_.above(2)).isAir(); + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch index aa0494d69b..f716a1089b 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java +++ b/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java -@@ -55,7 +_,7 @@ - Player player = (Player)entity; - int i = this.horse.getTemper(); - int j = this.horse.getMaxTemper(); -- if (j > 0 && this.horse.getRandom().nextInt(j) < i) { -+ if (j > 0 && this.horse.getRandom().nextInt(j) < i && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(horse, (Player)entity)) { - this.horse.tameWithName(player); - return; - } +@@ -58,7 +_,7 @@ + if (entity instanceof Player player) { + int i = this.horse.getTemper(); + int j = this.horse.getMaxTemper(); +- if (j > 0 && this.horse.getRandom().nextInt(j) < i) { ++ if (j > 0 && this.horse.getRandom().nextInt(j) < i && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(horse, (Player)entity)) { + this.horse.tameWithName(player); + return; + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch index 1d202cfa3d..d32b201c43 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java -@@ -229,10 +_,10 @@ - Vec3 vec3 = this.getTempMobPos(); - this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; - Vec3i vec3i = this.path.getNextNodePos(); -- double d0 = Math.abs(this.mob.getX() - ((double)vec3i.getX() + 0.5D)); -+ double d0 = Math.abs(this.mob.getX() - ((double)vec3i.getX() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 - double d1 = Math.abs(this.mob.getY() - (double)vec3i.getY()); -- double d2 = Math.abs(this.mob.getZ() - ((double)vec3i.getZ() + 0.5D)); -- boolean flag = d0 < (double)this.maxDistanceToWaypoint && d2 < (double)this.maxDistanceToWaypoint && d1 < 1.0D; -+ double d2 = Math.abs(this.mob.getZ() - ((double)vec3i.getZ() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 -+ boolean flag = d0 <= (double)this.maxDistanceToWaypoint && d2 <= (double)this.maxDistanceToWaypoint && d1 < 1.0D; //Forge: Fix MC-94054 - if (flag || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(vec3)) { - this.path.advance(); - } +@@ -235,10 +_,10 @@ + Vec3 vec3 = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3i vec3i = this.path.getNextNodePos(); +- double d0 = Math.abs(this.mob.getX() - ((double)vec3i.getX() + 0.5)); ++ double d0 = Math.abs(this.mob.getX() - ((double)vec3i.getX() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 + double d1 = Math.abs(this.mob.getY() - (double)vec3i.getY()); +- double d2 = Math.abs(this.mob.getZ() - ((double)vec3i.getZ() + 0.5)); +- boolean flag = d0 < (double)this.maxDistanceToWaypoint && d2 < (double)this.maxDistanceToWaypoint && d1 < 1.0; ++ double d2 = Math.abs(this.mob.getZ() - ((double)vec3i.getZ() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 ++ boolean flag = d0 <= (double)this.maxDistanceToWaypoint && d2 <= (double)this.maxDistanceToWaypoint && d1 < 1.0D; //Forge: Fix MC-94054 + if (flag || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(vec3)) { + this.path.advance(); + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java.patch index 1be52c0043..0f38827712 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java.patch @@ -1,12 +1,17 @@ --- a/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java -@@ -41,7 +_,8 @@ - super.tick(); - } else { - if (this.pathToPosition != null) { -- if (!this.pathToPosition.closerToCenterThan(this.mob.position(), (double)this.mob.getBbWidth()) && (!(this.mob.getY() > (double)this.pathToPosition.getY()) || !BlockPos.containing((double)this.pathToPosition.getX(), this.mob.getY(), (double)this.pathToPosition.getZ()).closerToCenterThan(this.mob.position(), (double)this.mob.getBbWidth()))) { -+ // FORGE: Fix MC-94054 -+ if (!this.pathToPosition.closerToCenterThan(this.mob.position(), Math.max((double)this.mob.getBbWidth(), 1.0D)) && (!(this.mob.getY() > (double)this.pathToPosition.getY()) || !(BlockPos.containing((double)this.pathToPosition.getX(), this.mob.getY(), (double)this.pathToPosition.getZ())).closerToCenterThan(this.mob.position(), Math.max((double)this.mob.getBbWidth(), 1.0D)))) { - this.mob.getMoveControl().setWantedPosition((double)this.pathToPosition.getX(), (double)this.pathToPosition.getY(), (double)this.pathToPosition.getZ(), this.speedModifier); - } else { - this.pathToPosition = null; +@@ -45,12 +_,8 @@ + super.tick(); + } else { + if (this.pathToPosition != null) { +- if (!this.pathToPosition.closerToCenterThan(this.mob.position(), (double)this.mob.getBbWidth()) +- && ( +- !(this.mob.getY() > (double)this.pathToPosition.getY()) +- || !BlockPos.containing((double)this.pathToPosition.getX(), this.mob.getY(), (double)this.pathToPosition.getZ()) +- .closerToCenterThan(this.mob.position(), (double)this.mob.getBbWidth()) +- )) { ++ // FORGE: Fix MC-94054 ++ if (!this.pathToPosition.closerToCenterThan(this.mob.position(), Math.max((double)this.mob.getBbWidth(), 1.0D)) && (!(this.mob.getY() > (double)this.pathToPosition.getY()) || !(BlockPos.containing((double)this.pathToPosition.getX(), this.mob.getY(), (double)this.pathToPosition.getZ())).closerToCenterThan(this.mob.position(), Math.max((double)this.mob.getBbWidth(), 1.0D)))) { + this.mob + .getMoveControl() + .setWantedPosition((double)this.pathToPosition.getX(), (double)this.pathToPosition.getY(), (double)this.pathToPosition.getZ(), this.speedModifier); diff --git a/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch index 0ce6efee72..f98a696d36 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch @@ -1,22 +1,23 @@ --- a/net/minecraft/world/entity/ai/village/VillageSiege.java +++ b/net/minecraft/world/entity/ai/village/VillageSiege.java -@@ -78,7 +_,9 @@ - this.spawnX = blockpos.getX() + Mth.floor(Mth.cos(f) * 32.0F); - this.spawnY = blockpos.getY(); - this.spawnZ = blockpos.getZ() + Mth.floor(Mth.sin(f) * 32.0F); -- if (this.findRandomSpawnPos(p_27008_, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)) != null) { -+ Vec3 siegeLocation = this.findRandomSpawnPos(p_27008_, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)); -+ if (siegeLocation != null) { -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.village.VillageSiegeEvent(this, p_27008_, player, siegeLocation))) return false; - this.nextSpawnTime = 0; - this.zombiesToSpawn = 20; - break; -@@ -98,7 +_,7 @@ - if (vec3 != null) { - Zombie zombie; - try { -- zombie = new Zombie(p_27017_); -+ zombie = EntityType.ZOMBIE.create(p_27017_); //Forge: Direct Initialization is deprecated, use EntityType. - zombie.finalizeSpawn(p_27017_, p_27017_.getCurrentDifficultyAt(zombie.blockPosition()), MobSpawnType.EVENT, (SpawnGroupData)null, (CompoundTag)null); - } catch (Exception exception) { - LOGGER.warn("Failed to create zombie for village siege at {}", vec3, exception); +@@ -77,7 +_,10 @@ + this.spawnX = blockpos.getX() + Mth.floor(Mth.cos(f) * 32.0F); + this.spawnY = blockpos.getY(); + this.spawnZ = blockpos.getZ() + Mth.floor(Mth.sin(f) * 32.0F); +- if (this.findRandomSpawnPos(p_27008_, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)) != null) { ++ Vec3 siegeLocation = this.findRandomSpawnPos(p_27008_, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)); ++ if (siegeLocation != null) { ++ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.village.VillageSiegeEvent(this, p_27008_, player, siegeLocation))) ++ return false; + this.nextSpawnTime = 0; + this.zombiesToSpawn = 20; + break; +@@ -97,7 +_,7 @@ + if (vec3 != null) { + Zombie zombie; + try { +- zombie = new Zombie(p_27017_); ++ zombie = EntityType.ZOMBIE.create(p_27017_); //Forge: Direct Initialization is deprecated, use EntityType. + zombie.finalizeSpawn(p_27017_, p_27017_.getCurrentDifficultyAt(zombie.blockPosition()), MobSpawnType.EVENT, null); + } catch (Exception exception) { + LOGGER.warn("Failed to create zombie for village siege at {}", vec3, exception); diff --git a/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch index 7937ac5519..358930f268 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch @@ -1,31 +1,19 @@ --- a/net/minecraft/world/entity/ai/village/poi/PoiTypes.java +++ b/net/minecraft/world/entity/ai/village/poi/PoiTypes.java -@@ -48,7 +_,9 @@ - private static final Set CAULDRONS = ImmutableList.of(Blocks.CAULDRON, Blocks.LAVA_CAULDRON, Blocks.WATER_CAULDRON, Blocks.POWDER_SNOW_CAULDRON).stream().flatMap((p_218093_) -> { - return p_218093_.getStateDefinition().getPossibleStates().stream(); - }).collect(ImmutableSet.toImmutableSet()); -- private static final Map> TYPE_BY_STATE = Maps.newHashMap(); -+ // Forge: We patch these 2 fields to support modded entries -+ private static final Map TYPE_BY_STATE = net.minecraftforge.registries.GameData.getBlockStatePointOfInterestTypeMap(); -+ protected static final Set f_218067_ = TYPE_BY_STATE.keySet(); +@@ -66,7 +_,7 @@ + .stream() + .flatMap(p_218093_ -> p_218093_.getStateDefinition().getPossibleStates().stream()) + .collect(ImmutableSet.toImmutableSet()); +- private static final Map> TYPE_BY_STATE = Maps.newHashMap(); ++ private static final Map> TYPE_BY_STATE = net.minecraftforge.registries.GameData.PoiTypeCallbacks.getStateToPoi(); - private static Set getBlockStates(Block p_218074_) { - return ImmutableSet.copyOf(p_218074_.getStateDefinition().getPossibleStates()); -@@ -66,16 +_,10 @@ - } + private static Set getBlockStates(Block p_218074_) { + return ImmutableSet.copyOf(p_218074_.getStateDefinition().getPossibleStates()); +@@ -79,7 +_,6 @@ + private static PoiType register(Registry p_218085_, ResourceKey p_218086_, Set p_218087_, int p_218088_, int p_218089_) { + PoiType poitype = new PoiType(p_218087_, p_218088_, p_218089_); + Registry.register(p_218085_, p_218086_, poitype); +- registerBlockStates(p_218085_.getHolderOrThrow(p_218086_), p_218087_); + return poitype; + } - private static void registerBlockStates(Holder p_250815_, Set p_250679_) { -- p_250679_.forEach((p_218081_) -> { -- Holder holder = TYPE_BY_STATE.put(p_218081_, p_250815_); -- if (holder != null) { -- throw (IllegalStateException)Util.pauseInIde(new IllegalStateException(String.format(Locale.ROOT, "%s is defined in more than one PoI type", p_218081_))); -- } -- }); - } - - public static Optional> forState(BlockState p_218076_) { -- return Optional.ofNullable(TYPE_BY_STATE.get(p_218076_)); -+ return Optional.ofNullable(TYPE_BY_STATE.get(p_218076_)).flatMap(net.minecraftforge.registries.ForgeRegistries.POI_TYPES::getHolder); - } - - public static boolean hasPoi(BlockState p_254440_) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch index 57fe4cf62d..ac25b38902 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/animal/Animal.java +++ b/net/minecraft/world/entity/animal/Animal.java -@@ -203,6 +_,17 @@ +@@ -201,6 +_,17 @@ - public void spawnChildFromBreeding(ServerLevel p_27564_, Animal p_27565_) { - AgeableMob ageablemob = this.getBreedOffspring(p_27564_, p_27565_); -+ final net.minecraftforge.event.entity.living.BabyEntitySpawnEvent event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, p_27565_, ageablemob); -+ final boolean cancelled = net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ ageablemob = event.getChild(); -+ if (cancelled) { -+ //Reset the "inLove" state for the animals -+ this.setAge(6000); -+ p_27565_.setAge(6000); -+ this.resetLove(); -+ p_27565_.resetLove(); -+ return; -+ } - if (ageablemob != null) { - ageablemob.setBaby(true); - ageablemob.moveTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); + public void spawnChildFromBreeding(ServerLevel p_27564_, Animal p_27565_) { + AgeableMob ageablemob = this.getBreedOffspring(p_27564_, p_27565_); ++ final net.minecraftforge.event.entity.living.BabyEntitySpawnEvent event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, p_27565_, ageablemob); ++ final boolean cancelled = net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); ++ ageablemob = event.getChild(); ++ if (cancelled) { ++ //Reset the "inLove" state for the animals ++ this.setAge(6000); ++ p_27565_.setAge(6000); ++ this.resetLove(); ++ p_27565_.resetLove(); ++ return; ++ } + if (ageablemob != null) { + ageablemob.setBaby(true); + ageablemob.moveTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Bee.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Bee.java.patch index ef5ee0a259..6956e7ca53 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Bee.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Bee.java.patch @@ -1,30 +1,39 @@ --- a/net/minecraft/world/entity/animal/Bee.java +++ b/net/minecraft/world/entity/animal/Bee.java -@@ -473,7 +_,7 @@ - return false; - } else { - BlockEntity blockentity = this.level().getBlockEntity(this.hivePos); -- return blockentity != null && blockentity.getType() == BlockEntityType.BEEHIVE; -+ return blockentity instanceof BeehiveBlockEntity; - } - } +@@ -486,7 +_,7 @@ + return false; + } else { + BlockEntity blockentity = this.level().getBlockEntity(this.hivePos); +- return blockentity != null && blockentity.getType() == BlockEntityType.BEEHIVE; ++ return blockentity instanceof BeehiveBlockEntity; + } + } -@@ -612,8 +_,18 @@ - return MobType.ARTHROPOD; - } +@@ -635,13 +_,22 @@ + } -+ @Deprecated // FORGE: use jumpInFluid instead - protected void jumpInLiquid(TagKey p_204061_) { -+ this.jumpInLiquidInternal(); -+ } + @Override +- protected void jumpInLiquid(TagKey p_204061_) { +- this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.01, 0.0)); +- } +- +- @Override + public Vec3 getLeashOffset() { + return new Vec3(0.0, (double)(0.5F * this.getEyeHeight()), (double)(this.getBbWidth() * 0.2F)); ++ } + -+ private void jumpInLiquidInternal() { - this.setDeltaMovement(this.getDeltaMovement().add(0.0D, 0.01D, 0.0D)); -+ } ++ @Deprecated // FORGE: use jumpInFluid instead ++ protected void jumpInLiquid(TagKey p_204061_) { ++ this.jumpInLiquidInternal(); ++ } + -+ @Override -+ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { -+ this.jumpInLiquidInternal(); - } ++ private void jumpInLiquidInternal() { ++ this.setDeltaMovement(this.getDeltaMovement().add(0.0D, 0.01D, 0.0D)); ++ } ++ ++ @Override ++ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { ++ this.jumpInLiquidInternal(); + } - public Vec3 getLeashOffset() { + boolean closerThan(BlockPos p_27817_, int p_27818_) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Cat.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Cat.java.patch index 2b3a885a0c..e0fd36918e 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Cat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Cat.java.patch @@ -1,21 +1,22 @@ --- a/net/minecraft/world/entity/animal/Cat.java +++ b/net/minecraft/world/entity/animal/Cat.java -@@ -366,8 +_,8 @@ - if (this.isOwnedBy(p_28153_)) { - if (!(item instanceof DyeItem)) { - if (item.isEdible() && this.isFood(itemstack) && this.getHealth() < this.getMaxHealth()) { -+ this.heal((float)itemstack.getFoodProperties(this).getNutrition()); - this.usePlayerItem(p_28153_, p_28154_, itemstack); -- this.heal((float)item.getFoodProperties().getNutrition()); - return InteractionResult.CONSUME; - } +@@ -379,9 +_,9 @@ + } + } else if (this.isFood(itemstack) && this.getHealth() < this.getMaxHealth()) { + if (!this.level().isClientSide()) { +- this.usePlayerItem(p_28153_, p_28154_, itemstack); + FoodProperties foodproperties = itemstack.get(DataComponents.FOOD); + this.heal(foodproperties != null ? (float)foodproperties.nutrition() : 1.0F); ++ this.usePlayerItem(p_28153_, p_28154_, itemstack); + } -@@ -392,7 +_,7 @@ - } - } else if (this.isFood(itemstack)) { - this.usePlayerItem(p_28153_, p_28154_, itemstack); -- if (this.random.nextInt(3) == 0) { -+ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_28153_)) { - this.tame(p_28153_); - this.setOrderedToSit(true); - this.level().broadcastEntityEvent(this, (byte)7); + return InteractionResult.sidedSuccess(this.level().isClientSide()); +@@ -441,7 +_,7 @@ + } + + private void tryToTame(Player p_333297_) { +- if (this.random.nextInt(3) == 0) { ++ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_333297_)) { + this.tame(p_333297_); + this.setOrderedToSit(true); + this.level().broadcastEntityEvent(this, (byte)7); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Fox.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Fox.java.patch index 05d123ad3a..38b54ccdbe 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Fox.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Fox.java.patch @@ -1,56 +1,57 @@ --- a/net/minecraft/world/entity/animal/Fox.java +++ b/net/minecraft/world/entity/animal/Fox.java -@@ -655,13 +_,16 @@ - } +@@ -670,13 +_,17 @@ - protected void dropAllDeathLoot(DamageSource p_28536_) { -+ super.dropAllDeathLoot(p_28536_); -+ } -+ protected void dropEquipment() { // Forge: move extra drops to dropEquipment to allow them to be captured by LivingDropsEvent -+ super.dropEquipment(); - ItemStack itemstack = this.getItemBySlot(EquipmentSlot.MAINHAND); - if (!itemstack.isEmpty()) { - this.spawnAtLocation(itemstack); - this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); - } + @Override + protected void dropAllDeathLoot(DamageSource p_28536_) { ++ super.dropAllDeathLoot(p_28536_); ++ } ++ ++ @Override ++ protected void dropEquipment() { // Forge: move extra drops to dropEquipment to allow them to be captured by LivingDropsEvent ++ super.dropEquipment(); + ItemStack itemstack = this.getItemBySlot(EquipmentSlot.MAINHAND); + if (!itemstack.isEmpty()) { + this.spawnAtLocation(itemstack); + this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); + } +- +- super.dropAllDeathLoot(p_28536_); + } -- super.dropAllDeathLoot(p_28536_); - } + public static boolean isPathClear(Fox p_28472_, LivingEntity p_28473_) { +@@ -835,6 +_,16 @@ + protected void breed() { + ServerLevel serverlevel = (ServerLevel)this.level; + Fox fox = (Fox)this.animal.getBreedOffspring(serverlevel, this.partner); ++ var event = net.minecraftforge.event.ForgeEventFactory.onBabySpawn(animal, partner, fox); ++ fox = (Fox)event.getChild(); ++ if (event.isCanceled()) { ++ //Reset the "inLove" state for the animals ++ this.animal.setAge(6000); ++ this.partner.setAge(6000); ++ this.animal.resetLove(); ++ this.partner.resetLove(); ++ return; ++ } + if (fox != null) { + ServerPlayer serverplayer = this.animal.getLoveCause(); + ServerPlayer serverplayer1 = this.partner.getLoveCause(); +@@ -918,7 +_,7 @@ + } - protected Vector3f getPassengerAttachmentPoint(Entity p_301360_, EntityDimensions p_299584_, float p_299082_) { -@@ -815,6 +_,17 @@ - protected void breed() { - ServerLevel serverlevel = (ServerLevel)this.level; - Fox fox = (Fox)this.animal.getBreedOffspring(serverlevel, this.partner); -+ final net.minecraftforge.event.entity.living.BabyEntitySpawnEvent event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(animal, partner, fox); -+ final boolean cancelled = net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ fox = (Fox) event.getChild(); -+ if (cancelled) { -+ //Reset the "inLove" state for the animals -+ this.animal.setAge(6000); -+ this.partner.setAge(6000); -+ this.animal.resetLove(); -+ this.partner.resetLove(); -+ return; -+ } - if (fox != null) { - ServerPlayer serverplayer = this.animal.getLoveCause(); - ServerPlayer serverplayer1 = this.partner.getLoveCause(); -@@ -886,7 +_,7 @@ - } + protected void onReachedTarget() { +- if (Fox.this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(Fox.this.level(), Fox.this)) { + BlockState blockstate = Fox.this.level().getBlockState(this.blockPos); + if (blockstate.is(Blocks.SWEET_BERRY_BUSH)) { + this.pickSweetBerries(blockstate); +@@ -977,7 +_,7 @@ - protected void onReachedTarget() { -- if (Fox.this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(Fox.this.level(), Fox.this)) { - BlockState blockstate = Fox.this.level().getBlockState(this.blockPos); - if (blockstate.is(Blocks.SWEET_BERRY_BUSH)) { - this.pickSweetBerries(blockstate); -@@ -942,7 +_,7 @@ - } - - public boolean canUse() { -- return Fox.this.isInWater() && Fox.this.getFluidHeight(FluidTags.WATER) > 0.25D || Fox.this.isInLava(); -+ return Fox.this.isInWater() && Fox.this.getFluidHeight(FluidTags.WATER) > 0.25D || Fox.this.isInLava() || Fox.this.isInFluidType((fluidType, height) -> Fox.this.canSwimInFluidType(fluidType) && height > 0.25D); - } - } + @Override + public boolean canUse() { +- return Fox.this.isInWater() && Fox.this.getFluidHeight(FluidTags.WATER) > 0.25 || Fox.this.isInLava(); ++ return Fox.this.isInWater() && Fox.this.getFluidHeight(FluidTags.WATER) > 0.25 || Fox.this.isInLava() || Fox.this.isInFluidType((fluidType, height) -> Fox.this.canSwimInFluidType(fluidType) && height > 0.25D); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/MushroomCow.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/MushroomCow.java.patch index 127d1e86bf..a247273dbb 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/MushroomCow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/MushroomCow.java.patch @@ -1,71 +1,75 @@ --- a/net/minecraft/world/entity/animal/MushroomCow.java +++ b/net/minecraft/world/entity/animal/MushroomCow.java -@@ -41,7 +_,7 @@ +@@ -42,7 +_,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; -public class MushroomCow extends Cow implements Shearable, VariantHolder { -+public class MushroomCow extends Cow implements Shearable, net.minecraftforge.common.IForgeShearable { - private static final EntityDataAccessor DATA_TYPE = SynchedEntityData.defineId(MushroomCow.class, EntityDataSerializers.STRING); - private static final int MUTATE_CHANCE = 1024; - private static final String TAG_STEW_EFFECTS = "stew_effects"; -@@ -102,7 +_,7 @@ ++public class MushroomCow extends Cow implements Shearable, VariantHolder, net.minecraftforge.common.IForgeShearable { + private static final EntityDataAccessor DATA_TYPE = SynchedEntityData.defineId(MushroomCow.class, EntityDataSerializers.STRING); + private static final int MUTATE_CHANCE = 1024; + private static final String TAG_STEW_EFFECTS = "stew_effects"; +@@ -108,7 +_,7 @@ - this.playSound(soundevent, 1.0F, 1.0F); - return InteractionResult.sidedSuccess(this.level().isClientSide); -- } else if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ } else if (false && itemstack.getItem() == Items.SHEARS && this.readyForShearing()) { //Forge: Moved to onSheared - this.shear(SoundSource.PLAYERS); - this.gameEvent(GameEvent.SHEAR, p_28941_); - if (!this.level().isClientSide) { -@@ -141,9 +_,20 @@ - } - } + this.playSound(soundevent, 1.0F, 1.0F); + return InteractionResult.sidedSuccess(this.level().isClientSide); +- } else if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ } else if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { //Forge: Moved to onSheared + this.shear(SoundSource.PLAYERS); + this.gameEvent(GameEvent.SHEAR, p_28941_); + if (!this.level().isClientSide) { +@@ -163,8 +_,13 @@ -+ @Override -+ public java.util.List onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { -+ this.gameEvent(GameEvent.SHEAR, player); -+ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS); -+ } + @Override + public void shear(SoundSource p_28924_) { ++ shearInternal(p_28924_).forEach(s -> this.level().addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0D), this.getZ(), s))); ++ } + - public void shear(SoundSource p_28924_) { -+ shearInternal(p_28924_).forEach(s -> this.level().addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0D), this.getZ(), s))); -+ } -+ -+ private java.util.List shearInternal(SoundSource p_28924_) { - this.level().playSound((Player)null, this, SoundEvents.MOOSHROOM_SHEAR, p_28924_, 1.0F, 1.0F); - if (!this.level().isClientSide()) { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.COW, time -> {})) return java.util.Collections.emptyList(); - Cow cow = EntityType.COW.create(this.level()); - if (cow != null) { - ((ServerLevel)this.level()).sendParticles(ParticleTypes.EXPLOSION, this.getX(), this.getY(0.5D), this.getZ(), 1, 0.0D, 0.0D, 0.0D, 0.0D); -@@ -162,12 +_,16 @@ ++ private java.util.List shearInternal(SoundSource p_28924_) { + this.level().playSound(null, this, SoundEvents.MOOSHROOM_SHEAR, p_28924_, 1.0F, 1.0F); + if (!this.level().isClientSide()) { ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.COW, time -> {})) return java.util.Collections.emptyList(); + Cow cow = EntityType.COW.create(this.level()); + if (cow != null) { + ((ServerLevel)this.level()).sendParticles(ParticleTypes.EXPLOSION, this.getX(), this.getY(0.5), this.getZ(), 1, 0.0, 0.0, 0.0, 0.0); +@@ -183,17 +_,16 @@ - cow.setInvulnerable(this.isInvulnerable()); - this.level().addFreshEntity(cow); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, cow); + cow.setInvulnerable(this.isInvulnerable()); + this.level().addFreshEntity(cow); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, cow); -+ java.util.List items = new java.util.ArrayList<>(); - for(int i = 0; i < 5; ++i) { -- this.level().addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0D), this.getZ(), new ItemStack(this.getVariant().blockState.getBlock()))); -+ items.add(new ItemStack(this.getVariant().blockState.getBlock())); ++ var items = new java.util.ArrayList(); + for (int i = 0; i < 5; i++) { +- this.level() +- .addFreshEntity( +- new ItemEntity( +- this.level(), this.getX(), this.getY(1.0), this.getZ(), new ItemStack(this.getVariant().blockState.getBlock()) +- ) +- ); ++ items.add(new ItemStack(this.getVariant().blockState.getBlock())); + } ++ return items; } -+ return items; - } - } -+ return java.util.Collections.emptyList(); + } ++ return java.util.Collections.emptyList(); + } - } + @Override +@@ -255,6 +_,17 @@ + } -@@ -231,6 +_,11 @@ - } - - return mushroomcow$mushroomtype2; -+ } + return mushroomcow$mushroomtype2; ++ } + -+ @Override -+ public boolean isShearable(ItemStack item, Level world, BlockPos pos) { -+ return readyForShearing(); - } ++ @Override ++ public java.util.List onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { ++ this.gameEvent(GameEvent.SHEAR, player); ++ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS); ++ } ++ ++ @Override ++ public boolean isShearable(ItemStack item, Level world, BlockPos pos) { ++ return readyForShearing(); + } - public static enum MushroomType implements StringRepresentable { + public static enum MushroomType implements StringRepresentable { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Ocelot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Ocelot.java.patch index 757464f26f..c40b917f1e 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Ocelot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Ocelot.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/animal/Ocelot.java +++ b/net/minecraft/world/entity/animal/Ocelot.java -@@ -162,7 +_,7 @@ - if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemstack) && p_29021_.distanceToSqr(this) < 9.0D) { - this.usePlayerItem(p_29021_, p_29022_, itemstack); - if (!this.level().isClientSide) { -- if (this.random.nextInt(3) == 0) { -+ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_29021_)) { - this.setTrusting(true); - this.spawnTrustingParticles(true); - this.level().broadcastEntityEvent(this, (byte)41); +@@ -170,7 +_,7 @@ + if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemstack) && p_29021_.distanceToSqr(this) < 9.0) { + this.usePlayerItem(p_29021_, p_29022_, itemstack); + if (!this.level().isClientSide) { +- if (this.random.nextInt(3) == 0) { ++ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_29021_)) { + this.setTrusting(true); + this.spawnTrustingParticles(true); + this.level().broadcastEntityEvent(this, (byte)41); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Parrot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Parrot.java.patch index 5f6343c3c7..70ffcde076 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Parrot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Parrot.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/animal/Parrot.java +++ b/net/minecraft/world/entity/animal/Parrot.java -@@ -247,7 +_,7 @@ - } +@@ -253,7 +_,7 @@ + } - if (!this.level().isClientSide) { -- if (this.random.nextInt(10) == 0) { -+ if (this.random.nextInt(10) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_29414_)) { - this.tame(p_29414_); - this.level().broadcastEntityEvent(this, (byte)7); - } else { + if (!this.level().isClientSide) { +- if (this.random.nextInt(10) == 0) { ++ if (this.random.nextInt(10) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_29414_)) { + this.tame(p_29414_); + this.level().broadcastEntityEvent(this, (byte)7); + } else { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Pig.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Pig.java.patch index b48a196d7f..fe73f68408 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Pig.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Pig.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/entity/animal/Pig.java +++ b/net/minecraft/world/entity/animal/Pig.java -@@ -203,7 +_,7 @@ - } +@@ -204,7 +_,7 @@ - public void thunderHit(ServerLevel p_29473_, LightningBolt p_29474_) { -- if (p_29473_.getDifficulty() != Difficulty.PEACEFUL) { -+ if (p_29473_.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> {})) { - ZombifiedPiglin zombifiedpiglin = EntityType.ZOMBIFIED_PIGLIN.create(p_29473_); - if (zombifiedpiglin != null) { - zombifiedpiglin.setItemSlot(EquipmentSlot.MAINHAND, new ItemStack(Items.GOLDEN_SWORD)); -@@ -216,6 +_,7 @@ - } + @Override + public void thunderHit(ServerLevel p_29473_, LightningBolt p_29474_) { +- if (p_29473_.getDifficulty() != Difficulty.PEACEFUL) { ++ if (p_29473_.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> {})) { + ZombifiedPiglin zombifiedpiglin = EntityType.ZOMBIFIED_PIGLIN.create(p_29473_); + if (zombifiedpiglin != null) { + zombifiedpiglin.setItemSlot(EquipmentSlot.MAINHAND, new ItemStack(Items.GOLDEN_SWORD)); +@@ -217,6 +_,7 @@ + } - zombifiedpiglin.setPersistenceRequired(); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombifiedpiglin); - p_29473_.addFreshEntity(zombifiedpiglin); - this.discard(); - } else { + zombifiedpiglin.setPersistenceRequired(); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombifiedpiglin); + p_29473_.addFreshEntity(zombifiedpiglin); + this.discard(); + } else { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Rabbit.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Rabbit.java.patch index 835b778c32..ffb2d48cae 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Rabbit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Rabbit.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/animal/Rabbit.java +++ b/net/minecraft/world/entity/animal/Rabbit.java -@@ -515,7 +_,7 @@ - - public boolean canUse() { - if (this.nextStartTick <= 0) { -- if (!this.rabbit.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.rabbit.level(), this.rabbit)) { - return false; - } +@@ -525,7 +_,7 @@ + @Override + public boolean canUse() { + if (this.nextStartTick <= 0) { +- if (!this.rabbit.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.rabbit.level(), this.rabbit)) { + return false; + } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Sheep.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Sheep.java.patch index da4dddc8f2..6256c7059d 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Sheep.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Sheep.java.patch @@ -1,48 +1,62 @@ --- a/net/minecraft/world/entity/animal/Sheep.java +++ b/net/minecraft/world/entity/animal/Sheep.java -@@ -63,7 +_,7 @@ +@@ -62,7 +_,7 @@ import net.minecraft.world.level.storage.loot.BuiltInLootTables; - import org.joml.Vector3f; + import net.minecraft.world.level.storage.loot.LootTable; -public class Sheep extends Animal implements Shearable { +public class Sheep extends Animal implements Shearable, net.minecraftforge.common.IForgeShearable { - private static final int EAT_ANIMATION_TICKS = 40; - private static final EntityDataAccessor DATA_WOOL_ID = SynchedEntityData.defineId(Sheep.class, EntityDataSerializers.BYTE); - private static final Map ITEM_BY_DYE = Util.make(Maps.newEnumMap(DyeColor.class), (p_29841_) -> { -@@ -235,7 +_,7 @@ + private static final int EAT_ANIMATION_TICKS = 40; + private static final EntityDataAccessor DATA_WOOL_ID = SynchedEntityData.defineId(Sheep.class, EntityDataSerializers.BYTE); + private static final Map ITEM_BY_DYE = Util.make(Maps.newEnumMap(DyeColor.class), p_29841_ -> { +@@ -208,7 +_,7 @@ + @Override + public InteractionResult mobInteract(Player p_29853_, InteractionHand p_29854_) { + ItemStack itemstack = p_29853_.getItemInHand(p_29854_); +- if (itemstack.is(Items.SHEARS)) { ++ if (false && itemstack.is(Items.SHEARS)) { // Forge: Moved to onSheared + if (!this.level().isClientSide && this.readyForShearing()) { + this.shear(SoundSource.PLAYERS); + this.gameEvent(GameEvent.SHEAR, p_29853_); +@@ -224,12 +_,24 @@ - public InteractionResult mobInteract(Player p_29853_, InteractionHand p_29854_) { - ItemStack itemstack = p_29853_.getItemInHand(p_29854_); -- if (itemstack.is(Items.SHEARS)) { -+ if (false && itemstack.getItem() == Items.SHEARS) { //Forge: Moved to onSheared - if (!this.level().isClientSide && this.readyForShearing()) { - this.shear(SoundSource.PLAYERS); - this.gameEvent(GameEvent.SHEAR, p_29853_); -@@ -392,5 +_,27 @@ + @Override + public void shear(SoundSource p_29819_) { ++ dropShearedItems(shearInternal(p_29819_)); ++ } ++ ++ private java.util.List shearInternal(SoundSource p_29819_) { + this.level().playSound(null, this, SoundEvents.SHEEP_SHEAR, p_29819_, 1.0F, 1.0F); + this.setSheared(true); + int i = 1 + this.random.nextInt(3); - protected Vector3f getPassengerAttachmentPoint(Entity p_297780_, EntityDimensions p_298437_, float p_300315_) { - return new Vector3f(0.0F, p_298437_.height - 0.0625F * p_300315_, 0.0F); -+ } ++ var ret = new java.util.ArrayList(); + for (int j = 0; j < i; j++) { +- ItemEntity itementity = this.spawnAtLocation(ITEM_BY_DYE.get(this.getColor()), 1); ++ ret.add(new ItemStack(ITEM_BY_DYE.get(this.getColor()))); ++ } ++ return ret; ++ } + -+ @Override -+ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) { -+ return readyForShearing(); -+ } ++ private void dropShearedItems(java.util.List items) { ++ for (var stack : items) { ++ ItemEntity itementity = this.spawnAtLocation(stack, 1); + if (itementity != null) { + itementity.setDeltaMovement( + itementity.getDeltaMovement() +@@ -375,5 +_,15 @@ + craftingcontainer.setItem(0, new ItemStack(DyeItem.byColor(p_29832_))); + craftingcontainer.setItem(1, new ItemStack(DyeItem.byColor(p_29833_))); + return craftingcontainer; ++ } + -+ @Override -+ public java.util.List onSheared(@Nullable Player player, ItemStack item, Level world, BlockPos pos, int fortune) { -+ world.playSound(null, this, SoundEvents.SHEEP_SHEAR, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, 1.0F, 1.0F); -+ this.gameEvent(GameEvent.SHEAR, player); -+ if (!world.isClientSide) { -+ this.setSheared(true); -+ int i = 1 + this.random.nextInt(3); ++ @Override ++ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) { ++ return readyForShearing(); ++ } + -+ java.util.List items = new java.util.ArrayList<>(); -+ for (int j = 0; j < i; ++j) { -+ items.add(new ItemStack(ITEM_BY_DYE.get(this.getColor()))); -+ } -+ return items; -+ } -+ return java.util.Collections.emptyList(); - } ++ @Override ++ public java.util.List onSheared(@Nullable Player player, ItemStack item, Level world, BlockPos pos, int fortune) { ++ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS); + } } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/SnowGolem.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/SnowGolem.java.patch index 8dc7847ec7..aa2f33beca 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/SnowGolem.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/SnowGolem.java.patch @@ -1,61 +1,60 @@ --- a/net/minecraft/world/entity/animal/SnowGolem.java +++ b/net/minecraft/world/entity/animal/SnowGolem.java -@@ -40,7 +_,7 @@ +@@ -38,7 +_,7 @@ import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.Vec3; -public class SnowGolem extends AbstractGolem implements Shearable, RangedAttackMob { +public class SnowGolem extends AbstractGolem implements Shearable, RangedAttackMob, net.minecraftforge.common.IForgeShearable { - private static final EntityDataAccessor DATA_PUMPKIN_ID = SynchedEntityData.defineId(SnowGolem.class, EntityDataSerializers.BYTE); - private static final byte PUMPKIN_FLAG = 16; - private static final float EYE_HEIGHT = 1.7F; -@@ -92,7 +_,7 @@ - this.hurt(this.damageSources().onFire(), 1.0F); - } + private static final EntityDataAccessor DATA_PUMPKIN_ID = SynchedEntityData.defineId(SnowGolem.class, EntityDataSerializers.BYTE); + private static final byte PUMPKIN_FLAG = 16; -- if (!this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { - return; - } +@@ -92,7 +_,7 @@ + this.hurt(this.damageSources().onFire(), 1.0F); + } + +- if (!this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { + return; + } @@ -103,7 +_,7 @@ - int k = Mth.floor(this.getY()); - int l = Mth.floor(this.getZ() + (double)((float)(i / 2 % 2 * 2 - 1) * 0.25F)); - BlockPos blockpos = new BlockPos(j, k, l); -- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { -+ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { - this.level().setBlockAndUpdate(blockpos, blockstate); - this.level().gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this, blockstate)); - } -@@ -130,7 +_,7 @@ - - protected InteractionResult mobInteract(Player p_29920_, InteractionHand p_29921_) { - ItemStack itemstack = p_29920_.getItemInHand(p_29921_); -- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (false && itemstack.getItem() == Items.SHEARS && this.readyForShearing()) { //Forge: Moved to onSheared - this.shear(SoundSource.PLAYERS); - this.gameEvent(GameEvent.SHEAR, p_29920_); - if (!this.level().isClientSide) { -@@ -189,5 +_,22 @@ - - public Vec3 getLeashOffset() { - return new Vec3(0.0D, (double)(0.75F * this.getEyeHeight()), (double)(this.getBbWidth() * 0.4F)); -+ } + int k = Mth.floor(this.getY()); + int l = Mth.floor(this.getZ() + (double)((float)(i / 2 % 2 * 2 - 1) * 0.25F)); + BlockPos blockpos = new BlockPos(j, k, l); +- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { ++ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { + this.level().setBlockAndUpdate(blockpos, blockstate); + this.level().gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this, blockstate)); + } +@@ -127,7 +_,7 @@ + @Override + protected InteractionResult mobInteract(Player p_29920_, InteractionHand p_29921_) { + ItemStack itemstack = p_29920_.getItemInHand(p_29921_); +- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { //Forge: Moved to onSheared + this.shear(SoundSource.PLAYERS); + this.gameEvent(GameEvent.SHEAR, p_29920_); + if (!this.level().isClientSide) { +@@ -189,4 +_,21 @@ + public Vec3 getLeashOffset() { + return new Vec3(0.0, (double)(0.75F * this.getEyeHeight()), (double)(this.getBbWidth() * 0.4F)); + } + -+ @Override -+ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) { -+ return readyForShearing(); -+ } ++ @Override ++ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) { ++ return readyForShearing(); ++ } + -+ @org.jetbrains.annotations.NotNull -+ @Override -+ public java.util.List onSheared(@Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { -+ world.playSound(null, this, SoundEvents.SNOW_GOLEM_SHEAR, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, 1.0F, 1.0F); -+ this.gameEvent(GameEvent.SHEAR, player); -+ if (!world.isClientSide()) { -+ setPumpkin(false); -+ return java.util.Collections.singletonList(new ItemStack(Items.CARVED_PUMPKIN)); -+ } -+ return java.util.Collections.emptyList(); - } ++ @org.jetbrains.annotations.NotNull ++ @Override ++ public java.util.List onSheared(@Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { ++ world.playSound(null, this, SoundEvents.SNOW_GOLEM_SHEAR, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, 1.0F, 1.0F); ++ this.gameEvent(GameEvent.SHEAR, player); ++ if (!world.isClientSide()) { ++ setPumpkin(false); ++ return java.util.Collections.singletonList(new ItemStack(Items.CARVED_PUMPKIN)); ++ } ++ return java.util.Collections.emptyList(); ++ } } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Wolf.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Wolf.java.patch index 242e2bfa40..2fb58ca9c3 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Wolf.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Wolf.java.patch @@ -1,34 +1,11 @@ --- a/net/minecraft/world/entity/animal/Wolf.java +++ b/net/minecraft/world/entity/animal/Wolf.java -@@ -325,11 +_,12 @@ - return flag ? InteractionResult.CONSUME : InteractionResult.PASS; - } else if (this.isTame()) { - if (this.isFood(itemstack) && this.getHealth() < this.getMaxHealth()) { -+ this.heal((float)itemstack.getFoodProperties(this).getNutrition()); - if (!p_30412_.getAbilities().instabuild) { - itemstack.shrink(1); - } +@@ -498,7 +_,7 @@ + } -- this.heal((float)item.getFoodProperties().getNutrition()); -+ this.gameEvent(GameEvent.EAT, this); - return InteractionResult.SUCCESS; - } else { - if (item instanceof DyeItem) { -@@ -365,7 +_,7 @@ - itemstack.shrink(1); - } - -- if (this.random.nextInt(3) == 0) { -+ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_30412_)) { - this.tame(p_30412_); + private void tryToTame(Player p_336244_) { +- if (this.random.nextInt(3) == 0) { ++ if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, p_336244_)) { + this.tame(p_336244_); this.navigation.stop(); - this.setTarget((LivingEntity)null); -@@ -404,7 +_,7 @@ - - public boolean isFood(ItemStack p_30440_) { - Item item = p_30440_.getItem(); -- return item.isEdible() && item.getFoodProperties().isMeat(); -+ return item.isEdible() && p_30440_.getFoodProperties(this).isMeat(); - } - - public int getMaxSpawnClusterSize() { + this.setTarget(null); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch index c429103e16..e94f782958 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch @@ -1,11 +1,14 @@ --- a/net/minecraft/world/entity/animal/allay/Allay.java +++ b/net/minecraft/world/entity/animal/allay/Allay.java -@@ -324,7 +_,7 @@ +@@ -363,10 +_,7 @@ + @Override + public boolean wantsToPickUp(ItemStack p_218387_) { + ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); +- return !itemstack.isEmpty() +- && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) +- && this.inventory.canAddItem(p_218387_) +- && this.allayConsidersItemEqual(itemstack, p_218387_); ++ return !itemstack.isEmpty() && this.inventory.canAddItem(p_218387_) && this.allayConsidersItemEqual(itemstack, p_218387_) && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this); + } - public boolean wantsToPickUp(ItemStack p_218387_) { - ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); -- return !itemstack.isEmpty() && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && this.inventory.canAddItem(p_218387_) && this.allayConsidersItemEqual(itemstack, p_218387_); -+ return !itemstack.isEmpty() && this.inventory.canAddItem(p_218387_) && this.allayConsidersItemEqual(itemstack, p_218387_) && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this); - } - - private boolean allayConsidersItemEqual(ItemStack p_252278_, ItemStack p_250405_) { + private boolean allayConsidersItemEqual(ItemStack p_252278_, ItemStack p_250405_) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/camel/Camel.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/camel/Camel.java.patch index 88ef86ceac..6b5a5b0c43 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/camel/Camel.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/camel/Camel.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/animal/camel/Camel.java +++ b/net/minecraft/world/entity/animal/camel/Camel.java -@@ -302,7 +_,7 @@ - } +@@ -329,7 +_,7 @@ - protected void playStepSound(BlockPos p_252056_, BlockState p_251457_) { -- if (p_251457_.is(BlockTags.CAMEL_SAND_STEP_SOUND_BLOCKS)) { -+ if (p_251457_.getSoundType(level(), p_252056_, this) == net.minecraft.world.level.block.SoundType.SAND) { - this.playSound(SoundEvents.CAMEL_STEP_SAND, 1.0F, 1.0F); - } else { - this.playSound(SoundEvents.CAMEL_STEP, 1.0F, 1.0F); + @Override + protected void playStepSound(BlockPos p_252056_, BlockState p_251457_) { +- if (p_251457_.is(BlockTags.CAMEL_SAND_STEP_SOUND_BLOCKS)) { ++ if (p_251457_.getSoundType(level(), p_252056_, this) == net.minecraft.world.level.block.SoundType.SAND) { + this.playSound(SoundEvents.CAMEL_STEP_SAND, 1.0F, 1.0F); + } else { + this.playSound(SoundEvents.CAMEL_STEP, 1.0F, 1.0F); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/frog/Tadpole.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/frog/Tadpole.java.patch index 58758f8449..65967d8556 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/frog/Tadpole.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/frog/Tadpole.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/world/entity/animal/frog/Tadpole.java +++ b/net/minecraft/world/entity/animal/frog/Tadpole.java -@@ -197,6 +_,7 @@ - private void ageUp() { - Level $$1 = this.level(); - if ($$1 instanceof ServerLevel serverlevel) { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.FROG, timer -> this.ticksToBeFrog = this.age + timer)) return; - Frog frog = EntityType.FROG.create(this.level()); - if (frog != null) { - frog.moveTo(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot()); -@@ -210,6 +_,7 @@ - frog.setPersistenceRequired(); - this.playSound(SoundEvents.TADPOLE_GROW_UP, 0.15F, 1.0F); - serverlevel.addFreshEntityWithPassengers(frog); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, frog); - this.discard(); - } - } +@@ -225,6 +_,7 @@ + + private void ageUp() { + if (this.level() instanceof ServerLevel serverlevel) { ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.FROG, timer -> this.ticksToBeFrog = this.age + timer)) return; + Frog frog = EntityType.FROG.create(this.level()); + if (frog != null) { + frog.moveTo(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot()); +@@ -238,6 +_,7 @@ + frog.setPersistenceRequired(); + this.playSound(SoundEvents.TADPOLE_GROW_UP, 0.15F, 1.0F); + serverlevel.addFreshEntityWithPassengers(frog); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, frog); + this.discard(); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/horse/AbstractHorse.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/horse/AbstractHorse.java.patch index 2777e9c168..1559c61213 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/horse/AbstractHorse.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/horse/AbstractHorse.java.patch @@ -1,68 +1,68 @@ --- a/net/minecraft/world/entity/animal/horse/AbstractHorse.java +++ b/net/minecraft/world/entity/animal/horse/AbstractHorse.java -@@ -283,6 +_,11 @@ - } +@@ -299,6 +_,11 @@ - public boolean causeFallDamage(float p_149499_, float p_149500_, DamageSource p_149501_) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_149499_, p_149500_); -+ if (event.isCanceled()) return false; -+ p_149499_ = event.getDistance(); -+ p_149500_ = event.getDamageMultiplier(); + @Override + public boolean causeFallDamage(float p_149499_, float p_149500_, DamageSource p_149501_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_149499_, p_149500_); ++ if (event.isCanceled()) return false; ++ p_149499_ = event.getDistance(); ++ p_149500_ = event.getDamageMultiplier(); + - if (p_149499_ > 1.0F) { - this.playSound(SoundEvents.HORSE_LAND, 0.4F, 1.0F); - } -@@ -328,6 +_,7 @@ + if (p_149499_ > 1.0F) { + this.playSound(SoundEvents.HORSE_LAND, 0.4F, 1.0F); + } +@@ -340,6 +_,7 @@ - this.inventory.addListener(this); - this.updateContainerEquipment(); -+ this.itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this.inventory)); - } + this.inventory.addListener(this); + this.syncSaddleToClients(); ++ this.itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this.inventory)); + } - protected void updateContainerEquipment() { -@@ -375,9 +_,9 @@ - protected void playStepSound(BlockPos p_30584_, BlockState p_30585_) { - if (!p_30585_.liquid()) { - BlockState blockstate = this.level().getBlockState(p_30584_.above()); -- SoundType soundtype = p_30585_.getSoundType(); -+ SoundType soundtype = p_30585_.getSoundType(level(), p_30584_, this); - if (blockstate.is(Blocks.SNOW)) { -- soundtype = blockstate.getSoundType(); -+ soundtype = blockstate.getSoundType(level(), p_30584_, this); - } + protected void syncSaddleToClients() { +@@ -385,9 +_,9 @@ + protected void playStepSound(BlockPos p_30584_, BlockState p_30585_) { + if (!p_30585_.liquid()) { + BlockState blockstate = this.level().getBlockState(p_30584_.above()); +- SoundType soundtype = p_30585_.getSoundType(); ++ SoundType soundtype = p_30585_.getSoundType(level(), p_30584_, this); + if (blockstate.is(Blocks.SNOW)) { +- soundtype = blockstate.getSoundType(); ++ soundtype = blockstate.getSoundType(level(), p_30584_.above(), this); + } - if (this.isVehicle() && this.canGallop) { -@@ -784,6 +_,7 @@ - this.setDeltaMovement(vec3.x, d1, vec3.z); - this.setIsJumping(true); - this.hasImpulse = true; -+ net.minecraftforge.common.ForgeHooks.onLivingJump(this); - if (p_275435_.z > 0.0D) { - float f = Mth.sin(this.getYRot() * ((float)Math.PI / 180F)); - float f1 = Mth.cos(this.getYRot() * ((float)Math.PI / 180F)); -@@ -1106,6 +_,25 @@ + if (this.isVehicle() && this.canGallop) { +@@ -810,6 +_,7 @@ + float f1 = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)); + this.setDeltaMovement(this.getDeltaMovement().add((double)(-0.4F * f * p_248808_), 0.0, (double)(0.4F * f1 * p_248808_))); + } ++ net.minecraftforge.common.ForgeHooks.onLivingJump(this); + } - this.randomizeAttributes(p_30555_.getRandom()); - return super.finalizeSpawn(p_30555_, p_30556_, p_30557_, p_30558_, p_30559_); -+ } + protected void playJumpSound() { +@@ -1126,5 +_,25 @@ + + public final Container getBodyArmorAccess() { + return this.bodyArmorAccess; ++ } + -+ private net.minecraftforge.common.util.LazyOptional itemHandler = null; ++ private net.minecraftforge.common.util.LazyOptional itemHandler = null; + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null && this.isAlive()) -+ return itemHandler.cast(); -+ return super.getCapability(capability, facing); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null && this.isAlive()) { ++ return itemHandler.cast(); ++ } ++ return super.getCapability(capability, facing); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ if (itemHandler != null) { -+ net.minecraftforge.common.util.LazyOptional oldHandler = itemHandler; -+ itemHandler = null; -+ oldHandler.invalidate(); -+ } - } - - public boolean hasInventoryChanged(Container p_149512_) { ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ if (itemHandler != null) { ++ var oldHandler = itemHandler; ++ itemHandler = null; ++ oldHandler.invalidate(); ++ } + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/horse/Horse.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/horse/Horse.java.patch deleted file mode 100644 index 606b6ef619..0000000000 --- a/patches/minecraft/net/minecraft/world/entity/animal/horse/Horse.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/entity/animal/horse/Horse.java -+++ b/net/minecraft/world/entity/animal/horse/Horse.java -@@ -144,6 +_,8 @@ - this.playSound(SoundEvents.HORSE_BREATHE, p_30709_.getVolume() * 0.6F, p_30709_.getPitch()); - } - -+ ItemStack stack = this.inventory.getItem(1); -+ if (isArmor(stack)) stack.onHorseArmorTick(level(), this); - } - - protected SoundEvent getAmbientSound() { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/horse/Llama.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/horse/Llama.java.patch index 1b0c1a6a66..b8158c1355 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/horse/Llama.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/horse/Llama.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/entity/animal/horse/Llama.java +++ b/net/minecraft/world/entity/animal/horse/Llama.java -@@ -366,6 +_,10 @@ - } +@@ -376,6 +_,10 @@ - public boolean causeFallDamage(float p_149538_, float p_149539_, DamageSource p_149540_) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_149538_, p_149539_); -+ if (event.isCanceled()) return false; -+ p_149538_ = event.getDistance(); -+ p_149539_ = event.getDamageMultiplier(); - int i = this.calculateFallDamage(p_149538_, p_149539_); - if (i <= 0) { - return false; + @Override + public boolean causeFallDamage(float p_149538_, float p_149539_, DamageSource p_149540_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, p_149538_, p_149539_); ++ if (event.isCanceled()) return false; ++ p_149538_ = event.getDistance(); ++ p_149539_ = event.getDamageMultiplier(); + int i = this.calculateFallDamage(p_149538_, p_149539_); + if (i <= 0) { + return false; diff --git a/patches/minecraft/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java.patch index e92585e302..5f25f31d7d 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java.patch @@ -1,21 +1,63 @@ --- a/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java +++ b/net/minecraft/world/entity/animal/horse/SkeletonTrapGoal.java -@@ -28,6 +_,10 @@ +@@ -31,33 +_,38 @@ + @Override + public void tick() { + ServerLevel serverlevel = (ServerLevel)this.horse.level(); +- DifficultyInstance difficultyinstance = serverlevel.getCurrentDifficultyAt(this.horse.blockPosition()); +- this.horse.setTrap(false); +- this.horse.setTamed(true); +- this.horse.setAge(0); +- LightningBolt lightningbolt = EntityType.LIGHTNING_BOLT.create(serverlevel); +- if (lightningbolt != null) { +- lightningbolt.moveTo(this.horse.getX(), this.horse.getY(), this.horse.getZ()); +- lightningbolt.setVisualOnly(true); +- serverlevel.addFreshEntity(lightningbolt); +- Skeleton skeleton = this.createSkeleton(difficultyinstance, this.horse); +- if (skeleton != null) { +- skeleton.startRiding(this.horse); +- serverlevel.addFreshEntityWithPassengers(skeleton); ++ // Forge: Trigger the trap in a tick task to avoid crashes when mods add goals to skeleton horses ++ // (MC-206338/Forge PR #7509) ++ serverlevel.getServer().tell(new net.minecraft.server.TickTask(serverlevel.getServer().getTickCount(), () -> { ++ if (!this.horse.isAlive()) return; ++ DifficultyInstance difficultyinstance = serverlevel.getCurrentDifficultyAt(this.horse.blockPosition()); ++ this.horse.setTrap(false); ++ this.horse.setTamed(true); ++ this.horse.setAge(0); ++ LightningBolt lightningbolt = EntityType.LIGHTNING_BOLT.create(serverlevel); ++ if (lightningbolt != null) { ++ lightningbolt.moveTo(this.horse.getX(), this.horse.getY(), this.horse.getZ()); ++ lightningbolt.setVisualOnly(true); ++ serverlevel.addFreshEntity(lightningbolt); ++ Skeleton skeleton = this.createSkeleton(difficultyinstance, this.horse); ++ if (skeleton != null) { ++ skeleton.startRiding(this.horse); ++ serverlevel.addFreshEntityWithPassengers(skeleton); - public void tick() { - ServerLevel serverlevel = (ServerLevel)this.horse.level(); -+ // Forge: Trigger the trap in a tick task to avoid crashes when mods add goals to skeleton horses -+ // (MC-206338/Forge PR #7509) -+ serverlevel.getServer().tell(new net.minecraft.server.TickTask(serverlevel.getServer().getTickCount(), () -> { -+ if (!this.horse.isAlive()) return; - DifficultyInstance difficultyinstance = serverlevel.getCurrentDifficultyAt(this.horse.blockPosition()); - this.horse.setTrap(false); - this.horse.setTamed(true); -@@ -56,6 +_,7 @@ +- for (int i = 0; i < 3; i++) { +- AbstractHorse abstracthorse = this.createHorse(difficultyinstance); +- if (abstracthorse != null) { +- Skeleton skeleton1 = this.createSkeleton(difficultyinstance, abstracthorse); +- if (skeleton1 != null) { +- skeleton1.startRiding(abstracthorse); +- abstracthorse.push(this.horse.getRandom().triangle(0.0, 1.1485), 0.0, this.horse.getRandom().triangle(0.0, 1.1485)); +- serverlevel.addFreshEntityWithPassengers(abstracthorse); ++ for (int i = 0; i < 3; i++) { ++ AbstractHorse abstracthorse = this.createHorse(difficultyinstance); ++ if (abstracthorse != null) { ++ Skeleton skeleton1 = this.createSkeleton(difficultyinstance, abstracthorse); ++ if (skeleton1 != null) { ++ skeleton1.startRiding(abstracthorse); ++ abstracthorse.push(this.horse.getRandom().triangle(0.0, 1.1485), 0.0, this.horse.getRandom().triangle(0.0, 1.1485)); ++ serverlevel.addFreshEntityWithPassengers(abstracthorse); ++ } + } + } + } + } +- } ++ })); + } - } - } -+ })); - } - - @Nullable + @Nullable diff --git a/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch index abcd572d7d..66702d0c90 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch @@ -1,11 +1,12 @@ --- a/net/minecraft/world/entity/animal/sniffer/Sniffer.java +++ b/net/minecraft/world/entity/animal/sniffer/Sniffer.java -@@ -275,7 +_,7 @@ - } +@@ -300,8 +_,7 @@ + } - if (this.tickCount % 10 == 0) { -- this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), blockstate.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false); -+ this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), blockstate.getSoundType(level(), blockpos.below(), this).getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false); + if (this.tickCount % 10 == 0) { +- this.level() +- .playLocalSound(this.getX(), this.getY(), this.getZ(), blockstate.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false); ++ this.level().playLocalSound(this.getX(), this.getY(), this.getZ(), blockstate.getSoundType(level(), blockpos.below(), this).getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false); + } } - } - } + } diff --git a/patches/minecraft/net/minecraft/world/entity/boss/EnderDragonPart.java.patch b/patches/minecraft/net/minecraft/world/entity/boss/EnderDragonPart.java.patch index dfa7fee38b..1aa2e0a005 100644 --- a/patches/minecraft/net/minecraft/world/entity/boss/EnderDragonPart.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/boss/EnderDragonPart.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/world/entity/boss/EnderDragonPart.java +++ b/net/minecraft/world/entity/boss/EnderDragonPart.java -@@ -11,13 +_,13 @@ +@@ -12,13 +_,13 @@ import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.item.ItemStack; -public class EnderDragonPart extends Entity { +public class EnderDragonPart extends net.minecraftforge.entity.PartEntity { - public final EnderDragon parentMob; - public final String name; - private final EntityDimensions size; + public final EnderDragon parentMob; + public final String name; + private final EntityDimensions size; - public EnderDragonPart(EnderDragon p_31014_, String p_31015_, float p_31016_, float p_31017_) { -- super(p_31014_.getType(), p_31014_.level()); -+ super(p_31014_); - this.size = EntityDimensions.scalable(p_31016_, p_31017_); - this.refreshDimensions(); - this.parentMob = p_31014_; + public EnderDragonPart(EnderDragon p_31014_, String p_31015_, float p_31016_, float p_31017_) { +- super(p_31014_.getType(), p_31014_.level()); ++ super(p_31014_); + this.size = EntityDimensions.scalable(p_31016_, p_31017_); + this.refreshDimensions(); + this.parentMob = p_31014_; diff --git a/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch b/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch index c0d0068d6f..7d7a49ca9a 100644 --- a/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch @@ -1,78 +1,91 @@ --- a/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java +++ b/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java -@@ -104,6 +_,14 @@ - this.noPhysics = true; - this.noCulling = true; - this.phaseManager = new EnderDragonPhaseManager(this); -+ this.setId(ENTITY_COUNTER.getAndAdd(this.subEntities.length + 1) + 1); // Forge: Fix MC-158205: Make sure part ids are successors of parent mob id -+ } +@@ -104,6 +_,15 @@ + this.noPhysics = true; + this.noCulling = true; + this.phaseManager = new EnderDragonPhaseManager(this); ++ this.setId(ENTITY_COUNTER.getAndAdd(this.subEntities.length + 1) + 1); // Forge: Fix MC-158205: Make sure part ids are successors of parent mob id ++ } + -+ @Override -+ public void setId(int p_20235_) { -+ super.setId(p_20235_); -+ for (int i = 0; i < this.subEntities.length; i++) // Forge: Fix MC-158205: Set part ids to successors of parent mob id -+ this.subEntities[i].setId(p_20235_ + i + 1); - } ++ @Override ++ public void setId(int p_20235_) { ++ super.setId(p_20235_); ++ for (int i = 0; i < this.subEntities.length; i++) { // Forge: Fix MC-158205: Set part ids to successors of parent mob id ++ this.subEntities[i].setId(p_20235_ + i + 1); ++ } + } - public void setDragonFight(EndDragonFight p_287736_) { -@@ -159,7 +_,11 @@ - return adouble; - } + public void setDragonFight(EndDragonFight p_287736_) { +@@ -171,8 +_,19 @@ + return adouble; + } -+ @org.jetbrains.annotations.Nullable private Player unlimitedLastHurtByPlayer = null; - public void aiStep() { -+ // lastHurtByPlayer is cleared after 100 ticks, capture it indefinitely in unlimitedLastHurtByPlayer for LivingExperienceDropEvent -+ if (this.lastHurtByPlayer != null) this.unlimitedLastHurtByPlayer = lastHurtByPlayer; -+ if (this.unlimitedLastHurtByPlayer != null && this.unlimitedLastHurtByPlayer.isRemoved()) this.unlimitedLastHurtByPlayer = null; - this.processFlappingMovement(); - if (this.level().isClientSide) { - this.setHealth(this.getHealth()); -@@ -433,7 +_,7 @@ - BlockPos blockpos = new BlockPos(k1, l1, i2); - BlockState blockstate = this.level().getBlockState(blockpos); - if (!blockstate.isAir() && !blockstate.is(BlockTags.DRAGON_TRANSPARENT)) { -- if (this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { -+ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(this.level(), blockpos, this) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { - flag1 = this.level().removeBlock(blockpos, false) || flag1; - } else { - flag = true; -@@ -524,7 +_,8 @@ - - if (this.level() instanceof ServerLevel) { - if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && flag) { -- ExperienceOrb.award((ServerLevel)this.level(), this.position(), Mth.floor((float)i * 0.08F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.unlimitedLastHurtByPlayer, Mth.floor((float)i * 0.08F)); -+ ExperienceOrb.award((ServerLevel) this.level(), this.position(), award); - } - - if (this.dragonDeathTime == 1 && !this.isSilent()) { -@@ -535,7 +_,8 @@ - this.move(MoverType.SELF, new Vec3(0.0D, (double)0.1F, 0.0D)); - if (this.dragonDeathTime == 200 && this.level() instanceof ServerLevel) { - if (flag) { -- ExperienceOrb.award((ServerLevel)this.level(), this.position(), Mth.floor((float)i * 0.2F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.unlimitedLastHurtByPlayer, Mth.floor((float)i * 0.2F)); -+ ExperienceOrb.award((ServerLevel) this.level(), this.position(), award); - } - - if (this.dragonFight != null) { -@@ -858,8 +_,19 @@ - return false; - } - -+ @Override -+ public boolean isMultipartEntity() { -+ return true; -+ } ++ @org.jetbrains.annotations.Nullable private Player unlimitedLastHurtByPlayer = null; + -+ @Override -+ public net.minecraftforge.entity.PartEntity[] getParts() { -+ return this.subEntities; -+ } + @Override + public void aiStep() { ++ // lastHurtByPlayer is cleared after 100 ticks, capture it indefinitely in unlimitedLastHurtByPlayer for LivingExperienceDropEvent ++ if (this.lastHurtByPlayer != null) { ++ this.unlimitedLastHurtByPlayer = lastHurtByPlayer; ++ } + - public void recreateFromPacket(ClientboundAddEntityPacket p_218825_) { - super.recreateFromPacket(p_218825_); -+ if (true) return; // Forge: Fix MC-158205: Moved into setId() - EnderDragonPart[] aenderdragonpart = this.getSubEntities(); ++ if (this.unlimitedLastHurtByPlayer != null && this.unlimitedLastHurtByPlayer.isRemoved()) { ++ this.unlimitedLastHurtByPlayer = null; ++ } ++ + this.processFlappingMovement(); + if (this.level().isClientSide) { + this.setHealth(this.getHealth()); +@@ -467,7 +_,7 @@ + BlockPos blockpos = new BlockPos(k1, l1, i2); + BlockState blockstate = this.level().getBlockState(blockpos); + if (!blockstate.isAir() && !blockstate.is(BlockTags.DRAGON_TRANSPARENT)) { +- if (this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { ++ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(this.level(), blockpos, this) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { + flag1 = this.level().removeBlock(blockpos, false) || flag1; + } else { + flag = true; +@@ -563,7 +_,8 @@ - for(int i = 0; i < aenderdragonpart.length; ++i) { + if (this.level() instanceof ServerLevel) { + if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && flag) { +- ExperienceOrb.award((ServerLevel)this.level(), this.position(), Mth.floor((float)i * 0.08F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.unlimitedLastHurtByPlayer, Mth.floor((float)i * 0.08F)); ++ ExperienceOrb.award((ServerLevel) this.level(), this.position(), award); + } + + if (this.dragonDeathTime == 1 && !this.isSilent()) { +@@ -574,7 +_,8 @@ + this.move(MoverType.SELF, new Vec3(0.0, 0.1F, 0.0)); + if (this.dragonDeathTime == 200 && this.level() instanceof ServerLevel) { + if (flag) { +- ExperienceOrb.award((ServerLevel)this.level(), this.position(), Mth.floor((float)i * 0.2F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.unlimitedLastHurtByPlayer, Mth.floor((float)i * 0.2F)); ++ ExperienceOrb.award((ServerLevel) this.level(), this.position(), award); + } + + if (this.dragonFight != null) { +@@ -908,6 +_,7 @@ + @Override + public void recreateFromPacket(ClientboundAddEntityPacket p_218825_) { + super.recreateFromPacket(p_218825_); ++ if (true) return; // Forge: Fix MC-158205: Moved into setId() + EnderDragonPart[] aenderdragonpart = this.getSubEntities(); + + for (int i = 0; i < aenderdragonpart.length; i++) { +@@ -923,5 +_,15 @@ + @Override + protected float sanitizeScale(float p_333905_) { + return 1.0F; ++ } ++ ++ @Override ++ public boolean isMultipartEntity() { ++ return true; ++ } ++ ++ @Override ++ public net.minecraftforge.entity.PartEntity[] getParts() { ++ return this.subEntities; + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch b/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch index 7dee16b661..e66087cbcb 100644 --- a/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/world/entity/boss/wither/WitherBoss.java +++ b/net/minecraft/world/entity/boss/wither/WitherBoss.java -@@ -279,7 +_,7 @@ +@@ -315,7 +_,7 @@ - if (this.destroyBlocksTick > 0) { - --this.destroyBlocksTick; -- if (this.destroyBlocksTick == 0 && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (this.destroyBlocksTick == 0 && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { - int j1 = Mth.floor(this.getY()); - int i2 = Mth.floor(this.getX()); - int j2 = Mth.floor(this.getZ()); -@@ -293,7 +_,7 @@ - int i1 = j2 + k2; - BlockPos blockpos = new BlockPos(l2, l, i1); + if (this.destroyBlocksTick > 0) { + this.destroyBlocksTick--; +- if (this.destroyBlocksTick == 0 && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (this.destroyBlocksTick == 0 && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { + boolean flag = false; + int l = Mth.floor(this.getBbWidth() / 2.0F + 1.0F); + int i1 = Mth.floor(this.getBbHeight()); +@@ -324,7 +_,7 @@ + this.getBlockX() - l, this.getBlockY(), this.getBlockZ() - l, this.getBlockX() + l, this.getBlockY() + i1, this.getBlockZ() + l + )) { BlockState blockstate = this.level().getBlockState(blockpos); - if (canDestroy(blockstate)) { + if (blockstate.canEntityDestroy(this.level(), blockpos, this) && net.minecraftforge.event.ForgeEventFactory.onEntityDestroyBlock(this, blockpos, blockstate)) { - flag = this.level().destroyBlock(blockpos, true, this) || flag; + flag = this.level().destroyBlock(blockpos, true, this) || flag; } - } -@@ -314,6 +_,10 @@ - } - } + } +@@ -343,6 +_,10 @@ + } + } -+ /** -+ * @deprecated Forge: Use {@link BlockState#canEntityDestroy(net.minecraft.world.level.BlockGetter, BlockPos, Entity)} instead. -+ */ -+ @Deprecated - public static boolean canDestroy(BlockState p_31492_) { - return !p_31492_.isAir() && !p_31492_.is(BlockTags.WITHER_IMMUNE); - } ++ /** ++ * @deprecated Forge: Use {@link BlockState#canEntityDestroy(net.minecraft.world.level.BlockGetter, BlockPos, Entity)} instead. ++ */ ++ @Deprecated + public static boolean canDestroy(BlockState p_31492_) { + return !p_31492_.isAir() && !p_31492_.is(BlockTags.WITHER_IMMUNE); + } diff --git a/patches/minecraft/net/minecraft/world/entity/decoration/ArmorStand.java.patch b/patches/minecraft/net/minecraft/world/entity/decoration/ArmorStand.java.patch index 43a3ecd2dc..b700757972 100644 --- a/patches/minecraft/net/minecraft/world/entity/decoration/ArmorStand.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/decoration/ArmorStand.java.patch @@ -1,11 +1,12 @@ --- a/net/minecraft/world/entity/decoration/ArmorStand.java +++ b/net/minecraft/world/entity/decoration/ArmorStand.java -@@ -71,7 +_,7 @@ - public static final EntityDataAccessor DATA_LEFT_LEG_POSE = SynchedEntityData.defineId(ArmorStand.class, EntityDataSerializers.ROTATIONS); - public static final EntityDataAccessor DATA_RIGHT_LEG_POSE = SynchedEntityData.defineId(ArmorStand.class, EntityDataSerializers.ROTATIONS); - private static final Predicate RIDABLE_MINECARTS = (p_31582_) -> { -- return p_31582_ instanceof AbstractMinecart && ((AbstractMinecart)p_31582_).getMinecartType() == AbstractMinecart.Type.RIDEABLE; -+ return p_31582_ instanceof AbstractMinecart && ((AbstractMinecart)p_31582_).canBeRidden(); - }; - private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); - private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); +@@ -73,8 +_,7 @@ + public static final EntityDataAccessor DATA_RIGHT_ARM_POSE = SynchedEntityData.defineId(ArmorStand.class, EntityDataSerializers.ROTATIONS); + public static final EntityDataAccessor DATA_LEFT_LEG_POSE = SynchedEntityData.defineId(ArmorStand.class, EntityDataSerializers.ROTATIONS); + public static final EntityDataAccessor DATA_RIGHT_LEG_POSE = SynchedEntityData.defineId(ArmorStand.class, EntityDataSerializers.ROTATIONS); +- private static final Predicate RIDABLE_MINECARTS = p_31582_ -> p_31582_ instanceof AbstractMinecart +- && ((AbstractMinecart)p_31582_).getMinecartType() == AbstractMinecart.Type.RIDEABLE; ++ private static final Predicate RIDABLE_MINECARTS = p_31582_ -> p_31582_ instanceof AbstractMinecart abstractMinecart && abstractMinecart.canBeRidden(); + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private boolean invisible; diff --git a/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch index 78695be9a7..76faef3e12 100644 --- a/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/decoration/HangingEntity.java +++ b/net/minecraft/world/entity/decoration/HangingEntity.java @@ -121,6 +_,8 @@ - int j1 = (j - 1) / -2; - blockpos$mutableblockpos.set(blockpos).move(direction, k + i1).move(Direction.UP, l + j1); - BlockState blockstate = this.level().getBlockState(blockpos$mutableblockpos); -+ if (net.minecraft.world.level.block.Block.canSupportCenter(this.level(), blockpos$mutableblockpos, this.direction)) -+ continue; - if (!blockstate.isSolid() && !DiodeBlock.isDiode(blockstate)) { - return false; - } + int j1 = (j - 1) / -2; + blockpos$mutableblockpos.set(blockpos).move(direction, k + i1).move(Direction.UP, l + j1); + BlockState blockstate = this.level().getBlockState(blockpos$mutableblockpos); ++ if (net.minecraft.world.level.block.Block.canSupportCenter(this.level(), blockpos$mutableblockpos, this.direction)) ++ continue; + if (!blockstate.isSolid() && !DiodeBlock.isDiode(blockstate)) { + return false; + } diff --git a/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch index a5645f111c..1fb78fd175 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch @@ -1,16 +1,20 @@ --- a/net/minecraft/world/entity/item/FallingBlockEntity.java +++ b/net/minecraft/world/entity/item/FallingBlockEntity.java -@@ -120,11 +_,11 @@ - if (!this.level().isClientSide) { - BlockPos blockpos = this.blockPosition(); - boolean flag = this.blockState.getBlock() instanceof ConcretePowderBlock; -- boolean flag1 = flag && this.level().getFluidState(blockpos).is(FluidTags.WATER); -+ boolean flag1 = flag && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockpos), blockpos); - double d0 = this.getDeltaMovement().lengthSqr(); - if (flag && d0 > 1.0D) { - BlockHitResult blockhitresult = this.level().clip(new ClipContext(new Vec3(this.xo, this.yo, this.zo), this.position(), ClipContext.Block.COLLIDER, ClipContext.Fluid.SOURCE_ONLY, this)); -- if (blockhitresult.getType() != HitResult.Type.MISS && this.level().getFluidState(blockhitresult.getBlockPos()).is(FluidTags.WATER)) { -+ if (blockhitresult.getType() != HitResult.Type.MISS && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockhitresult.getBlockPos()), blockhitresult.getBlockPos())) { - blockpos = blockhitresult.getBlockPos(); - flag1 = true; - } +@@ -133,7 +_,7 @@ + if (!this.level().isClientSide) { + BlockPos blockpos = this.blockPosition(); + boolean flag = this.blockState.getBlock() instanceof ConcretePowderBlock; +- boolean flag1 = flag && this.level().getFluidState(blockpos).is(FluidTags.WATER); ++ boolean flag1 = flag && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockpos), blockpos); + double d0 = this.getDeltaMovement().lengthSqr(); + if (flag && d0 > 1.0) { + BlockHitResult blockhitresult = this.level() +@@ -146,7 +_,7 @@ + this + ) + ); +- if (blockhitresult.getType() != HitResult.Type.MISS && this.level().getFluidState(blockhitresult.getBlockPos()).is(FluidTags.WATER)) { ++ if (blockhitresult.getType() != HitResult.Type.MISS && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockhitresult.getBlockPos()), blockhitresult.getBlockPos())) { + blockpos = blockhitresult.getBlockPos(); + flag1 = true; + } diff --git a/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch index 1bcca3241c..6e708120e3 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch @@ -1,150 +1,143 @@ --- a/net/minecraft/world/entity/item/ItemEntity.java +++ b/net/minecraft/world/entity/item/ItemEntity.java -@@ -44,6 +_,10 @@ - @Nullable - private UUID target; - public final float bobOffs; -+ /** -+ * The maximum age of this EntityItem. The item is expired once this is reached. -+ */ -+ public int lifespan = ItemEntity.LIFETIME; +@@ -48,6 +_,10 @@ + @Nullable + private UUID target; + public final float bobOffs; ++ /** ++ * The maximum age of this EntityItem. The item is expired once this is reached. ++ */ ++ public int lifespan = ItemEntity.LIFETIME; - public ItemEntity(EntityType p_31991_, Level p_31992_) { - super(p_31991_, p_31992_); -@@ -60,6 +_,7 @@ - this.setPos(p_149664_, p_149665_, p_149666_); - this.setDeltaMovement(p_149668_, p_149669_, p_149670_); - this.setItem(p_149667_); -+ this.lifespan = (p_149667_.getItem() == null ? ItemEntity.LIFETIME : p_149667_.getEntityLifespan(p_149663_)); - } + public ItemEntity(EntityType p_31991_, Level p_31992_) { + super(p_31991_, p_31992_); +@@ -66,6 +_,7 @@ + this.setPos(p_149664_, p_149665_, p_149666_); + this.setDeltaMovement(p_149668_, p_149669_, p_149670_); + this.setItem(p_149667_); ++ this.lifespan = (p_149667_.getItem() == null ? ItemEntity.LIFETIME : p_149667_.getEntityLifespan(p_149663_)); + } - private ItemEntity(ItemEntity p_31994_) { -@@ -68,6 +_,7 @@ - this.copyPosition(p_31994_); - this.age = p_31994_.age; - this.bobOffs = p_31994_.bobOffs; -+ this.lifespan = p_31994_.lifespan; - } + private ItemEntity(ItemEntity p_31994_) { +@@ -74,6 +_,7 @@ + this.copyPosition(p_31994_); + this.age = p_31994_.age; + this.bobOffs = p_31994_.bobOffs; ++ this.lifespan = p_31994_.lifespan; + } - public boolean dampensVibrations() { -@@ -109,6 +_,7 @@ - } + @Override +@@ -119,6 +_,7 @@ - public void tick() { -+ if (getItem().onEntityItemUpdate(this)) return; - if (this.getItem().isEmpty()) { - this.discard(); - } else { -@@ -122,6 +_,9 @@ - this.zo = this.getZ(); - Vec3 vec3 = this.getDeltaMovement(); - float f = this.getEyeHeight() - 0.11111111F; -+ net.minecraftforge.fluids.FluidType fluidType = this.getMaxHeightFluidType(); -+ if (!fluidType.isAir() && !fluidType.isVanilla() && this.getFluidTypeHeight(fluidType) > (double)f) fluidType.setItemMovement(this); -+ else - if (this.isInWater() && this.getFluidHeight(FluidTags.WATER) > (double)f) { - this.setUnderwaterMovement(); - } else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > (double)f) { -@@ -143,7 +_,8 @@ - this.move(MoverType.SELF, this.getDeltaMovement()); - float f1 = 0.98F; - if (this.onGround()) { -- f1 = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; -+ BlockPos groundPos = getBlockPosBelowThatAffectsMyMovement(); -+ f1 = this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; + @Override + public void tick() { ++ if (getItem().onEntityItemUpdate(this)) return; + if (this.getItem().isEmpty()) { + this.discard(); + } else { +@@ -131,6 +_,10 @@ + this.yo = this.getY(); + this.zo = this.getZ(); + Vec3 vec3 = this.getDeltaMovement(); ++ var fluidType = this.getMaxHeightFluidType(); ++ if (!fluidType.isAir() && !fluidType.isVanilla() && this.getFluidTypeHeight(fluidType) > 0.1F) { ++ fluidType.setItemMovement(this); ++ } else + if (this.isInWater() && this.getFluidHeight(FluidTags.WATER) > 0.1F) { + this.setUnderwaterMovement(); + } else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > 0.1F) { +@@ -152,7 +_,8 @@ + this.move(MoverType.SELF, this.getDeltaMovement()); + float f = 0.98F; + if (this.onGround()) { +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; ++ BlockPos groundPos = getBlockPosBelowThatAffectsMyMovement(); ++ f = this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; + } + + this.setDeltaMovement(this.getDeltaMovement().multiply((double)f, 0.98, (double)f)); +@@ -184,7 +_,16 @@ + } } - this.setDeltaMovement(this.getDeltaMovement().multiply((double)f1, 0.98D, (double)f1)); -@@ -173,7 +_,16 @@ +- if (!this.level().isClientSide && this.age >= 6000) { ++ ItemStack item = this.getItem(); ++ if (!this.level().isClientSide && this.age >= lifespan) { ++ int hook = net.minecraftforge.event.ForgeEventFactory.onItemExpire(this, item); ++ if (hook < 0) { ++ this.discard(); ++ } else { ++ this.lifespan += hook; ++ } ++ } ++ if (item.isEmpty() && !this.isRemoved()) { + this.discard(); + } + } +@@ -281,7 +_,7 @@ + this.health = (int)((float)this.health - p_32014_); + this.gameEvent(GameEvent.ENTITY_DAMAGE, p_32013_.getEntity()); + if (this.health <= 0) { +- this.getItem().onDestroyed(this); ++ this.getItem().onDestroyed(this, p_32013_); + this.discard(); } - } -- if (!this.level().isClientSide && this.age >= 6000) { -+ ItemStack item = this.getItem(); -+ if (!this.level().isClientSide && this.age >= lifespan) { -+ int hook = net.minecraftforge.event.ForgeEventFactory.onItemExpire(this, item); -+ if (hook < 0) { -+ this.discard(); -+ } else { -+ this.lifespan += hook; -+ } -+ } -+ if (item.isEmpty() && !this.isRemoved()) { - this.discard(); - } +@@ -294,6 +_,7 @@ + p_32050_.putShort("Health", (short)this.health); + p_32050_.putShort("Age", (short)this.age); + p_32050_.putShort("PickupDelay", (short)this.pickupDelay); ++ p_32050_.putInt("Lifespan", this.lifespan); + if (this.thrower != null) { + p_32050_.putUUID("Thrower", this.thrower); + } +@@ -315,6 +_,10 @@ + this.pickupDelay = p_32034_.getShort("PickupDelay"); + } -@@ -235,6 +_,8 @@ - return false; - } else if (p_32028_.hasTag() ^ p_32027_.hasTag()) { - return false; -+ } else if (!p_32027_.areCapsCompatible(p_32028_)) { -+ return false; - } else { - return !p_32028_.hasTag() || p_32028_.getTag().equals(p_32027_.getTag()); - } -@@ -280,7 +_,7 @@ - this.health = (int)((float)this.health - p_32014_); - this.gameEvent(GameEvent.ENTITY_DAMAGE, p_32013_.getEntity()); - if (this.health <= 0) { -- this.getItem().onDestroyed(this); -+ this.getItem().onDestroyed(this, p_32013_); - this.discard(); - } ++ if (p_32034_.contains("Lifespan")) { ++ this.lifespan = p_32034_.getInt("Lifespan"); ++ } ++ + if (p_32034_.hasUUID("Owner")) { + this.target = p_32034_.getUUID("Owner"); + } +@@ -339,10 +_,17 @@ + @Override + public void playerTouch(Player p_32040_) { + if (!this.level().isClientSide) { ++ if (this.pickupDelay > 0) return; + ItemStack itemstack = this.getItem(); + Item item = itemstack.getItem(); + int i = itemstack.getCount(); +- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(p_32040_.getUUID())) && p_32040_.getInventory().add(itemstack)) { ++ int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(this, p_32040_); ++ if (hook < 0) return; ++ ItemStack copy = itemstack.copy(); ++ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(p_32040_.getUUID())) && (hook == 1 || i <= 0 || p_32040_.getInventory().add(itemstack))) { ++ i = copy.getCount() - itemstack.getCount(); ++ copy.setCount(i); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerItemPickupEvent(p_32040_, this, copy); + p_32040_.take(this, i); + if (itemstack.isEmpty()) { + this.discard(); +@@ -368,8 +_,8 @@ -@@ -292,6 +_,7 @@ - p_32050_.putShort("Health", (short)this.health); - p_32050_.putShort("Age", (short)this.age); - p_32050_.putShort("PickupDelay", (short)this.pickupDelay); -+ p_32050_.putInt("Lifespan", this.lifespan); - if (this.thrower != null) { - p_32050_.putUUID("Thrower", this.thrower); - } -@@ -312,6 +_,9 @@ - if (p_32034_.contains("PickupDelay")) { - this.pickupDelay = p_32034_.getShort("PickupDelay"); - } -+ if (p_32034_.contains("Lifespan")) { -+ this.lifespan = p_32034_.getInt("Lifespan"); -+ } + @Nullable + @Override +- public Entity changeDimension(ServerLevel p_32042_) { +- Entity entity = super.changeDimension(p_32042_); ++ public Entity changeDimension(ServerLevel p_32042_, net.minecraftforge.common.util.ITeleporter teleporter) { ++ Entity entity = super.changeDimension(p_32042_, teleporter); + if (!this.level().isClientSide && entity instanceof ItemEntity) { + ((ItemEntity)entity).mergeWithNeighbours(); + } +@@ -436,7 +_,7 @@ - if (p_32034_.hasUUID("Owner")) { - this.target = p_32034_.getUUID("Owner"); -@@ -332,10 +_,17 @@ + public void makeFakeItem() { + this.setNeverPickUp(); +- this.age = 5999; ++ this.age = getItem().getEntityLifespan(this.level()) - 1; + } - public void playerTouch(Player p_32040_) { - if (!this.level().isClientSide) { -+ if (this.pickupDelay > 0) return; - ItemStack itemstack = this.getItem(); - Item item = itemstack.getItem(); - int i = itemstack.getCount(); -- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(p_32040_.getUUID())) && p_32040_.getInventory().add(itemstack)) { -+ int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(this, p_32040_); -+ if (hook < 0) return; -+ ItemStack copy = itemstack.copy(); -+ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(p_32040_.getUUID())) && (hook == 1 || i <= 0 || p_32040_.getInventory().add(itemstack))) { -+ i = copy.getCount() - itemstack.getCount(); -+ copy.setCount(i); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerItemPickupEvent(p_32040_, this, copy); - p_32040_.take(this, i); - if (itemstack.isEmpty()) { - this.discard(); -@@ -359,8 +_,8 @@ - } - - @Nullable -- public Entity changeDimension(ServerLevel p_32042_) { -- Entity entity = super.changeDimension(p_32042_); -+ public Entity changeDimension(ServerLevel p_32042_, net.minecraftforge.common.util.ITeleporter teleporter) { -+ Entity entity = super.changeDimension(p_32042_, teleporter); - if (!this.level().isClientSide && entity instanceof ItemEntity) { - ((ItemEntity)entity).mergeWithNeighbours(); - } -@@ -427,7 +_,7 @@ - - public void makeFakeItem() { - this.setNeverPickUp(); -- this.age = 5999; -+ this.age = getItem().getEntityLifespan(this.level()) - 1; - } - - public float getSpin(float p_32009_) { + public float getSpin(float p_32009_) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/AbstractSkeleton.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/AbstractSkeleton.java.patch index a4b4313700..408ffe8881 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/AbstractSkeleton.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/AbstractSkeleton.java.patch @@ -1,23 +1,24 @@ --- a/net/minecraft/world/entity/monster/AbstractSkeleton.java +++ b/net/minecraft/world/entity/monster/AbstractSkeleton.java @@ -155,7 +_,7 @@ - if (this.level() != null && !this.level().isClientSide) { - this.goalSelector.removeGoal(this.meleeGoal); - this.goalSelector.removeGoal(this.bowGoal); -- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - if (itemstack.is(Items.BOW)) { - int i = 20; - if (this.level().getDifficulty() != Difficulty.HARD) { -@@ -172,8 +_,10 @@ - } + if (this.level() != null && !this.level().isClientSide) { + this.goalSelector.removeGoal(this.meleeGoal); + this.goalSelector.removeGoal(this.bowGoal); +- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + if (itemstack.is(Items.BOW)) { + int i = this.getHardAttackInterval(); + if (this.level().getDifficulty() != Difficulty.HARD) { +@@ -180,8 +_,11 @@ - public void performRangedAttack(LivingEntity p_32141_, float p_32142_) { -- ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW))); -+ ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem))); - AbstractArrow abstractarrow = this.getArrow(itemstack, p_32142_); -+ if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem) -+ abstractarrow = ((net.minecraft.world.item.BowItem)this.getMainHandItem().getItem()).customArrow(abstractarrow); - double d0 = p_32141_.getX() - this.getX(); - double d1 = p_32141_.getY(0.3333333333333333D) - abstractarrow.getY(); - double d2 = p_32141_.getZ() - this.getZ(); + @Override + public void performRangedAttack(LivingEntity p_32141_, float p_32142_) { +- ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW))); ++ ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem))); + AbstractArrow abstractarrow = this.getArrow(itemstack, p_32142_); ++ if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { ++ abstractarrow = bow.customArrow(abstractarrow); ++ } + double d0 = p_32141_.getX() - this.getX(); + double d1 = p_32141_.getY(0.3333333333333333) - abstractarrow.getY(); + double d2 = p_32141_.getZ() - this.getZ(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch index 0b37f63821..8de742d7ee 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch @@ -1,14 +1,15 @@ --- a/net/minecraft/world/entity/monster/CrossbowAttackMob.java +++ b/net/minecraft/world/entity/monster/CrossbowAttackMob.java -@@ -24,9 +_,9 @@ - void onCrossbowAttackPerformed(); - - default void performCrossbowAttack(LivingEntity p_32337_, float p_32338_) { -- InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(p_32337_, Items.CROSSBOW); -+ InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(p_32337_, item -> item instanceof CrossbowItem); - ItemStack itemstack = p_32337_.getItemInHand(interactionhand); -- if (p_32337_.isHolding(Items.CROSSBOW)) { -+ if (p_32337_.isHolding(is -> is.getItem() instanceof CrossbowItem)) { - CrossbowItem.performShooting(p_32337_.level(), p_32337_, interactionhand, itemstack, p_32338_, (float)(14 - p_32337_.level().getDifficulty().getId() * 4)); - } +@@ -17,9 +_,10 @@ + void onCrossbowAttackPerformed(); + default void performCrossbowAttack(LivingEntity p_32337_, float p_32338_) { +- InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(p_32337_, Items.CROSSBOW); ++ InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(p_32337_, item -> item instanceof CrossbowItem); + ItemStack itemstack = p_32337_.getItemInHand(interactionhand); +- if (itemstack.getItem() instanceof CrossbowItem crossbowitem) { ++ if (p_32337_.isHolding(is -> is.getItem() instanceof CrossbowItem)) { ++ var crossbowitem = (CrossbowItem) itemstack.getItem(); + crossbowitem.performShooting( + p_32337_.level(), p_32337_, interactionhand, itemstack, p_32338_, (float)(14 - p_32337_.level().getDifficulty().getId() * 4), this.getTarget() + ); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch index 9b39268032..9958f0ce0e 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch @@ -1,75 +1,80 @@ --- a/net/minecraft/world/entity/monster/EnderMan.java +++ b/net/minecraft/world/entity/monster/EnderMan.java -@@ -111,7 +_,6 @@ - } +@@ -112,7 +_,6 @@ - public void setTarget(@Nullable LivingEntity p_32537_) { -- super.setTarget(p_32537_); - AttributeInstance attributeinstance = this.getAttribute(Attributes.MOVEMENT_SPEED); - if (p_32537_ == null) { - this.targetChangeTime = 0; + @Override + public void setTarget(@Nullable LivingEntity p_32537_) { +- super.setTarget(p_32537_); + AttributeInstance attributeinstance = this.getAttribute(Attributes.MOVEMENT_SPEED); + if (p_32537_ == null) { + this.targetChangeTime = 0; @@ -126,6 +_,7 @@ - } - } + attributeinstance.addTransientModifier(SPEED_MODIFIER_ATTACKING); + } + } ++ super.setTarget(p_32537_); //Forge: Moved down to allow event handlers to write data manager values. + } -+ super.setTarget(p_32537_); //Forge: Moved down to allow event handlers to write data manager values. - } + @Override +@@ -208,7 +_,7 @@ - protected void defineSynchedData() { -@@ -200,7 +_,7 @@ - - boolean isLookingAtMe(Player p_32535_) { - ItemStack itemstack = p_32535_.getInventory().armor.get(3); -- if (itemstack.is(Blocks.CARVED_PUMPKIN.asItem())) { -+ if (net.minecraftforge.common.ForgeHooks.shouldSuppressEnderManAnger(this, p_32535_, itemstack)) { - return false; - } else { - Vec3 vec3 = p_32535_.getViewVector(1.0F).normalize(); -@@ -283,8 +_,10 @@ - boolean flag = blockstate.blocksMotion(); - boolean flag1 = blockstate.getFluidState().is(FluidTags.WATER); - if (flag && !flag1) { -+ net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity event = net.minecraftforge.event.ForgeEventFactory.onEnderTeleport(this, p_32544_, p_32545_, p_32546_); -+ if (event.isCanceled()) return false; - Vec3 vec3 = this.position(); -- boolean flag2 = this.randomTeleport(p_32544_, p_32545_, p_32546_, true); -+ boolean flag2 = this.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true); - if (flag2) { - this.level().gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(this)); - if (!this.isSilent()) { -@@ -424,7 +_,7 @@ - public boolean canUse() { - if (this.enderman.getCarriedBlock() == null) { + boolean isLookingAtMe(Player p_32535_) { + ItemStack itemstack = p_32535_.getInventory().armor.get(3); +- if (itemstack.is(Blocks.CARVED_PUMPKIN.asItem())) { ++ if (net.minecraftforge.common.ForgeHooks.shouldSuppressEnderManAnger(this, p_32535_, itemstack)) { return false; -- } else if (!this.enderman.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ } else if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.enderman.level(), this.enderman)) { - return false; - } else { - return this.enderman.getRandom().nextInt(reducedTickDelay(2000)) == 0; -@@ -444,7 +_,7 @@ - BlockState blockstate2 = this.enderman.getCarriedBlock(); - if (blockstate2 != null) { - blockstate2 = Block.updateFromNeighbourShapes(blockstate2, this.enderman.level(), blockpos); -- if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1)) { -+ if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(enderman, net.minecraftforge.common.util.BlockSnapshot.create(level.dimension(), level, blockpos1), net.minecraft.core.Direction.UP)) { - level.setBlock(blockpos, blockstate2, 3); - level.gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this.enderman, blockstate2)); - this.enderman.setCarriedBlock((BlockState)null); -@@ -454,7 +_,7 @@ - } + } else { + Vec3 vec3 = p_32535_.getViewVector(1.0F).normalize(); +@@ -295,8 +_,10 @@ + boolean flag = blockstate.blocksMotion(); + boolean flag1 = blockstate.getFluidState().is(FluidTags.WATER); + if (flag && !flag1) { ++ net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity event = net.minecraftforge.event.ForgeEventFactory.onEnderTeleport(this, p_32544_, p_32545_, p_32546_); ++ if (event.isCanceled()) return false; + Vec3 vec3 = this.position(); +- boolean flag2 = this.randomTeleport(p_32544_, p_32545_, p_32546_, true); ++ boolean flag2 = this.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true); + if (flag2) { + this.level().gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(this)); + if (!this.isSilent()) { +@@ -447,7 +_,7 @@ + if (this.enderman.getCarriedBlock() == null) { + return false; + } else { +- return !this.enderman.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) ? false : this.enderman.getRandom().nextInt(reducedTickDelay(2000)) == 0; ++ return !net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.enderman.level(), this.enderman) ? false : this.enderman.getRandom().nextInt(reducedTickDelay(2000)) == 0; + } + } - private boolean canPlaceBlock(Level p_32559_, BlockPos p_32560_, BlockState p_32561_, BlockState p_32562_, BlockState p_32563_, BlockPos p_32564_) { -- return p_32562_.isAir() && !p_32563_.isAir() && !p_32563_.is(Blocks.BEDROCK) && p_32563_.isCollisionShapeFullBlock(p_32559_, p_32564_) && p_32561_.canSurvive(p_32559_, p_32560_) && p_32559_.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(p_32560_))).isEmpty(); -+ return p_32562_.isAir() && !p_32563_.isAir() && !p_32563_.is(Blocks.BEDROCK) && !p_32563_.is(net.minecraftforge.common.Tags.Blocks.ENDERMAN_PLACE_ON_BLACKLIST) && p_32563_.isCollisionShapeFullBlock(p_32559_, p_32564_) && p_32561_.canSurvive(p_32559_, p_32560_) && p_32559_.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(p_32560_))).isEmpty(); - } - } +@@ -465,7 +_,7 @@ + BlockState blockstate2 = this.enderman.getCarriedBlock(); + if (blockstate2 != null) { + blockstate2 = Block.updateFromNeighbourShapes(blockstate2, this.enderman.level(), blockpos); +- if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1)) { ++ if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(enderman, net.minecraftforge.common.util.BlockSnapshot.create(level.dimension(), level, blockpos1), net.minecraft.core.Direction.UP)) { + level.setBlock(blockpos, blockstate2, 3); + level.gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this.enderman, blockstate2)); + this.enderman.setCarriedBlock(null); +@@ -474,12 +_,7 @@ + } + + private boolean canPlaceBlock(Level p_32559_, BlockPos p_32560_, BlockState p_32561_, BlockState p_32562_, BlockState p_32563_, BlockPos p_32564_) { +- return p_32562_.isAir() +- && !p_32563_.isAir() +- && !p_32563_.is(Blocks.BEDROCK) +- && p_32563_.isCollisionShapeFullBlock(p_32559_, p_32564_) +- && p_32561_.canSurvive(p_32559_, p_32560_) +- && p_32559_.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(p_32560_))).isEmpty(); ++ return p_32562_.isAir() && !p_32563_.isAir() && !p_32563_.is(Blocks.BEDROCK) && !p_32563_.is(net.minecraftforge.common.Tags.Blocks.ENDERMAN_PLACE_ON_BLACKLIST) && p_32563_.isCollisionShapeFullBlock(p_32559_, p_32564_) && p_32561_.canSurvive(p_32559_, p_32560_) && p_32559_.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(p_32560_))).isEmpty(); + } + } + +@@ -585,7 +_,7 @@ + if (this.enderman.getCarriedBlock() != null) { + return false; + } else { +- return !this.enderman.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) ? false : this.enderman.getRandom().nextInt(reducedTickDelay(20)) == 0; ++ return !net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.enderman.level(), this.enderman) ? false : this.enderman.getRandom().nextInt(reducedTickDelay(20)) == 0; + } + } -@@ -556,7 +_,7 @@ - public boolean canUse() { - if (this.enderman.getCarriedBlock() != null) { - return false; -- } else if (!this.enderman.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ } else if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.enderman.level(), this.enderman)) { - return false; - } else { - return this.enderman.getRandom().nextInt(reducedTickDelay(20)) == 0; diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Evoker.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Evoker.java.patch index d191b575e5..7fc02da689 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Evoker.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Evoker.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/Evoker.java +++ b/net/minecraft/world/entity/monster/Evoker.java -@@ -285,7 +_,7 @@ - return false; - } else if (Evoker.this.tickCount < this.nextAttackTickCount) { - return false; -- } else if (!Evoker.this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ } else if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(Evoker.this.level(), Evoker.this)) { - return false; - } else { - List list = Evoker.this.level().getNearbyEntities(Sheep.class, this.wololoTargeting, Evoker.this, Evoker.this.getBoundingBox().inflate(16.0D, 4.0D, 16.0D)); +@@ -307,7 +_,7 @@ + return false; + } else if (Evoker.this.tickCount < this.nextAttackTickCount) { + return false; +- } else if (!Evoker.this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ } else if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(Evoker.this.level(), Evoker.this)) { + return false; + } else { + List list = Evoker.this.level().getNearbyEntities(Sheep.class, this.wololoTargeting, Evoker.this, Evoker.this.getBoundingBox().inflate(16.0, 4.0, 16.0)); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Husk.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Husk.java.patch index 1e23a3bc6c..1d70eedfc3 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Husk.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Husk.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/entity/monster/Husk.java +++ b/net/minecraft/world/entity/monster/Husk.java -@@ -62,6 +_,7 @@ - } +@@ -69,6 +_,7 @@ - protected void doUnderWaterConversion() { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIE, (timer) -> this.conversionTime = timer)) return; - this.convertToZombieType(EntityType.ZOMBIE); - if (!this.isSilent()) { - this.level().levelEvent((Player)null, 1041, this.blockPosition(), 0); + @Override + protected void doUnderWaterConversion() { ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIE, (timer) -> this.conversionTime = timer)) return; + this.convertToZombieType(EntityType.ZOMBIE); + if (!this.isSilent()) { + this.level().levelEvent(null, 1041, this.blockPosition(), 0); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Illusioner.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Illusioner.java.patch index 25d63eb3d5..11c89ed042 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Illusioner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Illusioner.java.patch @@ -1,14 +1,15 @@ --- a/net/minecraft/world/entity/monster/Illusioner.java +++ b/net/minecraft/world/entity/monster/Illusioner.java -@@ -178,8 +_,10 @@ - } +@@ -172,8 +_,11 @@ - public void performRangedAttack(LivingEntity p_32918_, float p_32919_) { -- ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW))); -+ ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem))); - AbstractArrow abstractarrow = ProjectileUtil.getMobArrow(this, itemstack, p_32919_); -+ if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem) -+ abstractarrow = ((net.minecraft.world.item.BowItem)this.getMainHandItem().getItem()).customArrow(abstractarrow); - double d0 = p_32918_.getX() - this.getX(); - double d1 = p_32918_.getY(0.3333333333333333D) - abstractarrow.getY(); - double d2 = p_32918_.getZ() - this.getZ(); + @Override + public void performRangedAttack(LivingEntity p_32918_, float p_32919_) { +- ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW))); ++ ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem))); + AbstractArrow abstractarrow = ProjectileUtil.getMobArrow(this, itemstack, p_32919_); ++ if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { ++ abstractarrow = bow.customArrow(abstractarrow); ++ } + double d0 = p_32918_.getX() - this.getX(); + double d1 = p_32918_.getY(0.3333333333333333) - abstractarrow.getY(); + double d2 = p_32918_.getZ() - this.getZ(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch index db771af0ab..4958bcdd1a 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch @@ -1,33 +1,33 @@ --- a/net/minecraft/world/entity/monster/MagmaCube.java +++ b/net/minecraft/world/entity/monster/MagmaCube.java -@@ -67,17 +_,28 @@ - float f = (float)this.getSize() * 0.1F; - this.setDeltaMovement(vec3.x, (double)(this.getJumpPower() + f), vec3.z); - this.hasImpulse = true; -+ net.minecraftforge.common.ForgeHooks.onLivingJump(this); - } +@@ -71,17 +_,28 @@ + float f = (float)this.getSize() * 0.1F; + this.setDeltaMovement(vec3.x, (double)(this.getJumpPower() + f), vec3.z); + this.hasImpulse = true; ++ net.minecraftforge.common.ForgeHooks.onLivingJump(this); + } -+ @Deprecated // FORGE: use jumpInFluid instead - protected void jumpInLiquid(TagKey p_204065_) { -- if (p_204065_ == FluidTags.LAVA) { -+ this.jumpInLiquidInternal(() -> p_204065_ == FluidTags.LAVA, () -> super.jumpInLiquid(p_204065_)); -+ } ++ /** @deprecated Forge - Use {@link #jumpInFluid(net.minecraftforge.fluids.FluidType)} */ + @Override + protected void jumpInLiquid(TagKey p_204065_) { +- if (p_204065_ == FluidTags.LAVA) { ++ this.jumpInLiquidInternal(() -> p_204065_ == FluidTags.LAVA, () -> super.jumpInLiquid(p_204065_)); ++ } + -+ private void jumpInLiquidInternal(java.util.function.BooleanSupplier isLava, Runnable onSuper) { -+ if (isLava.getAsBoolean()) { - Vec3 vec3 = this.getDeltaMovement(); - this.setDeltaMovement(vec3.x, (double)(0.22F + (float)this.getSize() * 0.05F), vec3.z); - this.hasImpulse = true; - } else { -- super.jumpInLiquid(p_204065_); -+ onSuper.run(); - } - -+ } ++ private void jumpInLiquidInternal(java.util.function.BooleanSupplier isLava, Runnable onSuper) { ++ if (isLava.getAsBoolean()) { + Vec3 vec3 = this.getDeltaMovement(); + this.setDeltaMovement(vec3.x, (double)(0.22F + (float)this.getSize() * 0.05F), vec3.z); + this.hasImpulse = true; + } else { +- super.jumpInLiquid(p_204065_); ++ onSuper.run(); + } ++ } + -+ @Override -+ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { -+ this.jumpInLiquidInternal(() -> type == net.minecraftforge.common.ForgeMod.LAVA_TYPE.get(), () -> super.jumpInFluid(type)); - } ++ @Override ++ public void jumpInFluid(net.minecraftforge.fluids.FluidType type) { ++ this.jumpInLiquidInternal(() -> type == net.minecraftforge.common.ForgeMod.LAVA_TYPE.get(), () -> super.jumpInFluid(type)); + } - protected boolean isDealsDamage() { + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch index 3347aa0fa4..5fcded1daa 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/entity/monster/Monster.java +++ b/net/minecraft/world/entity/monster/Monster.java -@@ -121,9 +_,9 @@ - if (p_33038_.getItem() instanceof ProjectileWeaponItem) { - Predicate predicate = ((ProjectileWeaponItem)p_33038_.getItem()).getSupportedHeldProjectiles(); - ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); -- return itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_33038_, itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack); - } else { -- return ItemStack.EMPTY; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_33038_, ItemStack.EMPTY); - } - } +@@ -138,9 +_,9 @@ + if (p_33038_.getItem() instanceof ProjectileWeaponItem) { + Predicate predicate = ((ProjectileWeaponItem)p_33038_.getItem()).getSupportedHeldProjectiles(); + ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); +- return itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_33038_, itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack); + } else { +- return ItemStack.EMPTY; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_33038_, ItemStack.EMPTY); + } + } } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Pillager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Pillager.java.patch index 8004af6849..0ecf222c12 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Pillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Pillager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/Pillager.java +++ b/net/minecraft/world/entity/monster/Pillager.java -@@ -109,7 +_,7 @@ - public AbstractIllager.IllagerArmPose getArmPose() { - if (this.isChargingCrossbow()) { - return AbstractIllager.IllagerArmPose.CROSSBOW_CHARGE; -- } else if (this.isHolding(Items.CROSSBOW)) { -+ } else if (this.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem)) { - return AbstractIllager.IllagerArmPose.CROSSBOW_HOLD; - } else { - return this.isAggressive() ? AbstractIllager.IllagerArmPose.ATTACKING : AbstractIllager.IllagerArmPose.NEUTRAL; +@@ -112,7 +_,7 @@ + public AbstractIllager.IllagerArmPose getArmPose() { + if (this.isChargingCrossbow()) { + return AbstractIllager.IllagerArmPose.CROSSBOW_CHARGE; +- } else if (this.isHolding(Items.CROSSBOW)) { ++ } else if (this.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem)) { + return AbstractIllager.IllagerArmPose.CROSSBOW_HOLD; + } else { + return this.isAggressive() ? AbstractIllager.IllagerArmPose.ATTACKING : AbstractIllager.IllagerArmPose.NEUTRAL; diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch index 6a2964e622..78d069cb30 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/Ravager.java +++ b/net/minecraft/world/entity/monster/Ravager.java -@@ -129,7 +_,7 @@ - this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1D, d1, d0)); - } +@@ -133,7 +_,7 @@ + this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1, d1, d0)); + } -- if (this.horizontalCollision && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { - boolean flag = false; - AABB aabb = this.getBoundingBox().inflate(0.2D); +- if (this.horizontalCollision && this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this)) { + boolean flag = false; + AABB aabb = this.getBoundingBox().inflate(0.2); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch index f5a574f204..89864dc705 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/monster/Shulker.java +++ b/net/minecraft/world/entity/monster/Shulker.java -@@ -354,6 +_,12 @@ - if (blockpos1.getY() > this.level().getMinBuildHeight() && this.level().isEmptyBlock(blockpos1) && this.level().getWorldBorder().isWithinBounds(blockpos1) && this.level().noCollision(this, (new AABB(blockpos1)).deflate(1.0E-6D))) { - Direction direction = this.findAttachableSurface(blockpos1); - if (direction != null) { -+ net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity event = net.minecraftforge.event.ForgeEventFactory.onEnderTeleport(this, blockpos1.getX(), blockpos1.getY(), blockpos1.getZ()); -+ if (event.isCanceled()) direction = null; -+ blockpos1 = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); -+ } +@@ -390,6 +_,12 @@ + && this.level().noCollision(this, new AABB(blockpos1).deflate(1.0E-6))) { + Direction direction = this.findAttachableSurface(blockpos1); + if (direction != null) { ++ net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity event = net.minecraftforge.event.ForgeEventFactory.onEnderTeleport(this, blockpos1.getX(), blockpos1.getY(), blockpos1.getZ()); ++ if (event.isCanceled()) direction = null; ++ blockpos1 = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); ++ } + -+ if (direction != null) { - this.unRide(); - this.setAttachFace(direction); - this.playSound(SoundEvents.SHULKER_TELEPORT, 1.0F, 1.0F); ++ if (direction != null) { + this.unRide(); + this.setAttachFace(direction); + this.playSound(SoundEvents.SHULKER_TELEPORT, 1.0F, 1.0F); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch index ef0b32456a..3769ca904a 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/monster/Silverfish.java +++ b/net/minecraft/world/entity/monster/Silverfish.java -@@ -141,7 +_,7 @@ - return false; - } else { - RandomSource randomsource = this.mob.getRandom(); -- if (this.mob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && randomsource.nextInt(reducedTickDelay(10)) == 0) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.mob.level(), this.mob) && randomsource.nextInt(reducedTickDelay(10)) == 0) { - this.selectedDirection = Direction.getRandom(randomsource); - BlockPos blockpos = BlockPos.containing(this.mob.getX(), this.mob.getY() + 0.5D, this.mob.getZ()).relative(this.selectedDirection); - BlockState blockstate = this.mob.level().getBlockState(blockpos); -@@ -210,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos1); - Block block = blockstate.getBlock(); - if (block instanceof InfestedBlock) { -- if (level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this.silverfish)) { - level.destroyBlock(blockpos1, true, this.silverfish); - } else { - level.setBlock(blockpos1, ((InfestedBlock)block).hostStateByInfested(level.getBlockState(blockpos1)), 3); +@@ -140,7 +_,7 @@ + return false; + } else { + RandomSource randomsource = this.mob.getRandom(); +- if (this.mob.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && randomsource.nextInt(reducedTickDelay(10)) == 0) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.mob.level(), this.mob) && randomsource.nextInt(reducedTickDelay(10)) == 0) { + this.selectedDirection = Direction.getRandom(randomsource); + BlockPos blockpos = BlockPos.containing(this.mob.getX(), this.mob.getY() + 0.5, this.mob.getZ()) + .relative(this.selectedDirection); +@@ -213,7 +_,7 @@ + BlockState blockstate = level.getBlockState(blockpos1); + Block block = blockstate.getBlock(); + if (block instanceof InfestedBlock) { +- if (level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this.silverfish)) { + level.destroyBlock(blockpos1, true, this.silverfish); + } else { + level.setBlock(blockpos1, ((InfestedBlock)block).hostStateByInfested(level.getBlockState(blockpos1)), 3); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Skeleton.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Skeleton.java.patch index 2ab2956ac0..599359a84d 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Skeleton.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Skeleton.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/entity/monster/Skeleton.java +++ b/net/minecraft/world/entity/monster/Skeleton.java -@@ -83,10 +_,12 @@ - } +@@ -85,10 +_,12 @@ + } - protected void doFreezeConversion() { -- this.convertTo(EntityType.STRAY, true); -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.STRAY, (timer) -> this.conversionTime = timer)) return; -+ var result = this.convertTo(EntityType.STRAY, true); - if (!this.isSilent()) { - this.level().levelEvent((Player)null, 1048, this.blockPosition(), 0); - } -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, result); - - } + protected void doFreezeConversion() { +- this.convertTo(EntityType.STRAY, true); ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.STRAY, (timer) -> this.conversionTime = timer)) return; ++ var result = this.convertTo(EntityType.STRAY, true); + if (!this.isSilent()) { + this.level().levelEvent(null, 1048, this.blockPosition(), 0); + } ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, result); + } + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch index cda58f6ffa..9799066a38 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch @@ -1,24 +1,38 @@ --- a/net/minecraft/world/entity/monster/Slime.java +++ b/net/minecraft/world/entity/monster/Slime.java -@@ -130,6 +_,8 @@ - if (this.onGround() && !this.wasOnGround) { - int i = this.getSize(); +@@ -139,13 +_,15 @@ + float f = this.getDimensions(this.getPose()).width() * 2.0F; + float f1 = f / 2.0F; -+ // Forge: Don't spawn particles if it's handled by the implementation itself -+ if (!spawnCustomParticles()) - for(int j = 0; j < i * 8; ++j) { - float f = this.random.nextFloat() * ((float)Math.PI * 2F); - float f1 = this.random.nextFloat() * 0.5F + 0.5F; -@@ -337,6 +_,12 @@ - public EntityDimensions getDimensions(Pose p_33597_) { - return super.getDimensions(p_33597_).scale(0.255F * (float)this.getSize()); - } +- for (int i = 0; (float)i < f * 16.0F; i++) { +- float f2 = this.random.nextFloat() * (float) (Math.PI * 2); +- float f3 = this.random.nextFloat() * 0.5F + 0.5F; +- float f4 = Mth.sin(f2) * f1 * f3; +- float f5 = Mth.cos(f2) * f1 * f3; +- this.level().addParticle(this.getParticleType(), this.getX() + (double)f4, this.getY(), this.getZ() + (double)f5, 0.0, 0.0, 0.0); +- } ++ // Forge: Don't spawn particles if it's handled by the implementation itself ++ if (!spawnCustomParticles()) ++ for (int i = 0; (float)i < f * 16.0F; i++) { ++ float f2 = this.random.nextFloat() * (float) (Math.PI * 2); ++ float f3 = this.random.nextFloat() * 0.5F + 0.5F; ++ float f4 = Mth.sin(f2) * f1 * f3; ++ float f5 = Mth.cos(f2) * f1 * f3; ++ this.level().addParticle(this.getParticleType(), this.getX() + (double)f4, this.getY(), this.getZ() + (double)f5, 0.0, 0.0, 0.0); ++ } + + this.playSound(this.getSquishSound(), this.getSoundVolume(), ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F) / 0.8F); + this.targetSquish = -0.5F; +@@ -156,6 +_,12 @@ + this.wasOnGround = this.onGround(); + this.decreaseSquish(); + } + -+ /** -+ * Called when the slime spawns particles on landing, see onUpdate. -+ * Return true to prevent the spawning of the default particles. -+ */ -+ protected boolean spawnCustomParticles() { return false; } ++ /** ++ * Called when the slime spawns particles on landing, see onUpdate. ++ * Return true to prevent the spawning of the default particles. ++ */ ++ protected boolean spawnCustomParticles() { return false; } - static class SlimeAttackGoal extends Goal { - private final Slime slime; + protected void decreaseSquish() { + this.targetSquish *= 0.6F; diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Spider.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Spider.java.patch index 7ec902f510..124b84e74c 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Spider.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Spider.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/entity/monster/Spider.java +++ b/net/minecraft/world/entity/monster/Spider.java @@ -121,7 +_,12 @@ - } - public boolean canBeAffected(MobEffectInstance p_33809_) { -- return p_33809_.getEffect() == MobEffects.POISON ? false : super.canBeAffected(p_33809_); -+ if (p_33809_.getEffect() == MobEffects.POISON) { -+ net.minecraftforge.event.entity.living.MobEffectEvent.Applicable event = new net.minecraftforge.event.entity.living.MobEffectEvent.Applicable(this, p_33809_); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW; -+ } -+ return super.canBeAffected(p_33809_); - } + @Override + public boolean canBeAffected(MobEffectInstance p_33809_) { +- return p_33809_.is(MobEffects.POISON) ? false : super.canBeAffected(p_33809_); ++ if (p_33809_.getEffect() == MobEffects.POISON) { ++ net.minecraftforge.event.entity.living.MobEffectEvent.Applicable event = new net.minecraftforge.event.entity.living.MobEffectEvent.Applicable(this, p_33809_); ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); ++ return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW; ++ } ++ return super.canBeAffected(p_33809_); + } - public boolean isClimbing() { + public boolean isClimbing() { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Zombie.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Zombie.java.patch index f7920c59c6..80fb4ecea0 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Zombie.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Zombie.java.patch @@ -1,80 +1,93 @@ --- a/net/minecraft/world/entity/monster/Zombie.java +++ b/net/minecraft/world/entity/monster/Zombie.java -@@ -243,6 +_,7 @@ - } +@@ -249,6 +_,7 @@ + } - protected void doUnderWaterConversion() { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.DROWNED, (timer) -> this.conversionTime = timer)) return; - this.convertToZombieType(EntityType.DROWNED); - if (!this.isSilent()) { - this.level().levelEvent((Player)null, 1040, this.blockPosition(), 0); -@@ -255,6 +_,7 @@ - if (zombie != null) { - zombie.handleAttributes(zombie.level().getCurrentDifficultyAt(zombie.blockPosition()).getSpecialMultiplier()); - zombie.setCanBreakDoors(zombie.supportsBreakDoorGoal() && this.canBreakDoors()); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombie); - } + protected void doUnderWaterConversion() { ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.DROWNED, (timer) -> this.conversionTime = timer)) return; + this.convertToZombieType(EntityType.DROWNED); + if (!this.isSilent()) { + this.level().levelEvent(null, 1040, this.blockPosition(), 0); +@@ -260,6 +_,7 @@ + if (zombie != null) { + zombie.handleAttributes(zombie.level().getCurrentDifficultyAt(zombie.blockPosition()).getSpecialMultiplier()); + zombie.setCanBreakDoors(zombie.supportsBreakDoorGoal() && this.canBreakDoors()); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombie); + } + } - } -@@ -275,11 +_,15 @@ - livingentity = (LivingEntity)p_34288_.getEntity(); - } - -- if (livingentity != null && this.level().getDifficulty() == Difficulty.HARD && (double)this.random.nextFloat() < this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE) && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)) { - int i = Mth.floor(this.getX()); - int j = Mth.floor(this.getY()); - int k = Mth.floor(this.getZ()); -- Zombie zombie = new Zombie(this.level()); -+ net.minecraftforge.event.entity.living.ZombieEvent.SummonAidEvent event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).getValue()); -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY) return true; -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || -+ livingentity != null && this.level().getDifficulty() == Difficulty.HARD && (double)this.random.nextFloat() < this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).getValue() && this.level() -+ .getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)) { -+ Zombie zombie = event.getCustomSummonedAid() != null && event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW ? event.getCustomSummonedAid() : EntityType.ZOMBIE.create(this.level()); - - for(int l = 0; l < 50; ++l) { - int i1 = i + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); -@@ -291,6 +_,7 @@ - if (NaturalSpawner.isSpawnPositionOk(spawnplacements$type, this.level(), blockpos, entitytype) && SpawnPlacements.checkSpawnRules(entitytype, serverlevel, MobSpawnType.REINFORCEMENT, blockpos, this.level().random)) { - zombie.setPos((double)i1, (double)j1, (double)k1); - if (!this.level().hasNearbyAlivePlayer((double)i1, (double)j1, (double)k1, 7.0D) && this.level().isUnobstructed(zombie) && this.level().noCollision(zombie) && !this.level().containsAnyLiquid(zombie.getBoundingBox())) { -+ if (livingentity != null) - zombie.setTarget(livingentity); - zombie.finalizeSpawn(serverlevel, this.level().getCurrentDifficultyAt(zombie.blockPosition()), MobSpawnType.REINFORCEMENT, (SpawnGroupData)null, (CompoundTag)null); - serverlevel.addFreshEntityWithPassengers(zombie); -@@ -381,6 +_,9 @@ - return flag; - } - -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(p_219161_, EntityType.ZOMBIE_VILLAGER, (timer) -> {})) -+ return flag; -+ - ZombieVillager zombievillager = villager.convertTo(EntityType.ZOMBIE_VILLAGER, false); - if (zombievillager != null) { - zombievillager.finalizeSpawn(p_219160_, p_219160_.getCurrentDifficultyAt(zombievillager.blockPosition()), MobSpawnType.CONVERSION, new Zombie.ZombieGroupData(false, true), (CompoundTag)null); -@@ -388,6 +_,7 @@ - zombievillager.setGossips(villager.getGossips().store(NbtOps.INSTANCE)); - zombievillager.setTradeOffers(villager.getOffers().createTag()); - zombievillager.setVillagerXp(villager.getVillagerXp()); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(p_219161_, zombievillager); - if (!this.isSilent()) { - p_219160_.levelEvent((Player)null, 1026, this.blockPosition(), 0); +@@ -280,15 +_,25 @@ + livingentity = (LivingEntity)p_34288_.getEntity(); } -@@ -465,7 +_,7 @@ - } - public static boolean getSpawnAsBabyOdds(RandomSource p_219163_) { -- return p_219163_.nextFloat() < 0.05F; -+ return p_219163_.nextFloat() < net.minecraftforge.common.ForgeConfig.SERVER.zombieBabyChance.get(); - } +- if (livingentity != null ++ var vanilla = (livingentity != null + && this.level().getDifficulty() == Difficulty.HARD + && (double)this.random.nextFloat() < this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE) +- && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)) { ++ && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)); ++ + int i = Mth.floor(this.getX()); + int j = Mth.floor(this.getY()); + int k = Mth.floor(this.getZ()); +- Zombie zombie = new Zombie(this.level()); +- ++ ++ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); ++ ++ Zombie zombie = null; ++ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW) { ++ zombie = event.getCustomSummonedAid() != null ? event.getCustomSummonedAid() : EntityType.ZOMBIE.create(this.level()); ++ } else if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && vanilla) { ++ zombie = EntityType.ZOMBIE.create(this.level()); ++ } ++ ++ if (zombie != null) { + for (int l = 0; l < 50; l++) { + int i1 = i + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); + int j1 = j + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); +@@ -302,6 +_,7 @@ + && this.level().isUnobstructed(zombie) + && this.level().noCollision(zombie) + && !this.level().containsAnyLiquid(zombie.getBoundingBox())) { ++ if (livingentity != null) + zombie.setTarget(livingentity); + zombie.finalizeSpawn(serverlevel, this.level().getCurrentDifficultyAt(zombie.blockPosition()), MobSpawnType.REINFORCEMENT, null); + serverlevel.addFreshEntityWithPassengers(zombie); +@@ -397,6 +_,10 @@ + return flag; + } - protected void handleAttributes(float p_34340_) { -@@ -485,7 +_,7 @@ - } ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(p_219161_, EntityType.ZOMBIE_VILLAGER, (timer) -> {})) { ++ return flag; ++ } ++ + ZombieVillager zombievillager = villager.convertTo(EntityType.ZOMBIE_VILLAGER, false); + if (zombievillager != null) { + zombievillager.finalizeSpawn( +@@ -406,6 +_,7 @@ + zombievillager.setGossips(villager.getGossips().store(NbtOps.INSTANCE)); + zombievillager.setTradeOffers(villager.getOffers().copy()); + zombievillager.setVillagerXp(villager.getVillagerXp()); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(p_219161_, zombievillager); + if (!this.isSilent()) { + p_219160_.levelEvent(null, 1026, this.blockPosition(), 0); + } +@@ -487,7 +_,7 @@ + } - protected void randomizeReinforcementsChance() { -- this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * (double)0.1F); -+ this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * net.minecraftforge.common.ForgeConfig.SERVER.zombieBaseSummonChance.get()); - } + public static boolean getSpawnAsBabyOdds(RandomSource p_219163_) { +- return p_219163_.nextFloat() < 0.05F; ++ return p_219163_.nextFloat() < net.minecraftforge.common.ForgeConfig.SERVER.zombieBabyChance.get(); + } - protected Vector3f getPassengerAttachmentPoint(Entity p_300549_, EntityDimensions p_298020_, float p_298000_) { + protected void handleAttributes(float p_34340_) { +@@ -510,7 +_,7 @@ + } + + protected void randomizeReinforcementsChance() { +- this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * 0.1F); ++ this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * net.minecraftforge.common.ForgeConfig.SERVER.zombieBaseSummonChance.get()); + } + + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/monster/ZombieVillager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/ZombieVillager.java.patch index 5310a487ea..0c46a00cd5 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/ZombieVillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/ZombieVillager.java.patch @@ -1,20 +1,19 @@ --- a/net/minecraft/world/entity/monster/ZombieVillager.java +++ b/net/minecraft/world/entity/monster/ZombieVillager.java -@@ -129,7 +_,7 @@ - if (!this.level().isClientSide && this.isAlive() && this.isConverting()) { - int i = this.getConversionProgress(); - this.villagerConversionTime -= i; -- if (this.villagerConversionTime <= 0) { -+ if (this.villagerConversionTime <= 0 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.VILLAGER, (timer) -> this.villagerConversionTime = timer)) { - this.finishConversion((ServerLevel)this.level()); - } - } -@@ -231,7 +_,7 @@ - if (!this.isSilent()) { - p_34399_.levelEvent((Player)null, 1027, this.blockPosition(), 0); - } -- -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, villager); - } +@@ -133,7 +_,7 @@ + if (!this.level().isClientSide && this.isAlive() && this.isConverting()) { + int i = this.getConversionProgress(); + this.villagerConversionTime -= i; +- if (this.villagerConversionTime <= 0) { ++ if (this.villagerConversionTime <= 0 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.VILLAGER, (timer) -> this.villagerConversionTime = timer)) { + this.finishConversion((ServerLevel)this.level()); + } + } +@@ -245,6 +_,7 @@ + if (!this.isSilent()) { + p_34399_.levelEvent(null, 1027, this.blockPosition(), 0); + } ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, villager); + } - private int getConversionProgress() { + private int getConversionProgress() { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch index 96d7cb5e64..19fd1c9e3f 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/entity/monster/hoglin/Hoglin.java +++ b/net/minecraft/world/entity/monster/hoglin/Hoglin.java -@@ -128,7 +_,7 @@ - HoglinAi.updateActivity(this); - if (this.isConverting()) { - ++this.timeInOverworld; -- if (this.timeInOverworld > 300) { -+ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOGLIN, (timer) -> this.timeInOverworld = timer)) { - this.playSoundEvent(SoundEvents.HOGLIN_CONVERTED_TO_ZOMBIFIED); - this.finishConversion((ServerLevel)this.level()); - } -@@ -221,6 +_,7 @@ - Zoglin zoglin = this.convertTo(EntityType.ZOGLIN, true); - if (zoglin != null) { - zoglin.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 200, 0)); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zoglin); - } +@@ -161,7 +_,7 @@ + HoglinAi.updateActivity(this); + if (this.isConverting()) { + this.timeInOverworld++; +- if (this.timeInOverworld > 300) { ++ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOGLIN, (timer) -> this.timeInOverworld = timer)) { + this.makeSound(SoundEvents.HOGLIN_CONVERTED_TO_ZOMBIFIED); + this.finishConversion((ServerLevel)this.level()); + } +@@ -257,6 +_,7 @@ + Zoglin zoglin = this.convertTo(EntityType.ZOGLIN, true); + if (zoglin != null) { + zoglin.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 200, 0)); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zoglin); + } + } - } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch index 7e71d6b5a8..844536bcf6 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch @@ -1,22 +1,19 @@ --- a/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java +++ b/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java -@@ -93,9 +_,10 @@ - ++this.timeInOverworld; - } else { - this.timeInOverworld = 0; -+ this.timeInOverworld = 0; - } +@@ -80,7 +_,7 @@ + this.timeInOverworld = 0; + } -- if (this.timeInOverworld > 300) { -+ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> this.timeInOverworld = timer)) { - this.playConvertedSound(); - this.finishConversion((ServerLevel)this.level()); - } -@@ -110,6 +_,7 @@ - ZombifiedPiglin zombifiedpiglin = this.convertTo(EntityType.ZOMBIFIED_PIGLIN, true); - if (zombifiedpiglin != null) { - zombifiedpiglin.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 200, 0)); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombifiedpiglin); - } +- if (this.timeInOverworld > 300) { ++ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> this.timeInOverworld = timer)) { + this.playConvertedSound(); + this.finishConversion((ServerLevel)this.level()); + } +@@ -94,6 +_,7 @@ + ZombifiedPiglin zombifiedpiglin = this.convertTo(EntityType.ZOMBIFIED_PIGLIN, true); + if (zombifiedpiglin != null) { + zombifiedpiglin.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 200, 0)); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombifiedpiglin); + } + } - } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/Piglin.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/Piglin.java.patch index b448373fb1..c3e80cd74c 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/Piglin.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/Piglin.java.patch @@ -1,29 +1,29 @@ --- a/net/minecraft/world/entity/monster/piglin/Piglin.java +++ b/net/minecraft/world/entity/monster/piglin/Piglin.java -@@ -289,7 +_,7 @@ - } else if (this.isChargingCrossbow()) { - return PiglinArmPose.CROSSBOW_CHARGE; - } else { -- return this.isAggressive() && this.isHolding(Items.CROSSBOW) ? PiglinArmPose.CROSSBOW_HOLD : PiglinArmPose.DEFAULT; -+ return this.isAggressive() && this.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem) ? PiglinArmPose.CROSSBOW_HOLD : PiglinArmPose.DEFAULT; - } - } +@@ -345,7 +_,7 @@ + } else if (this.isChargingCrossbow()) { + return PiglinArmPose.CROSSBOW_CHARGE; + } else { +- return this.isAggressive() && this.isHolding(Items.CROSSBOW) ? PiglinArmPose.CROSSBOW_HOLD : PiglinArmPose.DEFAULT; ++ return this.isAggressive() && this.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem) ? PiglinArmPose.CROSSBOW_HOLD : PiglinArmPose.DEFAULT; + } + } -@@ -331,7 +_,7 @@ - } +@@ -386,7 +_,7 @@ + } - protected void holdInOffHand(ItemStack p_34786_) { -- if (p_34786_.is(PiglinAi.BARTERING_ITEM)) { -+ if (p_34786_.isPiglinCurrency()) { - this.setItemSlot(EquipmentSlot.OFFHAND, p_34786_); - this.setGuaranteedDrop(EquipmentSlot.OFFHAND); - } else { -@@ -341,7 +_,7 @@ - } + protected void holdInOffHand(ItemStack p_34786_) { +- if (p_34786_.is(PiglinAi.BARTERING_ITEM)) { ++ if (p_34786_.isPiglinCurrency()) { + this.setItemSlot(EquipmentSlot.OFFHAND, p_34786_); + this.setGuaranteedDrop(EquipmentSlot.OFFHAND); + } else { +@@ -396,7 +_,7 @@ - public boolean wantsToPickUp(ItemStack p_34777_) { -- return this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && this.canPickUpLoot() && PiglinAi.wantsToPickup(this, p_34777_); -+ return net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this) && this.canPickUpLoot() && PiglinAi.wantsToPickup(this, p_34777_); - } + @Override + public boolean wantsToPickUp(ItemStack p_34777_) { +- return this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) && this.canPickUpLoot() && PiglinAi.wantsToPickup(this, p_34777_); ++ return net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this) && this.canPickUpLoot() && PiglinAi.wantsToPickup(this, p_34777_); + } - protected boolean canReplaceCurrentItem(ItemStack p_34788_) { + protected boolean canReplaceCurrentItem(ItemStack p_34788_) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch index a3d329b13c..f3a6c76df9 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch @@ -1,47 +1,29 @@ --- a/net/minecraft/world/entity/monster/piglin/PiglinAi.java +++ b/net/minecraft/world/entity/monster/piglin/PiglinAi.java -@@ -268,7 +_,7 @@ - ItemStack itemstack = p_34868_.getItemInHand(InteractionHand.OFF_HAND); - p_34868_.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); - if (p_34868_.isAdult()) { -- boolean flag = isBarterCurrency(itemstack); -+ boolean flag = itemstack.isPiglinCurrency(); - if (p_34869_ && flag) { - throwItems(p_34868_, getBarterResponseItems(p_34868_)); - } else if (!flag) { -@@ -356,7 +_,7 @@ - return false; - } else if (isAdmiringDisabled(p_34858_) && p_34858_.getBrain().hasMemoryValue(MemoryModuleType.ATTACK_TARGET)) { - return false; -- } else if (isBarterCurrency(p_34859_)) { -+ } else if (p_34859_.isPiglinCurrency()) { - return isNotHoldingLovedItemInOffHand(p_34858_); - } else { - boolean flag = p_34858_.canAddToInventory(p_34859_); -@@ -455,7 +_,7 @@ - } +@@ -635,7 +_,7 @@ + public static boolean isWearingGold(LivingEntity p_34809_) { + for (ItemStack itemstack : p_34809_.getArmorAndBodyArmorSlots()) { + Item item = itemstack.getItem(); +- if (item instanceof ArmorItem && ((ArmorItem)item).getMaterial().is(ArmorMaterials.GOLD)) { ++ if (itemstack.makesPiglinsNeutral(p_34809_)) { + return true; + } + } +@@ -779,7 +_,7 @@ + } - protected static boolean canAdmire(Piglin p_34910_, ItemStack p_34911_) { -- return !isAdmiringDisabled(p_34910_) && !isAdmiringItem(p_34910_) && p_34910_.isAdult() && isBarterCurrency(p_34911_); -+ return !isAdmiringDisabled(p_34910_) && !isAdmiringItem(p_34910_) && p_34910_.isAdult() && p_34911_.isPiglinCurrency(); - } + private static boolean hasCrossbow(LivingEntity p_34919_) { +- return p_34919_.isHolding(Items.CROSSBOW); ++ return p_34919_.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem); + } - protected static void wasHurtBy(Piglin p_34838_, LivingEntity p_34839_) { -@@ -550,7 +_,7 @@ - public static boolean isWearingGold(LivingEntity p_34809_) { - for(ItemStack itemstack : p_34809_.getArmorSlots()) { - Item item = itemstack.getItem(); -- if (item instanceof ArmorItem && ((ArmorItem)item).getMaterial() == ArmorMaterials.GOLD) { -+ if (itemstack.makesPiglinsNeutral(p_34809_)) { - return true; - } - } -@@ -703,7 +_,7 @@ - } + private static void admireGoldItem(LivingEntity p_34939_) { +@@ -791,7 +_,7 @@ + } - private static boolean hasCrossbow(LivingEntity p_34919_) { -- return p_34919_.isHolding(Items.CROSSBOW); -+ return p_34919_.isHolding(is -> is.getItem() instanceof net.minecraft.world.item.CrossbowItem); - } + private static boolean isBarterCurrency(ItemStack p_149968_) { +- return p_149968_.is(BARTERING_ITEM); ++ return p_149968_.is(BARTERING_ITEM) || p_149968_.isPiglinCurrency(); + } - private static void admireGoldItem(LivingEntity p_34939_) { + private static boolean isFood(ItemStack p_149970_) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java.patch index 0a8c2f6dc5..cc06ca652a 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java +++ b/net/minecraft/world/entity/monster/piglin/StopHoldingItemIfNoLongerAdmiring.java -@@ -10,7 +_,7 @@ - return BehaviorBuilder.create((p_259197_) -> { - return p_259197_.group(p_259197_.absent(MemoryModuleType.ADMIRING_ITEM)).apply(p_259197_, (p_259512_) -> { - return (p_309208_, p_309209_, p_309210_) -> { -- if (!p_309209_.getOffhandItem().isEmpty() && !p_309209_.getOffhandItem().is(Items.SHIELD)) { -+ if (!p_309209_.getOffhandItem().isEmpty() && !p_309209_.getOffhandItem().canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { - PiglinAi.stopHoldingOffHandItem(p_309209_, true); - return true; - } else { +@@ -11,7 +_,7 @@ + public static BehaviorControl create() { + return BehaviorBuilder.create( + p_259197_ -> p_259197_.group(p_259197_.absent(MemoryModuleType.ADMIRING_ITEM)).apply(p_259197_, p_259512_ -> (p_327034_, p_327035_, p_327036_) -> { +- if (!p_327035_.getOffhandItem().isEmpty() && !p_327035_.getOffhandItem().is(Items.SHIELD)) { ++ if (!p_327035_.getOffhandItem().isEmpty() && !p_327035_.getOffhandItem().canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { + PiglinAi.stopHoldingOffHandItem(p_327035_, true); + return true; + } else { diff --git a/patches/minecraft/net/minecraft/world/entity/npc/AbstractVillager.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/AbstractVillager.java.patch index f13f88863a..ef388699b9 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/AbstractVillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/AbstractVillager.java.patch @@ -1,22 +1,23 @@ --- a/net/minecraft/world/entity/npc/AbstractVillager.java +++ b/net/minecraft/world/entity/npc/AbstractVillager.java -@@ -116,6 +_,7 @@ - CriteriaTriggers.TRADE.trigger((ServerPlayer)this.tradingPlayer, this, p_35274_.getResult()); - } +@@ -123,6 +_,8 @@ + if (this.tradingPlayer instanceof ServerPlayer) { + CriteriaTriggers.TRADE.trigger((ServerPlayer)this.tradingPlayer, this, p_35274_.getResult()); + } ++ ++ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.TradeWithVillagerEvent(this.tradingPlayer, p_35274_, this)); + } -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.TradeWithVillagerEvent(this.tradingPlayer, p_35274_, this)); - } + protected abstract void rewardTradeXp(MerchantOffer p_35299_); +@@ -179,9 +_,9 @@ - protected abstract void rewardTradeXp(MerchantOffer p_35299_); -@@ -164,9 +_,9 @@ - } + @Nullable + @Override +- public Entity changeDimension(ServerLevel p_35295_) { ++ public Entity changeDimension(ServerLevel p_35295_, net.minecraftforge.common.util.ITeleporter teleporter) { + this.stopTrading(); +- return super.changeDimension(p_35295_); ++ return super.changeDimension(p_35295_, teleporter); + } - @Nullable -- public Entity changeDimension(ServerLevel p_35295_) { -+ public Entity changeDimension(ServerLevel p_35295_, net.minecraftforge.common.util.ITeleporter teleporter) { - this.stopTrading(); -- return super.changeDimension(p_35295_); -+ return super.changeDimension(p_35295_, teleporter); - } - - protected void stopTrading() { + protected void stopTrading() { diff --git a/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch index 7a9976901a..c0cbf518d6 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/entity/npc/CatSpawner.java +++ b/net/minecraft/world/entity/npc/CatSpawner.java -@@ -86,8 +_,8 @@ - if (cat == null) { - return 0; - } else { -+ cat.moveTo(p_35334_, 0.0F, 0.0F); // Fix MC-147659: Some witch huts spawn the incorrect cat - cat.finalizeSpawn(p_35335_, p_35335_.getCurrentDifficultyAt(p_35334_), MobSpawnType.NATURAL, (SpawnGroupData)null, (CompoundTag)null); -- cat.moveTo(p_35334_, 0.0F, 0.0F); - p_35335_.addFreshEntityWithPassengers(cat); - return 1; - } +@@ -83,8 +_,8 @@ + if (cat == null) { + return 0; + } else { ++ cat.moveTo(p_35334_, 0.0F, 0.0F); // Fix MC-147659: Some witch huts spawn the incorrect cat + cat.finalizeSpawn(p_35335_, p_35335_.getCurrentDifficultyAt(p_35334_), MobSpawnType.NATURAL, null); +- cat.moveTo(p_35334_, 0.0F, 0.0F); + p_35335_.addFreshEntityWithPassengers(cat); + return 1; + } diff --git a/patches/minecraft/net/minecraft/world/entity/npc/Villager.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/Villager.java.patch index 669c59a8ff..e923bbb53c 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/Villager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/Villager.java.patch @@ -1,38 +1,38 @@ --- a/net/minecraft/world/entity/npc/Villager.java +++ b/net/minecraft/world/entity/npc/Villager.java -@@ -256,7 +_,7 @@ - - public InteractionResult mobInteract(Player p_35472_, InteractionHand p_35473_) { - ItemStack itemstack = p_35472_.getItemInHand(p_35473_); -- if (!itemstack.is(Items.VILLAGER_SPAWN_EGG) && this.isAlive() && !this.isTrading() && !this.isSleeping()) { -+ if (itemstack.getItem() != Items.VILLAGER_SPAWN_EGG && this.isAlive() && !this.isTrading() && !this.isSleeping() && !p_35472_.isSecondaryUseActive()) { - if (this.isBaby()) { +@@ -314,7 +_,7 @@ + @Override + public InteractionResult mobInteract(Player p_35472_, InteractionHand p_35473_) { + ItemStack itemstack = p_35472_.getItemInHand(p_35473_); +- if (itemstack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) { ++ if (itemstack.getItem() != Items.VILLAGER_SPAWN_EGG && this.isAlive() && !this.isTrading() && !this.isSleeping() && !p_35472_.isSecondaryUseActive()) { + return super.mobInteract(p_35472_, p_35473_); + } else if (this.isBaby()) { this.setUnhappy(); - return InteractionResult.sidedSuccess(this.level().isClientSide); -@@ -670,7 +_,8 @@ - } +@@ -725,7 +_,8 @@ - protected Component getTypeName() { -- return Component.translatable(this.getType().getDescriptionId() + "." + BuiltInRegistries.VILLAGER_PROFESSION.getKey(this.getVillagerData().getProfession()).getPath()); -+ net.minecraft.resources.ResourceLocation profName = net.minecraftforge.registries.ForgeRegistries.VILLAGER_PROFESSIONS.getKey(this.getVillagerData().getProfession()); -+ return Component.translatable(this.getType().getDescriptionId() + '.' + (!"minecraft".equals(profName.getNamespace()) ? profName.getNamespace() + '.' : "") + profName.getPath()); - } + @Override + protected Component getTypeName() { +- return Component.translatable(this.getType().getDescriptionId() + "." + BuiltInRegistries.VILLAGER_PROFESSION.getKey(this.getVillagerData().getProfession()).getPath()); ++ var profName = net.minecraftforge.registries.ForgeRegistries.VILLAGER_PROFESSIONS.getKey(this.getVillagerData().getProfession()); ++ return Component.translatable(this.getType().getDescriptionId() + '.' + (!"minecraft".equals(profName.getNamespace()) ? profName.getNamespace() + '.' : "") + profName.getPath()); + } - public void handleEntityEvent(byte p_35391_) { -@@ -723,7 +_,7 @@ - } + @Override +@@ -780,7 +_,7 @@ - public void thunderHit(ServerLevel p_35409_, LightningBolt p_35410_) { -- if (p_35409_.getDifficulty() != Difficulty.PEACEFUL) { -+ if (p_35409_.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.WITCH, (timer) -> {})) { - LOGGER.info("Villager {} was struck by lightning {}.", this, p_35410_); - Witch witch = EntityType.WITCH.create(p_35409_); - if (witch != null) { -@@ -736,6 +_,7 @@ - } + @Override + public void thunderHit(ServerLevel p_35409_, LightningBolt p_35410_) { +- if (p_35409_.getDifficulty() != Difficulty.PEACEFUL) { ++ if (p_35409_.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.WITCH, (timer) -> {})) { + LOGGER.info("Villager {} was struck by lightning {}.", this, p_35410_); + Witch witch = EntityType.WITCH.create(p_35409_); + if (witch != null) { +@@ -793,6 +_,7 @@ + } - witch.setPersistenceRequired(); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, witch); - p_35409_.addFreshEntityWithPassengers(witch); - this.releaseAllPois(); - this.discard(); + witch.setPersistenceRequired(); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, witch); + p_35409_.addFreshEntityWithPassengers(witch); + this.releaseAllPois(); + this.discard(); diff --git a/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch b/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch index 82240ca4a3..70c4c4902b 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch @@ -2,44 +2,34 @@ +++ b/net/minecraft/world/entity/player/Inventory.java @@ -130,7 +_,7 @@ - for(int k = 0; k < 9; ++k) { - int l = (this.selected + k) % 9; -- if (!this.items.get(l).isEnchanted()) { -+ if (!this.items.get(l).isNotReplaceableByPickAction(this.player, l)) { - return l; - } - } -@@ -178,7 +_,8 @@ - int i = p_36049_.getCount(); - ItemStack itemstack = this.getItem(p_36048_); - if (itemstack.isEmpty()) { -- itemstack = new ItemStack(item, 0); -+ itemstack = p_36049_.copy(); // Forge: Replace Item clone above to preserve item capabilities when picking the item up. -+ itemstack.setCount(0); - if (p_36049_.hasTag()) { - itemstack.setTag(p_36049_.getTag().copy()); - } -@@ -222,11 +_,13 @@ - } - - public void tick() { -+ int idx = 0; - for(NonNullList nonnulllist : this.compartments) { - for(int i = 0; i < nonnulllist.size(); ++i) { - if (!nonnulllist.get(i).isEmpty()) { -- nonnulllist.get(i).inventoryTick(this.player.level(), this.player, i, this.selected == i); -+ nonnulllist.get(i).onInventoryTick(this.player.level(), this.player, idx, this.selected); + for (int k = 0; k < 9; k++) { + int l = (this.selected + k) % 9; +- if (!this.items.get(l).isEnchanted()) { ++ if (!this.items.get(l).isNotReplaceableByPickAction(this.player, l)) { + return l; } -+ idx++; - } - } + } +@@ -211,11 +_,13 @@ + } -@@ -277,6 +_,8 @@ - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "Adding item to inventory"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Item being added"); -+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_36042_.getItem()))); -+ crashreportcategory.setDetail("Item Class", () -> p_36042_.getItem().getClass().getName()); - crashreportcategory.setDetail("Item ID", Item.getId(p_36042_.getItem())); - crashreportcategory.setDetail("Item data", p_36042_.getDamageValue()); - crashreportcategory.setDetail("Item name", () -> { + public void tick() { ++ int idx = 0; + for (NonNullList nonnulllist : this.compartments) { + for (int i = 0; i < nonnulllist.size(); i++) { + if (!nonnulllist.get(i).isEmpty()) { +- nonnulllist.get(i).inventoryTick(this.player.level(), this.player, i, this.selected == i); ++ nonnulllist.get(i).onInventoryTick(this.player.level(), this.player, idx, this.selected); + } ++ idx++; + } + } + } +@@ -265,6 +_,8 @@ + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "Adding item to inventory"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Item being added"); ++ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_36042_.getItem()))); ++ crashreportcategory.setDetail("Item Class", () -> p_36042_.getItem().getClass().getName()); + crashreportcategory.setDetail("Item ID", Item.getId(p_36042_.getItem())); + crashreportcategory.setDetail("Item data", p_36042_.getDamageValue()); + crashreportcategory.setDetail("Item name", () -> p_36042_.getHoverName().getString()); diff --git a/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch b/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch index a4b2ca6fbb..c559592870 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch @@ -1,479 +1,461 @@ --- a/net/minecraft/world/entity/player/Player.java +++ b/net/minecraft/world/entity/player/Player.java -@@ -110,7 +_,8 @@ +@@ -114,7 +_,7 @@ import net.minecraft.world.scores.Team; import org.slf4j.Logger; -public abstract class Player extends LivingEntity { +public abstract class Player extends LivingEntity implements net.minecraftforge.common.extensions.IForgePlayer { -+ public static final String PERSISTED_NBT_TAG = "PlayerPersisted"; - private static final Logger LOGGER = LogUtils.getLogger(); - public static final int MAX_NAME_LENGTH = 16; - public static final HumanoidArm DEFAULT_MAIN_HAND = HumanoidArm.RIGHT; -@@ -164,6 +_,9 @@ - @Nullable - public FishingHook fishing; - protected float hurtDir; -+ private final java.util.Collection prefixes = new java.util.LinkedList<>(); -+ private final java.util.Collection suffixes = new java.util.LinkedList<>(); -+ @Nullable private Pose forcedPose; + private static final Logger LOGGER = LogUtils.getLogger(); + public static final HumanoidArm DEFAULT_MAIN_HAND = HumanoidArm.RIGHT; + public static final int DEFAULT_MODEL_CUSTOMIZATION = 0; +@@ -190,6 +_,9 @@ + @Nullable + public Entity currentExplosionCause; + public boolean ignoreFallDamageFromCurrentImpulse; ++ private final java.util.Collection prefixes = new java.util.LinkedList<>(); ++ private final java.util.Collection suffixes = new java.util.LinkedList<>(); ++ @Nullable private Pose forcedPose; - public Player(Level p_250508_, BlockPos p_250289_, float p_251702_, GameProfile p_252153_) { - super(EntityType.PLAYER, p_250508_); -@@ -189,7 +_,7 @@ - } + public Player(Level p_250508_, BlockPos p_250289_, float p_251702_, GameProfile p_252153_) { + super(EntityType.PLAYER, p_250508_); +@@ -222,7 +_,8 @@ + .add(Attributes.LUCK) + .add(Attributes.BLOCK_INTERACTION_RANGE, 4.5) + .add(Attributes.ENTITY_INTERACTION_RANGE, 3.0) +- .add(Attributes.BLOCK_BREAK_SPEED); ++ .add(Attributes.BLOCK_BREAK_SPEED) ++ .add(Attributes.ATTACK_KNOCKBACK); + } - public static AttributeSupplier.Builder createAttributes() { -- return LivingEntity.createLivingAttributes().add(Attributes.ATTACK_DAMAGE, 1.0D).add(Attributes.MOVEMENT_SPEED, (double)0.1F).add(Attributes.ATTACK_SPEED).add(Attributes.LUCK); -+ return LivingEntity.createLivingAttributes().add(Attributes.ATTACK_DAMAGE, 1.0D).add(Attributes.MOVEMENT_SPEED, (double) 0.1F).add(Attributes.ATTACK_SPEED).add(Attributes.LUCK).add(net.minecraftforge.common.ForgeMod.BLOCK_REACH.get()).add(Attributes.ATTACK_KNOCKBACK).add(net.minecraftforge.common.ForgeMod.ENTITY_REACH.get()); - } + @Override +@@ -238,6 +_,7 @@ - protected void defineSynchedData() { -@@ -203,6 +_,7 @@ - } - - public void tick() { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerPreTick(this); - this.noPhysics = this.isSpectator(); - if (this.isSpectator()) { - this.setOnGround(false); -@@ -218,7 +_,7 @@ - this.sleepCounter = 100; - } - -- if (!this.level().isClientSide && this.level().isDay()) { -+ if (!this.level().isClientSide && !net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, getSleepingPos())) { - this.stopSleepInBed(false, true); - } - } else if (this.sleepCounter > 0) { -@@ -273,6 +_,7 @@ - this.turtleHelmetTick(); - this.cooldowns.tick(); - this.updatePlayerPose(); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerPostTick(this); - } - - protected float getMaxHeadRotationRelativeToBody() { -@@ -352,6 +_,10 @@ - } - - protected void updatePlayerPose() { -+ if(forcedPose != null) { -+ this.setPose(forcedPose); -+ return; -+ } - if (this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.SWIMMING)) { - Pose pose; - if (this.isFallFlying()) { -@@ -572,6 +_,7 @@ - } - - public void die(DamageSource p_36152_) { -+ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_36152_)) return; - super.die(p_36152_); - this.reapplyPosition(); - if (!this.isSpectator()) { -@@ -621,7 +_,7 @@ - - @Nullable - public ItemEntity drop(ItemStack p_36177_, boolean p_36178_) { -- return this.drop(p_36177_, false, p_36178_); -+ return net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, p_36177_, p_36178_); - } - - @Nullable -@@ -659,7 +_,12 @@ - } - } - -+ @Deprecated //Use location sensitive version below - public float getDestroySpeed(BlockState p_36282_) { -+ return getDigSpeed(p_36282_, null); -+ } -+ -+ public float getDigSpeed(BlockState p_36282_, @Nullable BlockPos pos) { - float f = this.inventory.getDestroySpeed(p_36282_); - if (f > 1.0F) { - int i = EnchantmentHelper.getBlockEfficiency(this); -@@ -701,11 +_,12 @@ - f /= 5.0F; - } - -+ f = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, p_36282_, f, pos); - return f; - } - - public boolean hasCorrectToolForDrops(BlockState p_36299_) { -- return !p_36299_.requiresCorrectToolForDrops() || this.inventory.getSelected().isCorrectToolForDrops(p_36299_); -+ return net.minecraftforge.event.ForgeEventFactory.doPlayerHarvestCheck(this, p_36299_, !p_36299_.requiresCorrectToolForDrops() || this.inventory.getSelected().isCorrectToolForDrops(p_36299_)); - } - - public void readAdditionalSaveData(CompoundTag p_36215_) { -@@ -791,6 +_,7 @@ - } - - public boolean hurt(DamageSource p_36154_, float p_36155_) { -+ if (!net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, p_36154_, p_36155_)) return false; - if (this.isInvulnerableTo(p_36154_)) { - return false; - } else if (this.abilities.invulnerable && !p_36154_.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { -@@ -825,7 +_,7 @@ - - protected void blockUsingShield(LivingEntity p_36295_) { - super.blockUsingShield(p_36295_); -- if (p_36295_.canDisableShield()) { -+ if (p_36295_.getMainHandItem().canDisableShield(this.useItem, this, p_36295_)) { - this.disableShield(true); - } - -@@ -854,7 +_,7 @@ - } - - protected void hurtCurrentlyUsedShield(float p_36383_) { -- if (this.useItem.is(Items.SHIELD)) { -+ if (this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { - if (!this.level().isClientSide) { - this.awardStat(Stats.ITEM_USED.get(this.useItem.getItem())); - } -@@ -864,6 +_,8 @@ - InteractionHand interactionhand = this.getUsedItemHand(); - this.useItem.hurtAndBreak(i, this, (p_219739_) -> { - p_219739_.broadcastBreakEvent(interactionhand); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, this.useItem, interactionhand); -+ stopUsingItem(); // Forge: fix MC-168573 - }); - if (this.useItem.isEmpty()) { - if (interactionhand == InteractionHand.MAIN_HAND) { -@@ -882,10 +_,13 @@ - - protected void actuallyHurt(DamageSource p_36312_, float p_36313_) { - if (!this.isInvulnerableTo(p_36312_)) { -+ p_36313_ = net.minecraftforge.common.ForgeHooks.onLivingHurt(this, p_36312_, p_36313_); -+ if (p_36313_ <= 0) return; - p_36313_ = this.getDamageAfterArmorAbsorb(p_36312_, p_36313_); - p_36313_ = this.getDamageAfterMagicAbsorb(p_36312_, p_36313_); - float f1 = Math.max(p_36313_ - this.getAbsorptionAmount(), 0.0F); - this.setAbsorptionAmount(this.getAbsorptionAmount() - (p_36313_ - f1)); -+ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, p_36312_, f1); - float f = p_36313_ - f1; - if (f > 0.0F && f < 3.4028235E37F) { - this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(f * 10.0F)); -@@ -948,6 +_,8 @@ - - return InteractionResult.PASS; - } else { -+ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onInteractEntity(this, p_36158_, p_36159_); -+ if (cancelResult != null) return cancelResult; - ItemStack itemstack = this.getItemInHand(p_36159_); - ItemStack itemstack1 = itemstack.copy(); - InteractionResult interactionresult = p_36158_.interact(this, p_36159_); -@@ -956,6 +_,9 @@ - itemstack.setCount(itemstack1.getCount()); + @Override + public void tick() { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerPreTick(this); + this.noPhysics = this.isSpectator(); + if (this.isSpectator()) { + this.setOnGround(false); +@@ -253,7 +_,7 @@ + this.sleepCounter = 100; } -+ if (!this.abilities.instabuild && itemstack.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, p_36159_); +- if (!this.level().isClientSide && this.level().isDay()) { ++ if (!this.level().isClientSide && !net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, getSleepingPos())) { + this.stopSleepInBed(false, true); + } + } else if (this.sleepCounter > 0) { +@@ -308,6 +_,7 @@ + this.turtleHelmetTick(); + this.cooldowns.tick(); + this.updatePlayerPose(); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerPostTick(this); + } + + @Override +@@ -387,6 +_,10 @@ + } + + protected void updatePlayerPose() { ++ if (forcedPose != null) { ++ this.setPose(forcedPose); ++ return; ++ } + if (this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.SWIMMING)) { + Pose pose; + if (this.isFallFlying()) { +@@ -613,6 +_,7 @@ + + @Override + public void die(DamageSource p_36152_) { ++ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_36152_)) return; + super.die(p_36152_); + this.reapplyPosition(); + if (!this.isSpectator()) { +@@ -667,7 +_,7 @@ + + @Nullable + public ItemEntity drop(ItemStack p_36177_, boolean p_36178_) { +- return this.drop(p_36177_, false, p_36178_); ++ return net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, p_36177_, p_36178_); + } + + @Nullable +@@ -709,7 +_,12 @@ + } + } + ++ /** @deprecated Use {@link #getDestroySpeed(BlockState,BlockPos) */ + public float getDestroySpeed(BlockState p_36282_) { ++ return getDestroySpeed(p_36282_, null); ++ } ++ ++ public float getDestroySpeed(BlockState p_36282_, @Nullable BlockPos pos) { + float f = this.inventory.getDestroySpeed(p_36282_); + if (f > 1.0F) { + int i = EnchantmentHelper.getBlockEfficiency(this); +@@ -741,11 +_,14 @@ + f /= 5.0F; + } + ++ f = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, p_36282_, f, pos); ++ + return f; + } + + public boolean hasCorrectToolForDrops(BlockState p_36299_) { +- return !p_36299_.requiresCorrectToolForDrops() || this.inventory.getSelected().isCorrectToolForDrops(p_36299_); ++ var vanilla = !p_36299_.requiresCorrectToolForDrops() || this.inventory.getSelected().isCorrectToolForDrops(p_36299_); ++ return net.minecraftforge.event.ForgeEventFactory.doPlayerHarvestCheck(this, p_36299_, vanilla); + } + + @Override +@@ -844,6 +_,7 @@ + + @Override + public boolean hurt(DamageSource p_36154_, float p_36155_) { ++ if (!net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, p_36154_, p_36155_)) return false; + if (this.isInvulnerableTo(p_36154_)) { + return false; + } else if (this.abilities.invulnerable && !p_36154_.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { +@@ -879,7 +_,7 @@ + @Override + protected void blockUsingShield(LivingEntity p_36295_) { + super.blockUsingShield(p_36295_); +- if (p_36295_.canDisableShield()) { ++ if (p_36295_.getMainHandItem().canDisableShield(this.useItem, this, p_36295_)) { + this.disableShield(); + } + } +@@ -911,7 +_,7 @@ + + @Override + protected void hurtCurrentlyUsedShield(float p_36383_) { +- if (this.useItem.is(Items.SHIELD)) { ++ if (this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { + if (!this.level().isClientSide) { + this.awardStat(Stats.ITEM_USED.get(this.useItem.getItem())); + } +@@ -937,10 +_,13 @@ + @Override + protected void actuallyHurt(DamageSource p_36312_, float p_36313_) { + if (!this.isInvulnerableTo(p_36312_)) { ++ p_36313_ = net.minecraftforge.common.ForgeHooks.onLivingHurt(this, p_36312_, p_36313_); ++ if (p_36313_ <= 0) return; + p_36313_ = this.getDamageAfterArmorAbsorb(p_36312_, p_36313_); + p_36313_ = this.getDamageAfterMagicAbsorb(p_36312_, p_36313_); + float f1 = Math.max(p_36313_ - this.getAbsorptionAmount(), 0.0F); + this.setAbsorptionAmount(this.getAbsorptionAmount() - (p_36313_ - f1)); ++ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, p_36312_, f1); + float f = p_36313_ - f1; + if (f > 0.0F && f < 3.4028235E37F) { + this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(f * 10.0F)); +@@ -1004,6 +_,10 @@ + + return InteractionResult.PASS; + } else { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEntityInteract(this, p_36158_, p_36159_); ++ if (event.isCanceled()) { ++ return event.getCancellationResult(); + } - return interactionresult; - } else { - if (!itemstack.isEmpty() && p_36158_ instanceof LivingEntity) { -@@ -967,6 +_,7 @@ - if (interactionresult1.consumesAction()) { - this.level().gameEvent(GameEvent.ENTITY_INTERACT, p_36158_.position(), GameEvent.Context.of(this)); - if (itemstack.isEmpty() && !this.abilities.instabuild) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, p_36159_); - this.setItemInHand(p_36159_, ItemStack.EMPTY); - } + ItemStack itemstack = this.getItemInHand(p_36159_); + ItemStack itemstack1 = itemstack.copy(); + InteractionResult interactionresult = p_36158_.interact(this, p_36159_); +@@ -1012,6 +_,10 @@ + itemstack.setCount(itemstack1.getCount()); + } -@@ -996,6 +_,7 @@ - return !this.abilities.flying; - } - -+ // Forge: Don't update this method to use IForgeEntity#getStepHeight() - https://github.com/MinecraftForge/MinecraftForge/issues/8922 - protected Vec3 maybeBackOffFromEdge(Vec3 p_36201_, MoverType p_36202_) { - if (!this.abilities.flying && p_36201_.y <= 0.0D && (p_36202_ == MoverType.SELF || p_36202_ == MoverType.PLAYER) && this.isStayingOnGroundSurface() && this.isAboveGround()) { - double d0 = p_36201_.x; -@@ -1046,11 +_,13 @@ - return p_36201_; - } - -+ // Forge: Don't update this method to use IForgeEntity#getStepHeight() - https://github.com/MinecraftForge/MinecraftForge/issues/9376 - private boolean isAboveGround() { - return this.onGround() || this.fallDistance < this.maxUpStep() && !this.level().noCollision(this, this.getBoundingBox().move(0.0D, (double)(this.fallDistance - this.maxUpStep()), 0.0D)); - } - - public void attack(Entity p_36347_) { -+ if (!net.minecraftforge.common.ForgeHooks.onPlayerAttackTarget(this, p_36347_)) return; - if (p_36347_.isAttackable()) { - if (!p_36347_.skipAttackInteraction(this)) { - float f = (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); -@@ -1064,11 +_,10 @@ - float f2 = this.getAttackStrengthScale(0.5F); - f *= 0.2F + f2 * f2 * 0.8F; - f1 *= f2; -- this.resetAttackStrengthTicker(); - if (f > 0.0F || f1 > 0.0F) { - boolean flag = f2 > 0.9F; - boolean flag1 = false; -- int i = 0; -+ float i = (float)this.getAttributeValue(Attributes.ATTACK_KNOCKBACK); // Forge: Initialize this value to the attack knockback attribute of the player, which is by default 0 - i += EnchantmentHelper.getKnockbackBonus(this); - if (this.isSprinting() && flag) { - this.level().playSound((Player)null, this.getX(), this.getY(), this.getZ(), SoundEvents.PLAYER_ATTACK_KNOCKBACK, this.getSoundSource(), 1.0F, 1.0F); -@@ -1078,8 +_,10 @@ - - boolean flag2 = flag && this.fallDistance > 0.0F && !this.onGround() && !this.onClimbable() && !this.isInWater() && !this.hasEffect(MobEffects.BLINDNESS) && !this.isPassenger() && p_36347_ instanceof LivingEntity; - flag2 = flag2 && !this.isSprinting(); -+ net.minecraftforge.event.entity.player.CriticalHitEvent hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, p_36347_, flag2, flag2 ? 1.5F : 1.0F); -+ flag2 = hitResult != null; - if (flag2) { -- f *= 1.5F; -+ f *= hitResult.getDamageModifier(); - } - - f += f1; -@@ -1087,9 +_,7 @@ - double d0 = (double)(this.walkDist - this.walkDistO); - if (flag && !flag2 && !flag1 && this.onGround() && d0 < (double)this.getSpeed()) { - ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); -- if (itemstack.getItem() instanceof SwordItem) { -- flag3 = true; -- } -+ flag3 = itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SWORD_SWEEP); - } - - float f4 = 0.0F; -@@ -1120,8 +_,9 @@ - if (flag3) { - float f3 = 1.0F + EnchantmentHelper.getSweepingDamageRatio(this) * f; - -- for(LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, p_36347_.getBoundingBox().inflate(1.0D, 0.25D, 1.0D))) { -- if (livingentity != this && livingentity != p_36347_ && !this.isAlliedTo(livingentity) && (!(livingentity instanceof ArmorStand) || !((ArmorStand)livingentity).isMarker()) && this.distanceToSqr(livingentity) < 9.0D) { -+ for(LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, p_36347_))) { -+ double entityReachSq = Mth.square(this.getEntityReach()); // Use entity reach instead of constant 9.0. Vanilla uses bottom center-to-center checks here, so don't update this to use canReach, since it uses closest-corner checks. -+ if (livingentity != this && livingentity != p_36347_ && !this.isAlliedTo(livingentity) && (!(livingentity instanceof ArmorStand) || !((ArmorStand)livingentity).isMarker()) && this.distanceToSqr(livingentity) < entityReachSq) { - livingentity.knockback((double)0.4F, (double)Mth.sin(this.getYRot() * ((float)Math.PI / 180F)), (double)(-Mth.cos(this.getYRot() * ((float)Math.PI / 180F)))); - livingentity.hurt(this.damageSources().playerAttack(this), f3); - } -@@ -1162,13 +_,15 @@ - EnchantmentHelper.doPostDamageEffects(this, p_36347_); - ItemStack itemstack1 = this.getMainHandItem(); - Entity entity = p_36347_; -- if (p_36347_ instanceof EnderDragonPart) { -- entity = ((EnderDragonPart)p_36347_).parentMob; -+ if (p_36347_ instanceof net.minecraftforge.entity.PartEntity) { -+ entity = ((net.minecraftforge.entity.PartEntity) p_36347_).getParent(); - } - - if (!this.level().isClientSide && !itemstack1.isEmpty() && entity instanceof LivingEntity) { -+ ItemStack copy = itemstack1.copy(); - itemstack1.hurtEnemy((LivingEntity)entity, this); - if (itemstack1.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, copy, InteractionHand.MAIN_HAND); - this.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); - } - } -@@ -1194,6 +_,7 @@ - } - } - } -+ this.resetAttackStrengthTicker(); // FORGE: Moved from beginning of attack() so that getAttackStrengthScale() returns an accurate value during all attack events - - } - } -@@ -1210,7 +_,7 @@ - } - - if (this.random.nextFloat() < f) { -- this.getCooldowns().addCooldown(Items.SHIELD, 100); -+ this.getCooldowns().addCooldown(this.getUseItem().getItem(), 100); - this.stopUsingItem(); - this.level().broadcastEntityEvent(this, (byte)30); - } -@@ -1274,6 +_,7 @@ - } - - public void stopSleepInBed(boolean p_36226_, boolean p_36227_) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerWakeup(this, p_36226_, p_36227_); - super.stopSleeping(); - if (this.level() instanceof ServerLevel && p_36227_) { - ((ServerLevel)this.level()).updateSleepingPlayerList(); -@@ -1299,7 +_,7 @@ - } else if (block instanceof BedBlock && BedBlock.canSetSpawn(p_36131_)) { - return BedBlock.findStandUpPosition(EntityType.PLAYER, p_36131_, p_36132_, blockstate.getValue(BedBlock.FACING), p_36133_); - } else if (!p_36134_) { -- return Optional.empty(); -+ return blockstate.getRespawnPosition(EntityType.PLAYER, p_36131_, p_36132_, p_36133_, null); - } else { - boolean flag = block.isPossibleToRespawnInThis(blockstate); - BlockState blockstate1 = p_36131_.getBlockState(p_36132_.above()); -@@ -1404,6 +_,7 @@ - - public boolean causeFallDamage(float p_150093_, float p_150094_, DamageSource p_150095_) { - if (this.abilities.mayfly) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerFall(this, p_150093_, p_150093_); - return false; - } else { - if (p_150093_ >= 2.0F) { -@@ -1417,7 +_,7 @@ - public boolean tryToStartFallFlying() { - if (!this.onGround() && !this.isFallFlying() && !this.isInWater() && !this.hasEffect(MobEffects.LEVITATION)) { - ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); -- if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack)) { -+ if (itemstack.canElytraFly(this)) { - this.startFallFlying(); - return true; - } -@@ -1445,13 +_,13 @@ - protected void playStepSound(BlockPos p_282121_, BlockState p_282194_) { - if (this.isInWater()) { - this.waterSwimSound(); -- this.playMuffledStepSound(p_282194_); -+ this.playMuffledStepSound(p_282194_, p_282121_); - } else { - BlockPos blockpos = this.getPrimaryStepSoundBlockPos(p_282121_); - if (!p_282121_.equals(blockpos)) { - BlockState blockstate = this.level().getBlockState(blockpos); - if (blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { -- this.playCombinationStepSounds(blockstate, p_282194_); -+ this.playCombinationStepSounds(blockstate, p_282194_, blockpos, p_282121_); ++ if (!this.abilities.instabuild && itemstack.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, getSlotForHand(p_36159_)); ++ } ++ + return interactionresult; } else { - super.playStepSound(blockpos, blockstate); + if (!itemstack.isEmpty() && p_36158_ instanceof LivingEntity) { +@@ -1023,6 +_,7 @@ + if (interactionresult1.consumesAction()) { + this.level().gameEvent(GameEvent.ENTITY_INTERACT, p_36158_.position(), GameEvent.Context.of(this)); + if (itemstack.isEmpty() && !this.abilities.instabuild) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, getSlotForHand(p_36159_)); + this.setItemInHand(p_36159_, ItemStack.EMPTY); + } + +@@ -1122,6 +_,7 @@ + } + + public void attack(Entity p_36347_) { ++ if (!net.minecraftforge.common.ForgeHooks.onPlayerAttackTarget(this, p_36347_)) return; + if (p_36347_.isAttackable()) { + if (!p_36347_.skipAttackInteraction(this)) { + float f = (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); +@@ -1129,14 +_,13 @@ + float f2 = this.getAttackStrengthScale(0.5F); + f *= 0.2F + f2 * f2 * 0.8F; + f1 *= f2; +- this.resetAttackStrengthTicker(); + if (p_36347_.getType().is(EntityTypeTags.REDIRECTABLE_PROJECTILE) && p_36347_ instanceof Projectile projectile) { + projectile.deflect(ProjectileDeflection.AIM_DEFLECT, this, this, true); + } else { + if (f > 0.0F || f1 > 0.0F) { + boolean flag = f2 > 0.9F; + boolean flag1 = false; +- int i = 0; ++ float i = (float)this.getAttributeValue(Attributes.ATTACK_KNOCKBACK); // Forge: Initialize this value to the attack knockback attribute of the player, which is by default 0 + i += EnchantmentHelper.getKnockbackBonus(this); + if (this.isSprinting() && flag) { + this.level().playSound(null, this.getX(), this.getY(), this.getZ(), SoundEvents.PLAYER_ATTACK_KNOCKBACK, this.getSoundSource(), 1.0F, 1.0F); +@@ -1154,8 +_,10 @@ + && !this.isPassenger() + && p_36347_ instanceof LivingEntity + && !this.isSprinting(); ++ var hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, p_36347_, flag2, flag2 ? 1.5F : 1.0F); ++ flag2 = hitResult != null; + if (flag2) { +- f *= 1.5F; ++ f *= hitResult.getDamageModifier(); + } + + f += f1; +@@ -1163,7 +_,7 @@ + double d0 = (double)(this.walkDist - this.walkDistO); + if (flag && !flag2 && !flag1 && this.onGround() && d0 < (double)this.getSpeed()) { + ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); +- if (itemstack.getItem() instanceof SwordItem) { ++ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SWORD_SWEEP)) { + flag3 = true; + } + } +@@ -1205,7 +_,7 @@ + if (flag3) { + float f3 = 1.0F + EnchantmentHelper.getSweepingDamageRatio(this) * f; + +- for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, p_36347_.getBoundingBox().inflate(1.0, 0.25, 1.0))) { ++ for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, p_36347_))) { + if (livingentity != this + && livingentity != p_36347_ + && !this.isAlliedTo(livingentity) +@@ -1259,13 +_,15 @@ + EnchantmentHelper.doPostDamageEffects(this, p_36347_); + ItemStack itemstack1 = this.getMainHandItem(); + Entity entity = p_36347_; +- if (p_36347_ instanceof EnderDragonPart) { +- entity = ((EnderDragonPart)p_36347_).parentMob; ++ if (p_36347_ instanceof net.minecraftforge.entity.PartEntity part) { ++ entity = part.getParent(); + } + + if (!this.level().isClientSide && !itemstack1.isEmpty() && entity instanceof LivingEntity) { ++ ItemStack copy = itemstack1.copy(); + itemstack1.hurtEnemy((LivingEntity)entity, this); + if (itemstack1.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, copy, InteractionHand.MAIN_HAND); + this.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + } + } +@@ -1295,6 +_,7 @@ + } + } + } ++ this.resetAttackStrengthTicker(); // FORGE: Moved from beginning of attack() so that getAttackStrengthScale() returns an accurate value during all attack events } -@@ -1479,6 +_,10 @@ - } + } + } +@@ -1305,7 +_,7 @@ + } - public void giveExperiencePoints(int p_36291_) { -+ net.minecraftforge.event.entity.player.PlayerXpEvent.XpChange event = new net.minecraftforge.event.entity.player.PlayerXpEvent.XpChange(this, p_36291_); -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) return; -+ p_36291_ = event.getAmount(); -+ - this.increaseScore(p_36291_); - this.experienceProgress += (float)p_36291_ / (float)this.getXpNeededForNextLevel(); - this.totalExperience = Mth.clamp(this.totalExperience + p_36291_, 0, Integer.MAX_VALUE); -@@ -1507,7 +_,7 @@ - } + public void disableShield() { +- this.getCooldowns().addCooldown(Items.SHIELD, 100); ++ this.getCooldowns().addCooldown(this.getUseItem().getItem(), 100); + this.stopUsingItem(); + this.level().broadcastEntityEvent(this, (byte)30); + } +@@ -1371,6 +_,7 @@ + } - public void onEnchantmentPerformed(ItemStack p_36172_, int p_36173_) { -- this.experienceLevel -= p_36173_; -+ giveExperienceLevels(-p_36173_); - if (this.experienceLevel < 0) { - this.experienceLevel = 0; - this.experienceProgress = 0.0F; -@@ -1518,6 +_,10 @@ - } - - public void giveExperienceLevels(int p_36276_) { -+ net.minecraftforge.event.entity.player.PlayerXpEvent.LevelChange event = new net.minecraftforge.event.entity.player.PlayerXpEvent.LevelChange(this, p_36276_); -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) return; -+ p_36276_ = event.getLevels(); -+ - this.experienceLevel += p_36276_; - if (this.experienceLevel < 0) { - this.experienceLevel = 0; -@@ -1713,7 +_,11 @@ - } - - public Component getDisplayName() { -- MutableComponent mutablecomponent = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); -+ if (this.displayname == null) this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); -+ MutableComponent mutablecomponent = Component.literal(""); -+ mutablecomponent = prefixes.stream().reduce(mutablecomponent, MutableComponent::append); -+ mutablecomponent = mutablecomponent.append(PlayerTeam.formatNameForTeam(this.getTeam(), this.displayname)); -+ mutablecomponent = suffixes.stream().reduce(mutablecomponent, MutableComponent::append); - return this.decorateDisplayNameComponent(mutablecomponent); - } - -@@ -1846,24 +_,24 @@ - Predicate predicate = ((ProjectileWeaponItem)p_36349_.getItem()).getSupportedHeldProjectiles(); - ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); - if (!itemstack.isEmpty()) { -- return itemstack; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, itemstack); - } else { - predicate = ((ProjectileWeaponItem)p_36349_.getItem()).getAllSupportedProjectiles(); - - for(int i = 0; i < this.inventory.getContainerSize(); ++i) { - ItemStack itemstack1 = this.inventory.getItem(i); - if (predicate.test(itemstack1)) { -- return itemstack1; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, itemstack1); - } + public void stopSleepInBed(boolean p_36226_, boolean p_36227_) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerWakeup(this, p_36226_, p_36227_); + super.stopSleeping(); + if (this.level() instanceof ServerLevel && p_36227_) { + ((ServerLevel)this.level()).updateSleepingPlayerList(); +@@ -1399,7 +_,7 @@ + } else if (block instanceof BedBlock && BedBlock.canSetSpawn(p_36131_)) { + return BedBlock.findStandUpPosition(EntityType.PLAYER, p_36131_, p_36132_, blockstate.getValue(BedBlock.FACING), p_36133_); + } else if (!p_36134_) { +- return Optional.empty(); ++ return blockstate.getRespawnPosition(EntityType.PLAYER, p_36131_, p_36132_, p_36133_, null); + } else { + boolean flag = block.isPossibleToRespawnInThis(blockstate); + BlockState blockstate1 = p_36131_.getBlockState(p_36132_.above()); +@@ -1510,6 +_,7 @@ + @Override + public boolean causeFallDamage(float p_150093_, float p_150094_, DamageSource p_150095_) { + if (this.abilities.mayfly) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerFall(this, p_150093_, p_150093_); + return false; + } else { + if (p_150093_ >= 2.0F) { +@@ -1529,7 +_,7 @@ + public boolean tryToStartFallFlying() { + if (!this.onGround() && !this.isFallFlying() && !this.isInWater() && !this.hasEffect(MobEffects.LEVITATION)) { + ItemStack itemstack = this.getItemBySlot(EquipmentSlot.CHEST); +- if (itemstack.is(Items.ELYTRA) && ElytraItem.isFlyEnabled(itemstack)) { ++ if (itemstack.canElytraFly(this)) { + this.startFallFlying(); + return true; } +@@ -1558,13 +_,13 @@ + protected void playStepSound(BlockPos p_282121_, BlockState p_282194_) { + if (this.isInWater()) { + this.waterSwimSound(); +- this.playMuffledStepSound(p_282194_); ++ this.playMuffledStepSound(p_282194_, p_282121_); + } else { + BlockPos blockpos = this.getPrimaryStepSoundBlockPos(p_282121_); + if (!p_282121_.equals(blockpos)) { + BlockState blockstate = this.level().getBlockState(blockpos); + if (blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { +- this.playCombinationStepSounds(blockstate, p_282194_); ++ this.playCombinationStepSounds(blockstate, p_282194_, blockpos, p_282121_); + } else { + super.playStepSound(blockpos, blockstate); + } +@@ -1595,6 +_,12 @@ + } -- return this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY); - } - } - } + public void giveExperiencePoints(int p_36291_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerXpChange(this, p_36291_); ++ if (event.isCanceled()) { ++ return; ++ } ++ p_36291_ = event.getAmount(); ++ + this.increaseScore(p_36291_); + this.experienceProgress = this.experienceProgress + (float)p_36291_ / (float)this.getXpNeededForNextLevel(); + this.totalExperience = Mth.clamp(this.totalExperience + p_36291_, 0, Integer.MAX_VALUE); +@@ -1622,7 +_,7 @@ + } - public ItemStack eat(Level p_36185_, ItemStack p_36186_) { -- this.getFoodData().eat(p_36186_.getItem(), p_36186_); -+ this.getFoodData().eat(p_36186_.getItem(), p_36186_, this); - this.awardStat(Stats.ITEM_USED.get(p_36186_.getItem())); - p_36185_.playSound((Player)null, this.getX(), this.getY(), this.getZ(), SoundEvents.PLAYER_BURP, SoundSource.PLAYERS, 0.5F, p_36185_.random.nextFloat() * 0.1F + 0.9F); - if (this instanceof ServerPlayer) { -@@ -1981,5 +_,63 @@ - public Component getMessage() { - return this.message; - } -+ } + public void onEnchantmentPerformed(ItemStack p_36172_, int p_36173_) { +- this.experienceLevel -= p_36173_; ++ giveExperienceLevels(-p_36173_); + if (this.experienceLevel < 0) { + this.experienceLevel = 0; + this.experienceProgress = 0.0F; +@@ -1633,6 +_,12 @@ + } + + public void giveExperienceLevels(int p_36276_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerLevelChange(this, p_36276_); ++ if (event.isCanceled()) { ++ return; ++ } ++ p_36276_ = event.getLevels(); + -+ // =========== FORGE START ==============// -+ public Collection getPrefixes() { -+ return this.prefixes; -+ } + this.experienceLevel += p_36276_; + if (this.experienceLevel < 0) { + this.experienceLevel = 0; +@@ -1841,7 +_,13 @@ + + @Override + public Component getDisplayName() { +- MutableComponent mutablecomponent = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); ++ if (this.displayname == null) { ++ this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); ++ } ++ MutableComponent mutablecomponent = Component.literal(""); ++ mutablecomponent = prefixes.stream().reduce(mutablecomponent, MutableComponent::append); ++ mutablecomponent = mutablecomponent.append(PlayerTeam.formatNameForTeam(this.getTeam(), this.displayname)); ++ mutablecomponent = suffixes.stream().reduce(mutablecomponent, MutableComponent::append); + return this.decorateDisplayNameComponent(mutablecomponent); + } + +@@ -2002,18 +_,19 @@ + Predicate predicate = ((ProjectileWeaponItem)p_36349_.getItem()).getSupportedHeldProjectiles(); + ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); + if (!itemstack.isEmpty()) { +- return itemstack; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, itemstack); + } else { + predicate = ((ProjectileWeaponItem)p_36349_.getItem()).getAllSupportedProjectiles(); + + for (int i = 0; i < this.inventory.getContainerSize(); i++) { + ItemStack itemstack1 = this.inventory.getItem(i); + if (predicate.test(itemstack1)) { +- return itemstack1; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, itemstack1); + } + } + +- return this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; ++ var vanilla = this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, p_36349_, vanilla); + } + } + } +@@ -2147,6 +_,65 @@ + this.currentImpulseImpactPos = null; + this.ignoreFallDamageFromCurrentImpulse = false; + } + -+ public Collection getSuffixes() { -+ return this.suffixes; -+ } ++ public Collection getPrefixes() { ++ return this.prefixes; ++ } + -+ private Component displayname = null; -+ /** -+ * Force the displayed name to refresh, by firing {@link net.minecraftforge.event.entity.player.PlayerEvent.NameFormat}, using the real player name as event parameter. -+ */ -+ public void refreshDisplayName() { -+ this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); -+ } ++ public Collection getSuffixes() { ++ return this.suffixes; ++ } + -+ private final net.minecraftforge.common.util.LazyOptional -+ playerMainHandler = net.minecraftforge.common.util.LazyOptional.of( -+ () -> new net.minecraftforge.items.wrapper.PlayerMainInvWrapper(inventory)); ++ private Component displayname = null; + -+ private final net.minecraftforge.common.util.LazyOptional -+ playerEquipmentHandler = net.minecraftforge.common.util.LazyOptional.of( -+ () -> new net.minecraftforge.items.wrapper.CombinedInvWrapper( -+ new net.minecraftforge.items.wrapper.PlayerArmorInvWrapper(inventory), -+ new net.minecraftforge.items.wrapper.PlayerOffhandInvWrapper(inventory))); ++ /** ++ * Force the displayed name to refresh, by firing {@link net.minecraftforge.event.entity.player.PlayerEvent.NameFormat}, using the real player name as event parameter. ++ */ ++ public void refreshDisplayName() { ++ this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); ++ } + -+ private final net.minecraftforge.common.util.LazyOptional -+ playerJoinedHandler = net.minecraftforge.common.util.LazyOptional.of( -+ () -> new net.minecraftforge.items.wrapper.PlayerInvWrapper(inventory)); ++ private final net.minecraftforge.common.util.LazyOptional ++ playerMainHandler = net.minecraftforge.common.util.LazyOptional.of( ++ () -> new net.minecraftforge.items.wrapper.PlayerMainInvWrapper(inventory)); + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { -+ if (facing == null) return playerJoinedHandler.cast(); -+ else if (facing.getAxis().isVertical()) return playerMainHandler.cast(); -+ else if (facing.getAxis().isHorizontal()) return playerEquipmentHandler.cast(); -+ } -+ return super.getCapability(capability, facing); -+ } ++ private final net.minecraftforge.common.util.LazyOptional ++ playerEquipmentHandler = net.minecraftforge.common.util.LazyOptional.of( ++ () -> new net.minecraftforge.items.wrapper.CombinedInvWrapper( ++ new net.minecraftforge.items.wrapper.PlayerArmorInvWrapper(inventory), ++ new net.minecraftforge.items.wrapper.PlayerOffhandInvWrapper(inventory))); + -+ /** -+ * Force a pose for the player. If set, the vanilla pose determination and clearance check is skipped. Make sure the pose is clear yourself (e.g. in PlayerTick). -+ * This has to be set just once, do not set it every tick. -+ * Make sure to clear (null) the pose if not required anymore and only use if necessary. -+ */ -+ public void setForcedPose(@Nullable Pose pose) { -+ this.forcedPose = pose; -+ } ++ private final net.minecraftforge.common.util.LazyOptional ++ playerJoinedHandler = net.minecraftforge.common.util.LazyOptional.of( ++ () -> new net.minecraftforge.items.wrapper.PlayerInvWrapper(inventory)); + -+ /** -+ * @return The forced pose if set, null otherwise -+ */ -+ @Nullable -+ public Pose getForcedPose() { -+ return this.forcedPose; - } - } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { ++ if (facing == null) return playerJoinedHandler.cast(); ++ else if (facing.getAxis().isVertical()) return playerMainHandler.cast(); ++ else if (facing.getAxis().isHorizontal()) return playerEquipmentHandler.cast(); ++ } ++ return super.getCapability(capability, facing); ++ } ++ ++ /** ++ * Force a pose for the player. If set, the vanilla pose determination and clearance check is skipped. Make sure the pose is clear yourself (e.g. in PlayerTick). ++ * This has to be set just once, do not set it every tick. ++ * Make sure to clear (null) the pose if not required anymore and only use if necessary. ++ */ ++ public void setForcedPose(@Nullable Pose pose) { ++ this.forcedPose = pose; ++ } ++ ++ /** ++ * @return The forced pose if set, null otherwise ++ */ ++ @Nullable ++ public Pose getForcedPose() { ++ return this.forcedPose; ++ } ++ + + public static enum BedSleepingProblem { + NOT_POSSIBLE_HERE, diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/AbstractArrow.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/AbstractArrow.java.patch index ff3a56c4e7..692276c16e 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/AbstractArrow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/AbstractArrow.java.patch @@ -1,71 +1,71 @@ --- a/net/minecraft/world/entity/projectile/AbstractArrow.java +++ b/net/minecraft/world/entity/projectile/AbstractArrow.java -@@ -68,6 +_,8 @@ - private List piercedAndKilledEntities; - private ItemStack pickupItemStack; +@@ -68,6 +_,7 @@ + @Nullable + private List piercedAndKilledEntities; + private ItemStack pickupItemStack = this.getDefaultPickupItem(); ++ private final IntOpenHashSet ignoredEntities = new IntOpenHashSet(); -+ private final IntOpenHashSet ignoredEntities = new IntOpenHashSet(); -+ - protected AbstractArrow(EntityType p_36717_, Level p_36719_, ItemStack p_312639_) { - super(p_36717_, p_36719_); - this.pickupItemStack = p_312639_.copy(); -@@ -157,7 +_,7 @@ - --this.shakeTime; - } + protected AbstractArrow(EntityType p_332730_, Level p_335646_) { + super(p_332730_, p_335646_); +@@ -167,7 +_,7 @@ + this.shakeTime--; + } -- if (this.isInWaterOrRain() || blockstate.is(Blocks.POWDER_SNOW)) { -+ if (this.isInWaterOrRain() || blockstate.is(Blocks.POWDER_SNOW) || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType))) { - this.clearFire(); - } +- if (this.isInWaterOrRain() || blockstate.is(Blocks.POWDER_SNOW)) { ++ if (this.isInWaterOrRain() || blockstate.is(Blocks.POWDER_SNOW) || this.isInFluidType((fluidType, height) -> this.canFluidExtinguish(fluidType))) { + this.clearFire(); + } -@@ -193,9 +_,28 @@ - } +@@ -203,11 +_,27 @@ + } + } + +- if (hitresult != null && !flag) { +- ProjectileDeflection projectiledeflection = this.hitTargetOrDeflectSelf(hitresult); +- this.hasImpulse = true; +- if (projectiledeflection != ProjectileDeflection.NONE) { +- break; ++ if (hitresult != null && hitresult.getType() != HitResult.Type.MISS && !flag) { ++ switch (net.minecraftforge.event.ForgeEventFactory.onProjectileImpactResult(this, hitresult)) { ++ case SKIP_ENTITY: ++ if (hitresult.getType() != HitResult.Type.ENTITY) { // If there is no entity, we just return default behaviour ++ this.onHit(hitresult); ++ this.hasImpulse = true; ++ break; ++ } ++ ignoredEntities.add(entityhitresult.getEntity().getId()); ++ entityhitresult = null; // Don't process any further ++ break; ++ case STOP_AT_CURRENT_NO_DAMAGE: ++ this.discard(); ++ entityhitresult = null; // Don't process any further ++ break; ++ case STOP_AT_CURRENT: ++ this.setPierceLevel((byte) 0); ++ case DEFAULT: ++ this.onHit(hitresult); ++ this.hasImpulse = true; ++ break; + } + } + +@@ -218,6 +_,9 @@ + hitresult = null; } -- if (hitresult != null && !flag) { -- this.onHit(hitresult); -- this.hasImpulse = true; -+ if (hitresult != null && hitresult.getType() != HitResult.Type.MISS && !flag) { -+ switch (net.minecraftforge.event.ForgeEventFactory.onProjectileImpactResult(this, hitresult)) { -+ case SKIP_ENTITY: -+ if (hitresult.getType() != HitResult.Type.ENTITY) { // If there is no entity, we just return default behaviour -+ this.onHit(hitresult); -+ this.hasImpulse = true; -+ break; -+ } -+ ignoredEntities.add(entityhitresult.getEntity().getId()); -+ entityhitresult = null; // Don't process any further -+ break; -+ case STOP_AT_CURRENT_NO_DAMAGE: -+ this.discard(); -+ entityhitresult = null; // Don't process any further -+ break; -+ case STOP_AT_CURRENT: -+ this.setPierceLevel((byte) 0); -+ case DEFAULT: -+ this.onHit(hitresult); -+ this.hasImpulse = true; -+ break; -+ } - } - - if (entityhitresult == null || this.getPierceLevel() <= 0) { -@@ -205,6 +_,9 @@ - hitresult = null; - } - -+ if (this.isRemoved()) -+ return; ++ if (this.isRemoved()) ++ return; + - vec3 = this.getDeltaMovement(); - double d5 = vec3.x; - double d6 = vec3.y; -@@ -439,7 +_,7 @@ - } + vec3 = this.getDeltaMovement(); + double d5 = vec3.x; + double d6 = vec3.y; +@@ -453,7 +_,7 @@ - protected boolean canHitEntity(Entity p_36743_) { -- return super.canHitEntity(p_36743_) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(p_36743_.getId())); -+ return super.canHitEntity(p_36743_) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(p_36743_.getId())) && !this.ignoredEntities.contains(p_36743_.getId()); - } + @Override + protected boolean canHitEntity(Entity p_36743_) { +- return super.canHitEntity(p_36743_) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(p_36743_.getId())); ++ return super.canHitEntity(p_36743_) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(p_36743_.getId())) && !this.ignoredEntities.contains(p_36743_.getId()); + } - public void addAdditionalSaveData(CompoundTag p_36772_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java.patch index 7a38600e8c..bfae07601a 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java +++ b/net/minecraft/world/entity/projectile/AbstractHurtingProjectile.java -@@ -76,7 +_,7 @@ - } +@@ -89,7 +_,7 @@ + } - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity, this.getClipType()); -- if (hitresult.getType() != HitResult.Type.MISS) { -+ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.onHit(hitresult); - } + HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity, this.getClipType()); +- if (hitresult.getType() != HitResult.Type.MISS) { ++ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { + this.hitTargetOrDeflectSelf(hitresult); + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch index d781853954..6063e70081 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch @@ -1,16 +1,14 @@ --- a/net/minecraft/world/entity/projectile/FireworkRocketEntity.java +++ b/net/minecraft/world/entity/projectile/FireworkRocketEntity.java -@@ -150,6 +_,13 @@ - - } - -+ @Override -+ protected void onHit(HitResult result) { -+ if (result.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, result)) { -+ super.onHit(result); -+ } -+ } +@@ -301,4 +_,11 @@ + private static ItemStack getDefaultItem() { + return new ItemStack(Items.FIREWORK_ROCKET); + } + - private void explode() { - this.level().broadcastEntityEvent(this, (byte)17); - this.gameEvent(GameEvent.EXPLODE, this.getOwner()); ++ @Override ++ protected void onHit(HitResult result) { ++ if (result.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, result)) { ++ super.onHit(result); ++ } ++ } + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch index 6dc4d327d0..56548534a4 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch @@ -1,55 +1,56 @@ --- a/net/minecraft/world/entity/projectile/FishingHook.java +++ b/net/minecraft/world/entity/projectile/FishingHook.java -@@ -229,8 +_,8 @@ - private boolean shouldStopFishing(Player p_37137_) { - ItemStack itemstack = p_37137_.getMainHandItem(); - ItemStack itemstack1 = p_37137_.getOffhandItem(); -- boolean flag = itemstack.is(Items.FISHING_ROD); -- boolean flag1 = itemstack1.is(Items.FISHING_ROD); -+ boolean flag = itemstack.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); -+ boolean flag1 = itemstack1.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); - if (!p_37137_.isRemoved() && p_37137_.isAlive() && (flag || flag1) && !(this.distanceToSqr(p_37137_) > 1024.0D)) { - return false; - } else { -@@ -241,7 +_,7 @@ +@@ -238,8 +_,8 @@ + private boolean shouldStopFishing(Player p_37137_) { + ItemStack itemstack = p_37137_.getMainHandItem(); + ItemStack itemstack1 = p_37137_.getOffhandItem(); +- boolean flag = itemstack.is(Items.FISHING_ROD); +- boolean flag1 = itemstack1.is(Items.FISHING_ROD); ++ boolean flag = itemstack.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); ++ boolean flag1 = itemstack1.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); + if (!p_37137_.isRemoved() && p_37137_.isAlive() && (flag || flag1) && !(this.distanceToSqr(p_37137_) > 1024.0)) { + return false; + } else { +@@ -250,6 +_,7 @@ - private void checkCollision() { - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); -- this.onHit(hitresult); -+ if (hitresult.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) this.onHit(hitresult); - } + private void checkCollision() { + HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); ++ if (hitresult.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) + this.hitTargetOrDeflectSelf(hitresult); + } - protected boolean canHitEntity(Entity p_37135_) { -@@ -403,15 +_,22 @@ - Player player = this.getPlayerOwner(); - if (!this.level().isClientSide && player != null && !this.shouldStopFishing(player)) { - int i = 0; -+ net.minecraftforge.event.entity.player.ItemFishedEvent event = null; - if (this.hookedIn != null) { - this.pullEntity(this.hookedIn); - CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, p_37157_, this, Collections.emptyList()); - this.level().broadcastEntityEvent(this, (byte)31); - i = this.hookedIn instanceof ItemEntity ? 3 : 5; - } else if (this.nibble > 0) { -- LootParams lootparams = (new LootParams.Builder((ServerLevel)this.level())).withParameter(LootContextParams.ORIGIN, this.position()).withParameter(LootContextParams.TOOL, p_37157_).withParameter(LootContextParams.THIS_ENTITY, this).withLuck((float)this.luck + player.getLuck()).create(LootContextParamSets.FISHING); -+ LootParams lootparams = (new LootParams.Builder((ServerLevel)this.level())).withParameter(LootContextParams.ORIGIN, this.position()).withParameter(LootContextParams.TOOL, p_37157_).withParameter(LootContextParams.THIS_ENTITY, this).withParameter(LootContextParams.KILLER_ENTITY, this.getOwner()).withParameter(LootContextParams.THIS_ENTITY, this).withLuck((float)this.luck + player.getLuck()).create(LootContextParamSets.FISHING); - LootTable loottable = this.level().getServer().getLootData().getLootTable(BuiltInLootTables.FISHING); - List list = loottable.getRandomItems(lootparams); -+ event = new net.minecraftforge.event.entity.player.ItemFishedEvent(list, this.onGround() ? 2 : 1, this); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ if (event.isCanceled()) { -+ this.discard(); -+ return event.getRodDamage(); -+ } - CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, p_37157_, this, list); +@@ -439,6 +_,7 @@ + Player player = this.getPlayerOwner(); + if (!this.level().isClientSide && player != null && !this.shouldStopFishing(player)) { + int i = 0; ++ net.minecraftforge.event.entity.player.ItemFishedEvent event = null; + if (this.hookedIn != null) { + this.pullEntity(this.hookedIn); + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, p_37157_, this, Collections.emptyList()); +@@ -449,10 +_,17 @@ + .withParameter(LootContextParams.ORIGIN, this.position()) + .withParameter(LootContextParams.TOOL, p_37157_) + .withParameter(LootContextParams.THIS_ENTITY, this) ++ .withParameter(LootContextParams.KILLER_ENTITY, this.getOwner()) ++ .withParameter(LootContextParams.THIS_ENTITY, this) + .withLuck((float)this.luck + player.getLuck()) + .create(LootContextParamSets.FISHING); + LootTable loottable = this.level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); + List list = loottable.getRandomItems(lootparams); ++ event = net.minecraftforge.event.ForgeEventFactory.onPlayerFishedItem(list, this.onGround() ? 2 : 1, this); ++ if (event.isCanceled()) { ++ this.discard(); ++ return event.getRodDamage(); ++ } + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, p_37157_, this, list); - for(ItemStack itemstack : list) { -@@ -436,7 +_,7 @@ - } + for (ItemStack itemstack : list) { +@@ -482,7 +_,7 @@ + } - this.discard(); -- return i; -+ return event == null ? i : event.getRodDamage(); - } else { - return 0; - } + this.discard(); +- return i; ++ return event == null ? i : event.getRodDamage(); + } else { + return 0; + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/LargeFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/LargeFireball.java.patch index bdde41d4ed..fdc0e0cec9 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/LargeFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/LargeFireball.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/entity/projectile/LargeFireball.java +++ b/net/minecraft/world/entity/projectile/LargeFireball.java -@@ -24,7 +_,8 @@ - protected void onHit(HitResult p_37218_) { - super.onHit(p_37218_); - if (!this.level().isClientSide) { -- boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); -+ // TODO 1.19.3: The creation of Level.ExplosionInteraction means this code path will fire EntityMobGriefingEvent twice. Should we try and fix it? -SS -+ boolean flag = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this.getOwner()); - this.level().explode(this, this.getX(), this.getY(), this.getZ(), (float)this.explosionPower, flag, Level.ExplosionInteraction.MOB); - this.discard(); - } +@@ -25,7 +_,8 @@ + protected void onHit(HitResult p_37218_) { + super.onHit(p_37218_); + if (!this.level().isClientSide) { +- boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); ++ // TODO 1.19.3: The creation of Level.ExplosionInteraction means this code path will fire EntityMobGriefingEvent twice. Should we try and fix it? -SS ++ boolean flag = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), this.getOwner()); + this.level().explode(this, this.getX(), this.getY(), this.getZ(), (float)this.explosionPower, flag, Level.ExplosionInteraction.MOB); + this.discard(); + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch index b5c35ee4c0..74a47b9478 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch @@ -1,10 +1,12 @@ --- a/net/minecraft/world/entity/projectile/LlamaSpit.java +++ b/net/minecraft/world/entity/projectile/LlamaSpit.java -@@ -29,6 +_,7 @@ - super.tick(); - Vec3 vec3 = this.getDeltaMovement(); - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); -+ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) - this.onHit(hitresult); - double d0 = this.getX() + vec3.x; - double d1 = this.getY() + vec3.y; +@@ -39,7 +_,8 @@ + super.tick(); + Vec3 vec3 = this.getDeltaMovement(); + HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); +- this.hitTargetOrDeflectSelf(hitresult); ++ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) ++ this.hitTargetOrDeflectSelf(hitresult); + double d0 = this.getX() + vec3.x; + double d1 = this.getY() + vec3.y; + double d2 = this.getZ() + vec3.z; diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch index ba17b28441..eac92992b3 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/Projectile.java +++ b/net/minecraft/world/entity/projectile/Projectile.java -@@ -229,7 +_,7 @@ - if (entity instanceof Player) { - return entity.mayInteract(p_150167_, p_150168_); - } else { -- return entity == null || p_150167_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); -+ return entity == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_150167_, entity); - } - } +@@ -265,7 +_,7 @@ + @Override + public boolean mayInteract(Level p_150167_, BlockPos p_150168_) { + Entity entity = this.getOwner(); +- return entity instanceof Player ? entity.mayInteract(p_150167_, p_150168_) : entity == null || p_150167_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); ++ return entity instanceof Player ? entity.mayInteract(p_150167_, p_150168_) : entity == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_150167_, entity); + } + public boolean mayBreak(Level p_313184_) { diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch index 62aa22700e..12ae3ea748 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/world/entity/projectile/ProjectileUtil.java +++ b/net/minecraft/world/entity/projectile/ProjectileUtil.java -@@ -77,7 +_,7 @@ - Vec3 vec31 = optional.get(); - double d1 = p_37289_.distanceToSqr(vec31); - if (d1 < d0 || d0 == 0.0D) { -- if (entity1.getRootVehicle() == p_37288_.getRootVehicle()) { -+ if (entity1.getRootVehicle() == p_37288_.getRootVehicle() && !entity1.canRiderInteract()) { - if (d0 == 0.0D) { - entity = entity1; - vec3 = vec31; -@@ -147,8 +_,13 @@ - } - } +@@ -79,7 +_,7 @@ + Vec3 vec31 = optional.get(); + double d1 = p_37289_.distanceToSqr(vec31); + if (d1 < d0 || d0 == 0.0) { +- if (entity1.getRootVehicle() == p_37288_.getRootVehicle()) { ++ if (entity1.getRootVehicle() == p_37288_.getRootVehicle() && !entity1.canRiderInteract()) { + if (d0 == 0.0) { + entity = entity1; + vec3 = vec31; +@@ -151,8 +_,13 @@ + } + } -+ @Deprecated // Forge: Use the version below that takes in a Predicate instead of an Item - public static InteractionHand getWeaponHoldingHand(LivingEntity p_37298_, Item p_37299_) { - return p_37298_.getMainHandItem().is(p_37299_) ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; -+ } ++ @Deprecated + public static InteractionHand getWeaponHoldingHand(LivingEntity p_37298_, Item p_37299_) { + return p_37298_.getMainHandItem().is(p_37299_) ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; ++ } + -+ public static InteractionHand getWeaponHoldingHand(LivingEntity livingEntity, Predicate itemPredicate) { -+ return itemPredicate.test(livingEntity.getMainHandItem().getItem()) ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - } ++ public static InteractionHand getWeaponHoldingHand(LivingEntity livingEntity, Predicate itemPredicate) { ++ return itemPredicate.test(livingEntity.getMainHandItem().getItem()) ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; + } - public static AbstractArrow getMobArrow(LivingEntity p_37301_, ItemStack p_37302_, float p_37303_) { + public static AbstractArrow getMobArrow(LivingEntity p_37301_, ItemStack p_37302_, float p_37303_) { diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch index cb808aa817..3234346084 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/ShulkerBullet.java +++ b/net/minecraft/world/entity/projectile/ShulkerBullet.java -@@ -212,7 +_,7 @@ - } +@@ -219,7 +_,7 @@ + } - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); -- if (hitresult.getType() != HitResult.Type.MISS) { -+ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.onHit(hitresult); - } - } + HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); +- if (hitresult.getType() != HitResult.Type.MISS) { ++ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { + this.hitTargetOrDeflectSelf(hitresult); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/SmallFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/SmallFireball.java.patch index 986dce07ce..fbf1188026 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/SmallFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/SmallFireball.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/SmallFireball.java +++ b/net/minecraft/world/entity/projectile/SmallFireball.java -@@ -46,7 +_,7 @@ - super.onHitBlock(p_37384_); - if (!this.level().isClientSide) { - Entity entity = this.getOwner(); -- if (!(entity instanceof Mob) || this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (!(entity instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), entity)) { - BlockPos blockpos = p_37384_.getBlockPos().relative(p_37384_.getDirection()); - if (this.level().isEmptyBlock(blockpos)) { - this.level().setBlockAndUpdate(blockpos, BaseFireBlock.getState(this.level(), blockpos)); +@@ -47,7 +_,7 @@ + super.onHitBlock(p_37384_); + if (!this.level().isClientSide) { + Entity entity = this.getOwner(); +- if (!(entity instanceof Mob) || this.level().getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (!(entity instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this.level(), entity)) { + BlockPos blockpos = p_37384_.getBlockPos().relative(p_37384_.getDirection()); + if (this.level().isEmptyBlock(blockpos)) { + this.level().setBlockAndUpdate(blockpos, BaseFireBlock.getState(this.level(), blockpos)); diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch index e7fc026fa0..69cb0bea27 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/ThrowableProjectile.java +++ b/net/minecraft/world/entity/projectile/ThrowableProjectile.java -@@ -58,7 +_,7 @@ - } - } +@@ -60,7 +_,7 @@ + } + } -- if (hitresult.getType() != HitResult.Type.MISS && !flag) { -+ if (hitresult.getType() != HitResult.Type.MISS && !flag && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.onHit(hitresult); - } +- if (hitresult.getType() != HitResult.Type.MISS && !flag) { ++ if (hitresult.getType() != HitResult.Type.MISS && !flag && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { + this.hitTargetOrDeflectSelf(hitresult); + } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ThrownEnderpearl.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ThrownEnderpearl.java.patch index 336111901c..d343ec0f81 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ThrownEnderpearl.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ThrownEnderpearl.java.patch @@ -1,39 +1,39 @@ --- a/net/minecraft/world/entity/projectile/ThrownEnderpearl.java +++ b/net/minecraft/world/entity/projectile/ThrownEnderpearl.java -@@ -48,6 +_,8 @@ - if (entity instanceof ServerPlayer) { - ServerPlayer serverplayer = (ServerPlayer)entity; - if (serverplayer.connection.isAcceptingMessages() && serverplayer.level() == this.level() && !serverplayer.isSleeping()) { -+ net.minecraftforge.event.entity.EntityTeleportEvent.EnderPearl event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(serverplayer, this.getX(), this.getY(), this.getZ(), this, 5.0F, p_37504_); -+ if (!event.isCanceled()) { // Don't indent to lower patch size - if (this.random.nextFloat() < 0.05F && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)) { - Endermite endermite = EntityType.ENDERMITE.create(this.level()); - if (endermite != null) { -@@ -62,9 +_,11 @@ - entity.teleportTo(this.getX(), this.getY(), this.getZ()); - } +@@ -58,6 +_,8 @@ + Entity entity = this.getOwner(); + if (entity instanceof ServerPlayer serverplayer) { + if (serverplayer.connection.isAcceptingMessages() && serverplayer.level() == this.level() && !serverplayer.isSleeping()) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(serverplayer, this.getX(), this.getY(), this.getZ(), this, 5.0F, p_37504_); ++ if (!event.isCanceled()) { // Don't indent to lower patch size + if (this.random.nextFloat() < 0.05F && this.level().getGameRules().getBoolean(GameRules.RULE_DOMOBSPAWNING)) { + Endermite endermite = EntityType.ENDERMITE.create(this.level()); + if (endermite != null) { +@@ -72,9 +_,11 @@ + entity.teleportTo(this.getX(), this.getY(), this.getZ()); + } -+ entity.teleportTo(event.getTargetX(), event.getTargetY(), event.getTargetZ()); - entity.resetFallDistance(); -- entity.hurt(this.damageSources().fall(), 5.0F); - this.level().playSound((Player)null, this.getX(), this.getY(), this.getZ(), SoundEvents.PLAYER_TELEPORT, SoundSource.PLAYERS); -+ entity.hurt(this.damageSources().fall(), event.getAttackDamage()); -+ } //Forge: End - } - } else if (entity != null) { - entity.teleportTo(this.getX(), this.getY(), this.getZ()); -@@ -87,12 +_,12 @@ - } ++ entity.teleportTo(event.getTargetX(), event.getTargetY(), event.getTargetZ()); + entity.resetFallDistance(); +- entity.hurt(this.damageSources().fall(), 5.0F); + this.level().playSound(null, this.getX(), this.getY(), this.getZ(), SoundEvents.PLAYER_TELEPORT, SoundSource.PLAYERS); ++ entity.hurt(this.damageSources().fall(), event.getAttackDamage()); ++ } //Forge: End + } + } else if (entity != null) { + entity.teleportTo(this.getX(), this.getY(), this.getZ()); +@@ -97,12 +_,12 @@ - @Nullable -- public Entity changeDimension(ServerLevel p_37506_) { -+ public Entity changeDimension(ServerLevel p_37506_, net.minecraftforge.common.util.ITeleporter teleporter) { - Entity entity = this.getOwner(); - if (entity != null && entity.level().dimension() != p_37506_.dimension()) { - this.setOwner((Entity)null); - } + @Nullable + @Override +- public Entity changeDimension(ServerLevel p_37506_) { ++ public Entity changeDimension(ServerLevel p_37506_, net.minecraftforge.common.util.ITeleporter teleporter) { + Entity entity = this.getOwner(); + if (entity != null && entity.level().dimension() != p_37506_.dimension()) { + this.setOwner(null); + } -- return super.changeDimension(p_37506_); -+ return super.changeDimension(p_37506_, teleporter); - } +- return super.changeDimension(p_37506_); ++ return super.changeDimension(p_37506_, teleporter); + } } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/WitherSkull.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/WitherSkull.java.patch index 8e9f3c05c1..19188424ff 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/WitherSkull.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/WitherSkull.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/WitherSkull.java +++ b/net/minecraft/world/entity/projectile/WitherSkull.java -@@ -41,7 +_,7 @@ - } +@@ -44,7 +_,7 @@ - public float getBlockExplosionResistance(Explosion p_37619_, BlockGetter p_37620_, BlockPos p_37621_, BlockState p_37622_, FluidState p_37623_, float p_37624_) { -- return this.isDangerous() && WitherBoss.canDestroy(p_37622_) ? Math.min(0.8F, p_37624_) : p_37624_; -+ return this.isDangerous() && p_37622_.canEntityDestroy(p_37620_, p_37621_, this) ? Math.min(0.8F, p_37624_) : p_37624_; - } + @Override + public float getBlockExplosionResistance(Explosion p_37619_, BlockGetter p_37620_, BlockPos p_37621_, BlockState p_37622_, FluidState p_37623_, float p_37624_) { +- return this.isDangerous() && WitherBoss.canDestroy(p_37622_) ? Math.min(0.8F, p_37624_) : p_37624_; ++ return this.isDangerous() && p_37622_.canEntityDestroy(p_37620_, p_37621_, this) ? Math.min(0.8F, p_37624_) : p_37624_; + } - protected void onHitEntity(EntityHitResult p_37626_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch b/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch index 17c1b30834..873820d1af 100644 --- a/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/world/entity/raid/Raid.java +++ b/net/minecraft/world/entity/raid/Raid.java -@@ -816,7 +_,7 @@ - } - } +@@ -836,7 +_,7 @@ + } + } -- static enum RaiderType { -+ public static enum RaiderType implements net.minecraftforge.common.IExtensibleEnum { - VINDICATOR(EntityType.VINDICATOR, new int[]{0, 0, 2, 0, 1, 4, 2, 5}), - EVOKER(EntityType.EVOKER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}), - PILLAGER(EntityType.PILLAGER, new int[]{0, 4, 3, 3, 4, 4, 4, 2}), -@@ -830,6 +_,20 @@ - private RaiderType(EntityType p_37821_, int[] p_37822_) { - this.entityType = p_37821_; - this.spawnsPerWaveBeforeBonus = p_37822_; -+ } -+ -+ /** -+ * The waveCountsIn integer decides how many entities of the EntityType defined in typeIn will spawn in each wave. -+ * For example, one ravager will always spawn in wave 3. -+ */ -+ public static RaiderType create(String name, EntityType typeIn, int[] waveCountsIn) { -+ throw new IllegalStateException("Enum not extended"); -+ } -+ -+ @Override -+ @Deprecated -+ public void init() { -+ VALUES = values(); - } - } +- static enum RaiderType { ++ static enum RaiderType implements net.minecraftforge.common.IExtensibleEnum { + VINDICATOR(EntityType.VINDICATOR, new int[]{0, 0, 2, 0, 1, 4, 2, 5}), + EVOKER(EntityType.EVOKER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}), + PILLAGER(EntityType.PILLAGER, new int[]{0, 4, 3, 3, 4, 4, 4, 2}), +@@ -850,6 +_,20 @@ + private RaiderType(final EntityType p_37821_, final int[] p_37822_) { + this.entityType = p_37821_; + this.spawnsPerWaveBeforeBonus = p_37822_; ++ } ++ ++ /** ++ * The waveCountsIn integer decides how many entities of the EntityType defined in typeIn will spawn in each wave. ++ * For example, one ravager will always spawn in wave 3. ++ */ ++ public static RaiderType create(String name, EntityType typeIn, int[] waveCountsIn) { ++ throw new IllegalStateException("Enum not extended"); ++ } ++ ++ @Override ++ @Deprecated ++ public void init() { ++ VALUES = values(); + } + } } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecart.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecart.java.patch index 0325d1b3ac..de8a55f201 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecart.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecart.java.patch @@ -1,247 +1,251 @@ --- a/net/minecraft/world/entity/vehicle/AbstractMinecart.java +++ b/net/minecraft/world/entity/vehicle/AbstractMinecart.java -@@ -46,7 +_,7 @@ +@@ -45,7 +_,7 @@ + import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; - import org.joml.Vector3f; -public abstract class AbstractMinecart extends VehicleEntity { +public abstract class AbstractMinecart extends VehicleEntity implements net.minecraftforge.common.extensions.IForgeAbstractMinecart { - private static final float LOWERED_PASSENGER_ATTACHMENT_Y = 0.0F; - private static final float PASSENGER_ATTACHMENT_Y = 0.1875F; - private static final EntityDataAccessor DATA_ID_DISPLAY_BLOCK = SynchedEntityData.defineId(AbstractMinecart.class, EntityDataSerializers.INT); -@@ -83,6 +_,8 @@ - p_38135_.put(RailShape.NORTH_WEST, Pair.of(vec3i2, vec3i)); - p_38135_.put(RailShape.NORTH_EAST, Pair.of(vec3i2, vec3i1)); - }); -+ private static net.minecraftforge.common.IMinecartCollisionHandler COLLISIONS = null; -+ private boolean canBePushed = true; + private static final Vec3 LOWERED_PASSENGER_ATTACHMENT = new Vec3(0.0, 0.0, 0.0); + private static final EntityDataAccessor DATA_ID_DISPLAY_BLOCK = SynchedEntityData.defineId(AbstractMinecart.class, EntityDataSerializers.INT); + private static final EntityDataAccessor DATA_ID_DISPLAY_OFFSET = SynchedEntityData.defineId(AbstractMinecart.class, EntityDataSerializers.INT); +@@ -83,6 +_,7 @@ + p_38135_.put(RailShape.NORTH_WEST, Pair.of(vec3i2, vec3i)); + p_38135_.put(RailShape.NORTH_EAST, Pair.of(vec3i2, vec3i1)); + }); ++ private boolean canBePushed = true; - protected AbstractMinecart(EntityType p_38087_, Level p_38088_) { - super(p_38087_, p_38088_); -@@ -97,6 +_,14 @@ - this.zo = p_38094_; - } + protected AbstractMinecart(EntityType p_38087_, Level p_38088_) { + super(p_38087_, p_38088_); +@@ -139,7 +_,7 @@ -+ public net.minecraftforge.common.IMinecartCollisionHandler getCollisionHandler() { -+ return COLLISIONS; -+ } -+ -+ public static void registerCollisionHandler(@Nullable net.minecraftforge.common.IMinecartCollisionHandler handler) { -+ COLLISIONS = handler; -+ } -+ - public static AbstractMinecart createMinecart(ServerLevel p_310486_, double p_38121_, double p_38122_, double p_38123_, AbstractMinecart.Type p_38124_, ItemStack p_311363_, @Nullable Player p_310754_) { - Object object; - switch (p_38124_) { -@@ -143,7 +_,7 @@ - } + @Override + public boolean isPushable() { +- return true; ++ return canBePushed; + } - public boolean isPushable() { -- return true; -+ return canBePushed; - } - - protected Vec3 getRelativePortalPosition(Direction.Axis p_38132_, BlockUtil.FoundRectangle p_38133_) { -@@ -265,9 +_,9 @@ - BlockPos blockpos = new BlockPos(k, i, j); - BlockState blockstate = this.level().getBlockState(blockpos); - this.onRails = BaseRailBlock.isRail(blockstate); -- if (this.onRails) { -+ if (canUseRail() && this.onRails) { - this.moveAlongTrack(blockpos, blockstate); -- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { -+ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { - this.activateMinecart(k, i, j, blockstate.getValue(PoweredRailBlock.POWERED)); + @Override +@@ -271,9 +_,9 @@ + BlockPos blockpos = new BlockPos(i, j, k); + BlockState blockstate = this.level().getBlockState(blockpos); + this.onRails = BaseRailBlock.isRail(blockstate); +- if (this.onRails) { ++ if (canUseRail() && this.onRails) { + this.moveAlongTrack(blockpos, blockstate); +- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { ++ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { + this.activateMinecart(i, j, k, blockstate.getValue(PoweredRailBlock.POWERED)); + } + } else { +@@ -298,8 +_,11 @@ } - } else { -@@ -292,8 +_,11 @@ - } - this.setRot(this.getYRot(), this.getXRot()); -- if (this.getMinecartType() == AbstractMinecart.Type.RIDEABLE && this.getDeltaMovement().horizontalDistanceSqr() > 0.01D) { -- List list = this.level().getEntities(this, this.getBoundingBox().inflate((double)0.2F, 0.0D, (double)0.2F), EntitySelector.pushableBy(this)); -+ AABB box; -+ if (getCollisionHandler() != null) box = getCollisionHandler().getMinecartCollisionBox(this); -+ else box = this.getBoundingBox().inflate(0.2F, 0.0D, 0.2F); -+ if (canBeRidden() && this.getDeltaMovement().horizontalDistanceSqr() > 0.01D) { -+ List list = this.level().getEntities(this, box, EntitySelector.pushableBy(this)); - if (!list.isEmpty()) { - for(Entity entity1 : list) { - if (!(entity1 instanceof Player) && !(entity1 instanceof IronGolem) && !(entity1 instanceof AbstractMinecart) && !this.isVehicle() && !entity1.isPassenger()) { -@@ -304,7 +_,7 @@ - } + this.setRot(this.getYRot(), this.getXRot()); +- if (this.getMinecartType() == AbstractMinecart.Type.RIDEABLE && this.getDeltaMovement().horizontalDistanceSqr() > 0.01) { +- List list = this.level().getEntities(this, this.getBoundingBox().inflate(0.2F, 0.0, 0.2F), EntitySelector.pushableBy(this)); ++ AABB box; ++ if (getCollisionHandler() != null) box = getCollisionHandler().getMinecartCollisionBox(this); ++ else box = this.getBoundingBox().inflate(0.2F, 0.0D, 0.2F); ++ if (canBeRidden() && this.getDeltaMovement().horizontalDistanceSqr() > 0.01D) { ++ List list = this.level().getEntities(this, box, EntitySelector.pushableBy(this)); + if (!list.isEmpty()) { + for (Entity entity1 : list) { + if (!(entity1 instanceof Player) +@@ -314,7 +_,7 @@ + } + } + } else { +- for (Entity entity : this.level().getEntities(this, this.getBoundingBox().inflate(0.2F, 0.0, 0.2F))) { ++ for (Entity entity : this.level().getEntities(this, box)) { + if (!this.hasPassenger(entity) && entity.isPushable() && entity instanceof AbstractMinecart) { + entity.push(this); + } +@@ -339,16 +_,24 @@ + } + + protected void comeOffTrack() { +- double d0 = this.getMaxSpeed(); ++ double d0 = this.onGround() ? this.getMaxSpeed() : getMaxSpeedAirLateral(); + Vec3 vec3 = this.getDeltaMovement(); + this.setDeltaMovement(Mth.clamp(vec3.x, -d0, d0), vec3.y, Mth.clamp(vec3.z, -d0, d0)); + if (this.onGround()) { + this.setDeltaMovement(this.getDeltaMovement().scale(0.5)); + } + ++ if (getMaxSpeedAirVertical() > 0 && getDeltaMovement().y > getMaxSpeedAirVertical()) { ++ if (Math.abs(getDeltaMovement().x) < 0.3f && Math.abs(getDeltaMovement().z) < 0.3f) { ++ setDeltaMovement(new Vec3(getDeltaMovement().x, 0.15f, getDeltaMovement().z)); ++ } else { ++ setDeltaMovement(new Vec3(getDeltaMovement().x, getMaxSpeedAirVertical(), getDeltaMovement().z)); ++ } ++ } ++ + this.move(MoverType.SELF, this.getDeltaMovement()); + if (!this.onGround()) { +- this.setDeltaMovement(this.getDeltaMovement().scale(0.95)); ++ this.setDeltaMovement(this.getDeltaMovement().scale(getDragAir())); + } + } + +@@ -361,18 +_,19 @@ + d1 = (double)p_38156_.getY(); + boolean flag = false; + boolean flag1 = false; +- if (p_38157_.is(Blocks.POWERED_RAIL)) { ++ BaseRailBlock baserailblock = (BaseRailBlock) p_38157_.getBlock(); ++ if (baserailblock instanceof PoweredRailBlock power && !power.isActivatorRail()) { + flag = p_38157_.getValue(PoweredRailBlock.POWERED); + flag1 = !flag; + } + +- double d3 = 0.0078125; ++ double d3 = getSlopeAdjustment(); + if (this.isInWater()) { + d3 *= 0.2; + } + + Vec3 vec31 = this.getDeltaMovement(); +- RailShape railshape = p_38157_.getValue(((BaseRailBlock)p_38157_.getBlock()).getShapeProperty()); ++ RailShape railshape = baserailblock.getRailDirection(p_38157_, this.level(), p_38156_, this); + switch (railshape) { + case ASCENDING_EAST: + this.setDeltaMovement(vec31.add(-d3, 0.0, 0.0)); +@@ -418,7 +_,7 @@ } - } else { -- for(Entity entity : this.level().getEntities(this, this.getBoundingBox().inflate((double)0.2F, 0.0D, (double)0.2F))) { -+ for(Entity entity : this.level().getEntities(this, box)) { - if (!this.hasPassenger(entity) && entity.isPushable() && entity instanceof AbstractMinecart) { - entity.push(this); - } -@@ -329,16 +_,23 @@ - } + } - protected void comeOffTrack() { -- double d0 = this.getMaxSpeed(); -+ double d0 = this.onGround() ? this.getMaxSpeed() : getMaxSpeedAirLateral(); - Vec3 vec3 = this.getDeltaMovement(); - this.setDeltaMovement(Mth.clamp(vec3.x, -d0, d0), vec3.y, Mth.clamp(vec3.z, -d0, d0)); - if (this.onGround()) { - this.setDeltaMovement(this.getDeltaMovement().scale(0.5D)); - } +- if (flag1) { ++ if (flag1 && shouldDoRailFunctions()) { + double d22 = this.getDeltaMovement().horizontalDistance(); + if (d22 < 0.03) { + this.setDeltaMovement(Vec3.ZERO); +@@ -447,10 +_,7 @@ + d0 = d23 + d4 * d14; + d2 = d10 + d5 * d14; + this.setPos(d0, d1, d2); +- double d24 = this.isVehicle() ? 0.75 : 1.0; +- double d25 = this.getMaxSpeed(); +- vec31 = this.getDeltaMovement(); +- this.move(MoverType.SELF, new Vec3(Mth.clamp(d24 * vec31.x, -d25, d25), 0.0, Mth.clamp(d24 * vec31.z, -d25, d25))); ++ this.moveMinecartOnRail(p_38156_); + if (vec3i.getY() != 0 + && Mth.floor(this.getX()) - p_38156_.getX() == vec3i.getX() + && Mth.floor(this.getZ()) - p_38156_.getZ() == vec3i.getZ()) { +@@ -482,7 +_,11 @@ + this.setDeltaMovement(d26 * (double)(j - p_38156_.getX()), vec35.y, d26 * (double)(i - p_38156_.getZ())); + } -+ if (getMaxSpeedAirVertical() > 0 && getDeltaMovement().y > getMaxSpeedAirVertical()) { -+ if(Math.abs(getDeltaMovement().x) < 0.3f && Math.abs(getDeltaMovement().z) < 0.3f) -+ setDeltaMovement(new Vec3(getDeltaMovement().x, 0.15f, getDeltaMovement().z)); -+ else -+ setDeltaMovement(new Vec3(getDeltaMovement().x, getMaxSpeedAirVertical(), getDeltaMovement().z)); -+ } +- if (flag) { ++ if (shouldDoRailFunctions()) { ++ baserailblock.onMinecartPass(p_38157_, level(), p_38156_, this); ++ } + - this.move(MoverType.SELF, this.getDeltaMovement()); - if (!this.onGround()) { -- this.setDeltaMovement(this.getDeltaMovement().scale(0.95D)); -+ this.setDeltaMovement(this.getDeltaMovement().scale(getDragAir())); - } ++ if (flag && shouldDoRailFunctions()) { + Vec3 vec36 = this.getDeltaMovement(); + double d27 = vec36.horizontalDistance(); + if (d27 > 0.01) { +@@ -546,7 +_,7 @@ - } -@@ -352,18 +_,19 @@ - d1 = (double)p_38156_.getY(); - boolean flag = false; - boolean flag1 = false; -- if (p_38157_.is(Blocks.POWERED_RAIL)) { -+ BaseRailBlock baserailblock = (BaseRailBlock) p_38157_.getBlock(); -+ if (baserailblock instanceof PoweredRailBlock && !((PoweredRailBlock) baserailblock).isActivatorRail()) { - flag = p_38157_.getValue(PoweredRailBlock.POWERED); - flag1 = !flag; - } + BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); + if (BaseRailBlock.isRail(blockstate)) { +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this); + p_38098_ = (double)j; + if (railshape.isAscending()) { + p_38098_ = (double)(j + 1); +@@ -585,7 +_,7 @@ -- double d3 = 0.0078125D; -+ double d3 = getSlopeAdjustment(); - if (this.isInWater()) { - d3 *= 0.2D; - } + BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); + if (BaseRailBlock.isRail(blockstate)) { +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this); + Pair pair = exits(railshape); + Vec3i vec3i = pair.getFirst(); + Vec3i vec3i1 = pair.getSecond(); +@@ -649,6 +_,10 @@ - Vec3 vec31 = this.getDeltaMovement(); -- RailShape railshape = p_38157_.getValue(((BaseRailBlock)p_38157_.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)p_38157_.getBlock()).getRailDirection(p_38157_, this.level(), p_38156_, this); - switch (railshape) { - case ASCENDING_EAST: - this.setDeltaMovement(vec31.add(-d3, 0.0D, 0.0D)); -@@ -409,7 +_,7 @@ - } - } + @Override + public void push(Entity p_38165_) { ++ if (getCollisionHandler() != null) { ++ getCollisionHandler().onEntityCollision(this, p_38165_); ++ return; ++ } + if (!this.level().isClientSide) { + if (!p_38165_.noPhysics && !this.noPhysics) { + if (!this.hasPassenger(p_38165_)) { +@@ -670,7 +_,7 @@ + d1 *= 0.1F; + d0 *= 0.5; + d1 *= 0.5; +- if (p_38165_ instanceof AbstractMinecart) { ++ if (p_38165_ instanceof AbstractMinecart oMinecart) { + double d4 = p_38165_.getX() - this.getX(); + double d5 = p_38165_.getZ() - this.getZ(); + Vec3 vec3 = new Vec3(d4, 0.0, d5).normalize(); +@@ -687,12 +_,11 @@ -- if (flag1) { -+ if (flag1 && shouldDoRailFunctions()) { - double d22 = this.getDeltaMovement().horizontalDistance(); - if (d22 < 0.03D) { - this.setDeltaMovement(Vec3.ZERO); -@@ -438,10 +_,7 @@ - d0 = d23 + d4 * d14; - d2 = d10 + d5 * d14; - this.setPos(d0, d1, d2); -- double d24 = this.isVehicle() ? 0.75D : 1.0D; -- double d25 = this.getMaxSpeed(); -- vec31 = this.getDeltaMovement(); -- this.move(MoverType.SELF, new Vec3(Mth.clamp(d24 * vec31.x, -d25, d25), 0.0D, Mth.clamp(d24 * vec31.z, -d25, d25))); -+ this.moveMinecartOnRail(p_38156_); - if (vec3i.getY() != 0 && Mth.floor(this.getX()) - p_38156_.getX() == vec3i.getX() && Mth.floor(this.getZ()) - p_38156_.getZ() == vec3i.getZ()) { - this.setPos(this.getX(), this.getY() + (double)vec3i.getY(), this.getZ()); - } else if (vec3i1.getY() != 0 && Mth.floor(this.getX()) - p_38156_.getX() == vec3i1.getX() && Mth.floor(this.getZ()) - p_38156_.getZ() == vec3i1.getZ()) { -@@ -469,7 +_,10 @@ - this.setDeltaMovement(d26 * (double)(j - p_38156_.getX()), vec35.y, d26 * (double)(i - p_38156_.getZ())); - } - -- if (flag) { -+ if (shouldDoRailFunctions()) -+ baserailblock.onMinecartPass(p_38157_, level(), p_38156_, this); + Vec3 vec32 = this.getDeltaMovement(); + Vec3 vec33 = p_38165_.getDeltaMovement(); +- if (((AbstractMinecart)p_38165_).getMinecartType() == AbstractMinecart.Type.FURNACE && this.getMinecartType() != AbstractMinecart.Type.FURNACE) { ++ if (oMinecart.isPoweredCart() && !this.isPoweredCart()) { + this.setDeltaMovement(vec32.multiply(0.2, 1.0, 0.2)); + this.push(vec33.x - d0, 0.0, vec33.z - d1); + p_38165_.setDeltaMovement(vec33.multiply(0.95, 1.0, 0.95)); +- } else if (((AbstractMinecart)p_38165_).getMinecartType() != AbstractMinecart.Type.FURNACE +- && this.getMinecartType() == AbstractMinecart.Type.FURNACE) { ++ } else if (!oMinecart.isPoweredCart() && this.isPoweredCart()) { + p_38165_.setDeltaMovement(vec33.multiply(0.2, 1.0, 0.2)); + p_38165_.push(vec32.x + d0, 0.0, vec32.z + d1); + this.setDeltaMovement(vec32.multiply(0.95, 1.0, 0.95)); +@@ -802,6 +_,50 @@ + case HOPPER -> Items.HOPPER_MINECART; + case COMMAND_BLOCK -> Items.COMMAND_BLOCK_MINECART; + }); ++ } + -+ if (flag && shouldDoRailFunctions()) { - Vec3 vec36 = this.getDeltaMovement(); - double d27 = vec36.horizontalDistance(); - if (d27 > 0.01D) { -@@ -533,7 +_,7 @@ - - BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); - if (BaseRailBlock.isRail(blockstate)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this); - p_38098_ = (double)j; - if (railshape.isAscending()) { - p_38098_ = (double)(j + 1); -@@ -572,7 +_,7 @@ - - BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); - if (BaseRailBlock.isRail(blockstate)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this); - Pair pair = exits(railshape); - Vec3i vec3i = pair.getFirst(); - Vec3i vec3i1 = pair.getSecond(); -@@ -634,6 +_,10 @@ - } - - public void push(Entity p_38165_) { -+ if (getCollisionHandler() != null) { -+ getCollisionHandler().onEntityCollision(this, p_38165_); -+ return; -+ } - if (!this.level().isClientSide) { - if (!p_38165_.noPhysics && !this.noPhysics) { - if (!this.hasPassenger(p_38165_)) { -@@ -667,11 +_,11 @@ - - Vec3 vec32 = this.getDeltaMovement(); - Vec3 vec33 = p_38165_.getDeltaMovement(); -- if (((AbstractMinecart)p_38165_).getMinecartType() == AbstractMinecart.Type.FURNACE && this.getMinecartType() != AbstractMinecart.Type.FURNACE) { -+ if (((AbstractMinecart)p_38165_).isPoweredCart() && !this.isPoweredCart()) { - this.setDeltaMovement(vec32.multiply(0.2D, 1.0D, 0.2D)); - this.push(vec33.x - d0, 0.0D, vec33.z - d1); - p_38165_.setDeltaMovement(vec33.multiply(0.95D, 1.0D, 0.95D)); -- } else if (((AbstractMinecart)p_38165_).getMinecartType() != AbstractMinecart.Type.FURNACE && this.getMinecartType() == AbstractMinecart.Type.FURNACE) { -+ } else if (!((AbstractMinecart)p_38165_).isPoweredCart() && this.isPoweredCart()) { - p_38165_.setDeltaMovement(vec33.multiply(0.2D, 1.0D, 0.2D)); - p_38165_.push(vec32.x + d0, 0.0D, vec32.z + d1); - this.setDeltaMovement(vec32.multiply(0.95D, 1.0D, 0.95D)); -@@ -764,6 +_,42 @@ - public void setCustomDisplay(boolean p_38139_) { - this.getEntityData().set(DATA_ID_CUSTOM_DISPLAY, p_38139_); - } + -+ // Forge Start -+ private boolean canUseRail = true; -+ @Override public boolean canUseRail() { return canUseRail; } -+ @Override public void setCanUseRail(boolean value) { this.canUseRail = value; } -+ private float currentSpeedCapOnRail = getMaxCartSpeedOnRail(); -+ @Override public float getCurrentCartSpeedCapOnRail() { return currentSpeedCapOnRail; } -+ @Override public void setCurrentCartSpeedCapOnRail(float value) { currentSpeedCapOnRail = Math.min(value, getMaxCartSpeedOnRail()); } -+ @org.jetbrains.annotations.Nullable private Float maxSpeedAirLateral = null; -+ @Override public float getMaxSpeedAirLateral() { return maxSpeedAirLateral == null ? (float) this.getMaxSpeed() : maxSpeedAirLateral; } -+ @Override public void setMaxSpeedAirLateral(float value) { maxSpeedAirLateral = value; } -+ private float maxSpeedAirVertical = DEFAULT_MAX_SPEED_AIR_VERTICAL; -+ @Override public float getMaxSpeedAirVertical() { return maxSpeedAirVertical; } -+ @Override public void setMaxSpeedAirVertical(float value) { maxSpeedAirVertical = value; } -+ private double dragAir = DEFAULT_AIR_DRAG; -+ @Override public double getDragAir() { return dragAir; } -+ @Override public void setDragAir(double value) { dragAir = value; } -+ @Override -+ public double getMaxSpeedWithRail() { //Non-default because getMaximumSpeed is protected -+ if (!canUseRail()) return getMaxSpeed(); -+ BlockPos pos = this.getCurrentRailPosition(); -+ BlockState state = this.level().getBlockState(pos); -+ if (!state.is(BlockTags.RAILS)) return getMaxSpeed(); ++ private static net.minecraftforge.common.IMinecartCollisionHandler COLLISIONS = null; ++ public net.minecraftforge.common.IMinecartCollisionHandler getCollisionHandler() { return COLLISIONS; } ++ public static void registerCollisionHandler(@Nullable net.minecraftforge.common.IMinecartCollisionHandler handler) { COLLISIONS = handler; } ++ private boolean canUseRail = true; ++ @Override public boolean canUseRail() { return canUseRail; } ++ @Override public void setCanUseRail(boolean value) { this.canUseRail = value; } ++ private float currentSpeedCapOnRail = getMaxCartSpeedOnRail(); ++ @Override public float getCurrentCartSpeedCapOnRail() { return currentSpeedCapOnRail; } ++ @Override public void setCurrentCartSpeedCapOnRail(float value) { currentSpeedCapOnRail = Math.min(value, getMaxCartSpeedOnRail()); } ++ private Float maxSpeedAirLateral = null; ++ @Override public float getMaxSpeedAirLateral() { return maxSpeedAirLateral == null ? (float)this.getMaxSpeed() : maxSpeedAirLateral; } ++ @Override public void setMaxSpeedAirLateral(float value) { maxSpeedAirLateral = value; } ++ private float maxSpeedAirVertical = DEFAULT_MAX_SPEED_AIR_VERTICAL; ++ @Override public float getMaxSpeedAirVertical() { return maxSpeedAirVertical; } ++ @Override public void setMaxSpeedAirVertical(float value) { maxSpeedAirVertical = value; } ++ private double dragAir = DEFAULT_AIR_DRAG; ++ @Override public double getDragAir() { return dragAir; } ++ @Override public void setDragAir(double value) { dragAir = value; } ++ @Override ++ public double getMaxSpeedWithRail() { //Non-default because getMaximumSpeed is protected ++ if (!canUseRail()) { ++ return getMaxSpeed(); ++ } ++ BlockPos pos = this.getCurrentRailPosition(); ++ BlockState state = this.level().getBlockState(pos); + -+ float railMaxSpeed = ((BaseRailBlock)state.getBlock()).getRailMaxSpeed(state, this.level(), pos, this); -+ return Math.min(railMaxSpeed, getCurrentCartSpeedCapOnRail()); -+ } -+ @Override -+ public void moveMinecartOnRail(BlockPos pos) { //Non-default because getMaximumSpeed is protected -+ AbstractMinecart mc = this; -+ double d24 = mc.isVehicle() ? 0.75D : 1.0D; -+ double d25 = mc.getMaxSpeedWithRail(); -+ Vec3 vec3d1 = mc.getDeltaMovement(); -+ mc.move(MoverType.SELF, new Vec3(Mth.clamp(d24 * vec3d1.x, -d25, d25), 0.0D, Mth.clamp(d24 * vec3d1.z, -d25, d25))); -+ } -+ // Forge end ++ if (!state.is(BlockTags.RAILS)) { ++ return getMaxSpeed(); ++ } ++ ++ float railMaxSpeed = ((BaseRailBlock)state.getBlock()).getRailMaxSpeed(state, this.level(), pos, this); ++ return Math.min(railMaxSpeed, getCurrentCartSpeedCapOnRail()); ++ } ++ ++ @Override ++ public void moveMinecartOnRail(BlockPos pos) { //Non-default because getMaximumSpeed is protected ++ AbstractMinecart mc = this; ++ double d24 = mc.isVehicle() ? 0.75D : 1.0D; ++ double d25 = mc.getMaxSpeedWithRail(); ++ Vec3 vec3d1 = mc.getDeltaMovement(); ++ mc.move(MoverType.SELF, new Vec3(Mth.clamp(d24 * vec3d1.x, -d25, d25), 0.0D, Mth.clamp(d24 * vec3d1.z, -d25, d25))); + } - public ItemStack getPickResult() { - Item item; + public static enum Type { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java.patch index 93e786e5ab..d02a4f38ba 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java.patch @@ -1,40 +1,39 @@ --- a/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java +++ b/net/minecraft/world/entity/vehicle/AbstractMinecartContainer.java -@@ -82,6 +_,8 @@ - } +@@ -95,6 +_,8 @@ - public InteractionResult interact(Player p_38232_, InteractionHand p_38233_) { -+ InteractionResult ret = super.interact(p_38232_, p_38233_); -+ if (ret.consumesAction()) return ret; - return this.interactWithContainerVehicle(p_38232_); - } + @Override + public InteractionResult interact(Player p_38232_, InteractionHand p_38233_) { ++ var ret = super.interact(p_38232_, p_38233_); ++ if (ret.consumesAction()) return ret; + return this.interactWithContainerVehicle(p_38232_); + } -@@ -119,6 +_,28 @@ - } - - protected abstract AbstractContainerMenu createMenu(int p_38222_, Inventory p_38223_); +@@ -165,5 +_,27 @@ + @Override + public void clearItemStacks() { + this.itemStacks = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); ++ } + -+ // Forge Start -+ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); ++ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) -+ return itemHandler.cast(); -+ return super.getCapability(capability, facing); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { ++ return itemHandler.cast(); ++ } ++ return super.getCapability(capability, facing); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ itemHandler.invalidate(); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ itemHandler.invalidate(); ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); -+ } - - @Nullable - public ResourceLocation getLootTable() { ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/Boat.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/Boat.java.patch index 11b0a10397..9eb6d9ba4a 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/Boat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/Boat.java.patch @@ -1,82 +1,82 @@ --- a/net/minecraft/world/entity/vehicle/Boat.java +++ b/net/minecraft/world/entity/vehicle/Boat.java -@@ -52,7 +_,7 @@ +@@ -51,7 +_,7 @@ + import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; - import org.joml.Vector3f; -public class Boat extends VehicleEntity implements VariantHolder { -+public class Boat extends VehicleEntity implements net.minecraftforge.common.extensions.IForgeBoat { - private static final EntityDataAccessor DATA_ID_TYPE = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.INT); - private static final EntityDataAccessor DATA_ID_PADDLE_LEFT = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.BOOLEAN); - private static final EntityDataAccessor DATA_ID_PADDLE_RIGHT = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.BOOLEAN); -@@ -450,7 +_,7 @@ - for(int i2 = i1; i2 < j1; ++i2) { - blockpos$mutableblockpos.set(l1, k1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidstate)) { - f = Math.max(f, fluidstate.getHeight(this.level(), blockpos$mutableblockpos)); - } ++public class Boat extends VehicleEntity implements VariantHolder, net.minecraftforge.common.extensions.IForgeBoat { + private static final EntityDataAccessor DATA_ID_TYPE = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.INT); + private static final EntityDataAccessor DATA_ID_PADDLE_LEFT = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.BOOLEAN); + private static final EntityDataAccessor DATA_ID_PADDLE_RIGHT = SynchedEntityData.defineId(Boat.class, EntityDataSerializers.BOOLEAN); +@@ -471,7 +_,7 @@ + for (int i2 = i1; i2 < j1; i2++) { + blockpos$mutableblockpos.set(l1, k1, i2); + FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); +- if (fluidstate.is(FluidTags.WATER)) { ++ if (this.canBoatInFluid(fluidstate)) { + f = Math.max(f, fluidstate.getHeight(this.level(), blockpos$mutableblockpos)); + } -@@ -491,7 +_,7 @@ - blockpos$mutableblockpos.set(l1, k2, i2); - BlockState blockstate = this.level().getBlockState(blockpos$mutableblockpos); - if (!(blockstate.getBlock() instanceof WaterlilyBlock) && Shapes.joinIsNotEmpty(blockstate.getCollisionShape(this.level(), blockpos$mutableblockpos).move((double)l1, (double)k2, (double)i2), voxelshape, BooleanOp.AND)) { -- f += blockstate.getBlock().getFriction(); -+ f += blockstate.getFriction(this.level(), blockpos$mutableblockpos, this); - ++k1; - } - } -@@ -520,7 +_,7 @@ - for(int i2 = i1; i2 < j1; ++i2) { - blockpos$mutableblockpos.set(k1, l1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidstate)) { - float f = (float)l1 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos); - this.waterLevel = Math.max((double)f, this.waterLevel); - flag |= aabb.minY < (double)f; -@@ -550,7 +_,7 @@ - for(int i2 = i1; i2 < j1; ++i2) { - blockpos$mutableblockpos.set(k1, l1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER) && d0 < (double)((float)blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos))) { -+ if (this.canBoatInFluid(fluidstate) && d0 < (double)((float)blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos))) { - if (!fluidstate.isSource()) { - return Boat.Status.UNDER_FLOWING_WATER; - } -@@ -752,7 +_,7 @@ +@@ -517,7 +_,7 @@ + voxelshape, + BooleanOp.AND + )) { +- f += blockstate.getBlock().getFriction(); ++ f += blockstate.getFriction(this.level(), blockpos$mutableblockpos, this); + k1++; + } + } +@@ -546,7 +_,7 @@ + for (int i2 = i1; i2 < j1; i2++) { + blockpos$mutableblockpos.set(k1, l1, i2); + FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); +- if (fluidstate.is(FluidTags.WATER)) { ++ if (this.canBoatInFluid(fluidstate)) { + float f = (float)l1 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos); + this.waterLevel = Math.max((double)f, this.waterLevel); + flag |= aabb.minY < (double)f; +@@ -576,7 +_,7 @@ + for (int i2 = i1; i2 < j1; i2++) { + blockpos$mutableblockpos.set(k1, l1, i2); + FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); +- if (fluidstate.is(FluidTags.WATER) ++ if (this.canBoatInFluid(fluidstate) + && d0 < (double)((float)blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos))) { + if (!fluidstate.isSource()) { + return Boat.Status.UNDER_FLOWING_WATER; +@@ -794,7 +_,7 @@ + } + + this.resetFallDistance(); +- } else if (!this.level().getFluidState(this.blockPosition().below()).is(FluidTags.WATER) && p_38307_ < 0.0) { ++ } else if (!this.canBoatInFluid(this.level().getFluidState(this.blockPosition().below())) && p_38307_ < 0.0) { + this.fallDistance -= (float)p_38307_; } + } +@@ -826,7 +_,7 @@ - this.resetFallDistance(); -- } else if (!this.level().getFluidState(this.blockPosition().below()).is(FluidTags.WATER) && p_38307_ < 0.0D) { -+ } else if (!this.canBoatInFluid(this.level().getFluidState(this.blockPosition().below())) && p_38307_ < 0.0D) { - this.fallDistance -= (float)p_38307_; - } + @Override + protected boolean canAddPassenger(Entity p_38390_) { +- return this.getPassengers().size() < this.getMaxPassengers() && !this.isEyeInFluid(FluidTags.WATER); ++ return this.getPassengers().size() < this.getMaxPassengers() && !this.canBoatInFluid(this.getEyeInFluidType()); + } -@@ -784,7 +_,7 @@ - } - - protected boolean canAddPassenger(Entity p_38390_) { -- return this.getPassengers().size() < this.getMaxPassengers() && !this.isEyeInFluid(FluidTags.WATER); -+ return this.getPassengers().size() < this.getMaxPassengers() && !this.canBoatInFluid(this.getEyeInFluidType()); - } - - protected int getMaxPassengers() { -@@ -817,6 +_,16 @@ - - public boolean isUnderWater() { - return this.status == Boat.Status.UNDER_WATER || this.status == Boat.Status.UNDER_FLOWING_WATER; -+ } + protected int getMaxPassengers() { +@@ -859,6 +_,16 @@ + @Override + public ItemStack getPickResult() { + return new ItemStack(this.getDropItem()); ++ } + -+ // Forge: Fix MC-119811 by instantly completing lerp on board -+ @Override -+ protected void addPassenger(Entity passenger) { -+ super.addPassenger(passenger); -+ if (this.isControlledByLocalInstance() && this.lerpSteps > 0) { -+ this.lerpSteps = 0; -+ this.absMoveTo(this.lerpX, this.lerpY, this.lerpZ, (float)this.lerpYRot, (float)this.lerpXRot); -+ } - } ++ // Forge: Fix MC-119811 by instantly completing lerp on board ++ @Override ++ protected void addPassenger(Entity passenger) { ++ super.addPassenger(passenger); ++ if (this.isControlledByLocalInstance() && this.lerpSteps > 0) { ++ this.lerpSteps = 0; ++ this.absMoveTo(this.lerpX, this.lerpY, this.lerpZ, (float)this.lerpYRot, (float)this.lerpXRot); ++ } + } - public ItemStack getPickResult() { + public static enum Status { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/ChestBoat.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/ChestBoat.java.patch index 786822896c..88d426b0f6 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/ChestBoat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/ChestBoat.java.patch @@ -1,31 +1,29 @@ --- a/net/minecraft/world/entity/vehicle/ChestBoat.java +++ b/net/minecraft/world/entity/vehicle/ChestBoat.java -@@ -204,6 +_,28 @@ - this.itemStacks = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); - } - -+ // Forge Start -+ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); +@@ -213,4 +_,26 @@ + public void stopOpen(Player p_270286_) { + this.level().gameEvent(GameEvent.CONTAINER_CLOSE, this.position(), GameEvent.Context.of(p_270286_)); + } + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) -+ return itemHandler.cast(); -+ return super.getCapability(capability, facing); -+ } ++ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ itemHandler.invalidate(); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.isAlive()) { ++ return itemHandler.cast(); ++ } ++ return super.getCapability(capability, facing); ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ itemHandler.invalidate(); ++ } + - public void stopOpen(Player p_270286_) { - this.level().gameEvent(GameEvent.CONTAINER_CLOSE, this.position(), GameEvent.Context.of(p_270286_)); - } ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this)); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch index 925b7f6d23..d9d498b5e6 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/entity/vehicle/ContainerEntity.java +++ b/net/minecraft/world/entity/vehicle/ContainerEntity.java -@@ -103,6 +_,9 @@ +@@ -107,6 +_,9 @@ - this.setLootTable((ResourceLocation)null); - LootParams.Builder lootparams$builder = (new LootParams.Builder((ServerLevel)this.level())).withParameter(LootContextParams.ORIGIN, this.position()); -+ // Forge: set the chest to killer_entity for loot context. -+ if (this instanceof AbstractMinecartContainer entityContainer) -+ lootparams$builder.withParameter(LootContextParams.KILLER_ENTITY, entityContainer); - if (p_219950_ != null) { - lootparams$builder.withLuck(p_219950_.getLuck()).withParameter(LootContextParams.THIS_ENTITY, p_219950_); - } + this.setLootTable(null); + LootParams.Builder lootparams$builder = new LootParams.Builder((ServerLevel)this.level()).withParameter(LootContextParams.ORIGIN, this.position()); ++ // Forge: set the chest to killer_entity for loot context. ++ if (this instanceof AbstractMinecartContainer entityContainer) ++ lootparams$builder.withParameter(LootContextParams.KILLER_ENTITY, entityContainer); + if (p_219950_ != null) { + lootparams$builder.withLuck(p_219950_.getLuck()).withParameter(LootContextParams.THIS_ENTITY, p_219950_); + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/Minecart.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/Minecart.java.patch index 14c1e8ff9b..dcdbc9be2f 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/Minecart.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/Minecart.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/vehicle/Minecart.java +++ b/net/minecraft/world/entity/vehicle/Minecart.java -@@ -18,6 +_,8 @@ - } +@@ -19,6 +_,8 @@ - public InteractionResult interact(Player p_38483_, InteractionHand p_38484_) { -+ InteractionResult ret = super.interact(p_38483_, p_38484_); -+ if (ret.consumesAction()) return ret; - if (p_38483_.isSecondaryUseActive()) { - return InteractionResult.PASS; - } else if (this.isVehicle()) { + @Override + public InteractionResult interact(Player p_38483_, InteractionHand p_38484_) { ++ InteractionResult ret = super.interact(p_38483_, p_38484_); ++ if (ret.consumesAction()) return ret; + if (p_38483_.isSecondaryUseActive()) { + return InteractionResult.PASS; + } else if (this.isVehicle()) { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java.patch index af5e32889f..fa2e6954e2 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java +++ b/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java -@@ -78,6 +_,8 @@ - } +@@ -85,6 +_,8 @@ - public InteractionResult interact(Player p_38522_, InteractionHand p_38523_) { -+ InteractionResult ret = super.interact(p_38522_, p_38523_); -+ if (ret.consumesAction()) return ret; - return this.commandBlock.usedBy(p_38522_); - } + @Override + public InteractionResult interact(Player p_38522_, InteractionHand p_38523_) { ++ InteractionResult ret = super.interact(p_38522_, p_38523_); ++ if (ret.consumesAction()) return ret; + return this.commandBlock.usedBy(p_38522_); + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartFurnace.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartFurnace.java.patch index 093013f6a9..2f7d0ce506 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartFurnace.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartFurnace.java.patch @@ -1,23 +1,22 @@ --- a/net/minecraft/world/entity/vehicle/MinecartFurnace.java +++ b/net/minecraft/world/entity/vehicle/MinecartFurnace.java -@@ -110,6 +_,8 @@ - } +@@ -116,6 +_,8 @@ - public InteractionResult interact(Player p_38562_, InteractionHand p_38563_) { -+ InteractionResult ret = super.interact(p_38562_, p_38563_); -+ if (ret.consumesAction()) return ret; - ItemStack itemstack = p_38562_.getItemInHand(p_38563_); - if (INGREDIENT.test(itemstack) && this.fuel + 3600 <= 32000) { - if (!p_38562_.getAbilities().instabuild) { -@@ -125,6 +_,11 @@ - } - - return InteractionResult.sidedSuccess(this.level().isClientSide); -+ } + @Override + public InteractionResult interact(Player p_38562_, InteractionHand p_38563_) { ++ var ret = super.interact(p_38562_, p_38563_); ++ if (ret.consumesAction()) return ret; + ItemStack itemstack = p_38562_.getItemInHand(p_38563_); + if (INGREDIENT.test(itemstack) && this.fuel + 3600 <= 32000) { + itemstack.consume(1, p_38562_); +@@ -157,5 +_,10 @@ + @Override + public BlockState getDefaultDisplayBlockState() { + return Blocks.FURNACE.defaultBlockState().setValue(FurnaceBlock.FACING, Direction.NORTH).setValue(FurnaceBlock.LIT, Boolean.valueOf(this.hasFuel())); ++ } + -+ @Override -+ public float getMaxCartSpeedOnRail() { -+ return 0.2f; - } - - protected void addAdditionalSaveData(CompoundTag p_38567_) { ++ @Override ++ public float getMaxCartSpeedOnRail() { ++ return 0.2f; + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartSpawner.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartSpawner.java.patch index cc2e4b770b..9390a84e57 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/MinecartSpawner.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/vehicle/MinecartSpawner.java +++ b/net/minecraft/world/entity/vehicle/MinecartSpawner.java -@@ -16,6 +_,12 @@ - public void broadcastEvent(Level p_150342_, BlockPos p_150343_, int p_150344_) { - p_150342_.broadcastEntityEvent(MinecartSpawner.this, (byte)p_150344_); - } +@@ -17,6 +_,12 @@ + public void broadcastEvent(Level p_150342_, BlockPos p_150343_, int p_150344_) { + p_150342_.broadcastEntityEvent(MinecartSpawner.this, (byte)p_150344_); + } + -+ @Override -+ @org.jetbrains.annotations.Nullable -+ public net.minecraft.world.entity.Entity getSpawnerEntity() { -+ return MinecartSpawner.this; -+ } - }; - private final Runnable ticker; ++ @Override ++ @org.jetbrains.annotations.Nullable ++ public net.minecraft.world.entity.Entity getSpawnerEntity() { ++ return MinecartSpawner.this; ++ } + }; + private final Runnable ticker; diff --git a/patches/minecraft/net/minecraft/world/food/FoodData.java.patch b/patches/minecraft/net/minecraft/world/food/FoodData.java.patch deleted file mode 100644 index 40953dd7ec..0000000000 --- a/patches/minecraft/net/minecraft/world/food/FoodData.java.patch +++ /dev/null @@ -1,19 +0,0 @@ ---- a/net/minecraft/world/food/FoodData.java -+++ b/net/minecraft/world/food/FoodData.java -@@ -23,9 +_,15 @@ - this.saturationLevel = Math.min(this.saturationLevel + (float)p_38708_ * p_38709_ * 2.0F, (float)this.foodLevel); - } - -+ // Use the LivingEntity sensitive version in favour of this. -+ @Deprecated - public void eat(Item p_38713_, ItemStack p_38714_) { -+ this.eat(p_38713_, p_38714_, null); -+ } -+ -+ public void eat(Item p_38713_, ItemStack p_38714_, @org.jetbrains.annotations.Nullable net.minecraft.world.entity.LivingEntity entity) { - if (p_38713_.isEdible()) { -- FoodProperties foodproperties = p_38713_.getFoodProperties(); -+ FoodProperties foodproperties = p_38714_.getFoodProperties(entity); - this.eat(foodproperties.getNutrition(), foodproperties.getSaturationModifier()); - } - diff --git a/patches/minecraft/net/minecraft/world/food/FoodProperties.java.patch b/patches/minecraft/net/minecraft/world/food/FoodProperties.java.patch deleted file mode 100644 index 12bf1ac78b..0000000000 --- a/patches/minecraft/net/minecraft/world/food/FoodProperties.java.patch +++ /dev/null @@ -1,73 +0,0 @@ ---- a/net/minecraft/world/food/FoodProperties.java -+++ b/net/minecraft/world/food/FoodProperties.java -@@ -11,15 +_,26 @@ - private final boolean isMeat; - private final boolean canAlwaysEat; - private final boolean fastFood; -- private final List> effects; -- -+ private final List, Float>> effects; -+ -+ private FoodProperties(FoodProperties.Builder builder) { -+ this.nutrition = builder.nutrition; -+ this.saturationModifier = builder.saturationModifier; -+ this.isMeat = builder.isMeat; -+ this.canAlwaysEat = builder.canAlwaysEat; -+ this.fastFood = builder.fastFood; -+ this.effects = builder.effects; -+ } -+ -+ // Forge: Use builder method instead -+ @Deprecated - FoodProperties(int p_38730_, float p_38731_, boolean p_38732_, boolean p_38733_, boolean p_38734_, List> p_38735_) { - this.nutrition = p_38730_; - this.saturationModifier = p_38731_; - this.isMeat = p_38732_; - this.canAlwaysEat = p_38733_; - this.fastFood = p_38734_; -- this.effects = p_38735_; -+ this.effects = p_38735_.stream().map(pair -> Pair., Float>of(pair::getFirst, pair.getSecond())).collect(java.util.stream.Collectors.toList()); - } - - public int getNutrition() { -@@ -43,7 +_,7 @@ - } - - public List> getEffects() { -- return this.effects; -+ return this.effects.stream().map(pair -> Pair.of(pair.getFirst() != null ? pair.getFirst().get() : null, pair.getSecond())).collect(java.util.stream.Collectors.toList()); - } - - public static class Builder { -@@ -52,7 +_,7 @@ - private boolean isMeat; - private boolean canAlwaysEat; - private boolean fastFood; -- private final List> effects = Lists.newArrayList(); -+ private final List, Float>> effects = Lists.newArrayList(); - - public FoodProperties.Builder nutrition(int p_38761_) { - this.nutrition = p_38761_; -@@ -79,13 +_,20 @@ - return this; - } - -+ public FoodProperties.Builder effect(java.util.function.Supplier effectIn, float probability) { -+ this.effects.add(Pair.of(effectIn, probability)); -+ return this; -+ } -+ -+ // Forge: Use supplier method instead -+ @Deprecated - public FoodProperties.Builder effect(MobEffectInstance p_38763_, float p_38764_) { -- this.effects.add(Pair.of(p_38763_, p_38764_)); -+ this.effects.add(Pair.of(() -> p_38763_, p_38764_)); - return this; - } - - public FoodProperties build() { -- return new FoodProperties(this.nutrition, this.saturationModifier, this.isMeat, this.canAlwaysEat, this.fastFood, this.effects); -+ return new FoodProperties(this); - } - } - } diff --git a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch index bb6a0e6576..5a650fd72b 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch @@ -1,48 +1,19 @@ --- a/net/minecraft/world/inventory/AbstractContainerMenu.java +++ b/net/minecraft/world/inventory/AbstractContainerMenu.java -@@ -229,6 +_,8 @@ - ItemStack itemstack1 = p_150438_.get(); - this.remoteSlots.set(p_150436_, itemstack1); - if (this.synchronizer != null) { -+ // Forge: Only synchronize a slot change if the itemstack actually changed in a way that is relevant to the client (i.e. share tag changed) -+ if (!p_150437_.equals(itemstack, true)) - this.synchronizer.sendSlotChange(this, p_150436_, itemstack1); - } - } @@ -401,6 +_,7 @@ - ItemStack itemstack10 = this.getCarried(); - p_150434_.updateTutorialInventoryAction(itemstack10, slot7.getItem(), clickaction); - if (!this.tryItemClickBehaviourOverride(p_150434_, clickaction, slot7, itemstack9, itemstack10)) { -+ if (!net.minecraftforge.common.ForgeHooks.onItemStackedOn(itemstack9, itemstack10, slot7, clickaction, p_150434_, createCarriedSlotAccess())) - if (itemstack9.isEmpty()) { - if (!itemstack10.isEmpty()) { - int i3 = clickaction == ClickAction.PRIMARY ? itemstack10.getCount() : 1; -@@ -610,14 +_,15 @@ - ItemStack itemstack = slot.getItem(); - if (!itemstack.isEmpty() && ItemStack.isSameItemSameTags(p_38904_, itemstack)) { - int j = itemstack.getCount() + p_38904_.getCount(); -- if (j <= p_38904_.getMaxStackSize()) { -+ int maxSize = Math.min(slot.getMaxStackSize(), p_38904_.getMaxStackSize()); -+ if (j <= maxSize) { - p_38904_.setCount(0); - itemstack.setCount(j); - slot.setChanged(); - flag = true; -- } else if (itemstack.getCount() < p_38904_.getMaxStackSize()) { -- p_38904_.shrink(p_38904_.getMaxStackSize() - itemstack.getCount()); -- itemstack.setCount(p_38904_.getMaxStackSize()); -+ } else if (itemstack.getCount() < maxSize) { -+ p_38904_.shrink(maxSize - itemstack.getCount()); -+ itemstack.setCount(maxSize); - slot.setChanged(); - flag = true; - } -@@ -718,7 +_,7 @@ - i = 1; - break; - case 2: -- i = p_279172_.getItem().getMaxStackSize(); -+ i = p_279172_.getMaxStackSize(); - break; - default: - i = p_279172_.getCount(); + ItemStack itemstack10 = this.getCarried(); + p_150434_.updateTutorialInventoryAction(itemstack10, slot7.getItem(), clickaction); + if (!this.tryItemClickBehaviourOverride(p_150434_, clickaction, slot7, itemstack9, itemstack10)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onItemStackedOn(itemstack9, itemstack10, slot7, clickaction, p_150434_, createCarriedSlotAccess())) + if (itemstack9.isEmpty()) { + if (!itemstack10.isEmpty()) { + int i3 = clickaction == ClickAction.PRIMARY ? itemstack10.getCount() : 1; +@@ -598,7 +_,7 @@ + ItemStack itemstack = slot.getItem(); + if (!itemstack.isEmpty() && ItemStack.isSameItemSameComponents(p_38904_, itemstack)) { + int j = itemstack.getCount() + p_38904_.getCount(); +- int k = slot.getMaxStackSize(itemstack); ++ int k = Math.min(slot.getMaxStackSize(itemstack), itemstack.getMaxStackSize()); + if (j <= k) { + p_38904_.setCount(0); + itemstack.setCount(j); diff --git a/patches/minecraft/net/minecraft/world/inventory/AbstractFurnaceMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AbstractFurnaceMenu.java.patch index cec1796714..dfcc8d9f22 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AbstractFurnaceMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AbstractFurnaceMenu.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/inventory/AbstractFurnaceMenu.java +++ b/net/minecraft/world/inventory/AbstractFurnaceMenu.java -@@ -149,7 +_,7 @@ - } +@@ -167,7 +_,7 @@ + } - protected boolean isFuel(ItemStack p_38989_) { -- return AbstractFurnaceBlockEntity.isFuel(p_38989_); -+ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_38989_, this.recipeType) > 0; - } + protected boolean isFuel(ItemStack p_38989_) { +- return AbstractFurnaceBlockEntity.isFuel(p_38989_); ++ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_38989_, this.recipeType) > 0; + } - public float getBurnProgress() { + public float getBurnProgress() { diff --git a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch index e6b78a8857..11ac3053a0 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch @@ -1,51 +1,54 @@ --- a/net/minecraft/world/inventory/AnvilMenu.java +++ b/net/minecraft/world/inventory/AnvilMenu.java -@@ -71,6 +_,8 @@ - p_150474_.giveExperienceLevels(-this.cost.get()); - } +@@ -79,6 +_,8 @@ + p_150474_.giveExperienceLevels(-this.cost.get()); + } -+ float breakChance = net.minecraftforge.common.ForgeHooks.onAnvilRepair(p_150474_, p_150475_, AnvilMenu.this.inputSlots.getItem(0), AnvilMenu.this.inputSlots.getItem(1)); ++ float breakChance = net.minecraftforge.event.ForgeEventFactory.onAnvilRepair(p_150474_, p_150475_, AnvilMenu.this.inputSlots.getItem(0), AnvilMenu.this.inputSlots.getItem(1)).getBreakChance(); + - this.inputSlots.setItem(0, ItemStack.EMPTY); - if (this.repairItemCountCost > 0) { - ItemStack itemstack = this.inputSlots.getItem(1); -@@ -87,7 +_,7 @@ - this.cost.set(0); - this.access.execute((p_150479_, p_150480_) -> { - BlockState blockstate = p_150479_.getBlockState(p_150480_); -- if (!p_150474_.getAbilities().instabuild && blockstate.is(BlockTags.ANVIL) && p_150474_.getRandom().nextFloat() < 0.12F) { -+ if (!p_150474_.getAbilities().instabuild && blockstate.is(BlockTags.ANVIL) && p_150474_.getRandom().nextFloat() < breakChance) { - BlockState blockstate1 = AnvilBlock.damage(blockstate); - if (blockstate1 == null) { - p_150479_.removeBlock(p_150480_, false); -@@ -118,8 +_,11 @@ - Map map = EnchantmentHelper.getEnchantments(itemstack1); - j += itemstack.getBaseRepairCost() + (itemstack2.isEmpty() ? 0 : itemstack2.getBaseRepairCost()); - this.repairItemCountCost = 0; -+ boolean flag = false; + this.inputSlots.setItem(0, ItemStack.EMPTY); + if (this.repairItemCountCost > 0) { + ItemStack itemstack = this.inputSlots.getItem(1); +@@ -95,7 +_,7 @@ + this.cost.set(0); + this.access.execute((p_150479_, p_150480_) -> { + BlockState blockstate = p_150479_.getBlockState(p_150480_); +- if (!p_150474_.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && p_150474_.getRandom().nextFloat() < 0.12F) { ++ if (!p_150474_.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && p_150474_.getRandom().nextFloat() < breakChance) { + BlockState blockstate1 = AnvilBlock.damage(blockstate); + if (blockstate1 == null) { + p_150479_.removeBlock(p_150480_, false); +@@ -124,8 +_,11 @@ + j += (long)itemstack.getOrDefault(DataComponents.REPAIR_COST, Integer.valueOf(0)).intValue() + + (long)itemstack2.getOrDefault(DataComponents.REPAIR_COST, Integer.valueOf(0)).intValue(); + this.repairItemCountCost = 0; ++ boolean flag = false; + -+ if (!net.minecraftforge.common.ForgeHooks.onAnvilChange(this, itemstack, itemstack2, resultSlots, itemName, j, this.player)) return; - if (!itemstack2.isEmpty()) { -- boolean flag = itemstack2.is(Items.ENCHANTED_BOOK) && !EnchantedBookItem.getEnchantments(itemstack2).isEmpty(); -+ flag = itemstack2.getItem() == Items.ENCHANTED_BOOK && !EnchantedBookItem.getEnchantments(itemstack2).isEmpty(); - if (itemstack1.isDamageableItem() && itemstack1.getItem().isValidRepairItem(itemstack, itemstack2)) { - int l2 = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); - if (l2 <= 0) { -@@ -236,6 +_,7 @@ - i += k; - itemstack1.resetHoverName(); - } -+ if (flag && !itemstack1.isBookEnchantable(itemstack2)) itemstack1 = ItemStack.EMPTY; ++ if (!net.minecraftforge.common.ForgeHooks.onAnvilChange(this, itemstack, itemstack2, resultSlots, itemName, j, this.player)) return; + if (!itemstack2.isEmpty()) { +- boolean flag = itemstack2.has(DataComponents.STORED_ENCHANTMENTS); ++ flag = itemstack2.has(DataComponents.STORED_ENCHANTMENTS); + if (itemstack1.isDamageableItem() && itemstack1.getItem().isValidRepairItem(itemstack, itemstack2)) { + int l2 = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); + if (l2 <= 0) { +@@ -229,6 +_,10 @@ + itemstack1.remove(DataComponents.CUSTOM_NAME); + } - this.cost.set(j + i); - if (i <= 0) { -@@ -301,5 +_,9 @@ - - public int getCost() { - return this.cost.get(); -+ } ++ if (flag && !itemstack1.isBookEnchantable(itemstack2)) { ++ itemstack1 = ItemStack.EMPTY; ++ } + -+ public void setMaximumCost(int value) { -+ this.cost.set(value); - } + int k2 = (int)Mth.clamp(j + (long)i, 0L, 2147483647L); + this.cost.set(k2); + if (i <= 0) { +@@ -297,5 +_,9 @@ + + public int getCost() { + return this.cost.get(); ++ } ++ ++ public void setMaximumCost(int value) { ++ this.cost.set(value); + } } diff --git a/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch index e62c8ef871..8df10e8f26 100644 --- a/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/inventory/BeaconMenu.java +++ b/net/minecraft/world/inventory/BeaconMenu.java -@@ -93,10 +_,8 @@ - } +@@ -98,10 +_,8 @@ + } - slot.onQuickCraft(itemstack1, itemstack); -- } else if (!this.paymentSlot.hasItem() && this.paymentSlot.mayPlace(itemstack1) && itemstack1.getCount() == 1) { -- if (!this.moveItemStackTo(itemstack1, 0, 1, false)) { -- return ItemStack.EMPTY; -- } -+ } else if (this.moveItemStackTo(itemstack1, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. -+ return ItemStack.EMPTY; - } else if (p_39052_ >= 1 && p_39052_ < 28) { - if (!this.moveItemStackTo(itemstack1, 28, 37, false)) { - return ItemStack.EMPTY; + slot.onQuickCraft(itemstack1, itemstack); +- } else if (!this.paymentSlot.hasItem() && this.paymentSlot.mayPlace(itemstack1) && itemstack1.getCount() == 1) { +- if (!this.moveItemStackTo(itemstack1, 0, 1, false)) { +- return ItemStack.EMPTY; +- } ++ } else if (this.moveItemStackTo(itemstack1, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. ++ return ItemStack.EMPTY; + } else if (p_39052_ >= 1 && p_39052_ < 28) { + if (!this.moveItemStackTo(itemstack1, 28, 37, false)) { + return ItemStack.EMPTY; diff --git a/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch index d9b267fabd..70e03e6a56 100644 --- a/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch @@ -1,37 +1,56 @@ --- a/net/minecraft/world/inventory/BrewingStandMenu.java +++ b/net/minecraft/world/inventory/BrewingStandMenu.java -@@ -75,7 +_,7 @@ - if (!this.moveItemStackTo(itemstack1, 3, 4, false)) { - return ItemStack.EMPTY; - } -- } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(itemstack) && itemstack.getCount() == 1) { -+ } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(itemstack)) { - if (!this.moveItemStackTo(itemstack1, 0, 3, false)) { - return ItemStack.EMPTY; - } -@@ -146,7 +_,7 @@ - } +@@ -41,9 +_,9 @@ + this.brewingStand = p_39095_; + this.brewingStandData = p_39096_; + PotionBrewing potionbrewing = p_39094_.player.level().potionBrewing(); +- this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 0, 56, 51)); +- this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 1, 79, 58)); +- this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 2, 102, 51)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 0, 56, 51, potionbrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 1, 79, 58, potionbrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(p_39095_, 2, 102, 51, potionbrewing)); + this.ingredientSlot = this.addSlot(new BrewingStandMenu.IngredientsSlot(potionbrewing, p_39095_, 3, 79, 17)); + this.addSlot(new BrewingStandMenu.FuelSlot(p_39095_, 4, 17, 17)); + this.addDataSlots(p_39096_); +@@ -80,7 +_,7 @@ + if (!this.moveItemStackTo(itemstack1, 3, 4, false)) { + return ItemStack.EMPTY; + } +- } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(itemstack)) { ++ } else if (this.slots.get(0).mayPlace(itemstack)) { // Forge: Use the slot's place which goes through custom recipes. + if (!this.moveItemStackTo(itemstack1, 0, 3, false)) { + return ItemStack.EMPTY; + } +@@ -157,12 +_,23 @@ + } - public boolean mayPlace(ItemStack p_39121_) { -- return PotionBrewing.isIngredient(p_39121_); -+ return net.minecraftforge.common.brewing.BrewingRecipeRegistry.isValidIngredient(p_39121_); - } + public static class PotionSlot extends Slot { ++ private final PotionBrewing potionBrewing; ++ ++ /** @deprecated Use the one that specifes a PotionBrewing */ + public PotionSlot(Container p_39123_, int p_39124_, int p_39125_, int p_39126_) { ++ this(p_39123_, p_39124_, p_39125_, p_39126_, null); ++ } ++ ++ public PotionSlot(Container p_39123_, int p_39124_, int p_39125_, int p_39126_, PotionBrewing potionBrewing) { + super(p_39123_, p_39124_, p_39125_, p_39126_); ++ this.potionBrewing = potionBrewing; + } - public int getMaxStackSize() { -@@ -170,6 +_,7 @@ - public void onTake(Player p_150499_, ItemStack p_150500_) { - Potion potion = PotionUtils.getPotion(p_150500_); - if (p_150499_ instanceof ServerPlayer) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerBrewedPotion(p_150499_, p_150500_); - CriteriaTriggers.BREWED_POTION.trigger((ServerPlayer)p_150499_, potion.builtInRegistryHolder()); - } + @Override + public boolean mayPlace(ItemStack p_39132_) { ++ if (this.potionBrewing != null) { ++ return this.potionBrewing.isValidInput(p_39132_); ++ } + return mayPlaceItem(p_39132_); + } -@@ -177,7 +_,7 @@ - } +@@ -175,6 +_,7 @@ + public void onTake(Player p_150499_, ItemStack p_150500_) { + Optional> optional = p_150500_.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (optional.isPresent() && p_150499_ instanceof ServerPlayer serverplayer) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerBrewedPotion(p_150499_, p_150500_); + CriteriaTriggers.BREWED_POTION.trigger(serverplayer, optional.get()); + } - public static boolean mayPlaceItem(ItemStack p_39134_) { -- return p_39134_.is(Items.POTION) || p_39134_.is(Items.SPLASH_POTION) || p_39134_.is(Items.LINGERING_POTION) || p_39134_.is(Items.GLASS_BOTTLE); -+ return net.minecraftforge.common.brewing.BrewingRecipeRegistry.isValidInput(p_39134_); - } - } - } diff --git a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch index e5140e8f8f..3f69b46ee9 100644 --- a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch @@ -1,48 +1,48 @@ --- a/net/minecraft/world/inventory/EnchantmentMenu.java +++ b/net/minecraft/world/inventory/EnchantmentMenu.java -@@ -54,7 +_,7 @@ - }); - this.addSlot(new Slot(this.enchantSlots, 1, 35, 47) { - public boolean mayPlace(ItemStack p_39517_) { -- return p_39517_.is(Items.LAPIS_LAZULI); -+ return p_39517_.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS); - } - - public Pair getNoItemIcon() { -@@ -89,23 +_,24 @@ - ItemStack itemstack = p_39461_.getItem(0); - if (!itemstack.isEmpty() && itemstack.isEnchantable()) { - this.access.execute((p_39485_, p_39486_) -> { -- int j = 0; -+ float j = 0; - - for(BlockPos blockpos : EnchantmentTableBlock.BOOKSHELF_OFFSETS) { - if (EnchantmentTableBlock.isValidBookShelf(p_39485_, p_39486_, blockpos)) { -- ++j; -+ j += p_39485_.getBlockState(p_39486_.offset(blockpos)).getEnchantPowerBonus(p_39485_, p_39486_.offset(blockpos)); - } - } - - this.random.setSeed((long)this.enchantmentSeed.get()); - - for(int k = 0; k < 3; ++k) { -- this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, j, itemstack); -+ this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, (int)j, itemstack); - this.enchantClue[k] = -1; - this.levelClue[k] = -1; - if (this.costs[k] < k + 1) { - this.costs[k] = 0; - } -+ this.costs[k] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(p_39485_, p_39486_, k, (int)j, itemstack, costs[k]); - } - - for(int l = 0; l < 3; ++l) { -@@ -237,7 +_,7 @@ - if (!this.moveItemStackTo(itemstack1, 2, 38, true)) { - return ItemStack.EMPTY; - } -- } else if (itemstack1.is(Items.LAPIS_LAZULI)) { -+ } else if (itemstack1.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS)) { - if (!this.moveItemStackTo(itemstack1, 1, 2, true)) { - return ItemStack.EMPTY; +@@ -57,7 +_,7 @@ + this.addSlot(new Slot(this.enchantSlots, 1, 35, 47) { + @Override + public boolean mayPlace(ItemStack p_39517_) { +- return p_39517_.is(Items.LAPIS_LAZULI); ++ return p_39517_.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS); } + + @Override +@@ -94,23 +_,25 @@ + ItemStack itemstack = p_39461_.getItem(0); + if (!itemstack.isEmpty() && itemstack.isEnchantable()) { + this.access.execute((p_327074_, p_327075_) -> { +- int j = 0; ++ float j = 0; + + for (BlockPos blockpos : EnchantingTableBlock.BOOKSHELF_OFFSETS) { + if (EnchantingTableBlock.isValidBookShelf(p_327074_, p_327075_, blockpos)) { + j++; ++ j += p_327074_.getBlockState(p_327075_.offset(blockpos)).getEnchantPowerBonus(p_327074_, p_327075_.offset(blockpos)); + } + } + + this.random.setSeed((long)this.enchantmentSeed.get()); + + for (int k = 0; k < 3; k++) { +- this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, j, itemstack); ++ this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, (int)j, itemstack); + this.enchantClue[k] = -1; + this.levelClue[k] = -1; + if (this.costs[k] < k + 1) { + this.costs[k] = 0; + } ++ this.costs[k] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(p_327074_, p_327075_, k, (int)j, itemstack, costs[k]); + } + + for (int l = 0; l < 3; l++) { +@@ -234,7 +_,7 @@ + if (!this.moveItemStackTo(itemstack1, 2, 38, true)) { + return ItemStack.EMPTY; + } +- } else if (itemstack1.is(Items.LAPIS_LAZULI)) { ++ } else if (itemstack1.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS)) { + if (!this.moveItemStackTo(itemstack1, 1, 2, true)) { + return ItemStack.EMPTY; + } diff --git a/patches/minecraft/net/minecraft/world/inventory/FurnaceResultSlot.java.patch b/patches/minecraft/net/minecraft/world/inventory/FurnaceResultSlot.java.patch index b4b43a0dfb..f1b2a8f389 100644 --- a/patches/minecraft/net/minecraft/world/inventory/FurnaceResultSlot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/FurnaceResultSlot.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/world/inventory/FurnaceResultSlot.java +++ b/net/minecraft/world/inventory/FurnaceResultSlot.java -@@ -48,5 +_,6 @@ - } +@@ -49,5 +_,6 @@ + } - this.removeCount = 0; -+ net.minecraftforge.event.ForgeEventFactory.firePlayerSmeltedEvent(this.player, p_39558_); - } + this.removeCount = 0; ++ net.minecraftforge.event.ForgeEventFactory.firePlayerSmeltedEvent(this.player, p_39558_); + } } diff --git a/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch index 59554d14f4..0c646da907 100644 --- a/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch @@ -1,89 +1,60 @@ --- a/net/minecraft/world/inventory/GrindstoneMenu.java +++ b/net/minecraft/world/inventory/GrindstoneMenu.java -@@ -34,6 +_,7 @@ - } - }; - private final ContainerLevelAccess access; -+ private int xp = -1; +@@ -37,6 +_,7 @@ + } + }; + private final ContainerLevelAccess access; ++ private int xp = -1; - public GrindstoneMenu(int p_39563_, Inventory p_39564_) { - this(p_39563_, p_39564_, ContainerLevelAccess.NULL); -@@ -44,12 +_,12 @@ - this.access = p_39568_; - this.addSlot(new Slot(this.repairSlots, 0, 49, 19) { - public boolean mayPlace(ItemStack p_39607_) { -- return p_39607_.isDamageableItem() || p_39607_.is(Items.ENCHANTED_BOOK) || p_39607_.isEnchanted(); -+ return p_39607_.isDamageableItem() || p_39607_.is(Items.ENCHANTED_BOOK) || p_39607_.isEnchanted() || p_39607_.canGrindstoneRepair(); - } - }); - this.addSlot(new Slot(this.repairSlots, 1, 49, 40) { - public boolean mayPlace(ItemStack p_39616_) { -- return p_39616_.isDamageableItem() || p_39616_.is(Items.ENCHANTED_BOOK) || p_39616_.isEnchanted(); -+ return p_39616_.isDamageableItem() || p_39616_.is(Items.ENCHANTED_BOOK) || p_39616_.isEnchanted() || p_39616_.canGrindstoneRepair(); - } - }); - this.addSlot(new Slot(this.resultSlots, 2, 129, 34) { -@@ -58,6 +_,7 @@ - } + public GrindstoneMenu(int p_39563_, Inventory p_39564_) { + this(p_39563_, p_39564_, ContainerLevelAccess.NULL); +@@ -48,13 +_,13 @@ + this.addSlot(new Slot(this.repairSlots, 0, 49, 19) { + @Override + public boolean mayPlace(ItemStack p_39607_) { +- return p_39607_.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(p_39607_); ++ return p_39607_.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(p_39607_) || p_39607_.canGrindstoneRepair(); + } + }); + this.addSlot(new Slot(this.repairSlots, 1, 49, 40) { + @Override + public boolean mayPlace(ItemStack p_39616_) { +- return p_39616_.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(p_39616_); ++ return p_39616_.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(p_39616_) || p_39616_.canGrindstoneRepair(); + } + }); + this.addSlot(new Slot(this.resultSlots, 2, 129, 34) { +@@ -65,6 +_,7 @@ - public void onTake(Player p_150574_, ItemStack p_150575_) { -+ if (net.minecraftforge.common.ForgeHooks.onGrindstoneTake(GrindstoneMenu.this.repairSlots, p_39568_, this::getExperienceAmount)) return; - p_39568_.execute((p_39634_, p_39635_) -> { - if (p_39634_ instanceof ServerLevel) { - ExperienceOrb.award((ServerLevel)p_39634_, Vec3.atCenterOf(p_39635_), this.getExperienceAmount(p_39634_)); -@@ -70,6 +_,7 @@ - } - - private int getExperienceAmount(Level p_39632_) { -+ if (xp > -1) return xp; - int l = 0; - l += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); - l += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); -@@ -122,6 +_,8 @@ - ItemStack itemstack1 = this.repairSlots.getItem(1); - boolean flag = !itemstack.isEmpty() || !itemstack1.isEmpty(); - boolean flag1 = !itemstack.isEmpty() && !itemstack1.isEmpty(); -+ this.xp = net.minecraftforge.common.ForgeHooks.onGrindstoneChange(itemstack, itemstack1, this.resultSlots, -1); -+ if (this.xp == Integer.MIN_VALUE) - if (!flag) { - this.resultSlots.setItem(0, ItemStack.EMPTY); - } else { -@@ -143,12 +_,13 @@ + @Override + public void onTake(Player p_150574_, ItemStack p_150575_) { ++ if (net.minecraftforge.common.ForgeHooks.onGrindstoneTake(GrindstoneMenu.this.repairSlots, p_39568_, this::getExperienceAmount)) return; + p_39568_.execute((p_39634_, p_39635_) -> { + if (p_39634_ instanceof ServerLevel) { + ExperienceOrb.award((ServerLevel)p_39634_, Vec3.atCenterOf(p_39635_), this.getExperienceAmount(p_39634_)); +@@ -77,6 +_,7 @@ } - Item item = itemstack.getItem(); -- int k = item.getMaxDamage() - itemstack.getDamageValue(); -- int l = item.getMaxDamage() - itemstack1.getDamageValue(); -- int i1 = k + l + item.getMaxDamage() * 5 / 100; -- i = Math.max(item.getMaxDamage() - i1, 0); -+ int k = itemstack.getMaxDamage() - itemstack.getDamageValue(); -+ int l = itemstack.getMaxDamage() - itemstack1.getDamageValue(); -+ int i1 = k + l + itemstack.getMaxDamage() * 5 / 100; -+ i = Math.max(itemstack.getMaxDamage() - i1, 0); - itemstack2 = this.mergeEnchants(itemstack, itemstack1); -- if (!itemstack2.isDamageableItem()) { -+ if (!itemstack2.isRepairable()) i = itemstack.getDamageValue(); -+ if (!itemstack2.isDamageableItem() || !itemstack2.isRepairable()) { - if (!ItemStack.matches(itemstack, itemstack1)) { - this.resultSlots.setItem(0, ItemStack.EMPTY); - this.broadcastChanges(); -@@ -163,6 +_,10 @@ - itemstack2 = flag3 ? itemstack : itemstack1; - } + private int getExperienceAmount(Level p_39632_) { ++ if (xp > -1) return xp; + int l = 0; + l += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); + l += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); +@@ -129,6 +_,17 @@ + } -+ // Forge: Skip the repair if the result would give an item stack with a count not normally obtainable -+ if (j > itemstack2.getMaxStackSize()) -+ this.resultSlots.setItem(0, ItemStack.EMPTY); -+ else - this.resultSlots.setItem(0, this.removeNonCurses(itemstack2, i, j)); - } - -@@ -175,7 +_,7 @@ - - for(Map.Entry entry : map.entrySet()) { - Enchantment enchantment = entry.getKey(); -- if (!enchantment.isCurse() || EnchantmentHelper.getItemEnchantmentLevel(enchantment, itemstack) == 0) { -+ if (!enchantment.isCurse() || EnchantmentHelper.getTagEnchantmentLevel(enchantment, itemstack) == 0) { - itemstack.enchant(enchantment, entry.getValue()); - } - } + private ItemStack computeResult(ItemStack p_335167_, ItemStack p_329934_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onGrindstoneChange(p_335167_, p_329934_, this.resultSlots, -1); ++ if (event.isCanceled()) { ++ this.xp = -1; ++ return ItemStack.EMPTY; ++ } else if (!event.getOutput().isEmpty()) { ++ this.xp = event.getXp(); ++ return event.getOutput(); ++ } else { ++ this.xp = Integer.MIN_VALUE; ++ } ++ + boolean flag = !p_335167_.isEmpty() || !p_329934_.isEmpty(); + if (!flag) { + return ItemStack.EMPTY; diff --git a/patches/minecraft/net/minecraft/world/inventory/InventoryMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/InventoryMenu.java.patch index c591f06e00..810b7719b9 100644 --- a/patches/minecraft/net/minecraft/world/inventory/InventoryMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/InventoryMenu.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/inventory/InventoryMenu.java +++ b/net/minecraft/world/inventory/InventoryMenu.java -@@ -63,7 +_,7 @@ - } +@@ -68,7 +_,7 @@ - public boolean mayPlace(ItemStack p_39746_) { -- return equipmentslot == Mob.getEquipmentSlotForItem(p_39746_); -+ return p_39746_.canEquip(equipmentslot, owner); - } + @Override + public boolean mayPlace(ItemStack p_39746_) { +- return equipmentslot == Mob.getEquipmentSlotForItem(p_39746_); ++ return p_39746_.canEquip(equipmentslot, owner); + } - public boolean mayPickup(Player p_39744_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch index 3405666edb..346db1f1df 100644 --- a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch @@ -6,21 +6,21 @@ -public class MenuType implements FeatureElement { +public class MenuType implements FeatureElement, net.minecraftforge.common.extensions.IForgeMenuType { - public static final MenuType GENERIC_9x1 = register("generic_9x1", ChestMenu::oneRow); - public static final MenuType GENERIC_9x2 = register("generic_9x2", ChestMenu::twoRows); - public static final MenuType GENERIC_9x3 = register("generic_9x3", ChestMenu::threeRows); -@@ -54,6 +_,14 @@ - - public T create(int p_39986_, Inventory p_39987_) { - return this.constructor.create(p_39986_, p_39987_); -+ } + public static final MenuType GENERIC_9x1 = register("generic_9x1", ChestMenu::oneRow); + public static final MenuType GENERIC_9x2 = register("generic_9x2", ChestMenu::twoRows); + public static final MenuType GENERIC_9x3 = register("generic_9x3", ChestMenu::threeRows); +@@ -57,6 +_,14 @@ + @Override + public FeatureFlagSet requiredFeatures() { + return this.requiredFeatures; ++ } + -+ @Override -+ public T create(int windowId, Inventory playerInv, net.minecraft.network.FriendlyByteBuf extraData) { -+ if (this.constructor instanceof net.minecraftforge.network.IContainerFactory ctr) { -+ return ctr.create(windowId, playerInv, extraData); -+ } -+ return create(windowId, playerInv); - } ++ @Override ++ public T create(int windowId, Inventory playerInv, net.minecraft.network.FriendlyByteBuf extraData) { ++ if (this.constructor instanceof net.minecraftforge.network.IContainerFactory ctr) { ++ return ctr.create(windowId, playerInv, extraData); ++ } ++ return create(windowId, playerInv); + } - public FeatureFlagSet requiredFeatures() { + public interface MenuSupplier { diff --git a/patches/minecraft/net/minecraft/world/inventory/RecipeBookMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/RecipeBookMenu.java.patch index 4a13fa7c36..6b0a1f4b9d 100644 --- a/patches/minecraft/net/minecraft/world/inventory/RecipeBookMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/RecipeBookMenu.java.patch @@ -1,13 +1,11 @@ --- a/net/minecraft/world/inventory/RecipeBookMenu.java +++ b/net/minecraft/world/inventory/RecipeBookMenu.java -@@ -30,6 +_,10 @@ +@@ -33,4 +_,8 @@ + public abstract RecipeBookType getRecipeBookType(); - public abstract int getSize(); - -+ public java.util.List getRecipeBookCategories() { -+ return net.minecraft.client.RecipeBookCategories.getCategories(this.getRecipeBookType()); -+ } + public abstract boolean shouldMoveToInventory(int p_150635_); + - public abstract RecipeBookType getRecipeBookType(); - - public abstract boolean shouldMoveToInventory(int p_150635_); ++ public java.util.List getRecipeBookCategories() { ++ return net.minecraft.client.RecipeBookCategories.getCategories(this.getRecipeBookType()); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/inventory/RecipeBookType.java.patch b/patches/minecraft/net/minecraft/world/inventory/RecipeBookType.java.patch index 2bd4395906..e8252a7de0 100644 --- a/patches/minecraft/net/minecraft/world/inventory/RecipeBookType.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/RecipeBookType.java.patch @@ -5,10 +5,10 @@ -public enum RecipeBookType { +public enum RecipeBookType implements net.minecraftforge.common.IExtensibleEnum { - CRAFTING, - FURNACE, - BLAST_FURNACE, - SMOKER; + CRAFTING, + FURNACE, + BLAST_FURNACE, + SMOKER; + + public static RecipeBookType create(String name) { + throw new IllegalStateException("Enum not extended!"); @@ -16,7 +16,7 @@ + + @Override + public void init() { -+ String name = this.name().toLowerCase(java.util.Locale.ROOT).replace("_",""); -+ net.minecraft.stats.RecipeBookSettings.addTagsForType(this, "is" + name + "GuiOpen", "is" + name + "FilteringCraftable"); ++ String name = this.name().toLowerCase(java.util.Locale.ROOT).replace("_",""); ++ net.minecraft.stats.RecipeBookSettings.addTagsForType(this, "is" + name + "GuiOpen", "is" + name + "FilteringCraftable"); + } } diff --git a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch index 9189405d41..e5c07be9d4 100644 --- a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch @@ -1,21 +1,20 @@ --- a/net/minecraft/world/inventory/ResultSlot.java +++ b/net/minecraft/world/inventory/ResultSlot.java -@@ -41,6 +_,7 @@ - protected void checkTakeAchievements(ItemStack p_40185_) { - if (this.removeCount > 0) { - p_40185_.onCraftedBy(this.player.level(), this.player, this.removeCount); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerCraftingEvent(this.player, p_40185_, this.craftSlots); - } +@@ -46,6 +_,7 @@ + protected void checkTakeAchievements(ItemStack p_40185_) { + if (this.removeCount > 0) { + p_40185_.onCraftedBy(this.player.level(), this.player, this.removeCount); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerCraftingEvent(this.player, p_40185_, this.craftSlots); + } - Container container = this.container; -@@ -53,8 +_,9 @@ + if (this.container instanceof RecipeCraftingHolder recipecraftingholder) { +@@ -58,7 +_,9 @@ + @Override + public void onTake(Player p_150638_, ItemStack p_150639_) { + this.checkTakeAchievements(p_150639_); ++ net.minecraftforge.common.ForgeHooks.setCraftingPlayer(p_150638_); + NonNullList nonnulllist = p_150638_.level().getRecipeManager().getRemainingItemsFor(RecipeType.CRAFTING, this.craftSlots, p_150638_.level()); ++ net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null); - public void onTake(Player p_150638_, ItemStack p_150639_) { - this.checkTakeAchievements(p_150639_); -+ net.minecraftforge.common.ForgeHooks.setCraftingPlayer(p_150638_); - NonNullList nonnulllist = p_150638_.level().getRecipeManager().getRemainingItemsFor(RecipeType.CRAFTING, this.craftSlots, p_150638_.level()); -- -+ net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null); - for(int i = 0; i < nonnulllist.size(); ++i) { - ItemStack itemstack = this.craftSlots.getItem(i); - ItemStack itemstack1 = nonnulllist.get(i); + for (int i = 0; i < nonnulllist.size(); i++) { + ItemStack itemstack = this.craftSlots.getItem(i); diff --git a/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch b/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch index 1395c79383..18d6f4ba8a 100644 --- a/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch @@ -1,50 +1,49 @@ --- a/net/minecraft/world/inventory/Slot.java +++ b/net/minecraft/world/inventory/Slot.java -@@ -82,7 +_,7 @@ +@@ -81,7 +_,7 @@ - @Nullable - public Pair getNoItemIcon() { -- return null; -+ return backgroundPair; - } + @Nullable + public Pair getNoItemIcon() { +- return null; ++ return backgroundPair; + } - public ItemStack remove(int p_40227_) { -@@ -95,6 +_,38 @@ + public ItemStack remove(int p_40227_) { +@@ -158,5 +_,37 @@ - public boolean isActive() { - return true; -+ } + public boolean isFake() { + return false; ++ } + -+ /** -+ * Retrieves the index in the inventory for this slot, this value should typically not -+ * be used, but can be useful for some occasions. -+ * -+ * @return Index in associated inventory for this slot. -+ */ -+ public int getSlotIndex() { -+ return slot; -+ } ++ /** ++ * Retrieves the index in the inventory for this slot, this value should typically not ++ * be used, but can be useful for some occasions. ++ * ++ * @return Index in associated inventory for this slot. ++ */ ++ public int getSlotIndex() { ++ return slot; ++ } + -+ /** -+ * Checks if the other slot is in the same inventory, by comparing the inventory reference. -+ * @param other -+ * @return true if the other slot is in the same inventory -+ */ -+ public boolean isSameInventory(Slot other) { -+ return this.container == other.container; -+ } ++ /** ++ * Checks if the other slot is in the same inventory, by comparing the inventory reference. ++ * @param other ++ * @return true if the other slot is in the same inventory ++ */ ++ public boolean isSameInventory(Slot other) { ++ return this.container == other.container; ++ } + -+ private Pair backgroundPair; -+ /** -+ * Sets the background atlas and sprite location. -+ * -+ * @param atlas The atlas name -+ * @param sprite The sprite located on that atlas. -+ * @return this, to allow chaining. -+ */ -+ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) { -+ this.backgroundPair = Pair.of(atlas, sprite); -+ return this; - } - - public Optional tryRemove(int p_150642_, int p_150643_, Player p_150644_) { ++ private Pair backgroundPair; ++ /** ++ * Sets the background atlas and sprite location. ++ * ++ * @param atlas The atlas name ++ * @param sprite The sprite located on that atlas. ++ * @return this, to allow chaining. ++ */ ++ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) { ++ this.backgroundPair = Pair.of(atlas, sprite); ++ return this; + } + } diff --git a/patches/minecraft/net/minecraft/world/item/AnimalArmorItem.java.patch b/patches/minecraft/net/minecraft/world/item/AnimalArmorItem.java.patch new file mode 100644 index 0000000000..f47af3d7e3 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/item/AnimalArmorItem.java.patch @@ -0,0 +1,22 @@ +--- a/net/minecraft/world/item/AnimalArmorItem.java ++++ b/net/minecraft/world/item/AnimalArmorItem.java +@@ -48,7 +_,7 @@ + return false; + } + +- public static enum BodyType { ++ public static enum BodyType implements net.minecraftforge.common.IExtensibleEnum { + EQUESTRIAN(p_331659_ -> p_331659_.withPath(p_329177_ -> "textures/entity/horse/armor/horse_armor_" + p_329177_), SoundEvents.ITEM_BREAK), + CANINE(p_333424_ -> p_333424_.withPath("textures/entity/wolf/wolf_armor"), SoundEvents.WOLF_ARMOR_BREAK); + +@@ -58,6 +_,10 @@ + private BodyType(final Function p_332420_, final SoundEvent p_335661_) { + this.textureLocator = p_332420_; + this.breakingSound = p_335661_; ++ } ++ ++ public static BodyType create(String name, final Function path, SoundEvent sound) { ++ throw new IllegalStateException("Enum not extended"); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/item/ArmorItem.java.patch b/patches/minecraft/net/minecraft/world/item/ArmorItem.java.patch deleted file mode 100644 index 306b63d17b..0000000000 --- a/patches/minecraft/net/minecraft/world/item/ArmorItem.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/item/ArmorItem.java -+++ b/net/minecraft/world/item/ArmorItem.java -@@ -75,7 +_,7 @@ - UUID uuid = ARMOR_MODIFIER_UUID_PER_TYPE.get(p_266831_); - builder.put(Attributes.ARMOR, new AttributeModifier(uuid, "Armor modifier", (double)this.defense, AttributeModifier.Operation.ADDITION)); - builder.put(Attributes.ARMOR_TOUGHNESS, new AttributeModifier(uuid, "Armor toughness", (double)this.toughness, AttributeModifier.Operation.ADDITION)); -- if (p_40386_ == ArmorMaterials.NETHERITE) { -+ if (this.knockbackResistance > 0) { - builder.put(Attributes.KNOCKBACK_RESISTANCE, new AttributeModifier(uuid, "Armor knockback resistance", (double)this.knockbackResistance, AttributeModifier.Operation.ADDITION)); - } - diff --git a/patches/minecraft/net/minecraft/world/item/ArrowItem.java.patch b/patches/minecraft/net/minecraft/world/item/ArrowItem.java.patch index bf69e086b5..849db20831 100644 --- a/patches/minecraft/net/minecraft/world/item/ArrowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ArrowItem.java.patch @@ -1,12 +1,14 @@ --- a/net/minecraft/world/item/ArrowItem.java +++ b/net/minecraft/world/item/ArrowItem.java -@@ -15,4 +_,9 @@ - arrow.setEffectsFromItem(p_40514_); - return arrow; - } +@@ -23,4 +_,11 @@ + arrow.pickup = AbstractArrow.Pickup.ALLOWED; + return arrow; + } + -+ public boolean isInfinite(ItemStack stack, ItemStack bow, net.minecraft.world.entity.player.Player player) { -+ int enchant = net.minecraft.world.item.enchantment.EnchantmentHelper.getItemEnchantmentLevel(net.minecraft.world.item.enchantment.Enchantments.INFINITY_ARROWS, bow); -+ return enchant <= 0 ? false : this.getClass() == ArrowItem.class; -+ } ++ public boolean isInfinite(ItemStack stack, ItemStack bow, net.minecraft.world.entity.LivingEntity owner) { ++ return false; ++ // Infinity doesnt go on arrows anymore.. ++ //int enchant = net.minecraft.world.item.enchantment.EnchantmentHelper.getItemEnchantmentLevel(net.minecraft.world.item.enchantment.Enchantments.INFINITY_ARROWS, bow); ++ //return enchant <= 0 ? false : this.getClass() == ArrowItem.class; ++ } } diff --git a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch index d3a9bed7b2..8ed3f3545e 100644 --- a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch @@ -1,33 +1,29 @@ --- a/net/minecraft/world/item/AxeItem.java +++ b/net/minecraft/world/item/AxeItem.java -@@ -32,7 +_,8 @@ - Level level = p_40529_.getLevel(); - BlockPos blockpos = p_40529_.getClickedPos(); - Player player = p_40529_.getPlayer(); -- Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); -+ var modded = level.getBlockState(blockpos).getToolModifiedState(p_40529_, net.minecraftforge.common.ToolActions.AXE_STRIP, false); -+ Optional optional = modded != null ? Optional.of(modded) : this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); - if (optional.isEmpty()) { - return InteractionResult.PASS; - } else { -@@ -79,9 +_,20 @@ - } - } - -+ @org.jetbrains.annotations.Nullable -+ public static BlockState getAxeStrippingState(BlockState originalState) { -+ Block block = STRIPPABLES.get(originalState.getBlock()); -+ return block != null ? block.defaultBlockState().setValue(RotatedPillarBlock.AXIS, originalState.getValue(RotatedPillarBlock.AXIS)) : null; -+ } +@@ -56,7 +_,8 @@ + Level level = p_40529_.getLevel(); + BlockPos blockpos = p_40529_.getClickedPos(); + Player player = p_40529_.getPlayer(); +- Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); ++ var modded = level.getBlockState(blockpos).getToolModifiedState(p_40529_, net.minecraftforge.common.ToolActions.AXE_STRIP, false); ++ Optional optional = modded != null ? Optional.of(modded) : this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); + if (optional.isEmpty()) { + return InteractionResult.PASS; + } else { +@@ -103,5 +_,16 @@ + private Optional getStripped(BlockState p_150691_) { + return Optional.ofNullable(STRIPPABLES.get(p_150691_.getBlock())) + .map(p_150689_ -> p_150689_.defaultBlockState().setValue(RotatedPillarBlock.AXIS, p_150691_.getValue(RotatedPillarBlock.AXIS))); ++ } + - private Optional getStripped(BlockState p_150691_) { - return Optional.ofNullable(STRIPPABLES.get(p_150691_.getBlock())).map((p_150689_) -> { - return p_150689_.defaultBlockState().setValue(RotatedPillarBlock.AXIS, p_150691_.getValue(RotatedPillarBlock.AXIS)); - }); -+ } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_AXE_ACTIONS.contains(toolAction); ++ } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_AXE_ACTIONS.contains(toolAction); - } ++ @org.jetbrains.annotations.Nullable ++ public static BlockState getAxeStrippingState(BlockState originalState) { ++ Block block = STRIPPABLES.get(originalState.getBlock()); ++ return block != null ? block.defaultBlockState().setValue(RotatedPillarBlock.AXIS, originalState.getValue(RotatedPillarBlock.AXIS)) : null; + } } diff --git a/patches/minecraft/net/minecraft/world/item/BannerItem.java.patch b/patches/minecraft/net/minecraft/world/item/BannerItem.java.patch deleted file mode 100644 index fbdd92a340..0000000000 --- a/patches/minecraft/net/minecraft/world/item/BannerItem.java.patch +++ /dev/null @@ -1,12 +0,0 @@ ---- a/net/minecraft/world/item/BannerItem.java -+++ b/net/minecraft/world/item/BannerItem.java -@@ -36,7 +_,8 @@ - holder.unwrapKey().map((p_220002_) -> { - return p_220002_.location().toShortLanguageKey(); - }).ifPresent((p_220006_) -> { -- p_40544_.add(Component.translatable("block.minecraft.banner." + p_220006_ + "." + dyecolor.getName()).withStyle(ChatFormatting.GRAY)); -+ net.minecraft.resources.ResourceLocation fileLoc = new net.minecraft.resources.ResourceLocation(p_220006_); -+ p_40544_.add(Component.translatable("block." + fileLoc.getNamespace() + ".banner." + fileLoc.getPath() + "." + dyecolor.getName()).withStyle(ChatFormatting.GRAY)); - }); - } - } diff --git a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch index 64ae4fe29b..669da194d0 100644 --- a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch @@ -1,50 +1,42 @@ --- a/net/minecraft/world/item/BlockItem.java +++ b/net/minecraft/world/item/BlockItem.java -@@ -82,8 +_,8 @@ - } - } +@@ -82,9 +_,9 @@ + } + } -- SoundType soundtype = blockstate1.getSoundType(); -- level.playSound(player, blockpos, this.getPlaceSound(blockstate1), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); -+ SoundType soundtype = blockstate1.getSoundType(level, blockpos, p_40577_.getPlayer()); -+ level.playSound(player, blockpos, this.getPlaceSound(blockstate1, level, blockpos, p_40577_.getPlayer()), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); - level.gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(player, blockstate1)); - if (player == null || !player.getAbilities().instabuild) { - itemstack.shrink(1); -@@ -95,10 +_,16 @@ - } - } +- SoundType soundtype = blockstate1.getSoundType(); ++ SoundType soundtype = blockstate1.getSoundType(level, blockpos, p_40577_.getPlayer()); + level.playSound( +- player, blockpos, this.getPlaceSound(blockstate1), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F ++ player, blockpos, this.getPlaceSound(blockstate1, level, blockpos, p_40577_.getPlayer()), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F + ); + level.gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(player, blockstate1)); + itemstack.consume(1, player); +@@ -94,10 +_,16 @@ + } + } -+ @Deprecated //Forge: Use more sensitive version {@link BlockItem#getPlaceSound(BlockState, IBlockReader, BlockPos, Entity) } - protected SoundEvent getPlaceSound(BlockState p_40588_) { - return p_40588_.getSoundType().getPlaceSound(); - } ++ @Deprecated //Forge: Use more sensitive version {@link BlockItem#getPlaceSound(BlockState, IBlockReader, BlockPos, Entity) } + protected SoundEvent getPlaceSound(BlockState p_40588_) { + return p_40588_.getSoundType().getPlaceSound(); + } -+ //Forge: Sensitive version of BlockItem#getPlaceSound -+ protected SoundEvent getPlaceSound(BlockState state, Level world, BlockPos pos, Player entity) { -+ return state.getSoundType(world, pos, entity).getPlaceSound(); -+ } ++ //Forge: Sensitive version of BlockItem#getPlaceSound ++ protected SoundEvent getPlaceSound(BlockState state, Level world, BlockPos pos, Player entity) { ++ return state.getSoundType(world, pos, entity).getPlaceSound(); ++ } + - @Nullable - public BlockPlaceContext updatePlacementContext(BlockPlaceContext p_40609_) { - return p_40609_; -@@ -195,11 +_,19 @@ - } + @Nullable + public BlockPlaceContext updatePlacementContext(BlockPlaceContext p_40609_) { + return p_40609_; +@@ -188,6 +_,10 @@ - public Block getBlock() { -+ return this.getBlockRaw() == null ? null : net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(this.getBlockRaw()).get(); -+ } + public void registerBlocks(Map p_40607_, Item p_40608_) { + p_40607_.put(this.getBlock(), p_40608_); ++ } + -+ private Block getBlockRaw() { - return this.block; - } ++ public void removeFromBlockToItemMap(Map blockToItemMap, Item itemIn) { ++ blockToItemMap.remove(this.getBlock()); + } - public void registerBlocks(Map p_40607_, Item p_40608_) { - p_40607_.put(this.getBlock(), p_40608_); -+ } -+ -+ public void removeFromBlockToItemMap(Map blockToItemMap, Item itemIn) { -+ blockToItemMap.remove(this.getBlock()); - } - - public boolean canFitInsideContainerItems() { + @Override diff --git a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch index e9b04cbd04..bbcd50db6d 100644 --- a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch @@ -1,29 +1,30 @@ --- a/net/minecraft/world/item/BoneMealItem.java +++ b/net/minecraft/world/item/BoneMealItem.java -@@ -35,7 +_,7 @@ - Level level = p_40637_.getLevel(); - BlockPos blockpos = p_40637_.getClickedPos(); - BlockPos blockpos1 = blockpos.relative(p_40637_.getClickedFace()); -- if (growCrop(p_40637_.getItemInHand(), level, blockpos)) { -+ if (applyBonemeal(p_40637_.getItemInHand(), level, blockpos, p_40637_.getPlayer())) { - if (!level.isClientSide) { - p_40637_.getPlayer().gameEvent(GameEvent.ITEM_INTERACT_FINISH); - level.levelEvent(1505, blockpos, 0); -@@ -58,8 +_,17 @@ - } - } +@@ -37,7 +_,7 @@ + Level level = p_40637_.getLevel(); + BlockPos blockpos = p_40637_.getClickedPos(); + BlockPos blockpos1 = blockpos.relative(p_40637_.getClickedFace()); +- if (growCrop(p_40637_.getItemInHand(), level, blockpos)) { ++ if (applyBonemeal(p_40637_.getItemInHand(), level, blockpos, p_40637_.getPlayer())) { + if (!level.isClientSide) { + p_40637_.getPlayer().gameEvent(GameEvent.ITEM_INTERACT_FINISH); + level.levelEvent(1505, blockpos, 15); +@@ -60,8 +_,18 @@ + } + } -+ @Deprecated //Forge: Use Player/Hand version - public static boolean growCrop(ItemStack p_40628_, Level p_40629_, BlockPos p_40630_) { -+ if (p_40629_ instanceof net.minecraft.server.level.ServerLevel) -+ return applyBonemeal(p_40628_, p_40629_, p_40630_, null); -+ return false; -+ } ++ @Deprecated //Forge: Use Player/Hand version + public static boolean growCrop(ItemStack p_40628_, Level p_40629_, BlockPos p_40630_) { ++ if (p_40629_ instanceof net.minecraft.server.level.ServerLevel) { ++ return applyBonemeal(p_40628_, p_40629_, p_40630_, null); ++ } ++ return false; ++ } + -+ public static boolean applyBonemeal(ItemStack p_40628_, Level p_40629_, BlockPos p_40630_, net.minecraft.world.entity.player.Player player) { - BlockState blockstate = p_40629_.getBlockState(p_40630_); -+ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, p_40629_, p_40630_, blockstate, p_40628_); -+ if (hook != 0) return hook > 0; - Block block = blockstate.getBlock(); - if (block instanceof BonemealableBlock bonemealableblock) { - if (bonemealableblock.isValidBonemealTarget(p_40629_, p_40630_, blockstate)) { ++ public static boolean applyBonemeal(ItemStack p_40628_, Level p_40629_, BlockPos p_40630_, net.minecraft.world.entity.player.Player player) { + BlockState blockstate = p_40629_.getBlockState(p_40630_); ++ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, p_40629_, p_40630_, blockstate, p_40628_); ++ if (hook != 0) return hook > 0; + if (blockstate.getBlock() instanceof BonemealableBlock bonemealableblock && bonemealableblock.isValidBonemealTarget(p_40629_, p_40630_, blockstate)) { + if (p_40629_ instanceof ServerLevel) { + if (bonemealableblock.isBonemealSuccess(p_40629_, p_40629_.random, p_40630_, blockstate)) { diff --git a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch index 9c79a930a1..319f72f5aa 100644 --- a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch @@ -1,50 +1,21 @@ --- a/net/minecraft/world/item/BowItem.java +++ b/net/minecraft/world/item/BowItem.java -@@ -25,18 +_,23 @@ - if (p_40669_ instanceof Player player) { - boolean flag = player.getAbilities().instabuild || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.INFINITY_ARROWS, p_40667_) > 0; - ItemStack itemstack = player.getProjectile(p_40667_); +@@ -27,6 +_,9 @@ + ItemStack itemstack = player.getProjectile(p_40667_); + if (!itemstack.isEmpty()) { + int i = this.getUseDuration(p_40667_) - p_40670_; ++ i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(p_40667_, p_40668_, player, i, true); ++ if (i < 0) return; + -+ int i = this.getUseDuration(p_40667_) - p_40670_; -+ i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(p_40667_, p_40668_, player, i, !itemstack.isEmpty() || flag); -+ if (i < 0) return; -+ - if (!itemstack.isEmpty() || flag) { - if (itemstack.isEmpty()) { - itemstack = new ItemStack(Items.ARROW); - } - -- int i = this.getUseDuration(p_40667_) - p_40670_; - float f = getPowerForTime(i); - if (!((double)f < 0.1D)) { -- boolean flag1 = flag && itemstack.is(Items.ARROW); -+ boolean flag1 = player.getAbilities().instabuild || (itemstack.getItem() instanceof ArrowItem && ((ArrowItem)itemstack.getItem()).isInfinite(itemstack, p_40667_, player)); - if (!p_40668_.isClientSide) { - ArrowItem arrowitem = (ArrowItem)(itemstack.getItem() instanceof ArrowItem ? itemstack.getItem() : Items.ARROW); - AbstractArrow abstractarrow = arrowitem.createArrow(p_40668_, itemstack, player); -+ abstractarrow = customArrow(abstractarrow); - abstractarrow.shootFromRotation(player, player.getXRot(), player.getYRot(), 0.0F, f * 3.0F, 1.0F); - if (f == 1.0F) { - abstractarrow.setCritArrow(true); -@@ -101,6 +_,10 @@ - public InteractionResultHolder use(Level p_40672_, Player p_40673_, InteractionHand p_40674_) { - ItemStack itemstack = p_40673_.getItemInHand(p_40674_); - boolean flag = !p_40673_.getProjectile(itemstack).isEmpty(); -+ -+ InteractionResultHolder ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, p_40672_, p_40673_, p_40674_, flag); -+ if (ret != null) return ret; -+ - if (!p_40673_.getAbilities().instabuild && !flag) { - return InteractionResultHolder.fail(itemstack); - } else { -@@ -111,6 +_,10 @@ - - public Predicate getAllSupportedProjectiles() { - return ARROW_ONLY; -+ } -+ -+ public AbstractArrow customArrow(AbstractArrow arrow) { -+ return arrow; - } - - public int getDefaultProjectileRange() { + float f = getPowerForTime(i); + if (!((double)f < 0.1)) { + List list = draw(p_40667_, itemstack, player); +@@ -81,6 +_,8 @@ + public InteractionResultHolder use(Level p_40672_, Player p_40673_, InteractionHand p_40674_) { + ItemStack itemstack = p_40673_.getItemInHand(p_40674_); + boolean flag = !p_40673_.getProjectile(itemstack).isEmpty(); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, p_40672_, p_40673_, p_40674_, flag); ++ if (ret != null) return ret; + if (!p_40673_.hasInfiniteMaterials() && !flag) { + return InteractionResultHolder.fail(itemstack); + } else { diff --git a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch index 4172e792a4..130936f3be 100644 --- a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch @@ -1,113 +1,122 @@ --- a/net/minecraft/world/item/BucketItem.java +++ b/net/minecraft/world/item/BucketItem.java -@@ -31,14 +_,28 @@ +@@ -31,15 +_,29 @@ public class BucketItem extends Item implements DispensibleContainerItem { - private final Fluid content; + private final Fluid content; -+ // Forge: Use the other constructor that takes a Supplier -+ @Deprecated - public BucketItem(Fluid p_40689_, Item.Properties p_40690_) { - super(p_40690_); - this.content = p_40689_; -+ this.fluidSupplier = net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_40689_); -+ } ++ // Forge: Use the other constructor that takes a Supplier ++ @Deprecated + public BucketItem(Fluid p_40689_, Item.Properties p_40690_) { + super(p_40690_); + this.content = p_40689_; ++ this.fluidSupplier = net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_40689_); ++ } + -+ /** -+ * @param supplier A fluid supplier such as {@link net.minecraftforge.registries.RegistryObject} -+ */ -+ public BucketItem(java.util.function.Supplier supplier, Item.Properties builder) { -+ super(builder); -+ this.content = null; -+ this.fluidSupplier = supplier; - } ++ /** ++ * @param supplier A fluid supplier such as {@link net.minecraftforge.registries.RegistryObject} ++ */ ++ public BucketItem(java.util.function.Supplier supplier, Item.Properties builder) { ++ super(builder); ++ this.content = null; ++ this.fluidSupplier = supplier; + } - public InteractionResultHolder use(Level p_40703_, Player p_40704_, InteractionHand p_40705_) { - ItemStack itemstack = p_40704_.getItemInHand(p_40705_); - BlockHitResult blockhitresult = getPlayerPOVHitResult(p_40703_, p_40704_, this.content == Fluids.EMPTY ? ClipContext.Fluid.SOURCE_ONLY : ClipContext.Fluid.NONE); -+ InteractionResultHolder ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(p_40704_, p_40703_, itemstack, blockhitresult); -+ if (ret != null) return ret; - if (blockhitresult.getType() == HitResult.Type.MISS) { - return InteractionResultHolder.pass(itemstack); - } else if (blockhitresult.getType() != HitResult.Type.BLOCK) { + @Override + public InteractionResultHolder use(Level p_40703_, Player p_40704_, InteractionHand p_40705_) { + ItemStack itemstack = p_40704_.getItemInHand(p_40705_); + BlockHitResult blockhitresult = getPlayerPOVHitResult(p_40703_, p_40704_, this.content == Fluids.EMPTY ? ClipContext.Fluid.SOURCE_ONLY : ClipContext.Fluid.NONE); ++ InteractionResultHolder ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(p_40704_, p_40703_, itemstack, blockhitresult); ++ if (ret != null) return ret; + if (blockhitresult.getType() == HitResult.Type.MISS) { + return InteractionResultHolder.pass(itemstack); + } else if (blockhitresult.getType() != HitResult.Type.BLOCK) { @@ -56,7 +_,7 @@ - ItemStack itemstack2 = bucketpickup.pickupBlock(p_40704_, p_40703_, blockpos, blockstate1); - if (!itemstack2.isEmpty()) { - p_40704_.awardStat(Stats.ITEM_USED.get(this)); -- bucketpickup.getPickupSound().ifPresent((p_150709_) -> { -+ bucketpickup.getPickupSound(blockstate1).ifPresent((p_150709_) -> { - p_40704_.playSound(p_150709_, 1.0F, 1.0F); - }); - p_40703_.gameEvent(p_40704_, GameEvent.FLUID_PICKUP, blockpos); -@@ -72,8 +_,8 @@ - return InteractionResultHolder.fail(itemstack); + ItemStack itemstack2 = bucketpickup.pickupBlock(p_40704_, p_40703_, blockpos, blockstate1); + if (!itemstack2.isEmpty()) { + p_40704_.awardStat(Stats.ITEM_USED.get(this)); +- bucketpickup.getPickupSound().ifPresent(p_150709_ -> p_40704_.playSound(p_150709_, 1.0F, 1.0F)); ++ bucketpickup.getPickupSound(blockstate1).ifPresent(p_150709_ -> p_40704_.playSound(p_150709_, 1.0F, 1.0F)); + p_40703_.gameEvent(p_40704_, GameEvent.FLUID_PICKUP, blockpos); + ItemStack itemstack1 = ItemUtils.createFilledResult(itemstack, p_40704_, itemstack2); + if (!p_40703_.isClientSide) { +@@ -70,8 +_,8 @@ + return InteractionResultHolder.fail(itemstack); } else { - BlockState blockstate = p_40703_.getBlockState(blockpos); -- BlockPos blockpos2 = blockstate.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? blockpos : blockpos1; -- if (this.emptyContents(p_40704_, p_40703_, blockpos2, blockhitresult)) { -+ BlockPos blockpos2 = canBlockContainFluid(p_40703_, blockpos, blockstate) ? blockpos : blockpos1; -+ if (this.emptyContents(p_40704_, p_40703_, blockpos2, blockhitresult, itemstack)) { - this.checkExtraContent(p_40704_, p_40703_, itemstack, blockpos2); - if (p_40704_ instanceof ServerPlayer) { - CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayer)p_40704_, blockpos2, itemstack); -@@ -98,7 +_,12 @@ - public void checkExtraContent(@Nullable Player p_150711_, Level p_150712_, ItemStack p_150713_, BlockPos p_150714_) { - } + BlockState blockstate = p_40703_.getBlockState(blockpos); +- BlockPos blockpos2 = blockstate.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? blockpos : blockpos1; +- if (this.emptyContents(p_40704_, p_40703_, blockpos2, blockhitresult)) { ++ BlockPos blockpos2 = canBlockContainFluid(p_40703_, blockpos, blockstate) ? blockpos : blockpos1; ++ if (this.emptyContents(p_40704_, p_40703_, blockpos2, blockhitresult, itemstack)) { + this.checkExtraContent(p_40704_, p_40703_, itemstack, blockpos2); + if (p_40704_ instanceof ServerPlayer) { + CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayer)p_40704_, blockpos2, itemstack); +@@ -94,8 +_,13 @@ + public void checkExtraContent(@Nullable Player p_150711_, Level p_150712_, ItemStack p_150713_, BlockPos p_150714_) { + } -+ @Deprecated //Forge: use the ItemStack sensitive version - public boolean emptyContents(@Nullable Player p_150716_, Level p_150717_, BlockPos p_150718_, @Nullable BlockHitResult p_150719_) { -+ return this.emptyContents(p_150716_, p_150717_, p_150718_, p_150719_, null); -+ } ++ @Deprecated //Forge: use the ItemStack sensitive version + @Override + public boolean emptyContents(@Nullable Player p_150716_, Level p_150717_, BlockPos p_150718_, @Nullable BlockHitResult p_150719_) { ++ return this.emptyContents(p_150716_, p_150717_, p_150718_, p_150719_, null); ++ } + -+ public boolean emptyContents(@Nullable Player p_150716_, Level p_150717_, BlockPos p_150718_, @Nullable BlockHitResult p_150719_, @Nullable ItemStack container) { - Fluid $$6 = this.content; - if ($$6 instanceof FlowingFluid flowingfluid) { - BlockState blockstate; -@@ -127,8 +_,12 @@ - } ++ public boolean emptyContents(@Nullable Player p_150716_, Level p_150717_, BlockPos p_150718_, @Nullable BlockHitResult p_150719_, @Nullable ItemStack container) { + if (!(this.content instanceof FlowingFluid flowingfluid)) { + return false; + } else { +@@ -122,8 +_,12 @@ + } - boolean flag1 = flag2; -+ java.util.Optional containedFluidStack = java.util.Optional.ofNullable(container).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); - if (!flag1) { -- return p_150719_ != null && this.emptyContents(p_150716_, p_150717_, p_150719_.getBlockPos().relative(p_150719_.getDirection()), (BlockHitResult)null); -+ return p_150719_ != null && this.emptyContents(p_150716_, p_150717_, p_150719_.getBlockPos().relative(p_150719_.getDirection()), (BlockHitResult)null, container); -+ } else if (containedFluidStack.isPresent() && this.content.getFluidType().isVaporizedOnPlacement(p_150717_, p_150718_, containedFluidStack.get())) { -+ this.content.getFluidType().onVaporize(p_150716_, p_150717_, p_150718_, containedFluidStack.get()); -+ return true; - } else if (p_150717_.dimensionType().ultraWarm() && this.content.is(FluidTags.WATER)) { - int l = p_150718_.getX(); - int i = p_150718_.getY(); -@@ -141,7 +_,7 @@ + boolean flag1 = flag2; ++ java.util.Optional containedFluidStack = java.util.Optional.ofNullable(container).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); + if (!flag1) { +- return p_150719_ != null && this.emptyContents(p_150716_, p_150717_, p_150719_.getBlockPos().relative(p_150719_.getDirection()), null); ++ return p_150719_ != null && this.emptyContents(p_150716_, p_150717_, p_150719_.getBlockPos().relative(p_150719_.getDirection()), null, container); ++ } else if (containedFluidStack.isPresent() && this.content.getFluidType().isVaporizedOnPlacement(p_150717_, p_150718_, containedFluidStack.get())) { ++ this.content.getFluidType().onVaporize(p_150716_, p_150717_, p_150718_, containedFluidStack.get()); ++ return true; + } else if (p_150717_.dimensionType().ultraWarm() && this.content.is(FluidTags.WATER)) { + int l = p_150718_.getX(); + int i = p_150718_.getY(); +@@ -143,7 +_,7 @@ - return true; - } else { -- if ($$7 instanceof LiquidBlockContainer) { -+ if ($$7 instanceof LiquidBlockContainer liquid && liquid.canPlaceLiquid(p_150716_, p_150717_, p_150718_, blockstate, content)) { - LiquidBlockContainer liquidblockcontainer1 = (LiquidBlockContainer)$$7; - if (this.content == Fluids.WATER) { - liquidblockcontainer1.placeLiquid(p_150717_, p_150718_, blockstate, flowingfluid.getSource(false)); -@@ -166,8 +_,24 @@ - } + return true; + } else { +- if ($$7 instanceof LiquidBlockContainer liquidblockcontainer1 && this.content == Fluids.WATER) { ++ if ($$7 instanceof LiquidBlockContainer liquidblockcontainer1 && liquidblockcontainer1.canPlaceLiquid(p_150716_, p_150717_, p_150718_, blockstate, content) && this.content == Fluids.WATER) { + liquidblockcontainer1.placeLiquid(p_150717_, p_150718_, blockstate, flowingfluid.getSource(false)); + this.playEmptySound(p_150716_, p_150717_, p_150718_); + return true; +@@ -165,7 +_,32 @@ - protected void playEmptySound(@Nullable Player p_40696_, LevelAccessor p_40697_, BlockPos p_40698_) { -- SoundEvent soundevent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; -+ SoundEvent soundevent = this.content.getFluidType().getSound(p_40696_, p_40697_, p_40698_, net.minecraftforge.common.SoundActions.BUCKET_EMPTY); -+ if(soundevent == null) soundevent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; - p_40697_.playSound(p_40696_, p_40698_, soundevent, SoundSource.BLOCKS, 1.0F, 1.0F); - p_40697_.gameEvent(p_40696_, GameEvent.FLUID_PLACE, p_40698_); -+ } + protected void playEmptySound(@Nullable Player p_40696_, LevelAccessor p_40697_, BlockPos p_40698_) { + SoundEvent soundevent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; ++ var custom = this.content.getFluidType().getSound(p_40696_, p_40697_, p_40698_, net.minecraftforge.common.SoundActions.BUCKET_EMPTY); ++ if (custom != null) { ++ soundevent = custom; ++ } + p_40697_.playSound(p_40696_, p_40698_, soundevent, SoundSource.BLOCKS, 1.0F, 1.0F); + p_40697_.gameEvent(p_40696_, GameEvent.FLUID_PLACE, p_40698_); ++ } + -+ @Override -+ public net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable net.minecraft.nbt.CompoundTag nbt) { -+ if (this.getClass() == BucketItem.class) -+ return new net.minecraftforge.fluids.capability.wrappers.FluidBucketWrapper(stack); -+ else -+ return super.initCapabilities(stack, nbt); -+ } ++ /** Forge: TODO: Forge ItemStack capabilities - Lex 042724 ++ @Override ++ public net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable net.minecraft.nbt.CompoundTag nbt) { ++ if (this.getClass() == BucketItem.class) { ++ return new net.minecraftforge.fluids.capability.wrappers.FluidBucketWrapper(stack); ++ } else { ++ return super.initCapabilities(stack, nbt); ++ } ++ } ++ */ + -+ private final java.util.function.Supplier fluidSupplier; -+ public Fluid getFluid() { return fluidSupplier.get(); } ++ private final java.util.function.Supplier fluidSupplier; + -+ protected boolean canBlockContainFluid(Level worldIn, BlockPos posIn, BlockState blockstate) { -+ return blockstate.getBlock() instanceof LiquidBlockContainer liquid && liquid.canPlaceLiquid(null, worldIn, posIn, blockstate, this.content); - } ++ public Fluid getFluid() { ++ return fluidSupplier.get(); ++ } ++ ++ protected boolean canBlockContainFluid(Level worldIn, BlockPos posIn, BlockState blockstate) { ++ return blockstate.getBlock() instanceof LiquidBlockContainer liquid && liquid.canPlaceLiquid(null, worldIn, posIn, blockstate, this.content); + } } diff --git a/patches/minecraft/net/minecraft/world/item/BundleItem.java.patch b/patches/minecraft/net/minecraft/world/item/BundleItem.java.patch index 38ce946c82..82e8af93d8 100644 --- a/patches/minecraft/net/minecraft/world/item/BundleItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BundleItem.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/item/BundleItem.java +++ b/net/minecraft/world/item/BundleItem.java -@@ -40,7 +_,7 @@ - } +@@ -38,7 +_,7 @@ - public boolean overrideStackedOnOther(ItemStack p_150733_, Slot p_150734_, ClickAction p_150735_, Player p_150736_) { -- if (p_150735_ != ClickAction.SECONDARY) { -+ if (p_150733_.getCount() != 1 || p_150735_ != ClickAction.SECONDARY) { - return false; - } else { - ItemStack itemstack = p_150734_.getItem(); -@@ -62,6 +_,7 @@ - } + @Override + public boolean overrideStackedOnOther(ItemStack p_150733_, Slot p_150734_, ClickAction p_150735_, Player p_150736_) { +- if (p_150735_ != ClickAction.SECONDARY) { ++ if (p_150733_.getCount() != 1 || p_150735_ != ClickAction.SECONDARY) { + return false; + } else { + BundleContents bundlecontents = p_150733_.get(DataComponents.BUNDLE_CONTENTS); +@@ -69,6 +_,7 @@ - public boolean overrideOtherStackedOnMe(ItemStack p_150742_, ItemStack p_150743_, Slot p_150744_, ClickAction p_150745_, Player p_150746_, SlotAccess p_150747_) { -+ if (p_150742_.getCount() != 1) return false; - if (p_150745_ == ClickAction.SECONDARY && p_150744_.allowModification(p_150746_)) { - if (p_150743_.isEmpty()) { - removeOne(p_150742_).ifPresent((p_186347_) -> { + @Override + public boolean overrideOtherStackedOnMe(ItemStack p_150742_, ItemStack p_150743_, Slot p_150744_, ClickAction p_150745_, Player p_150746_, SlotAccess p_150747_) { ++ if (p_150742_.getCount() != 1) return false; + if (p_150745_ == ClickAction.SECONDARY && p_150744_.allowModification(p_150746_)) { + BundleContents bundlecontents = p_150742_.get(DataComponents.BUNDLE_CONTENTS); + if (bundlecontents == null) { diff --git a/patches/minecraft/net/minecraft/world/item/ChorusFruitItem.java.patch b/patches/minecraft/net/minecraft/world/item/ChorusFruitItem.java.patch index 7a8ce3401f..47e6611d82 100644 --- a/patches/minecraft/net/minecraft/world/item/ChorusFruitItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ChorusFruitItem.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/item/ChorusFruitItem.java +++ b/net/minecraft/world/item/ChorusFruitItem.java -@@ -29,7 +_,9 @@ - } +@@ -34,7 +_,9 @@ + } - Vec3 vec3 = p_40714_.position(); -- if (p_40714_.randomTeleport(d0, d1, d2, true)) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onChorusFruitTeleport(p_40714_, d0, d1, d2); -+ if (event.isCanceled()) return itemstack; -+ if (p_40714_.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true)) { - p_40713_.gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(p_40714_)); - SoundSource soundsource; - SoundEvent soundevent; + Vec3 vec3 = p_40714_.position(); +- if (p_40714_.randomTeleport(d0, d1, d2, true)) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onChorusFruitTeleport(p_40714_, d0, d1, d2); ++ if (event.isCanceled()) return itemstack; ++ if (p_40714_.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true)) { + p_40713_.gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(p_40714_)); + SoundSource soundsource; + SoundEvent soundevent; diff --git a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch index a4b3a1ed83..26807841ce 100644 --- a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch +++ b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch @@ -1,210 +1,221 @@ --- a/net/minecraft/world/item/CreativeModeTab.java +++ b/net/minecraft/world/item/CreativeModeTab.java -@@ -31,16 +_,38 @@ - private Consumer> searchTreeBuilder; - private final Supplier iconGenerator; - private final CreativeModeTab.DisplayItemsGenerator displayItemsGenerator; -+ private net.minecraft.resources.ResourceLocation backgroundLocation; -+ private final boolean hasSearchBar; -+ private final int searchBarWidth; -+ private final int labelColor; -+ private final int slotColor; -+ public final List tabsBefore; -+ public final List tabsAfter; +@@ -31,6 +_,13 @@ + private Consumer> searchTreeBuilder; + private final Supplier iconGenerator; + private final CreativeModeTab.DisplayItemsGenerator displayItemsGenerator; ++ private net.minecraft.resources.ResourceLocation backgroundLocation; ++ private final boolean hasSearchBar; ++ private final int searchBarWidth; ++ private final int labelColor; ++ private final int slotColor; ++ public final List tabsBefore; ++ public final List tabsAfter; -- CreativeModeTab(CreativeModeTab.Row p_260217_, int p_259557_, CreativeModeTab.Type p_260176_, Component p_260100_, Supplier p_259543_, CreativeModeTab.DisplayItemsGenerator p_259085_) { -+ CreativeModeTab(CreativeModeTab.Row p_260217_, int p_259557_, CreativeModeTab.Type p_260176_, Component p_260100_, Supplier p_259543_, CreativeModeTab.DisplayItemsGenerator p_259085_, net.minecraft.resources.ResourceLocation backgroundLocation, boolean hasSearchBar, int searchBarWidth, int labelColor, int slotColor, List tabsBefore, List tabsAfter) { - this.row = p_260217_; - this.column = p_259557_; - this.displayName = p_260100_; - this.iconGenerator = p_259543_; - this.displayItemsGenerator = p_259085_; - this.type = p_260176_; -- } + CreativeModeTab( + CreativeModeTab.Row p_260217_, +@@ -38,7 +_,8 @@ + CreativeModeTab.Type p_260176_, + Component p_260100_, + Supplier p_259543_, +- CreativeModeTab.DisplayItemsGenerator p_259085_ ++ CreativeModeTab.DisplayItemsGenerator p_259085_, ++ Builder builder + ) { + this.row = p_260217_; + this.column = p_259557_; +@@ -46,8 +_,24 @@ + this.iconGenerator = p_259543_; + this.displayItemsGenerator = p_259085_; + this.type = p_260176_; +- } - -+ this.backgroundLocation = backgroundLocation; -+ this.hasSearchBar = hasSearchBar; -+ this.searchBarWidth = searchBarWidth; -+ this.labelColor = labelColor; -+ this.slotColor = slotColor; -+ this.tabsBefore = List.copyOf(tabsBefore); -+ this.tabsAfter = List.copyOf(tabsAfter); -+ } ++ this.backgroundLocation = builder.backgroundLocation; ++ this.hasSearchBar = builder.hasSearchBar; ++ this.searchBarWidth = builder.searchBarWidth; ++ this.labelColor = builder.labelColor; ++ this.slotColor = builder.slotColor; ++ this.tabsBefore = List.copyOf(builder.tabsBefore); ++ this.tabsAfter = List.copyOf(builder.tabsAfter); ++ } + -+ protected CreativeModeTab(CreativeModeTab.Builder builder) { -+ this(builder.row, builder.column, builder.type, builder.displayName, builder.iconGenerator, builder.displayItemsGenerator, builder.backgroundLocation, builder.hasSearchBar, builder.searchBarWidth, builder.labelColor, builder.slotColor, builder.tabsBefore, builder.tabsAfter); -+ } ++ protected CreativeModeTab(CreativeModeTab.Builder builder) { ++ this(builder.row, builder.column, builder.type, builder.displayName, builder.iconGenerator, builder.displayItemsGenerator, builder); ++ } + -+ public static CreativeModeTab.Builder builder() { -+ return new CreativeModeTab.Builder(Row.TOP, 0); -+ } -+ /** @deprecated Forge: use {@link #builder()} **/ @Deprecated - public static CreativeModeTab.Builder builder(CreativeModeTab.Row p_259342_, int p_260312_) { - return new CreativeModeTab.Builder(p_259342_, p_260312_); - } -@@ -57,6 +_,10 @@ - return this.iconItemStack; - } ++ public static CreativeModeTab.Builder builder() { ++ return new CreativeModeTab.Builder(Row.TOP, 0); ++ } ++ ++ /** @deprecated Forge: use {@link #builder()} **/ + public static CreativeModeTab.Builder builder(CreativeModeTab.Row p_259342_, int p_260312_) { + return new CreativeModeTab.Builder(p_259342_, p_260312_); + } +@@ -64,6 +_,7 @@ + return this.iconItemStack; + } -+ /** -+ * Forge: Use {@link #getBackgroundLocation()} instead. -+ */ -+ @Deprecated - public String getBackgroundSuffix() { - return this.backgroundSuffix; - } -@@ -98,7 +_,7 @@ - ResourceKey resourcekey = BuiltInRegistries.CREATIVE_MODE_TAB.getResourceKey(this).orElseThrow(() -> { - return new IllegalStateException("Unregistered creative tab: " + this); - }); -- this.displayItemsGenerator.accept(p_270156_, creativemodetab$itemdisplaybuilder); -+ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, resourcekey, this.displayItemsGenerator, p_270156_, creativemodetab$itemdisplaybuilder); - this.displayItems = creativemodetab$itemdisplaybuilder.tabContents; - this.displayItemsSearchTab = creativemodetab$itemdisplaybuilder.searchTabContents; - this.rebuildSearchTree(); -@@ -127,6 +_,26 @@ ++ /** @deprecated Forge: Use {@link #getBackgroundLocation()} instead. */ + public String getBackgroundSuffix() { + return this.backgroundSuffix; + } +@@ -105,7 +_,7 @@ + ResourceKey resourcekey = BuiltInRegistries.CREATIVE_MODE_TAB + .getResourceKey(this) + .orElseThrow(() -> new IllegalStateException("Unregistered creative tab: " + this)); +- this.displayItemsGenerator.accept(p_270156_, creativemodetab$itemdisplaybuilder); ++ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, resourcekey, this.displayItemsGenerator, p_270156_, creativemodetab$itemdisplaybuilder); + this.displayItems = creativemodetab$itemdisplaybuilder.tabContents; + this.displayItemsSearchTab = creativemodetab$itemdisplaybuilder.searchTabContents; + this.rebuildSearchTree(); +@@ -133,6 +_,26 @@ + } + } - } ++ public net.minecraft.resources.ResourceLocation getBackgroundLocation() { ++ return backgroundLocation; ++ } ++ ++ public boolean hasSearchBar() { ++ return this.hasSearchBar; ++ } ++ ++ public int getSearchBarWidth() { ++ return searchBarWidth; ++ } ++ ++ public int getLabelColor() { ++ return labelColor; ++ } ++ ++ public int getSlotColor() { ++ return slotColor; ++ } ++ + public static class Builder { + private static final CreativeModeTab.DisplayItemsGenerator EMPTY_GENERATOR = (p_270422_, p_259433_) -> { + }; +@@ -146,6 +_,16 @@ + private boolean alignedRight = false; + private CreativeModeTab.Type type = CreativeModeTab.Type.CATEGORY; + private String backgroundSuffix = "items.png"; ++ @Nullable ++ private net.minecraft.resources.ResourceLocation backgroundLocation; ++ private boolean hasSearchBar = false; ++ private int searchBarWidth = 89; ++ private int labelColor = 4210752; ++ private int slotColor = -2130706433; ++ private java.util.function.Function tabFactory = ++ builder -> new CreativeModeTab(builder.row, builder.column, builder.type, builder.displayName, builder.iconGenerator, builder.displayItemsGenerator, builder); ++ private final List tabsBefore = new java.util.ArrayList<>(); ++ private final List tabsAfter = new java.util.ArrayList<>(); -+ public net.minecraft.resources.ResourceLocation getBackgroundLocation() { -+ return backgroundLocation; -+ } -+ -+ public boolean hasSearchBar() { -+ return this.hasSearchBar; -+ } -+ -+ public int getSearchBarWidth() { -+ return searchBarWidth; -+ } -+ -+ public int getLabelColor() { -+ return labelColor; -+ } -+ -+ public int getSlotColor() { -+ return slotColor; -+ } -+ - public static class Builder { - private static final CreativeModeTab.DisplayItemsGenerator EMPTY_GENERATOR = (p_270422_, p_259433_) -> { - }; -@@ -142,6 +_,15 @@ - private boolean alignedRight = false; - private CreativeModeTab.Type type = CreativeModeTab.Type.CATEGORY; - private String backgroundSuffix = "items.png"; -+ @Nullable -+ private net.minecraft.resources.ResourceLocation backgroundLocation; -+ private boolean hasSearchBar = false; -+ private int searchBarWidth = 89; -+ private int labelColor = 4210752; -+ private int slotColor = -2130706433; -+ private java.util.function.Function tabFactory = CreativeModeTab::new; -+ private final List tabsBefore = new java.util.ArrayList<>(); -+ private final List tabsAfter = new java.util.ArrayList<>(); + public Builder(CreativeModeTab.Row p_259171_, int p_259661_) { + this.row = p_259171_; +@@ -184,11 +_,89 @@ - public Builder(CreativeModeTab.Row p_259171_, int p_259661_) { - this.row = p_259171_; -@@ -180,11 +_,87 @@ + protected CreativeModeTab.Builder type(CreativeModeTab.Type p_259283_) { + this.type = p_259283_; ++ if (p_259283_ == Type.SEARCH) { ++ return this.withSearchBar(); ++ } + return this; + } - protected CreativeModeTab.Builder type(CreativeModeTab.Type p_259283_) { - this.type = p_259283_; -+ if (p_259283_ == Type.SEARCH) -+ return this.withSearchBar(); - return this; - } + public CreativeModeTab.Builder backgroundSuffix(String p_259981_) { +- this.backgroundSuffix = p_259981_; ++ return withBackgroundLocation(new net.minecraft.resources.ResourceLocation("textures/gui/container/creative_inventory/tab_" + p_259981_)); ++ } ++ ++ /** ++ * Sets the location of the tab background. ++ */ ++ public CreativeModeTab.Builder withBackgroundLocation(net.minecraft.resources.ResourceLocation background) { ++ this.backgroundLocation = background; ++ return this; ++ } ++ ++ /** ++ * Gives this tab a search bar. ++ *

Note that, if using a custom {@link #withBackgroundLocation(net.minecraft.resources.ResourceLocation) background image}, you will need to make sure that your image contains the input box and the scroll bar.

++ */ ++ public CreativeModeTab.Builder withSearchBar() { ++ this.hasSearchBar = true; ++ if (this.backgroundLocation == null) { ++ return this.backgroundSuffix("item_search.png"); ++ } ++ return this; ++ } ++ ++ /** ++ * Gives this tab a search bar, with a specific width. ++ * @param searchBarWidth the width of the search bar ++ */ ++ public CreativeModeTab.Builder withSearchBar(int searchBarWidth) { ++ this.searchBarWidth = searchBarWidth; ++ return withSearchBar(); ++ } ++ ++ /** ++ * Sets the color of the tab label. ++ */ ++ public CreativeModeTab.Builder withLabelColor(int labelColor) { ++ this.labelColor = labelColor; ++ return this; ++ } ++ ++ /** ++ * Sets the color of tab's slots. ++ */ ++ public CreativeModeTab.Builder withSlotColor(int slotColor) { ++ this.slotColor = slotColor; ++ return this; ++ } ++ ++ public CreativeModeTab.Builder withTabFactory(java.util.function.Function tabFactory) { ++ this.tabFactory = tabFactory; ++ return this; ++ } ++ ++ /** Define tabs that should come before this tab. This tab will be placed after the {@code tabs}. **/ ++ public CreativeModeTab.Builder withTabsBefore(net.minecraft.resources.ResourceLocation... tabs) { ++ this.tabsBefore.addAll(List.of(tabs)); ++ return this; ++ } ++ ++ /** Define tabs that should come after this tab. This tab will be placed before the {@code tabs}.**/ ++ public CreativeModeTab.Builder withTabsAfter(net.minecraft.resources.ResourceLocation... tabs) { ++ this.tabsAfter.addAll(List.of(tabs)); ++ return this; ++ } ++ ++ /** Define tabs that should come before this tab. This tab will be placed after the {@code tabs}. **/ ++ @SafeVarargs ++ public final CreativeModeTab.Builder withTabsBefore(net.minecraft.resources.ResourceKey... tabs) { ++ java.util.stream.Stream.of(tabs).map(net.minecraft.resources.ResourceKey::location).forEach(this.tabsBefore::add); ++ return this; ++ } ++ ++ /** Define tabs that should come after this tab. This tab will be placed before the {@code tabs}.**/ ++ @SafeVarargs ++ public final CreativeModeTab.Builder withTabsAfter(net.minecraft.resources.ResourceKey... tabs) { ++ java.util.stream.Stream.of(tabs).map(net.minecraft.resources.ResourceKey::location).forEach(this.tabsAfter::add); + return this; + } - public CreativeModeTab.Builder backgroundSuffix(String p_259981_) { -- this.backgroundSuffix = p_259981_; -+ return withBackgroundLocation(new net.minecraft.resources.ResourceLocation("textures/gui/container/creative_inventory/tab_" + p_259981_)); -+ } -+ -+ /** -+ * Sets the location of the tab background. -+ */ -+ public CreativeModeTab.Builder withBackgroundLocation(net.minecraft.resources.ResourceLocation background) { -+ this.backgroundLocation = background; -+ return this; -+ } -+ -+ /** -+ * Gives this tab a search bar. -+ *

Note that, if using a custom {@link #withBackgroundLocation(net.minecraft.resources.ResourceLocation) background image}, you will need to make sure that your image contains the input box and the scroll bar.

-+ */ -+ public CreativeModeTab.Builder withSearchBar() { -+ this.hasSearchBar = true; -+ if (this.backgroundLocation == null) -+ return this.backgroundSuffix("item_search.png"); -+ return this; -+ } -+ -+ /** -+ * Gives this tab a search bar, with a specific width. -+ * @param searchBarWidth the width of the search bar -+ */ -+ public CreativeModeTab.Builder withSearchBar(int searchBarWidth) { -+ this.searchBarWidth = searchBarWidth; -+ return withSearchBar(); -+ } -+ -+ /** -+ * Sets the color of the tab label. -+ */ -+ public CreativeModeTab.Builder withLabelColor(int labelColor) { -+ this.labelColor = labelColor; -+ return this; -+ } -+ -+ /** -+ * Sets the color of tab's slots. -+ */ -+ public CreativeModeTab.Builder withSlotColor(int slotColor) { -+ this.slotColor = slotColor; -+ return this; -+ } -+ -+ public CreativeModeTab.Builder withTabFactory(java.util.function.Function tabFactory) { -+ this.tabFactory = tabFactory; -+ return this; -+ } -+ -+ /** Define tabs that should come before this tab. This tab will be placed after the {@code tabs}. **/ -+ public CreativeModeTab.Builder withTabsBefore(net.minecraft.resources.ResourceLocation... tabs) { -+ this.tabsBefore.addAll(List.of(tabs)); -+ return this; -+ } -+ -+ /** Define tabs that should come after this tab. This tab will be placed before the {@code tabs}.**/ -+ public CreativeModeTab.Builder withTabsAfter(net.minecraft.resources.ResourceLocation... tabs) { -+ this.tabsAfter.addAll(List.of(tabs)); -+ return this; -+ } -+ -+ /** Define tabs that should come before this tab. This tab will be placed after the {@code tabs}. **/ -+ @SafeVarargs -+ public final CreativeModeTab.Builder withTabsBefore(net.minecraft.resources.ResourceKey... tabs) { -+ java.util.stream.Stream.of(tabs).map(net.minecraft.resources.ResourceKey::location).forEach(this.tabsBefore::add); -+ return this; -+ } -+ -+ /** Define tabs that should come after this tab. This tab will be placed before the {@code tabs}.**/ -+ @SafeVarargs -+ public final CreativeModeTab.Builder withTabsAfter(net.minecraft.resources.ResourceKey... tabs) { -+ java.util.stream.Stream.of(tabs).map(net.minecraft.resources.ResourceKey::location).forEach(this.tabsAfter::add); - return this; - } - -@@ -192,11 +_,12 @@ - if ((this.type == CreativeModeTab.Type.HOTBAR || this.type == CreativeModeTab.Type.INVENTORY) && this.displayItemsGenerator != EMPTY_GENERATOR) { - throw new IllegalStateException("Special tabs can't have display items"); - } else { -- CreativeModeTab creativemodetab = new CreativeModeTab(this.row, this.column, this.type, this.displayName, this.iconGenerator, this.displayItemsGenerator); -+ CreativeModeTab creativemodetab = tabFactory.apply(this); - creativemodetab.alignedRight = this.alignedRight; - creativemodetab.showTitle = this.showTitle; - creativemodetab.canScroll = this.canScroll; - creativemodetab.backgroundSuffix = this.backgroundSuffix; -+ creativemodetab.backgroundLocation = this.backgroundLocation != null ? this.backgroundLocation : new net.minecraft.resources.ResourceLocation("textures/gui/container/creative_inventory/tab_" + this.backgroundSuffix); - return creativemodetab; - } - } +@@ -196,13 +_,12 @@ + if ((this.type == CreativeModeTab.Type.HOTBAR || this.type == CreativeModeTab.Type.INVENTORY) && this.displayItemsGenerator != EMPTY_GENERATOR) { + throw new IllegalStateException("Special tabs can't have display items"); + } else { +- CreativeModeTab creativemodetab = new CreativeModeTab( +- this.row, this.column, this.type, this.displayName, this.iconGenerator, this.displayItemsGenerator +- ); ++ CreativeModeTab creativemodetab = this.tabFactory.apply(this); + creativemodetab.alignedRight = this.alignedRight; + creativemodetab.showTitle = this.showTitle; + creativemodetab.canScroll = this.canScroll; + creativemodetab.backgroundSuffix = this.backgroundSuffix; ++ creativemodetab.backgroundLocation = this.backgroundLocation != null ? this.backgroundLocation : new net.minecraft.resources.ResourceLocation("textures/gui/container/creative_inventory/tab_" + this.backgroundSuffix); + return creativemodetab; + } + } diff --git a/patches/minecraft/net/minecraft/world/item/CreativeModeTabs.java.patch b/patches/minecraft/net/minecraft/world/item/CreativeModeTabs.java.patch deleted file mode 100644 index 4b57e23182..0000000000 --- a/patches/minecraft/net/minecraft/world/item/CreativeModeTabs.java.patch +++ /dev/null @@ -1,20 +0,0 @@ ---- a/net/minecraft/world/item/CreativeModeTabs.java -+++ b/net/minecraft/world/item/CreativeModeTabs.java -@@ -1679,7 +_,7 @@ - - private static void generateEnchantmentBookTypesOnlyMaxLevel(CreativeModeTab.Output p_270868_, HolderLookup p_270903_, Set p_270380_, CreativeModeTab.TabVisibility p_270407_) { - p_270903_.listElements().map(Holder::value).filter((p_270008_) -> { -- return p_270380_.contains(p_270008_.category); -+ return p_270008_.allowedInCreativeTab(Items.ENCHANTED_BOOK, p_270380_); - }).map((p_270038_) -> { - return EnchantedBookItem.createForEnchantment(new EnchantmentInstance(p_270038_, p_270038_.getMaxLevel())); - }).forEach((p_269989_) -> { -@@ -1689,7 +_,7 @@ - - private static void generateEnchantmentBookTypesAllLevels(CreativeModeTab.Output p_270961_, HolderLookup p_270628_, Set p_271024_, CreativeModeTab.TabVisibility p_270805_) { - p_270628_.listElements().map(Holder::value).filter((p_269991_) -> { -- return p_271024_.contains(p_269991_.category); -+ return p_269991_.allowedInCreativeTab(Items.ENCHANTED_BOOK, p_271024_); - }).flatMap((p_270024_) -> { - return IntStream.rangeClosed(p_270024_.getMinLevel(), p_270024_.getMaxLevel()).mapToObj((p_270006_) -> { - return EnchantedBookItem.createForEnchantment(new EnchantmentInstance(p_270024_, p_270006_)); diff --git a/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch b/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch index 3157a4ce63..cd4a9636eb 100644 --- a/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/item/CrossbowItem.java +++ b/net/minecraft/world/item/CrossbowItem.java -@@ -241,6 +_,7 @@ - } - - public static void performShooting(Level p_40888_, LivingEntity p_40889_, InteractionHand p_40890_, ItemStack p_40891_, float p_40892_, float p_40893_) { -+ if (p_40889_ instanceof Player player && net.minecraftforge.event.ForgeEventFactory.onArrowLoose(p_40891_, p_40889_.level(), player, 1, true) < 0) return; - List list = getChargedProjectiles(p_40891_); - float[] afloat = getShotPitches(p_40889_.getRandom()); - +@@ -169,6 +_,7 @@ + Level p_40888_, LivingEntity p_40889_, InteractionHand p_40890_, ItemStack p_40891_, float p_40892_, float p_40893_, @Nullable LivingEntity p_329478_ + ) { + if (!p_40888_.isClientSide()) { ++ if (p_40889_ instanceof Player player && net.minecraftforge.event.ForgeEventFactory.onArrowLoose(p_40891_, p_40889_.level(), player, 1, true) < 0) return; + ChargedProjectiles chargedprojectiles = p_40891_.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); + if (chargedprojectiles != null && !chargedprojectiles.isEmpty()) { + this.shoot( diff --git a/patches/minecraft/net/minecraft/world/item/DiggerItem.java.patch b/patches/minecraft/net/minecraft/world/item/DiggerItem.java.patch deleted file mode 100644 index d69f98ed07..0000000000 --- a/patches/minecraft/net/minecraft/world/item/DiggerItem.java.patch +++ /dev/null @@ -1,26 +0,0 @@ ---- a/net/minecraft/world/item/DiggerItem.java -+++ b/net/minecraft/world/item/DiggerItem.java -@@ -60,7 +_,11 @@ - return this.attackDamageBaseline; - } - -+ @Deprecated // FORGE: Use stack sensitive variant below - public boolean isCorrectToolForDrops(BlockState p_150816_) { -+ if (net.minecraftforge.common.TierSortingRegistry.isTierSorted(getTier())) { -+ return net.minecraftforge.common.TierSortingRegistry.isCorrectTierForDrops(getTier(), p_150816_) && p_150816_.is(this.blocks); -+ } - int i = this.getTier().getLevel(); - if (i < 3 && p_150816_.is(BlockTags.NEEDS_DIAMOND_TOOL)) { - return false; -@@ -69,5 +_,11 @@ - } else { - return i < 1 && p_150816_.is(BlockTags.NEEDS_STONE_TOOL) ? false : p_150816_.is(this.blocks); - } -+ } -+ -+ // FORGE START -+ @Override -+ public boolean isCorrectToolForDrops(ItemStack stack, BlockState state) { -+ return state.is(blocks) && net.minecraftforge.common.TierSortingRegistry.isCorrectTierForDrops(getTier(), state); - } - } diff --git a/patches/minecraft/net/minecraft/world/item/DispensibleContainerItem.java.patch b/patches/minecraft/net/minecraft/world/item/DispensibleContainerItem.java.patch index b981952aeb..d04842eb0a 100644 --- a/patches/minecraft/net/minecraft/world/item/DispensibleContainerItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/DispensibleContainerItem.java.patch @@ -6,9 +6,9 @@ -public interface DispensibleContainerItem { +public interface DispensibleContainerItem extends net.minecraftforge.common.extensions.IForgeDispensibleContainerItem { - default void checkExtraContent(@Nullable Player p_150817_, Level p_150818_, ItemStack p_150819_, BlockPos p_150820_) { - } + default void checkExtraContent(@Nullable Player p_150817_, Level p_150818_, ItemStack p_150819_, BlockPos p_150820_) { + } -+ @Deprecated //Forge: use the ItemStack sensitive version - boolean emptyContents(@Nullable Player p_150821_, Level p_150822_, BlockPos p_150823_, @Nullable BlockHitResult p_150824_); ++ @Deprecated //Forge: use the ItemStack sensitive version + boolean emptyContents(@Nullable Player p_150821_, Level p_150822_, BlockPos p_150823_, @Nullable BlockHitResult p_150824_); } diff --git a/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch b/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch index 6d5b88ea36..5c79d7215f 100644 --- a/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch +++ b/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch @@ -1,42 +1,45 @@ --- a/net/minecraft/world/item/DyeColor.java +++ b/net/minecraft/world/item/DyeColor.java -@@ -40,6 +_,7 @@ - private final MapColor mapColor; - private final float[] textureDiffuseColors; - private final int fireworkColor; -+ private final net.minecraft.tags.TagKey tag; - private final int textColor; +@@ -43,6 +_,7 @@ + private final float[] textureDiffuseColors; + private final int fireworkColor; + private final int textColor; ++ private final net.minecraft.tags.TagKey tag; - private DyeColor(int p_41046_, String p_41047_, int p_41048_, MapColor p_285297_, int p_41050_, int p_41051_) { -@@ -50,6 +_,7 @@ - int i = (p_41048_ & 16711680) >> 16; - int j = (p_41048_ & '\uff00') >> 8; - int k = (p_41048_ & 255) >> 0; -+ this.tag = net.minecraft.tags.ItemTags.create(new net.minecraft.resources.ResourceLocation("forge", "dyes/" + p_41047_)); - this.textureDiffuseColors = new float[]{(float)i / 255.0F, (float)j / 255.0F, (float)k / 255.0F}; - this.fireworkColor = p_41050_; - } -@@ -100,5 +_,23 @@ + private DyeColor(final int p_41046_, final String p_41047_, final int p_41048_, final MapColor p_285297_, final int p_41050_, final int p_41051_) { + this.id = p_41046_; +@@ -54,6 +_,7 @@ + int k = (p_41048_ & 0xFF) >> 0; + this.textureDiffuseColors = new float[]{(float)i / 255.0F, (float)j / 255.0F, (float)k / 255.0F}; + this.fireworkColor = p_41050_; ++ this.tag = net.minecraft.tags.ItemTags.create(new net.minecraft.resources.ResourceLocation("forge", "dyes/" + p_41047_)); + } - public String getSerializedName() { - return this.name; -+ } + public int getId() { +@@ -104,5 +_,26 @@ + @Override + public String getSerializedName() { + return this.name; ++ } + -+ public net.minecraft.tags.TagKey getTag() { -+ return tag; -+ } + -+ @Nullable -+ public static DyeColor getColor(ItemStack stack) { -+ if (stack.getItem() instanceof DyeItem) -+ return ((DyeItem)stack.getItem()).getDyeColor(); ++ public net.minecraft.tags.TagKey getTag() { ++ return tag; ++ } + -+ for (int x = 0; x < BLACK.getId(); x++) { -+ DyeColor color = byId(x); -+ if (stack.is(color.getTag())) -+ return color; -+ } ++ @Nullable ++ public static DyeColor getColor(ItemStack stack) { ++ if (stack.getItem() instanceof DyeItem dye) { ++ return dye.getDyeColor(); ++ } + -+ return null; - } ++ for (int x = 0; x < BLACK.getId(); x++) { ++ var color = byId(x); ++ if (stack.is(color.getTag())) { ++ return color; ++ } ++ } ++ ++ return null; + } } diff --git a/patches/minecraft/net/minecraft/world/item/DyeableHorseArmorItem.java.patch b/patches/minecraft/net/minecraft/world/item/DyeableHorseArmorItem.java.patch deleted file mode 100644 index 79d6002a10..0000000000 --- a/patches/minecraft/net/minecraft/world/item/DyeableHorseArmorItem.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/world/item/DyeableHorseArmorItem.java -+++ b/net/minecraft/world/item/DyeableHorseArmorItem.java -@@ -4,4 +_,7 @@ - public DyeableHorseArmorItem(int p_41110_, String p_41111_, Item.Properties p_41112_) { - super(p_41110_, p_41111_, p_41112_); - } -+ public DyeableHorseArmorItem(int p_41110_, net.minecraft.resources.ResourceLocation p_41111_, Item.Properties p_41112_) { -+ super(p_41110_, p_41111_, p_41112_); -+ } - } diff --git a/patches/minecraft/net/minecraft/world/item/ElytraItem.java.patch b/patches/minecraft/net/minecraft/world/item/ElytraItem.java.patch index 810148ca52..b35a4ca8b2 100644 --- a/patches/minecraft/net/minecraft/world/item/ElytraItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ElytraItem.java.patch @@ -1,28 +1,26 @@ --- a/net/minecraft/world/item/ElytraItem.java +++ b/net/minecraft/world/item/ElytraItem.java -@@ -27,6 +_,25 @@ - return this.swapWithEquipmentSlot(this, p_41137_, p_41138_, p_41139_); - } - -+ @Override -+ public boolean canElytraFly(ItemStack stack, net.minecraft.world.entity.LivingEntity entity) { -+ return ElytraItem.isFlyEnabled(stack); -+ } +@@ -39,4 +_,23 @@ + public EquipmentSlot getEquipmentSlot() { + return EquipmentSlot.CHEST; + } + -+ @Override -+ public boolean elytraFlightTick(ItemStack stack, net.minecraft.world.entity.LivingEntity entity, int flightTicks) { -+ if (!entity.level().isClientSide) { -+ int nextFlightTick = flightTicks + 1; -+ if (nextFlightTick % 10 == 0) { -+ if (nextFlightTick % 20 == 0) { -+ stack.hurtAndBreak(1, entity, e -> e.broadcastBreakEvent(net.minecraft.world.entity.EquipmentSlot.CHEST)); -+ } -+ entity.gameEvent(net.minecraft.world.level.gameevent.GameEvent.ELYTRA_GLIDE); -+ } -+ } -+ return true; -+ } ++ @Override ++ public boolean canElytraFly(ItemStack stack, net.minecraft.world.entity.LivingEntity entity) { ++ return ElytraItem.isFlyEnabled(stack); ++ } + - public SoundEvent getEquipSound() { - return SoundEvents.ARMOR_EQUIP_ELYTRA; - } ++ @Override ++ public boolean elytraFlightTick(ItemStack stack, net.minecraft.world.entity.LivingEntity entity, int flightTicks) { ++ if (!entity.level().isClientSide) { ++ int nextFlightTick = flightTicks + 1; ++ if (nextFlightTick % 10 == 0) { ++ if (nextFlightTick % 20 == 0) { ++ stack.hurtAndBreak(1, entity, net.minecraft.world.entity.EquipmentSlot.CHEST); ++ } ++ entity.gameEvent(net.minecraft.world.level.gameevent.GameEvent.ELYTRA_GLIDE); ++ } ++ } ++ return true; ++ } + } diff --git a/patches/minecraft/net/minecraft/world/item/FireworkRocketItem.java.patch b/patches/minecraft/net/minecraft/world/item/FireworkRocketItem.java.patch deleted file mode 100644 index c6369cc82d..0000000000 --- a/patches/minecraft/net/minecraft/world/item/FireworkRocketItem.java.patch +++ /dev/null @@ -1,40 +0,0 @@ ---- a/net/minecraft/world/item/FireworkRocketItem.java -+++ b/net/minecraft/world/item/FireworkRocketItem.java -@@ -107,7 +_,7 @@ - return itemstack; - } - -- public static enum Shape { -+ public static enum Shape implements net.minecraftforge.common.IExtensibleEnum { - SMALL_BALL(0, "small_ball"), - LARGE_BALL(1, "large_ball"), - STAR(2, "star"), -@@ -131,8 +_,28 @@ - return this.name; - } - -+ public void save(net.minecraft.nbt.CompoundTag tag) { -+ tag.putByte("Type", (byte)getId()); -+ tag.putString("forge:shape_type", name()); -+ } -+ -+ /** Use {getShape(ComoundTag)} */ -+ @Deprecated - public static FireworkRocketItem.Shape byId(int p_41238_) { - return BY_ID.apply(p_41238_); -+ } -+ -+ public static FireworkRocketItem.Shape getShape(net.minecraft.nbt.CompoundTag tag) { -+ var name = tag.contains("forge:shape_type", 8) ? tag.getString("forge:shape_type") : null; -+ if (name == null) return byId(tag.getByte("Type")); -+ for (var ret : values()) -+ if (ret.name().equals(name)) -+ return ret; -+ return SMALL_BALL; -+ } -+ -+ public static Shape create(String registryName, int id, String shapeName) { -+ throw new IllegalStateException("Enum not extended"); - } - } - } diff --git a/patches/minecraft/net/minecraft/world/item/FireworkStarItem.java.patch b/patches/minecraft/net/minecraft/world/item/FireworkStarItem.java.patch deleted file mode 100644 index 0d3ad24d6d..0000000000 --- a/patches/minecraft/net/minecraft/world/item/FireworkStarItem.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/item/FireworkStarItem.java -+++ b/net/minecraft/world/item/FireworkStarItem.java -@@ -23,7 +_,7 @@ - } - - public static void appendHoverText(CompoundTag p_41257_, List p_41258_) { -- FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.byId(p_41257_.getByte("Type")); -+ FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.getShape(p_41257_); - p_41258_.add(Component.translatable("item.minecraft.firework_star.shape." + fireworkrocketitem$shape.getName()).withStyle(ChatFormatting.GRAY)); - int[] aint = p_41257_.getIntArray("Colors"); - if (aint.length > 0) { diff --git a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch index 3e0c2a9e9e..08ed0c4bd5 100644 --- a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch @@ -1,29 +1,25 @@ --- a/net/minecraft/world/item/FishingRodItem.java +++ b/net/minecraft/world/item/FishingRodItem.java -@@ -21,9 +_,13 @@ - if (p_41291_.fishing != null) { - if (!p_41290_.isClientSide) { - int i = p_41291_.fishing.retrieve(itemstack); -+ ItemStack original = itemstack.copy(); - itemstack.hurtAndBreak(i, p_41291_, (p_41288_) -> { - p_41288_.broadcastBreakEvent(p_41292_); - }); -+ if(itemstack.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(p_41291_, original, p_41292_); -+ } - } +@@ -23,7 +_,11 @@ + if (p_41291_.fishing != null) { + if (!p_41290_.isClientSide) { + int i = p_41291_.fishing.retrieve(itemstack); ++ ItemStack original = itemstack.copy(); + itemstack.hurtAndBreak(i, p_41291_, LivingEntity.getSlotForHand(p_41292_)); ++ if (itemstack.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(p_41291_, original, LivingEntity.getSlotForHand(p_41292_)); ++ } + } - p_41290_.playSound((Player)null, p_41291_.getX(), p_41291_.getY(), p_41291_.getZ(), SoundEvents.FISHING_BOBBER_RETRIEVE, SoundSource.NEUTRAL, 1.0F, 0.4F / (p_41290_.getRandom().nextFloat() * 0.4F + 0.8F)); -@@ -45,5 +_,12 @@ - - public int getEnchantmentValue() { - return 1; -+ } -+ -+ /* ******************** FORGE START ******************** */ + p_41290_.playSound( +@@ -64,5 +_,10 @@ + @Override + public int getEnchantmentValue() { + return 1; ++ } + + @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_FISHING_ROD_ACTIONS.contains(toolAction); - } ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_FISHING_ROD_ACTIONS.contains(toolAction); + } } diff --git a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch index 457cebb47d..8a0ac05b5d 100644 --- a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch @@ -1,36 +1,36 @@ --- a/net/minecraft/world/item/HoeItem.java +++ b/net/minecraft/world/item/HoeItem.java -@@ -22,6 +_,12 @@ +@@ -23,6 +_,12 @@ import net.minecraft.world.level.gameevent.GameEvent; public class HoeItem extends DiggerItem { -+ /** -+ * @deprecated Forge: This map is patched out of vanilla code. -+ * Listen to {@link net.minecraftforge.event.world.BlockEvent.BlockToolModificationEvent} -+ * or override {@link net.minecraftforge.common.extensions.IForgeBlock#getToolModifiedState(BlockState, UseOnContext, net.minecraftforge.common.ToolAction, boolean)}. -+ */ -+ @Deprecated - protected static final Map, Consumer>> TILLABLES = Maps.newHashMap(ImmutableMap.of(Blocks.GRASS_BLOCK, Pair.of(HoeItem::onlyIfAirAbove, changeIntoState(Blocks.FARMLAND.defaultBlockState())), Blocks.DIRT_PATH, Pair.of(HoeItem::onlyIfAirAbove, changeIntoState(Blocks.FARMLAND.defaultBlockState())), Blocks.DIRT, Pair.of(HoeItem::onlyIfAirAbove, changeIntoState(Blocks.FARMLAND.defaultBlockState())), Blocks.COARSE_DIRT, Pair.of(HoeItem::onlyIfAirAbove, changeIntoState(Blocks.DIRT.defaultBlockState())), Blocks.ROOTED_DIRT, Pair.of((p_238242_) -> { - return true; - }, changeIntoStateAndDropItem(Blocks.DIRT.defaultBlockState(), Items.HANGING_ROOTS)))); -@@ -33,7 +_,8 @@ - public InteractionResult useOn(UseOnContext p_41341_) { - Level level = p_41341_.getLevel(); - BlockPos blockpos = p_41341_.getClickedPos(); -- Pair, Consumer> pair = TILLABLES.get(level.getBlockState(blockpos).getBlock()); -+ BlockState toolModifiedState = level.getBlockState(blockpos).getToolModifiedState(p_41341_, net.minecraftforge.common.ToolActions.HOE_TILL, false); -+ Pair, Consumer> pair = toolModifiedState == null ? null : Pair.of(ctx -> true, changeIntoState(toolModifiedState)); - if (pair == null) { - return InteractionResult.PASS; - } else { -@@ -75,5 +_,10 @@ ++ /** ++ * @deprecated Forge: This map is patched out of vanilla code. ++ * Listen to {@link net.minecraftforge.event.world.BlockEvent.BlockToolModificationEvent} ++ * or override {@link net.minecraftforge.common.extensions.IForgeBlock#getToolModifiedState(BlockState, UseOnContext, net.minecraftforge.common.ToolAction, boolean)}. ++ */ ++ @Deprecated + protected static final Map, Consumer>> TILLABLES = Maps.newHashMap( + ImmutableMap.of( + Blocks.GRASS_BLOCK, +@@ -46,7 +_,8 @@ + public InteractionResult useOn(UseOnContext p_41341_) { + Level level = p_41341_.getLevel(); + BlockPos blockpos = p_41341_.getClickedPos(); +- Pair, Consumer> pair = TILLABLES.get(level.getBlockState(blockpos).getBlock()); ++ BlockState toolModifiedState = level.getBlockState(blockpos).getToolModifiedState(p_41341_, net.minecraftforge.common.ToolActions.HOE_TILL, false); ++ Pair, Consumer> pair = toolModifiedState == null ? null : Pair.of(ctx -> true, changeIntoState(toolModifiedState)); + if (pair == null) { + return InteractionResult.PASS; + } else { +@@ -86,5 +_,10 @@ - public static boolean onlyIfAirAbove(UseOnContext p_150857_) { - return p_150857_.getClickedFace() != Direction.DOWN && p_150857_.getLevel().getBlockState(p_150857_.getClickedPos().above()).isAir(); -+ } + public static boolean onlyIfAirAbove(UseOnContext p_150857_) { + return p_150857_.getClickedFace() != Direction.DOWN && p_150857_.getLevel().getBlockState(p_150857_.getClickedPos().above()).isAir(); ++ } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_HOE_ACTIONS.contains(toolAction); - } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_HOE_ACTIONS.contains(toolAction); + } } diff --git a/patches/minecraft/net/minecraft/world/item/HorseArmorItem.java.patch b/patches/minecraft/net/minecraft/world/item/HorseArmorItem.java.patch deleted file mode 100644 index bbc4c5d8a4..0000000000 --- a/patches/minecraft/net/minecraft/world/item/HorseArmorItem.java.patch +++ /dev/null @@ -1,26 +0,0 @@ ---- a/net/minecraft/world/item/HorseArmorItem.java -+++ b/net/minecraft/world/item/HorseArmorItem.java -@@ -5,16 +_,20 @@ - public class HorseArmorItem extends Item { - private static final String TEX_FOLDER = "textures/entity/horse/"; - private final int protection; -- private final String texture; -+ private final ResourceLocation texture; - - public HorseArmorItem(int p_41364_, String p_41365_, Item.Properties p_41366_) { -+ this(p_41364_, new ResourceLocation("textures/entity/horse/armor/horse_armor_" + p_41365_ + ".png"), p_41366_); -+ } -+ -+ public HorseArmorItem(int p_41364_, ResourceLocation p_41365_, Item.Properties p_41366_) { - super(p_41366_); - this.protection = p_41364_; -- this.texture = "textures/entity/horse/armor/horse_armor_" + p_41365_ + ".png"; -+ this.texture = p_41365_; - } - - public ResourceLocation getTexture() { -- return new ResourceLocation(this.texture); -+ return texture; - } - - public int getProtection() { diff --git a/patches/minecraft/net/minecraft/world/item/Item.java.patch b/patches/minecraft/net/minecraft/world/item/Item.java.patch index 6838929120..6a596d8c56 100644 --- a/patches/minecraft/net/minecraft/world/item/Item.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Item.java.patch @@ -1,205 +1,85 @@ --- a/net/minecraft/world/item/Item.java +++ b/net/minecraft/world/item/Item.java -@@ -50,9 +_,9 @@ +@@ -54,9 +_,12 @@ import net.minecraft.world.phys.Vec3; import org.slf4j.Logger; -public class Item implements FeatureElement, ItemLike { +public class Item implements FeatureElement, ItemLike, net.minecraftforge.common.extensions.IForgeItem { - private static final Logger LOGGER = LogUtils.getLogger(); -- public static final Map BY_BLOCK = Maps.newHashMap(); -+ public static final Map BY_BLOCK = net.minecraftforge.registries.GameData.getBlockItemMap(); - protected static final UUID BASE_ATTACK_DAMAGE_UUID = UUID.fromString("CB3F55D3-645C-4F38-A497-9C13A33DB5CF"); - protected static final UUID BASE_ATTACK_SPEED_UUID = UUID.fromString("FA233E1C-4180-4865-B01B-BCCE9785ACA3"); - public static final int MAX_STACK_SIZE = 64; -@@ -99,7 +_,8 @@ - LOGGER.error("Item classes should end with Item and {} doesn't.", (Object)s); - } - } -- -+ this.canRepair = p_41383_.canRepair; -+ initClient(); - } - - /** @deprecated */ -@@ -111,6 +_,8 @@ - public void onUseTick(Level p_41428_, LivingEntity p_41429_, ItemStack p_41430_, int p_41431_) { - } - -+ /** @deprecated Forge: {@link net.minecraftforge.common.extensions.IForgeItem#onDestroyed(ItemEntity, DamageSource) Use damage source sensitive version} */ -+ @Deprecated - public void onDestroyed(ItemEntity p_150887_) { - } - -@@ -134,9 +_,9 @@ - } - - public InteractionResultHolder use(Level p_41432_, Player p_41433_, InteractionHand p_41434_) { -- if (this.isEdible()) { -- ItemStack itemstack = p_41433_.getItemInHand(p_41434_); -- if (p_41433_.canEat(this.getFoodProperties().canAlwaysEat())) { -+ ItemStack itemstack = p_41433_.getItemInHand(p_41434_); -+ if (itemstack.isEdible()) { -+ if (p_41433_.canEat(itemstack.getFoodProperties(p_41433_).canAlwaysEat())) { - p_41433_.startUsingItem(p_41434_); - return InteractionResultHolder.consume(itemstack); - } else { -@@ -151,10 +_,12 @@ - return this.isEdible() ? p_41411_.eat(p_41410_, p_41409_) : p_41409_; - } - -+ @Deprecated // Use ItemStack sensitive version. - public final int getMaxStackSize() { - return this.maxStackSize; - } - -+ @Deprecated // Use ItemStack sensitive version. - public final int getMaxDamage() { - return this.maxDamage; - } -@@ -168,11 +_,12 @@ - } - - public int getBarWidth(ItemStack p_150900_) { -- return Math.round(13.0F - (float)p_150900_.getDamageValue() * 13.0F / (float)this.maxDamage); -+ return Math.round(13.0F - (float)p_150900_.getDamageValue() * 13.0F / (float)this.getMaxDamage(p_150900_)); - } - - public int getBarColor(ItemStack p_150901_) { -- float f = Math.max(0.0F, ((float)this.maxDamage - (float)p_150901_.getDamageValue()) / (float)this.maxDamage); -+ float stackMaxDamage = this.getMaxDamage(p_150901_); -+ float f = Math.max(0.0F, (stackMaxDamage - (float)p_150901_.getDamageValue()) / stackMaxDamage); - return Mth.hsvToRgb(f / 3.0F, 1.0F, 1.0F); - } - -@@ -229,10 +_,12 @@ - } - - @Nullable -+ @Deprecated // Use ItemStack sensitive version. - public final Item getCraftingRemainingItem() { - return this.craftingRemainingItem; - } - -+ @Deprecated // Use ItemStack sensitive version. - public boolean hasCraftingRemainingItem() { - return this.craftingRemainingItem != null; - } -@@ -257,7 +_,7 @@ - - public int getUseDuration(ItemStack p_41454_) { - if (p_41454_.getItem().isEdible()) { -- return this.getFoodProperties().isFastFood() ? 16 : 32; -+ return p_41454_.getFoodProperties(null).isFastFood() ? 16 : 32; - } else { - return 0; - } -@@ -299,7 +_,7 @@ - } - - public boolean isEnchantable(ItemStack p_41456_) { -- return this.getMaxStackSize() == 1 && this.canBeDepleted(); -+ return this.getMaxStackSize(p_41456_) == 1 && this.isDamageable(p_41456_); - } - - protected static BlockHitResult getPlayerPOVHitResult(Level p_41436_, Player p_41437_, ClipContext.Fluid p_41438_) { -@@ -312,11 +_,13 @@ - float f5 = Mth.sin(-f * ((float)Math.PI / 180F)); - float f6 = f3 * f4; - float f7 = f2 * f4; -- double d0 = 5.0D; -- Vec3 vec31 = vec3.add((double)f6 * 5.0D, (double)f5 * 5.0D, (double)f7 * 5.0D); -+ double d0 = p_41437_.getBlockReach(); -+ Vec3 vec31 = vec3.add((double)f6 * d0, (double)f5 * d0, (double)f7 * d0); - return p_41436_.clip(new ClipContext(vec3, vec31, ClipContext.Block.OUTLINE, p_41438_, p_41437_)); - } - -+ /** Forge: Use ItemStack sensitive version. */ -+ @Deprecated - public int getEnchantmentValue() { - return 0; - } -@@ -325,12 +_,20 @@ - return false; - } - -+ @Deprecated // Use ItemStack sensitive version. - public Multimap getDefaultAttributeModifiers(EquipmentSlot p_41388_) { - return ImmutableMultimap.of(); - } - -+ protected final boolean canRepair; + private static final Logger LOGGER = LogUtils.getLogger(); +- public static final Map BY_BLOCK = Maps.newHashMap(); + -+ @Override -+ public boolean isRepairable(ItemStack stack) { -+ return canRepair && isDamageable(stack); -+ } -+ - public boolean useOnRelease(ItemStack p_41464_) { -- return false; -+ return p_41464_.getItem() == Items.CROSSBOW; - } ++ public static final net.minecraft.network.codec.StreamCodec> STREAM_CODEC = ++ net.minecraft.network.codec.ByteBufCodecs.holderRegistry(net.minecraft.core.registries.Registries.ITEM); ++ public static final Map BY_BLOCK = net.minecraftforge.registries.GameData.ItemCallbacks.getBlockItemMap(); + public static final UUID BASE_ATTACK_DAMAGE_UUID = UUID.fromString("CB3F55D3-645C-4F38-A497-9C13A33DB5CF"); + public static final UUID BASE_ATTACK_SPEED_UUID = UUID.fromString("FA233E1C-4180-4865-B01B-BCCE9785ACA3"); + public static final int DEFAULT_MAX_STACK_SIZE = 64; +@@ -93,6 +_,7 @@ + LOGGER.error("Item classes should end with Item and {} doesn't.", s); + } + } ++ initClient(); + } - public ItemStack getDefaultInstance() { -@@ -341,6 +_,8 @@ - return this.foodProperties != null; - } + @Deprecated +@@ -111,6 +_,7 @@ + public void onUseTick(Level p_41428_, LivingEntity p_41429_, ItemStack p_41430_, int p_41431_) { + } -+ // Use IForgeItem#getFoodProperties(ItemStack, LivingEntity) in favour of this. -+ @Deprecated - @Nullable - public FoodProperties getFoodProperties() { - return this.foodProperties; -@@ -370,6 +_,32 @@ - return this.requiredFeatures; - } ++ /** @deprecated Forge: {@link net.minecraftforge.common.extensions.IForgeItem#onDestroyed(ItemEntity, DamageSource) Use damage source sensitive version} */ + public void onDestroyed(ItemEntity p_150887_) { + } -+ // FORGE START -+ private Object renderProperties; -+ -+ /* -+ DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE -+ Call RenderProperties.get instead -+ */ -+ public Object getRenderPropertiesInternal() { -+ return renderProperties; -+ } -+ -+ private void initClient() { -+ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen -+ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { -+ initializeClient(properties -> { -+ if (properties == this) -+ throw new IllegalStateException("Don't extend IItemRenderProperties in your item, use an anonymous class instead."); -+ this.renderProperties = properties; -+ }); -+ } -+ } -+ -+ public void initializeClient(java.util.function.Consumer consumer) { -+ } -+ // END FORGE -+ - public static class Properties { - int maxStackSize = 64; - int maxDamage; -@@ -380,6 +_,7 @@ - FoodProperties foodProperties; - boolean isFireResistant; - FeatureFlagSet requiredFeatures = FeatureFlags.VANILLA_SET; -+ private boolean canRepair = true; +@@ -232,10 +_,12 @@ + } - public Item.Properties food(FoodProperties p_41490_) { - this.foodProperties = p_41490_; -@@ -417,6 +_,11 @@ + @Nullable ++ @Deprecated // Use ItemStack sensitive version. + public final Item getCraftingRemainingItem() { + return this.craftingRemainingItem; + } - public Item.Properties fireResistant() { - this.isFireResistant = true; -+ return this; -+ } ++ @Deprecated // Use ItemStack sensitive version. + public boolean hasCraftingRemainingItem() { + return this.craftingRemainingItem != null; + } +@@ -291,6 +_,7 @@ + return p_41436_.clip(new ClipContext(vec3, vec31, ClipContext.Block.OUTLINE, p_41438_, p_41437_)); + } + ++ @Deprecated // Use ItemStack sensitive version. + public int getEnchantmentValue() { + return 0; + } +@@ -332,6 +_,30 @@ + public FeatureFlagSet requiredFeatures() { + return this.requiredFeatures; + } + -+ public Item.Properties setNoRepair() { -+ canRepair = false; - return this; - } ++ private Object renderProperties; ++ ++ /* ++ DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE ++ Call RenderProperties.get instead ++ */ ++ public Object getRenderPropertiesInternal() { ++ return renderProperties; ++ } ++ ++ private void initClient() { ++ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen ++ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { ++ initializeClient(properties -> { ++ if (properties == this) { ++ throw new IllegalStateException("Don't extend IItemRenderProperties in your item, use an anonymous class instead."); ++ } ++ this.renderProperties = properties; ++ }); ++ } ++ } ++ ++ public void initializeClient(java.util.function.Consumer consumer) { } + public static class Properties { + private static final Interner COMPONENT_INTERNER = Interners.newStrongInterner(); diff --git a/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch b/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch index 91562ae2ce..04af35d83d 100644 --- a/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch @@ -6,55 +6,55 @@ -public enum ItemDisplayContext implements StringRepresentable { +public enum ItemDisplayContext implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { - NONE(0, "none"), - THIRD_PERSON_LEFT_HAND(1, "thirdperson_lefthand"), - THIRD_PERSON_RIGHT_HAND(2, "thirdperson_righthand"), + NONE(0, "none"), + THIRD_PERSON_LEFT_HAND(1, "thirdperson_lefthand"), + THIRD_PERSON_RIGHT_HAND(2, "thirdperson_righthand"), @@ -16,14 +_,16 @@ - GROUND(7, "ground"), - FIXED(8, "fixed"); + GROUND(7, "ground"), + FIXED(8, "fixed"); -- public static final Codec CODEC = StringRepresentable.fromEnum(ItemDisplayContext::values); -- public static final IntFunction BY_ID = ByIdMap.continuous(ItemDisplayContext::getId, values(), ByIdMap.OutOfBoundsStrategy.ZERO); -+ public static final Codec CODEC = net.minecraft.util.ExtraCodecs.lazyInitializedCodec(() -> net.minecraftforge.registries.ForgeRegistries.DISPLAY_CONTEXTS.get().getCodec()); -+ public static final IntFunction BY_ID = id -> java.util.Objects.requireNonNullElse(((net.minecraftforge.registries.IForgeRegistryInternal) net.minecraftforge.registries.ForgeRegistries.DISPLAY_CONTEXTS.get()).getValue(id < 0 ? Byte.MAX_VALUE + -id : id), NONE); - private byte id; - private final String name; +- public static final Codec CODEC = StringRepresentable.fromEnum(ItemDisplayContext::values); +- public static final IntFunction BY_ID = ByIdMap.continuous(ItemDisplayContext::getId, values(), ByIdMap.OutOfBoundsStrategy.ZERO); ++ public static final Codec CODEC = com.mojang.serialization.Codec.lazyInitialized(() -> StringRepresentable.fromEnum(ItemDisplayContext::values)); ++ public static final IntFunction BY_ID = id -> java.util.Objects.requireNonNullElse(((net.minecraftforge.registries.IForgeRegistryInternal) net.minecraftforge.registries.ForgeRegistries.DISPLAY_CONTEXTS.get()).getValue(id < 0 ? Byte.MAX_VALUE + -id : id), NONE); + private byte id; + private final String name; - private ItemDisplayContext(int p_270624_, String p_270851_) { - this.name = p_270851_; - this.id = (byte)p_270624_; -+ this.isModded = false; -+ this.fallback = null; - } + private ItemDisplayContext(final int p_270624_, final String p_270851_) { + this.name = p_270851_; + this.id = (byte)p_270624_; ++ this.isModded = false; ++ this.fallback = null; + } - public String getSerializedName() { -@@ -37,4 +_,29 @@ - public boolean firstPerson() { - return this == FIRST_PERSON_LEFT_HAND || this == FIRST_PERSON_RIGHT_HAND; - } + @Override +@@ -38,4 +_,29 @@ + public boolean firstPerson() { + return this == FIRST_PERSON_LEFT_HAND || this == FIRST_PERSON_RIGHT_HAND; + } + -+ // Forge start -+ private final boolean isModded; -+ @javax.annotation.Nullable -+ private final ItemDisplayContext fallback; ++ private final boolean isModded; ++ @javax.annotation.Nullable ++ private final ItemDisplayContext fallback; + -+ private ItemDisplayContext(net.minecraft.resources.ResourceLocation serializeName, ItemDisplayContext fallback) { -+ this.id = 0; // If the context is never registered then it should be treated as the NONE one -+ this.name = java.util.Objects.requireNonNull(serializeName, "Modded ItemDisplayContexts must have a non-null serializeName").toString(); -+ this.isModded = true; -+ this.fallback = fallback; -+ } ++ private ItemDisplayContext(net.minecraft.resources.ResourceLocation serializeName, ItemDisplayContext fallback) { ++ this.id = 0; // If the context is never registered then it should be treated as the NONE one ++ this.name = java.util.Objects.requireNonNull(serializeName, "Modded ItemDisplayContexts must have a non-null serializeName").toString(); ++ this.isModded = true; ++ this.fallback = fallback; ++ } + -+ public boolean isModded() { -+ return isModded; -+ } ++ public boolean isModded() { ++ return isModded; ++ } + -+ public @javax.annotation.Nullable ItemDisplayContext fallback() { -+ return fallback; -+ } ++ public @javax.annotation.Nullable ItemDisplayContext fallback() { ++ return fallback; ++ } + -+ public static ItemDisplayContext create(String keyName, net.minecraft.resources.ResourceLocation serializedName, @javax.annotation.Nullable ItemDisplayContext fallback) { -+ throw new IllegalStateException("Enum not extended!"); -+ } -+ public static final net.minecraftforge.registries.IForgeRegistry.AddCallback ADD_CALLBACK = (owner, stage, id, key, obj, oldObj) -> obj.id = id > Byte.MAX_VALUE ? (byte) -(id - Byte.MAX_VALUE) : (byte) id; // if the ID is > 127 start doing negative IDs ++ public static ItemDisplayContext create(String keyName, net.minecraft.resources.ResourceLocation serializedName, @javax.annotation.Nullable ItemDisplayContext fallback) { ++ throw new IllegalStateException("Enum not extended!"); ++ } ++ ++ public static final net.minecraftforge.registries.IForgeRegistry.AddCallback ADD_CALLBACK = (owner, stage, id, key, obj, oldObj) -> obj.id = id > Byte.MAX_VALUE ? (byte) -(id - Byte.MAX_VALUE) : (byte) id; // if the ID is > 127 start doing negative IDs } diff --git a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch index 85dc28c265..12015bd19e 100644 --- a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch @@ -1,282 +1,63 @@ --- a/net/minecraft/world/item/ItemStack.java +++ b/net/minecraft/world/item/ItemStack.java -@@ -80,12 +_,16 @@ - import net.minecraft.world.level.block.state.pattern.BlockInWorld; +@@ -92,7 +_,7 @@ + import org.apache.commons.lang3.mutable.MutableBoolean; import org.slf4j.Logger; --public final class ItemStack { -+public final class ItemStack extends net.minecraftforge.common.capabilities.CapabilityProvider implements net.minecraftforge.common.extensions.IForgeItemStack { - public static final Codec CODEC = RecordCodecBuilder.create((p_309238_) -> { - return p_309238_.group(BuiltInRegistries.ITEM.holderByNameCodec().fieldOf("id").forGetter(ItemStack::getItemHolder), Codec.INT.fieldOf("Count").forGetter(ItemStack::getCount), CompoundTag.CODEC.optionalFieldOf("tag").forGetter((p_281115_) -> { - return Optional.ofNullable(p_281115_.getTag()); - })).apply(p_309238_, ItemStack::new); - }); -+ @org.jetbrains.annotations.Nullable -+ private final net.minecraft.core.Holder.Reference delegate; -+ private CompoundTag capNBT; +-public final class ItemStack implements DataComponentHolder { ++public final class ItemStack implements DataComponentHolder, net.minecraftforge.common.extensions.IForgeItemStack { + public static final Codec> ITEM_NON_AIR_CODEC = BuiltInRegistries.ITEM + .holderByNameCodec() + .validate( +@@ -335,13 +_,22 @@ + } + + public InteractionResult useOn(UseOnContext p_41662_) { ++ if (!p_41662_.getLevel().isClientSide) return net.minecraftforge.common.ForgeHooks.onPlaceItemIntoWorld(p_41662_); ++ return onItemUse(p_41662_, (c) -> getItem().useOn(p_41662_)); ++ } + - private static final Codec ITEM_NON_AIR_CODEC = ExtraCodecs.validate(BuiltInRegistries.ITEM.byNameCodec(), (p_309237_) -> { - return p_309237_ == Items.AIR ? DataResult.error(() -> { - return "Item must not be minecraft:air"; -@@ -160,28 +_,40 @@ - this(p_220155_.value(), p_220156_); - } - -- public ItemStack(ItemLike p_41601_, int p_41602_) { -- this.item = p_41601_.asItem(); -- this.count = p_41602_; -- if (this.item.canBeDepleted()) { -+ public ItemStack(ItemLike p_41601_, int p_41602_) { this(p_41601_, p_41602_, (CompoundTag) null); } -+ public ItemStack(ItemLike p_41604_, int p_41605_, @Nullable CompoundTag p_41606_) { -+ super(ItemStack.class, true); -+ this.capNBT = p_41606_; -+ this.item = p_41604_.asItem(); -+ this.delegate = net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_41604_.asItem()); -+ this.count = p_41605_; -+ this.forgeInit(); -+ if (this.item.isDamageable(this)) { - this.setDamageValue(this.getDamageValue()); - } - - } - - private ItemStack(@Nullable Void p_282703_) { -+ super(ItemStack.class, true); - this.item = null; -+ this.delegate = null; - } - - private ItemStack(CompoundTag p_41608_) { -+ super(ItemStack.class, true); -+ this.capNBT = p_41608_.contains("ForgeCaps") ? p_41608_.getCompound("ForgeCaps") : null; -+ Item rawItem = - this.item = BuiltInRegistries.ITEM.get(new ResourceLocation(p_41608_.getString("id"))); -+ this.delegate = net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(rawItem); - this.count = p_41608_.getByte("Count"); - if (p_41608_.contains("tag", 10)) { - this.tag = p_41608_.getCompound("tag").copy(); - this.getItem().verifyTagAfterLoad(this.tag); - } -+ this.forgeInit(); - -- if (this.getItem().canBeDepleted()) { -+ if (this.getItem().isDamageable(this)) { - this.setDamageValue(this.getDamageValue()); - } - -@@ -197,7 +_,7 @@ - } - - public boolean isEmpty() { -- return this == EMPTY || this.item == Items.AIR || this.count <= 0; -+ return this == EMPTY || this.count <= 0 || this.delegate.get() == Items.AIR; - } - - public boolean isItemEnabled(FeatureFlagSet p_250869_) { -@@ -222,7 +_,7 @@ - } - - public Item getItem() { -- return this.isEmpty() ? Items.AIR : this.item; -+ return this.isEmpty() ? Items.AIR : this.delegate.get(); - } - - public Holder getItemHolder() { -@@ -254,6 +_,15 @@ - } - - public InteractionResult useOn(UseOnContext p_41662_) { -+ if (!p_41662_.getLevel().isClientSide) return net.minecraftforge.common.ForgeHooks.onPlaceItemIntoWorld(p_41662_); -+ return onItemUse(p_41662_, (c) -> getItem().useOn(p_41662_)); -+ } ++ public InteractionResult onItemUseFirst(UseOnContext p_41662_) { ++ return onItemUse(p_41662_, (c) -> getItem().onItemUseFirst(this, p_41662_)); ++ } + -+ public InteractionResult onItemUseFirst(UseOnContext p_41662_) { -+ return onItemUse(p_41662_, (c) -> getItem().onItemUseFirst(this, p_41662_)); -+ } -+ -+ private InteractionResult onItemUse(UseOnContext p_41662_, java.util.function.Function callback) { - Player player = p_41662_.getPlayer(); - BlockPos blockpos = p_41662_.getClickedPos(); - BlockInWorld blockinworld = new BlockInWorld(p_41662_.getLevel(), blockpos, false); -@@ -261,7 +_,7 @@ - return InteractionResult.PASS; - } else { - Item item = this.getItem(); -- InteractionResult interactionresult = item.useOn(p_41662_); -+ InteractionResult interactionresult = callback.apply(p_41662_); - if (player != null && interactionresult.shouldAwardStats()) { - player.awardStat(Stats.ITEM_USED.get(item)); - } -@@ -290,11 +_,15 @@ - p_41740_.put("tag", this.tag.copy()); - } - -+ CompoundTag cnbt = this.serializeCaps(); -+ if (cnbt != null && !cnbt.isEmpty()) { -+ p_41740_.put("ForgeCaps", cnbt); -+ } - return p_41740_; - } - - public int getMaxStackSize() { -- return this.getItem().getMaxStackSize(); -+ return this.getItem().getMaxStackSize(this); - } - - public boolean isStackable() { -@@ -302,7 +_,7 @@ - } - - public boolean isDamageableItem() { -- if (!this.isEmpty() && this.getItem().getMaxDamage() > 0) { -+ if (!this.isEmpty() && this.getItem().isDamageable(this)) { - CompoundTag compoundtag = this.getTag(); - return compoundtag == null || !compoundtag.getBoolean("Unbreakable"); - } else { -@@ -311,19 +_,19 @@ - } - - public boolean isDamaged() { -- return this.isDamageableItem() && this.getDamageValue() > 0; -+ return this.isDamageableItem() && getItem().isDamaged(this); - } - - public int getDamageValue() { -- return this.tag == null ? 0 : this.tag.getInt("Damage"); -+ return this.getItem().getDamage(this); - } - - public void setDamageValue(int p_41722_) { -- this.getOrCreateTag().putInt("Damage", Math.max(0, p_41722_)); -+ this.getItem().setDamage(this, p_41722_); - } - - public int getMaxDamage() { -- return this.getItem().getMaxDamage(); -+ return this.getItem().getMaxDamage(this); - } - - public boolean hurt(int p_220158_, RandomSource p_220159_, @Nullable ServerPlayer p_220160_) { -@@ -359,6 +_,7 @@ - public void hurtAndBreak(int p_41623_, T p_41624_, Consumer p_41625_) { - if (!p_41624_.level().isClientSide && (!(p_41624_ instanceof Player) || !((Player)p_41624_).getAbilities().instabuild)) { - if (this.isDamageableItem()) { -+ p_41623_ = this.getItem().damageItem(this, p_41623_, p_41624_, p_41625_); - if (this.hurt(p_41623_, p_41624_.getRandom(), p_41624_ instanceof ServerPlayer ? (ServerPlayer)p_41624_ : null)) { - p_41625_.accept(p_41624_); - Item item = this.getItem(); -@@ -411,7 +_,7 @@ - } - - public boolean isCorrectToolForDrops(BlockState p_41736_) { -- return this.getItem().isCorrectToolForDrops(p_41736_); -+ return this.getItem().isCorrectToolForDrops(this, p_41736_); - } - - public InteractionResult interactLivingEntity(Player p_41648_, LivingEntity p_41649_, InteractionHand p_41650_) { -@@ -422,7 +_,7 @@ - if (this.isEmpty()) { - return EMPTY; - } else { -- ItemStack itemstack = new ItemStack(this.getItem(), this.count); -+ ItemStack itemstack = new ItemStack(this.getItem(), this.count, this.serializeCaps()); - itemstack.setPopTime(this.getPopTime()); - if (this.tag != null) { - itemstack.tag = this.tag.copy(); -@@ -458,7 +_,7 @@ - if (!p_150943_.is(p_150944_.getItem())) { - return false; - } else { -- return p_150943_.isEmpty() && p_150944_.isEmpty() ? true : Objects.equals(p_150943_.tag, p_150944_.tag); -+ return p_150943_.isEmpty() && p_150944_.isEmpty() ? true : Objects.equals(p_150943_.tag, p_150944_.tag) && p_150943_.areCapsCompatible(p_150944_); - } - } - -@@ -554,7 +_,7 @@ - - public void setTag(@Nullable CompoundTag p_41752_) { - this.tag = p_41752_; -- if (this.getItem().canBeDepleted()) { -+ if (this.getItem().isDamageable(this)) { - this.setDamageValue(this.getDamageValue()); - } - -@@ -615,7 +_,7 @@ - - public List getTooltipLines(@Nullable Player p_41652_, TooltipFlag p_41653_) { - List list = Lists.newArrayList(); -- MutableComponent mutablecomponent = Component.empty().append(this.getHoverName()).withStyle(this.getRarity().color); -+ MutableComponent mutablecomponent = Component.empty().append(this.getHoverName()).withStyle(this.getRarity().getStyleModifier()); - if (this.hasCustomHoverName()) { - mutablecomponent.withStyle(ChatFormatting.ITALIC); - } -@@ -762,6 +_,7 @@ - list.add(DISABLED_ITEM_TOOLTIP); - } - -+ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, p_41652_, list, p_41653_); - return list; - } - -@@ -770,7 +_,7 @@ - } - - private int getHideFlags() { -- return this.hasTag() && this.tag.contains("HideFlags", 99) ? this.tag.getInt("HideFlags") : 0; -+ return this.hasTag() && this.tag.contains("HideFlags", 99) ? this.tag.getInt("HideFlags") : this.getItem().getDefaultTooltipHideFlags(this); - } - - public void hideTooltipPart(ItemStack.TooltipPart p_41655_) { -@@ -890,9 +_,10 @@ ++ private InteractionResult onItemUse(UseOnContext p_41662_, java.util.function.Function callback) { + Player player = p_41662_.getPlayer(); + BlockPos blockpos = p_41662_.getClickedPos(); + if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(p_41662_.getLevel(), blockpos, false))) { + return InteractionResult.PASS; + } else { + Item item = this.getItem(); +- InteractionResult interactionresult = item.useOn(p_41662_); ++ InteractionResult interactionresult = callback.apply(p_41662_); + if (player != null && interactionresult.indicateItemUse()) { + player.awardStat(Stats.ITEM_USED.get(item)); + } +@@ -447,6 +_,10 @@ } - } - } else { -- multimap = this.getItem().getDefaultAttributeModifiers(p_41639_); -+ multimap = this.getItem().getAttributeModifiers(p_41639_, this); - } -+ multimap = net.minecraftforge.common.ForgeHooks.getAttributeModifiers(this, p_41639_, multimap); - return multimap; - } + this.hurtAndBreak(p_41623_, p_41624_.getRandom(), p_41624_ instanceof ServerPlayer serverplayer ? serverplayer : null, () -> { ++ if (p_41624_ instanceof Player player) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, this, p_335324_); ++ player.stopUsingItem(); // Forge: fix MC-168573 ++ } + p_41624_.broadcastBreakEvent(p_335324_); + Item item = this.getItem(); + this.shrink(1); +@@ -757,6 +_,8 @@ + list.add(DISABLED_ITEM_TOOLTIP); + } -@@ -920,7 +_,7 @@ - - MutableComponent mutablecomponent1 = ComponentUtils.wrapInSquareBrackets(mutablecomponent); - if (!this.isEmpty()) { -- mutablecomponent1.withStyle(this.getRarity().color).withStyle((p_220170_) -> { -+ mutablecomponent1.withStyle(this.getRarity().getStyleModifier()).withStyle((p_220170_) -> { - return p_220170_.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new HoverEvent.ItemStackInfo(this))); - }); - } -@@ -972,12 +_,31 @@ - this.getItem().onUseTick(p_41732_, p_41733_, this, p_41734_); - } - -+ /** @deprecated Forge: Use {@linkplain net.minecraftforge.common.extensions.IForgeItemStack#onDestroyed(ItemEntity, net.minecraft.world.damagesource.DamageSource) damage source sensitive version} */ -+ @Deprecated - public void onDestroyed(ItemEntity p_150925_) { - this.getItem().onDestroyed(p_150925_); - } - - public boolean isEdible() { - return this.getItem().isEdible(); -+ } ++ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, p_41652_, list, p_41653_); + -+ // FORGE START -+ public void deserializeNBT(CompoundTag nbt) { -+ final ItemStack itemStack = ItemStack.of(nbt); -+ this.setTag(itemStack.getTag()); -+ if (itemStack.capNBT != null) deserializeCaps(itemStack.capNBT); -+ } -+ -+ /** -+ * Set up forge's ItemStack additions. -+ */ -+ private void forgeInit() { -+ if (this.delegate != null) { -+ this.gatherCapabilities(() -> item.initCapabilities(this, this.capNBT)); -+ if (this.capNBT != null) deserializeCaps(this.capNBT); -+ } - } + return list; + } + } +@@ -970,6 +_,7 @@ + this.getItem().onUseTick(p_41732_, p_41733_, this, p_41734_); + } - public SoundEvent getDrinkingSound() { ++ /** @deprecated Forge: Use {@linkplain net.minecraftforge.common.extensions.IForgeItemStack#onDestroyed(ItemEntity, net.minecraft.world.damagesource.DamageSource) damage source sensitive version} */ + public void onDestroyed(ItemEntity p_150925_) { + this.getItem().onDestroyed(p_150925_); + } diff --git a/patches/minecraft/net/minecraft/world/item/Items.java.patch b/patches/minecraft/net/minecraft/world/item/Items.java.patch index 7781551d97..4d0c9719e9 100644 --- a/patches/minecraft/net/minecraft/world/item/Items.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Items.java.patch @@ -1,30 +1,38 @@ --- a/net/minecraft/world/item/Items.java +++ b/net/minecraft/world/item/Items.java -@@ -1337,11 +_,23 @@ - } +@@ -1807,7 +_,23 @@ + } - public static Item registerBlock(Block p_252092_, Block... p_248886_) { -- BlockItem blockitem = new BlockItem(p_252092_, new Item.Properties()); -+ BlockItem blockitem = new BlockItem(p_252092_, new Item.Properties()) { -+ @Override -+ public void registerBlocks(java.util.Map map, Item self) { -+ super.registerBlocks(map, self); -+ for (Block b : p_248886_) { -+ map.put(b, self); + public static Item registerBlock(Block p_252092_, Block... p_248886_) { +- BlockItem blockitem = new BlockItem(p_252092_, new Item.Properties()); ++ BlockItem blockitem = new BlockItem(p_252092_, new Item.Properties()) { ++ @Override ++ public void registerBlocks(java.util.Map map, Item self) { ++ super.registerBlocks(map, self); ++ for (Block b : p_248886_) { ++ map.put(b, self); ++ } + } -+ } - -- for(Block block : p_248886_) { -- Item.BY_BLOCK.put(block, blockitem); -- } -+ @Override -+ public void removeFromBlockToItemMap(java.util.Map map, Item self) { -+ super.removeFromBlockToItemMap(map, self); -+ for (Block b : p_248886_) { -+ map.remove(b); ++ ++ @Override ++ public void removeFromBlockToItemMap(java.util.Map map, Item self) { ++ super.removeFromBlockToItemMap(map, self); ++ for (Block b : p_248886_) { ++ map.remove(b); ++ } + } -+ } -+ }; ++ }; - return registerBlock(blockitem); - } + for (Block block : p_248886_) { + Item.BY_BLOCK.put(block, blockitem); +@@ -1833,10 +_,6 @@ + } + + public static Item registerItem(ResourceKey p_281502_, Item p_283159_) { +- if (p_283159_ instanceof BlockItem) { +- ((BlockItem)p_283159_).registerBlocks(Item.BY_BLOCK, p_283159_); +- } +- + return Registry.register(BuiltInRegistries.ITEM, p_281502_, p_283159_); + } + } diff --git a/patches/minecraft/net/minecraft/world/item/MapItem.java.patch b/patches/minecraft/net/minecraft/world/item/MapItem.java.patch deleted file mode 100644 index 434a6f0ad3..0000000000 --- a/patches/minecraft/net/minecraft/world/item/MapItem.java.patch +++ /dev/null @@ -1,23 +0,0 @@ ---- a/net/minecraft/world/item/MapItem.java -+++ b/net/minecraft/world/item/MapItem.java -@@ -58,8 +_,18 @@ - - @Nullable - public static MapItemSavedData getSavedData(ItemStack p_42854_, Level p_42855_) { -- Integer integer = getMapId(p_42854_); -- return getSavedData(integer, p_42855_); -+ // Forge: Add instance method so that mods can override -+ Item map = p_42854_.getItem(); -+ if(map instanceof MapItem) { -+ return ((MapItem)map).getCustomMapData(p_42854_, p_42855_); -+ } -+ return null; -+ } -+ -+ @Nullable -+ protected MapItemSavedData getCustomMapData(ItemStack p_42910_, Level p_42911_) { -+ Integer integer = getMapId(p_42910_); -+ return getSavedData(integer, p_42911_); - } - - @Nullable diff --git a/patches/minecraft/net/minecraft/world/item/MilkBucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/MilkBucketItem.java.patch deleted file mode 100644 index 52bbe36bf1..0000000000 --- a/patches/minecraft/net/minecraft/world/item/MilkBucketItem.java.patch +++ /dev/null @@ -1,32 +0,0 @@ ---- a/net/minecraft/world/item/MilkBucketItem.java -+++ b/net/minecraft/world/item/MilkBucketItem.java -@@ -17,6 +_,7 @@ - } - - public ItemStack finishUsingItem(ItemStack p_42923_, Level p_42924_, LivingEntity p_42925_) { -+ if (!p_42924_.isClientSide) p_42925_.curePotionEffects(p_42923_); // FORGE - move up so stack.shrink does not turn stack into air - if (p_42925_ instanceof ServerPlayer serverplayer) { - CriteriaTriggers.CONSUME_ITEM.trigger(serverplayer, p_42923_); - serverplayer.awardStat(Stats.ITEM_USED.get(this)); -@@ -26,10 +_,6 @@ - p_42923_.shrink(1); - } - -- if (!p_42924_.isClientSide) { -- p_42925_.removeAllEffects(); -- } -- - return p_42923_.isEmpty() ? new ItemStack(Items.BUCKET) : p_42923_; - } - -@@ -43,5 +_,10 @@ - - public InteractionResultHolder use(Level p_42927_, Player p_42928_, InteractionHand p_42929_) { - return ItemUtils.startUsingInstantly(p_42927_, p_42928_, p_42929_); -+ } -+ -+ @Override -+ public net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @org.jetbrains.annotations.Nullable net.minecraft.nbt.CompoundTag nbt) { -+ return new net.minecraftforge.fluids.capability.wrappers.FluidBucketWrapper(stack); - } - } diff --git a/patches/minecraft/net/minecraft/world/item/MinecartItem.java.patch b/patches/minecraft/net/minecraft/world/item/MinecartItem.java.patch index 8dce7417a1..1bf03fac0d 100644 --- a/patches/minecraft/net/minecraft/world/item/MinecartItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/MinecartItem.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/item/MinecartItem.java +++ b/net/minecraft/world/item/MinecartItem.java -@@ -32,7 +_,7 @@ - double d2 = vec3.z() + (double)direction.getStepZ() * 1.125D; - BlockPos blockpos = p_42949_.pos().relative(direction); - BlockState blockstate = serverlevel.getBlockState(blockpos); -- RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock ? blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()) : RailShape.NORTH_SOUTH; -+ RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock ? ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, serverlevel, blockpos, null) : RailShape.NORTH_SOUTH; - double d3; - if (blockstate.is(BlockTags.RAILS)) { - if (railshape.isAscending()) { -@@ -82,7 +_,7 @@ - ItemStack itemstack = p_42943_.getItemInHand(); - if (level instanceof ServerLevel) { - ServerLevel serverlevel = (ServerLevel)level; -- RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock ? blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()) : RailShape.NORTH_SOUTH; -+ RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock ? ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, level, blockpos, null) : RailShape.NORTH_SOUTH; - double d0 = 0.0D; - if (railshape.isAscending()) { - d0 = 0.5D; +@@ -33,7 +_,7 @@ + BlockPos blockpos = p_42949_.pos().relative(direction); + BlockState blockstate = serverlevel.getBlockState(blockpos); + RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock +- ? blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()) ++ ? ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, serverlevel, blockpos, null) + : RailShape.NORTH_SOUTH; + double d3; + if (blockstate.is(BlockTags.RAILS)) { +@@ -49,7 +_,7 @@ + + BlockState blockstate1 = serverlevel.getBlockState(blockpos.below()); + RailShape railshape1 = blockstate1.getBlock() instanceof BaseRailBlock +- ? blockstate1.getValue(((BaseRailBlock)blockstate1.getBlock()).getShapeProperty()) ++ ? ((BaseRailBlock)blockstate1.getBlock()).getRailDirection(blockstate, serverlevel, blockpos, null) + : RailShape.NORTH_SOUTH; + if (direction != Direction.DOWN && railshape1.isAscending()) { + d3 = -0.4; diff --git a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch index 3fb8bbb174..3ce487b630 100644 --- a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch @@ -1,64 +1,63 @@ --- a/net/minecraft/world/item/MobBucketItem.java +++ b/net/minecraft/world/item/MobBucketItem.java -@@ -22,13 +_,18 @@ - import net.minecraft.world.level.material.Fluid; +@@ -25,13 +_,18 @@ public class MobBucketItem extends BucketItem { -- private final EntityType type; -- private final SoundEvent emptySound; -+ private final java.util.function.Supplier> entityTypeSupplier; -+ private final java.util.function.Supplier emptySoundSupplier; + private static final MapCodec VARIANT_FIELD_CODEC = TropicalFish.Variant.CODEC.fieldOf("BucketVariantTag"); +- private final EntityType type; +- private final SoundEvent emptySound; ++ private final java.util.function.Supplier> entityTypeSupplier; ++ private final java.util.function.Supplier emptySoundSupplier; -+ @Deprecated - public MobBucketItem(EntityType p_151137_, Fluid p_151138_, SoundEvent p_151139_, Item.Properties p_151140_) { -- super(p_151138_, p_151140_); -- this.type = p_151137_; -- this.emptySound = p_151139_; -+ this(() -> p_151137_, () -> p_151138_, () -> p_151139_, p_151140_); -+ } ++ @Deprecated + public MobBucketItem(EntityType p_151137_, Fluid p_151138_, SoundEvent p_151139_, Item.Properties p_151140_) { +- super(p_151138_, p_151140_); +- this.type = p_151137_; +- this.emptySound = p_151139_; ++ this(() -> p_151137_, () -> p_151138_, () -> p_151139_, p_151140_); ++ } + -+ public MobBucketItem(java.util.function.Supplier> entitySupplier, java.util.function.Supplier fluidSupplier, java.util.function.Supplier soundSupplier, Item.Properties properties) { -+ super(fluidSupplier, properties); -+ this.emptySoundSupplier = soundSupplier; -+ this.entityTypeSupplier = entitySupplier; - } ++ public MobBucketItem(java.util.function.Supplier> entitySupplier, java.util.function.Supplier fluidSupplier, java.util.function.Supplier soundSupplier, Item.Properties properties) { ++ super(fluidSupplier, properties); ++ this.emptySoundSupplier = soundSupplier; ++ this.entityTypeSupplier = entitySupplier; + } - public void checkExtraContent(@Nullable Player p_151146_, Level p_151147_, ItemStack p_151148_, BlockPos p_151149_) { -@@ -40,11 +_,11 @@ - } + @Override +@@ -44,11 +_,11 @@ - protected void playEmptySound(@Nullable Player p_151151_, LevelAccessor p_151152_, BlockPos p_151153_) { -- p_151152_.playSound(p_151151_, p_151153_, this.emptySound, SoundSource.NEUTRAL, 1.0F, 1.0F); -+ p_151152_.playSound(p_151151_, p_151153_, getEmptySound(), SoundSource.NEUTRAL, 1.0F, 1.0F); - } + @Override + protected void playEmptySound(@Nullable Player p_151151_, LevelAccessor p_151152_, BlockPos p_151153_) { +- p_151152_.playSound(p_151151_, p_151153_, this.emptySound, SoundSource.NEUTRAL, 1.0F, 1.0F); ++ p_151152_.playSound(p_151151_, p_151153_, this.getEmptySound(), SoundSource.NEUTRAL, 1.0F, 1.0F); + } - private void spawn(ServerLevel p_151142_, ItemStack p_151143_, BlockPos p_151144_) { -- Entity entity = this.type.spawn(p_151142_, p_151143_, (Player)null, p_151144_, MobSpawnType.BUCKET, true, false); -+ Entity entity = getFishType().spawn(p_151142_, p_151143_, (Player)null, p_151144_, MobSpawnType.BUCKET, true, false); - if (entity instanceof Bucketable bucketable) { - bucketable.loadFromBucketTag(p_151143_.getOrCreateTag()); - bucketable.setFromBucket(true); -@@ -53,7 +_,7 @@ - } + private void spawn(ServerLevel p_151142_, ItemStack p_151143_, BlockPos p_151144_) { +- if (this.type.spawn(p_151142_, p_151143_, null, p_151144_, MobSpawnType.BUCKET, true, false) instanceof Bucketable bucketable) { ++ if (this.getFishType().spawn(p_151142_, p_151143_, null, p_151144_, MobSpawnType.BUCKET, true, false) instanceof Bucketable bucketable) { + CustomData customdata = p_151143_.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); + bucketable.loadFromBucketTag(customdata.copyTag()); + bucketable.setFromBucket(true); +@@ -57,7 +_,7 @@ - public void appendHoverText(ItemStack p_151155_, @Nullable Level p_151156_, List p_151157_, TooltipFlag p_151158_) { -- if (this.type == EntityType.TROPICAL_FISH) { -+ if (getFishType() == EntityType.TROPICAL_FISH) { - CompoundTag compoundtag = p_151155_.getTag(); - if (compoundtag != null && compoundtag.contains("BucketVariantTag", 3)) { - int i = compoundtag.getInt("BucketVariantTag"); -@@ -79,5 +_,14 @@ - } - } - -+ } + @Override + public void appendHoverText(ItemStack p_151155_, Item.TooltipContext p_329546_, List p_151157_, TooltipFlag p_151158_) { +- if (this.type == EntityType.TROPICAL_FISH) { ++ if (this.getFishType() == EntityType.TROPICAL_FISH) { + CustomData customdata = p_151155_.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); + if (customdata.isEmpty()) { + return; +@@ -85,5 +_,13 @@ + p_151157_.add(mutablecomponent); + } + } ++ } + -+ // Forge Start -+ protected EntityType getFishType() { -+ return entityTypeSupplier.get(); -+ } ++ protected EntityType getFishType() { ++ return entityTypeSupplier.get(); ++ } + -+ protected SoundEvent getEmptySound() { -+ return emptySoundSupplier.get(); - } ++ protected SoundEvent getEmptySound() { ++ return emptySoundSupplier.get(); + } } diff --git a/patches/minecraft/net/minecraft/world/item/PickaxeItem.java.patch b/patches/minecraft/net/minecraft/world/item/PickaxeItem.java.patch index e472644dbb..ad70eb6979 100644 --- a/patches/minecraft/net/minecraft/world/item/PickaxeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/PickaxeItem.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/item/PickaxeItem.java +++ b/net/minecraft/world/item/PickaxeItem.java @@ -6,4 +_,9 @@ - public PickaxeItem(Tier p_42961_, int p_42962_, float p_42963_, Item.Properties p_42964_) { - super((float)p_42962_, p_42963_, p_42961_, BlockTags.MINEABLE_WITH_PICKAXE, p_42964_); - } + public PickaxeItem(Tier p_42961_, Item.Properties p_42964_) { + super(p_42961_, BlockTags.MINEABLE_WITH_PICKAXE, p_42964_); + } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_PICKAXE_ACTIONS.contains(toolAction); -+ } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_PICKAXE_ACTIONS.contains(toolAction); ++ } } diff --git a/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch new file mode 100644 index 0000000000..d0c3278e64 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch @@ -0,0 +1,32 @@ +--- a/net/minecraft/world/item/ProjectileWeaponItem.java ++++ b/net/minecraft/world/item/ProjectileWeaponItem.java +@@ -85,6 +_,7 @@ + protected Projectile createProjectile(Level p_333069_, LivingEntity p_334736_, ItemStack p_333680_, ItemStack p_329118_, boolean p_336242_) { + ArrowItem arrowitem = p_329118_.getItem() instanceof ArrowItem arrowitem1 ? arrowitem1 : (ArrowItem)Items.ARROW; + AbstractArrow abstractarrow = arrowitem.createArrow(p_333069_, p_329118_, p_334736_); ++ abstractarrow = customArrow(abstractarrow); + if (p_336242_) { + abstractarrow.setCritArrow(true); + } +@@ -123,9 +_,10 @@ + int j = i == 0 ? 1 : 3; + List list = new ArrayList<>(j); + ItemStack itemstack = p_328618_.copy(); ++ boolean infinite = p_328618_.getItem() instanceof ArrowItem arrow && arrow.isInfinite(p_328618_, p_329054_, p_335616_); + + for (int k = 0; k < j; k++) { +- list.add(useAmmo(p_329054_, k == 0 ? p_328618_ : itemstack, p_335616_, k > 0)); ++ list.add(useAmmo(p_329054_, k == 0 ? p_328618_ : itemstack, p_335616_, k > 0 || infinite)); + } + + return list; +@@ -146,5 +_,9 @@ + + return itemstack; + } ++ } ++ ++ public AbstractArrow customArrow(AbstractArrow arrow) { ++ return arrow; + } + } diff --git a/patches/minecraft/net/minecraft/world/item/Rarity.java.patch b/patches/minecraft/net/minecraft/world/item/Rarity.java.patch deleted file mode 100644 index 2af5d9b7a9..0000000000 --- a/patches/minecraft/net/minecraft/world/item/Rarity.java.patch +++ /dev/null @@ -1,40 +0,0 @@ ---- a/net/minecraft/world/item/Rarity.java -+++ b/net/minecraft/world/item/Rarity.java -@@ -2,15 +_,36 @@ - - import net.minecraft.ChatFormatting; - --public enum Rarity { -+public enum Rarity implements net.minecraftforge.common.IExtensibleEnum { - COMMON(ChatFormatting.WHITE), - UNCOMMON(ChatFormatting.YELLOW), - RARE(ChatFormatting.AQUA), - EPIC(ChatFormatting.LIGHT_PURPLE); - -+ /** @deprecated Forge: Use {@link #getStyleModifier()} */ -+ @Deprecated - public final ChatFormatting color; -+ private final java.util.function.UnaryOperator styleModifier; - - private Rarity(ChatFormatting p_43028_) { - this.color = p_43028_; -+ this.styleModifier = style -> style.withColor(p_43028_); -+ } -+ -+ Rarity(java.util.function.UnaryOperator styleModifier) { -+ this.color = ChatFormatting.BLACK; -+ this.styleModifier = styleModifier; -+ } -+ -+ public java.util.function.UnaryOperator getStyleModifier() { -+ return this.styleModifier; -+ } -+ -+ public static Rarity create(String name, ChatFormatting p_43028_) { -+ throw new IllegalStateException("Enum not extended"); -+ } -+ -+ public static Rarity create(String name, java.util.function.UnaryOperator styleModifier) { -+ throw new IllegalStateException("Enum not extended"); - } - } diff --git a/patches/minecraft/net/minecraft/world/item/RecordItem.java.patch b/patches/minecraft/net/minecraft/world/item/RecordItem.java.patch index 5885b79c86..a3065efbd0 100644 --- a/patches/minecraft/net/minecraft/world/item/RecordItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/RecordItem.java.patch @@ -1,54 +1,53 @@ --- a/net/minecraft/world/item/RecordItem.java +++ b/net/minecraft/world/item/RecordItem.java -@@ -22,17 +_,42 @@ +@@ -21,17 +_,41 @@ import net.minecraft.world.level.gameevent.GameEvent; public class RecordItem extends Item { -+ @Deprecated // Forge: refer to WorldRender#playRecord. Modders: there's no need to reflectively modify this map! - private static final Map BY_NAME = Maps.newHashMap(); - private final int analogOutput; -+ @Deprecated // Forge: refer to soundSupplier - private final SoundEvent sound; - private final int lengthInTicks; -+ private final java.util.function.Supplier soundSupplier; ++ @Deprecated // Forge: refer to WorldRender#playRecord. Modders: there's no need to reflectively modify this map! + private static final Map BY_NAME = Maps.newHashMap(); + private final int analogOutput; ++ @Deprecated // Forge: refer to soundSupplier + private final SoundEvent sound; + private final int lengthInTicks; ++ private final java.util.function.Supplier soundSupplier; -+ @Deprecated // Forge: Use the constructor that takes a supplier instead - public RecordItem(int p_239614_, SoundEvent p_239615_, Item.Properties p_239616_, int p_239617_) { - super(p_239616_); - this.analogOutput = p_239614_; - this.sound = p_239615_; - this.lengthInTicks = p_239617_ * 20; - BY_NAME.put(this.sound, this); -+ this.soundSupplier = net.minecraftforge.registries.ForgeRegistries.SOUND_EVENTS.getDelegateOrThrow(this.sound); -+ } ++ /** @deprecated Forge: Use the constructor that takes a supplier instead */ + public RecordItem(int p_239614_, SoundEvent p_239615_, Item.Properties p_239616_, int p_239617_) { + super(p_239616_); + this.analogOutput = p_239614_; + this.sound = p_239615_; + this.lengthInTicks = p_239617_ * 20; + BY_NAME.put(this.sound, this); ++ this.soundSupplier = net.minecraftforge.registries.ForgeRegistries.SOUND_EVENTS.getDelegateOrThrow(this.sound); ++ } + -+ /** -+ * For mod use, allows to create a music disc without having to create a new -+ * SoundEvent before their registry event is fired. -+ * -+ * @param comparatorValue The value this music disc should output on the comparator. Must be between 0 and 15. -+ * @param soundSupplier A supplier that provides the sound that should be played. Use a -+ * {@link net.minecraftforge.registries.RegistryObject} or a -+ * {@link net.minecraft.core.Holder} for this parameter. -+ * @param builder A set of {@link Item.Properties} that describe this item. -+ * @param lengthInTicks The length of the music disc track in ticks. -+ */ -+ public RecordItem(int comparatorValue, java.util.function.Supplier soundSupplier, Item.Properties builder, int lengthInTicks) -+ { -+ super(builder); -+ this.analogOutput = comparatorValue; -+ this.sound = null; -+ this.soundSupplier = soundSupplier; -+ this.lengthInTicks = lengthInTicks; - } ++ /** ++ * For mod use, allows to create a music disc without having to create a new ++ * SoundEvent before their registry event is fired. ++ * ++ * @param comparatorValue The value this music disc should output on the comparator. Must be between 0 and 15. ++ * @param soundSupplier A supplier that provides the sound that should be played. Use a ++ * {@link net.minecraftforge.registries.RegistryObject} or a ++ * {@link net.minecraft.core.Holder} for this parameter. ++ * @param builder A set of {@link Item.Properties} that describe this item. ++ * @param lengthInTicks The length of the music disc track in ticks. ++ */ ++ public RecordItem(int comparatorValue, java.util.function.Supplier soundSupplier, Item.Properties builder, int lengthInTicks) { ++ super(builder); ++ this.analogOutput = comparatorValue; ++ this.sound = null; ++ this.soundSupplier = soundSupplier; ++ this.lengthInTicks = lengthInTicks; + } - public InteractionResult useOn(UseOnContext p_43048_) { -@@ -80,7 +_,7 @@ - } + @Override +@@ -79,7 +_,7 @@ + } - public SoundEvent getSound() { -- return this.sound; -+ return this.soundSupplier.get(); - } + public SoundEvent getSound() { +- return this.sound; ++ return this.soundSupplier.get(); + } - public int getLengthInTicks() { + public int getLengthInTicks() { diff --git a/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch index 86768eb675..7c6bee2ef2 100644 --- a/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch @@ -1,34 +1,34 @@ --- a/net/minecraft/world/item/ShearsItem.java +++ b/net/minecraft/world/item/ShearsItem.java -@@ -49,6 +_,31 @@ - } - } +@@ -79,4 +_,31 @@ -+ @Override -+ public net.minecraft.world.InteractionResult interactLivingEntity(ItemStack stack, net.minecraft.world.entity.player.Player playerIn, LivingEntity entity, net.minecraft.world.InteractionHand hand) { -+ if (entity instanceof net.minecraftforge.common.IForgeShearable target) { -+ if (entity.level().isClientSide) return net.minecraft.world.InteractionResult.SUCCESS; -+ BlockPos pos = BlockPos.containing(entity.position()); -+ if (target.isShearable(stack, entity.level(), pos)) { -+ java.util.List drops = target.onSheared(playerIn, stack, entity.level(), pos, -+ net.minecraft.world.item.enchantment.EnchantmentHelper.getItemEnchantmentLevel(net.minecraft.world.item.enchantment.Enchantments.BLOCK_FORTUNE, stack)); -+ java.util.Random rand = new java.util.Random(); -+ drops.forEach(d -> { -+ net.minecraft.world.entity.item.ItemEntity ent = entity.spawnAtLocation(d, 1.0F); -+ ent.setDeltaMovement(ent.getDeltaMovement().add((double)((rand.nextFloat() - rand.nextFloat()) * 0.1F), (double)(rand.nextFloat() * 0.05F), (double)((rand.nextFloat() - rand.nextFloat()) * 0.1F))); -+ }); -+ stack.hurtAndBreak(1, playerIn, e -> e.broadcastBreakEvent(hand)); -+ } -+ return net.minecraft.world.InteractionResult.SUCCESS; -+ } -+ return net.minecraft.world.InteractionResult.PASS; -+ } + return super.useOn(p_186371_); + } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_SHEARS_ACTIONS.contains(toolAction); -+ } ++ @Override ++ public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity entity, net.minecraft.world.InteractionHand hand) { ++ if (entity instanceof net.minecraftforge.common.IForgeShearable target) { ++ if (entity.level().isClientSide) { ++ return InteractionResult.SUCCESS; ++ } + - public InteractionResult useOn(UseOnContext p_186371_) { - Level level = p_186371_.getLevel(); - BlockPos blockpos = p_186371_.getClickedPos(); ++ BlockPos pos = BlockPos.containing(entity.position()); ++ if (target.isShearable(stack, entity.level(), pos)) { ++ var drops = target.onSheared(playerIn, stack, entity.level(), pos, stack.getEnchantments().getLevel(net.minecraft.world.item.enchantment.Enchantments.FORTUNE)); ++ var rand = new java.util.Random(); ++ drops.forEach(d -> { ++ var ent = entity.spawnAtLocation(d, 1.0F); ++ ent.setDeltaMovement(ent.getDeltaMovement().add((double)((rand.nextFloat() - rand.nextFloat()) * 0.1F), (double)(rand.nextFloat() * 0.05F), (double)((rand.nextFloat() - rand.nextFloat()) * 0.1F))); ++ }); ++ stack.hurtAndBreak(1, playerIn, LivingEntity.getSlotForHand(hand)); ++ } ++ return InteractionResult.SUCCESS; ++ } ++ return InteractionResult.PASS; ++ } ++ ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_SHEARS_ACTIONS.contains(toolAction); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/item/ShieldItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShieldItem.java.patch index 8ce0504f73..6994bf4701 100644 --- a/patches/minecraft/net/minecraft/world/item/ShieldItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShieldItem.java.patch @@ -1,16 +1,12 @@ --- a/net/minecraft/world/item/ShieldItem.java +++ b/net/minecraft/world/item/ShieldItem.java -@@ -53,6 +_,13 @@ - return compoundtag != null ? DyeColor.byId(compoundtag.getInt("Base")) : DyeColor.WHITE; - } - -+ /* ******************** FORGE START ******************** */ +@@ -57,4 +_,9 @@ + public EquipmentSlot getEquipmentSlot() { + return EquipmentSlot.OFFHAND; + } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_SHIELD_ACTIONS.contains(toolAction); -+ } -+ - public EquipmentSlot getEquipmentSlot() { - return EquipmentSlot.OFFHAND; - } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_SHIELD_ACTIONS.contains(toolAction); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch index e8e5e02716..22058b574f 100644 --- a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/world/item/ShovelItem.java +++ b/net/minecraft/world/item/ShovelItem.java -@@ -33,9 +_,9 @@ - return InteractionResult.PASS; - } else { - Player player = p_43119_.getPlayer(); -- BlockState blockstate1 = FLATTENABLES.get(blockstate.getBlock()); -+ BlockState blockstate1 = blockstate.getToolModifiedState(p_43119_, net.minecraftforge.common.ToolActions.SHOVEL_FLATTEN, false); - BlockState blockstate2 = null; -- if (blockstate1 != null && level.getBlockState(blockpos.above()).isAir()) { -+ if (blockstate1 != null && level.isEmptyBlock(blockpos.above())) { - level.playSound(player, blockpos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); - blockstate2 = blockstate1; - } else if (blockstate.getBlock() instanceof CampfireBlock && blockstate.getValue(CampfireBlock.LIT)) { -@@ -63,5 +_,15 @@ +@@ -44,9 +_,9 @@ return InteractionResult.PASS; - } - } -+ } + } else { + Player player = p_43119_.getPlayer(); +- BlockState blockstate1 = FLATTENABLES.get(blockstate.getBlock()); ++ BlockState blockstate1 = blockstate.getToolModifiedState(p_43119_, net.minecraftforge.common.ToolActions.SHOVEL_FLATTEN, false); + BlockState blockstate2 = null; +- if (blockstate1 != null && level.getBlockState(blockpos.above()).isAir()) { ++ if (blockstate1 != null && level.isEmptyBlock(blockpos.above())) { + level.playSound(player, blockpos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); + blockstate2 = blockstate1; + } else if (blockstate.getBlock() instanceof CampfireBlock && blockstate.getValue(CampfireBlock.LIT)) { +@@ -72,5 +_,15 @@ + return InteractionResult.PASS; + } + } ++ } + -+ @org.jetbrains.annotations.Nullable -+ public static BlockState getShovelPathingState(BlockState originalState) { -+ return FLATTENABLES.get(originalState.getBlock()); -+ } ++ @org.jetbrains.annotations.Nullable ++ public static BlockState getShovelPathingState(BlockState originalState) { ++ return FLATTENABLES.get(originalState.getBlock()); ++ } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_SHOVEL_ACTIONS.contains(toolAction); - } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_SHOVEL_ACTIONS.contains(toolAction); + } } diff --git a/patches/minecraft/net/minecraft/world/item/SpawnEggItem.java.patch b/patches/minecraft/net/minecraft/world/item/SpawnEggItem.java.patch index 2d610c41e8..bd9d58de00 100644 --- a/patches/minecraft/net/minecraft/world/item/SpawnEggItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/SpawnEggItem.java.patch @@ -1,55 +1,49 @@ --- a/net/minecraft/world/item/SpawnEggItem.java +++ b/net/minecraft/world/item/SpawnEggItem.java -@@ -39,11 +_,14 @@ - private final int highlightColor; - private final EntityType defaultType; +@@ -42,11 +_,13 @@ + private final int highlightColor; + private final EntityType defaultType; -+ /** @deprecated Forge: Use {@link net.minecraftforge.common.ForgeSpawnEggItem} instead for suppliers */ -+ @Deprecated - public SpawnEggItem(EntityType p_43207_, int p_43208_, int p_43209_, Item.Properties p_43210_) { - super(p_43210_); - this.defaultType = p_43207_; - this.backgroundColor = p_43208_; - this.highlightColor = p_43209_; -+ if (p_43207_ != null) - BY_ID.put(p_43207_, this); - } ++ /** @deprecated Forge: Use {@link net.minecraftforge.common.ForgeSpawnEggItem} instead for suppliers */ + public SpawnEggItem(EntityType p_43207_, int p_43208_, int p_43209_, Item.Properties p_43210_) { + super(p_43210_); + this.defaultType = p_43207_; + this.backgroundColor = p_43208_; + this.highlightColor = p_43209_; ++ if (p_43207_ != null) + BY_ID.put(p_43207_, this); + } -@@ -123,6 +_,8 @@ - return p_43212_ == 0 ? this.backgroundColor : this.highlightColor; - } +@@ -132,6 +_,7 @@ + return p_43212_ == 0 ? this.backgroundColor : this.highlightColor; + } -+ /** @deprecated Forge: call {@link net.minecraftforge.common.ForgeSpawnEggItem#fromEntityType(EntityType)} instead */ -+ @Deprecated - @Nullable - public static SpawnEggItem byId(@Nullable EntityType p_43214_) { - return BY_ID.get(p_43214_); -@@ -136,15 +_,15 @@ - if (p_43229_ != null && p_43229_.contains("EntityTag", 10)) { - CompoundTag compoundtag = p_43229_.getCompound("EntityTag"); - if (compoundtag.contains("id", 8)) { -- return EntityType.byString(compoundtag.getString("id")).orElse(this.defaultType); -+ return EntityType.byString(compoundtag.getString("id")).orElse(this.getDefaultType()); - } - } ++ /** @deprecated Forge: call {@link net.minecraftforge.common.ForgeSpawnEggItem#fromEntityType(EntityType)} instead */ + @Nullable + public static SpawnEggItem byId(@Nullable EntityType p_43214_) { + return BY_ID.get(p_43214_); +@@ -143,12 +_,12 @@ -- return this.defaultType; -+ return this.getDefaultType(); - } + public EntityType getType(ItemStack p_334231_) { + CustomData customdata = p_334231_.getOrDefault(DataComponents.ENTITY_DATA, CustomData.EMPTY); +- return !customdata.isEmpty() ? customdata.read(ENTITY_TYPE_FIELD_CODEC).result().orElse(this.defaultType) : this.defaultType; ++ return !customdata.isEmpty() ? customdata.read(ENTITY_TYPE_FIELD_CODEC).result().orElse(this.getDefaultType()) : this.getDefaultType(); + } - public FeatureFlagSet requiredFeatures() { -- return this.defaultType.requiredFeatures(); -+ return this.getDefaultType().requiredFeatures(); - } + @Override + public FeatureFlagSet requiredFeatures() { +- return this.defaultType.requiredFeatures(); ++ return this.getDefaultType().requiredFeatures(); + } - public Optional spawnOffspringFromSpawnEgg(Player p_43216_, Mob p_43217_, EntityType p_43218_, ServerLevel p_43219_, Vec3 p_43220_, ItemStack p_43221_) { -@@ -179,5 +_,9 @@ + public Optional spawnOffspringFromSpawnEgg(Player p_43216_, Mob p_43217_, EntityType p_43218_, ServerLevel p_43219_, Vec3 p_43220_, ItemStack p_43221_) { +@@ -177,5 +_,9 @@ + } } - } - } -+ } + } ++ } + -+ protected EntityType getDefaultType() { -+ return defaultType; - } ++ protected EntityType getDefaultType() { ++ return defaultType; + } } diff --git a/patches/minecraft/net/minecraft/world/item/StandingAndWallBlockItem.java.patch b/patches/minecraft/net/minecraft/world/item/StandingAndWallBlockItem.java.patch index 636f03b927..781b756bc0 100644 --- a/patches/minecraft/net/minecraft/world/item/StandingAndWallBlockItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/StandingAndWallBlockItem.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/item/StandingAndWallBlockItem.java +++ b/net/minecraft/world/item/StandingAndWallBlockItem.java -@@ -48,4 +_,9 @@ - super.registerBlocks(p_43252_, p_43253_); - p_43252_.put(this.wallBlock, p_43253_); - } +@@ -50,4 +_,9 @@ + super.registerBlocks(p_43252_, p_43253_); + p_43252_.put(this.wallBlock, p_43253_); + } + -+ public void removeFromBlockToItemMap(Map blockToItemMap, Item itemIn) { -+ super.removeFromBlockToItemMap(blockToItemMap, itemIn); -+ blockToItemMap.remove(this.wallBlock); -+ } ++ public void removeFromBlockToItemMap(Map blockToItemMap, Item itemIn) { ++ super.removeFromBlockToItemMap(blockToItemMap, itemIn); ++ blockToItemMap.remove(this.wallBlock); ++ } } diff --git a/patches/minecraft/net/minecraft/world/item/SwordItem.java.patch b/patches/minecraft/net/minecraft/world/item/SwordItem.java.patch index 53e6ce7b8f..aa17c66570 100644 --- a/patches/minecraft/net/minecraft/world/item/SwordItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/SwordItem.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/item/SwordItem.java +++ b/net/minecraft/world/item/SwordItem.java -@@ -67,4 +_,9 @@ - public Multimap getDefaultAttributeModifiers(EquipmentSlot p_43274_) { - return p_43274_ == EquipmentSlot.MAINHAND ? this.defaultModifiers : super.getDefaultAttributeModifiers(p_43274_); - } +@@ -50,4 +_,9 @@ + p_43278_.hurtAndBreak(1, p_43280_, EquipmentSlot.MAINHAND); + return true; + } + -+ @Override -+ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { -+ return net.minecraftforge.common.ToolActions.DEFAULT_SWORD_ACTIONS.contains(toolAction); -+ } ++ @Override ++ public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) { ++ return net.minecraftforge.common.ToolActions.DEFAULT_SWORD_ACTIONS.contains(toolAction); ++ } } diff --git a/patches/minecraft/net/minecraft/world/item/Tier.java.patch b/patches/minecraft/net/minecraft/world/item/Tier.java.patch deleted file mode 100644 index 906894d511..0000000000 --- a/patches/minecraft/net/minecraft/world/item/Tier.java.patch +++ /dev/null @@ -1,15 +0,0 @@ ---- a/net/minecraft/world/item/Tier.java -+++ b/net/minecraft/world/item/Tier.java -@@ -9,9 +_,12 @@ - - float getAttackDamageBonus(); - -+ @Deprecated // FORGE: Use TierSortingRegistry to define which tiers are better than others - int getLevel(); - - int getEnchantmentValue(); - - Ingredient getRepairIngredient(); -+ -+ @org.jetbrains.annotations.Nullable default net.minecraft.tags.TagKey getTag() { return null; } - } diff --git a/patches/minecraft/net/minecraft/world/item/Tiers.java.patch b/patches/minecraft/net/minecraft/world/item/Tiers.java.patch deleted file mode 100644 index f4d2313f78..0000000000 --- a/patches/minecraft/net/minecraft/world/item/Tiers.java.patch +++ /dev/null @@ -1,9 +0,0 @@ ---- a/net/minecraft/world/item/Tiers.java -+++ b/net/minecraft/world/item/Tiers.java -@@ -64,4 +_,6 @@ - public Ingredient getRepairIngredient() { - return this.repairIngredient.get(); - } -+ -+ @org.jetbrains.annotations.Nullable public net.minecraft.tags.TagKey getTag() { return net.minecraftforge.common.ForgeHooks.getTagFromVanillaTier(this); } - } diff --git a/patches/minecraft/net/minecraft/world/item/UseAnim.java.patch b/patches/minecraft/net/minecraft/world/item/UseAnim.java.patch index 9c2e316780..3f78819ea3 100644 --- a/patches/minecraft/net/minecraft/world/item/UseAnim.java.patch +++ b/patches/minecraft/net/minecraft/world/item/UseAnim.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/item/UseAnim.java +++ b/net/minecraft/world/item/UseAnim.java @@ -10,5 +_,10 @@ - CROSSBOW, - SPYGLASS, - TOOT_HORN, -- BRUSH; -+ BRUSH, -+ /** -+ * Items with custom arm animation should return this in `Item#getUseAnimation` -+ * to prevent vanilla from also trying to animate same item -+ */ -+ CUSTOM + CROSSBOW, + SPYGLASS, + TOOT_HORN, +- BRUSH; ++ BRUSH, ++ /** ++ * Items with custom arm animation should return this in `Item#getUseAnimation` ++ * to prevent vanilla from also trying to animate same item ++ */ ++ CUSTOM } diff --git a/patches/minecraft/net/minecraft/world/item/alchemy/Potion.java.patch b/patches/minecraft/net/minecraft/world/item/alchemy/Potion.java.patch deleted file mode 100644 index 7d90cda0d0..0000000000 --- a/patches/minecraft/net/minecraft/world/item/alchemy/Potion.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/item/alchemy/Potion.java -+++ b/net/minecraft/world/item/alchemy/Potion.java -@@ -8,7 +_,7 @@ - import net.minecraft.resources.ResourceLocation; - import net.minecraft.world.effect.MobEffectInstance; - --public class Potion { -+public class Potion implements net.minecraftforge.common.extensions.IForgePotion { - @Nullable - private final String name; - private final ImmutableList effects; diff --git a/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch b/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch index 6b8209fa11..f85a3cd3e5 100644 --- a/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch +++ b/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch @@ -1,82 +1,132 @@ --- a/net/minecraft/world/item/alchemy/PotionBrewing.java +++ b/net/minecraft/world/item/alchemy/PotionBrewing.java -@@ -51,7 +_,7 @@ +@@ -19,15 +_,35 @@ + private final List containers; + private final List> potionMixes; + private final List> containerMixes; ++ private final List recipes; - public static boolean isBrewablePotion(Potion p_43512_) { - for(PotionBrewing.Mix mix : POTION_MIXES) { -- if (mix.to == p_43512_) { -+ if (mix.to.get() == p_43512_) { - return true; - } - } -@@ -71,7 +_,7 @@ - Item item = p_43520_.getItem(); + PotionBrewing(List p_331253_, List> p_333814_, List> p_332419_) { ++ this(p_331253_, p_333814_, p_332419_, null); ++ } ++ ++ PotionBrewing(List p_331253_, List> p_333814_, List> p_332419_, Builder builder) { + this.containers = p_331253_; + this.potionMixes = p_333814_; + this.containerMixes = p_332419_; ++ var tmp = new ArrayList(); ++ tmp.add(new net.minecraftforge.common.brewing.VanillaBrewingRecipe(this, this::mixVanilla)); ++ if (builder != null) { ++ tmp.addAll(builder.recipes); ++ } ++ this.recipes = java.util.Collections.unmodifiableList(tmp); + } - for(PotionBrewing.Mix mix : CONTAINER_MIXES) { -- if (mix.from == item && mix.ingredient.test(p_43521_)) { -+ if (mix.from.get() == item && mix.ingredient.test(p_43521_)) { - return true; - } - } -@@ -83,7 +_,7 @@ - Potion potion = PotionUtils.getPotion(p_43525_); + public boolean isIngredient(ItemStack p_43507_) { +- return this.isContainerIngredient(p_43507_) || this.isPotionIngredient(p_43507_); ++ if (p_43507_.isEmpty()) { ++ return false; ++ } ++ ++ for (var recipe : recipes) { ++ if (recipe.isIngredient(p_43507_)) { ++ return true; ++ } ++ } ++ return false; + } - for(PotionBrewing.Mix mix : POTION_MIXES) { -- if (mix.from == potion && mix.ingredient.test(p_43526_)) { -+ if (mix.from.get() == potion && mix.ingredient.test(p_43526_)) { - return true; - } - } -@@ -97,14 +_,14 @@ - Item item = p_43531_.getItem(); + private boolean isContainer(ItemStack p_328293_) { +@@ -71,9 +_,10 @@ + } - for(PotionBrewing.Mix mix : CONTAINER_MIXES) { -- if (mix.from == item && mix.ingredient.test(p_43530_)) { -- return PotionUtils.setPotion(new ItemStack(mix.to), potion); -+ if (mix.from.get() == item && mix.ingredient.test(p_43530_)) { -+ return PotionUtils.setPotion(new ItemStack(mix.to.get()), potion); + public boolean hasMix(ItemStack p_43509_, ItemStack p_43510_) { +- return !this.isContainer(p_43509_) ? false : this.hasContainerMix(p_43509_, p_43510_) || this.hasPotionMix(p_43509_, p_43510_); ++ return !mix(p_43509_, p_43510_).isEmpty(); + } + ++ /** @deprecated Forge: use hasMix(ItemStack, ItemStack)*/ + public boolean hasContainerMix(ItemStack p_43520_, ItemStack p_43521_) { + for (PotionBrewing.Mix mix : this.containerMixes) { + if (p_43520_.is(mix.from) && mix.ingredient.test(p_43521_)) { +@@ -84,6 +_,7 @@ + return false; + } + ++ /** @deprecated Forge: use hasMix(ItemStack, ItemStack)*/ + public boolean hasPotionMix(ItemStack p_43525_, ItemStack p_43526_) { + Optional> optional = p_43525_.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (optional.isEmpty()) { +@@ -100,6 +_,19 @@ + } + + public ItemStack mix(ItemStack p_43530_, ItemStack p_43531_) { ++ if (p_43530_.isEmpty() || p_43530_.getCount() != 1) return ItemStack.EMPTY; ++ if (p_43531_.isEmpty()) return ItemStack.EMPTY; ++ ++ for (var recipe : recipes) { ++ ItemStack output = recipe.getOutput(p_43530_, p_43531_); ++ if (!output.isEmpty()) { ++ return output; ++ } ++ } ++ return ItemStack.EMPTY; ++ } ++ ++ private ItemStack mixVanilla(ItemStack p_43530_, ItemStack p_43531_) { + if (p_43531_.isEmpty()) { + return p_43531_; + } else { +@@ -124,9 +_,29 @@ + } + } + ++ /** ++ * Returns true if the passed ItemStack is a valid input for the start of a recipe ++ */ ++ public boolean isValidInput(ItemStack stack) { ++ for (var recipe : recipes) { ++ if (recipe.isInput(stack)) { ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ /** ++ * Returns an unmodifiable list containing all the recipes in the registry ++ */ ++ public List getRecipes() { ++ return this.recipes; ++ } ++ + public static PotionBrewing bootstrap(FeatureFlagSet p_329176_) { + PotionBrewing.Builder potionbrewing$builder = new PotionBrewing.Builder(p_329176_); + addVanillaMixes(potionbrewing$builder); ++ net.minecraftforge.event.ForgeEventFactory.onBrewingRecipeRegister(potionbrewing$builder, p_329176_); + return potionbrewing$builder.build(); + } + +@@ -195,6 +_,7 @@ + private final List> potionMixes = new ArrayList<>(); + private final List> containerMixes = new ArrayList<>(); + private final FeatureFlagSet enabledFeatures; ++ private final List recipes = new ArrayList<>(); + + public Builder(FeatureFlagSet p_332559_) { + this.enabledFeatures = p_332559_; +@@ -234,8 +_,13 @@ } - } + } - for(PotionBrewing.Mix mix1 : POTION_MIXES) { -- if (mix1.from == potion && mix1.ingredient.test(p_43530_)) { -- return PotionUtils.setPotion(new ItemStack(item), mix1.to); -+ if (mix1.from.get() == potion && mix1.ingredient.test(p_43530_)) { -+ return PotionUtils.setPotion(new ItemStack(item), mix1.to.get()); - } - } - } -@@ -181,7 +_,7 @@ - } else if (!(p_43505_ instanceof PotionItem)) { - throw new IllegalArgumentException("Expected a potion, got: " + BuiltInRegistries.ITEM.getKey(p_43505_)); - } else { -- CONTAINER_MIXES.add(new PotionBrewing.Mix<>(p_43503_, Ingredient.of(p_43504_), p_43505_)); -+ CONTAINER_MIXES.add(new PotionBrewing.Mix<>(net.minecraftforge.registries.ForgeRegistries.ITEMS, p_43503_, Ingredient.of(p_43504_), p_43505_)); - } - } ++ public Builder add(net.minecraftforge.common.brewing.IBrewingRecipe recipe) { ++ this.recipes.add(recipe); ++ return this; ++ } ++ + public PotionBrewing build() { +- return new PotionBrewing(List.copyOf(this.containers), List.copyOf(this.potionMixes), List.copyOf(this.containerMixes)); ++ return new PotionBrewing(List.copyOf(this.containers), List.copyOf(this.potionMixes), List.copyOf(this.containerMixes), this); + } + } -@@ -194,18 +_,18 @@ - } - - private static void addMix(Potion p_43514_, Item p_43515_, Potion p_43516_) { -- POTION_MIXES.add(new PotionBrewing.Mix<>(p_43514_, Ingredient.of(p_43515_), p_43516_)); -+ POTION_MIXES.add(new PotionBrewing.Mix<>(net.minecraftforge.registries.ForgeRegistries.POTIONS, p_43514_, Ingredient.of(p_43515_), p_43516_)); - } - - public static class Mix { -- final T from; -+ public final net.minecraft.core.Holder.Reference from; - public final Ingredient ingredient; -- final T to; -+ public final net.minecraft.core.Holder.Reference to; - -- public Mix(T p_43536_, Ingredient p_43537_, T p_43538_) { -- this.from = p_43536_; -+ public Mix(net.minecraftforge.registries.IForgeRegistry registry, T p_43536_, Ingredient p_43537_, T p_43538_) { -+ this.from = registry.getDelegateOrThrow(p_43536_); - this.ingredient = p_43537_; -- this.to = p_43538_; -+ this.to = registry.getDelegateOrThrow(p_43538_); - } - } - } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch index db2aedfcd0..ba676d13ae 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java +++ b/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java -@@ -79,8 +_,8 @@ - for(int i = 0; i < nonnulllist.size(); ++i) { - ItemStack itemstack = p_43791_.getItem(i); - if (!itemstack.isEmpty()) { -- if (itemstack.getItem().hasCraftingRemainingItem()) { -- nonnulllist.set(i, new ItemStack(itemstack.getItem().getCraftingRemainingItem())); -+ if (itemstack.hasCraftingRemainingItem()) { -+ nonnulllist.set(i, itemstack.getCraftingRemainingItem()); - } else if (itemstack.hasTag() && BannerBlockEntity.getPatternCount(itemstack) > 0) { - nonnulllist.set(i, itemstack.copyWithCount(1)); - } +@@ -80,8 +_,8 @@ + for (int i = 0; i < nonnulllist.size(); i++) { + ItemStack itemstack = p_43791_.getItem(i); + if (!itemstack.isEmpty()) { +- if (itemstack.getItem().hasCraftingRemainingItem()) { +- nonnulllist.set(i, new ItemStack(itemstack.getItem().getCraftingRemainingItem())); ++ if (itemstack.hasCraftingRemainingItem()) { ++ nonnulllist.set(i, itemstack.getCraftingRemainingItem()); + } else if (!itemstack.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers().isEmpty()) { + nonnulllist.set(i, itemstack.copyWithCount(1)); + } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch index f1ac53581f..8644f5f583 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/item/crafting/BookCloningRecipe.java +++ b/net/minecraft/world/item/crafting/BookCloningRecipe.java -@@ -79,8 +_,8 @@ +@@ -84,8 +_,8 @@ - for(int i = 0; i < nonnulllist.size(); ++i) { - ItemStack itemstack = p_43820_.getItem(i); -- if (itemstack.getItem().hasCraftingRemainingItem()) { -- nonnulllist.set(i, new ItemStack(itemstack.getItem().getCraftingRemainingItem())); -+ if (itemstack.hasCraftingRemainingItem()) { -+ nonnulllist.set(i, itemstack.getCraftingRemainingItem()); - } else if (itemstack.getItem() instanceof WrittenBookItem) { - nonnulllist.set(i, itemstack.copyWithCount(1)); - break; + for (int i = 0; i < nonnulllist.size(); i++) { + ItemStack itemstack = p_43820_.getItem(i); +- if (itemstack.getItem().hasCraftingRemainingItem()) { +- nonnulllist.set(i, new ItemStack(itemstack.getItem().getCraftingRemainingItem())); ++ if (itemstack.hasCraftingRemainingItem()) { ++ nonnulllist.set(i, itemstack.getCraftingRemainingItem()); + } else if (itemstack.getItem() instanceof WrittenBookItem) { + nonnulllist.set(i, itemstack.copyWithCount(1)); + break; diff --git a/patches/minecraft/net/minecraft/world/item/crafting/FireworkStarRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/FireworkStarRecipe.java.patch deleted file mode 100644 index 6f7eb833ba..0000000000 --- a/patches/minecraft/net/minecraft/world/item/crafting/FireworkStarRecipe.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/item/crafting/FireworkStarRecipe.java -+++ b/net/minecraft/world/item/crafting/FireworkStarRecipe.java -@@ -106,7 +_,7 @@ - } - - compoundtag.putIntArray("Colors", list); -- compoundtag.putByte("Type", (byte)fireworkrocketitem$shape.getId()); -+ fireworkrocketitem$shape.save(compoundtag); - return itemstack; - } - diff --git a/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch index 458ccb5155..59b03b0c5d 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch @@ -1,140 +1,122 @@ --- a/net/minecraft/world/item/crafting/Ingredient.java +++ b/net/minecraft/world/item/crafting/Ingredient.java -@@ -27,14 +_,24 @@ +@@ -28,16 +_,25 @@ import net.minecraft.world.level.ItemLike; public class Ingredient implements Predicate { -+ //Because Mojang caches things... we need to invalidate them.. so... here we go.. -+ private static final java.util.concurrent.atomic.AtomicInteger INVALIDATION_COUNTER = new java.util.concurrent.atomic.AtomicInteger(); -+ public static void invalidateAll() { -+ INVALIDATION_COUNTER.incrementAndGet(); -+ } ++ //Because Mojang caches things... we need to invalidate them.. so... here we go.. ++ private static final java.util.concurrent.atomic.AtomicInteger INVALIDATION_COUNTER = new java.util.concurrent.atomic.AtomicInteger(); ++ public static void invalidateAll() { ++ INVALIDATION_COUNTER.incrementAndGet(); ++ } + public static final Ingredient EMPTY = new Ingredient(Stream.empty()); +- public static final StreamCodec CONTENTS_STREAM_CODEC = ItemStack.LIST_STREAM_CODEC +- .map(p_327193_ -> fromValues(p_327193_.stream().map(Ingredient.ItemValue::new)), p_327192_ -> Arrays.asList(p_327192_.getItems())); ++ public static final StreamCodec CONTENTS_STREAM_CODEC = net.minecraftforge.common.ForgeHooks.ingredientStreamCodec(); + private final Ingredient.Value[] values; + @Nullable + private ItemStack[] itemStacks; + @Nullable + private IntList stackingIds; +- public static final Codec CODEC = codec(true); +- public static final Codec CODEC_NONEMPTY = codec(false); ++ /** The vanilla codec that doesn't support custom Ingredient types. */ ++ public static final Codec VANILLA_CODEC = codec(true); ++ public static final com.mojang.serialization.MapCodec VANILLA_MAP_CODEC = com.mojang.serialization.MapCodec.assumeMapUnsafe(VANILLA_CODEC); ++ public static final Codec CODEC = net.minecraftforge.common.ForgeHooks.enhanceIngredientCodec(VANILLA_CODEC); ++ private static final Codec VANILLA_CODEC_NONEMPTY = codec(false); ++ public static final Codec CODEC_NONEMPTY = net.minecraftforge.common.ForgeHooks.enhanceIngredientCodec(VANILLA_CODEC_NONEMPTY); ++ private int invalidationCounter; + + protected Ingredient(Stream p_43907_) { + this.values = p_43907_.toArray(Ingredient.Value[]::new); +@@ -48,7 +_,7 @@ + } + + public ItemStack[] getItems() { +- if (this.itemStacks == null) { ++ if (this.itemStacks == null || checkInvalidation()) { + this.itemStacks = Arrays.stream(this.values).flatMap(p_43916_ -> p_43916_.getItems().stream()).distinct().toArray(ItemStack[]::new); + } + +@@ -72,7 +_,8 @@ + } + + public IntList getStackingIds() { +- if (this.stackingIds == null) { ++ if (this.stackingIds == null || checkInvalidation()) { ++ this.markValid(); + ItemStack[] aitemstack = this.getItems(); + this.stackingIds = new IntArrayList(aitemstack.length); + +@@ -120,6 +_,56 @@ + return fromValues(Stream.of(new Ingredient.TagValue(p_204133_))); + } + ++ public final boolean checkInvalidation() { ++ int currentInvalidationCounter = INVALIDATION_COUNTER.get(); ++ if (this.invalidationCounter != currentInvalidationCounter) { ++ invalidate(); ++ return true; ++ } ++ return false; ++ } + - public static final Ingredient EMPTY = new Ingredient(Stream.empty()); - private final Ingredient.Value[] values; - @Nullable - private ItemStack[] itemStacks; - @Nullable - private IntList stackingIds; -- public static final Codec CODEC = codec(true); -- public static final Codec CODEC_NONEMPTY = codec(false); -+ /** The vanilla codec that doesn't support custom Ingredient types. */ -+ public static final Codec VANILLA_CODEC = codec(true); -+ public static final Codec CODEC = net.minecraftforge.common.ForgeHooks.enhanceIngredientCodec(VANILLA_CODEC); -+ private static final Codec VANILLA_CODEC_NONEMPTY = codec(false); -+ public static final Codec CODEC_NONEMPTY = net.minecraftforge.common.ForgeHooks.enhanceIngredientCodec(VANILLA_CODEC_NONEMPTY); -+ private int invalidationCounter; - - protected Ingredient(Stream p_43907_) { - this.values = p_43907_.toArray((p_43933_) -> { -@@ -47,7 +_,7 @@ - } - - public ItemStack[] getItems() { -- if (this.itemStacks == null) { -+ if (this.itemStacks == null || checkInvalidation()) { - this.itemStacks = Arrays.stream(this.values).flatMap((p_43916_) -> { - return p_43916_.getItems().stream(); - }).distinct().toArray((p_43910_) -> { -@@ -75,7 +_,8 @@ - } - - public IntList getStackingIds() { -- if (this.stackingIds == null) { -+ if (this.stackingIds == null || checkInvalidation()) { -+ this.markValid(); - ItemStack[] aitemstack = this.getItems(); - this.stackingIds = new IntArrayList(aitemstack.length); - -@@ -90,6 +_,7 @@ - } - - public final void toNetwork(FriendlyByteBuf p_43924_) { -+ if (net.minecraftforge.common.ForgeHooks.ingredientToNetwork(p_43924_, this)) - p_43924_.writeCollection(Arrays.asList(this.getItems()), FriendlyByteBuf::writeItem); - } - -@@ -105,6 +_,38 @@ - } - } - -+ public final boolean checkInvalidation() { -+ int currentInvalidationCounter = INVALIDATION_COUNTER.get(); -+ if (this.invalidationCounter != currentInvalidationCounter) { -+ invalidate(); -+ return true; -+ } -+ return false; -+ } ++ protected final void markValid() { ++ this.invalidationCounter = INVALIDATION_COUNTER.get(); ++ } + -+ protected final void markValid() { -+ this.invalidationCounter = INVALIDATION_COUNTER.get(); -+ } ++ protected void invalidate() { ++ this.itemStacks = null; ++ this.stackingIds = null; ++ } + -+ protected void invalidate() { -+ this.itemStacks = null; -+ this.stackingIds = null; -+ } ++ public boolean isSimple() { ++ return true; ++ } + -+ public boolean isSimple() { -+ return true; -+ } ++ private final boolean isVanilla = this.getClass() == Ingredient.class; ++ public final boolean isVanilla() { ++ return isVanilla; ++ } + -+ private final boolean isVanilla = this.getClass() == Ingredient.class; -+ public final boolean isVanilla() { -+ return isVanilla; -+ } ++ public net.minecraftforge.common.crafting.ingredients.IIngredientSerializer serializer() { ++ if (!isVanilla()) throw new IllegalStateException("Modders must implement Ingredient.codec in their custom Ingredients: " + getClass()); ++ return net.minecraftforge.common.crafting.ingredients.IIngredientSerializer.VANILLA; ++ } + -+ public net.minecraftforge.common.crafting.ingredients.IIngredientSerializer serializer() { -+ if (!isVanilla()) throw new IllegalStateException("Modders must implement Ingredient.codec in their custom Ingredients: " + getClass()); -+ return net.minecraftforge.common.crafting.ingredients.IIngredientSerializer.VANILLA; -+ } ++ @Override ++ public String toString() { ++ var buf = new StringBuilder(); ++ buf.append("Ingredient["); ++ for (int x = 0; x < values.length; x++) { ++ if (x != 0) ++ buf.append(", "); ++ if (values[x] instanceof TagValue tag) ++ buf.append('#').append(tag.tag().location()); ++ else if (values[x] instanceof ItemValue item) ++ buf.append(item.item()); ++ else ++ buf.append(values[x]); ++ } ++ buf.append(']'); ++ return buf.toString(); ++ } + - public static Ingredient fromValues(Stream p_43939_) { - Ingredient ingredient = new Ingredient(p_43939_); - return ingredient.isEmpty() ? EMPTY : ingredient; -@@ -133,7 +_,9 @@ - } + private static Codec codec(boolean p_298496_) { + Codec codec = Codec.list(Ingredient.Value.CODEC) + .comapFlatMap( +@@ -182,6 +_,13 @@ - public static Ingredient fromNetwork(FriendlyByteBuf p_43941_) { -- return fromValues(p_43941_.readList(FriendlyByteBuf::readItem).stream().map(Ingredient.ItemValue::new)); -+ var size = p_43941_.readVarInt(); -+ if (size == -1) return net.minecraftforge.common.ForgeHooks.ingredientFromNetwork(p_43941_); -+ return fromValues(Stream.generate(() -> new Ingredient.ItemValue(p_43941_.readItem())).limit(size)); - } - - private static Codec codec(boolean p_298496_) { -@@ -199,6 +_,9 @@ - list.add(new ItemStack(holder)); - } - -+ if (list.size() == 0) { -+ list.add(new ItemStack(net.minecraft.world.level.block.Blocks.BARRIER).setHoverName(net.minecraft.network.chat.Component.literal("Empty Tag: " + this.tag.location()))); -+ } - return list; - } - } -@@ -221,5 +_,23 @@ - }); - - Collection getItems(); -+ } + for (Holder holder : BuiltInRegistries.ITEM.getTagOrEmpty(this.tag)) { + list.add(new ItemStack(holder)); ++ } + -+ @Override -+ public String toString() { -+ var buf = new StringBuilder(); -+ buf.append("Ingredient["); -+ for (int x = 0; x < values.length; x++) { -+ if (x != 0) -+ buf.append(", "); -+ if (values[x] instanceof TagValue tag) -+ buf.append('#').append(tag.tag().location()); -+ else if (values[x] instanceof ItemValue item) -+ buf.append(item.item()); -+ else -+ buf.append(values[x]); -+ } -+ buf.append(']'); -+ return buf.toString(); - } - } ++ if (list.size() == 0) { ++ var marker = new ItemStack(net.minecraft.world.level.block.Blocks.BARRIER); ++ marker.set(net.minecraft.core.component.DataComponents.CUSTOM_NAME, ++ net.minecraft.network.chat.Component.literal("Empty Tag: " + this.tag.location())); ++ list.add(marker); + } + + return list; diff --git a/patches/minecraft/net/minecraft/world/item/crafting/Recipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/Recipe.java.patch index f388fcc47b..a2c0e1f496 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/Recipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/Recipe.java.patch @@ -1,23 +1,22 @@ --- a/net/minecraft/world/item/crafting/Recipe.java +++ b/net/minecraft/world/item/crafting/Recipe.java -@@ -25,9 +_,9 @@ - NonNullList nonnulllist = NonNullList.withSize(p_44004_.getContainerSize(), ItemStack.EMPTY); +@@ -31,9 +_,9 @@ + NonNullList nonnulllist = NonNullList.withSize(p_44004_.getContainerSize(), ItemStack.EMPTY); - for(int i = 0; i < nonnulllist.size(); ++i) { -- Item item = p_44004_.getItem(i).getItem(); -+ ItemStack item = p_44004_.getItem(i); - if (item.hasCraftingRemainingItem()) { -- nonnulllist.set(i, new ItemStack(item.getCraftingRemainingItem())); -+ nonnulllist.set(i, item.getCraftingRemainingItem()); - } - } + for (int i = 0; i < nonnulllist.size(); i++) { +- Item item = p_44004_.getItem(i).getItem(); ++ ItemStack item = p_44004_.getItem(i); + if (item.hasCraftingRemainingItem()) { +- nonnulllist.set(i, new ItemStack(item.getCraftingRemainingItem())); ++ nonnulllist.set(i, item.getCraftingRemainingItem()); + } + } -@@ -61,7 +_,7 @@ - default boolean isIncomplete() { - NonNullList nonnulllist = this.getIngredients(); - return nonnulllist.isEmpty() || nonnulllist.stream().anyMatch((p_151268_) -> { -- return p_151268_.getItems().length == 0; -+ return net.minecraftforge.common.ForgeHooks.hasNoElements(p_151268_); - }); - } +@@ -66,6 +_,6 @@ + + default boolean isIncomplete() { + NonNullList nonnulllist = this.getIngredients(); +- return nonnulllist.isEmpty() || nonnulllist.stream().anyMatch(p_151268_ -> p_151268_.getItems().length == 0); ++ return nonnulllist.isEmpty() || nonnulllist.stream().anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); + } } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch index f1833115e1..054a666e86 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch @@ -1,34 +1,39 @@ --- a/net/minecraft/world/item/crafting/RecipeManager.java +++ b/net/minecraft/world/item/crafting/RecipeManager.java -@@ -37,9 +_,17 @@ - private Map, Map>> recipes = ImmutableMap.of(); - private Map> byName = ImmutableMap.of(); - private boolean hasErrors; -+ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; //Forge: add context +@@ -40,22 +_,35 @@ + private Multimap, RecipeHolder> byType = ImmutableMultimap.of(); + private Map> byName = ImmutableMap.of(); + private boolean hasErrors; ++ private final net.minecraftforge.common.crafting.conditions.ICondition.IContext context; //Forge: add context -+ /** @deprecated Forge: use {@linkplain RecipeManager#RecipeManager(net.minecraftforge.common.crafting.conditions.ICondition.IContext) constructor with context}. */ -+ @Deprecated - public RecipeManager() { -+ this(net.minecraftforge.common.crafting.conditions.ICondition.IContext.EMPTY); -+ } ++ /** @deprecated Forge: use {@linkplain RecipeManager#RecipeManager(net.minecraftforge.common.crafting.conditions.ICondition.IContext) constructor with context}. */ + public RecipeManager(HolderLookup.Provider p_330459_) { ++ this(p_330459_, net.minecraftforge.common.crafting.conditions.ICondition.IContext.EMPTY); ++ } + -+ public RecipeManager(net.minecraftforge.common.crafting.conditions.ICondition.IContext context) { - super(GSON, "recipes"); -+ this.context = context; - } ++ public RecipeManager(HolderLookup.Provider p_330459_, net.minecraftforge.common.crafting.conditions.ICondition.IContext context) { + super(GSON, "recipes"); + this.registries = p_330459_; ++ this.context = context; + } - protected void apply(Map p_44037_, ResourceManager p_44038_, ProfilerFiller p_44039_) { -@@ -49,8 +_,13 @@ + protected void apply(Map p_44037_, ResourceManager p_44038_, ProfilerFiller p_44039_) { + this.hasErrors = false; + Builder, RecipeHolder> builder = ImmutableMultimap.builder(); + com.google.common.collect.ImmutableMap.Builder> builder1 = ImmutableMap.builder(); +- RegistryOps registryops = this.registries.createSerializationContext(JsonOps.INSTANCE); ++ RegistryOps registryops = this.registries.createSerializationContext(JsonOps.INSTANCE) ++ .withContext(net.minecraftforge.common.crafting.conditions.ICondition.IContext.KEY, this.context); - for(Map.Entry entry : p_44037_.entrySet()) { - ResourceLocation resourcelocation = entry.getKey(); -+ if (resourcelocation.getPath().startsWith("_")) continue; //Forge: filter anything beginning with "_" as it's used for metadata. + for (Entry entry : p_44037_.entrySet()) { + ResourceLocation resourcelocation = entry.getKey(); ++ if (resourcelocation.getPath().startsWith("_")) continue; //Forge: filter anything beginning with "_" as it's used for metadata. - try { -+ if (entry.getValue().isJsonObject() && !net.minecraftforge.common.ForgeHooks.readAndTestCondition(this.context, entry.getValue().getAsJsonObject())) { -+ LOGGER.debug("Skipping loading recipe {} as it's conditions were not met", resourcelocation); -+ continue; -+ } - RecipeHolder recipeholder = fromJson(resourcelocation, GsonHelper.convertToJsonObject(entry.getValue(), "top element")); - map.computeIfAbsent(recipeholder.value().getType(), (p_44075_) -> { - return ImmutableMap.builder(); + try { ++ if (entry.getValue().isJsonObject() && !net.minecraftforge.common.ForgeHooks.readAndTestCondition(registryops, entry.getValue().getAsJsonObject())) { ++ LOGGER.debug("Skipping loading recipe {} as it's conditions were not met", resourcelocation); ++ continue; ++ } + Recipe recipe = Recipe.CODEC.parse(registryops, entry.getValue()).getOrThrow(JsonParseException::new); + RecipeHolder recipeholder = new RecipeHolder<>(resourcelocation, recipe); + builder.put(recipe.getType(), recipeholder); diff --git a/patches/minecraft/net/minecraft/world/item/crafting/RecipeSerializer.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/RecipeSerializer.java.patch deleted file mode 100644 index d18e423ad4..0000000000 --- a/patches/minecraft/net/minecraft/world/item/crafting/RecipeSerializer.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/world/item/crafting/RecipeSerializer.java -+++ b/net/minecraft/world/item/crafting/RecipeSerializer.java -@@ -32,6 +_,7 @@ - - Codec codec(); - -+ @org.jetbrains.annotations.Nullable - T fromNetwork(FriendlyByteBuf p_44106_); - - void toNetwork(FriendlyByteBuf p_44101_, T p_44102_); diff --git a/patches/minecraft/net/minecraft/world/item/crafting/RecipeType.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/RecipeType.java.patch index 6838525233..1463899343 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/RecipeType.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/RecipeType.java.patch @@ -1,17 +1,17 @@ --- a/net/minecraft/world/item/crafting/RecipeType.java +++ b/net/minecraft/world/item/crafting/RecipeType.java -@@ -20,4 +_,14 @@ - } - }); - } +@@ -21,4 +_,14 @@ + } + }); + } + -+ public static > RecipeType simple(final ResourceLocation name) { -+ final String toString = name.toString(); -+ return new RecipeType() { -+ @Override -+ public String toString() { -+ return toString; -+ } -+ }; -+ } ++ public static > RecipeType simple(final ResourceLocation name) { ++ final String toString = name.toString(); ++ return new RecipeType() { ++ @Override ++ public String toString() { ++ return toString; ++ } ++ }; ++ } } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/RepairItemRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/RepairItemRecipe.java.patch deleted file mode 100644 index 7191dc12b8..0000000000 --- a/patches/minecraft/net/minecraft/world/item/crafting/RepairItemRecipe.java.patch +++ /dev/null @@ -1,38 +0,0 @@ ---- a/net/minecraft/world/item/crafting/RepairItemRecipe.java -+++ b/net/minecraft/world/item/crafting/RepairItemRecipe.java -@@ -27,7 +_,7 @@ - list.add(itemstack); - if (list.size() > 1) { - ItemStack itemstack1 = list.get(0); -- if (!itemstack.is(itemstack1.getItem()) || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.getItem().canBeDepleted()) { -+ if (itemstack.getItem() != itemstack1.getItem() || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.isRepairable()) { - return false; - } - } -@@ -46,7 +_,7 @@ - list.add(itemstack); - if (list.size() > 1) { - ItemStack itemstack1 = list.get(0); -- if (!itemstack.is(itemstack1.getItem()) || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.getItem().canBeDepleted()) { -+ if (itemstack.getItem() != itemstack1.getItem() || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.isRepairable()) { - return ItemStack.EMPTY; - } - } -@@ -56,12 +_,12 @@ - if (list.size() == 2) { - ItemStack itemstack3 = list.get(0); - ItemStack itemstack4 = list.get(1); -- if (itemstack3.is(itemstack4.getItem()) && itemstack3.getCount() == 1 && itemstack4.getCount() == 1 && itemstack3.getItem().canBeDepleted()) { -+ if (itemstack3.getItem() == itemstack4.getItem() && itemstack3.getCount() == 1 && itemstack4.getCount() == 1 && itemstack3.isRepairable()) { - Item item = itemstack3.getItem(); -- int j = item.getMaxDamage() - itemstack3.getDamageValue(); -- int k = item.getMaxDamage() - itemstack4.getDamageValue(); -- int l = j + k + item.getMaxDamage() * 5 / 100; -- int i1 = item.getMaxDamage() - l; -+ int j = itemstack3.getMaxDamage() - itemstack3.getDamageValue(); -+ int k = itemstack3.getMaxDamage() - itemstack4.getDamageValue(); -+ int l = j + k + itemstack3.getMaxDamage() * 5 / 100; -+ int i1 = itemstack3.getMaxDamage() - l; - if (i1 < 0) { - i1 = 0; - } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch index 5e84ed7fb6..032c041a84 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch @@ -1,54 +1,44 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipe.java +++ b/net/minecraft/world/item/crafting/ShapedRecipe.java -@@ -10,7 +_,20 @@ +@@ -12,7 +_,19 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -public class ShapedRecipe implements CraftingRecipe { +public class ShapedRecipe implements CraftingRecipe, net.minecraftforge.common.crafting.IShapedRecipe { -+ static int MAX_WIDTH = 3; -+ static int MAX_HEIGHT = 3; -+ /** -+ * Expand the max width and height allowed in the deserializer. -+ * This should be called by modders who add custom crafting tables that are larger than the vanilla 3x3. -+ * @param width your max recipe width -+ * @param height your max recipe height -+ */ -+ public static void setCraftingSize(int width, int height) { -+ if (MAX_WIDTH < width) MAX_WIDTH = width; -+ if (MAX_HEIGHT < height) MAX_HEIGHT = height; -+ } -+ - final ShapedRecipePattern pattern; - final ItemStack result; - final String group; -@@ -37,10 +_,20 @@ - return this.group; - } ++ static int MAX_WIDTH = 3; ++ static int MAX_HEIGHT = 3; ++ /** ++ * Expand the max width and height allowed in the deserializer. ++ * This should be called by modders who add custom crafting tables that are larger than the vanilla 3x3. ++ * @param width your max recipe width ++ * @param height your max recipe height ++ */ ++ public static void setCraftingSize(int width, int height) { ++ if (MAX_WIDTH < width) MAX_WIDTH = width; ++ if (MAX_HEIGHT < height) MAX_HEIGHT = height; ++ } + final ShapedRecipePattern pattern; + final ItemStack result; + final String group; +@@ -83,9 +_,19 @@ + } -+ @Override -+ public int getRecipeWidth() { -+ return getWidth(); -+ } + @Override ++ public int getRecipeWidth() { ++ return getWidth(); ++ } + - public CraftingBookCategory category() { - return this.category; - } - -+ @Override -+ public int getRecipeHeight() { -+ return getHeight(); -+ } ++ @Override ++ public int getRecipeHeight() { ++ return getHeight(); ++ } + - public ItemStack getResultItem(RegistryAccess p_266881_) { - return this.result; - } -@@ -78,7 +_,7 @@ - return nonnulllist.isEmpty() || nonnulllist.stream().filter((p_151277_) -> { - return !p_151277_.isEmpty(); - }).anyMatch((p_151273_) -> { -- return p_151273_.getItems().length == 0; -+ return net.minecraftforge.common.ForgeHooks.hasNoElements(p_151273_); - }); - } ++ @Override + public boolean isIncomplete() { + NonNullList nonnulllist = this.getIngredients(); +- return nonnulllist.isEmpty() || nonnulllist.stream().filter(p_151277_ -> !p_151277_.isEmpty()).anyMatch(p_151273_ -> p_151273_.getItems().length == 0); ++ return nonnulllist.isEmpty() || nonnulllist.stream().filter(p_151277_ -> !p_151277_.isEmpty()).anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); + } + public static class Serializer implements RecipeSerializer { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch index 21f1056acf..c184711dd9 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch @@ -1,26 +1,23 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipePattern.java +++ b/net/minecraft/world/item/crafting/ShapedRecipePattern.java -@@ -178,9 +_,9 @@ +@@ -179,16 +_,16 @@ - public static record Data(Map key, List pattern) { - private static final Codec> PATTERN_CODEC = Codec.STRING.listOf().comapFlatMap((p_311191_) -> { -- if (p_311191_.size() > 3) { -+ if (p_311191_.size() > ShapedRecipe.MAX_HEIGHT) { - return DataResult.error(() -> { -- return "Invalid pattern: too many rows, 3 is maximum"; -+ return "Invalid pattern: too many rows, " + ShapedRecipe.MAX_HEIGHT + " is maximum"; - }); - } else if (p_311191_.isEmpty()) { - return DataResult.error(() -> { -@@ -190,9 +_,9 @@ - int i = p_311191_.get(0).length(); + public static record Data(Map key, List pattern) { + private static final Codec> PATTERN_CODEC = Codec.STRING.listOf().comapFlatMap(p_311191_ -> { +- if (p_311191_.size() > 3) { +- return DataResult.error(() -> "Invalid pattern: too many rows, 3 is maximum"); ++ if (p_311191_.size() > ShapedRecipe.MAX_HEIGHT) { ++ return DataResult.error(() -> "Invalid pattern: too many rows, " + ShapedRecipe.MAX_HEIGHT + " is maximum"); + } else if (p_311191_.isEmpty()) { + return DataResult.error(() -> "Invalid pattern: empty pattern not allowed"); + } else { + int i = p_311191_.get(0).length(); - for(String s : p_311191_) { -- if (s.length() > 3) { -+ if (s.length() > ShapedRecipe.MAX_WIDTH) { - return DataResult.error(() -> { -- return "Invalid pattern: too many columns, 3 is maximum"; -+ return "Invalid pattern: too many columns, " + ShapedRecipe.MAX_WIDTH + " is maximum"; - }); - } + for (String s : p_311191_) { +- if (s.length() > 3) { +- return DataResult.error(() -> "Invalid pattern: too many columns, 3 is maximum"); ++ if (s.length() > ShapedRecipe.MAX_HEIGHT) { ++ return DataResult.error(() -> "Invalid pattern: too many columns, " + ShapedRecipe.MAX_HEIGHT + " is maximum"); + } + if (i != s.length()) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch index f342087fed..59cf3279c2 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch @@ -1,48 +1,48 @@ --- a/net/minecraft/world/item/crafting/ShapelessRecipe.java +++ b/net/minecraft/world/item/crafting/ShapelessRecipe.java -@@ -18,12 +_,14 @@ - final CraftingBookCategory category; - final ItemStack result; - final NonNullList ingredients; -+ private final boolean isSimple; +@@ -20,12 +_,14 @@ + final CraftingBookCategory category; + final ItemStack result; + final NonNullList ingredients; ++ private final boolean isSimple; - public ShapelessRecipe(String p_249640_, CraftingBookCategory p_249390_, ItemStack p_252071_, NonNullList p_250689_) { - this.group = p_249640_; - this.category = p_249390_; - this.result = p_252071_; - this.ingredients = p_250689_; -+ this.isSimple = p_250689_.stream().allMatch(Ingredient::isSimple); - } + public ShapelessRecipe(String p_249640_, CraftingBookCategory p_249390_, ItemStack p_252071_, NonNullList p_250689_) { + this.group = p_249640_; + this.category = p_249390_; + this.result = p_252071_; + this.ingredients = p_250689_; ++ this.isSimple = p_250689_.stream().allMatch(Ingredient::isSimple); + } - public RecipeSerializer getSerializer() { -@@ -48,17 +_,20 @@ + @Override +@@ -55,17 +_,20 @@ - public boolean matches(CraftingContainer p_44262_, Level p_44263_) { - StackedContents stackedcontents = new StackedContents(); -+ java.util.List inputs = new java.util.ArrayList<>(); - int i = 0; + public boolean matches(CraftingContainer p_44262_, Level p_44263_) { + StackedContents stackedcontents = new StackedContents(); ++ var inputs = new java.util.ArrayList(); + int i = 0; - for(int j = 0; j < p_44262_.getContainerSize(); ++j) { - ItemStack itemstack = p_44262_.getItem(j); - if (!itemstack.isEmpty()) { - ++i; -+ if (isSimple) - stackedcontents.accountStack(itemstack, 1); -+ else inputs.add(itemstack); - } - } - -- return i == this.ingredients.size() && stackedcontents.canCraft(this, (IntList)null); -+ return i == this.ingredients.size() && (isSimple ? stackedcontents.canCraft(this, (IntList)null) : net.minecraftforge.common.util.RecipeMatcher.findMatches(inputs, this.ingredients) != null); - } - - public ItemStack assemble(CraftingContainer p_44260_, RegistryAccess p_266797_) { -@@ -88,7 +_,7 @@ - return "No ingredients for shapeless recipe"; - }); - } else { -- return aingredient.length > 9 ? DataResult.error(() -> { -+ return aingredient.length > ShapedRecipe.MAX_WIDTH * ShapedRecipe.MAX_HEIGHT ? DataResult.error(() -> { - return "Too many ingredients for shapeless recipe"; - }) : DataResult.success(NonNullList.of(Ingredient.EMPTY, aingredient)); + for (int j = 0; j < p_44262_.getContainerSize(); j++) { + ItemStack itemstack = p_44262_.getItem(j); + if (!itemstack.isEmpty()) { + i++; ++ if (isSimple) + stackedcontents.accountStack(itemstack, 1); ++ else inputs.add(itemstack); } + } + +- return i == this.ingredients.size() && stackedcontents.canCraft(this, null); ++ return i == this.ingredients.size() && (isSimple ? stackedcontents.canCraft(this, null) : net.minecraftforge.common.util.RecipeMatcher.findMatches(inputs, this.ingredients) != null); + } + + public ItemStack assemble(CraftingContainer p_44260_, HolderLookup.Provider p_334364_) { +@@ -92,7 +_,7 @@ + if (aingredient.length == 0) { + return DataResult.error(() -> "No ingredients for shapeless recipe"); + } else { +- return aingredient.length > 9 ++ return aingredient.length > ShapedRecipe.MAX_WIDTH * ShapedRecipe.MAX_HEIGHT + ? DataResult.error(() -> "Too many ingredients for shapeless recipe") + : DataResult.success(NonNullList.of(Ingredient.EMPTY, aingredient)); + } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShulkerBoxColoring.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShulkerBoxColoring.java.patch index b16b0c4f29..a94126fb54 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShulkerBoxColoring.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShulkerBoxColoring.java.patch @@ -1,38 +1,38 @@ --- a/net/minecraft/world/item/crafting/ShulkerBoxColoring.java +++ b/net/minecraft/world/item/crafting/ShulkerBoxColoring.java @@ -25,7 +_,7 @@ - if (Block.byItem(itemstack.getItem()) instanceof ShulkerBoxBlock) { - ++i; - } else { -- if (!(itemstack.getItem() instanceof DyeItem)) { -+ if (!itemstack.is(net.minecraftforge.common.Tags.Items.DYES)) { - return false; - } + if (Block.byItem(itemstack.getItem()) instanceof ShulkerBoxBlock) { + i++; + } else { +- if (!(itemstack.getItem() instanceof DyeItem)) { ++ if (!itemstack.is(net.minecraftforge.common.Tags.Items.DYES)) { + return false; + } @@ -43,7 +_,7 @@ - public ItemStack assemble(CraftingContainer p_44322_, RegistryAccess p_266985_) { - ItemStack itemstack = ItemStack.EMPTY; -- DyeItem dyeitem = (DyeItem)Items.WHITE_DYE; -+ net.minecraft.world.item.DyeColor dyecolor = net.minecraft.world.item.DyeColor.WHITE; + public ItemStack assemble(CraftingContainer p_44322_, HolderLookup.Provider p_336251_) { + ItemStack itemstack = ItemStack.EMPTY; +- DyeItem dyeitem = (DyeItem)Items.WHITE_DYE; ++ var dyecolor = net.minecraft.world.item.DyeColor.WHITE; - for(int i = 0; i < p_44322_.getContainerSize(); ++i) { - ItemStack itemstack1 = p_44322_.getItem(i); -@@ -51,13 +_,14 @@ - Item item = itemstack1.getItem(); - if (Block.byItem(item) instanceof ShulkerBoxBlock) { - itemstack = itemstack1; -- } else if (item instanceof DyeItem) { -- dyeitem = (DyeItem)item; -+ } else { -+ net.minecraft.world.item.DyeColor tmp = net.minecraft.world.item.DyeColor.getColor(itemstack1); -+ if (tmp != null) dyecolor = tmp; + for (int i = 0; i < p_44322_.getContainerSize(); i++) { + ItemStack itemstack1 = p_44322_.getItem(i); +@@ -52,12 +_,15 @@ + if (Block.byItem(item) instanceof ShulkerBoxBlock) { + itemstack = itemstack1; + } else if (item instanceof DyeItem) { +- dyeitem = (DyeItem)item; ++ var tmp = net.minecraft.world.item.DyeColor.getColor(itemstack1); ++ if (tmp != null) { ++ dyecolor = tmp; ++ } + } } - } - } + } + +- Block block = ShulkerBoxBlock.getBlockByColor(dyeitem.getDyeColor()); ++ Block block = ShulkerBoxBlock.getBlockByColor(dyecolor); + return itemstack.transmuteCopy(block, 1); + } -- ItemStack itemstack2 = ShulkerBoxBlock.getColoredItemStack(dyeitem.getDyeColor()); -+ ItemStack itemstack2 = ShulkerBoxBlock.getColoredItemStack(dyecolor); - if (itemstack.hasTag()) { - itemstack2.setTag(itemstack.getTag().copy()); - } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/SmithingTransformRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/SmithingTransformRecipe.java.patch index 31f04249ce..686d0f671c 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/SmithingTransformRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/SmithingTransformRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/SmithingTransformRecipe.java +++ b/net/minecraft/world/item/crafting/SmithingTransformRecipe.java -@@ -58,7 +_,7 @@ - } +@@ -63,7 +_,7 @@ - public boolean isIncomplete() { -- return Stream.of(this.template, this.base, this.addition).anyMatch(Ingredient::isEmpty); -+ return Stream.of(this.template, this.base, this.addition).anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); - } + @Override + public boolean isIncomplete() { +- return Stream.of(this.template, this.base, this.addition).anyMatch(Ingredient::isEmpty); ++ return Stream.of(this.template, this.base, this.addition).anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); + } - public static class Serializer implements RecipeSerializer { + public static class Serializer implements RecipeSerializer { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/SmithingTrimRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/SmithingTrimRecipe.java.patch index a77bcd79ed..1069cf5ec3 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/SmithingTrimRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/SmithingTrimRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/SmithingTrimRecipe.java +++ b/net/minecraft/world/item/crafting/SmithingTrimRecipe.java -@@ -87,7 +_,7 @@ - } +@@ -92,7 +_,7 @@ - public boolean isIncomplete() { -- return Stream.of(this.template, this.base, this.addition).anyMatch(Ingredient::isEmpty); -+ return Stream.of(this.template, this.base, this.addition).anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); - } + @Override + public boolean isIncomplete() { +- return Stream.of(this.template, this.base, this.addition).anyMatch(Ingredient::isEmpty); ++ return Stream.of(this.template, this.base, this.addition).anyMatch(net.minecraftforge.common.ForgeHooks::hasNoElements); + } - public static class Serializer implements RecipeSerializer { + public static class Serializer implements RecipeSerializer { diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/DiggingEnchantment.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/DiggingEnchantment.java.patch deleted file mode 100644 index 73f4532bcd..0000000000 --- a/patches/minecraft/net/minecraft/world/item/enchantment/DiggingEnchantment.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/world/item/enchantment/DiggingEnchantment.java -+++ b/net/minecraft/world/item/enchantment/DiggingEnchantment.java -@@ -22,6 +_,6 @@ - } - - public boolean canEnchant(ItemStack p_44668_) { -- return p_44668_.is(Items.SHEARS) ? true : super.canEnchant(p_44668_); -+ return p_44668_.getItem() instanceof net.minecraft.world.item.ShearsItem ? true : super.canEnchant(p_44668_); - } - } diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/Enchantment.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/Enchantment.java.patch index 24d241b62f..dafbcdc4b5 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/Enchantment.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/Enchantment.java.patch @@ -1,53 +1,19 @@ --- a/net/minecraft/world/item/enchantment/Enchantment.java +++ b/net/minecraft/world/item/enchantment/Enchantment.java -@@ -17,7 +_,7 @@ - import net.minecraft.world.entity.MobType; +@@ -23,7 +_,7 @@ + import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; --public abstract class Enchantment { -+public abstract class Enchantment implements net.minecraftforge.common.extensions.IForgeEnchantment { - private final EquipmentSlot[] slots; - private final Enchantment.Rarity rarity; - public final EnchantmentCategory category; -@@ -73,6 +_,7 @@ - return 0; - } - -+ @Deprecated // Forge: Use ItemStack aware version in IForgeEnchantment - public float getDamageBonus(int p_44682_, MobType p_44683_) { - return 0.0F; - } -@@ -113,7 +_,7 @@ - } - - public boolean canEnchant(ItemStack p_44689_) { -- return this.category.canEnchant(p_44689_.getItem()); -+ return canApplyAtEnchantingTable(p_44689_); - } - - public void doPostAttack(LivingEntity p_44686_, Entity p_44687_, int p_44688_) { -@@ -135,6 +_,24 @@ - } - - public boolean isDiscoverable() { -+ return true; -+ } -+ -+ /** -+ * This applies specifically to applying at the enchanting table. The other method {@link #canEnchant(ItemStack)} -+ * applies for all possible enchantments. -+ * @param stack -+ * @return -+ */ -+ public boolean canApplyAtEnchantingTable(ItemStack stack) { -+ return stack.canApplyAtEnchantingTable(this); -+ } -+ -+ /** -+ * Is this enchantment allowed to be enchanted on books via Enchantment Table -+ * @return false to disable the vanilla feature -+ */ -+ public boolean isAllowedOnBooks() { - return true; - } +-public class Enchantment implements FeatureElement { ++public class Enchantment implements FeatureElement, net.minecraftforge.common.extensions.IForgeEnchantment { + private final Enchantment.EnchantmentDefinition definition; + @Nullable + protected String descriptionId; +@@ -131,6 +_,7 @@ + return 0; + } ++ @Deprecated // Forge: Use ItemStack aware version in IForgeEnchantment + public float getDamageBonus(int p_44682_, @Nullable EntityType p_331633_) { + return 0.0F; + } diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentCategory.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentCategory.java.patch deleted file mode 100644 index 7abe482661..0000000000 --- a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentCategory.java.patch +++ /dev/null @@ -1,32 +0,0 @@ ---- a/net/minecraft/world/item/enchantment/EnchantmentCategory.java -+++ b/net/minecraft/world/item/enchantment/EnchantmentCategory.java -@@ -13,7 +_,7 @@ - import net.minecraft.world.item.Vanishable; - import net.minecraft.world.level.block.Block; - --public enum EnchantmentCategory { -+public enum EnchantmentCategory implements net.minecraftforge.common.IExtensibleEnum { - ARMOR { - public boolean canEnchant(Item p_44751_) { - return p_44751_ instanceof ArmorItem; -@@ -109,5 +_,19 @@ - } - }; - -- public abstract boolean canEnchant(Item p_44743_); -+ private java.util.function.Predicate delegate; -+ -+ private EnchantmentCategory() {} -+ -+ private EnchantmentCategory(java.util.function.Predicate delegate) { -+ this.delegate = delegate; -+ } -+ -+ public static EnchantmentCategory create(String name, java.util.function.Predicate delegate) { -+ throw new IllegalStateException("Enum not extended"); -+ } -+ -+ public boolean canEnchant(Item p_44743_) { -+ return this.delegate == null ? false : this.delegate.test(p_44743_); -+ } - } diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch index 7138023c31..23d6e7896a 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch @@ -1,83 +1,54 @@ --- a/net/minecraft/world/item/enchantment/EnchantmentHelper.java +++ b/net/minecraft/world/item/enchantment/EnchantmentHelper.java -@@ -59,7 +_,14 @@ - return BuiltInRegistries.ENCHANTMENT.getKey(p_182433_); - } +@@ -99,7 +_,7 @@ -+ /** @deprecated forge: use {@link #getTagEnchantmentLevel(Enchantment, ItemStack)} or {@link ItemStack#getEnchantmentLevel(Enchantment)} */ -+ @Deprecated - public static int getItemEnchantmentLevel(Enchantment p_44844_, ItemStack p_44845_) { -+ return p_44845_.getEnchantmentLevel(p_44844_); -+ } -+ -+ /** Gets the enchantment level from NBT. Generally should use {@link ItemStack#getEnchantmentLevel(Enchantment)} for gameplay logic */ -+ public static int getTagEnchantmentLevel(Enchantment p_44844_, ItemStack p_44845_) { - if (p_44845_.isEmpty()) { - return 0; - } else { -@@ -120,6 +_,13 @@ + public static float getDamageBonus(ItemStack p_44834_, @Nullable EntityType p_331963_) { + MutableFloat mutablefloat = new MutableFloat(); +- runIterationOnItem((p_327223_, p_327224_) -> mutablefloat.add(p_327223_.getDamageBonus(p_327224_, p_331963_)), p_44834_); ++ runIterationOnItem((p_327223_, p_327224_) -> mutablefloat.add(p_327223_.getDamageBonus(p_327224_, p_331963_, p_44834_)), p_44834_); + return mutablefloat.floatValue(); + } - private static void runIterationOnItem(EnchantmentHelper.EnchantmentVisitor p_44851_, ItemStack p_44852_) { - if (!p_44852_.isEmpty()) { -+ if (true) { // forge: redirect enchantment logic to allow non-NBT enchants -+ for (Map.Entry entry : p_44852_.getAllEnchantments().entrySet()) { -+ p_44851_.accept(entry.getKey(), entry.getValue()); -+ } -+ return; -+ } -+ - ListTag listtag = p_44852_.getEnchantmentTags(); +@@ -125,6 +_,7 @@ + runIterationOnInventory(enchantmenthelper$enchantmentvisitor, p_44824_.getAllSlots()); + } - for(int i = 0; i < listtag.size(); ++i) { -@@ -150,7 +_,7 @@ - public static float getDamageBonus(ItemStack p_44834_, MobType p_44835_) { - MutableFloat mutablefloat = new MutableFloat(); - runIterationOnItem((p_44887_, p_44888_) -> { -- mutablefloat.add(p_44887_.getDamageBonus(p_44888_, p_44835_)); -+ mutablefloat.add(p_44887_.getDamageBonus(p_44888_, p_44835_, p_44834_)); - }, p_44834_); - return mutablefloat.floatValue(); - } -@@ -168,6 +_,7 @@ - runIterationOnInventory(enchantmenthelper$enchantmentvisitor, p_44824_.getAllSlots()); - } ++ if(false) // Forge: Fix MC-248272 + if (p_44825_ instanceof Player) { + runIterationOnItem(enchantmenthelper$enchantmentvisitor, p_44824_.getMainHandItem()); + } +@@ -136,6 +_,7 @@ + runIterationOnInventory(enchantmenthelper$enchantmentvisitor, p_44897_.getAllSlots()); + } -+ if(false) // Forge: Fix MC-248272 - if (p_44825_ instanceof Player) { - runIterationOnItem(enchantmenthelper$enchantmentvisitor, p_44824_.getMainHandItem()); - } -@@ -182,6 +_,7 @@ - runIterationOnInventory(enchantmenthelper$enchantmentvisitor, p_44897_.getAllSlots()); - } ++ if(false) // Forge: Fix MC-248272 + if (p_44897_ instanceof Player) { + runIterationOnItem(enchantmenthelper$enchantmentvisitor, p_44897_.getMainHandItem()); + } +@@ -263,7 +_,7 @@ -+ if(false) // Forge: Fix MC-248272 - if (p_44897_ instanceof Player) { - runIterationOnItem(enchantmenthelper$enchantmentvisitor, p_44897_.getMainHandItem()); - } -@@ -306,7 +_,7 @@ - - public static int getEnchantmentCost(RandomSource p_220288_, int p_220289_, int p_220290_, ItemStack p_220291_) { - Item item = p_220291_.getItem(); -- int i = item.getEnchantmentValue(); -+ int i = p_220291_.getEnchantmentValue(); - if (i <= 0) { - return 0; - } else { -@@ -344,7 +_,7 @@ - public static List selectEnchantment(RandomSource p_220298_, ItemStack p_220299_, int p_220300_, boolean p_220301_) { - List list = Lists.newArrayList(); - Item item = p_220299_.getItem(); -- int i = item.getEnchantmentValue(); -+ int i = p_220299_.getEnchantmentValue(); - if (i <= 0) { - return list; - } else { -@@ -400,7 +_,7 @@ - boolean flag = p_44819_.is(Items.BOOK); - - for(Enchantment enchantment : BuiltInRegistries.ENCHANTMENT) { -- if ((!enchantment.isTreasureOnly() || p_44820_) && enchantment.isDiscoverable() && (enchantment.category.canEnchant(item) || flag)) { -+ if ((!enchantment.isTreasureOnly() || p_44820_) && enchantment.isDiscoverable() && (enchantment.canApplyAtEnchantingTable(p_44819_) || (flag && enchantment.isAllowedOnBooks()))) { - for(int i = enchantment.getMaxLevel(); i > enchantment.getMinLevel() - 1; --i) { - if (p_44818_ >= enchantment.getMinCost(i) && p_44818_ <= enchantment.getMaxCost(i)) { - list.add(new EnchantmentInstance(enchantment, i)); + public static int getEnchantmentCost(RandomSource p_220288_, int p_220289_, int p_220290_, ItemStack p_220291_) { + Item item = p_220291_.getItem(); +- int i = item.getEnchantmentValue(); ++ int i = p_220291_.getEnchantmentValue(); + if (i <= 0) { + return 0; + } else { +@@ -296,7 +_,7 @@ + public static List selectEnchantment(FeatureFlagSet p_329284_, RandomSource p_220298_, ItemStack p_220299_, int p_220300_, boolean p_220301_) { + List list = Lists.newArrayList(); + Item item = p_220299_.getItem(); +- int i = item.getEnchantmentValue(); ++ int i = p_220299_.getEnchantmentValue(); + if (i <= 0) { + return list; + } else { +@@ -353,7 +_,7 @@ + if (enchantment.isEnabled(p_334102_) + && (!enchantment.isTreasureOnly() || p_44820_) + && enchantment.isDiscoverable() +- && (flag || enchantment.canEnchant(p_44819_) && enchantment.isPrimaryItem(p_44819_))) { ++ && ((flag && enchantment.isAllowedOnBooks()) || enchantment.canApplyAtEnchatingTable(p_44819_))) { + for (int i = enchantment.getMaxLevel(); i > enchantment.getMinLevel() - 1; i--) { + if (p_44818_ >= enchantment.getMinCost(i) && p_44818_ <= enchantment.getMaxCost(i)) { + list.add(new EnchantmentInstance(enchantment, i)); diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java.patch index efca49f72a..624f98fa61 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java.patch @@ -1,11 +1,14 @@ --- a/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java +++ b/net/minecraft/world/item/enchantment/FrostWalkerEnchantment.java -@@ -43,7 +_,7 @@ - BlockState blockstate1 = p_45020_.getBlockState(blockpos$mutableblockpos); - if (blockstate1.isAir()) { - BlockState blockstate2 = p_45020_.getBlockState(blockpos); -- if (blockstate2 == FrostedIceBlock.meltsInto() && blockstate.canSurvive(p_45020_, blockpos) && p_45020_.isUnobstructed(blockstate, blockpos, CollisionContext.empty())) { -+ if (blockstate2 == FrostedIceBlock.meltsInto() && blockstate.canSurvive(p_45020_, blockpos) && p_45020_.isUnobstructed(blockstate, blockpos, CollisionContext.empty()) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(p_45019_, net.minecraftforge.common.util.BlockSnapshot.create(p_45020_.dimension(), p_45020_, blockpos), net.minecraft.core.Direction.UP)) { - p_45020_.setBlockAndUpdate(blockpos, blockstate); - p_45020_.scheduleTick(blockpos, Blocks.FROSTED_ICE, Mth.nextInt(p_45019_.getRandom(), 60, 120)); - } +@@ -32,8 +_,9 @@ + if (blockstate1.isAir()) { + BlockState blockstate2 = p_45020_.getBlockState(blockpos); + if (blockstate2 == FrostedIceBlock.meltsInto() +- && blockstate.canSurvive(p_45020_, blockpos) +- && p_45020_.isUnobstructed(blockstate, blockpos, CollisionContext.empty())) { ++ && blockstate.canSurvive(p_45020_, blockpos) ++ && p_45020_.isUnobstructed(blockstate, blockpos, CollisionContext.empty()) ++ && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(p_45019_, net.minecraftforge.common.util.BlockSnapshot.create(p_45020_.dimension(), p_45020_, blockpos), net.minecraft.core.Direction.UP)) { + p_45020_.setBlockAndUpdate(blockpos, blockstate); + p_45020_.scheduleTick(blockpos, Blocks.FROSTED_ICE, Mth.nextInt(p_45019_.getRandom(), 60, 120)); + } diff --git a/patches/minecraft/net/minecraft/world/item/trading/MerchantOffer.java.patch b/patches/minecraft/net/minecraft/world/item/trading/MerchantOffer.java.patch deleted file mode 100644 index d11303fc9d..0000000000 --- a/patches/minecraft/net/minecraft/world/item/trading/MerchantOffer.java.patch +++ /dev/null @@ -1,20 +0,0 @@ ---- a/net/minecraft/world/item/trading/MerchantOffer.java -+++ b/net/minecraft/world/item/trading/MerchantOffer.java -@@ -90,7 +_,7 @@ - } else { - int i = this.baseCostA.getCount(); - int j = Math.max(0, Mth.floor((float)(i * this.demand) * this.priceMultiplier)); -- return this.baseCostA.copyWithCount(Mth.clamp(i + j + this.specialPriceDiff, 1, this.baseCostA.getItem().getMaxStackSize())); -+ return this.baseCostA.copyWithCount(Mth.clamp(i + j + this.specialPriceDiff, 1, this.baseCostA.getMaxStackSize())); - } - } - -@@ -194,7 +_,7 @@ - return true; - } else { - ItemStack itemstack = p_45366_.copy(); -- if (itemstack.getItem().canBeDepleted()) { -+ if (itemstack.getItem().isDamageable(itemstack)) { - itemstack.setDamageValue(itemstack.getDamageValue()); - } - diff --git a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch index 64559a3b77..779fdb2421 100644 --- a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch @@ -1,33 +1,36 @@ --- a/net/minecraft/world/level/BaseSpawner.java +++ b/net/minecraft/world/level/BaseSpawner.java -@@ -133,12 +_,14 @@ - entity.moveTo(entity.getX(), entity.getY(), entity.getZ(), randomsource.nextFloat() * 360.0F, 0.0F); - if (entity instanceof Mob) { - Mob mob = (Mob)entity; -- if (spawndata.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(p_151312_, MobSpawnType.SPAWNER) || !mob.checkSpawnObstruction(p_151312_)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, p_151312_, MobSpawnType.SPAWNER, spawndata, this)) { - continue; - } +@@ -149,13 +_,15 @@ -- if (spawndata.getEntityToSpawn().size() == 1 && spawndata.getEntityToSpawn().contains("id", 8)) { -- ((Mob)entity).finalizeSpawn(p_151312_, p_151312_.getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.SPAWNER, (SpawnGroupData)null, (CompoundTag)null); -+ // Forge: Patch in FinalizeSpawn for spawners so it may be fired unconditionally, instead of only when vanilla normally would trigger it. -+ var event = net.minecraftforge.event.ForgeEventFactory.onFinalizeSpawnSpawner(mob, p_151312_, p_151312_.getCurrentDifficultyAt(entity.blockPosition()), null, compoundtag, this); -+ if (event != null && spawndata.getEntityToSpawn().size() == 1 && spawndata.getEntityToSpawn().contains("id", 8)) { -+ ((Mob)entity).finalizeSpawn(p_151312_, event.getDifficulty(), event.getSpawnType(), event.getSpawnData(), event.getSpawnTag()); - } - } + entity.moveTo(entity.getX(), entity.getY(), entity.getZ(), randomsource.nextFloat() * 360.0F, 0.0F); + if (entity instanceof Mob mob) { +- if (spawndata.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(p_151312_, MobSpawnType.SPAWNER) || !mob.checkSpawnObstruction(p_151312_)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, p_151312_, MobSpawnType.SPAWNER, spawndata, this)) { + continue; + } -@@ -285,4 +_,12 @@ - public double getoSpin() { - return this.oSpin; - } + boolean flag1 = spawndata.getEntityToSpawn().size() == 1 && spawndata.getEntityToSpawn().contains("id", 8); ++ // Forge: Patch in FinalizeSpawn for spawners so it may be fired unconditionally, instead of only when vanilla normally would trigger it. ++ var event = net.minecraftforge.event.ForgeEventFactory.onFinalizeSpawnSpawner(mob, p_151312_, p_151312_.getCurrentDifficultyAt(entity.blockPosition()), null, compoundtag, this); + if (flag1) { +- ((Mob)entity).finalizeSpawn(p_151312_, p_151312_.getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.SPAWNER, null); ++ ((Mob)entity).finalizeSpawn(p_151312_, event.getDifficulty(), MobSpawnType.SPAWNER, null); + } + + spawndata.getEquipment().ifPresent(mob::equip); +@@ -305,5 +_,15 @@ + + public double getoSpin() { + return this.oSpin; ++ } + -+ @Nullable -+ public Entity getSpawnerEntity() { -+ return null; -+ } ++ @Nullable ++ public Entity getSpawnerEntity() { ++ return null; ++ } + -+ @Nullable -+ public net.minecraft.world.level.block.entity.BlockEntity getSpawnerBlockEntity(){ return null; } ++ @Nullable ++ public net.minecraft.world.level.block.entity.BlockEntity getSpawnerBlockEntity() { ++ return null; + } } diff --git a/patches/minecraft/net/minecraft/world/level/BlockAndTintGetter.java.patch b/patches/minecraft/net/minecraft/world/level/BlockAndTintGetter.java.patch index 73b33f8bd7..42354c7656 100644 --- a/patches/minecraft/net/minecraft/world/level/BlockAndTintGetter.java.patch +++ b/patches/minecraft/net/minecraft/world/level/BlockAndTintGetter.java.patch @@ -6,6 +6,6 @@ -public interface BlockAndTintGetter extends BlockGetter { +public interface BlockAndTintGetter extends BlockGetter, net.minecraftforge.client.extensions.IForgeBlockAndTintGetter { - float getShade(Direction p_45522_, boolean p_45523_); + float getShade(Direction p_45522_, boolean p_45523_); - LevelLightEngine getLightEngine(); + LevelLightEngine getLightEngine(); diff --git a/patches/minecraft/net/minecraft/world/level/BlockGetter.java.patch b/patches/minecraft/net/minecraft/world/level/BlockGetter.java.patch index 24075dda11..068f4f7cb2 100644 --- a/patches/minecraft/net/minecraft/world/level/BlockGetter.java.patch +++ b/patches/minecraft/net/minecraft/world/level/BlockGetter.java.patch @@ -6,15 +6,15 @@ -public interface BlockGetter extends LevelHeightAccessor { +public interface BlockGetter extends LevelHeightAccessor, net.minecraftforge.common.extensions.IForgeBlockGetter { - @Nullable - BlockEntity getBlockEntity(BlockPos p_45570_); + @Nullable + BlockEntity getBlockEntity(BlockPos p_45570_); @@ -32,7 +_,7 @@ - FluidState getFluidState(BlockPos p_45569_); + FluidState getFluidState(BlockPos p_45569_); - default int getLightEmission(BlockPos p_45572_) { -- return this.getBlockState(p_45572_).getLightEmission(); -+ return this.getBlockState(p_45572_).getLightEmission(this, p_45572_); - } + default int getLightEmission(BlockPos p_45572_) { +- return this.getBlockState(p_45572_).getLightEmission(); ++ return this.getBlockState(p_45572_).getLightEmission(this, p_45572_); + } - default int getMaxLightLevel() { + default int getMaxLightLevel() { diff --git a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch index 06e33c34ee..9194011a4d 100644 --- a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch +++ b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/level/DataPackConfig.java +++ b/net/minecraft/world/level/DataPackConfig.java -@@ -18,7 +_,7 @@ - private final List disabled; +@@ -19,7 +_,7 @@ + private final List disabled; - public DataPackConfig(List p_45848_, List p_45849_) { -- this.enabled = ImmutableList.copyOf(p_45848_); -+ this.enabled = com.google.common.collect.Lists.newArrayList(p_45848_); - this.disabled = ImmutableList.copyOf(p_45849_); - } + public DataPackConfig(List p_45848_, List p_45849_) { +- this.enabled = ImmutableList.copyOf(p_45848_); ++ this.enabled = new java.util.ArrayList<>(p_45848_); + this.disabled = ImmutableList.copyOf(p_45849_); + } -@@ -28,5 +_,9 @@ +@@ -29,5 +_,9 @@ - public List getDisabled() { - return this.disabled; -+ } + public List getDisabled() { + return this.disabled; ++ } + -+ public void addModPacks(List modPacks) { -+ enabled.addAll(modPacks.stream().filter(p->!enabled.contains(p)).collect(java.util.stream.Collectors.toList())); - } ++ public void addModPacks(List modPacks) { ++ enabled.addAll(modPacks.stream().filter(p -> !enabled.contains(p)).toList()); + } } diff --git a/patches/minecraft/net/minecraft/world/level/Explosion.java.patch b/patches/minecraft/net/minecraft/world/level/Explosion.java.patch index 1a1ac0feb2..60b9c32cbf 100644 --- a/patches/minecraft/net/minecraft/world/level/Explosion.java.patch +++ b/patches/minecraft/net/minecraft/world/level/Explosion.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/Explosion.java +++ b/net/minecraft/world/level/Explosion.java -@@ -193,6 +_,7 @@ - int j2 = Mth.floor(this.z - (double)f2 - 1.0D); - int j1 = Mth.floor(this.z + (double)f2 + 1.0D); - List list = this.level.getEntities(this.source, new AABB((double)k1, (double)i2, (double)j2, (double)l1, (double)i1, (double)j1)); -+ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, list, f2); - Vec3 vec3 = new Vec3(this.x, this.y, this.z); +@@ -256,6 +_,7 @@ + int j2 = Mth.floor(this.z - (double)f2 - 1.0); + int j1 = Mth.floor(this.z + (double)f2 + 1.0); + List list = this.level.getEntities(this.source, new AABB((double)k1, (double)i2, (double)j2, (double)l1, (double)i1, (double)j1)); ++ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, list, f2); + Vec3 vec3 = new Vec3(this.x, this.y, this.z); - for(Entity entity : list) { + for (Entity entity : list) { diff --git a/patches/minecraft/net/minecraft/world/level/ExplosionDamageCalculator.java.patch b/patches/minecraft/net/minecraft/world/level/ExplosionDamageCalculator.java.patch index b67eaa3768..510dce6c54 100644 --- a/patches/minecraft/net/minecraft/world/level/ExplosionDamageCalculator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/ExplosionDamageCalculator.java.patch @@ -3,9 +3,9 @@ @@ -9,7 +_,7 @@ public class ExplosionDamageCalculator { - public Optional getBlockExplosionResistance(Explosion p_46099_, BlockGetter p_46100_, BlockPos p_46101_, BlockState p_46102_, FluidState p_46103_) { -- return p_46102_.isAir() && p_46103_.isEmpty() ? Optional.empty() : Optional.of(Math.max(p_46102_.getBlock().getExplosionResistance(), p_46103_.getExplosionResistance())); -+ return p_46102_.isAir() && p_46103_.isEmpty() ? Optional.empty() : Optional.of(Math.max(p_46102_.getExplosionResistance(p_46100_, p_46101_, p_46099_), p_46103_.getExplosionResistance(p_46100_, p_46101_, p_46099_))); - } + public Optional getBlockExplosionResistance(Explosion p_46099_, BlockGetter p_46100_, BlockPos p_46101_, BlockState p_46102_, FluidState p_46103_) { +- return p_46102_.isAir() && p_46103_.isEmpty() ? Optional.empty() : Optional.of(Math.max(p_46102_.getBlock().getExplosionResistance(), p_46103_.getExplosionResistance())); ++ return p_46102_.isAir() && p_46103_.isEmpty() ? Optional.empty() : Optional.of(Math.max(p_46102_.getExplosionResistance(p_46100_, p_46101_, p_46099_), p_46103_.getExplosionResistance(p_46100_, p_46101_, p_46099_))); + } - public boolean shouldBlockExplode(Explosion p_46094_, BlockGetter p_46095_, BlockPos p_46096_, BlockState p_46097_, float p_46098_) { + public boolean shouldBlockExplode(Explosion p_46094_, BlockGetter p_46095_, BlockPos p_46096_, BlockState p_46097_, float p_46098_) { diff --git a/patches/minecraft/net/minecraft/world/level/ForcedChunksSavedData.java.patch b/patches/minecraft/net/minecraft/world/level/ForcedChunksSavedData.java.patch index eebfd8aa17..50a30ffdb1 100644 --- a/patches/minecraft/net/minecraft/world/level/ForcedChunksSavedData.java.patch +++ b/patches/minecraft/net/minecraft/world/level/ForcedChunksSavedData.java.patch @@ -1,35 +1,35 @@ --- a/net/minecraft/world/level/ForcedChunksSavedData.java +++ b/net/minecraft/world/level/ForcedChunksSavedData.java -@@ -24,15 +_,31 @@ - } +@@ -25,16 +_,31 @@ + } - public static ForcedChunksSavedData load(CompoundTag p_151484_) { -- return new ForcedChunksSavedData(new LongOpenHashSet(p_151484_.getLongArray("Forced"))); -+ ForcedChunksSavedData savedData = new ForcedChunksSavedData(new LongOpenHashSet(p_151484_.getLongArray("Forced"))); -+ net.minecraftforge.common.world.ForgeChunkManager.readForgeForcedChunks(p_151484_, savedData.blockForcedChunks, savedData.entityForcedChunks); -+ return savedData; - } + public static ForcedChunksSavedData load(CompoundTag p_151484_, HolderLookup.Provider p_329967_) { +- return new ForcedChunksSavedData(new LongOpenHashSet(p_151484_.getLongArray("Forced"))); ++ var ret = new ForcedChunksSavedData(new LongOpenHashSet(p_151484_.getLongArray("Forced"))); ++ net.minecraftforge.common.world.ForgeChunkManager.readForgeForcedChunks(p_151484_, ret.blockForcedChunks, ret.entityForcedChunks); ++ return ret; + } - public CompoundTag save(CompoundTag p_46120_) { - p_46120_.putLongArray("Forced", this.chunks.toLongArray()); -+ net.minecraftforge.common.world.ForgeChunkManager.writeForgeForcedChunks(p_46120_, this.blockForcedChunks, this.entityForcedChunks); - return p_46120_; - } + @Override + public CompoundTag save(CompoundTag p_46120_, HolderLookup.Provider p_329035_) { + p_46120_.putLongArray("Forced", this.chunks.toLongArray()); ++ net.minecraftforge.common.world.ForgeChunkManager.writeForgeForcedChunks(p_46120_, this.blockForcedChunks, this.entityForcedChunks); + return p_46120_; + } - public LongSet getChunks() { - return this.chunks; -+ } + public LongSet getChunks() { + return this.chunks; ++ } + -+ /* ======================================== FORGE START =====================================*/ -+ // TODO: not sure if these are being written correctly. load used to refer to these directly. -+ private net.minecraftforge.common.world.ForgeChunkManager.TicketTracker blockForcedChunks = new net.minecraftforge.common.world.ForgeChunkManager.TicketTracker<>(); -+ private net.minecraftforge.common.world.ForgeChunkManager.TicketTracker entityForcedChunks = new net.minecraftforge.common.world.ForgeChunkManager.TicketTracker<>(); ++ // TODO: not sure if these are being written correctly. load used to refer to these directly. ++ private net.minecraftforge.common.world.ForgeChunkManager.TicketTracker blockForcedChunks = new net.minecraftforge.common.world.ForgeChunkManager.TicketTracker<>(); ++ private net.minecraftforge.common.world.ForgeChunkManager.TicketTracker entityForcedChunks = new net.minecraftforge.common.world.ForgeChunkManager.TicketTracker<>(); + -+ public net.minecraftforge.common.world.ForgeChunkManager.TicketTracker getBlockForcedChunks() { -+ return this.blockForcedChunks; -+ } ++ public net.minecraftforge.common.world.ForgeChunkManager.TicketTracker getBlockForcedChunks() { ++ return this.blockForcedChunks; ++ } + -+ public net.minecraftforge.common.world.ForgeChunkManager.TicketTracker getEntityForcedChunks() { -+ return this.entityForcedChunks; - } ++ public net.minecraftforge.common.world.ForgeChunkManager.TicketTracker getEntityForcedChunks() { ++ return this.entityForcedChunks; + } } diff --git a/patches/minecraft/net/minecraft/world/level/Level.java.patch b/patches/minecraft/net/minecraft/world/level/Level.java.patch index b89aab32ee..7cc24ad940 100644 --- a/patches/minecraft/net/minecraft/world/level/Level.java.patch +++ b/patches/minecraft/net/minecraft/world/level/Level.java.patch @@ -1,243 +1,232 @@ --- a/net/minecraft/world/level/Level.java +++ b/net/minecraft/world/level/Level.java -@@ -73,7 +_,7 @@ +@@ -75,7 +_,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.Scoreboard; -public abstract class Level implements LevelAccessor, AutoCloseable { +public abstract class Level extends net.minecraftforge.common.capabilities.CapabilityProvider implements LevelAccessor, AutoCloseable, net.minecraftforge.common.extensions.IForgeLevel { - public static final Codec> RESOURCE_KEY_CODEC = ResourceKey.codec(Registries.DIMENSION); - public static final ResourceKey OVERWORLD = ResourceKey.create(Registries.DIMENSION, new ResourceLocation("overworld")); - public static final ResourceKey NETHER = ResourceKey.create(Registries.DIMENSION, new ResourceLocation("the_nether")); -@@ -113,8 +_,14 @@ - private final RegistryAccess registryAccess; - private final DamageSources damageSources; - private long subTickCount; -+ public boolean restoringBlockSnapshots = false; -+ public boolean captureBlockSnapshots = false; -+ public java.util.ArrayList capturedBlockSnapshots = new java.util.ArrayList<>(); -+ private final java.util.ArrayList freshBlockEntities = new java.util.ArrayList<>(); -+ private final java.util.ArrayList pendingFreshBlockEntities = new java.util.ArrayList<>(); + public static final Codec> RESOURCE_KEY_CODEC = ResourceKey.codec(Registries.DIMENSION); + public static final ResourceKey OVERWORLD = ResourceKey.create(Registries.DIMENSION, new ResourceLocation("overworld")); + public static final ResourceKey NETHER = ResourceKey.create(Registries.DIMENSION, new ResourceLocation("the_nether")); +@@ -113,6 +_,11 @@ + private final RegistryAccess registryAccess; + private final DamageSources damageSources; + private long subTickCount; ++ public boolean restoringBlockSnapshots = false; ++ public boolean captureBlockSnapshots = false; ++ public java.util.ArrayList capturedBlockSnapshots = new java.util.ArrayList<>(); ++ private final java.util.ArrayList freshBlockEntities = new java.util.ArrayList<>(); ++ private final java.util.ArrayList pendingFreshBlockEntities = new java.util.ArrayList<>(); - protected Level(WritableLevelData p_270739_, ResourceKey p_270683_, RegistryAccess p_270200_, Holder p_270240_, Supplier p_270692_, boolean p_270904_, boolean p_270470_, long p_270248_, int p_270466_) { -+ super(Level.class); - this.profiler = p_270692_; - this.levelData = p_270739_; - this.dimensionTypeRegistration = p_270240_; -@@ -201,11 +_,40 @@ - } else { - LevelChunk levelchunk = this.getChunkAt(p_46605_); - Block block = p_46606_.getBlock(); + protected Level( + WritableLevelData p_270739_, +@@ -125,6 +_,7 @@ + long p_270248_, + int p_270466_ + ) { ++ super(Level.class); + this.profiler = p_270692_; + this.levelData = p_270739_; + this.dimensionTypeRegistration = p_270240_; +@@ -215,11 +_,39 @@ + } else { + LevelChunk levelchunk = this.getChunkAt(p_46605_); + Block block = p_46606_.getBlock(); + -+ p_46605_ = p_46605_.immutable(); // Forge - prevent mutable BlockPos leaks -+ net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; -+ if (this.captureBlockSnapshots && !this.isClientSide) { -+ blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.create(this.dimension, this, p_46605_, p_46607_); -+ this.capturedBlockSnapshots.add(blockSnapshot); -+ } -+ -+ BlockState old = getBlockState(p_46605_); -+ int oldLight = old.getLightEmission(this, p_46605_); -+ int oldOpacity = old.getLightBlock(this, p_46605_); -+ - BlockState blockstate = levelchunk.setBlockState(p_46605_, p_46606_, (p_46607_ & 64) != 0); - if (blockstate == null) { -+ if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); - return false; - } else { - BlockState blockstate1 = this.getBlockState(p_46605_); -+ -+ if (blockSnapshot == null) { // Don't notify clients or update physics while capturing blockstates -+ this.markAndNotifyBlock(p_46605_, levelchunk, blockstate, p_46606_, p_46607_, p_46608_); ++ p_46605_ = p_46605_.immutable(); // Forge - prevent mutable BlockPos leaks ++ net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; ++ if (this.captureBlockSnapshots && !this.isClientSide) { ++ blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.create(this.dimension, this, p_46605_, p_46607_); ++ this.capturedBlockSnapshots.add(blockSnapshot); + } + -+ return true; -+ } -+ } -+ } ++ BlockState old = getBlockState(p_46605_); ++ int oldLight = old.getLightEmission(this, p_46605_); ++ int oldOpacity = old.getLightBlock(this, p_46605_); + -+ // Split off from original setBlockState(BlockPos, BlockState, int, int) method in order to directly send client and physic updates -+ public void markAndNotifyBlock(BlockPos p_46605_, @Nullable LevelChunk levelchunk, BlockState blockstate, BlockState p_46606_, int p_46607_, int p_46608_) { -+ Block block = p_46606_.getBlock(); -+ BlockState blockstate1 = getBlockState(p_46605_); -+ { -+ { - if (blockstate1 == p_46606_) { - if (blockstate != blockstate1) { - this.setBlocksDirty(p_46605_, blockstate, blockstate1); -@@ -230,9 +_,8 @@ - } + BlockState blockstate = levelchunk.setBlockState(p_46605_, p_46606_, (p_46607_ & 64) != 0); + if (blockstate == null) { ++ if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); + return false; + } else { + BlockState blockstate1 = this.getBlockState(p_46605_); ++ if (blockSnapshot == null) { // Don't notify clients or update physics while capturing blockstates ++ this.markAndNotifyBlock(p_46605_, levelchunk, blockstate, p_46606_, p_46607_, p_46608_); ++ } ++ ++ return true; ++ } ++ } ++ } ++ ++ // Split off from original setBlockState(BlockPos, BlockState, int, int) method in order to directly send client and physic updates ++ public void markAndNotifyBlock(BlockPos p_46605_, @Nullable LevelChunk levelchunk, BlockState blockstate, BlockState p_46606_, int p_46607_, int p_46608_) { ++ Block block = p_46606_.getBlock(); ++ BlockState blockstate1 = getBlockState(p_46605_); ++ { ++ { + if (blockstate1 == p_46606_) { + if (blockstate != blockstate1) { + this.setBlocksDirty(p_46605_, blockstate, blockstate1); +@@ -246,9 +_,8 @@ + } - this.onBlockStateChange(p_46605_, blockstate, blockstate1); -+ p_46606_.onBlockStateChange(this, p_46605_, blockstate); - } + this.onBlockStateChange(p_46605_, blockstate, blockstate1); ++ p_46606_.onBlockStateChange(this, p_46605_, blockstate); + } - -- return true; - } - } - } -@@ -282,6 +_,7 @@ - } - - public void updateNeighborsAt(BlockPos p_46673_, Block p_46674_) { -+ net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_46673_, this.getBlockState(p_46673_), java.util.EnumSet.allOf(Direction.class), false).isCanceled(); - } - - public void updateNeighborsAtExceptFromFacing(BlockPos p_46591_, Block p_46592_, Direction p_46593_) { -@@ -408,10 +_,26 @@ - (this.tickingBlockEntities ? this.pendingBlockEntityTickers : this.blockEntityTickers).add(p_151526_); - } - -+ public void addFreshBlockEntities(java.util.Collection beList) { -+ if (this.tickingBlockEntities) { -+ this.pendingFreshBlockEntities.addAll(beList); -+ } else { -+ this.freshBlockEntities.addAll(beList); -+ } -+ } -+ - protected void tickBlockEntities() { - ProfilerFiller profilerfiller = this.getProfiler(); - profilerfiller.push("blockEntities"); -+ if (!this.pendingFreshBlockEntities.isEmpty()) { -+ this.freshBlockEntities.addAll(this.pendingFreshBlockEntities); -+ this.pendingFreshBlockEntities.clear(); -+ } - this.tickingBlockEntities = true; -+ if (!this.freshBlockEntities.isEmpty()) { -+ this.freshBlockEntities.forEach(BlockEntity::onLoad); -+ this.freshBlockEntities.clear(); -+ } - if (!this.pendingBlockEntityTickers.isEmpty()) { - this.blockEntityTickers.addAll(this.pendingBlockEntityTickers); - this.pendingBlockEntityTickers.clear(); -@@ -435,12 +_,19 @@ - - public void guardEntityTick(Consumer p_46654_, T p_46655_) { - try { -+ net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackStart(p_46655_); - p_46654_.accept(p_46655_); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking entity"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Entity being ticked"); - p_46655_.fillCrashReportCategory(crashreportcategory); -+ if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringEntities.get()) { -+ com.mojang.logging.LogUtils.getLogger().error("{}", crashreport.getFriendlyReport()); -+ p_46655_.discard(); -+ } else - throw new ReportedException(crashreport); -+ } finally { -+ net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackEnd(p_46655_); - } - } - -@@ -486,7 +_,7 @@ - explosion$blockinteraction1 = this.getDestroyType(GameRules.RULE_BLOCK_EXPLOSION_DROP_DECAY); - break; - case MOB: -- explosion$blockinteraction1 = this.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) ? this.getDestroyType(GameRules.RULE_MOB_EXPLOSION_DROP_DECAY) : Explosion.BlockInteraction.KEEP; -+ explosion$blockinteraction1 = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this, p_312521_) ? this.getDestroyType(GameRules.RULE_MOB_EXPLOSION_DROP_DECAY) : Explosion.BlockInteraction.KEEP; - break; - case TNT: - explosion$blockinteraction1 = this.getDestroyType(GameRules.RULE_TNT_EXPLOSION_DROP_DECAY); -@@ -500,6 +_,7 @@ - - Explosion.BlockInteraction explosion$blockinteraction = explosion$blockinteraction1; - Explosion explosion = new Explosion(this, p_312521_, p_310678_, p_312887_, p_309783_, p_312776_, p_310505_, p_310209_, p_309445_, explosion$blockinteraction, p_311889_, p_311434_, p_312016_); -+ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, explosion)) return explosion; - explosion.explode(); - explosion.finalizeExplosion(p_309655_); - return explosion; -@@ -531,6 +_,7 @@ - if (!this.isOutsideBuildHeight(p_46748_)) { - this.getChunkAt(p_46748_).removeBlockEntity(p_46748_); - } -+ this.updateNeighbourForOutputSignal(p_46748_, getBlockState(p_46748_).getBlock()); //Notify neighbors of changes - } - - public boolean isLoaded(BlockPos p_46750_) { -@@ -601,6 +_,7 @@ - list.add(p_151522_); - } - -+ if (false) - if (p_151522_ instanceof EnderDragon) { - for(EnderDragonPart enderdragonpart : ((EnderDragon)p_151522_).getSubEntities()) { - if (p_151522_ != p_46536_ && p_46538_.test(enderdragonpart)) { -@@ -610,6 +_,11 @@ - } - - }); -+ for (net.minecraftforge.entity.PartEntity p : this.getPartEntities()) { -+ if (p != p_46536_ && p.getBoundingBox().intersects(p_46537_) && p_46538_.test(p)) { -+ list.add(p); -+ } -+ } - return list; - } - -@@ -633,6 +_,8 @@ +- return true; } - } + } + } +@@ -300,6 +_,7 @@ + } + public void updateNeighborsAt(BlockPos p_46673_, Block p_46674_) { ++ net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(this, p_46673_, this.getBlockState(p_46673_), java.util.EnumSet.allOf(Direction.class), false).isCanceled(); + } + + public void updateNeighborsAtExceptFromFacing(BlockPos p_46591_, Block p_46592_, Direction p_46593_) { +@@ -474,10 +_,30 @@ + (this.tickingBlockEntities ? this.pendingBlockEntityTickers : this.blockEntityTickers).add(p_151526_); + } + ++ public void addFreshBlockEntities(java.util.Collection beList) { ++ if (this.tickingBlockEntities) { ++ this.pendingFreshBlockEntities.addAll(beList); ++ } else { ++ this.freshBlockEntities.addAll(beList); ++ } ++ } + -+ if (false) - if (p_261454_ instanceof EnderDragon enderdragon) { - for(EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { - T t = p_261885_.tryCast(enderdragonpart); -@@ -647,6 +_,15 @@ + protected void tickBlockEntities() { + ProfilerFiller profilerfiller = this.getProfiler(); + profilerfiller.push("blockEntities"); ++ ++ if (!this.pendingFreshBlockEntities.isEmpty()) { ++ this.freshBlockEntities.addAll(this.pendingFreshBlockEntities); ++ this.pendingFreshBlockEntities.clear(); ++ } ++ + this.tickingBlockEntities = true; ++ ++ if (!this.freshBlockEntities.isEmpty()) { ++ this.freshBlockEntities.forEach(BlockEntity::onLoad); ++ this.freshBlockEntities.clear(); ++ } ++ + if (!this.pendingBlockEntityTickers.isEmpty()) { + this.blockEntityTickers.addAll(this.pendingBlockEntityTickers); + this.pendingBlockEntityTickers.clear(); +@@ -501,12 +_,19 @@ - return AbortableIterationConsumer.Continuation.CONTINUE; - }); -+ for (net.minecraftforge.entity.PartEntity p : this.getPartEntities()) { -+ T t = p_261885_.tryCast(p); -+ if (t != null && t.getBoundingBox().intersects(p_262086_) && p_261688_.test(t)) { -+ p_262071_.add(t); -+ if (p_262071_.size() >= p_261858_) { -+ break; -+ } -+ } -+ } - } + public void guardEntityTick(Consumer p_46654_, T p_46655_) { + try { ++ net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackStart(p_46655_); + p_46654_.accept(p_46655_); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking entity"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Entity being ticked"); + p_46655_.fillCrashReportCategory(crashreportcategory); ++ if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringEntities.get()) { ++ com.mojang.logging.LogUtils.getLogger().error("{}", crashreport.getFriendlyReport()); ++ p_46655_.discard(); ++ } else + throw new ReportedException(crashreport); ++ } finally { ++ net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackEnd(p_46655_); + } + } - @Nullable -@@ -780,16 +_,15 @@ - public abstract Scoreboard getScoreboard(); +@@ -655,7 +_,7 @@ + Explosion.BlockInteraction explosion$blockinteraction = switch (p_310628_) { + case NONE -> Explosion.BlockInteraction.KEEP; + case BLOCK -> this.getDestroyType(GameRules.RULE_BLOCK_EXPLOSION_DROP_DECAY); +- case MOB -> this.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING) ? this.getDestroyType(GameRules.RULE_MOB_EXPLOSION_DROP_DECAY) : Explosion.BlockInteraction.KEEP; ++ case MOB -> net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(this, p_312521_) ? this.getDestroyType(GameRules.RULE_MOB_EXPLOSION_DROP_DECAY) : Explosion.BlockInteraction.KEEP; + case TNT -> this.getDestroyType(GameRules.RULE_TNT_EXPLOSION_DROP_DECAY); + case BLOW -> Explosion.BlockInteraction.TRIGGER_BLOCK; + }; +@@ -674,6 +_,9 @@ + p_311434_, + p_328498_ + ); ++ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, explosion)) { ++ return explosion; ++ } + explosion.explode(); + explosion.finalizeExplosion(p_309655_); + return explosion; +@@ -708,6 +_,7 @@ + if (!this.isOutsideBuildHeight(p_46748_)) { + this.getChunkAt(p_46748_).removeBlockEntity(p_46748_); + } ++ this.updateNeighbourForOutputSignal(p_46748_, getBlockState(p_46748_).getBlock()); //Notify neighbors of changes + } - public void updateNeighbourForOutputSignal(BlockPos p_46718_, Block p_46719_) { -- for(Direction direction : Direction.Plane.HORIZONTAL) { -+ for(Direction direction : Direction.values()) { - BlockPos blockpos = p_46718_.relative(direction); - if (this.hasChunkAt(blockpos)) { - BlockState blockstate = this.getBlockState(blockpos); -- if (blockstate.is(Blocks.COMPARATOR)) { -- this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false); -- } else if (blockstate.isRedstoneConductor(this, blockpos)) { -+ blockstate.onNeighborChange(this, blockpos, p_46718_); -+ if (blockstate.isRedstoneConductor(this, blockpos)) { - blockpos = blockpos.relative(direction); - blockstate = this.getBlockState(blockpos); -- if (blockstate.is(Blocks.COMPARATOR)) { -+ if (blockstate.getWeakChanges(this, blockpos)) { - this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false); - } + public boolean isLoaded(BlockPos p_46750_) { +@@ -784,8 +_,8 @@ + list.add(p_151522_); } -@@ -874,6 +_,18 @@ - public BiomeManager getBiomeManager() { - return this.biomeManager; -+ } +- if (p_151522_ instanceof EnderDragon) { +- for (EnderDragonPart enderdragonpart : ((EnderDragon)p_151522_).getSubEntities()) { ++ if (p_151522_.isMultipartEntity()) { ++ for (var enderdragonpart : p_151522_.getParts()) { + if (p_151522_ != p_46536_ && p_46538_.test(enderdragonpart)) { + list.add(enderdragonpart); + } +@@ -818,8 +_,8 @@ + } + } + +- if (p_261454_ instanceof EnderDragon enderdragon) { +- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { ++ if (p_261454_ .isMultipartEntity()) { ++ for (var enderdragonpart : p_261454_.getParts()) { + T t = p_261885_.tryCast(enderdragonpart); + if (t != null && p_261688_.test(t)) { + p_262071_.add(t); +@@ -958,16 +_,15 @@ + public abstract Scoreboard getScoreboard(); + + public void updateNeighbourForOutputSignal(BlockPos p_46718_, Block p_46719_) { +- for (Direction direction : Direction.Plane.HORIZONTAL) { ++ for (Direction direction : Direction.values()) { + BlockPos blockpos = p_46718_.relative(direction); + if (this.hasChunkAt(blockpos)) { + BlockState blockstate = this.getBlockState(blockpos); +- if (blockstate.is(Blocks.COMPARATOR)) { +- this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false); +- } else if (blockstate.isRedstoneConductor(this, blockpos)) { ++ blockstate.onNeighborChange(this, blockpos, p_46718_); ++ if (blockstate.isRedstoneConductor(this, blockpos)) { + blockpos = blockpos.relative(direction); + blockstate = this.getBlockState(blockpos); +- if (blockstate.is(Blocks.COMPARATOR)) { ++ if (blockstate.getWeakChanges(this, blockpos)) { + this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false); + } + } +@@ -1078,6 +_,20 @@ + } + + public abstract PotionBrewing potionBrewing(); + -+ private double maxEntityRadius = 2.0D; -+ @Override -+ public double getMaxEntityRadius() { -+ return maxEntityRadius; -+ } -+ @Override -+ public double increaseMaxEntityRadius(double value) { -+ if (value > maxEntityRadius) -+ maxEntityRadius = value; -+ return maxEntityRadius; - } ++ private double maxEntityRadius = 2.0D; ++ ++ @Override ++ public double getMaxEntityRadius() { ++ return maxEntityRadius; ++ } ++ ++ @Override ++ public double increaseMaxEntityRadius(double value) { ++ if (value > maxEntityRadius) ++ maxEntityRadius = value; ++ return maxEntityRadius; ++ } - public final boolean isDebug() { + public static enum ExplosionInteraction { + NONE, diff --git a/patches/minecraft/net/minecraft/world/level/LevelReader.java.patch b/patches/minecraft/net/minecraft/world/level/LevelReader.java.patch index 9a273915fb..75a28d7697 100644 --- a/patches/minecraft/net/minecraft/world/level/LevelReader.java.patch +++ b/patches/minecraft/net/minecraft/world/level/LevelReader.java.patch @@ -1,13 +1,15 @@ --- a/net/minecraft/world/level/LevelReader.java +++ b/net/minecraft/world/level/LevelReader.java -@@ -182,6 +_,10 @@ - } +@@ -173,6 +_,12 @@ + : 15; + } - /** @deprecated */ -+ default boolean isAreaLoaded(BlockPos center, int range) { -+ return this.hasChunksAt(center.offset(-range, -range, -range), center.offset(range, range, range)); -+ } + - @Deprecated - default boolean hasChunksAt(BlockPos p_46833_, BlockPos p_46834_) { - return this.hasChunksAt(p_46833_.getX(), p_46833_.getY(), p_46833_.getZ(), p_46834_.getX(), p_46834_.getY(), p_46834_.getZ()); ++ @Deprecated ++ default boolean isAreaLoaded(BlockPos center, int range) { ++ return this.hasChunksAt(center.offset(-range, -range, -range), center.offset(range, range, range)); ++ } ++ + @Deprecated + default boolean hasChunkAt(int p_151578_, int p_151579_) { + return this.hasChunk(SectionPos.blockToSectionCoord(p_151578_), SectionPos.blockToSectionCoord(p_151579_)); diff --git a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch index d08b29a42b..df2acb0360 100644 --- a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch @@ -1,61 +1,71 @@ --- a/net/minecraft/world/level/LevelSettings.java +++ b/net/minecraft/world/level/LevelSettings.java -@@ -11,8 +_,12 @@ - private final boolean allowCommands; - private final GameRules gameRules; - private final WorldDataConfiguration dataConfiguration; -+ private final com.mojang.serialization.Lifecycle lifecycle; +@@ -11,9 +_,16 @@ + private final boolean allowCommands; + private final GameRules gameRules; + private final WorldDataConfiguration dataConfiguration; +- +- public LevelSettings( +- String p_250485_, GameType p_250207_, boolean p_251631_, Difficulty p_252122_, boolean p_248961_, GameRules p_248536_, WorldDataConfiguration p_249797_ ++ private final com.mojang.serialization.Lifecycle lifecycle; ++ ++ public LevelSettings( ++ String p_250485_, GameType p_250207_, boolean p_251631_, Difficulty p_252122_, boolean p_248961_, GameRules p_248536_, WorldDataConfiguration p_249797_ ++ ) { ++ this(p_250485_, p_250207_, p_251631_, p_252122_, p_248961_, p_248536_, p_249797_, com.mojang.serialization.Lifecycle.stable()); ++ } ++ ++ public LevelSettings( ++ String p_250485_, GameType p_250207_, boolean p_251631_, Difficulty p_252122_, boolean p_248961_, GameRules p_248536_, WorldDataConfiguration p_249797_, com.mojang.serialization.Lifecycle lifecycle + ) { + this.levelName = p_250485_; + this.gameType = p_250207_; +@@ -22,6 +_,7 @@ + this.allowCommands = p_248961_; + this.gameRules = p_248536_; + this.dataConfiguration = p_249797_; ++ this.lifecycle = lifecycle; + } - public LevelSettings(String p_250485_, GameType p_250207_, boolean p_251631_, Difficulty p_252122_, boolean p_248961_, GameRules p_248536_, WorldDataConfiguration p_249797_) { -+ this(p_250485_, p_250207_, p_251631_, p_252122_, p_248961_, p_248536_, p_249797_, com.mojang.serialization.Lifecycle.stable()); -+ } -+ public LevelSettings(String p_250485_, GameType p_250207_, boolean p_251631_, Difficulty p_252122_, boolean p_248961_, GameRules p_248536_, WorldDataConfiguration p_249797_, com.mojang.serialization.Lifecycle lifecycle) { - this.levelName = p_250485_; - this.gameType = p_250207_; - this.hardcore = p_251631_; -@@ -20,13 +_,14 @@ - this.allowCommands = p_248961_; - this.gameRules = p_248536_; - this.dataConfiguration = p_249797_; -+ this.lifecycle = lifecycle; - } + public static LevelSettings parse(Dynamic p_46925_, WorldDataConfiguration p_251697_) { +@@ -33,7 +_,8 @@ + p_46925_.get("Difficulty").asNumber().map(p_46928_ -> Difficulty.byId(p_46928_.byteValue())).result().orElse(Difficulty.NORMAL), + p_46925_.get("allowCommands").asBoolean(gametype == GameType.CREATIVE), + new GameRules(p_46925_.get("GameRules")), +- p_251697_ ++ p_251697_, ++ net.minecraftforge.common.ForgeHooks.parseLifecycle(p_46925_.get("forgeLifecycle").asString("stable")) + ); + } - public static LevelSettings parse(Dynamic p_46925_, WorldDataConfiguration p_251697_) { - GameType gametype = GameType.byId(p_46925_.get("GameType").asInt(0)); - return new LevelSettings(p_46925_.get("LevelName").asString(""), gametype, p_46925_.get("hardcore").asBoolean(false), p_46925_.get("Difficulty").asNumber().map((p_46928_) -> { - return Difficulty.byId(p_46928_.byteValue()); -- }).result().orElse(Difficulty.NORMAL), p_46925_.get("allowCommands").asBoolean(gametype == GameType.CREATIVE), new GameRules(p_46925_.get("GameRules")), p_251697_); -+ }).result().orElse(Difficulty.NORMAL), p_46925_.get("allowCommands").asBoolean(gametype == GameType.CREATIVE), new GameRules(p_46925_.get("GameRules")), p_251697_, net.minecraftforge.common.ForgeHooks.parseLifecycle(p_46925_.get("forgeLifecycle").asString("stable"))); - } +@@ -66,18 +_,26 @@ + } - public String levelName() { -@@ -58,18 +_,25 @@ - } + public LevelSettings withGameType(GameType p_46923_) { +- return new LevelSettings(this.levelName, p_46923_, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration); ++ return new LevelSettings(this.levelName, p_46923_, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration, this.lifecycle); + } - public LevelSettings withGameType(GameType p_46923_) { -- return new LevelSettings(this.levelName, p_46923_, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration); -+ return new LevelSettings(this.levelName, p_46923_, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration, this.lifecycle); - } + public LevelSettings withDifficulty(Difficulty p_46919_) { +- return new LevelSettings(this.levelName, this.gameType, this.hardcore, p_46919_, this.allowCommands, this.gameRules, this.dataConfiguration); ++ return new LevelSettings(this.levelName, this.gameType, this.hardcore, p_46919_, this.allowCommands, this.gameRules, this.dataConfiguration, this.lifecycle); + } - public LevelSettings withDifficulty(Difficulty p_46919_) { -- return new LevelSettings(this.levelName, this.gameType, this.hardcore, p_46919_, this.allowCommands, this.gameRules, this.dataConfiguration); -+ net.minecraftforge.common.ForgeHooks.onDifficultyChange(p_46919_, this.difficulty); -+ return new LevelSettings(this.levelName, this.gameType, this.hardcore, p_46919_, this.allowCommands, this.gameRules, this.dataConfiguration, this.lifecycle); - } + public LevelSettings withDataConfiguration(WorldDataConfiguration p_250867_) { +- return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, p_250867_); ++ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, p_250867_, this.lifecycle); + } - public LevelSettings withDataConfiguration(WorldDataConfiguration p_250867_) { -- return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, p_250867_); -+ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, dataConfiguration, this.lifecycle); - } - - public LevelSettings copy() { -- return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules.copy(), this.dataConfiguration); -+ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules.copy(), this.dataConfiguration, this.lifecycle); -+ } -+ public LevelSettings withLifecycle(com.mojang.serialization.Lifecycle lifecycle) { -+ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration, lifecycle); -+ } -+ public com.mojang.serialization.Lifecycle getLifecycle() { -+ return this.lifecycle; - } + public LevelSettings copy() { +- return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules.copy(), this.dataConfiguration); ++ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules.copy(), this.dataConfiguration, this.lifecycle); ++ } ++ ++ public LevelSettings withLifecycle(com.mojang.serialization.Lifecycle lifecycle) { ++ return new LevelSettings(this.levelName, this.gameType, this.hardcore, this.difficulty, this.allowCommands, this.gameRules, this.dataConfiguration, lifecycle); ++ } ++ ++ public com.mojang.serialization.Lifecycle getLifecycle() { ++ return this.lifecycle; + } } diff --git a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch index 706b180504..e4d352c355 100644 --- a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch @@ -1,86 +1,64 @@ --- a/net/minecraft/world/level/NaturalSpawner.java +++ b/net/minecraft/world/level/NaturalSpawner.java -@@ -48,6 +_,7 @@ - import net.minecraft.world.phys.Vec3; - import org.slf4j.Logger; - -+// TODO: ForgeHooks.canEntitySpawn - public final class NaturalSpawner { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final int MIN_SPAWN_DISTANCE = 24; -@@ -74,7 +_,7 @@ +@@ -67,7 +_,7 @@ + continue; } - } -- MobCategory mobcategory = entity.getType().getCategory(); -+ MobCategory mobcategory = entity.getClassification(true); - if (mobcategory != MobCategory.MISC) { - BlockPos blockpos = entity.blockPosition(); - p_186527_.query(ChunkPos.asLong(blockpos), (p_275163_) -> { -@@ -177,7 +_,7 @@ - ++l1; - p_47040_.addFreshEntityWithPassengers(mob); - p_47044_.run(mob, p_47041_); -- if (j >= mob.getMaxSpawnClusterSize()) { -+ if (j >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { - return; - } +- MobCategory mobcategory = entity.getType().getCategory(); ++ MobCategory mobcategory = entity.getClassification(true); + if (mobcategory != MobCategory.MISC) { + BlockPos blockpos = entity.blockPosition(); + p_186527_.query(ChunkPos.asLong(blockpos), p_275163_ -> { +@@ -187,7 +_,7 @@ + l1++; + p_47040_.addFreshEntityWithPassengers(mob); + p_47044_.run(mob, p_47041_); +- if (j >= mob.getMaxSpawnClusterSize()) { ++ if (j >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { + return; + } -@@ -244,7 +_,7 @@ - if (p_46994_ > (double)(p_46993_.getType().getCategory().getDespawnDistance() * p_46993_.getType().getCategory().getDespawnDistance()) && p_46993_.removeWhenFarAway(p_46994_)) { - return false; - } else { -- return p_46993_.checkSpawnRules(p_46992_, MobSpawnType.NATURAL) && p_46993_.checkSpawnObstruction(p_46992_); -+ return net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(p_46993_, p_46992_, MobSpawnType.NATURAL); - } - } +@@ -260,7 +_,7 @@ + private static boolean isValidPositionForMob(ServerLevel p_46992_, Mob p_46993_, double p_46994_) { + return p_46994_ > (double)(p_46993_.getType().getCategory().getDespawnDistance() * p_46993_.getType().getCategory().getDespawnDistance()) && p_46993_.removeWhenFarAway(p_46994_) + ? false +- : p_46993_.checkSpawnRules(p_46992_, MobSpawnType.NATURAL) && p_46993_.checkSpawnObstruction(p_46992_); ++ : net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(p_46993_, p_46992_, MobSpawnType.NATURAL); + } -@@ -258,7 +_,8 @@ - } + private static Optional getRandomSpawnMobAt( +@@ -291,9 +_,13 @@ + BlockPos p_220448_, + @Nullable Holder p_220449_ + ) { +- return isInNetherFortressBounds(p_220448_, p_220444_, p_220447_, p_220445_) +- ? NetherFortressStructure.FORTRESS_ENEMIES +- : p_220446_.getMobsAt(p_220449_ != null ? p_220449_ : p_220444_.getBiome(p_220448_), p_220445_, p_220447_, p_220448_); ++ // Forge: Add in potential spawns, and replace hardcoded nether fortress mob list ++ return net.minecraftforge.event.ForgeEventFactory.getPotentialSpawns(p_220444_, p_220447_, p_220448_, ++ isInNetherFortressBounds(p_220448_, p_220444_, p_220447_, p_220445_) ++ ? p_220445_.registryAccess().registryOrThrow(Registries.STRUCTURE).getOrThrow(BuiltinStructures.FORTRESS) ++ .spawnOverrides().get(MobCategory.MONSTER).spawns() ++ : p_220446_.getMobsAt(p_220449_ != null ? p_220449_ : p_220444_.getBiome(p_220448_), p_220445_, p_220447_, p_220448_) ++ ); + } - private static WeightedRandomList mobsAt(ServerLevel p_220444_, StructureManager p_220445_, ChunkGenerator p_220446_, MobCategory p_220447_, BlockPos p_220448_, @Nullable Holder p_220449_) { -- return isInNetherFortressBounds(p_220448_, p_220444_, p_220447_, p_220445_) ? NetherFortressStructure.FORTRESS_ENEMIES : p_220446_.getMobsAt(p_220449_ != null ? p_220449_ : p_220444_.getBiome(p_220448_), p_220445_, p_220447_, p_220448_); -+ // Forge: Add in potential spawns, and replace hardcoded nether fortress mob list -+ return net.minecraftforge.event.ForgeEventFactory.getPotentialSpawns(p_220444_, p_220447_, p_220448_, isInNetherFortressBounds(p_220448_, p_220444_, p_220447_, p_220445_) ? p_220445_.registryAccess().registryOrThrow(Registries.STRUCTURE).getOrThrow(BuiltinStructures.FORTRESS).spawnOverrides().get(MobCategory.MONSTER).spawns() : p_220446_.getMobsAt(p_220449_ != null ? p_220449_ : p_220444_.getBiome(p_220448_), p_220445_, p_220447_, p_220448_)); - } + public static boolean isInNetherFortressBounds(BlockPos p_220456_, ServerLevel p_220457_, MobCategory p_220458_, StructureManager p_220459_) { +@@ -379,7 +_,7 @@ + } - public static boolean isInNetherFortressBounds(BlockPos p_220456_, ServerLevel p_220457_, MobCategory p_220458_, StructureManager p_220459_) { -@@ -297,6 +_,13 @@ - if (p_47052_ == SpawnPlacements.Type.NO_RESTRICTIONS) { - return true; - } else if (p_47055_ != null && p_47053_.getWorldBorder().isWithinBounds(p_47054_)) { -+ return p_47052_.canSpawnAt(p_47053_, p_47054_, p_47055_); -+ } -+ return false; -+ } -+ -+ public static boolean canSpawnAtBody(SpawnPlacements.Type p_47052_, LevelReader p_47053_, BlockPos p_47054_, @Nullable EntityType p_47055_) { -+ { - BlockState blockstate = p_47053_.getBlockState(p_47054_); - FluidState fluidstate = p_47053_.getFluidState(p_47054_); - BlockPos blockpos = p_47054_.above(); -@@ -309,14 +_,12 @@ - case ON_GROUND: - default: - BlockState blockstate1 = p_47053_.getBlockState(blockpos1); -- if (!blockstate1.isValidSpawn(p_47053_, blockpos1, p_47055_)) { -+ if (!blockstate1.isValidSpawn(p_47053_, blockpos1, p_47052_, p_47055_)) { - return false; - } else { - return isValidEmptySpawnBlock(p_47053_, p_47054_, blockstate, fluidstate, p_47055_) && isValidEmptySpawnBlock(p_47053_, blockpos, p_47053_.getBlockState(blockpos), p_47053_.getFluidState(blockpos), p_47055_); - } - } -- } else { -- return false; - } - } + entity.moveTo(d0, (double)blockpos.getY(), d1, p_220454_.nextFloat() * 360.0F, 0.0F); +- if (entity instanceof Mob mob && mob.checkSpawnRules(p_220451_, MobSpawnType.CHUNK_GENERATION) && mob.checkSpawnObstruction(p_220451_)) { ++ if (entity instanceof Mob mob && net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, p_220451_, MobSpawnType.CHUNK_GENERATION)) { + spawngroupdata = mob.finalizeSpawn(p_220451_, p_220451_.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.CHUNK_GENERATION, spawngroupdata); + p_220451_.addFreshEntityWithPassengers(mob); + flag = true; +@@ -483,7 +_,7 @@ + } -@@ -366,7 +_,7 @@ - entity.moveTo(d0, (double)blockpos.getY(), d1, p_220454_.nextFloat() * 360.0F, 0.0F); - if (entity instanceof Mob) { - Mob mob = (Mob)entity; -- if (mob.checkSpawnRules(p_220451_, MobSpawnType.CHUNK_GENERATION) && mob.checkSpawnObstruction(p_220451_)) { -+ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, p_220451_, MobSpawnType.CHUNK_GENERATION)) { - spawngroupdata = mob.finalizeSpawn(p_220451_, p_220451_.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.CHUNK_GENERATION, spawngroupdata, (CompoundTag)null); - p_220451_.addFreshEntityWithPassengers(mob); - flag = true; + this.spawnPotential.addCharge(blockpos, d0); +- MobCategory mobcategory = entitytype.getCategory(); ++ MobCategory mobcategory = p_47132_.getClassification(true); + this.mobCategoryCounts.addTo(mobcategory, 1); + this.localMobCapCalculator.addMob(new ChunkPos(blockpos), mobcategory); + } diff --git a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch index c950cff113..610631297d 100644 --- a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch +++ b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/SignalGetter.java +++ b/net/minecraft/world/level/SignalGetter.java @@ -65,7 +_,7 @@ - default int getSignal(BlockPos p_277961_, Direction p_277351_) { - BlockState blockstate = this.getBlockState(p_277961_); - int i = blockstate.getSignal(this, p_277961_, p_277351_); -- return blockstate.isRedstoneConductor(this, p_277961_) ? Math.max(i, this.getDirectSignalTo(p_277961_)) : i; -+ return blockstate.shouldCheckWeakPower(this, p_277961_, p_277351_) ? Math.max(i, this.getDirectSignalTo(p_277961_)) : i; - } + default int getSignal(BlockPos p_277961_, Direction p_277351_) { + BlockState blockstate = this.getBlockState(p_277961_); + int i = blockstate.getSignal(this, p_277961_, p_277351_); +- return blockstate.isRedstoneConductor(this, p_277961_) ? Math.max(i, this.getDirectSignalTo(p_277961_)) : i; ++ return blockstate.shouldCheckWeakPower(this, p_277961_, p_277351_) ? Math.max(i, this.getDirectSignalTo(p_277961_)) : i; + } - default boolean hasNeighborSignal(BlockPos p_277626_) { + default boolean hasNeighborSignal(BlockPos p_277626_) { diff --git a/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch b/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch index eab5cf9200..463c645f61 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch @@ -1,75 +1,76 @@ --- a/net/minecraft/world/level/biome/Biome.java +++ b/net/minecraft/world/level/biome/Biome.java -@@ -34,9 +_,9 @@ +@@ -35,8 +_,8 @@ public final class Biome { - public static final Codec DIRECT_CODEC = RecordCodecBuilder.create((p_220544_) -> { - return p_220544_.group(Biome.ClimateSettings.CODEC.forGetter((p_151717_) -> { -- return p_151717_.climateSettings; -+ return p_151717_.modifiableBiomeInfo().getOriginalBiomeInfo().climateSettings(); // FORGE: Patch codec to ignore field redirect coremods. - }), BiomeSpecialEffects.CODEC.fieldOf("effects").forGetter((p_220550_) -> { -- return p_220550_.specialEffects; -+ return p_220550_.modifiableBiomeInfo().getOriginalBiomeInfo().effects(); // FORGE: Patch codec to ignore field redirect coremods. - }), BiomeGenerationSettings.CODEC.forGetter((p_220548_) -> { - return p_220548_.generationSettings; - }), MobSpawnSettings.CODEC.forGetter((p_220546_) -> { -@@ -82,6 +_,7 @@ - this.generationSettings = p_220532_; - this.mobSettings = p_220533_; - this.specialEffects = p_220531_; -+ this.modifiableBiomeInfo = new net.minecraftforge.common.world.ModifiableBiomeInfo(new net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo(p_220530_, p_220531_, p_220532_, p_220533_)); // FORGE: cache original biome info on construction so we can bypass our field read coremods where necessary - } + public static final Codec DIRECT_CODEC = RecordCodecBuilder.create( + p_220544_ -> p_220544_.group( +- Biome.ClimateSettings.CODEC.forGetter(p_151717_ -> p_151717_.climateSettings), +- BiomeSpecialEffects.CODEC.fieldOf("effects").forGetter(p_220550_ -> p_220550_.specialEffects), ++ Biome.ClimateSettings.CODEC.forGetter(p_151717_ -> p_151717_.modifiableBiomeInfo().getOriginalBiomeInfo().climateSettings()), // FORGE: Patch codec to ignore field redirect coremods. ++ BiomeSpecialEffects.CODEC.fieldOf("effects").forGetter(p_220550_ -> p_220550_.modifiableBiomeInfo().getOriginalBiomeInfo().effects()), // FORGE: Patch codec to ignore field redirect coremods. + BiomeGenerationSettings.CODEC.forGetter(p_220548_ -> p_220548_.generationSettings), + MobSpawnSettings.CODEC.forGetter(p_220546_ -> p_220546_.mobSettings) + ) +@@ -71,12 +_,14 @@ + long2floatlinkedopenhashmap.defaultReturnValue(Float.NaN); + return long2floatlinkedopenhashmap; + })); ++ private final net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo; - public int getSkyColor() { -@@ -89,7 +_,7 @@ - } + Biome(Biome.ClimateSettings p_220530_, BiomeSpecialEffects p_220531_, BiomeGenerationSettings p_220532_, MobSpawnSettings p_220533_) { + this.climateSettings = p_220530_; + this.generationSettings = p_220532_; + this.mobSettings = p_220533_; + this.specialEffects = p_220531_; ++ this.modifiableBiomeInfo = new net.minecraftforge.common.world.ModifiableBiomeInfo(new net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo(p_220530_, p_220531_, p_220532_, p_220533_)); // FORGE: cache original biome info on construction so we can bypass our field read coremods where necessary + } - public MobSpawnSettings getMobSettings() { -- return this.mobSettings; -+ return this.modifiableBiomeInfo().get().mobSpawnSettings(); - } + public int getSkyColor() { +@@ -84,7 +_,7 @@ + } - public boolean hasPrecipitation() { -@@ -188,7 +_,7 @@ - } + public MobSpawnSettings getMobSettings() { +- return this.mobSettings; ++ return this.modifiableBiomeInfo().get().mobSpawnSettings(); + } - public BiomeGenerationSettings getGenerationSettings() { -- return this.generationSettings; -+ return this.modifiableBiomeInfo().get().generationSettings(); - } + public boolean hasPrecipitation() { +@@ -189,7 +_,7 @@ + } - public int getFogColor() { -@@ -384,4 +_,34 @@ - return this.name; - } - } + public BiomeGenerationSettings getGenerationSettings() { +- return this.generationSettings; ++ return this.modifiableBiomeInfo().get().generationSettings(); + } + + public int getFogColor() { +@@ -251,6 +_,29 @@ + + public Optional getBackgroundMusic() { + return this.specialEffects.getBackgroundMusic(); ++ } + -+ // FORGE START ++ /** ++ * {@return Cache of original biome data and biome data modified by biome modifiers} ++ * Modified biome data is set by server after datapacks and serverconfigs load. ++ * Climate and effects field reads are coremodded to redirect to this. ++ **/ ++ public net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo() { ++ return this.modifiableBiomeInfo; ++ } + -+ private final net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo; ++ /** ++ * {@return The biome's climate settings, with modifications if called after modifiers are applied in server init.} ++ */ ++ public ClimateSettings getModifiedClimateSettings() { ++ return this.modifiableBiomeInfo().get().climateSettings(); ++ } + -+ /** -+ * {@return Cache of original biome data and biome data modified by biome modifiers} -+ * Modified biome data is set by server after datapacks and serverconfigs load. -+ * Climate and effects field reads are coremodded to redirect to this. -+ **/ -+ public net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo() -+ { -+ return this.modifiableBiomeInfo; -+ } -+ -+ /** -+ * {@return The biome's climate settings, with modifications if called after modifiers are applied in server init.} -+ */ -+ public ClimateSettings getModifiedClimateSettings() { -+ return this.modifiableBiomeInfo().get().climateSettings(); -+ } -+ -+ /** -+ * {@return The biome's client effects, with modifications if called after modifiers are applied in server init.} -+ */ -+ public BiomeSpecialEffects getModifiedSpecialEffects() { -+ return this.modifiableBiomeInfo().get().effects(); -+ } -+ -+ // FORGE END - } ++ /** ++ * {@return The biome's client effects, with modifications if called after modifiers are applied in server init.} ++ */ ++ public BiomeSpecialEffects getModifiedSpecialEffects() { ++ return this.modifiableBiomeInfo().get().effects(); + } + + public static class BiomeBuilder { diff --git a/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch b/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch index 1099693966..6d5908f541 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch @@ -1,26 +1,29 @@ --- a/net/minecraft/world/level/biome/BiomeGenerationSettings.java +++ b/net/minecraft/world/level/biome/BiomeGenerationSettings.java -@@ -39,6 +_,7 @@ - })).apply(p_186655_, BiomeGenerationSettings::new); - }); - private final Map>> carvers; -+ private final java.util.Set carversView; - private final List> features; - private final Supplier>> flowerFeatures; - private final Supplier> featureSet; -@@ -54,10 +_,15 @@ - this.featureSet = Suppliers.memoize(() -> { - return p_186651_.stream().flatMap(HolderSet::stream).map(Holder::value).collect(Collectors.toSet()); - }); -+ this.carversView = java.util.Collections.unmodifiableSet(carvers.keySet()); - } +@@ -50,6 +_,7 @@ + .apply(p_186655_, BiomeGenerationSettings::new) + ); + private final Map>> carvers; ++ private final java.util.Set carversView; + private final List> features; + private final Supplier>> flowerFeatures; + private final Supplier> featureSet; +@@ -66,6 +_,7 @@ + .collect(ImmutableList.toImmutableList()) + ); + this.featureSet = Suppliers.memoize(() -> p_186651_.stream().flatMap(HolderSet::stream).map(Holder::value).collect(Collectors.toSet())); ++ this.carversView = java.util.Collections.unmodifiableSet(carvers.keySet()); + } - public Iterable>> getCarvers(GenerationStep.Carving p_204188_) { - return Objects.requireNonNullElseGet(this.carvers.get(p_204188_), List::of); -+ } + public Iterable>> getCarvers(GenerationStep.Carving p_204188_) { +@@ -82,6 +_,10 @@ + + public boolean hasFeature(PlacedFeature p_186659_) { + return this.featureSet.get().contains(p_186659_); ++ } + -+ public java.util.Set getCarvingStages() { -+ return this.carversView; - } ++ public java.util.Set getCarvingStages() { ++ return this.carversView; + } - public List> getFlowerFeatures() { + public static class Builder extends BiomeGenerationSettings.PlainBuilder { diff --git a/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch b/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch index e5d542e82c..84809c8087 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch @@ -1,51 +1,62 @@ --- a/net/minecraft/world/level/biome/BiomeSpecialEffects.java +++ b/net/minecraft/world/level/biome/BiomeSpecialEffects.java -@@ -201,7 +_,7 @@ - } - } +@@ -212,7 +_,7 @@ + } + } -- public static enum GrassColorModifier implements StringRepresentable { -+ public static enum GrassColorModifier implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { - NONE("none") { - public int modifyColor(double p_48081_, double p_48082_, int p_48083_) { - return p_48083_; -@@ -220,14 +_,37 @@ - }; +- public static enum GrassColorModifier implements StringRepresentable { ++ public static enum GrassColorModifier implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { + NONE("none") { + @Override + public int modifyColor(double p_48081_, double p_48082_, int p_48083_) { +@@ -234,11 +_,16 @@ + }; - private final String name; -- public static final Codec CODEC = StringRepresentable.fromEnum(BiomeSpecialEffects.GrassColorModifier::values); -+ public static final Codec CODEC = net.minecraftforge.common.IExtensibleEnum.createCodecForExtensibleEnum(BiomeSpecialEffects.GrassColorModifier::values, BiomeSpecialEffects.GrassColorModifier::byName); -+ private static final java.util.Map BY_NAME = java.util.Arrays.stream(values()).collect(java.util.stream.Collectors.toMap(BiomeSpecialEffects.GrassColorModifier::getName, grassColorModifier -> grassColorModifier)); + private final String name; +- public static final Codec CODEC = StringRepresentable.fromEnum( +- BiomeSpecialEffects.GrassColorModifier::values ++ public static final Codec CODEC = net.minecraftforge.common.IExtensibleEnum.createCodecForExtensibleEnum( ++ BiomeSpecialEffects.GrassColorModifier::values, ++ BiomeSpecialEffects.GrassColorModifier::byName + ); ++ private static final java.util.Map BY_NAME = java.util.Arrays.stream(values()).collect(java.util.stream.Collectors.toMap(BiomeSpecialEffects.GrassColorModifier::getName, grassColorModifier -> grassColorModifier)); ++ private ColorModifier delegate; -- public abstract int modifyColor(double p_48065_, double p_48066_, int p_48067_); -+ public int modifyColor(double p_48065_, double p_48066_, int p_48067_) { -+ return delegate.modifyGrassColor(p_48065_, p_48066_, p_48067_); -+ } +- public abstract int modifyColor(double p_48065_, double p_48066_, int p_48067_); ++ public int modifyColor(double p_48065_, double p_48066_, int p_48067_) { ++ return delegate.modifyGrassColor(p_48065_, p_48066_, p_48067_); ++ } - GrassColorModifier(String p_48058_) { - this.name = p_48058_; - } - -+ private ColorModifier delegate; -+ private GrassColorModifier(String name, ColorModifier delegate) { -+ this(name); -+ this.delegate = delegate; -+ } -+ public static GrassColorModifier create(String name, String id, ColorModifier delegate) { -+ throw new IllegalStateException("Enum not extended"); -+ } -+ @Override -+ public void init() { -+ BY_NAME.put(this.getName(), this); -+ } -+ // Forge: Access enum members by name -+ public static BiomeSpecialEffects.GrassColorModifier byName(String name) { -+ return BY_NAME.get(name); -+ } -+ @FunctionalInterface -+ public interface ColorModifier { -+ int modifyGrassColor(double x, double z, int color); -+ } - public String getName() { - return this.name; - } + GrassColorModifier(final String p_48058_) { + this.name = p_48058_; +@@ -251,6 +_,30 @@ + @Override + public String getSerializedName() { + return this.name; ++ } ++ ++ private GrassColorModifier(String name, ColorModifier delegate) { ++ this(name); ++ this.delegate = delegate; ++ } ++ ++ public static GrassColorModifier create(String name, String id, ColorModifier delegate) { ++ throw new IllegalStateException("Enum not extended"); ++ } ++ ++ @Override ++ public void init() { ++ BY_NAME.put(this.getName(), this); ++ } ++ ++ // Forge: Access enum members by name ++ public static BiomeSpecialEffects.GrassColorModifier byName(String name) { ++ return BY_NAME.get(name); ++ } ++ ++ @FunctionalInterface ++ public interface ColorModifier { ++ int modifyGrassColor(double x, double z, int color); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch b/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch index d6b9ec3071..3815e1afc1 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch @@ -1,35 +1,35 @@ --- a/net/minecraft/world/level/biome/MobSpawnSettings.java +++ b/net/minecraft/world/level/biome/MobSpawnSettings.java -@@ -40,20 +_,32 @@ - private final float creatureGenerationProbability; - private final Map> spawners; - private final Map, MobSpawnSettings.MobSpawnCost> mobSpawnCosts; -+ private final java.util.Set typesView; -+ private final java.util.Set> costView; +@@ -49,6 +_,8 @@ + private final float creatureGenerationProbability; + private final Map> spawners; + private final Map, MobSpawnSettings.MobSpawnCost> mobSpawnCosts; ++ private final java.util.Set typesView; ++ private final java.util.Set> costView; - MobSpawnSettings(float p_196689_, Map> p_196690_, Map, MobSpawnSettings.MobSpawnCost> p_196691_) { - this.creatureGenerationProbability = p_196689_; - this.spawners = ImmutableMap.copyOf(p_196690_); - this.mobSpawnCosts = ImmutableMap.copyOf(p_196691_); -+ this.typesView = java.util.Collections.unmodifiableSet(this.spawners.keySet()); -+ this.costView = java.util.Collections.unmodifiableSet(this.mobSpawnCosts.keySet()); - } + MobSpawnSettings( + float p_196689_, +@@ -58,6 +_,8 @@ + this.creatureGenerationProbability = p_196689_; + this.spawners = ImmutableMap.copyOf(p_196690_); + this.mobSpawnCosts = ImmutableMap.copyOf(p_196691_); ++ this.typesView = java.util.Collections.unmodifiableSet(this.spawners.keySet()); ++ this.costView = java.util.Collections.unmodifiableSet(this.mobSpawnCosts.keySet()); + } - public WeightedRandomList getMobs(MobCategory p_151799_) { - return this.spawners.getOrDefault(p_151799_, EMPTY_MOB_LIST); - } + public WeightedRandomList getMobs(MobCategory p_151799_) { +@@ -71,6 +_,14 @@ -+ public java.util.Set getSpawnerTypes() { -+ return this.typesView; -+ } + public float getCreatureProbability() { + return this.creatureGenerationProbability; ++ } + - @Nullable - public MobSpawnSettings.MobSpawnCost getMobSpawnCost(EntityType p_48346_) { - return this.mobSpawnCosts.get(p_48346_); -+ } ++ public java.util.Set getSpawnerTypes() { ++ return this.typesView; ++ } + -+ public java.util.Set> getEntityTypes() { -+ return this.costView; - } ++ public java.util.Set> getEntityTypes() { ++ return this.costView; + } - public float getCreatureProbability() { + public static class Builder { diff --git a/patches/minecraft/net/minecraft/world/level/block/BambooSaplingBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BambooSaplingBlock.java.patch index 76b61675ca..7b2087683b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BambooSaplingBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BambooSaplingBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/BambooSaplingBlock.java +++ b/net/minecraft/world/level/block/BambooSaplingBlock.java -@@ -79,7 +_,7 @@ - } +@@ -88,7 +_,7 @@ - public float getDestroyProgress(BlockState p_48981_, Player p_48982_, BlockGetter p_48983_, BlockPos p_48984_) { -- return p_48982_.getMainHandItem().getItem() instanceof SwordItem ? 1.0F : super.getDestroyProgress(p_48981_, p_48982_, p_48983_, p_48984_); -+ return p_48982_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(p_48981_, p_48982_, p_48983_, p_48984_); - } + @Override + protected float getDestroyProgress(BlockState p_48981_, Player p_48982_, BlockGetter p_48983_, BlockPos p_48984_) { +- return p_48982_.getMainHandItem().getItem() instanceof SwordItem ? 1.0F : super.getDestroyProgress(p_48981_, p_48982_, p_48983_, p_48984_); ++ return p_48982_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(p_48981_, p_48982_, p_48983_, p_48984_); + } - protected void growBamboo(Level p_48973_, BlockPos p_48974_) { + protected void growBamboo(Level p_48973_, BlockPos p_48974_) { diff --git a/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch index ff3e8d9a15..d5daf07dae 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch @@ -6,42 +6,42 @@ -public class BambooStalkBlock extends Block implements BonemealableBlock { +public class BambooStalkBlock extends Block implements BonemealableBlock, net.minecraftforge.common.IPlantable { - public static final MapCodec CODEC = simpleCodec(BambooStalkBlock::new); - protected static final float SMALL_LEAVES_AABB_OFFSET = 3.0F; - protected static final float LARGE_LEAVES_AABB_OFFSET = 5.0F; -@@ -116,10 +_,11 @@ - - public void randomTick(BlockState p_261931_, ServerLevel p_261751_, BlockPos p_261616_, RandomSource p_261766_) { - if (p_261931_.getValue(STAGE) == 0) { -- if (p_261766_.nextInt(3) == 0 && p_261751_.isEmptyBlock(p_261616_.above()) && p_261751_.getRawBrightness(p_261616_.above(), 0) >= 9) { -+ if (p_261751_.isEmptyBlock(p_261616_.above()) && p_261751_.getRawBrightness(p_261616_.above(), 0) >= 9) { - int i = this.getHeightBelowUpToMax(p_261751_, p_261616_) + 1; -- if (i < 16) { -+ if (i < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_261751_, p_261616_, p_261931_, p_261766_.nextInt(3) == 0)) { - this.growBamboo(p_261931_, p_261751_, p_261616_, p_261766_, i); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_261751_, p_261616_, p_261931_); + public static final MapCodec CODEC = simpleCodec(BambooStalkBlock::new); + protected static final float SMALL_LEAVES_AABB_OFFSET = 3.0F; + protected static final float LARGE_LEAVES_AABB_OFFSET = 5.0F; +@@ -130,10 +_,12 @@ + @Override + protected void randomTick(BlockState p_261931_, ServerLevel p_261751_, BlockPos p_261616_, RandomSource p_261766_) { + if (p_261931_.getValue(STAGE) == 0) { +- if (p_261766_.nextInt(3) == 0 && p_261751_.isEmptyBlock(p_261616_.above()) && p_261751_.getRawBrightness(p_261616_.above(), 0) >= 9) { ++ boolean vanilla = p_261766_.nextInt(3) == 0; ++ if (p_261751_.isEmptyBlock(p_261616_.above()) && p_261751_.getRawBrightness(p_261616_.above(), 0) >= 9) { + int i = this.getHeightBelowUpToMax(p_261751_, p_261616_) + 1; +- if (i < 16) { ++ if (i < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_261751_, p_261616_, p_261931_, vanilla)) { + this.growBamboo(p_261931_, p_261751_, p_261616_, p_261766_, i); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_261751_, p_261616_, p_261931_); + } } - } + } +@@ -193,7 +_,7 @@ -@@ -173,7 +_,7 @@ - } + @Override + protected float getDestroyProgress(BlockState p_261691_, Player p_262171_, BlockGetter p_261621_, BlockPos p_261500_) { +- return p_262171_.getMainHandItem().getItem() instanceof SwordItem ? 1.0F : super.getDestroyProgress(p_261691_, p_262171_, p_261621_, p_261500_); ++ return p_262171_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(p_261691_, p_262171_, p_261621_, p_261500_); + } - public float getDestroyProgress(BlockState p_261691_, Player p_262171_, BlockGetter p_261621_, BlockPos p_261500_) { -- return p_262171_.getMainHandItem().getItem() instanceof SwordItem ? 1.0F : super.getDestroyProgress(p_261691_, p_262171_, p_261621_, p_261500_); -+ return p_262171_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(p_261691_, p_262171_, p_261621_, p_261500_); - } + protected void growBamboo(BlockState p_261855_, Level p_262076_, BlockPos p_262109_, RandomSource p_261633_, int p_261759_) { +@@ -240,5 +_,11 @@ + } - protected void growBamboo(BlockState p_261855_, Level p_262076_, BlockPos p_262109_, RandomSource p_261633_, int p_261759_) { -@@ -214,5 +_,12 @@ - } - - return i; -+ } + return i; ++ } + -+ @Override -+ public BlockState getPlant(BlockGetter world, BlockPos pos) { -+ BlockState state = world.getBlockState(pos); -+ if (state.getBlock() != this) return defaultBlockState(); -+ return state; - } ++ @Override ++ public BlockState getPlant(BlockGetter world, BlockPos pos) { ++ BlockState state = world.getBlockState(pos); ++ return state.getBlock() == this ? state : defaultBlockState(); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch index 57e659f018..9dc40ef6dd 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/level/block/BaseFireBlock.java +++ b/net/minecraft/world/level/block/BaseFireBlock.java -@@ -127,6 +_,7 @@ - if (!p_49282_.is(p_49279_.getBlock())) { - if (inPortalDimension(p_49280_)) { - Optional optional = PortalShape.findEmptyPortalShape(p_49280_, p_49281_, Direction.Axis.X); -+ optional = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(p_49280_, p_49281_, optional); - if (optional.isPresent()) { - optional.get().createPortalBlocks(); - return; -@@ -172,7 +_,7 @@ - boolean flag = false; +@@ -141,6 +_,7 @@ + if (!p_49282_.is(p_49279_.getBlock())) { + if (inPortalDimension(p_49280_)) { + Optional optional = PortalShape.findEmptyPortalShape(p_49280_, p_49281_, Direction.Axis.X); ++ optional = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(p_49280_, p_49281_, optional); + if (optional.isPresent()) { + optional.get().createPortalBlocks(); + return; +@@ -183,7 +_,7 @@ + boolean flag = false; - for(Direction direction : Direction.values()) { -- if (p_49270_.getBlockState(blockpos$mutableblockpos.set(p_49271_).move(direction)).is(Blocks.OBSIDIAN)) { -+ if (p_49270_.getBlockState(blockpos$mutableblockpos.set(p_49271_).move(direction)).isPortalFrame(p_49270_, blockpos$mutableblockpos)) { - flag = true; - break; - } + for (Direction direction : Direction.values()) { +- if (p_49270_.getBlockState(blockpos$mutableblockpos.set(p_49271_).move(direction)).is(Blocks.OBSIDIAN)) { ++ if (p_49270_.getBlockState(blockpos$mutableblockpos.set(p_49271_).move(direction)).isPortalFrame(p_49270_, blockpos$mutableblockpos)) { + flag = true; + break; + } diff --git a/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch index de14a5939f..0b211d3e56 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch @@ -6,60 +6,60 @@ -public abstract class BaseRailBlock extends Block implements SimpleWaterloggedBlock { +public abstract class BaseRailBlock extends Block implements SimpleWaterloggedBlock, net.minecraftforge.common.extensions.IForgeBaseRailBlock { - protected static final VoxelShape FLAT_AABB = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D); - protected static final VoxelShape HALF_BLOCK_AABB = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D); - public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; -@@ -47,6 +_,7 @@ + protected static final VoxelShape FLAT_AABB = Block.box(0.0, 0.0, 0.0, 16.0, 2.0, 16.0); + protected static final VoxelShape HALF_BLOCK_AABB = Block.box(0.0, 0.0, 0.0, 16.0, 8.0, 16.0); + public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; +@@ -49,6 +_,7 @@ + @Override + protected VoxelShape getShape(BlockState p_49403_, BlockGetter p_49404_, BlockPos p_49405_, CollisionContext p_49406_) { + RailShape railshape = p_49403_.is(this) ? p_49403_.getValue(this.getShapeProperty()) : null; ++ //RailShape railShape2 = p_49403_.is(this) ? getRailDirection(p_49403_, p_49404_, p_49405_, null) : null; // seems unused in old patch, should it be wired up or removed? -Paint_Ninja + return railshape != null && railshape.isAscending() ? HALF_BLOCK_AABB : FLAT_AABB; + } - public VoxelShape getShape(BlockState p_49403_, BlockGetter p_49404_, BlockPos p_49405_, CollisionContext p_49406_) { - RailShape railshape = p_49403_.is(this) ? p_49403_.getValue(this.getShapeProperty()) : null; -+ RailShape railShape2 = p_49403_.is(this) ? getRailDirection(p_49403_, p_49404_, p_49405_, null) : null; - return railshape != null && railshape.isAscending() ? HALF_BLOCK_AABB : FLAT_AABB; - } +@@ -76,7 +_,7 @@ + @Override + protected void neighborChanged(BlockState p_49377_, Level p_49378_, BlockPos p_49379_, Block p_49380_, BlockPos p_49381_, boolean p_49382_) { + if (!p_49378_.isClientSide && p_49378_.getBlockState(p_49379_).is(this)) { +- RailShape railshape = p_49377_.getValue(this.getShapeProperty()); ++ RailShape railshape = getRailDirection(p_49377_, p_49378_, p_49379_, null); + if (shouldBeRemoved(p_49379_, p_49378_, railshape)) { + dropResources(p_49377_, p_49378_, p_49379_); + p_49378_.removeBlock(p_49379_, p_49382_); +@@ -121,7 +_,7 @@ + protected void onRemove(BlockState p_49384_, Level p_49385_, BlockPos p_49386_, BlockState p_49387_, boolean p_49388_) { + if (!p_49388_) { + super.onRemove(p_49384_, p_49385_, p_49386_, p_49387_, p_49388_); +- if (p_49384_.getValue(this.getShapeProperty()).isAscending()) { ++ if (getRailDirection(p_49384_, p_49385_, p_49386_, null).isAscending()) { + p_49385_.updateNeighborsAt(p_49386_.above(), this); + } -@@ -71,7 +_,7 @@ +@@ -142,6 +_,11 @@ + return blockstate.setValue(this.getShapeProperty(), flag1 ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, Boolean.valueOf(flag)); + } - public void neighborChanged(BlockState p_49377_, Level p_49378_, BlockPos p_49379_, Block p_49380_, BlockPos p_49381_, boolean p_49382_) { - if (!p_49378_.isClientSide && p_49378_.getBlockState(p_49379_).is(this)) { -- RailShape railshape = p_49377_.getValue(this.getShapeProperty()); -+ RailShape railshape = getRailDirection(p_49377_, p_49378_, p_49379_, null); - if (shouldBeRemoved(p_49379_, p_49378_, railshape)) { - dropResources(p_49377_, p_49378_, p_49379_); - p_49378_.removeBlock(p_49379_, p_49382_); -@@ -116,7 +_,7 @@ - public void onRemove(BlockState p_49384_, Level p_49385_, BlockPos p_49386_, BlockState p_49387_, boolean p_49388_) { - if (!p_49388_) { - super.onRemove(p_49384_, p_49385_, p_49386_, p_49387_, p_49388_); -- if (p_49384_.getValue(this.getShapeProperty()).isAscending()) { -+ if (getRailDirection(p_49384_, p_49385_, p_49386_, null).isAscending()) { - p_49385_.updateNeighborsAt(p_49386_.above(), this); - } ++ /** ++ * @deprecated Forge: Use {@link BaseRailBlock#getRailDirection(BlockState, BlockGetter, BlockPos, net.minecraft.world.entity.vehicle.AbstractMinecart)} for enhanced ability. ++ * If you do change this property, be aware that other functions in this/subclasses may break as they can make assumptions about this property ++ */ ++ @Deprecated + public abstract Property getShapeProperty(); -@@ -137,6 +_,11 @@ - return blockstate.setValue(this.getShapeProperty(), flag1 ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, Boolean.valueOf(flag)); - } - -+ /** -+ * @deprecated Forge: Use {@link BaseRailBlock#getRailDirection(BlockState, BlockGetter, BlockPos, net.minecraft.world.entity.vehicle.AbstractMinecart)} for enhanced ability -+ * If you do change this property be aware that other functions in this/subclasses may break as they can make assumptions about this property -+ */ -+ @Deprecated - public abstract Property getShapeProperty(); - - public BlockState updateShape(BlockState p_152151_, Direction p_152152_, BlockState p_152153_, LevelAccessor p_152154_, BlockPos p_152155_, BlockPos p_152156_) { -@@ -149,5 +_,15 @@ - - public FluidState getFluidState(BlockState p_152158_) { - return p_152158_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_152158_); -+ } + @Override +@@ -158,5 +_,15 @@ + @Override + protected FluidState getFluidState(BlockState p_152158_) { + return p_152158_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_152158_); ++ } + -+ @Override -+ public boolean isFlexibleRail(BlockState state, BlockGetter world, BlockPos pos) { -+ return !this.isStraight; -+ } ++ @Override ++ public boolean isFlexibleRail(BlockState state, BlockGetter world, BlockPos pos) { ++ return !this.isStraight; ++ } + -+ @Override -+ public RailShape getRailDirection(BlockState state, BlockGetter world, BlockPos pos, @org.jetbrains.annotations.Nullable net.minecraft.world.entity.vehicle.AbstractMinecart cart) { -+ return state.getValue(getShapeProperty()); - } ++ @Override ++ public RailShape getRailDirection(BlockState state, BlockGetter world, BlockPos pos, @org.jetbrains.annotations.Nullable net.minecraft.world.entity.vehicle.AbstractMinecart cart) { ++ return state.getValue(getShapeProperty()); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch index 857665e418..d4e909cf35 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/BeehiveBlock.java +++ b/net/minecraft/world/level/block/BeehiveBlock.java -@@ -121,7 +_,7 @@ - boolean flag = false; - if (i >= 5) { - Item item = itemstack.getItem(); -- if (itemstack.is(Items.SHEARS)) { -+ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - p_49625_.playSound(p_49627_, p_49627_.getX(), p_49627_.getY(), p_49627_.getZ(), SoundEvents.BEEHIVE_SHEAR, SoundSource.BLOCKS, 1.0F, 1.0F); - dropHoneycomb(p_49625_, p_49626_); - itemstack.hurtAndBreak(1, p_49627_, (p_49571_) -> { +@@ -126,7 +_,7 @@ + boolean flag = false; + if (i >= 5) { + Item item = p_331014_.getItem(); +- if (p_331014_.is(Items.SHEARS)) { ++ if (p_331014_.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { + p_329187_.playSound( + p_336201_, p_336201_.getX(), p_336201_.getY(), p_336201_.getZ(), SoundEvents.BEEHIVE_SHEAR, SoundSource.BLOCKS, 1.0F, 1.0F + ); diff --git a/patches/minecraft/net/minecraft/world/level/block/Block.java.patch b/patches/minecraft/net/minecraft/world/level/block/Block.java.patch index 175c7d89e3..b4a64255cc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Block.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Block.java.patch @@ -6,191 +6,169 @@ -public class Block extends BlockBehaviour implements ItemLike { +public class Block extends BlockBehaviour implements ItemLike, net.minecraftforge.common.extensions.IForgeBlock { - public static final MapCodec CODEC = simpleCodec(Block::new); - private static final Logger LOGGER = LogUtils.getLogger(); - private final Holder.Reference builtInRegistryHolder = BuiltInRegistries.BLOCK.createIntrusiveHolder(this); -- public static final IdMapper BLOCK_STATE_REGISTRY = new IdMapper<>(); -+ @Deprecated //Forge: Do not use, use GameRegistry -+ public static final IdMapper BLOCK_STATE_REGISTRY = net.minecraftforge.registries.GameData.getBlockStateIDMap(); - private static final LoadingCache SHAPE_FULL_BLOCK_CACHE = CacheBuilder.newBuilder().maximumSize(512L).weakKeys().build(new CacheLoader() { - public Boolean load(VoxelShape p_49972_) { - return !Shapes.joinIsNotEmpty(Shapes.block(), p_49972_, BooleanOp.NOT_SAME); -@@ -182,7 +_,7 @@ - LOGGER.error("Block classes should end with Block and {} doesn't.", (Object)s); - } - } -- -+ initClient(); - } + public static final MapCodec CODEC = simpleCodec(Block::new); + private static final Logger LOGGER = LogUtils.getLogger(); + private final Holder.Reference builtInRegistryHolder = BuiltInRegistries.BLOCK.createIntrusiveHolder(this); +- public static final IdMapper BLOCK_STATE_REGISTRY = new IdMapper<>(); ++ @Deprecated //Forge: Do not use, use GameRegistry ++ public static final IdMapper BLOCK_STATE_REGISTRY = net.minecraftforge.registries.GameData.BlockCallbacks.getBlockStateIDMap(); + private static final LoadingCache SHAPE_FULL_BLOCK_CACHE = CacheBuilder.newBuilder() + .maximumSize(512L) + .weakKeys() +@@ -191,6 +_,7 @@ + LOGGER.error("Block classes should end with Block and {} doesn't.", s); + } + } ++ initClient(); + } - public static boolean isExceptionForConnection(BlockState p_152464_) { -@@ -197,6 +_,8 @@ - BlockState blockstate = p_152446_.getBlockState(p_152449_); - if (p_152445_.skipRendering(blockstate, p_152448_)) { - return false; -+ } else if (p_152445_.supportsExternalFaceHiding() && blockstate.hidesNeighborFace(p_152446_, p_152449_, p_152445_, p_152448_.getOpposite())) { -+ return false; - } else if (blockstate.canOcclude()) { - Block.BlockStatePairKey block$blockstatepairkey = new Block.BlockStatePairKey(p_152445_, blockstate, p_152448_); - Object2ByteLinkedOpenHashMap object2bytelinkedopenhashmap = OCCLUSION_CACHE.get(); -@@ -282,11 +_,14 @@ - } - - public static void dropResources(BlockState p_49882_, Level p_49883_, BlockPos p_49884_, @Nullable BlockEntity p_49885_, @Nullable Entity p_49886_, ItemStack p_49887_) { -+ dropResources(p_49882_, p_49883_, p_49884_, p_49885_, p_49886_, p_49887_, true); -+ } -+ public static void dropResources(BlockState p_49882_, Level p_49883_, BlockPos p_49884_, @Nullable BlockEntity p_49885_, @Nullable Entity p_49886_, ItemStack p_49887_, boolean dropXp) { - if (p_49883_ instanceof ServerLevel) { - getDrops(p_49882_, (ServerLevel)p_49883_, p_49884_, p_49885_, p_49886_, p_49887_).forEach((p_49944_) -> { - popResource(p_49883_, p_49884_, p_49944_); - }); -- p_49882_.spawnAfterBreak((ServerLevel)p_49883_, p_49884_, p_49887_, true); -+ p_49882_.spawnAfterBreak((ServerLevel)p_49883_, p_49884_, p_49887_, dropXp); - } - - } -@@ -319,7 +_,7 @@ - } - - private static void popResource(Level p_152441_, Supplier p_152442_, ItemStack p_152443_) { -- if (!p_152441_.isClientSide && !p_152443_.isEmpty() && p_152441_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) { -+ if (!p_152441_.isClientSide && !p_152443_.isEmpty() && p_152441_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS) && !p_152441_.restoringBlockSnapshots) { - ItemEntity itementity = p_152442_.get(); - itementity.setDefaultPickUpDelay(); - p_152441_.addFreshEntity(itementity); -@@ -327,12 +_,13 @@ - } - - public void popExperience(ServerLevel p_49806_, BlockPos p_49807_, int p_49808_) { -- if (p_49806_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) { -+ if (p_49806_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS) && !p_49806_.restoringBlockSnapshots) { - ExperienceOrb.award(p_49806_, Vec3.atCenterOf(p_49807_), p_49808_); - } - - } - -+ @Deprecated //Forge: Use more sensitive version - public float getExplosionResistance() { - return this.explosionResistance; - } -@@ -351,7 +_,8 @@ - public void playerDestroy(Level p_49827_, Player p_49828_, BlockPos p_49829_, BlockState p_49830_, @Nullable BlockEntity p_49831_, ItemStack p_49832_) { - p_49828_.awardStat(Stats.BLOCK_MINED.get(this)); - p_49828_.causeFoodExhaustion(0.005F); -- dropResources(p_49830_, p_49827_, p_49829_, p_49831_, p_49828_, p_49832_); -+ //Forge: Don't drop xp as part of the resources as it is handled by the patches in ServerPlayerGameMode#destroyBlock -+ dropResources(p_49830_, p_49827_, p_49829_, p_49831_, p_49828_, p_49832_, false); - } - - public void setPlacedBy(Level p_49847_, BlockPos p_49848_, BlockState p_49849_, @Nullable LivingEntity p_49850_, ItemStack p_49851_) { -@@ -379,8 +_,10 @@ - - public void updateEntityAfterFallOn(BlockGetter p_49821_, Entity p_49822_) { - p_49822_.setDeltaMovement(p_49822_.getDeltaMovement().multiply(1.0D, 0.0D, 1.0D)); -+ p_49822_.setDeltaMovement(p_49822_.getDeltaMovement().multiply(1.0D, 0.0D, 1.0D)); - } - -+ @Deprecated //Forge: Use more sensitive version - public ItemStack getCloneItemStack(LevelReader p_312699_, BlockPos p_49824_, BlockState p_49825_) { - return new ItemStack(this); - } -@@ -414,6 +_,7 @@ - public void handlePrecipitation(BlockState p_152450_, Level p_152451_, BlockPos p_152452_, Biome.Precipitation p_152453_) { - } - -+ @Deprecated //Forge: Use more sensitive version - public boolean dropFromExplosion(Explosion p_49826_) { - return true; - } -@@ -449,6 +_,7 @@ - return p_152456_.setValue(p_152457_, p_152455_.getValue(p_152457_)); - } - -+ @Deprecated //Forge: Use more sensitive version {@link IForgeBlockState#getSoundType(IWorldReader, BlockPos, Entity) } - public SoundType getSoundType(BlockState p_49963_) { - return this.soundType; - } -@@ -458,7 +_,7 @@ - this.item = Item.byBlock(this); - } - -- return this.item; -+ return net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(this.item).get(); // Forge: Vanilla caches the items, update with registry replacements. - } - - public boolean hasDynamicShape() { -@@ -479,6 +_,74 @@ - protected ImmutableMap getShapeForEachState(Function p_152459_) { - return this.stateDefinition.getPossibleStates().stream().collect(ImmutableMap.toImmutableMap(Function.identity(), p_152459_)); - } + public static boolean isExceptionForConnection(BlockState p_152464_) { +@@ -207,6 +_,8 @@ + BlockState blockstate = p_152446_.getBlockState(p_152449_); + if (p_152445_.skipRendering(blockstate, p_152448_)) { + return false; ++ } else if (p_152445_.supportsExternalFaceHiding() && blockstate.hidesNeighborFace(p_152446_, p_152449_, p_152445_, p_152448_.getOpposite())) { ++ return false; + } else if (blockstate.canOcclude()) { + Block.BlockStatePairKey block$blockstatepairkey = new Block.BlockStatePairKey(p_152445_, blockstate, p_152448_); + Object2ByteLinkedOpenHashMap object2bytelinkedopenhashmap = OCCLUSION_CACHE.get(); +@@ -295,9 +_,13 @@ + public static void dropResources( + BlockState p_49882_, Level p_49883_, BlockPos p_49884_, @Nullable BlockEntity p_49885_, @Nullable Entity p_49886_, ItemStack p_49887_ + ) { ++ dropResources(p_49882_, p_49883_, p_49884_, p_49885_, p_49886_, p_49887_, true); ++ } + -+ /* ======================================== FORGE START =====================================*/ -+ private Object renderProperties; -+ -+ /* -+ DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE -+ Call RenderProperties.get instead -+ */ -+ public Object getRenderPropertiesInternal() { -+ return renderProperties; -+ } -+ -+ private void initClient() { -+ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen -+ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { -+ initializeClient(properties -> { -+ if (properties == this) -+ throw new IllegalStateException("Don't extend IBlockRenderProperties in your block, use an anonymous class instead."); -+ this.renderProperties = properties; -+ }); -+ } -+ } -+ -+ public void initializeClient(java.util.function.Consumer consumer) { -+ } -+ -+ @Override -+ public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing, net.minecraftforge.common.IPlantable plantable) { -+ var plant = plantable.getPlant(world, pos.relative(facing)); -+ var type = plantable.getPlantType(world, pos.relative(facing)); -+ -+ if (plant.getBlock() == Blocks.CACTUS) -+ return state.is(Blocks.CACTUS) || state.is(BlockTags.SAND); -+ -+ if (plant.getBlock() == Blocks.SUGAR_CANE && this == Blocks.SUGAR_CANE) -+ return true; -+ -+ if (plantable instanceof BushBlock bush && bush.mayPlaceOn(state, world, pos)) -+ return true; -+ -+ if (net.minecraftforge.common.PlantType.DESERT.equals(type)) { -+ return state.is(BlockTags.SAND) || this == Blocks.TERRACOTTA || this instanceof GlazedTerracottaBlock; -+ } else if (net.minecraftforge.common.PlantType.NETHER.equals(type)) { -+ return this == Blocks.SOUL_SAND; -+ } else if (net.minecraftforge.common.PlantType.CROP.equals(type)) { -+ return state.is(Blocks.FARMLAND); -+ } else if (net.minecraftforge.common.PlantType.CAVE.equals(type)) { -+ return state.isFaceSturdy(world, pos, Direction.UP); -+ } else if (net.minecraftforge.common.PlantType.PLAINS.equals(type)) { -+ return state.is(BlockTags.DIRT) || this == Blocks.FARMLAND; -+ } else if (net.minecraftforge.common.PlantType.WATER.equals(type)) { -+ return (state.is(Blocks.WATER) || state.getBlock() instanceof IceBlock) && world.getFluidState(pos.relative(facing)).isEmpty(); -+ } else if (net.minecraftforge.common.PlantType.BEACH.equals(type)) { -+ boolean isBeach = state.is(BlockTags.DIRT) || state.is(BlockTags.SAND); -+ boolean hasWater = false; -+ for (Direction face : Direction.Plane.HORIZONTAL) { -+ BlockState adjacentBlockState = world.getBlockState(pos.relative(face)); -+ var adjacentFluidState = world.getFluidState(pos.relative(face)); -+ hasWater = hasWater || adjacentBlockState.is(Blocks.FROSTED_ICE) || adjacentFluidState.is(net.minecraft.tags.FluidTags.WATER); -+ if (hasWater) -+ break; //No point continuing. -+ } -+ return isBeach && hasWater; -+ } -+ return false; -+ } -+ -+ /* ========================================= FORGE END ======================================*/ ++ public static void dropResources(BlockState p_49882_, Level p_49883_, BlockPos p_49884_, @Nullable BlockEntity p_49885_, @Nullable Entity p_49886_, ItemStack p_49887_, boolean dropXp) { + if (p_49883_ instanceof ServerLevel) { + getDrops(p_49882_, (ServerLevel)p_49883_, p_49884_, p_49885_, p_49886_, p_49887_).forEach(p_49944_ -> popResource(p_49883_, p_49884_, p_49944_)); +- p_49882_.spawnAfterBreak((ServerLevel)p_49883_, p_49884_, p_49887_, true); ++ p_49882_.spawnAfterBreak((ServerLevel)p_49883_, p_49884_, p_49887_, dropXp); + } + } - /** @deprecated */ - @Deprecated +@@ -325,7 +_,7 @@ + } + + private static void popResource(Level p_152441_, Supplier p_152442_, ItemStack p_152443_) { +- if (!p_152441_.isClientSide && !p_152443_.isEmpty() && p_152441_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) { ++ if (!p_152441_.isClientSide && !p_152443_.isEmpty() && p_152441_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS) && !p_152441_.restoringBlockSnapshots) { + ItemEntity itementity = p_152442_.get(); + itementity.setDefaultPickUpDelay(); + p_152441_.addFreshEntity(itementity); +@@ -333,11 +_,12 @@ + } + + public void popExperience(ServerLevel p_49806_, BlockPos p_49807_, int p_49808_) { +- if (p_49806_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) { ++ if (p_49806_.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS) && !p_49806_.restoringBlockSnapshots) { + ExperienceOrb.award(p_49806_, Vec3.atCenterOf(p_49807_), p_49808_); + } + } + ++ @Deprecated //Forge: Use more sensitive version + public float getExplosionResistance() { + return this.explosionResistance; + } +@@ -356,7 +_,8 @@ + public void playerDestroy(Level p_49827_, Player p_49828_, BlockPos p_49829_, BlockState p_49830_, @Nullable BlockEntity p_49831_, ItemStack p_49832_) { + p_49828_.awardStat(Stats.BLOCK_MINED.get(this)); + p_49828_.causeFoodExhaustion(0.005F); +- dropResources(p_49830_, p_49827_, p_49829_, p_49831_, p_49828_, p_49832_); ++ //Forge: Don't drop xp as part of the resources as it is handled by the patches in ServerPlayerGameMode#destroyBlock ++ dropResources(p_49830_, p_49827_, p_49829_, p_49831_, p_49828_, p_49832_, false); + } + + public void setPlacedBy(Level p_49847_, BlockPos p_49848_, BlockState p_49849_, @Nullable LivingEntity p_49850_, ItemStack p_49851_) { +@@ -386,6 +_,7 @@ + p_49822_.setDeltaMovement(p_49822_.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + ++ /** @deprecated Forge use {@link IForgeBlock#getCloneItemStack(BlockState, HitResult, LevelReader, BlockPos, Player)}*/ + public ItemStack getCloneItemStack(LevelReader p_312699_, BlockPos p_49824_, BlockState p_49825_) { + return new ItemStack(this); + } +@@ -460,7 +_,7 @@ + this.item = Item.byBlock(this); + } + +- return this.item; ++ return net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(this.item).get(); // Forge: Vanilla caches the items, update with registry replacements. + } + + public boolean hasDynamicShape() { +@@ -528,5 +_,74 @@ + i = 31 * i + this.second.hashCode(); + return 31 * i + this.direction.hashCode(); + } ++ } ++ ++ private Object renderProperties; ++ ++ /** ++ * DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE ++ * Call RenderProperties.get instead ++ */ ++ public Object getRenderPropertiesInternal() { ++ return renderProperties; ++ } ++ ++ private void initClient() { ++ // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen ++ if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) { ++ initializeClient(properties -> { ++ if (properties == this) { ++ throw new IllegalStateException("Don't extend IBlockRenderProperties in your block, use an anonymous class instead."); ++ } ++ this.renderProperties = properties; ++ }); ++ } ++ } ++ ++ public void initializeClient(java.util.function.Consumer consumer) { ++ } ++ ++ @Override ++ public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing, net.minecraftforge.common.IPlantable plantable) { ++ var plant = plantable.getPlant(world, pos.relative(facing)); ++ var type = plantable.getPlantType(world, pos.relative(facing)); ++ ++ if (plant.getBlock() == Blocks.CACTUS) { ++ return state.is(Blocks.CACTUS) || state.is(BlockTags.SAND); ++ } else if (plant.getBlock() == Blocks.SUGAR_CANE && this == Blocks.SUGAR_CANE) { ++ return true; ++ } else if (plantable instanceof BushBlock bush && bush.mayPlaceOn(state, world, pos)) { ++ return true; ++ } else if (net.minecraftforge.common.PlantType.DESERT.equals(type)) { ++ return state.is(BlockTags.SAND) || this == Blocks.TERRACOTTA || this instanceof GlazedTerracottaBlock; ++ } else if (net.minecraftforge.common.PlantType.NETHER.equals(type)) { ++ return this == Blocks.SOUL_SAND; ++ } else if (net.minecraftforge.common.PlantType.CROP.equals(type)) { ++ return state.is(Blocks.FARMLAND); ++ } else if (net.minecraftforge.common.PlantType.CAVE.equals(type)) { ++ return state.isFaceSturdy(world, pos, Direction.UP); ++ } else if (net.minecraftforge.common.PlantType.PLAINS.equals(type)) { ++ return state.is(BlockTags.DIRT) || this == Blocks.FARMLAND; ++ } else if (net.minecraftforge.common.PlantType.WATER.equals(type)) { ++ return (state.is(Blocks.WATER) || state.getBlock() instanceof IceBlock) && world.getFluidState(pos.relative(facing)).isEmpty(); ++ } else if (net.minecraftforge.common.PlantType.BEACH.equals(type)) { ++ boolean isBeach = state.is(BlockTags.DIRT) || state.is(BlockTags.SAND); ++ boolean hasWater = false; ++ for (Direction face : Direction.Plane.HORIZONTAL) { ++ BlockState adjacentBlockState = world.getBlockState(pos.relative(face)); ++ var adjacentFluidState = world.getFluidState(pos.relative(face)); ++ hasWater = hasWater || adjacentBlockState.is(Blocks.FROSTED_ICE) || adjacentFluidState.is(net.minecraft.tags.FluidTags.WATER); ++ if (hasWater) { ++ break; //No point continuing. ++ } ++ } ++ return isBeach && hasWater; ++ } ++ return false; ++ } ++ ++ @SuppressWarnings("deprecation") ++ public SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity) { ++ return getSoundType(state); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch b/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch index cca5a0bbfe..effead84a4 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch @@ -1,29 +1,28 @@ --- a/net/minecraft/world/level/block/Blocks.java +++ b/net/minecraft/world/level/block/Blocks.java -@@ -170,7 +_,7 @@ - public static final Block GREEN_BED = register("green_bed", bed(DyeColor.GREEN)); - public static final Block RED_BED = register("red_bed", bed(DyeColor.RED)); - public static final Block BLACK_BED = register("black_bed", bed(DyeColor.BLACK)); -- public static final Block POWERED_RAIL = register("powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL))); -+ public static final Block POWERED_RAIL = register("powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL), true)); - public static final Block DETECTOR_RAIL = register("detector_rail", new DetectorRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL))); - public static final Block STICKY_PISTON = register("sticky_piston", pistonBase(true)); - public static final Block COBWEB = register("cobweb", new WebBlock(BlockBehaviour.Properties.of().mapColor(MapColor.WOOL).forceSolidOn().noCollission().requiresCorrectToolForDrops().strength(4.0F).pushReaction(PushReaction.DESTROY))); -@@ -1305,17 +_,5 @@ +@@ -791,7 +_,7 @@ + public static final Block RED_BED = register("red_bed", bed(DyeColor.RED)); + public static final Block BLACK_BED = register("black_bed", bed(DyeColor.BLACK)); + public static final Block POWERED_RAIL = register( +- "powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL)) ++ "powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL), true) + ); + public static final Block DETECTOR_RAIL = register( + "detector_rail", new DetectorRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL)) +@@ -7581,16 +_,5 @@ - public static void rebuildCache() { - Block.BLOCK_STATE_REGISTRY.forEach(BlockBehaviour.BlockStateBase::initCache); -- } + public static void rebuildCache() { + Block.BLOCK_STATE_REGISTRY.forEach(BlockBehaviour.BlockStateBase::initCache); +- } - -- static { -- for(Block block : BuiltInRegistries.BLOCK) { -- for(BlockState blockstate : block.getStateDefinition().getPossibleStates()) { -- Block.BLOCK_STATE_REGISTRY.add(blockstate); -- blockstate.initCache(); -- } +- static { +- for (Block block : BuiltInRegistries.BLOCK) { +- for (BlockState blockstate : block.getStateDefinition().getPossibleStates()) { +- Block.BLOCK_STATE_REGISTRY.add(blockstate); +- blockstate.initCache(); +- } - -- block.getLootTable(); -- } -- - } +- block.getLootTable(); +- } + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/BucketPickup.java.patch b/patches/minecraft/net/minecraft/world/level/block/BucketPickup.java.patch index 268070ecb8..d56ea8805d 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BucketPickup.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BucketPickup.java.patch @@ -1,13 +1,14 @@ --- a/net/minecraft/world/level/block/BucketPickup.java +++ b/net/minecraft/world/level/block/BucketPickup.java -@@ -9,8 +_,9 @@ +@@ -9,8 +_,10 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.state.BlockState; -public interface BucketPickup { +public interface BucketPickup extends net.minecraftforge.common.extensions.IForgeBucketPickup { - ItemStack pickupBlock(@Nullable Player p_298551_, LevelAccessor p_152719_, BlockPos p_152720_, BlockState p_152721_); + ItemStack pickupBlock(@Nullable Player p_298551_, LevelAccessor p_152719_, BlockPos p_152720_, BlockState p_152721_); -+ @Deprecated//Forge: Use state sensitive variant instead - Optional getPickupSound(); ++ /** @deprecated Forge: Use state-sensitive variant instead */ ++ @Deprecated + Optional getPickupSound(); } diff --git a/patches/minecraft/net/minecraft/world/level/block/BushBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BushBlock.java.patch index 3868e7ce87..4a431d2d84 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BushBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BushBlock.java.patch @@ -6,28 +6,28 @@ -public abstract class BushBlock extends Block { +public abstract class BushBlock extends Block implements net.minecraftforge.common.IPlantable { - protected BushBlock(BlockBehaviour.Properties p_51021_) { - super(p_51021_); - } -@@ -28,6 +_,8 @@ + protected BushBlock(BlockBehaviour.Properties p_51021_) { + super(p_51021_); + } +@@ -31,6 +_,9 @@ + @Override + protected boolean canSurvive(BlockState p_51028_, LevelReader p_51029_, BlockPos p_51030_) { + BlockPos blockpos = p_51030_.below(); ++ if (p_51028_.getBlock() == this) { //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. ++ return p_51029_.getBlockState(blockpos).canSustainPlant(p_51029_, blockpos, Direction.UP, this); ++ } + return this.mayPlaceOn(p_51029_.getBlockState(blockpos), p_51029_, blockpos); + } - public boolean canSurvive(BlockState p_51028_, LevelReader p_51029_, BlockPos p_51030_) { - BlockPos blockpos = p_51030_.below(); -+ if (p_51028_.getBlock() == this) //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. -+ return p_51029_.getBlockState(blockpos).canSustainPlant(p_51029_, blockpos, Direction.UP, this); - return this.mayPlaceOn(p_51029_.getBlockState(blockpos), p_51029_, blockpos); - } - -@@ -37,5 +_,12 @@ - - public boolean isPathfindable(BlockState p_51023_, BlockGetter p_51024_, BlockPos p_51025_, PathComputationType p_51026_) { - return p_51026_ == PathComputationType.AIR && !this.hasCollision ? true : super.isPathfindable(p_51023_, p_51024_, p_51025_, p_51026_); -+ } +@@ -42,5 +_,11 @@ + @Override + protected boolean isPathfindable(BlockState p_51023_, PathComputationType p_51026_) { + return p_51026_ == PathComputationType.AIR && !this.hasCollision ? true : super.isPathfindable(p_51023_, p_51026_); ++ } + -+ @Override -+ public BlockState getPlant(BlockGetter world, BlockPos pos) { -+ BlockState state = world.getBlockState(pos); -+ if (state.getBlock() != this) return defaultBlockState(); -+ return state; - } ++ @Override ++ public BlockState getPlant(BlockGetter world, BlockPos pos) { ++ BlockState state = world.getBlockState(pos); ++ return state.getBlock() == this ? state : defaultBlockState(); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch index 80ae296b8f..2175804583 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch @@ -6,61 +6,56 @@ -public class CactusBlock extends Block { +public class CactusBlock extends Block implements net.minecraftforge.common.IPlantable { - public static final MapCodec CODEC = simpleCodec(CactusBlock::new); - public static final IntegerProperty AGE = BlockStateProperties.AGE_15; - public static final int MAX_AGE = 15; -@@ -39,6 +_,7 @@ - } + public static final MapCodec CODEC = simpleCodec(CactusBlock::new); + public static final IntegerProperty AGE = BlockStateProperties.AGE_15; + public static final int MAX_AGE = 15; +@@ -41,6 +_,7 @@ - public void tick(BlockState p_220908_, ServerLevel p_220909_, BlockPos p_220910_, RandomSource p_220911_) { -+ if (!p_220909_.isAreaLoaded(p_220910_, 1)) return; // Forge: prevent growing cactus from loading unloaded chunks with block update - if (!p_220908_.canSurvive(p_220909_, p_220910_)) { - p_220909_.destroyBlock(p_220910_, true); - } -@@ -54,15 +_,17 @@ + @Override + protected void tick(BlockState p_220908_, ServerLevel p_220909_, BlockPos p_220910_, RandomSource p_220911_) { ++ if (!p_220909_.isAreaLoaded(p_220910_, 1)) return; // Forge: prevent growing cactus from loading unloaded chunks with block update + if (!p_220908_.canSurvive(p_220909_, p_220910_)) { + p_220909_.destroyBlock(p_220910_, true); + } +@@ -58,6 +_,7 @@ - if (i < 3) { - int j = p_220913_.getValue(AGE); -+ if(net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_220914_, blockpos, p_220913_, true)) { - if (j == 15) { - p_220914_.setBlockAndUpdate(blockpos, this.defaultBlockState()); -- BlockState blockstate = p_220913_.setValue(AGE, Integer.valueOf(0)); -+ BlockState blockstate = p_220913_.setValue(AGE, 0); - p_220914_.setBlock(p_220915_, blockstate, 4); - p_220914_.neighborChanged(blockstate, blockpos, this, p_220915_, false); - } else { -- p_220914_.setBlock(p_220915_, p_220913_.setValue(AGE, Integer.valueOf(j + 1)), 4); -- } -- -+ p_220914_.setBlock(p_220915_, p_220913_.setValue(AGE, j + 1), 4); -+ } -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_220914_, p_220915_, p_220913_); -+ } - } - } - } -@@ -92,7 +_,7 @@ - } + if (i < 3) { + int j = p_220913_.getValue(AGE); ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_220914_, blockpos, p_220913_, true)) { + if (j == 15) { + p_220914_.setBlockAndUpdate(blockpos, this.defaultBlockState()); + BlockState blockstate = p_220913_.setValue(AGE, Integer.valueOf(0)); +@@ -66,6 +_,8 @@ + } else { + p_220914_.setBlock(p_220915_, p_220913_.setValue(AGE, Integer.valueOf(j + 1)), 4); + } ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_220914_, p_220915_, p_220913_); ++ } + } + } + } +@@ -99,7 +_,7 @@ + } - BlockState blockstate1 = p_51154_.getBlockState(p_51155_.below()); -- return (blockstate1.is(Blocks.CACTUS) || blockstate1.is(BlockTags.SAND)) && !p_51154_.getBlockState(p_51155_.above()).liquid(); -+ return blockstate1.canSustainPlant(p_51154_, p_51155_, Direction.UP, this) && !p_51154_.getBlockState(p_51155_.above()).liquid(); - } + BlockState blockstate1 = p_51154_.getBlockState(p_51155_.below()); +- return (blockstate1.is(Blocks.CACTUS) || blockstate1.is(BlockTags.SAND)) && !p_51154_.getBlockState(p_51155_.above()).liquid(); ++ return blockstate1.canSustainPlant(p_51154_, p_51155_, Direction.UP, this) && !p_51154_.getBlockState(p_51155_.above()).liquid(); + } - public void entityInside(BlockState p_51148_, Level p_51149_, BlockPos p_51150_, Entity p_51151_) { -@@ -105,5 +_,15 @@ - - public boolean isPathfindable(BlockState p_51143_, BlockGetter p_51144_, BlockPos p_51145_, PathComputationType p_51146_) { - return false; -+ } + @Override +@@ -115,5 +_,15 @@ + @Override + protected boolean isPathfindable(BlockState p_51143_, PathComputationType p_51146_) { + return false; ++ } + -+ @Override -+ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { -+ return net.minecraftforge.common.PlantType.DESERT; -+ } ++ @Override ++ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { ++ return net.minecraftforge.common.PlantType.DESERT; ++ } + -+ @Override -+ public BlockState getPlant(BlockGetter world, BlockPos pos) { -+ return defaultBlockState(); - } ++ @Override ++ public BlockState getPlant(BlockGetter world, BlockPos pos) { ++ return defaultBlockState(); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch index 67d134fda6..1c3462f9e1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/CampfireBlock.java +++ b/net/minecraft/world/level/block/CampfireBlock.java -@@ -218,7 +_,7 @@ - return true; - } +@@ -277,7 +_,7 @@ + return true; + } -- boolean flag = Shapes.joinIsNotEmpty(VIRTUAL_FENCE_POST, blockstate.getCollisionShape(p_51249_, p_51250_, CollisionContext.empty()), BooleanOp.AND); -+ boolean flag = Shapes.joinIsNotEmpty(VIRTUAL_FENCE_POST, blockstate.getCollisionShape(p_51249_, blockpos, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 - if (flag) { - BlockState blockstate1 = p_51249_.getBlockState(blockpos.below()); - return isLitCampfire(blockstate1); +- boolean flag = Shapes.joinIsNotEmpty(VIRTUAL_FENCE_POST, blockstate.getCollisionShape(p_51249_, p_51250_, CollisionContext.empty()), BooleanOp.AND); ++ boolean flag = Shapes.joinIsNotEmpty(VIRTUAL_FENCE_POST, blockstate.getCollisionShape(p_51249_, blockpos, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 + if (flag) { + BlockState blockstate1 = p_51249_.getBlockState(blockpos.below()); + return isLitCampfire(blockstate1); diff --git a/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch index 9c04195b38..99655a4e31 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/ChestBlock.java +++ b/net/minecraft/world/level/block/ChestBlock.java -@@ -338,7 +_,8 @@ - } +@@ -357,7 +_,8 @@ - public BlockState mirror(BlockState p_51549_, Mirror p_51550_) { -- return p_51549_.rotate(p_51550_.getRotation(p_51549_.getValue(FACING))); -+ BlockState rotated = p_51549_.rotate(p_51550_.getRotation(p_51549_.getValue(FACING))); -+ return p_51550_ == Mirror.NONE ? rotated : rotated.setValue(TYPE, rotated.getValue(TYPE).getOpposite()); // Forge: Fixed MC-134110 Structure mirroring breaking apart double chests - } + @Override + protected BlockState mirror(BlockState p_51549_, Mirror p_51550_) { +- return p_51549_.rotate(p_51550_.getRotation(p_51549_.getValue(FACING))); ++ BlockState rotated = p_51549_.rotate(p_51550_.getRotation(p_51549_.getValue(FACING))); ++ return p_51550_ == Mirror.NONE ? rotated : rotated.setValue(TYPE, rotated.getValue(TYPE).getOpposite()); // Forge: Fixed MC-134110 Structure mirroring breaking apart double chests + } - protected void createBlockStateDefinition(StateDefinition.Builder p_51562_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch index 0a2a6e3ca6..42f89536d1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch @@ -1,20 +1,19 @@ --- a/net/minecraft/world/level/block/ChorusFlowerBlock.java +++ b/net/minecraft/world/level/block/ChorusFlowerBlock.java -@@ -61,7 +_,7 @@ - BlockPos blockpos = p_220982_.above(); - if (p_220981_.isEmptyBlock(blockpos) && blockpos.getY() < p_220981_.getMaxBuildHeight()) { - int i = p_220980_.getValue(AGE); -- if (i < 5) { -+ if (i < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_220981_, blockpos, p_220980_, true)) { - boolean flag = false; - boolean flag1 = false; - BlockState blockstate = p_220981_.getBlockState(p_220982_.below()); -@@ -117,7 +_,7 @@ - } else { - this.placeDeadFlower(p_220981_, p_220982_); +@@ -65,7 +_,7 @@ + BlockPos blockpos = p_220982_.above(); + if (p_220981_.isEmptyBlock(blockpos) && blockpos.getY() < p_220981_.getMaxBuildHeight()) { + int i = p_220980_.getValue(AGE); +- if (i < 5) { ++ if (i < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_220981_, blockpos, p_220980_, true)) { + boolean flag = false; + boolean flag1 = false; + BlockState blockstate = p_220981_.getBlockState(p_220982_.below()); +@@ -121,6 +_,7 @@ + } else { + this.placeDeadFlower(p_220981_, p_220982_); + } ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_220981_, p_220982_, p_220980_); } -- -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_220981_, p_220982_, p_220980_); - } - } - } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch index 206561a79b..0915c0cae4 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch @@ -1,17 +1,16 @@ --- a/net/minecraft/world/level/block/CocoaBlock.java +++ b/net/minecraft/world/level/block/CocoaBlock.java -@@ -53,10 +_,11 @@ - } - - public void randomTick(BlockState p_221000_, ServerLevel p_221001_, BlockPos p_221002_, RandomSource p_221003_) { -- if (p_221001_.random.nextInt(5) == 0) { -+ if (true) { - int i = p_221000_.getValue(AGE); -- if (i < 2) { -- p_221001_.setBlock(p_221002_, p_221000_.setValue(AGE, Integer.valueOf(i + 1)), 2); -+ if (i < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221001_, p_221002_, p_221000_, p_221001_.random.nextInt(5) == 0)) { -+ p_221001_.setBlock(p_221002_, p_221000_.setValue(AGE, i + 1), 2); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221001_, p_221002_, p_221000_); - } - } +@@ -64,10 +_,11 @@ + @Override + protected void randomTick(BlockState p_221000_, ServerLevel p_221001_, BlockPos p_221002_, RandomSource p_221003_) { +- if (p_221001_.random.nextInt(5) == 0) { ++ { + int i = p_221000_.getValue(AGE); +- if (i < 2) { ++ if (i < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221001_, p_221002_, p_221000_, p_221001_.random.nextInt(5) == 0)) { + p_221001_.setBlock(p_221002_, p_221000_.setValue(AGE, Integer.valueOf(i + 1)), 2); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221001_, p_221002_, p_221000_); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch index dfb08ad5d8..7d14e773c3 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/level/block/ComparatorBlock.java +++ b/net/minecraft/world/level/block/ComparatorBlock.java -@@ -176,4 +_,16 @@ - protected void createBlockStateDefinition(StateDefinition.Builder p_51887_) { - p_51887_.add(FACING, MODE, POWERED); - } +@@ -197,4 +_,16 @@ + protected void createBlockStateDefinition(StateDefinition.Builder p_51887_) { + p_51887_.add(FACING, MODE, POWERED); + } + -+ @Override -+ public boolean getWeakChanges(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos) { -+ return state.is(Blocks.COMPARATOR); -+ } ++ @Override ++ public boolean getWeakChanges(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos) { ++ return state.is(Blocks.COMPARATOR); ++ } + -+ @Override -+ public void onNeighborChange(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos, BlockPos neighbor) { -+ if (pos.getY() == neighbor.getY() && world instanceof Level && !((Level)world).isClientSide()) { -+ state.neighborChanged((Level)world, pos, world.getBlockState(neighbor).getBlock(), neighbor, false); -+ } -+ } ++ @Override ++ public void onNeighborChange(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos, BlockPos neighbor) { ++ if (pos.getY() == neighbor.getY() && world instanceof Level level) { ++ level.neighborChanged(state, pos, world.getBlockState(neighbor).getBlock(), neighbor, false); ++ } ++ } } diff --git a/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch index 239cf99fb0..29cb799e4c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch @@ -1,49 +1,49 @@ --- a/net/minecraft/world/level/block/ConcretePowderBlock.java +++ b/net/minecraft/world/level/block/ConcretePowderBlock.java -@@ -32,7 +_,7 @@ - } +@@ -34,7 +_,7 @@ - public void onLand(Level p_52068_, BlockPos p_52069_, BlockState p_52070_, BlockState p_52071_, FallingBlockEntity p_52072_) { -- if (shouldSolidify(p_52068_, p_52069_, p_52071_)) { -+ if (shouldSolidify(p_52068_, p_52069_, p_52070_, p_52071_.getFluidState())) { // Forge: Use block of falling entity instead of block at replaced position, and check if shouldSolidify with the FluidState of the replaced block - p_52068_.setBlock(p_52069_, this.concrete.defaultBlockState(), 3); - } + @Override + public void onLand(Level p_52068_, BlockPos p_52069_, BlockState p_52070_, BlockState p_52071_, FallingBlockEntity p_52072_) { +- if (shouldSolidify(p_52068_, p_52069_, p_52071_)) { ++ if (shouldSolidify(p_52068_, p_52069_, p_52070_, p_52071_.getFluidState())) { // Forge: Use block of falling entity instead of block at replaced position, and check if shouldSolidify with the FluidState of the replaced block + p_52068_.setBlock(p_52069_, this.concrete.defaultBlockState(), 3); + } + } +@@ -47,20 +_,24 @@ + return shouldSolidify(blockgetter, blockpos, blockstate) ? this.concrete.defaultBlockState() : super.getStateForPlacement(p_52063_); + } -@@ -45,20 +_,24 @@ - return shouldSolidify(blockgetter, blockpos, blockstate) ? this.concrete.defaultBlockState() : super.getStateForPlacement(p_52063_); - } - -+ private static boolean shouldSolidify(BlockGetter p_52081_, BlockPos p_52082_, BlockState p_52083_, net.minecraft.world.level.material.FluidState fluidState) { -+ return p_52083_.canBeHydrated(p_52081_, p_52082_, fluidState, p_52082_) || touchesLiquid(p_52081_, p_52082_, p_52083_); -+ } ++ private static boolean shouldSolidify(BlockGetter p_52081_, BlockPos p_52082_, BlockState p_52083_, net.minecraft.world.level.material.FluidState fluidState) { ++ return p_52083_.canBeHydrated(p_52081_, p_52082_, fluidState, p_52082_) || touchesLiquid(p_52081_, p_52082_, p_52083_); ++ } + - private static boolean shouldSolidify(BlockGetter p_52081_, BlockPos p_52082_, BlockState p_52083_) { -- return canSolidify(p_52083_) || touchesLiquid(p_52081_, p_52082_); -+ return shouldSolidify(p_52081_, p_52082_, p_52083_, p_52081_.getFluidState(p_52082_)); - } + private static boolean shouldSolidify(BlockGetter p_52081_, BlockPos p_52082_, BlockState p_52083_) { +- return canSolidify(p_52083_) || touchesLiquid(p_52081_, p_52082_); ++ return shouldSolidify(p_52081_, p_52082_, p_52083_, p_52081_.getFluidState(p_52082_)); + } -- private static boolean touchesLiquid(BlockGetter p_52065_, BlockPos p_52066_) { -+ private static boolean touchesLiquid(BlockGetter p_52065_, BlockPos p_52066_, BlockState state) { - boolean flag = false; - BlockPos.MutableBlockPos blockpos$mutableblockpos = p_52066_.mutable(); +- private static boolean touchesLiquid(BlockGetter p_52065_, BlockPos p_52066_) { ++ private static boolean touchesLiquid(BlockGetter p_52065_, BlockPos p_52066_, BlockState state) { + boolean flag = false; + BlockPos.MutableBlockPos blockpos$mutableblockpos = p_52066_.mutable(); - for(Direction direction : Direction.values()) { - BlockState blockstate = p_52065_.getBlockState(blockpos$mutableblockpos); -- if (direction != Direction.DOWN || canSolidify(blockstate)) { -+ if (direction != Direction.DOWN || state.canBeHydrated(p_52065_, p_52066_, blockstate.getFluidState(), blockpos$mutableblockpos)) { - blockpos$mutableblockpos.setWithOffset(p_52066_, direction); - blockstate = p_52065_.getBlockState(blockpos$mutableblockpos); -- if (canSolidify(blockstate) && !blockstate.isFaceSturdy(p_52065_, p_52066_, direction.getOpposite())) { -+ if (state.canBeHydrated(p_52065_, p_52066_, blockstate.getFluidState(), blockpos$mutableblockpos) && !blockstate.isFaceSturdy(p_52065_, p_52066_, direction.getOpposite())) { - flag = true; - break; - } -@@ -73,7 +_,7 @@ - } + for (Direction direction : Direction.values()) { + BlockState blockstate = p_52065_.getBlockState(blockpos$mutableblockpos); +- if (direction != Direction.DOWN || canSolidify(blockstate)) { ++ if (direction != Direction.DOWN || state.canBeHydrated(p_52065_, p_52066_, blockstate.getFluidState(), blockpos$mutableblockpos)) { + blockpos$mutableblockpos.setWithOffset(p_52066_, direction); + blockstate = p_52065_.getBlockState(blockpos$mutableblockpos); +- if (canSolidify(blockstate) && !blockstate.isFaceSturdy(p_52065_, p_52066_, direction.getOpposite())) { ++ if (state.canBeHydrated(p_52065_, p_52066_, blockstate.getFluidState(), blockpos$mutableblockpos) && !blockstate.isFaceSturdy(p_52065_, p_52066_, direction.getOpposite())) { + flag = true; + break; + } +@@ -76,7 +_,7 @@ - public BlockState updateShape(BlockState p_52074_, Direction p_52075_, BlockState p_52076_, LevelAccessor p_52077_, BlockPos p_52078_, BlockPos p_52079_) { -- return touchesLiquid(p_52077_, p_52078_) ? this.concrete.defaultBlockState() : super.updateShape(p_52074_, p_52075_, p_52076_, p_52077_, p_52078_, p_52079_); -+ return touchesLiquid(p_52077_, p_52078_, p_52074_) ? this.concrete.defaultBlockState() : super.updateShape(p_52074_, p_52075_, p_52076_, p_52077_, p_52078_, p_52079_); - } + @Override + protected BlockState updateShape(BlockState p_52074_, Direction p_52075_, BlockState p_52076_, LevelAccessor p_52077_, BlockPos p_52078_, BlockPos p_52079_) { +- return touchesLiquid(p_52077_, p_52078_) ? this.concrete.defaultBlockState() : super.updateShape(p_52074_, p_52075_, p_52076_, p_52077_, p_52078_, p_52079_); ++ return touchesLiquid(p_52077_, p_52078_, p_52074_) ? this.concrete.defaultBlockState() : super.updateShape(p_52074_, p_52075_, p_52076_, p_52077_, p_52078_, p_52079_); + } - public int getDustColor(BlockState p_52085_, BlockGetter p_52086_, BlockPos p_52087_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch index 84994d25cb..5a1ed63e3c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/CoralBlock.java +++ b/net/minecraft/world/level/block/CoralBlock.java -@@ -50,9 +_,10 @@ - } +@@ -51,9 +_,10 @@ + } - protected boolean scanForWater(BlockGetter p_52135_, BlockPos p_52136_) { -+ BlockState state = p_52135_.getBlockState(p_52136_); - for(Direction direction : Direction.values()) { - FluidState fluidstate = p_52135_.getFluidState(p_52136_.relative(direction)); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (state.canBeHydrated(p_52135_, p_52136_, fluidstate, p_52136_.relative(direction))) { - return true; - } - } + protected boolean scanForWater(BlockGetter p_52135_, BlockPos p_52136_) { ++ BlockState state = p_52135_.getBlockState(p_52136_); + for (Direction direction : Direction.values()) { + FluidState fluidstate = p_52135_.getFluidState(p_52136_.relative(direction)); +- if (fluidstate.is(FluidTags.WATER)) { ++ if (state.canBeHydrated(p_52135_, p_52136_, fluidstate, p_52136_.relative(direction))) { + return true; + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch index b70d3d3d8f..dcf81a4eac 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch @@ -1,39 +1,34 @@ --- a/net/minecraft/world/level/block/CropBlock.java +++ b/net/minecraft/world/level/block/CropBlock.java -@@ -70,12 +_,14 @@ - } - - public void randomTick(BlockState p_221050_, ServerLevel p_221051_, BlockPos p_221052_, RandomSource p_221053_) { -+ if (!p_221051_.isAreaLoaded(p_221052_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light - if (p_221051_.getRawBrightness(p_221052_, 0) >= 9) { - int i = this.getAge(p_221050_); - if (i < this.getMaxAge()) { - float f = getGrowthSpeed(this, p_221051_, p_221052_); -- if (p_221053_.nextInt((int)(25.0F / f) + 1) == 0) { -+ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221051_, p_221052_, p_221050_, p_221053_.nextInt((int)(25.0F / f) + 1) == 0)) { - p_221051_.setBlock(p_221052_, this.getStateForAge(i + 1), 2); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221051_, p_221052_, p_221050_); +@@ -88,8 +_,9 @@ + int i = this.getAge(p_221050_); + if (i < this.getMaxAge()) { + float f = getGrowthSpeed(this, p_221051_, p_221052_); +- if (p_221053_.nextInt((int)(25.0F / f) + 1) == 0) { ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221051_, p_221052_, p_221050_, p_221053_.nextInt((int)(25.0F / f) + 1) == 0)) { + p_221051_.setBlock(p_221052_, this.getStateForAge(i + 1), 2); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221051_, p_221052_, p_221050_); + } } - } - } -@@ -104,9 +_,9 @@ - for(int j = -1; j <= 1; ++j) { - float f1 = 0.0F; - BlockState blockstate = p_52274_.getBlockState(blockpos.offset(i, 0, j)); -- if (blockstate.is(Blocks.FARMLAND)) { -+ if (blockstate.canSustainPlant(p_52274_, blockpos.offset(i, 0, j), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable) p_52273_)) { - f1 = 1.0F; -- if (blockstate.getValue(FarmBlock.MOISTURE) > 0) { -+ if (blockstate.isFertile(p_52274_, p_52275_.offset(i, 0, j))) { - f1 = 3.0F; - } - } -@@ -146,7 +_,7 @@ - } + } +@@ -117,9 +_,9 @@ + for (int j = -1; j <= 1; j++) { + float f1 = 0.0F; + BlockState blockstate = p_52274_.getBlockState(blockpos.offset(i, 0, j)); +- if (blockstate.is(Blocks.FARMLAND)) { ++ if (blockstate.canSustainPlant(p_52274_, blockpos.offset(i, 0, j), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable) p_52273_)) { + f1 = 1.0F; +- if (blockstate.getValue(FarmBlock.MOISTURE) > 0) { ++ if (blockstate.isFertile(p_52274_, p_52275_.offset(i, 0, j))) { + f1 = 3.0F; + } + } +@@ -164,7 +_,7 @@ - public void entityInside(BlockState p_52277_, Level p_52278_, BlockPos p_52279_, Entity p_52280_) { -- if (p_52280_ instanceof Ravager && p_52278_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { -+ if (p_52280_ instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_52278_, p_52280_)) { - p_52278_.destroyBlock(p_52279_, true, p_52280_); - } + @Override + protected void entityInside(BlockState p_52277_, Level p_52278_, BlockPos p_52279_, Entity p_52280_) { +- if (p_52280_ instanceof Ravager && p_52278_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { ++ if (p_52280_ instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_52278_, p_52280_)) { + p_52278_.destroyBlock(p_52279_, true, p_52280_); + } diff --git a/patches/minecraft/net/minecraft/world/level/block/DeadBushBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DeadBushBlock.java.patch index 3a62be0cca..0e25a00037 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DeadBushBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DeadBushBlock.java.patch @@ -6,6 +6,6 @@ -public class DeadBushBlock extends BushBlock { +public class DeadBushBlock extends BushBlock implements net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(DeadBushBlock::new); - protected static final float AABB_OFFSET = 6.0F; - protected static final VoxelShape SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 13.0D, 14.0D); + public static final MapCodec CODEC = simpleCodec(DeadBushBlock::new); + protected static final float AABB_OFFSET = 6.0F; + protected static final VoxelShape SHAPE = Block.box(2.0, 0.0, 2.0, 14.0, 13.0, 14.0); diff --git a/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch index b1faddea3d..0e04437a76 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch @@ -1,32 +1,33 @@ --- a/net/minecraft/world/level/block/DetectorRailBlock.java +++ b/net/minecraft/world/level/block/DetectorRailBlock.java -@@ -37,6 +_,10 @@ +@@ -38,6 +_,10 @@ - public DetectorRailBlock(BlockBehaviour.Properties p_52431_) { - super(true, p_52431_); -+ this.registerDefaultState(); -+ } + public DetectorRailBlock(BlockBehaviour.Properties p_52431_) { + super(true, p_52431_); ++ this.registerDefaultState(); ++ } + -+ protected void registerDefaultState() { - this.registerDefaultState(this.stateDefinition.any().setValue(POWERED, Boolean.valueOf(false)).setValue(SHAPE, RailShape.NORTH_SOUTH).setValue(WATERLOGGED, Boolean.valueOf(false))); - } ++ protected void registerDefaultState() { + this.registerDefaultState( + this.stateDefinition + .any() +@@ -152,7 +_,10 @@ + return list.get(0).getCommandBlock().getSuccessCount(); + } -@@ -141,7 +_,9 @@ - return list.get(0).getCommandBlock().getSuccessCount(); - } +- List list1 = this.getInteractingMinecartOfType(p_52455_, p_52456_, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); ++ List carts = this.getInteractingMinecartOfType(p_52455_, p_52456_, AbstractMinecart.class, e -> e.isAlive()); ++ if (!carts.isEmpty() && carts.get(0).getComparatorLevel() > -1) return carts.get(0).getComparatorLevel(); ++ List list1 = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).toList(); ++ + if (!list1.isEmpty()) { + return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)list1.get(0)); + } +@@ -297,6 +_,6 @@ -- List list1 = this.getInteractingMinecartOfType(p_52455_, p_52456_, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); -+ List carts = this.getInteractingMinecartOfType(p_52455_, p_52456_, AbstractMinecart.class, e -> e.isAlive()); -+ if (!carts.isEmpty() && carts.get(0).getComparatorLevel() > -1) return carts.get(0).getComparatorLevel(); -+ List list1 = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).collect(java.util.stream.Collectors.toList()); - if (!list1.isEmpty()) { - return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)list1.get(0)); - } -@@ -276,6 +_,6 @@ - } - - protected void createBlockStateDefinition(StateDefinition.Builder p_52469_) { -- p_52469_.add(SHAPE, POWERED, WATERLOGGED); -+ p_52469_.add(getShapeProperty(), POWERED, WATERLOGGED); - } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder p_52469_) { +- p_52469_.add(SHAPE, POWERED, WATERLOGGED); ++ p_52469_.add(getShapeProperty(), POWERED, WATERLOGGED); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch index 024abe6a42..32480d060f 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch @@ -1,11 +1,12 @@ --- a/net/minecraft/world/level/block/DiodeBlock.java +++ b/net/minecraft/world/level/block/DiodeBlock.java -@@ -162,6 +_,8 @@ - protected void updateNeighborsInFront(Level p_52581_, BlockPos p_52582_, BlockState p_52583_) { - Direction direction = p_52583_.getValue(FACING); - BlockPos blockpos = p_52582_.relative(direction.getOpposite()); -+ if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(p_52581_, p_52582_, p_52581_.getBlockState(p_52582_), java.util.EnumSet.of(direction.getOpposite()), false).isCanceled()) -+ return; - p_52581_.neighborChanged(blockpos, this, p_52582_); - p_52581_.updateNeighborsAtExceptFromFacing(blockpos, this, direction); - } +@@ -172,6 +_,9 @@ + protected void updateNeighborsInFront(Level p_52581_, BlockPos p_52582_, BlockState p_52583_) { + Direction direction = p_52583_.getValue(FACING); + BlockPos blockpos = p_52582_.relative(direction.getOpposite()); ++ if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(p_52581_, p_52582_, p_52581_.getBlockState(p_52582_), java.util.EnumSet.of(direction.getOpposite()), false).isCanceled()) { ++ return; ++ } + p_52581_.neighborChanged(blockpos, this, p_52582_); + p_52581_.updateNeighborsAtExceptFromFacing(blockpos, this, direction); + } diff --git a/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch index 124e43dc65..34be88a048 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/block/DoublePlantBlock.java +++ b/net/minecraft/world/level/block/DoublePlantBlock.java -@@ -60,6 +_,7 @@ - return super.canSurvive(p_52887_, p_52888_, p_52889_); - } else { - BlockState blockstate = p_52888_.getBlockState(p_52889_.below()); -+ if (p_52887_.getBlock() != this) return super.canSurvive(p_52887_, p_52888_, p_52889_); //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. - return blockstate.is(this) && blockstate.getValue(HALF) == DoubleBlockHalf.LOWER; - } - } +@@ -69,6 +_,7 @@ + return super.canSurvive(p_52887_, p_52888_, p_52889_); + } else { + BlockState blockstate = p_52888_.getBlockState(p_52889_.below()); ++ if (p_52887_.getBlock() != this) return super.canSurvive(p_52887_, p_52888_, p_52889_); //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. + return blockstate.is(this) && blockstate.getValue(HALF) == DoubleBlockHalf.LOWER; + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch index 354ac2e4e8..9c378753c0 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch @@ -1,18 +1,17 @@ --- a/net/minecraft/world/level/block/DropExperienceBlock.java +++ b/net/minecraft/world/level/block/DropExperienceBlock.java -@@ -28,9 +_,11 @@ - - public void spawnAfterBreak(BlockState p_221086_, ServerLevel p_221087_, BlockPos p_221088_, ItemStack p_221089_, boolean p_221090_) { - super.spawnAfterBreak(p_221086_, p_221087_, p_221088_, p_221089_, p_221090_); -- if (p_221090_) { -- this.tryDropExperience(p_221087_, p_221088_, p_221089_, this.xpRange); -- } -- +@@ -30,8 +_,13 @@ + @Override + protected void spawnAfterBreak(BlockState p_221086_, ServerLevel p_221087_, BlockPos p_221088_, ItemStack p_221089_, boolean p_221090_) { + super.spawnAfterBreak(p_221086_, p_221087_, p_221088_, p_221089_, p_221090_); +- if (p_221090_) { ++ if (false && p_221090_) { // Forge: moved to getExpDrop + this.tryDropExperience(p_221087_, p_221088_, p_221089_, this.xpRange); + } ++ } + -+ } -+ -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, net.minecraft.util.RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { -+ return silkTouchLevel == 0 ? this.xpRange.sample(randomSource) : 0; - } ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, net.minecraft.util.RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { ++ return silkTouchLevel == 0 ? this.xpRange.sample(randomSource) : 0; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch index 9a56f8e911..a395e4b7e9 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/DropperBlock.java +++ b/net/minecraft/world/level/block/DropperBlock.java -@@ -51,7 +_,7 @@ - p_52944_.levelEvent(1001, p_52945_, 0); - } else { - ItemStack itemstack = dispenserblockentity.getItem(i); -- if (!itemstack.isEmpty()) { -+ if (!itemstack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(p_52944_, p_52945_, dispenserblockentity, i, itemstack)) { - Direction direction = p_52944_.getBlockState(p_52945_).getValue(FACING); - Container container = HopperBlockEntity.getContainerAt(p_52944_, p_52945_.relative(direction)); - ItemStack itemstack1; +@@ -56,7 +_,7 @@ + p_52944_.levelEvent(1001, p_52945_, 0); + } else { + ItemStack itemstack = dispenserblockentity.getItem(i); +- if (!itemstack.isEmpty()) { ++ if (!itemstack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(p_52944_, p_52945_, dispenserblockentity, i, itemstack)) { + Direction direction = p_52944_.getBlockState(p_52945_).getValue(FACING); + Container container = HopperBlockEntity.getContainerAt(p_52944_, p_52945_.relative(direction)); + ItemStack itemstack1; diff --git a/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch new file mode 100644 index 0000000000..92207f6d2a --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/EnchantingTableBlock.java ++++ b/net/minecraft/world/level/block/EnchantingTableBlock.java +@@ -47,7 +_,7 @@ + } + + public static boolean isValidBookShelf(Level p_328191_, BlockPos p_328702_, BlockPos p_336071_) { +- return p_328191_.getBlockState(p_328702_.offset(p_336071_)).is(BlockTags.ENCHANTMENT_POWER_PROVIDER) ++ return p_328191_.getBlockState(p_328702_.offset(p_336071_)).getEnchantPowerBonus(p_328191_, p_328702_.offset(p_336071_)) != 0 + && p_328191_.getBlockState(p_328702_.offset(p_336071_.getX() / 2, p_336071_.getY(), p_336071_.getZ() / 2)).is(BlockTags.ENCHANTMENT_POWER_TRANSMITTER); + } + diff --git a/patches/minecraft/net/minecraft/world/level/block/EnchantmentTableBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/EnchantmentTableBlock.java.patch deleted file mode 100644 index c9368d2cd5..0000000000 --- a/patches/minecraft/net/minecraft/world/level/block/EnchantmentTableBlock.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/level/block/EnchantmentTableBlock.java -+++ b/net/minecraft/world/level/block/EnchantmentTableBlock.java -@@ -47,7 +_,7 @@ - } - - public static boolean isValidBookShelf(Level p_207910_, BlockPos p_207911_, BlockPos p_207912_) { -- return p_207910_.getBlockState(p_207911_.offset(p_207912_)).is(BlockTags.ENCHANTMENT_POWER_PROVIDER) && p_207910_.getBlockState(p_207911_.offset(p_207912_.getX() / 2, p_207912_.getY(), p_207912_.getZ() / 2)).is(BlockTags.ENCHANTMENT_POWER_TRANSMITTER); -+ return p_207910_.getBlockState(p_207911_.offset(p_207912_)).getEnchantPowerBonus(p_207910_, p_207911_.offset(p_207912_)) != 0 && p_207910_.getBlockState(p_207911_.offset(p_207912_.getX() / 2, p_207912_.getY(), p_207912_.getZ() / 2)).is(BlockTags.ENCHANTMENT_POWER_TRANSMITTER); - } - - public boolean useShapeForLightOcclusion(BlockState p_52997_) { diff --git a/patches/minecraft/net/minecraft/world/level/block/FarmBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FarmBlock.java.patch index 665fd69d68..f528073e8a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FarmBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FarmBlock.java.patch @@ -1,35 +1,38 @@ --- a/net/minecraft/world/level/block/FarmBlock.java +++ b/net/minecraft/world/level/block/FarmBlock.java -@@ -90,7 +_,7 @@ - } +@@ -98,10 +_,7 @@ + @Override + public void fallOn(Level p_153227_, BlockState p_153228_, BlockPos p_153229_, Entity p_153230_, float p_153231_) { + if (!p_153227_.isClientSide +- && p_153227_.random.nextFloat() < p_153231_ - 0.5F +- && p_153230_ instanceof LivingEntity +- && (p_153230_ instanceof Player || p_153227_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) +- && p_153230_.getBbWidth() * p_153230_.getBbWidth() * p_153230_.getBbHeight() > 0.512F) { ++ && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(p_153227_, p_153229_, Blocks.DIRT.defaultBlockState(), p_153231_, p_153230_)) { // Forge: Move logic to Entity#canTrample + turnToDirt(p_153230_, p_153228_, p_153227_, p_153229_); + } - public void fallOn(Level p_153227_, BlockState p_153228_, BlockPos p_153229_, Entity p_153230_, float p_153231_) { -- if (!p_153227_.isClientSide && p_153227_.random.nextFloat() < p_153231_ - 0.5F && p_153230_ instanceof LivingEntity && (p_153230_ instanceof Player || p_153227_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) && p_153230_.getBbWidth() * p_153230_.getBbWidth() * p_153230_.getBbHeight() > 0.512F) { -+ if (!p_153227_.isClientSide && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(p_153227_, p_153229_, Blocks.DIRT.defaultBlockState(), p_153231_, p_153230_)) { // Forge: Move logic to Entity#canTrample - turnToDirt(p_153230_, p_153228_, p_153227_, p_153229_); - } +@@ -115,17 +_,20 @@ + } -@@ -104,17 +_,20 @@ - } + private static boolean shouldMaintainFarmland(BlockGetter p_279219_, BlockPos p_279209_) { +- return p_279219_.getBlockState(p_279209_.above()).is(BlockTags.MAINTAINS_FARMLAND); ++ BlockState plant = p_279219_.getBlockState(p_279209_.above()); ++ BlockState state = p_279219_.getBlockState(p_279209_); ++ return plant.getBlock() instanceof net.minecraftforge.common.IPlantable plantable && state.canSustainPlant(p_279219_, p_279209_, Direction.UP, plantable); + } - private static boolean shouldMaintainFarmland(BlockGetter p_279219_, BlockPos p_279209_) { -- return p_279219_.getBlockState(p_279209_.above()).is(BlockTags.MAINTAINS_FARMLAND); -+ BlockState plant = p_279219_.getBlockState(p_279209_.above()); -+ BlockState state = p_279219_.getBlockState(p_279209_); -+ return plant.getBlock() instanceof net.minecraftforge.common.IPlantable && state.canSustainPlant(p_279219_, p_279209_, Direction.UP, (net.minecraftforge.common.IPlantable)plant.getBlock()); - } + private static boolean isNearWater(LevelReader p_53259_, BlockPos p_53260_) { ++ BlockState state = p_53259_.getBlockState(p_53260_); + for (BlockPos blockpos : BlockPos.betweenClosed(p_53260_.offset(-4, 0, -4), p_53260_.offset(4, 1, 4))) { +- if (p_53259_.getFluidState(blockpos).is(FluidTags.WATER)) { ++ if (state.canBeHydrated(p_53259_, p_53260_, p_53259_.getFluidState(blockpos), blockpos)) { + return true; + } + } - private static boolean isNearWater(LevelReader p_53259_, BlockPos p_53260_) { -+ BlockState state = p_53259_.getBlockState(p_53260_); - for(BlockPos blockpos : BlockPos.betweenClosed(p_53260_.offset(-4, 0, -4), p_53260_.offset(4, 1, 4))) { -- if (p_53259_.getFluidState(blockpos).is(FluidTags.WATER)) { -+ if (state.canBeHydrated(p_53259_, p_53260_, p_53259_.getFluidState(blockpos), blockpos)) { - return true; - } - } +- return false; ++ return net.minecraftforge.common.FarmlandWaterManager.hasBlockWaterTicket(p_53259_, p_53260_); + } -- return false; -+ return net.minecraftforge.common.FarmlandWaterManager.hasBlockWaterTicket(p_53259_, p_53260_); - } - - protected void createBlockStateDefinition(StateDefinition.Builder p_53283_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch index aef2e5680c..ea10379f73 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch @@ -1,53 +1,55 @@ --- a/net/minecraft/world/level/block/FenceGateBlock.java +++ b/net/minecraft/world/level/block/FenceGateBlock.java -@@ -52,14 +_,21 @@ - protected static final VoxelShape Z_OCCLUSION_SHAPE_LOW = Shapes.or(Block.box(0.0D, 2.0D, 7.0D, 2.0D, 13.0D, 9.0D), Block.box(14.0D, 2.0D, 7.0D, 16.0D, 13.0D, 9.0D)); - protected static final VoxelShape X_OCCLUSION_SHAPE_LOW = Shapes.or(Block.box(7.0D, 2.0D, 0.0D, 9.0D, 13.0D, 2.0D), Block.box(7.0D, 2.0D, 14.0D, 9.0D, 13.0D, 16.0D)); - private final WoodType type; -+ private final net.minecraft.sounds.SoundEvent openSound; -+ private final net.minecraft.sounds.SoundEvent closeSound; +@@ -50,6 +_,8 @@ + protected static final VoxelShape Z_OCCLUSION_SHAPE_LOW = Shapes.or(Block.box(0.0, 2.0, 7.0, 2.0, 13.0, 9.0), Block.box(14.0, 2.0, 7.0, 16.0, 13.0, 9.0)); + protected static final VoxelShape X_OCCLUSION_SHAPE_LOW = Shapes.or(Block.box(7.0, 2.0, 0.0, 9.0, 13.0, 2.0), Block.box(7.0, 2.0, 14.0, 9.0, 13.0, 16.0)); + private final WoodType type; ++ private final net.minecraft.sounds.SoundEvent openSound; ++ private final net.minecraft.sounds.SoundEvent closeSound; - public MapCodec codec() { - return CODEC; - } - - public FenceGateBlock(WoodType p_273340_, BlockBehaviour.Properties p_273352_) { -- super(p_273352_.sound(p_273340_.soundType())); -- this.type = p_273340_; -+ this(p_273352_.sound(p_273340_.soundType()), p_273340_.fenceGateOpen(), p_273340_.fenceGateClose(), p_273340_); -+ } -+ public FenceGateBlock(BlockBehaviour.Properties props, net.minecraft.sounds.SoundEvent openSound, net.minecraft.sounds.SoundEvent closeSound, WoodType woodType) { -+ super(props); -+ this.type = woodType; -+ this.openSound = openSound; -+ this.closeSound = closeSound; - this.registerDefaultState(this.stateDefinition.any().setValue(OPEN, Boolean.valueOf(false)).setValue(POWERED, Boolean.valueOf(false)).setValue(IN_WALL, Boolean.valueOf(false))); - } - -@@ -147,7 +_,7 @@ - } - - boolean flag = p_53365_.getValue(OPEN); -- p_53366_.playSound(p_53368_, p_53367_, flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, p_53366_.getRandom().nextFloat() * 0.1F + 0.9F); -+ p_53366_.playSound(p_53368_, p_53367_, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, p_53366_.getRandom().nextFloat() * 0.1F + 0.9F); - p_53366_.gameEvent(p_53368_, flag ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, p_53367_); - return InteractionResult.sidedSuccess(p_53366_.isClientSide); - } -@@ -156,7 +_,7 @@ - if (p_312135_.getBlockInteraction() == Explosion.BlockInteraction.TRIGGER_BLOCK && !p_310915_.isClientSide() && !p_311339_.getValue(POWERED)) { - boolean flag = p_311339_.getValue(OPEN); - p_310915_.setBlockAndUpdate(p_311232_, p_311339_.setValue(OPEN, Boolean.valueOf(!flag))); -- p_310915_.playSound((Player)null, p_311232_, flag ? this.type.fenceGateClose() : this.type.fenceGateOpen(), SoundSource.BLOCKS, 1.0F, p_310915_.getRandom().nextFloat() * 0.1F + 0.9F); -+ p_310915_.playSound((Player)null, p_311232_, flag ? this.closeSound : this.openSound, SoundSource.BLOCKS, 1.0F, p_310915_.getRandom().nextFloat() * 0.1F + 0.9F); - p_310915_.gameEvent(flag ? GameEvent.BLOCK_CLOSE : GameEvent.BLOCK_OPEN, p_311232_, GameEvent.Context.of(p_311339_)); - } + @Override + public MapCodec codec() { +@@ -57,8 +_,14 @@ + } + public FenceGateBlock(WoodType p_273340_, BlockBehaviour.Properties p_273352_) { +- super(p_273352_.sound(p_273340_.soundType())); +- this.type = p_273340_; ++ this(p_273340_, p_273352_, p_273340_.fenceGateOpen(), p_273340_.fenceGateClose()); ++ } ++ ++ public FenceGateBlock(WoodType p_273340_, BlockBehaviour.Properties p_273352_, net.minecraft.sounds.SoundEvent openSound, net.minecraft.sounds.SoundEvent closeSound) { ++ super(p_273352_); ++ this.type = p_273340_; ++ this.openSound = openSound; ++ this.closeSound = closeSound; + this.registerDefaultState( + this.stateDefinition + .any() @@ -169,7 +_,7 @@ - if (p_53372_.getValue(POWERED) != flag) { - p_53373_.setBlock(p_53374_, p_53372_.setValue(POWERED, Boolean.valueOf(flag)).setValue(OPEN, Boolean.valueOf(flag)), 2); - if (p_53372_.getValue(OPEN) != flag) { -- p_53373_.playSound((Player)null, p_53374_, flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, p_53373_.getRandom().nextFloat() * 0.1F + 0.9F); -+ p_53373_.playSound((Player)null, p_53374_, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, p_53373_.getRandom().nextFloat() * 0.1F + 0.9F); - p_53373_.gameEvent((Entity)null, flag ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, p_53374_); - } - } + p_53366_.playSound( + p_53368_, + p_53367_, +- flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), ++ flag ? this.openSound : this.closeSound, + SoundSource.BLOCKS, + 1.0F, + p_53366_.getRandom().nextFloat() * 0.1F + 0.9F +@@ -186,7 +_,7 @@ + p_310915_.playSound( + null, + p_311232_, +- flag ? this.type.fenceGateClose() : this.type.fenceGateOpen(), ++ flag ? this.closeSound : this.openSound, + SoundSource.BLOCKS, + 1.0F, + p_310915_.getRandom().nextFloat() * 0.1F + 0.9F +@@ -207,7 +_,7 @@ + p_53373_.playSound( + null, + p_53374_, +- flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), ++ flag ? this.openSound : this.closeSound, + SoundSource.BLOCKS, + 1.0F, + p_53373_.getRandom().nextFloat() * 0.1F + 0.9F diff --git a/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch index 36f011a91e..d40fd7aab9 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch @@ -1,151 +1,141 @@ --- a/net/minecraft/world/level/block/FireBlock.java +++ b/net/minecraft/world/level/block/FireBlock.java -@@ -110,13 +_,13 @@ - protected BlockState getStateForPlacement(BlockGetter p_53471_, BlockPos p_53472_) { - BlockPos blockpos = p_53472_.below(); - BlockState blockstate = p_53471_.getBlockState(blockpos); -- if (!this.canBurn(blockstate) && !blockstate.isFaceSturdy(p_53471_, blockpos, Direction.UP)) { -+ if (!this.canCatchFire(p_53471_, p_53472_, Direction.UP) && !blockstate.isFaceSturdy(p_53471_, blockpos, Direction.UP)) { - BlockState blockstate1 = this.defaultBlockState(); +@@ -130,13 +_,13 @@ + protected BlockState getStateForPlacement(BlockGetter p_53471_, BlockPos p_53472_) { + BlockPos blockpos = p_53472_.below(); + BlockState blockstate = p_53471_.getBlockState(blockpos); +- if (!this.canBurn(blockstate) && !blockstate.isFaceSturdy(p_53471_, blockpos, Direction.UP)) { ++ if (!this.canCatchFire(p_53471_, p_53472_, Direction.UP) && !blockstate.isFaceSturdy(p_53471_, blockpos, Direction.UP)) { + BlockState blockstate1 = this.defaultBlockState(); - for(Direction direction : Direction.values()) { - BooleanProperty booleanproperty = PROPERTY_BY_DIRECTION.get(direction); - if (booleanproperty != null) { -- blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canBurn(p_53471_.getBlockState(p_53472_.relative(direction))))); -+ blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canCatchFire(p_53471_, p_53472_.relative(direction), direction.getOpposite()))); + for (Direction direction : Direction.values()) { + BooleanProperty booleanproperty = PROPERTY_BY_DIRECTION.get(direction); + if (booleanproperty != null) { +- blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canBurn(p_53471_.getBlockState(p_53472_.relative(direction))))); ++ blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canCatchFire(p_53471_, p_53472_.relative(direction), direction.getOpposite()))); + } } - } -@@ -135,14 +_,14 @@ - p_221161_.scheduleTick(p_221162_, this, getFireTickDelay(p_221161_.random)); - if (p_221161_.getGameRules().getBoolean(GameRules.RULE_DOFIRETICK)) { - if (!p_221160_.canSurvive(p_221161_, p_221162_)) { -- p_221161_.removeBlock(p_221162_, false); - } +@@ -161,7 +_,7 @@ + } - BlockState blockstate = p_221161_.getBlockState(p_221162_.below()); -- boolean flag = blockstate.is(p_221161_.dimensionType().infiniburn()); -+ boolean flag = blockstate.isFireSource(p_221161_, p_221162_, Direction.UP); - int i = p_221160_.getValue(AGE); - if (!flag && p_221161_.isRaining() && this.isNearRain(p_221161_, p_221162_) && p_221163_.nextFloat() < 0.2F + (float)i * 0.03F) { - p_221161_.removeBlock(p_221162_, false); -+ p_221161_.removeBlock(p_221162_, false); - } else { - int j = Math.min(15, i + p_221163_.nextInt(3) / 2); - if (i != j) { -@@ -160,7 +_,7 @@ - return; - } + BlockState blockstate = p_221161_.getBlockState(p_221162_.below()); +- boolean flag = blockstate.is(p_221161_.dimensionType().infiniburn()); ++ boolean flag = blockstate.isFireSource(p_221161_, p_221162_, Direction.UP); + int i = p_221160_.getValue(AGE); + if (!flag && p_221161_.isRaining() && this.isNearRain(p_221161_, p_221162_) && p_221163_.nextFloat() < 0.2F + (float)i * 0.03F) { + p_221161_.removeBlock(p_221162_, false); +@@ -182,7 +_,7 @@ + return; + } -- if (i == 15 && p_221163_.nextInt(4) == 0 && !this.canBurn(p_221161_.getBlockState(p_221162_.below()))) { -+ if (i == 15 && p_221163_.nextInt(4) == 0 && !this.canCatchFire(p_221161_, p_221162_.below(), Direction.UP)) { - p_221161_.removeBlock(p_221162_, false); - return; - } -@@ -168,12 +_,12 @@ +- if (i == 15 && p_221163_.nextInt(4) == 0 && !this.canBurn(p_221161_.getBlockState(p_221162_.below()))) { ++ if (i == 15 && p_221163_.nextInt(4) == 0 && !this.canCatchFire(p_221161_, p_221162_.below(), Direction.UP)) { + p_221161_.removeBlock(p_221162_, false); + return; + } +@@ -190,12 +_,12 @@ - boolean flag1 = p_221161_.getBiome(p_221162_).is(BiomeTags.INCREASED_FIRE_BURNOUT); - int k = flag1 ? -50 : 0; -- this.checkBurnOut(p_221161_, p_221162_.east(), 300 + k, p_221163_, i); -- this.checkBurnOut(p_221161_, p_221162_.west(), 300 + k, p_221163_, i); -- this.checkBurnOut(p_221161_, p_221162_.below(), 250 + k, p_221163_, i); -- this.checkBurnOut(p_221161_, p_221162_.above(), 250 + k, p_221163_, i); -- this.checkBurnOut(p_221161_, p_221162_.north(), 300 + k, p_221163_, i); -- this.checkBurnOut(p_221161_, p_221162_.south(), 300 + k, p_221163_, i); -+ this.tryCatchFire(p_221161_, p_221162_.east(), 300 + k, p_221163_, i, Direction.WEST); -+ this.tryCatchFire(p_221161_, p_221162_.west(), 300 + k, p_221163_, i, Direction.EAST); -+ this.tryCatchFire(p_221161_, p_221162_.below(), 250 + k, p_221163_, i, Direction.UP); -+ this.tryCatchFire(p_221161_, p_221162_.above(), 250 + k, p_221163_, i, Direction.DOWN); -+ this.tryCatchFire(p_221161_, p_221162_.north(), 300 + k, p_221163_, i, Direction.SOUTH); -+ this.tryCatchFire(p_221161_, p_221162_.south(), 300 + k, p_221163_, i, Direction.NORTH); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + boolean flag1 = p_221161_.getBiome(p_221162_).is(BiomeTags.INCREASED_FIRE_BURNOUT); + int k = flag1 ? -50 : 0; +- this.checkBurnOut(p_221161_, p_221162_.east(), 300 + k, p_221163_, i); +- this.checkBurnOut(p_221161_, p_221162_.west(), 300 + k, p_221163_, i); +- this.checkBurnOut(p_221161_, p_221162_.below(), 250 + k, p_221163_, i); +- this.checkBurnOut(p_221161_, p_221162_.above(), 250 + k, p_221163_, i); +- this.checkBurnOut(p_221161_, p_221162_.north(), 300 + k, p_221163_, i); +- this.checkBurnOut(p_221161_, p_221162_.south(), 300 + k, p_221163_, i); ++ this.checkBurnOut(p_221161_, p_221162_.east(), 300 + k, p_221163_, i, Direction.WEST); ++ this.checkBurnOut(p_221161_, p_221162_.west(), 300 + k, p_221163_, i, Direction.EAST); ++ this.checkBurnOut(p_221161_, p_221162_.below(), 250 + k, p_221163_, i, Direction.UP); ++ this.checkBurnOut(p_221161_, p_221162_.above(), 250 + k, p_221163_, i, Direction.DOWN); ++ this.checkBurnOut(p_221161_, p_221162_.north(), 300 + k, p_221163_, i, Direction.SOUTH); ++ this.checkBurnOut(p_221161_, p_221162_.south(), 300 + k, p_221163_, i, Direction.NORTH); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - for(int l = -1; l <= 1; ++l) { -@@ -211,28 +_,27 @@ - return p_53429_.isRainingAt(p_53430_) || p_53429_.isRainingAt(p_53430_.west()) || p_53429_.isRainingAt(p_53430_.east()) || p_53429_.isRainingAt(p_53430_.north()) || p_53429_.isRainingAt(p_53430_.south()); - } + for (int l = -1; l <= 1; l++) { +@@ -238,33 +_,31 @@ + || p_53429_.isRainingAt(p_53430_.south()); + } -+ @Deprecated //Forge: Use IForgeBlockState.getFlammability, Public for default implementation only. - public int getBurnOdds(BlockState p_221165_) { - return p_221165_.hasProperty(BlockStateProperties.WATERLOGGED) && p_221165_.getValue(BlockStateProperties.WATERLOGGED) ? 0 : this.burnOdds.getInt(p_221165_.getBlock()); - } ++ @Deprecated //Forge: Use IForgeBlockState.getFlammability, Public for default implementation only. + public int getBurnOdds(BlockState p_221165_) { + return p_221165_.hasProperty(BlockStateProperties.WATERLOGGED) && p_221165_.getValue(BlockStateProperties.WATERLOGGED) + ? 0 + : this.burnOdds.getInt(p_221165_.getBlock()); + } -+ @Deprecated //Forge: Use IForgeBlockState.getFireSpreadSpeed - public int getIgniteOdds(BlockState p_221167_) { - return p_221167_.hasProperty(BlockStateProperties.WATERLOGGED) && p_221167_.getValue(BlockStateProperties.WATERLOGGED) ? 0 : this.igniteOdds.getInt(p_221167_.getBlock()); - } ++ @Deprecated //Forge: Use IForgeBlockState.getFireSpreadSpeed + public int getIgniteOdds(BlockState p_221167_) { + return p_221167_.hasProperty(BlockStateProperties.WATERLOGGED) && p_221167_.getValue(BlockStateProperties.WATERLOGGED) + ? 0 + : this.igniteOdds.getInt(p_221167_.getBlock()); + } -- private void checkBurnOut(Level p_221151_, BlockPos p_221152_, int p_221153_, RandomSource p_221154_, int p_221155_) { -- int i = this.getBurnOdds(p_221151_.getBlockState(p_221152_)); -- if (p_221154_.nextInt(p_221153_) < i) { -- BlockState blockstate = p_221151_.getBlockState(p_221152_); -- if (p_221154_.nextInt(p_221155_ + 10) < 5 && !p_221151_.isRainingAt(p_221152_)) { -- int j = Math.min(p_221155_ + p_221154_.nextInt(5) / 4, 15); -- p_221151_.setBlock(p_221152_, this.getStateWithAge(p_221151_, p_221152_, j), 3); -- } else { -- p_221151_.removeBlock(p_221152_, false); -- } -+ private void tryCatchFire(Level p_53432_, BlockPos p_53433_, int p_53434_, RandomSource p_53435_, int p_53436_, Direction face) { -+ int i = p_53432_.getBlockState(p_53433_).getFlammability(p_53432_, p_53433_, face); -+ if (p_53435_.nextInt(p_53434_) < i) { -+ BlockState blockstate = p_53432_.getBlockState(p_53433_); -+ blockstate.onCaughtFire(p_53432_, p_53433_, face, null); +- private void checkBurnOut(Level p_221151_, BlockPos p_221152_, int p_221153_, RandomSource p_221154_, int p_221155_) { +- int i = this.getBurnOdds(p_221151_.getBlockState(p_221152_)); ++ private void checkBurnOut(Level p_221151_, BlockPos p_221152_, int p_221153_, RandomSource p_221154_, int p_221155_, Direction face) { ++ int i = p_221151_.getBlockState(p_221152_).getFlammability(p_221151_, p_221152_, face); + if (p_221154_.nextInt(p_221153_) < i) { + BlockState blockstate = p_221151_.getBlockState(p_221152_); ++ blockstate.onCaughtFire(p_221151_, p_221152_, face, null); + if (p_221154_.nextInt(p_221155_ + 10) < 5 && !p_221151_.isRainingAt(p_221152_)) { + int j = Math.min(p_221155_ + p_221154_.nextInt(5) / 4, 15); + p_221151_.setBlock(p_221152_, this.getStateWithAge(p_221151_, p_221152_, j), 3); + } else { + p_221151_.removeBlock(p_221152_, false); + } +- +- Block block = blockstate.getBlock(); +- if (block instanceof TntBlock) { +- TntBlock.explode(p_221151_, p_221152_); +- } + } + } -- Block block = blockstate.getBlock(); -- if (block instanceof TntBlock) { -- TntBlock.explode(p_221151_, p_221152_); -+ if (p_53435_.nextInt(p_53434_ + 10) < 5 && !p_53432_.isRainingAt(p_53433_)) { -+ int j = Math.min(p_53434_ + p_53435_.nextInt(5) / 4, 15); -+ p_53432_.setBlock(p_53433_, this.getStateWithAge(p_53432_, p_53433_, j), 3); -+ } else { -+ p_53432_.removeBlock(p_53433_, false); - } - } +@@ -275,7 +_,7 @@ -@@ -245,7 +_,7 @@ + private boolean isValidFireLocation(BlockGetter p_53486_, BlockPos p_53487_) { + for (Direction direction : Direction.values()) { +- if (this.canBurn(p_53486_.getBlockState(p_53487_.relative(direction)))) { ++ if (this.canCatchFire(p_53486_, p_53487_.relative(direction), direction.getOpposite())) { + return true; + } + } +@@ -291,13 +_,14 @@ - private boolean isValidFireLocation(BlockGetter p_53486_, BlockPos p_53487_) { - for(Direction direction : Direction.values()) { -- if (this.canBurn(p_53486_.getBlockState(p_53487_.relative(direction)))) { -+ if (this.canCatchFire(p_53486_, p_53487_.relative(direction), direction.getOpposite())) { - return true; - } - } -@@ -261,13 +_,14 @@ + for (Direction direction : Direction.values()) { + BlockState blockstate = p_221157_.getBlockState(p_221158_.relative(direction)); +- i = Math.max(this.getIgniteOdds(blockstate), i); ++ i = Math.max(blockstate.getFireSpreadSpeed(p_221157_, p_221158_.relative(direction), direction.getOpposite()), i); + } - for(Direction direction : Direction.values()) { - BlockState blockstate = p_221157_.getBlockState(p_221158_.relative(direction)); -- i = Math.max(this.getIgniteOdds(blockstate), i); -+ i = Math.max(blockstate.getFireSpreadSpeed(p_221157_, p_221158_.relative(direction), direction.getOpposite()), i); - } + return i; + } + } - return i; - } - } ++ @Deprecated //Forge: Use canCatchFire with more context + @Override + protected boolean canBurn(BlockState p_53489_) { + return this.getIgniteOdds(p_53489_) > 0; +@@ -319,8 +_,21 @@ + } -+ @Deprecated //Forge: Use canCatchFire with more context - protected boolean canBurn(BlockState p_53489_) { - return this.getIgniteOdds(p_53489_) > 0; - } -@@ -286,8 +_,21 @@ - } - - public void setFlammable(Block p_53445_, int p_53446_, int p_53447_) { -+ if (p_53445_ == Blocks.AIR) throw new IllegalArgumentException("Tried to set air on fire... This is bad."); - this.igniteOdds.put(p_53445_, p_53446_); - this.burnOdds.put(p_53445_, p_53447_); -+ } + public void setFlammable(Block p_53445_, int p_53446_, int p_53447_) { ++ if (p_53445_ == Blocks.AIR) throw new IllegalArgumentException("Tried to set air on fire... This is bad."); + this.igniteOdds.put(p_53445_, p_53446_); + this.burnOdds.put(p_53445_, p_53447_); ++ } + -+ /** -+ * Side sensitive version that calls the block function. -+ * -+ * @param world The current world -+ * @param pos Block position -+ * @param face The side the fire is coming from -+ * @return True if the face can catch fire. -+ */ -+ public boolean canCatchFire(BlockGetter world, BlockPos pos, Direction face) { -+ return world.getBlockState(pos).isFlammable(world, pos, face); - } ++ /** ++ * Side sensitive version that calls the block function. ++ * ++ * @param world The current world ++ * @param pos Block position ++ * @param face The side the fire is coming from ++ * @return True if the face can catch fire. ++ */ ++ public boolean canCatchFire(BlockGetter world, BlockPos pos, Direction face) { ++ return world.getBlockState(pos).isFlammable(world, pos, face); + } - public static void bootStrap() { + public static void bootStrap() { diff --git a/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch index 3b46e57566..ddf177ad84 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch @@ -1,88 +1,87 @@ --- a/net/minecraft/world/level/block/FlowerPotBlock.java +++ b/net/minecraft/world/level/block/FlowerPotBlock.java -@@ -41,10 +_,33 @@ - return CODEC; - } +@@ -43,9 +_,31 @@ + } -+ @Deprecated // Mods should use the constructor below - public FlowerPotBlock(Block p_53528_, BlockBehaviour.Properties p_53529_) { -- super(p_53529_); -- this.potted = p_53528_; -- POTTED_BY_CONTENT.put(p_53528_, this); -+ this(Blocks.FLOWER_POT == null ? null : () -> (FlowerPotBlock) net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.FLOWER_POT).get(), () -> net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_53528_).get(), p_53529_); -+ if (Blocks.FLOWER_POT != null) { -+ ((FlowerPotBlock)Blocks.FLOWER_POT).addPlant(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(p_53528_), () -> this); -+ } -+ } + public FlowerPotBlock(Block p_53528_, BlockBehaviour.Properties p_53529_) { +- super(p_53529_); +- this.potted = p_53528_; +- POTTED_BY_CONTENT.put(p_53528_, this); ++ this(Blocks.FLOWER_POT == null ? null : () -> (FlowerPotBlock) net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.FLOWER_POT).get(), () -> net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_53528_).get(), p_53529_); ++ if (Blocks.FLOWER_POT != null) { ++ ((FlowerPotBlock)Blocks.FLOWER_POT).addPlant(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(p_53528_), () -> this); ++ } ++ } + -+ /** -+ * For mod use, eliminates the need to extend this class, and prevents modded -+ * flower pots from altering vanilla behavior. -+ * -+ * @param emptyPot The empty pot for this pot, or null for self. -+ * @param p_53528_ The flower block. -+ * @param properties -+ */ -+ public FlowerPotBlock(@org.jetbrains.annotations.Nullable java.util.function.Supplier emptyPot, java.util.function.Supplier p_53528_, BlockBehaviour.Properties properties) { -+ super(properties); -+ this.potted = null; // Unused, redirected by coremod -+ this.flowerDelegate = p_53528_; -+ if (emptyPot == null) { -+ this.fullPots = Maps.newHashMap(); -+ this.emptyPot = null; -+ } else { -+ this.fullPots = java.util.Collections.emptyMap(); -+ this.emptyPot = emptyPot; -+ } - } ++ /** ++ * For mod use, eliminates the need to extend this class, and prevents modded ++ * flower pots from altering vanilla behavior. ++ * ++ * @param emptyPot The empty pot for this pot, or null for self. ++ * @param p_53528_ The flower block. ++ * @param properties ++ */ ++ public FlowerPotBlock(@org.jetbrains.annotations.Nullable java.util.function.Supplier emptyPot, java.util.function.Supplier p_53528_, BlockBehaviour.Properties properties) { ++ super(properties); ++ this.potted = null; // Unused, redirected by coremod ++ this.flowerDelegate = p_53528_; ++ if (emptyPot == null) { ++ this.fullPots = Maps.newHashMap(); ++ this.emptyPot = null; ++ } else { ++ this.fullPots = java.util.Collections.emptyMap(); ++ this.emptyPot = emptyPot; ++ } + } - public VoxelShape getShape(BlockState p_53556_, BlockGetter p_53557_, BlockPos p_53558_, CollisionContext p_53559_) { + @Override @@ -58,7 +_,7 @@ - public InteractionResult use(BlockState p_53540_, Level p_53541_, BlockPos p_53542_, Player p_53543_, InteractionHand p_53544_, BlockHitResult p_53545_) { - ItemStack itemstack = p_53543_.getItemInHand(p_53544_); - Item item = itemstack.getItem(); -- BlockState blockstate = (item instanceof BlockItem ? POTTED_BY_CONTENT.getOrDefault(((BlockItem)item).getBlock(), Blocks.AIR) : Blocks.AIR).defaultBlockState(); -+ BlockState blockstate = (item instanceof BlockItem ? getEmptyPot().fullPots.getOrDefault(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(((BlockItem)item).getBlock()), net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR)).get() : Blocks.AIR).defaultBlockState(); - boolean flag = blockstate.is(Blocks.AIR); - boolean flag1 = this.isEmpty(); - if (flag != flag1) { -@@ -76,7 +_,7 @@ - p_53543_.drop(itemstack1, false); + ItemStack p_329639_, BlockState p_328047_, Level p_328816_, BlockPos p_334572_, Player p_329206_, InteractionHand p_329142_, BlockHitResult p_330607_ + ) { + BlockState blockstate = (p_329639_.getItem() instanceof BlockItem blockitem +- ? POTTED_BY_CONTENT.getOrDefault(blockitem.getBlock(), Blocks.AIR) ++ ? getEmptyPot().fullPots.getOrDefault(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(blockitem.getBlock()), net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR)).get() + : Blocks.AIR) + .defaultBlockState(); + if (blockstate.isAir()) { +@@ -84,7 +_,7 @@ + p_333787_.drop(itemstack, false); } -- p_53541_.setBlock(p_53542_, Blocks.FLOWER_POT.defaultBlockState(), 3); -+ p_53541_.setBlock(p_53542_, getEmptyPot().defaultBlockState(), 3); - } +- p_334489_.setBlock(p_330334_, Blocks.FLOWER_POT.defaultBlockState(), 3); ++ p_334489_.setBlock(p_330334_, getEmptyPot().defaultBlockState(), 3); + p_334489_.gameEvent(p_333787_, GameEvent.BLOCK_CHANGE, p_330334_); + return InteractionResult.sidedSuccess(p_334489_.isClientSide); + } +@@ -107,11 +_,30 @@ + } - p_53541_.gameEvent(p_53543_, GameEvent.BLOCK_CHANGE, p_53542_); -@@ -99,10 +_,29 @@ - } + public Block getPotted() { +- return this.potted; ++ return flowerDelegate.get(); + } - public Block getPotted() { -- return this.potted; -+ return flowerDelegate.get(); - } - - public boolean isPathfindable(BlockState p_53535_, BlockGetter p_53536_, BlockPos p_53537_, PathComputationType p_53538_) { - return false; -+ } + @Override + protected boolean isPathfindable(BlockState p_53535_, PathComputationType p_53538_) { + return false; ++ } + -+ private final Map> fullPots; -+ private final java.util.function.Supplier emptyPot; -+ private final java.util.function.Supplier flowerDelegate; ++ private final Map> fullPots; ++ private final java.util.function.Supplier emptyPot; ++ private final java.util.function.Supplier flowerDelegate; + -+ public FlowerPotBlock getEmptyPot() { -+ return emptyPot == null ? this : emptyPot.get(); -+ } ++ public FlowerPotBlock getEmptyPot() { ++ return emptyPot == null ? this : emptyPot.get(); ++ } + -+ public void addPlant(net.minecraft.resources.ResourceLocation flower, java.util.function.Supplier fullPot) { -+ if (getEmptyPot() != this) { -+ throw new IllegalArgumentException("Cannot add plant to non-empty pot: " + this); -+ } -+ fullPots.put(flower, fullPot); -+ } ++ public void addPlant(net.minecraft.resources.ResourceLocation flower, java.util.function.Supplier fullPot) { ++ if (getEmptyPot() != this) { ++ throw new IllegalArgumentException("Cannot add plant to non-empty pot: " + this); ++ } ++ fullPots.put(flower, fullPot); ++ } + -+ public Map> getFullPotsView() { -+ return java.util.Collections.unmodifiableMap(fullPots); - } ++ public Map> getFullPotsView() { ++ return java.util.Collections.unmodifiableMap(fullPots); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/FungusBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FungusBlock.java.patch index e9036bc5c7..40c9160951 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FungusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FungusBlock.java.patch @@ -1,13 +1,14 @@ --- a/net/minecraft/world/level/block/FungusBlock.java +++ b/net/minecraft/world/level/block/FungusBlock.java -@@ -66,7 +_,9 @@ +@@ -76,6 +_,10 @@ - public void performBonemeal(ServerLevel p_221243_, RandomSource p_221244_, BlockPos p_221245_, BlockState p_221246_) { - this.getFeature(p_221243_).ifPresent((p_256352_) -> { -- p_256352_.value().place(p_221243_, p_221243_.getChunkSource().getGenerator(), p_221244_, p_221245_); -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_221243_, p_221244_, p_221245_, p_256352_); -+ if (event.getResult().equals(net.minecraftforge.eventbus.api.Event.Result.DENY)) return; -+ event.getFeature().value().place(p_221243_, p_221243_.getChunkSource().getGenerator(), p_221244_, p_221245_); - }); - } + @Override + public void performBonemeal(ServerLevel p_221243_, RandomSource p_221244_, BlockPos p_221245_, BlockState p_221246_) { +- this.getFeature(p_221243_).ifPresent(p_256352_ -> p_256352_.value().place(p_221243_, p_221243_.getChunkSource().getGenerator(), p_221244_, p_221245_)); ++ this.getFeature(p_221243_).ifPresent(p_256352_ -> { ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_221243_, p_221244_, p_221245_, p_256352_); ++ if (event.getResult().equals(net.minecraftforge.eventbus.api.Event.Result.DENY)) return; ++ event.getFeature().value().place(p_221243_, p_221243_.getChunkSource().getGenerator(), p_221244_, p_221245_); ++ }); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch index f410eacc1d..9a16ca6843 100644 --- a/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch @@ -1,15 +1,17 @@ --- a/net/minecraft/world/level/block/GrowingPlantHeadBlock.java +++ b/net/minecraft/world/level/block/GrowingPlantHeadBlock.java -@@ -38,10 +_,11 @@ - } - - public void randomTick(BlockState p_221350_, ServerLevel p_221351_, BlockPos p_221352_, RandomSource p_221353_) { -- if (p_221350_.getValue(AGE) < 25 && p_221353_.nextDouble() < this.growPerTickProbability) { -+ if (p_221350_.getValue(AGE) < 25 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221351_, p_221352_.relative(this.growthDirection), p_221351_.getBlockState(p_221352_.relative(this.growthDirection)),p_221353_.nextDouble() < this.growPerTickProbability)) { - BlockPos blockpos = p_221352_.relative(this.growthDirection); - if (this.canGrowInto(p_221351_.getBlockState(blockpos))) { - p_221351_.setBlockAndUpdate(blockpos, this.getGrowIntoState(p_221350_, p_221351_.random)); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221351_, blockpos, p_221351_.getBlockState(blockpos)); - } - } +@@ -42,10 +_,13 @@ + @Override + protected void randomTick(BlockState p_221350_, ServerLevel p_221351_, BlockPos p_221352_, RandomSource p_221353_) { +- if (p_221350_.getValue(AGE) < 25 && p_221353_.nextDouble() < this.growPerTickProbability) { ++ var vanilla = p_221353_.nextDouble() < this.growPerTickProbability; ++ var target = p_221352_.relative(this.growthDirection); ++ if (p_221350_.getValue(AGE) < 25 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221351_, target, p_221351_.getBlockState(target), vanilla)) { + BlockPos blockpos = p_221352_.relative(this.growthDirection); + if (this.canGrowInto(p_221351_.getBlockState(blockpos))) { + p_221351_.setBlockAndUpdate(blockpos, this.getGrowIntoState(p_221350_, p_221351_.random)); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221351_, blockpos, p_221351_.getBlockState(blockpos)); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/LeavesBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/LeavesBlock.java.patch index 9f6fb33003..8e6f4c0603 100644 --- a/patches/minecraft/net/minecraft/world/level/block/LeavesBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/LeavesBlock.java.patch @@ -6,6 +6,6 @@ -public class LeavesBlock extends Block implements SimpleWaterloggedBlock { +public class LeavesBlock extends Block implements SimpleWaterloggedBlock, net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(LeavesBlock::new); - public static final int DECAY_DISTANCE = 7; - public static final IntegerProperty DISTANCE = BlockStateProperties.DISTANCE; + public static final MapCodec CODEC = simpleCodec(LeavesBlock::new); + public static final int DECAY_DISTANCE = 7; + public static final IntegerProperty DISTANCE = BlockStateProperties.DISTANCE; diff --git a/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch index b309f6376b..d53a83a399 100644 --- a/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch @@ -1,98 +1,96 @@ --- a/net/minecraft/world/level/block/LiquidBlock.java +++ b/net/minecraft/world/level/block/LiquidBlock.java -@@ -56,7 +_,8 @@ - }), propertiesCodec()).apply(p_310157_, LiquidBlock::new); - }); - public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; -- protected final FlowingFluid fluid; -+ @Deprecated // Use getFluid -+ private final FlowingFluid fluid; - private final List stateCache; - public static final VoxelShape STABLE_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D); - public static final ImmutableList POSSIBLE_FLOW_DIRECTIONS = ImmutableList.of(Direction.DOWN, Direction.SOUTH, Direction.NORTH, Direction.EAST, Direction.WEST); -@@ -65,6 +_,7 @@ - return CODEC; - } +@@ -50,7 +_,8 @@ + p_310157_ -> p_310157_.group(FLOWING_FLUID.fieldOf("fluid").forGetter(p_312827_ -> p_312827_.fluid), propertiesCodec()).apply(p_310157_, LiquidBlock::new) + ); + public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; +- protected final FlowingFluid fluid; ++ @Deprecated // Use getFluid ++ private final FlowingFluid fluid; + private final List stateCache; + public static final VoxelShape STABLE_SHAPE = Block.box(0.0, 0.0, 0.0, 16.0, 8.0, 16.0); + public static final ImmutableList POSSIBLE_FLOW_DIRECTIONS = ImmutableList.of(Direction.DOWN, Direction.SOUTH, Direction.NORTH, Direction.EAST, Direction.WEST); +@@ -60,6 +_,7 @@ + return CODEC; + } -+ @Deprecated // Forge: Use the constructor that takes a supplier - public LiquidBlock(FlowingFluid p_54694_, BlockBehaviour.Properties p_54695_) { - super(p_54695_); - this.fluid = p_54694_; -@@ -77,6 +_,19 @@ ++ @Deprecated // Forge: Use the constructor that takes a supplier + public LiquidBlock(FlowingFluid p_54694_, BlockBehaviour.Properties p_54695_) { + super(p_54695_); + this.fluid = p_54694_; +@@ -72,6 +_,19 @@ - this.stateCache.add(p_54694_.getFlowing(8, true)); - this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, Integer.valueOf(0))); -+ fluidStateCacheInitialized = true; -+ supplier = net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_54694_); -+ } + this.stateCache.add(p_54694_.getFlowing(8, true)); + this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, Integer.valueOf(0))); ++ fluidStateCacheInitialized = true; ++ supplier = () -> p_54694_; ++ } + -+ /** -+ * @param p_54694_ A fluid supplier such as {@link net.minecraftforge.registries.RegistryObject} -+ */ -+ public LiquidBlock(java.util.function.Supplier p_54694_, BlockBehaviour.Properties p_54695_) { -+ super(p_54695_); -+ this.fluid = null; -+ this.stateCache = Lists.newArrayList(); -+ this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, Integer.valueOf(0))); -+ this.supplier = p_54694_; - } ++ /** ++ * @param p_54694_ A fluid supplier such as {@link net.minecraftforge.registries.RegistryObject} ++ */ ++ public LiquidBlock(java.util.function.Supplier p_54694_, BlockBehaviour.Properties p_54695_) { ++ super(p_54695_); ++ this.fluid = null; ++ this.stateCache = Lists.newArrayList(); ++ this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, Integer.valueOf(0))); ++ this.supplier = p_54694_; + } - public VoxelShape getCollisionShape(BlockState p_54760_, BlockGetter p_54761_, BlockPos p_54762_, CollisionContext p_54763_) { -@@ -101,6 +_,7 @@ + @Override +@@ -106,6 +_,7 @@ + @Override + protected FluidState getFluidState(BlockState p_54765_) { + int i = p_54765_.getValue(LEVEL); ++ if (!fluidStateCacheInitialized) initFluidStateCache(); + return this.stateCache.get(Math.min(i, 8)); + } - public FluidState getFluidState(BlockState p_54765_) { - int i = p_54765_.getValue(LEVEL); -+ if (!fluidStateCacheInitialized) initFluidStateCache(); - return this.stateCache.get(Math.min(i, 8)); - } +@@ -131,7 +_,7 @@ -@@ -121,7 +_,7 @@ - } + @Override + protected void onPlace(BlockState p_54754_, Level p_54755_, BlockPos p_54756_, BlockState p_54757_, boolean p_54758_) { +- if (this.shouldSpreadLiquid(p_54755_, p_54756_, p_54754_)) { ++ if (!net.minecraftforge.fluids.FluidInteractionRegistry.canInteract(p_54755_, p_54756_)) { + p_54755_.scheduleTick(p_54756_, p_54754_.getFluidState().getType(), this.fluid.getTickDelay(p_54755_)); + } + } +@@ -147,11 +_,12 @@ - public void onPlace(BlockState p_54754_, Level p_54755_, BlockPos p_54756_, BlockState p_54757_, boolean p_54758_) { -- if (this.shouldSpreadLiquid(p_54755_, p_54756_, p_54754_)) { -+ if (!net.minecraftforge.fluids.FluidInteractionRegistry.canInteract(p_54755_, p_54756_)) { - p_54755_.scheduleTick(p_54756_, p_54754_.getFluidState().getType(), this.fluid.getTickDelay(p_54755_)); - } + @Override + protected void neighborChanged(BlockState p_54709_, Level p_54710_, BlockPos p_54711_, Block p_54712_, BlockPos p_54713_, boolean p_54714_) { +- if (this.shouldSpreadLiquid(p_54710_, p_54711_, p_54709_)) { ++ if (!net.minecraftforge.fluids.FluidInteractionRegistry.canInteract(p_54710_, p_54711_)) { + p_54710_.scheduleTick(p_54711_, p_54709_.getFluidState().getType(), this.fluid.getTickDelay(p_54710_)); + } + } -@@ -136,12 +_,13 @@ - } - - public void neighborChanged(BlockState p_54709_, Level p_54710_, BlockPos p_54711_, Block p_54712_, BlockPos p_54713_, boolean p_54714_) { -- if (this.shouldSpreadLiquid(p_54710_, p_54711_, p_54709_)) { -+ if (!net.minecraftforge.fluids.FluidInteractionRegistry.canInteract(p_54710_, p_54711_)) { - p_54710_.scheduleTick(p_54711_, p_54709_.getFluidState().getType(), this.fluid.getTickDelay(p_54710_)); - } - - } - -+ @Deprecated // FORGE: Use FluidInteractionRegistry#canInteract instead - private boolean shouldSpreadLiquid(Level p_54697_, BlockPos p_54698_, BlockState p_54699_) { - if (this.fluid.is(FluidTags.LAVA)) { - boolean flag = p_54697_.getBlockState(p_54698_.below()).is(Blocks.SOUL_SOIL); -@@ -180,6 +_,25 @@ - return new ItemStack(this.fluid.getBucket()); - } else { - return ItemStack.EMPTY; -+ } -+ } ++ @Deprecated // FORGE: Use FluidInteractionRegistry#canInteract instead + private boolean shouldSpreadLiquid(Level p_54697_, BlockPos p_54698_, BlockState p_54699_) { + if (this.fluid.is(FluidTags.LAVA)) { + boolean flag = p_54697_.getBlockState(p_54698_.below()).is(Blocks.SOUL_SOIL); +@@ -198,5 +_,24 @@ + @Override + public Optional getPickupSound() { + return this.fluid.getPickupSound(); ++ } + -+ // Forge start -+ private final java.util.function.Supplier supplier; -+ public FlowingFluid getFluid() { -+ return (FlowingFluid)supplier.get(); -+ } ++ private final java.util.function.Supplier supplier; ++ public FlowingFluid getFluid() { ++ return (FlowingFluid)supplier.get(); ++ } + -+ private boolean fluidStateCacheInitialized = false; -+ protected synchronized void initFluidStateCache() { -+ if (fluidStateCacheInitialized == false) { -+ this.stateCache.add(getFluid().getSource(false)); ++ private boolean fluidStateCacheInitialized = false; ++ protected synchronized void initFluidStateCache() { ++ if (fluidStateCacheInitialized == false) { ++ this.stateCache.add(getFluid().getSource(false)); + -+ for (int i = 1; i < 8; ++i) -+ this.stateCache.add(getFluid().getFlowing(8 - i, false)); ++ for (int i = 1; i < 8; ++i) { ++ this.stateCache.add(getFluid().getFlowing(8 - i, false)); ++ } + -+ this.stateCache.add(getFluid().getFlowing(8, true)); -+ fluidStateCacheInitialized = true; - } - } - ++ this.stateCache.add(getFluid().getFlowing(8, true)); ++ fluidStateCacheInitialized = true; ++ } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch index 519df2145c..491f3e347b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/world/level/block/MushroomBlock.java +++ b/net/minecraft/world/level/block/MushroomBlock.java @@ -83,7 +_,7 @@ - if (blockstate.is(BlockTags.MUSHROOM_GROW_BLOCK)) { - return true; - } else { -- return p_54881_.getRawBrightness(p_54882_, 0) < 13 && this.mayPlaceOn(blockstate, p_54881_, blockpos); -+ return p_54881_.getRawBrightness(p_54882_, 0) < 13 && blockstate.canSustainPlant(p_54881_, blockpos, net.minecraft.core.Direction.UP, this); - } - } + protected boolean canSurvive(BlockState p_54880_, LevelReader p_54881_, BlockPos p_54882_) { + BlockPos blockpos = p_54882_.below(); + BlockState blockstate = p_54881_.getBlockState(blockpos); +- return blockstate.is(BlockTags.MUSHROOM_GROW_BLOCK) ? true : p_54881_.getRawBrightness(p_54882_, 0) < 13 && this.mayPlaceOn(blockstate, p_54881_, blockpos); ++ return blockstate.is(BlockTags.MUSHROOM_GROW_BLOCK) ? true : p_54881_.getRawBrightness(p_54882_, 0) < 13 && blockstate.canSustainPlant(p_54881_, blockpos, net.minecraft.core.Direction.UP, this); + } -@@ -92,8 +_,10 @@ - if (optional.isEmpty()) { - return false; - } else { -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_221774_, p_221777_, p_221775_, optional.get()); -+ if (event.getResult().equals(net.minecraftforge.eventbus.api.Event.Result.DENY)) return false; - p_221774_.removeBlock(p_221775_, false); -- if (optional.get().value().place(p_221774_, p_221774_.getChunkSource().getGenerator(), p_221777_, p_221775_)) { -+ if (event.getFeature().value().place(p_221774_, p_221774_.getChunkSource().getGenerator(), p_221777_, p_221775_)) { - return true; - } else { - p_221774_.setBlock(p_221775_, p_221776_, 3); + public boolean growMushroom(ServerLevel p_221774_, BlockPos p_221775_, BlockState p_221776_, RandomSource p_221777_) { +@@ -91,8 +_,10 @@ + if (optional.isEmpty()) { + return false; + } else { ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_221774_, p_221777_, p_221775_, optional.get()); ++ if (event.getResult().equals(net.minecraftforge.eventbus.api.Event.Result.DENY)) return false; + p_221774_.removeBlock(p_221775_, false); +- if (optional.get().value().place(p_221774_, p_221774_.getChunkSource().getGenerator(), p_221777_, p_221775_)) { ++ if (event.getFeature().value().place(p_221774_, p_221774_.getChunkSource().getGenerator(), p_221777_, p_221775_)) { + return true; + } else { + p_221774_.setBlock(p_221775_, p_221776_, 3); diff --git a/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch index 3b8fc80e29..67f48fc3e1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/NetherWartBlock.java +++ b/net/minecraft/world/level/block/NetherWartBlock.java -@@ -45,9 +_,10 @@ +@@ -55,9 +_,10 @@ + @Override + protected void randomTick(BlockState p_221806_, ServerLevel p_221807_, BlockPos p_221808_, RandomSource p_221809_) { + int i = p_221806_.getValue(AGE); +- if (i < 3 && p_221809_.nextInt(10) == 0) { ++ if (i < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221807_, p_221808_, p_221806_, p_221809_.nextInt(10) == 0)) { + p_221806_ = p_221806_.setValue(AGE, Integer.valueOf(i + 1)); + p_221807_.setBlock(p_221808_, p_221806_, 2); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221807_, p_221808_, p_221806_); + } + } - public void randomTick(BlockState p_221806_, ServerLevel p_221807_, BlockPos p_221808_, RandomSource p_221809_) { - int i = p_221806_.getValue(AGE); -- if (i < 3 && p_221809_.nextInt(10) == 0) { -+ if (i < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_221807_, p_221808_, p_221806_, p_221809_.nextInt(10) == 0)) { - p_221806_ = p_221806_.setValue(AGE, Integer.valueOf(i + 1)); - p_221807_.setBlock(p_221808_, p_221806_, 2); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_221807_, p_221808_, p_221806_); - } - - } diff --git a/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch index 3b04944441..1eecf2fbef 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/world/level/block/NoteBlock.java +++ b/net/minecraft/world/level/block/NoteBlock.java -@@ -95,7 +_,9 @@ - } else if (p_55035_.isClientSide) { - return InteractionResult.SUCCESS; - } else { -- p_55034_ = p_55034_.cycle(NOTE); -+ int _new = net.minecraftforge.common.ForgeHooks.onNoteChange(p_55035_, p_55036_, p_55034_, p_55034_.getValue(NOTE), p_55034_.cycle(NOTE).getValue(NOTE)); -+ if (_new == -1) return InteractionResult.FAIL; -+ p_55034_ = p_55034_.setValue(NOTE, _new); - p_55035_.setBlock(p_55036_, p_55034_, 3); - this.playNote(p_55037_, p_55034_, p_55035_, p_55036_); - p_55037_.awardStat(Stats.TUNE_NOTEBLOCK); -@@ -115,6 +_,9 @@ - } +@@ -110,7 +_,9 @@ + if (p_332131_.isClientSide) { + return InteractionResult.SUCCESS; + } else { +- p_331116_ = p_331116_.cycle(NOTE); ++ int _new = net.minecraftforge.common.ForgeHooks.onNoteChange(p_332131_, p_333586_, p_331116_, p_331116_.getValue(NOTE), p_331116_.cycle(NOTE).getValue(NOTE)); ++ if (_new == -1) return InteractionResult.FAIL; ++ p_331116_ = p_331116_.setValue(NOTE, _new); + p_332131_.setBlock(p_333586_, p_331116_, 3); + this.playNote(p_329332_, p_331116_, p_332131_, p_333586_); + p_329332_.awardStat(Stats.TUNE_NOTEBLOCK); +@@ -132,6 +_,9 @@ - public boolean triggerEvent(BlockState p_55023_, Level p_55024_, BlockPos p_55025_, int p_55026_, int p_55027_) { -+ net.minecraftforge.event.level.NoteBlockEvent.Play e = new net.minecraftforge.event.level.NoteBlockEvent.Play(p_55024_, p_55025_, p_55023_, p_55023_.getValue(NOTE), p_55023_.getValue(INSTRUMENT)); -+ if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(e)) return false; -+ p_55023_ = p_55023_.setValue(NOTE, e.getVanillaNoteId()).setValue(INSTRUMENT, e.getInstrument()); - NoteBlockInstrument noteblockinstrument = p_55023_.getValue(INSTRUMENT); - float f; - if (noteblockinstrument.isTunable()) { + @Override + protected boolean triggerEvent(BlockState p_55023_, Level p_55024_, BlockPos p_55025_, int p_55026_, int p_55027_) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onNotePlay(p_55024_, p_55025_, p_55023_, p_55023_.getValue(NOTE), p_55023_.getValue(INSTRUMENT)); ++ if (event.isCanceled()) return false; ++ p_55023_ = p_55023_.setValue(NOTE, event.getVanillaNoteId()).setValue(INSTRUMENT, event.getInstrument()); + NoteBlockInstrument noteblockinstrument = p_55023_.getValue(INSTRUMENT); + float f; + if (noteblockinstrument.isTunable()) { diff --git a/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch index 89e5762be9..29c7e6ca18 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/PowderSnowBlock.java +++ b/net/minecraft/world/level/block/PowderSnowBlock.java -@@ -114,7 +_,7 @@ - if (p_154256_.getType().is(EntityTypeTags.POWDER_SNOW_WALKABLE_MOBS)) { - return true; - } else { -- return p_154256_ instanceof LivingEntity ? ((LivingEntity)p_154256_).getItemBySlot(EquipmentSlot.FEET).is(Items.LEATHER_BOOTS) : false; -+ return p_154256_ instanceof LivingEntity ? ((LivingEntity)p_154256_).getItemBySlot(EquipmentSlot.FEET).canWalkOnPowderedSnow((LivingEntity)p_154256_) : false; - } - } +@@ -130,7 +_,7 @@ + if (p_154256_.getType().is(EntityTypeTags.POWDER_SNOW_WALKABLE_MOBS)) { + return true; + } else { +- return p_154256_ instanceof LivingEntity ? ((LivingEntity)p_154256_).getItemBySlot(EquipmentSlot.FEET).is(Items.LEATHER_BOOTS) : false; ++ return p_154256_ instanceof LivingEntity ? ((LivingEntity)p_154256_).getItemBySlot(EquipmentSlot.FEET).canWalkOnPowderedSnow((LivingEntity)p_154256_) : false; + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch index f3277b768b..f375117360 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch @@ -1,85 +1,90 @@ --- a/net/minecraft/world/level/block/PoweredRailBlock.java +++ b/net/minecraft/world/level/block/PoweredRailBlock.java -@@ -16,13 +_,23 @@ - public static final MapCodec CODEC = simpleCodec(PoweredRailBlock::new); - public static final EnumProperty SHAPE = BlockStateProperties.RAIL_SHAPE_STRAIGHT; - public static final BooleanProperty POWERED = BlockStateProperties.POWERED; -+ private final boolean isActivator; // TRUE for an Activator Rail, FALSE for Powered Rail +@@ -16,6 +_,7 @@ + public static final MapCodec CODEC = simpleCodec(PoweredRailBlock::new); + public static final EnumProperty SHAPE = BlockStateProperties.RAIL_SHAPE_STRAIGHT; + public static final BooleanProperty POWERED = BlockStateProperties.POWERED; ++ private final boolean isActivator; // TRUE for an Activator Rail, FALSE for Powered Rail - public MapCodec codec() { - return CODEC; - } + @Override + public MapCodec codec() { +@@ -23,7 +_,16 @@ + } - public PoweredRailBlock(BlockBehaviour.Properties p_55218_) { -+ this(p_55218_, false); -+ } + public PoweredRailBlock(BlockBehaviour.Properties p_55218_) { ++ this(p_55218_, false); ++ } + -+ protected PoweredRailBlock(BlockBehaviour.Properties p_55218_, boolean isPoweredRail) { - super(true, p_55218_); -+ this.isActivator = !isPoweredRail; -+ this.registerDefaultState(); -+ } ++ protected PoweredRailBlock(BlockBehaviour.Properties p_55218_, boolean isPoweredRail) { + super(true, p_55218_); ++ this.isActivator = !isPoweredRail; ++ this.registerDefaultState(); ++ } + -+ protected void registerDefaultState() { - this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, RailShape.NORTH_SOUTH).setValue(POWERED, Boolean.valueOf(false)).setValue(WATERLOGGED, Boolean.valueOf(false))); - } ++ protected void registerDefaultState() { + this.registerDefaultState( + this.stateDefinition + .any() +@@ -41,7 +_,7 @@ + int j = p_55221_.getY(); + int k = p_55221_.getZ(); + boolean flag = true; +- RailShape railshape = p_55222_.getValue(SHAPE); ++ RailShape railshape = p_55222_.getValue(getShapeProperty()); + switch (railshape) { + case NORTH_SOUTH: + if (p_55223_) { +@@ -110,18 +_,18 @@ -@@ -34,7 +_,7 @@ - int j = p_55221_.getY(); - int k = p_55221_.getZ(); - boolean flag = true; -- RailShape railshape = p_55222_.getValue(SHAPE); -+ RailShape railshape = p_55222_.getValue(getShapeProperty()); - switch (railshape) { - case NORTH_SOUTH: - if (p_55223_) { -@@ -105,14 +_,14 @@ - - protected boolean isSameRailWithPower(Level p_55226_, BlockPos p_55227_, boolean p_55228_, int p_55229_, RailShape p_55230_) { - BlockState blockstate = p_55226_.getBlockState(p_55227_); -- if (!blockstate.is(this)) { -+ if (!(blockstate.getBlock() instanceof PoweredRailBlock other)) { - return false; - } else { -- RailShape railshape = blockstate.getValue(SHAPE); -+ RailShape railshape = other.getRailDirection(blockstate, p_55226_, p_55227_, null); - if (p_55230_ != RailShape.EAST_WEST || railshape != RailShape.NORTH_SOUTH && railshape != RailShape.ASCENDING_NORTH && railshape != RailShape.ASCENDING_SOUTH) { - if (p_55230_ != RailShape.NORTH_SOUTH || railshape != RailShape.EAST_WEST && railshape != RailShape.ASCENDING_EAST && railshape != RailShape.ASCENDING_WEST) { -- if (blockstate.getValue(POWERED)) { -- return p_55226_.hasNeighborSignal(p_55227_) ? true : this.findPoweredRailSignal(p_55226_, p_55227_, blockstate, p_55228_, p_55229_ + 1); -+ if (isActivatorRail() == other.isActivatorRail()) { -+ return p_55226_.hasNeighborSignal(p_55227_) ? true : other.findPoweredRailSignal(p_55226_, p_55227_, blockstate, p_55228_, p_55229_ + 1); - } else { - return false; - } -@@ -131,7 +_,7 @@ - if (flag1 != flag) { - p_55233_.setBlock(p_55234_, p_55232_.setValue(POWERED, Boolean.valueOf(flag1)), 3); - p_55233_.updateNeighborsAt(p_55234_.below(), this); -- if (p_55232_.getValue(SHAPE).isAscending()) { -+ if (p_55232_.getValue(getShapeProperty()).isAscending()) { - p_55233_.updateNeighborsAt(p_55234_.above(), this); - } - } -@@ -162,6 +_,9 @@ - return p_55240_.setValue(SHAPE, RailShape.SOUTH_EAST); - case NORTH_EAST: - return p_55240_.setValue(SHAPE, RailShape.SOUTH_WEST); -+ case NORTH_SOUTH: //Forge fix: MC-196102 -+ case EAST_WEST: -+ return p_55240_; + protected boolean isSameRailWithPower(Level p_55226_, BlockPos p_55227_, boolean p_55228_, int p_55229_, RailShape p_55230_) { + BlockState blockstate = p_55226_.getBlockState(p_55227_); +- if (!blockstate.is(this)) { ++ if (!(blockstate.getBlock() instanceof PoweredRailBlock other)) { + return false; + } else { +- RailShape railshape = blockstate.getValue(SHAPE); ++ RailShape railshape = other.getRailDirection(blockstate, p_55226_, p_55227_, null); + if (p_55230_ != RailShape.EAST_WEST + || railshape != RailShape.NORTH_SOUTH && railshape != RailShape.ASCENDING_NORTH && railshape != RailShape.ASCENDING_SOUTH) { + if (p_55230_ != RailShape.NORTH_SOUTH + || railshape != RailShape.EAST_WEST && railshape != RailShape.ASCENDING_EAST && railshape != RailShape.ASCENDING_WEST) { +- if (!blockstate.getValue(POWERED)) { ++ if (isActivatorRail() == other.isActivatorRail()) { + return false; + } else { +- return p_55226_.hasNeighborSignal(p_55227_) ? true : this.findPoweredRailSignal(p_55226_, p_55227_, blockstate, p_55228_, p_55229_ + 1); ++ return p_55226_.hasNeighborSignal(p_55227_) ? true : other.findPoweredRailSignal(p_55226_, p_55227_, blockstate, p_55228_, p_55229_ + 1); + } + } else { + return false; +@@ -141,7 +_,7 @@ + if (flag1 != flag) { + p_55233_.setBlock(p_55234_, p_55232_.setValue(POWERED, Boolean.valueOf(flag1)), 3); + p_55233_.updateNeighborsAt(p_55234_.below(), this); +- if (p_55232_.getValue(SHAPE).isAscending()) { ++ if (p_55232_.getValue(getShapeProperty()).isAscending()) { + p_55233_.updateNeighborsAt(p_55234_.above(), this); } - case COUNTERCLOCKWISE_90: - switch ((RailShape)p_55240_.getValue(SHAPE)) { -@@ -259,6 +_,10 @@ - } + } +@@ -173,6 +_,9 @@ + return p_55240_.setValue(SHAPE, RailShape.SOUTH_EAST); + case NORTH_EAST: + return p_55240_.setValue(SHAPE, RailShape.SOUTH_WEST); ++ case NORTH_SOUTH: //Forge fix: MC-196102 ++ case EAST_WEST: ++ return p_55240_; + } + case COUNTERCLOCKWISE_90: + switch ((RailShape)p_55240_.getValue(SHAPE)) { +@@ -272,6 +_,10 @@ - protected void createBlockStateDefinition(StateDefinition.Builder p_55243_) { -- p_55243_.add(SHAPE, POWERED, WATERLOGGED); -+ p_55243_.add(getShapeProperty(), POWERED, WATERLOGGED); -+ } + @Override + protected void createBlockStateDefinition(StateDefinition.Builder p_55243_) { +- p_55243_.add(SHAPE, POWERED, WATERLOGGED); ++ p_55243_.add(getShapeProperty(), POWERED, WATERLOGGED); ++ } + -+ public boolean isActivatorRail() { -+ return isActivator; - } ++ public boolean isActivatorRail() { ++ return isActivator; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch index 13689a8d69..c449149a54 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/PumpkinBlock.java +++ b/net/minecraft/world/level/block/PumpkinBlock.java -@@ -31,7 +_,7 @@ - - public InteractionResult use(BlockState p_55289_, Level p_55290_, BlockPos p_55291_, Player p_55292_, InteractionHand p_55293_, BlockHitResult p_55294_) { - ItemStack itemstack = p_55292_.getItemInHand(p_55293_); -- if (itemstack.is(Items.SHEARS)) { -+ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_CARVE)) { - if (!p_55290_.isClientSide) { - Direction direction = p_55294_.getDirection(); - Direction direction1 = direction.getAxis() == Direction.Axis.Y ? p_55292_.getDirection().getOpposite() : direction; +@@ -35,7 +_,7 @@ + protected ItemInteractionResult useItemOn( + ItemStack p_330568_, BlockState p_330263_, Level p_327756_, BlockPos p_328675_, Player p_334049_, InteractionHand p_331851_, BlockHitResult p_329008_ + ) { +- if (!p_330568_.is(Items.SHEARS)) { ++ if (p_330568_.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_CARVE)) { + return super.useItemOn(p_330568_, p_330263_, p_327756_, p_328675_, p_334049_, p_331851_, p_329008_); + } else if (p_327756_.isClientSide) { + return ItemInteractionResult.sidedSuccess(p_327756_.isClientSide); diff --git a/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch b/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch index ced459eefd..24c8a3719b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch @@ -1,77 +1,78 @@ --- a/net/minecraft/world/level/block/RailState.java +++ b/net/minecraft/world/level/block/RailState.java @@ -16,14 +_,16 @@ - private BlockState state; - private final boolean isStraight; - private final List connections = Lists.newArrayList(); -+ private final boolean canMakeSlopes; + private BlockState state; + private final boolean isStraight; + private final List connections = Lists.newArrayList(); ++ private final boolean canMakeSlopes; - public RailState(Level p_55421_, BlockPos p_55422_, BlockState p_55423_) { - this.level = p_55421_; - this.pos = p_55422_; - this.state = p_55423_; - this.block = (BaseRailBlock)p_55423_.getBlock(); -- RailShape railshape = p_55423_.getValue(this.block.getShapeProperty()); -- this.isStraight = this.block.isStraight(); -+ RailShape railshape = this.block.getRailDirection(state, p_55421_, p_55422_, null); -+ this.isStraight = !this.block.isFlexibleRail(state, p_55421_, p_55422_); -+ this.canMakeSlopes = this.block.canMakeSlopes(state, p_55421_, p_55422_); - this.updateConnections(railshape); - } + public RailState(Level p_55421_, BlockPos p_55422_, BlockState p_55423_) { + this.level = p_55421_; + this.pos = p_55422_; + this.state = p_55423_; + this.block = (BaseRailBlock)p_55423_.getBlock(); +- RailShape railshape = p_55423_.getValue(this.block.getShapeProperty()); +- this.isStraight = this.block.isStraight(); ++ RailShape railshape = this.block.getRailDirection(state, p_55421_, p_55422_, null); ++ this.isStraight = !this.block.isFlexibleRail(state, p_55421_, p_55422_); ++ this.canMakeSlopes = this.block.canMakeSlopes(state, p_55421_, p_55422_); + this.updateConnections(railshape); + } @@ -179,7 +_,7 @@ - } - } + } + } -- if (railshape == RailShape.NORTH_SOUTH) { -+ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos.above())) { - railshape = RailShape.ASCENDING_NORTH; - } +- if (railshape == RailShape.NORTH_SOUTH) { ++ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, blockpos.above())) { + railshape = RailShape.ASCENDING_NORTH; + } @@ -189,7 +_,7 @@ - } - } + } + } -- if (railshape == RailShape.EAST_WEST) { -+ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos3.above())) { - railshape = RailShape.ASCENDING_EAST; - } -@@ -203,6 +_,10 @@ - railshape = RailShape.NORTH_SOUTH; - } +- if (railshape == RailShape.EAST_WEST) { ++ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, blockpos3.above())) { + railshape = RailShape.ASCENDING_EAST; + } +@@ -201,6 +_,11 @@ -+ if (!this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid -+ this.connections.remove(p_55442_.pos); -+ return; -+ } - this.state = this.state.setValue(this.block.getShapeProperty(), railshape); - this.level.setBlock(this.pos, this.state, 3); - } + if (railshape == null) { + railshape = RailShape.NORTH_SOUTH; ++ } ++ ++ if (!this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid ++ this.connections.remove(p_55442_.pos); ++ return; + } + + this.state = this.state.setValue(this.block.getShapeProperty(), railshape); @@ -305,7 +_,7 @@ - } - } + } + } -- if (railshape == RailShape.NORTH_SOUTH) { -+ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos.above())) { - railshape = RailShape.ASCENDING_NORTH; - } +- if (railshape == RailShape.NORTH_SOUTH) { ++ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, blockpos.above())) { + railshape = RailShape.ASCENDING_NORTH; + } @@ -315,7 +_,7 @@ - } - } + } + } -- if (railshape == RailShape.EAST_WEST) { -+ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos3.above())) { - railshape = RailShape.ASCENDING_EAST; - } +- if (railshape == RailShape.EAST_WEST) { ++ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, blockpos3.above())) { + railshape = RailShape.ASCENDING_EAST; + } @@ -325,7 +_,7 @@ - } - } + } + } -- if (railshape == null) { -+ if (railshape == null || !this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid - railshape = p_55434_; - } +- if (railshape == null) { ++ if (railshape == null || !this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid + railshape = p_55434_; + } diff --git a/patches/minecraft/net/minecraft/world/level/block/RedStoneOreBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/RedStoneOreBlock.java.patch index 5206dbb0e0..1dbf1a61d1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RedStoneOreBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RedStoneOreBlock.java.patch @@ -1,18 +1,22 @@ --- a/net/minecraft/world/level/block/RedStoneOreBlock.java +++ b/net/minecraft/world/level/block/RedStoneOreBlock.java -@@ -80,11 +_,11 @@ - - public void spawnAfterBreak(BlockState p_221907_, ServerLevel p_221908_, BlockPos p_221909_, ItemStack p_221910_, boolean p_221911_) { - super.spawnAfterBreak(p_221907_, p_221908_, p_221909_, p_221910_, p_221911_); -- if (p_221911_ && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, p_221910_) == 0) { -- int i = 1 + p_221908_.random.nextInt(5); -- this.popExperience(p_221908_, p_221909_, i); -- } -+ } - -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader world, RandomSource randomSource, BlockPos pos, int fortune, int silktouch) { -+ return silktouch == 0 ? 1 + randomSource.nextInt(5) : 0; - } - - public void animateTick(BlockState p_221913_, Level p_221914_, BlockPos p_221915_, RandomSource p_221916_) { +@@ -88,7 +_,7 @@ + @Override + protected void spawnAfterBreak(BlockState p_221907_, ServerLevel p_221908_, BlockPos p_221909_, ItemStack p_221910_, boolean p_221911_) { + super.spawnAfterBreak(p_221907_, p_221908_, p_221909_, p_221910_, p_221911_); +- if (p_221911_ && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, p_221910_) == 0) { ++ if (false && p_221911_ && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, p_221910_) == 0) { // Forge: moved to getExpDrop + int i = 1 + p_221908_.random.nextInt(5); + this.popExperience(p_221908_, p_221909_, i); + } +@@ -129,4 +_,10 @@ + protected void createBlockStateDefinition(StateDefinition.Builder p_55484_) { + p_55484_.add(LIT); + } ++ ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader world, RandomSource randomSource, BlockPos pos, int fortune, int silktouch) { ++ return silktouch == 0 ? 1 + randomSource.nextInt(5) : 0; ++ } ++ + } diff --git a/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch index 21497371c2..ab67d54b69 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch @@ -1,27 +1,29 @@ --- a/net/minecraft/world/level/block/RedStoneWireBlock.java +++ b/net/minecraft/world/level/block/RedStoneWireBlock.java -@@ -202,7 +_,7 @@ - BlockState blockstate = p_55523_.getBlockState(blockpos); - if (p_55526_) { - boolean flag = blockstate.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(p_55523_, blockpos, blockstate); -- if (flag && shouldConnectTo(p_55523_.getBlockState(blockpos.above()))) { -+ if (flag && p_55523_.getBlockState(blockpos.above()).canRedstoneConnectTo(p_55523_, blockpos.above(), null)) { - if (blockstate.isFaceSturdy(p_55523_, blockpos, p_55525_.getOpposite())) { - return RedstoneSide.UP; +@@ -249,7 +_,7 @@ + BlockState blockstate = p_55523_.getBlockState(blockpos); + if (p_55526_) { + boolean flag = blockstate.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(p_55523_, blockpos, blockstate); +- if (flag && shouldConnectTo(p_55523_.getBlockState(blockpos.above()))) { ++ if (flag && p_55523_.getBlockState(blockpos.above()).canRedstoneConnectTo(p_55523_, blockpos.above(), null)) { + if (blockstate.isFaceSturdy(p_55523_, blockpos, p_55525_.getOpposite())) { + return RedstoneSide.UP; + } +@@ -258,9 +_,14 @@ } -@@ -211,7 +_,14 @@ - } - } + } -- return !shouldConnectTo(blockstate, p_55525_) && (blockstate.isRedstoneConductor(p_55523_, blockpos) || !shouldConnectTo(p_55523_.getBlockState(blockpos.below()))) ? RedstoneSide.NONE : RedstoneSide.SIDE; -+ if (blockstate.canRedstoneConnectTo(p_55523_, blockpos, p_55525_)) { -+ return RedstoneSide.SIDE; -+ } else if (blockstate.isRedstoneConductor(p_55523_, blockpos)) { -+ return RedstoneSide.NONE; -+ } else { -+ BlockPos blockPosBelow = blockpos.below(); -+ return p_55523_.getBlockState(blockPosBelow).canRedstoneConnectTo(p_55523_, blockPosBelow, null) ? RedstoneSide.SIDE : RedstoneSide.NONE; -+ } - } +- return !shouldConnectTo(blockstate, p_55525_) && (blockstate.isRedstoneConductor(p_55523_, blockpos) || !shouldConnectTo(p_55523_.getBlockState(blockpos.below()))) +- ? RedstoneSide.NONE +- : RedstoneSide.SIDE; ++ if (blockstate.canRedstoneConnectTo(p_55523_, blockpos, p_55525_)) { ++ return RedstoneSide.SIDE; ++ } else if (blockstate.isRedstoneConductor(p_55523_, blockpos)) { ++ return RedstoneSide.NONE; ++ } else { ++ BlockPos blockPosBelow = blockpos.below(); ++ return p_55523_.getBlockState(blockPosBelow).canRedstoneConnectTo(p_55523_, blockPosBelow, null) ? RedstoneSide.SIDE : RedstoneSide.NONE; ++ } + } - public boolean canSurvive(BlockState p_55585_, LevelReader p_55586_, BlockPos p_55587_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch index f9365cfb47..a0b98fc1dd 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/block/SaplingBlock.java +++ b/net/minecraft/world/level/block/SaplingBlock.java -@@ -43,6 +_,7 @@ - } +@@ -46,6 +_,7 @@ - public void randomTick(BlockState p_222011_, ServerLevel p_222012_, BlockPos p_222013_, RandomSource p_222014_) { -+ if (!p_222012_.isAreaLoaded(p_222013_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light - if (p_222012_.getMaxLocalRawBrightness(p_222013_.above()) >= 9 && p_222014_.nextInt(7) == 0) { - this.advanceTree(p_222012_, p_222013_, p_222011_, p_222014_); - } + @Override + protected void randomTick(BlockState p_222011_, ServerLevel p_222012_, BlockPos p_222013_, RandomSource p_222014_) { ++ if (!p_222012_.isAreaLoaded(p_222013_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light + if (p_222012_.getMaxLocalRawBrightness(p_222013_.above()) >= 9 && p_222014_.nextInt(7) == 0) { + this.advanceTree(p_222012_, p_222013_, p_222011_, p_222014_); + } diff --git a/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch index 3a333613d5..9d54d480b1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch @@ -1,18 +1,17 @@ --- a/net/minecraft/world/level/block/SculkCatalystBlock.java +++ b/net/minecraft/world/level/block/SculkCatalystBlock.java -@@ -60,9 +_,11 @@ - - public void spawnAfterBreak(BlockState p_222109_, ServerLevel p_222110_, BlockPos p_222111_, ItemStack p_222112_, boolean p_222113_) { - super.spawnAfterBreak(p_222109_, p_222110_, p_222111_, p_222112_, p_222113_); -- if (p_222113_) { -- this.tryDropExperience(p_222110_, p_222111_, p_222112_, this.xpRange); -- } -- +@@ -66,8 +_,13 @@ + @Override + protected void spawnAfterBreak(BlockState p_222109_, ServerLevel p_222110_, BlockPos p_222111_, ItemStack p_222112_, boolean p_222113_) { + super.spawnAfterBreak(p_222109_, p_222110_, p_222111_, p_222112_, p_222113_); +- if (p_222113_) { ++ if (false && p_222113_) { // Forge Moved to getExpDrop + this.tryDropExperience(p_222110_, p_222111_, p_222112_, this.xpRange); + } ++ } + -+ } -+ -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { -+ return silkTouchLevel == 0 ? this.xpRange.sample(randomSource) : 0; - } ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { ++ return silkTouchLevel == 0 ? this.xpRange.sample(randomSource) : 0; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch index da64862a8b..a512a7769c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch @@ -1,18 +1,17 @@ --- a/net/minecraft/world/level/block/SculkSensorBlock.java +++ b/net/minecraft/world/level/block/SculkSensorBlock.java -@@ -258,9 +_,11 @@ - - public void spawnAfterBreak(BlockState p_222142_, ServerLevel p_222143_, BlockPos p_222144_, ItemStack p_222145_, boolean p_222146_) { - super.spawnAfterBreak(p_222142_, p_222143_, p_222144_, p_222145_, p_222146_); -- if (p_222146_) { -- this.tryDropExperience(p_222143_, p_222144_, p_222145_, ConstantInt.of(5)); -- } -- +@@ -294,8 +_,13 @@ + @Override + protected void spawnAfterBreak(BlockState p_222142_, ServerLevel p_222143_, BlockPos p_222144_, ItemStack p_222145_, boolean p_222146_) { + super.spawnAfterBreak(p_222142_, p_222143_, p_222144_, p_222145_, p_222146_); +- if (p_222146_) { ++ if (false && p_222146_) { // Forge: Moved to getExpDrop + this.tryDropExperience(p_222143_, p_222144_, p_222145_, ConstantInt.of(5)); + } ++ } + -+ } -+ -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { -+ return silkTouchLevel == 0 ? 5 : 0; - } ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { ++ return silkTouchLevel == 0 ? 5 : 0; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch index c01afce043..e3eafbb8c3 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch @@ -1,19 +1,22 @@ --- a/net/minecraft/world/level/block/SculkShriekerBlock.java +++ b/net/minecraft/world/level/block/SculkShriekerBlock.java -@@ -127,10 +_,12 @@ - - public void spawnAfterBreak(BlockState p_222192_, ServerLevel p_222193_, BlockPos p_222194_, ItemStack p_222195_, boolean p_222196_) { - super.spawnAfterBreak(p_222192_, p_222193_, p_222194_, p_222195_, p_222196_); -- if (p_222196_) { -- this.tryDropExperience(p_222193_, p_222194_, p_222195_, ConstantInt.of(5)); -- } -- +@@ -140,7 +_,7 @@ + @Override + protected void spawnAfterBreak(BlockState p_222192_, ServerLevel p_222193_, BlockPos p_222194_, ItemStack p_222195_, boolean p_222196_) { + super.spawnAfterBreak(p_222192_, p_222193_, p_222194_, p_222195_, p_222196_); +- if (p_222196_) { ++ if (false && p_222196_) { // Forge: Moved to getExpDrop + this.tryDropExperience(p_222193_, p_222194_, p_222195_, ConstantInt.of(5)); + } + } +@@ -155,5 +_,10 @@ + (p_281134_, p_281135_, p_281136_, p_281137_) -> VibrationSystem.Ticker.tick(p_281134_, p_281137_.getVibrationData(), p_281137_.getVibrationUser()) + ) + : null; ++ } + -+ } -+ -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { -+ return silkTouchLevel == 0 ? 5 : 0; - } - - @Nullable ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { ++ return silkTouchLevel == 0 ? 5 : 0; + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch index f6bae9c40b..19577ef76e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch @@ -6,6 +6,6 @@ -public class SeagrassBlock extends BushBlock implements BonemealableBlock, LiquidBlockContainer { +public class SeagrassBlock extends BushBlock implements BonemealableBlock, LiquidBlockContainer, net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(SeagrassBlock::new); - protected static final float AABB_OFFSET = 6.0F; - protected static final VoxelShape SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 12.0D, 14.0D); + public static final MapCodec CODEC = simpleCodec(SeagrassBlock::new); + protected static final float AABB_OFFSET = 6.0F; + protected static final VoxelShape SHAPE = Block.box(2.0, 0.0, 2.0, 14.0, 12.0, 14.0); diff --git a/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch b/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch index 6885cb955b..585d15c498 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/block/SoundType.java +++ b/net/minecraft/world/level/block/SoundType.java -@@ -122,6 +_,7 @@ - private final SoundEvent hitSound; - private final SoundEvent fallSound; +@@ -351,6 +_,7 @@ + private final SoundEvent hitSound; + private final SoundEvent fallSound; -+ @Deprecated // Forge: Use {@link net.minecraftforge.common.util.ForgeSoundType} instead for suppliers - public SoundType(float p_56766_, float p_56767_, SoundEvent p_56768_, SoundEvent p_56769_, SoundEvent p_56770_, SoundEvent p_56771_, SoundEvent p_56772_) { - this.volume = p_56766_; - this.pitch = p_56767_; ++ @Deprecated // Forge: Use {@link net.minecraftforge.common.util.ForgeSoundType} instead for suppliers + public SoundType(float p_56766_, float p_56767_, SoundEvent p_56768_, SoundEvent p_56769_, SoundEvent p_56770_, SoundEvent p_56771_, SoundEvent p_56772_) { + this.volume = p_56766_; + this.pitch = p_56767_; diff --git a/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch index 363c50bcd8..214eae1b2f 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch @@ -1,20 +1,22 @@ --- a/net/minecraft/world/level/block/SpawnerBlock.java +++ b/net/minecraft/world/level/block/SpawnerBlock.java -@@ -40,11 +_,12 @@ - - public void spawnAfterBreak(BlockState p_222477_, ServerLevel p_222478_, BlockPos p_222479_, ItemStack p_222480_, boolean p_222481_) { - super.spawnAfterBreak(p_222477_, p_222478_, p_222479_, p_222480_, p_222481_); -- if (p_222481_) { -- int i = 15 + p_222478_.random.nextInt(15) + p_222478_.random.nextInt(15); -- this.popExperience(p_222478_, p_222479_, i); -- } -- +@@ -44,7 +_,7 @@ + @Override + protected void spawnAfterBreak(BlockState p_222477_, ServerLevel p_222478_, BlockPos p_222479_, ItemStack p_222480_, boolean p_222481_) { + super.spawnAfterBreak(p_222477_, p_222478_, p_222479_, p_222480_, p_222481_); +- if (p_222481_) { ++ if (false && p_222481_) { // Forge: moved to getExpDrop + int i = 15 + p_222478_.random.nextInt(15) + p_222478_.random.nextInt(15); + this.popExperience(p_222478_, p_222479_, i); + } +@@ -59,5 +_,10 @@ + public void appendHoverText(ItemStack p_255714_, Item.TooltipContext p_331610_, List p_255708_, TooltipFlag p_255667_) { + super.appendHoverText(p_255714_, p_331610_, p_255708_, p_255667_); + Spawner.appendHoverText(p_255714_, p_255708_, "SpawnData"); ++ } + -+ } -+ -+ @Override -+ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader world, net.minecraft.util.RandomSource randomSource, BlockPos pos, int fortune, int silktouch) { -+ return 15 + randomSource.nextInt(15) + randomSource.nextInt(15); - } - - public RenderShape getRenderShape(BlockState p_56794_) { ++ @Override ++ public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader world, net.minecraft.util.RandomSource randomSource, BlockPos pos, int fortune, int silktouch) { ++ return 15 + randomSource.nextInt(15) + randomSource.nextInt(15); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch index bfe6b860c1..15599e6625 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/level/block/SpongeBlock.java +++ b/net/minecraft/world/level/block/SpongeBlock.java -@@ -47,6 +_,7 @@ - } +@@ -49,6 +_,7 @@ + } - private boolean removeWaterBreadthFirstSearch(Level p_56808_, BlockPos p_56809_) { -+ BlockState spongeState = p_56808_.getBlockState(p_56809_); - return BlockPos.breadthFirstTraversal(p_56809_, 6, 65, (p_277519_, p_277492_) -> { - for(Direction direction : ALL_DIRECTIONS) { - p_277492_.accept(p_277519_.relative(direction)); -@@ -58,7 +_,7 @@ - } else { - BlockState blockstate = p_56808_.getBlockState(p_296944_); - FluidState fluidstate = p_56808_.getFluidState(p_296944_); -- if (!fluidstate.is(FluidTags.WATER)) { -+ if (!spongeState.canBeHydrated(p_56808_, p_56809_, fluidstate, p_296944_)) { - return false; - } else { - Block block = blockstate.getBlock(); + private boolean removeWaterBreadthFirstSearch(Level p_56808_, BlockPos p_56809_) { ++ BlockState spongeState = p_56808_.getBlockState(p_56809_); + return BlockPos.breadthFirstTraversal( + p_56809_, + 6, +@@ -64,7 +_,7 @@ + } else { + BlockState blockstate = p_56808_.getBlockState(p_296944_); + FluidState fluidstate = p_56808_.getFluidState(p_296944_); +- if (!fluidstate.is(FluidTags.WATER)) { ++ if (!spongeState.canBeHydrated(p_56808_, p_56809_, fluidstate, p_296944_)) { + return false; + } else { + if (blockstate.getBlock() instanceof BucketPickup bucketpickup diff --git a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java.patch index 0600f87a83..0c7f4162b8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java +++ b/net/minecraft/world/level/block/SpreadingSnowyDirtBlock.java -@@ -38,8 +_,10 @@ - - public void randomTick(BlockState p_222508_, ServerLevel p_222509_, BlockPos p_222510_, RandomSource p_222511_) { - if (!canBeGrass(p_222508_, p_222509_, p_222510_)) { -+ if (!p_222509_.isAreaLoaded(p_222510_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading - p_222509_.setBlockAndUpdate(p_222510_, Blocks.DIRT.defaultBlockState()); - } else { -+ if (!p_222509_.isAreaLoaded(p_222510_, 3)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading - if (p_222509_.getMaxLocalRawBrightness(p_222510_.above()) >= 9) { - BlockState blockstate = this.defaultBlockState(); +@@ -40,8 +_,10 @@ + @Override + protected void randomTick(BlockState p_222508_, ServerLevel p_222509_, BlockPos p_222510_, RandomSource p_222511_) { + if (!canBeGrass(p_222508_, p_222509_, p_222510_)) { ++ if (!p_222509_.isAreaLoaded(p_222510_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading + p_222509_.setBlockAndUpdate(p_222510_, Blocks.DIRT.defaultBlockState()); + } else { ++ if (!p_222509_.isAreaLoaded(p_222510_, 3)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading + if (p_222509_.getMaxLocalRawBrightness(p_222510_.above()) >= 9) { + BlockState blockstate = this.defaultBlockState(); diff --git a/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch index 9aca878ef9..4cd858d1bc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch @@ -1,44 +1,35 @@ --- a/net/minecraft/world/level/block/StemBlock.java +++ b/net/minecraft/world/level/block/StemBlock.java -@@ -65,17 +_,18 @@ - } +@@ -79,9 +_,11 @@ - public void randomTick(BlockState p_222538_, ServerLevel p_222539_, BlockPos p_222540_, RandomSource p_222541_) { -+ if (!p_222539_.isAreaLoaded(p_222540_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light - if (p_222539_.getRawBrightness(p_222540_, 0) >= 9) { - float f = CropBlock.getGrowthSpeed(this, p_222539_, p_222540_); -- if (p_222541_.nextInt((int)(25.0F / f) + 1) == 0) { -+ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222539_, p_222540_, p_222538_, p_222541_.nextInt((int)(25.0F / f) + 1) == 0)) { - int i = p_222538_.getValue(AGE); - if (i < 7) { -- p_222538_ = p_222538_.setValue(AGE, Integer.valueOf(i + 1)); -- p_222539_.setBlock(p_222540_, p_222538_, 2); -+ p_222539_.setBlock(p_222540_, p_222538_.setValue(AGE, Integer.valueOf(i + 1)), 2); - } else { - Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(p_222541_); - BlockPos blockpos = p_222540_.relative(direction); - BlockState blockstate = p_222539_.getBlockState(blockpos.below()); -+ // Forge: TODO: Soil blockstate.canSustainPlant(p_222539_, blockpos.below(), Direction.UP, this.fruit) - if (p_222539_.getBlockState(blockpos).isAir() && (blockstate.is(Blocks.FARMLAND) || blockstate.is(BlockTags.DIRT))) { - Registry registry = p_222539_.registryAccess().registryOrThrow(Registries.BLOCK); - Optional optional = registry.getOptional(this.fruit); -@@ -86,6 +_,7 @@ - } - } - } -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_222539_, p_222540_, p_222538_); - } - - } -@@ -115,5 +_,11 @@ - - protected void createBlockStateDefinition(StateDefinition.Builder p_57040_) { - p_57040_.add(AGE); -+ } + @Override + protected void randomTick(BlockState p_222538_, ServerLevel p_222539_, BlockPos p_222540_, RandomSource p_222541_) { ++ if (!p_222539_.isAreaLoaded(p_222540_, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light + if (p_222539_.getRawBrightness(p_222540_, 0) >= 9) { + float f = CropBlock.getGrowthSpeed(this, p_222539_, p_222540_); +- if (p_222541_.nextInt((int)(25.0F / f) + 1) == 0) { ++ var vanilla = p_222541_.nextInt((int)(25.0F / f) + 1) == 0; ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222539_, p_222540_, p_222538_, vanilla)) { + int i = p_222538_.getValue(AGE); + if (i < 7) { + p_222538_ = p_222538_.setValue(AGE, Integer.valueOf(i + 1)); +@@ -90,7 +_,7 @@ + Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(p_222541_); + BlockPos blockpos = p_222540_.relative(direction); + BlockState blockstate = p_222539_.getBlockState(blockpos.below()); +- if (p_222539_.getBlockState(blockpos).isAir() && (blockstate.is(Blocks.FARMLAND) || blockstate.is(BlockTags.DIRT))) { ++ if (p_222539_.getBlockState(blockpos).isAir() && blockstate.canSustainPlant(p_222539_, blockpos.below(), Direction.UP, this)) { + Registry registry = p_222539_.registryAccess().registryOrThrow(Registries.BLOCK); + Optional optional = registry.getOptional(this.fruit); + Optional optional1 = registry.getOptional(this.attachedStem); +@@ -132,5 +_,10 @@ + @Override + protected void createBlockStateDefinition(StateDefinition.Builder p_57040_) { + p_57040_.add(AGE); ++ } + -+ //FORGE START -+ @Override -+ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { -+ return net.minecraftforge.common.PlantType.CROP; - } ++ @Override ++ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { ++ return net.minecraftforge.common.PlantType.CROP; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch index 87de9a994a..12c5ed398b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch @@ -6,56 +6,56 @@ -public class SugarCaneBlock extends Block { +public class SugarCaneBlock extends Block implements net.minecraftforge.common.IPlantable { - public static final MapCodec CODEC = simpleCodec(SugarCaneBlock::new); - public static final IntegerProperty AGE = BlockStateProperties.AGE_15; - protected static final float AABB_OFFSET = 6.0F; -@@ -53,12 +_,15 @@ + public static final MapCodec CODEC = simpleCodec(SugarCaneBlock::new); + public static final IntegerProperty AGE = BlockStateProperties.AGE_15; + protected static final float AABB_OFFSET = 6.0F; +@@ -58,12 +_,15 @@ - if (i < 3) { - int j = p_222548_.getValue(AGE); -+ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222549_, p_222550_, p_222548_, true)) { - if (j == 15) { - p_222549_.setBlockAndUpdate(p_222550_.above(), this.defaultBlockState()); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_222549_, p_222550_.above(), this.defaultBlockState()); - p_222549_.setBlock(p_222550_, p_222548_.setValue(AGE, Integer.valueOf(0)), 4); - } else { - p_222549_.setBlock(p_222550_, p_222548_.setValue(AGE, Integer.valueOf(j + 1)), 4); + if (i < 3) { + int j = p_222548_.getValue(AGE); ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222549_, p_222550_, p_222548_, true)) { + if (j == 15) { + p_222549_.setBlockAndUpdate(p_222550_.above(), this.defaultBlockState()); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_222549_, p_222550_.above(), this.defaultBlockState()); + p_222549_.setBlock(p_222550_, p_222548_.setValue(AGE, Integer.valueOf(0)), 4); + } else { + p_222549_.setBlock(p_222550_, p_222548_.setValue(AGE, Integer.valueOf(j + 1)), 4); + } ++ } } -+ } - } - } + } + } +@@ -79,6 +_,8 @@ -@@ -73,6 +_,8 @@ - } - - public boolean canSurvive(BlockState p_57175_, LevelReader p_57176_, BlockPos p_57177_) { -+ BlockState soil = p_57176_.getBlockState(p_57177_.below()); -+ if (soil.canSustainPlant(p_57176_, p_57177_.below(), Direction.UP, this)) return true; - BlockState blockstate = p_57176_.getBlockState(p_57177_.below()); - if (blockstate.is(this)) { - return true; -@@ -83,7 +_,7 @@ - for(Direction direction : Direction.Plane.HORIZONTAL) { - BlockState blockstate1 = p_57176_.getBlockState(blockpos.relative(direction)); - FluidState fluidstate = p_57176_.getFluidState(blockpos.relative(direction)); -- if (fluidstate.is(FluidTags.WATER) || blockstate1.is(Blocks.FROSTED_ICE)) { -+ if (p_57175_.canBeHydrated(p_57176_, p_57177_, fluidstate, blockpos.relative(direction)) || blockstate1.is(Blocks.FROSTED_ICE)) { - return true; - } - } -@@ -95,5 +_,15 @@ - - protected void createBlockStateDefinition(StateDefinition.Builder p_57186_) { - p_57186_.add(AGE); -+ } + @Override + protected boolean canSurvive(BlockState p_57175_, LevelReader p_57176_, BlockPos p_57177_) { ++ BlockState soil = p_57176_.getBlockState(p_57177_.below()); ++ if (soil.canSustainPlant(p_57176_, p_57177_.below(), Direction.UP, this)) return true; + BlockState blockstate = p_57176_.getBlockState(p_57177_.below()); + if (blockstate.is(this)) { + return true; +@@ -89,7 +_,7 @@ + for (Direction direction : Direction.Plane.HORIZONTAL) { + BlockState blockstate1 = p_57176_.getBlockState(blockpos.relative(direction)); + FluidState fluidstate = p_57176_.getFluidState(blockpos.relative(direction)); +- if (fluidstate.is(FluidTags.WATER) || blockstate1.is(Blocks.FROSTED_ICE)) { ++ if (p_57175_.canBeHydrated(p_57176_, p_57177_, fluidstate, blockpos.relative(direction)) || blockstate1.is(Blocks.FROSTED_ICE)) { + return true; + } + } +@@ -102,5 +_,15 @@ + @Override + protected void createBlockStateDefinition(StateDefinition.Builder p_57186_) { + p_57186_.add(AGE); ++ } + -+ @Override -+ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { -+ return net.minecraftforge.common.PlantType.BEACH; -+ } ++ @Override ++ public net.minecraftforge.common.PlantType getPlantType(BlockGetter world, BlockPos pos) { ++ return net.minecraftforge.common.PlantType.BEACH; ++ } + -+ @Override -+ public BlockState getPlant(BlockGetter world, BlockPos pos) { -+ return defaultBlockState(); - } ++ @Override ++ public BlockState getPlant(BlockGetter world, BlockPos pos) { ++ return defaultBlockState(); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch index afd52342ed..6bd43d3b94 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/block/SweetBerryBushBlock.java +++ b/net/minecraft/world/level/block/SweetBerryBushBlock.java -@@ -63,10 +_,11 @@ +@@ -69,10 +_,11 @@ + @Override + protected void randomTick(BlockState p_222563_, ServerLevel p_222564_, BlockPos p_222565_, RandomSource p_222566_) { + int i = p_222563_.getValue(AGE); +- if (i < 3 && p_222566_.nextInt(5) == 0 && p_222564_.getRawBrightness(p_222565_.above(), 0) >= 9) { ++ if (i < 3 && p_222564_.getRawBrightness(p_222565_.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222564_, p_222565_, p_222563_, p_222566_.nextInt(5) == 0)) { + BlockState blockstate = p_222563_.setValue(AGE, Integer.valueOf(i + 1)); + p_222564_.setBlock(p_222565_, blockstate, 2); + p_222564_.gameEvent(GameEvent.BLOCK_CHANGE, p_222565_, GameEvent.Context.of(blockstate)); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_222564_, p_222565_, p_222563_); + } + } - public void randomTick(BlockState p_222563_, ServerLevel p_222564_, BlockPos p_222565_, RandomSource p_222566_) { - int i = p_222563_.getValue(AGE); -- if (i < 3 && p_222566_.nextInt(5) == 0 && p_222564_.getRawBrightness(p_222565_.above(), 0) >= 9) { -+ if (i < 3 && p_222564_.getRawBrightness(p_222565_.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(p_222564_, p_222565_, p_222563_, p_222566_.nextInt(5) == 0)) { - BlockState blockstate = p_222563_.setValue(AGE, Integer.valueOf(i + 1)); - p_222564_.setBlock(p_222565_, blockstate, 2); - p_222564_.gameEvent(GameEvent.BLOCK_CHANGE, p_222565_, GameEvent.Context.of(blockstate)); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(p_222564_, p_222565_, p_222563_); - } - - } diff --git a/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch index 1c5c616642..780d99540a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch @@ -6,6 +6,6 @@ -public class TallGrassBlock extends BushBlock implements BonemealableBlock { +public class TallGrassBlock extends BushBlock implements BonemealableBlock, net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(TallGrassBlock::new); - protected static final float AABB_OFFSET = 6.0F; - protected static final VoxelShape SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 13.0D, 14.0D); + public static final MapCodec CODEC = simpleCodec(TallGrassBlock::new); + protected static final float AABB_OFFSET = 6.0F; + protected static final VoxelShape SHAPE = Block.box(2.0, 0.0, 2.0, 14.0, 13.0, 14.0); diff --git a/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch index a5e2ba556a..1b272f1664 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch @@ -1,67 +1,70 @@ --- a/net/minecraft/world/level/block/TntBlock.java +++ b/net/minecraft/world/level/block/TntBlock.java -@@ -39,10 +_,14 @@ - this.registerDefaultState(this.defaultBlockState().setValue(UNSTABLE, Boolean.valueOf(false))); - } +@@ -44,7 +_,7 @@ + protected void onPlace(BlockState p_57466_, Level p_57467_, BlockPos p_57468_, BlockState p_57469_, boolean p_57470_) { + if (!p_57469_.is(p_57466_.getBlock())) { + if (p_57467_.hasNeighborSignal(p_57468_)) { +- explode(p_57467_, p_57468_); ++ onCaughtFire(p_57466_, p_57467_, p_57468_, null, null); + p_57467_.removeBlock(p_57468_, false); + } + } +@@ -53,7 +_,7 @@ + @Override + protected void neighborChanged(BlockState p_57457_, Level p_57458_, BlockPos p_57459_, Block p_57460_, BlockPos p_57461_, boolean p_57462_) { + if (p_57458_.hasNeighborSignal(p_57459_)) { +- explode(p_57458_, p_57459_); ++ onCaughtFire(p_57457_, p_57458_, p_57459_, null, null); + p_57458_.removeBlock(p_57459_, false); + } + } +@@ -61,7 +_,7 @@ + @Override + public BlockState playerWillDestroy(Level p_57445_, BlockPos p_57446_, BlockState p_57447_, Player p_57448_) { + if (!p_57445_.isClientSide() && !p_57448_.isCreative() && p_57447_.getValue(UNSTABLE)) { +- explode(p_57445_, p_57446_); ++ onCaughtFire(p_57447_, p_57445_, p_57446_, null, null); + } -+ public void onCaughtFire(BlockState state, Level world, BlockPos pos, @Nullable net.minecraft.core.Direction face, @Nullable LivingEntity igniter) { -+ explode(world, pos, igniter); -+ } + return super.playerWillDestroy(p_57445_, p_57446_, p_57447_, p_57448_); +@@ -79,10 +_,12 @@ + } + } + ++ @Deprecated //Forge: Prefer using IForgeBlock#catchFire + public static void explode(Level p_57434_, BlockPos p_57435_) { + explode(p_57434_, p_57435_, null); + } + ++ @Deprecated //Forge: Prefer using IForgeBlock#catchFire + private static void explode(Level p_57437_, BlockPos p_57438_, @Nullable LivingEntity p_57439_) { + if (!p_57437_.isClientSide) { + PrimedTnt primedtnt = new PrimedTnt( +@@ -101,7 +_,7 @@ + if (!p_329029_.is(Items.FLINT_AND_STEEL) && !p_329029_.is(Items.FIRE_CHARGE)) { + return super.useItemOn(p_329029_, p_331413_, p_329038_, p_333168_, p_335932_, p_331663_, p_330020_); + } else { +- explode(p_329038_, p_333168_, p_335932_); ++ onCaughtFire(p_331413_, p_329038_, p_333168_, p_330020_.getDirection(), p_335932_); + p_329038_.setBlock(p_333168_, Blocks.AIR.defaultBlockState(), 11); + Item item = p_329029_.getItem(); + if (!p_335932_.isCreative()) { +@@ -123,7 +_,7 @@ + BlockPos blockpos = p_57431_.getBlockPos(); + Entity entity = p_57432_.getOwner(); + if (p_57432_.isOnFire() && p_57432_.mayInteract(p_57429_, blockpos)) { +- explode(p_57429_, blockpos, entity instanceof LivingEntity ? (LivingEntity)entity : null); ++ onCaughtFire(p_57430_, p_57429_, blockpos, null, entity instanceof LivingEntity ? (LivingEntity)entity : null); + p_57429_.removeBlock(blockpos, false); + } + } +@@ -137,5 +_,9 @@ + @Override + protected void createBlockStateDefinition(StateDefinition.Builder p_57464_) { + p_57464_.add(UNSTABLE); ++ } + - public void onPlace(BlockState p_57466_, Level p_57467_, BlockPos p_57468_, BlockState p_57469_, boolean p_57470_) { - if (!p_57469_.is(p_57466_.getBlock())) { - if (p_57467_.hasNeighborSignal(p_57468_)) { -- explode(p_57467_, p_57468_); -+ onCaughtFire(p_57466_, p_57467_, p_57468_, null, null); - p_57467_.removeBlock(p_57468_, false); - } - -@@ -51,7 +_,7 @@ - - public void neighborChanged(BlockState p_57457_, Level p_57458_, BlockPos p_57459_, Block p_57460_, BlockPos p_57461_, boolean p_57462_) { - if (p_57458_.hasNeighborSignal(p_57459_)) { -- explode(p_57458_, p_57459_); -+ onCaughtFire(p_57457_, p_57458_, p_57459_, null, null); - p_57458_.removeBlock(p_57459_, false); - } - -@@ -59,7 +_,7 @@ - - public BlockState playerWillDestroy(Level p_57445_, BlockPos p_57446_, BlockState p_57447_, Player p_57448_) { - if (!p_57445_.isClientSide() && !p_57448_.isCreative() && p_57447_.getValue(UNSTABLE)) { -- explode(p_57445_, p_57446_); -+ onCaughtFire(p_57447_, p_57445_, p_57446_, null, null); - } - - return super.playerWillDestroy(p_57445_, p_57446_, p_57447_, p_57448_); -@@ -74,10 +_,12 @@ - } - } - -+ @Deprecated //Forge: Prefer using IForgeBlock#catchFire - public static void explode(Level p_57434_, BlockPos p_57435_) { - explode(p_57434_, p_57435_, (LivingEntity)null); - } - -+ @Deprecated //Forge: Prefer using IForgeBlock#catchFire - private static void explode(Level p_57437_, BlockPos p_57438_, @Nullable LivingEntity p_57439_) { - if (!p_57437_.isClientSide) { - PrimedTnt primedtnt = new PrimedTnt(p_57437_, (double)p_57438_.getX() + 0.5D, (double)p_57438_.getY(), (double)p_57438_.getZ() + 0.5D, p_57439_); -@@ -92,7 +_,7 @@ - if (!itemstack.is(Items.FLINT_AND_STEEL) && !itemstack.is(Items.FIRE_CHARGE)) { - return super.use(p_57450_, p_57451_, p_57452_, p_57453_, p_57454_, p_57455_); - } else { -- explode(p_57451_, p_57452_, p_57453_); -+ onCaughtFire(p_57450_, p_57451_, p_57452_, p_57455_.getDirection(), p_57453_); - p_57451_.setBlock(p_57452_, Blocks.AIR.defaultBlockState(), 11); - Item item = itemstack.getItem(); - if (!p_57453_.isCreative()) { -@@ -115,7 +_,7 @@ - BlockPos blockpos = p_57431_.getBlockPos(); - Entity entity = p_57432_.getOwner(); - if (p_57432_.isOnFire() && p_57432_.mayInteract(p_57429_, blockpos)) { -- explode(p_57429_, blockpos, entity instanceof LivingEntity ? (LivingEntity)entity : null); -+ onCaughtFire(p_57430_, p_57429_, blockpos, null, entity instanceof LivingEntity ? (LivingEntity)entity : null); - p_57429_.removeBlock(blockpos, false); - } - } ++ public void onCaughtFire(BlockState state, Level world, BlockPos pos, @Nullable net.minecraft.core.Direction face, @Nullable LivingEntity igniter) { ++ explode(world, pos, igniter); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch index 8684651243..20cb8b1065 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch @@ -1,22 +1,17 @@ --- a/net/minecraft/world/level/block/TrapDoorBlock.java +++ b/net/minecraft/world/level/block/TrapDoorBlock.java -@@ -175,6 +_,19 @@ - return super.updateShape(p_57554_, p_57555_, p_57556_, p_57557_, p_57558_, p_57559_); - } - -+ //Forge Start -+ @Override -+ public boolean isLadder(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos, net.minecraft.world.entity.LivingEntity entity) { -+ if (state.getValue(OPEN)) { -+ BlockPos downPos = pos.below(); -+ BlockState down = world.getBlockState(downPos); -+ return down.getBlock().makesOpenTrapdoorAboveClimbable(down, world, downPos, state); -+ } -+ return false; -+ } -+ //Forge End +@@ -205,4 +_,14 @@ + protected BlockSetType getType() { + return this.type; + } + -+ - protected BlockSetType getType() { - return this.type; - } ++ @Override ++ public boolean isLadder(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos, net.minecraft.world.entity.LivingEntity entity) { ++ if (state.getValue(OPEN)) { ++ BlockPos downPos = pos.below(); ++ BlockState down = world.getBlockState(downPos); ++ return down.getBlock().makesOpenTrapdoorAboveClimbable(down, world, downPos, state); ++ } ++ return false; ++ } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch index eb81be237e..5b1c54e6c8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/TripWireBlock.java +++ b/net/minecraft/world/level/block/TripWireBlock.java -@@ -81,7 +_,7 @@ - } +@@ -104,7 +_,7 @@ - public BlockState playerWillDestroy(Level p_57615_, BlockPos p_57616_, BlockState p_57617_, Player p_57618_) { -- if (!p_57615_.isClientSide && !p_57618_.getMainHandItem().isEmpty() && p_57618_.getMainHandItem().is(Items.SHEARS)) { -+ if (!p_57615_.isClientSide && !p_57618_.getMainHandItem().isEmpty() && p_57618_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_DISARM)) { - p_57615_.setBlock(p_57616_, p_57617_.setValue(DISARMED, Boolean.valueOf(true)), 4); - p_57615_.gameEvent(p_57618_, GameEvent.SHEAR, p_57616_); - } + @Override + public BlockState playerWillDestroy(Level p_57615_, BlockPos p_57616_, BlockState p_57617_, Player p_57618_) { +- if (!p_57615_.isClientSide && !p_57618_.getMainHandItem().isEmpty() && p_57618_.getMainHandItem().is(Items.SHEARS)) { ++ if (!p_57615_.isClientSide && !p_57618_.getMainHandItem().isEmpty() && p_57618_.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_DISARM)) { + p_57615_.setBlock(p_57616_, p_57617_.setValue(DISARMED, Boolean.valueOf(true)), 4); + p_57615_.gameEvent(p_57618_, GameEvent.SHEAR, p_57616_); + } diff --git a/patches/minecraft/net/minecraft/world/level/block/TripWireHookBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TripWireHookBlock.java.patch index fdcce5301e..a05968a164 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TripWireHookBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TripWireHookBlock.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/TripWireHookBlock.java +++ b/net/minecraft/world/level/block/TripWireHookBlock.java -@@ -166,8 +_,8 @@ - BlockPos blockpos2 = p_57687_.relative(direction, k); - BlockState blockstate2 = ablockstate[k]; - if (blockstate2 != null) { -+ if (!p_57686_.getBlockState(blockpos2).isAir()) { // FORGE: fix MC-129055 - p_57686_.setBlock(blockpos2, blockstate2.trySetValue(ATTACHED, Boolean.valueOf(flag2)), 3); -- if (!p_57686_.getBlockState(blockpos2).isAir()) { - } - } - } +@@ -176,8 +_,8 @@ + BlockPos blockpos2 = p_57687_.relative(direction, k); + BlockState blockstate2 = ablockstate[k]; + if (blockstate2 != null) { ++ if (!p_57686_.getBlockState(blockpos2).isAir()) { // FORGE: fix MC-129055 + p_57686_.setBlock(blockpos2, blockstate2.trySetValue(ATTACHED, Boolean.valueOf(flag2)), 3); +- if (!p_57686_.getBlockState(blockpos2).isAir()) { + } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/TurtleEggBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TurtleEggBlock.java.patch index 5b0d8e9c92..e100c3c967 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TurtleEggBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TurtleEggBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/TurtleEggBlock.java +++ b/net/minecraft/world/level/block/TurtleEggBlock.java -@@ -166,7 +_,7 @@ - if (!(p_57769_ instanceof LivingEntity)) { +@@ -177,7 +_,7 @@ + if (p_57769_ instanceof Turtle || p_57769_ instanceof Bat) { return false; - } else { -- return p_57769_ instanceof Player || p_57768_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); -+ return p_57769_ instanceof Player || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_57768_, p_57769_); - } - } else { - return false; + } else { +- return !(p_57769_ instanceof LivingEntity) ? false : p_57769_ instanceof Player || p_57768_.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); ++ return !(p_57769_ instanceof LivingEntity) ? false : p_57769_ instanceof Player || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(p_57768_, p_57769_); + } + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch index bdaec23869..26a5f6474c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/level/block/VineBlock.java +++ b/net/minecraft/world/level/block/VineBlock.java -@@ -24,7 +_,7 @@ +@@ -25,7 +_,7 @@ import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -public class VineBlock extends Block { +public class VineBlock extends Block implements net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(VineBlock::new); - public static final BooleanProperty UP = PipeBlock.UP; - public static final BooleanProperty NORTH = PipeBlock.NORTH; -@@ -164,7 +_,7 @@ - - public void randomTick(BlockState p_222655_, ServerLevel p_222656_, BlockPos p_222657_, RandomSource p_222658_) { - if (p_222656_.getGameRules().getBoolean(GameRules.RULE_DO_VINES_SPREAD)) { -- if (p_222658_.nextInt(4) == 0) { -+ if (p_222656_.random.nextInt(4) == 0 && p_222656_.isAreaLoaded(p_222657_, 4)) { // Forge: check area to prevent loading unloaded chunks - Direction direction = Direction.getRandom(p_222658_); - BlockPos blockpos = p_222657_.above(); - if (direction.getAxis().isHorizontal() && !p_222655_.getValue(getPropertyForFace(direction))) { + public static final MapCodec CODEC = simpleCodec(VineBlock::new); + public static final BooleanProperty UP = PipeBlock.UP; + public static final BooleanProperty NORTH = PipeBlock.NORTH; +@@ -181,7 +_,7 @@ + @Override + protected void randomTick(BlockState p_222655_, ServerLevel p_222656_, BlockPos p_222657_, RandomSource p_222658_) { + if (p_222656_.getGameRules().getBoolean(GameRules.RULE_DO_VINES_SPREAD)) { +- if (p_222658_.nextInt(4) == 0) { ++ if (p_222656_.random.nextInt(4) == 0 && p_222656_.isAreaLoaded(p_222657_, 4)) { // Forge: check area to prevent loading unloaded chunks + Direction direction = Direction.getRandom(p_222658_); + BlockPos blockpos = p_222657_.above(); + if (direction.getAxis().isHorizontal() && !p_222655_.getValue(getPropertyForFace(direction))) { diff --git a/patches/minecraft/net/minecraft/world/level/block/WebBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/WebBlock.java.patch index b4d931110d..da68452d1f 100644 --- a/patches/minecraft/net/minecraft/world/level/block/WebBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/WebBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/WebBlock.java +++ b/net/minecraft/world/level/block/WebBlock.java -@@ -8,7 +_,7 @@ +@@ -10,7 +_,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -public class WebBlock extends Block { +public class WebBlock extends Block implements net.minecraftforge.common.IForgeShearable { - public static final MapCodec CODEC = simpleCodec(WebBlock::new); + public static final MapCodec CODEC = simpleCodec(WebBlock::new); - public MapCodec codec() { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch index 8971aaf929..97fe7b17e4 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch @@ -1,190 +1,193 @@ --- a/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java +++ b/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java -@@ -59,6 +_,7 @@ - public static final int NUM_DATA_VALUES = 4; - public static final int BURN_TIME_STANDARD = 200; - public static final int BURN_COOL_SPEED = 2; -+ private final RecipeType recipeType; - protected NonNullList items = NonNullList.withSize(3, ItemStack.EMPTY); - int litTime; - int litDuration; -@@ -107,8 +_,11 @@ - protected AbstractFurnaceBlockEntity(BlockEntityType p_154991_, BlockPos p_154992_, BlockState p_154993_, RecipeType p_154994_) { - super(p_154991_, p_154992_, p_154993_); - this.quickCheck = RecipeManager.createCheck((RecipeType)p_154994_); -+ this.recipeType = p_154994_; - } +@@ -60,6 +_,7 @@ + public static final int NUM_DATA_VALUES = 4; + public static final int BURN_TIME_STANDARD = 200; + public static final int BURN_COOL_SPEED = 2; ++ private final RecipeType recipeType; + protected NonNullList items = NonNullList.withSize(3, ItemStack.EMPTY); + int litTime; + int litDuration; +@@ -114,12 +_,15 @@ + ) { + super(p_154991_, p_154992_, p_154993_); + this.quickCheck = RecipeManager.createCheck((RecipeType)p_154994_); ++ this.recipeType = p_154994_; + } -+ /**@deprecated Forge: get burn times by calling ForgeHooks#getBurnTime(ItemStack)*/ -+ @Deprecated - public static Map getFuel() { - Map map = Maps.newLinkedHashMap(); - add(map, Items.LAVA_BUCKET, 20000); -@@ -205,9 +_,9 @@ - super.load(p_155025_); - this.items = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); - ContainerHelper.loadAllItems(p_155025_, this.items); -- this.litTime = p_155025_.getShort("BurnTime"); -- this.cookingProgress = p_155025_.getShort("CookTime"); -- this.cookingTotalTime = p_155025_.getShort("CookTimeTotal"); -+ this.litTime = p_155025_.getInt("BurnTime"); -+ this.cookingProgress = p_155025_.getInt("CookTime"); -+ this.cookingTotalTime = p_155025_.getInt("CookTimeTotal"); - this.litDuration = this.getBurnDuration(this.items.get(1)); - CompoundTag compoundtag = p_155025_.getCompound("RecipesUsed"); + public static void invalidateCache() { + fuelCache = null; + } -@@ -219,9 +_,9 @@ ++ /**@deprecated Forge: get burn times by calling ForgeHooks#getBurnTime(ItemStack)*/ ++ @Deprecated + public static Map getFuel() { + Map map = fuelCache; + if (map != null) { +@@ -226,9 +_,9 @@ + super.loadAdditional(p_335441_, p_330623_); + this.items = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); + ContainerHelper.loadAllItems(p_335441_, this.items, p_330623_); +- this.litTime = p_335441_.getShort("BurnTime"); +- this.cookingProgress = p_335441_.getShort("CookTime"); +- this.cookingTotalTime = p_335441_.getShort("CookTimeTotal"); ++ this.litTime = p_335441_.getInt("BurnTime"); ++ this.cookingProgress = p_335441_.getInt("CookTime"); ++ this.cookingTotalTime = p_335441_.getInt("CookTimeTotal"); + this.litDuration = this.getBurnDuration(this.items.get(1)); + CompoundTag compoundtag = p_335441_.getCompound("RecipesUsed"); - protected void saveAdditional(CompoundTag p_187452_) { - super.saveAdditional(p_187452_); -- p_187452_.putShort("BurnTime", (short)this.litTime); -- p_187452_.putShort("CookTime", (short)this.cookingProgress); -- p_187452_.putShort("CookTimeTotal", (short)this.cookingTotalTime); -+ p_187452_.putInt("BurnTime", this.litTime); -+ p_187452_.putInt("CookTime", this.cookingProgress); -+ p_187452_.putInt("CookTimeTotal", this.cookingTotalTime); - ContainerHelper.saveAllItems(p_187452_, this.items); - CompoundTag compoundtag = new CompoundTag(); - this.recipesUsed.forEach((p_187449_, p_187450_) -> { -@@ -249,28 +_,30 @@ - } - - int i = p_155017_.getMaxStackSize(); -- if (!p_155017_.isLit() && canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { -+ if (!p_155017_.isLit() && p_155017_.canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { - p_155017_.litTime = p_155017_.getBurnDuration(itemstack); - p_155017_.litDuration = p_155017_.litTime; - if (p_155017_.isLit()) { - flag1 = true; -+ if (itemstack.hasCraftingRemainingItem()) -+ p_155017_.items.set(1, itemstack.getCraftingRemainingItem()); -+ else - if (flag3) { - Item item = itemstack.getItem(); - itemstack.shrink(1); - if (itemstack.isEmpty()) { -- Item item1 = item.getCraftingRemainingItem(); -- p_155017_.items.set(1, item1 == null ? ItemStack.EMPTY : new ItemStack(item1)); -+ p_155017_.items.set(1, itemstack.getCraftingRemainingItem()); - } - } +@@ -240,9 +_,9 @@ + @Override + protected void saveAdditional(CompoundTag p_187452_, HolderLookup.Provider p_330192_) { + super.saveAdditional(p_187452_, p_330192_); +- p_187452_.putShort("BurnTime", (short)this.litTime); +- p_187452_.putShort("CookTime", (short)this.cookingProgress); +- p_187452_.putShort("CookTimeTotal", (short)this.cookingTotalTime); ++ p_187452_.putInt("BurnTime", this.litTime); ++ p_187452_.putInt("CookTime", this.cookingProgress); ++ p_187452_.putInt("CookTimeTotal", this.cookingTotalTime); + ContainerHelper.saveAllItems(p_187452_, this.items, p_330192_); + CompoundTag compoundtag = new CompoundTag(); + this.recipesUsed.forEach((p_187449_, p_187450_) -> compoundtag.putInt(p_187449_.toString(), p_187450_)); +@@ -268,28 +_,30 @@ } - } -- if (p_155017_.isLit() && canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { -+ if (p_155017_.isLit() && p_155017_.canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { - ++p_155017_.cookingProgress; - if (p_155017_.cookingProgress == p_155017_.cookingTotalTime) { - p_155017_.cookingProgress = 0; - p_155017_.cookingTotalTime = getTotalCookTime(p_155014_, p_155017_); -- if (burn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { -+ if (p_155017_.burn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { - p_155017_.setRecipeUsed(recipeholder); - } + int i = p_155017_.getMaxStackSize(); +- if (!p_155017_.isLit() && canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { ++ if (!p_155017_.isLit() && p_155017_.canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { + p_155017_.litTime = p_155017_.getBurnDuration(itemstack); + p_155017_.litDuration = p_155017_.litTime; + if (p_155017_.isLit()) { + flag1 = true; ++ if (itemstack.hasCraftingRemainingItem()) { ++ p_155017_.items.set(1, itemstack.getCraftingRemainingItem()); ++ } else + if (flag3) { + Item item = itemstack.getItem(); + itemstack.shrink(1); + if (itemstack.isEmpty()) { +- Item item1 = item.getCraftingRemainingItem(); +- p_155017_.items.set(1, item1 == null ? ItemStack.EMPTY : new ItemStack(item1)); ++ p_155017_.items.set(1, itemstack.getCraftingRemainingItem()); + } + } + } + } -@@ -295,9 +_,9 @@ +- if (p_155017_.isLit() && canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { ++ if (p_155017_.isLit() && p_155017_.canBurn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { + p_155017_.cookingProgress++; + if (p_155017_.cookingProgress == p_155017_.cookingTotalTime) { + p_155017_.cookingProgress = 0; + p_155017_.cookingTotalTime = getTotalCookTime(p_155014_, p_155017_); +- if (burn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { ++ if (p_155017_.burn(p_155014_.registryAccess(), recipeholder, p_155017_.items, i)) { + p_155017_.setRecipeUsed(recipeholder); + } - } +@@ -313,9 +_,9 @@ + } + } -- private static boolean canBurn(RegistryAccess p_266924_, @Nullable RecipeHolder p_299207_, NonNullList p_155007_, int p_155008_) { -+ private boolean canBurn(RegistryAccess p_266924_, @Nullable RecipeHolder p_299207_, NonNullList p_155007_, int p_155008_) { - if (!p_155007_.get(0).isEmpty() && p_299207_ != null) { -- ItemStack itemstack = p_299207_.value().getResultItem(p_266924_); -+ ItemStack itemstack = ((RecipeHolder>)p_299207_).value().assemble(this, p_266924_); - if (itemstack.isEmpty()) { - return false; - } else { -@@ -306,10 +_,10 @@ - return true; - } else if (!ItemStack.isSameItem(itemstack1, itemstack)) { - return false; -- } else if (itemstack1.getCount() < p_155008_ && itemstack1.getCount() < itemstack1.getMaxStackSize()) { -+ } else if (itemstack1.getCount() + itemstack.getCount() <= p_155008_ && itemstack1.getCount() + itemstack.getCount() <= itemstack1.getMaxStackSize()) { // Forge fix: make furnace respect stack sizes in furnace recipes - return true; +- private static boolean canBurn(RegistryAccess p_266924_, @Nullable RecipeHolder p_299207_, NonNullList p_155007_, int p_155008_) { ++ private boolean canBurn(RegistryAccess p_266924_, @Nullable RecipeHolder p_299207_, NonNullList p_155007_, int p_155008_) { + if (!p_155007_.get(0).isEmpty() && p_299207_ != null) { +- ItemStack itemstack = p_299207_.value().getResultItem(p_266924_); ++ ItemStack itemstack = ((RecipeHolder>)p_299207_).value().assemble(this, p_266924_); + if (itemstack.isEmpty()) { + return false; } else { -- return itemstack1.getCount() < itemstack.getMaxStackSize(); -+ return itemstack1.getCount() + itemstack.getCount() <= itemstack.getMaxStackSize(); // Forge fix: make furnace respect stack sizes in furnace recipes +@@ -325,9 +_,9 @@ + } else if (!ItemStack.isSameItemSameComponents(itemstack1, itemstack)) { + return false; + } else { +- return itemstack1.getCount() < p_155008_ && itemstack1.getCount() < itemstack1.getMaxStackSize() ++ return (itemstack1.getCount() + itemstack.getCount() <= p_155008_ && itemstack1.getCount() + itemstack.getCount() <= itemstack1.getMaxStackSize()) // Forge fix: make furnace respect stack sizes in furnace recipes + ? true +- : itemstack1.getCount() < itemstack.getMaxStackSize(); ++ : itemstack1.getCount() + itemstack.getCount() <= itemstack.getMaxStackSize(); // Forge fix: make furnace respect stack sizes in furnace recipes + } } - } - } else { -@@ -317,15 +_,15 @@ - } - } + } else { +@@ -335,15 +_,15 @@ + } + } -- private static boolean burn(RegistryAccess p_266740_, @Nullable RecipeHolder p_299450_, NonNullList p_267073_, int p_267157_) { -- if (p_299450_ != null && canBurn(p_266740_, p_299450_, p_267073_, p_267157_)) { -+ private boolean burn(RegistryAccess p_266740_, @Nullable RecipeHolder p_299450_, NonNullList p_267073_, int p_267157_) { -+ if (p_299450_ != null && this.canBurn(p_266740_, p_299450_, p_267073_, p_267157_)) { - ItemStack itemstack = p_267073_.get(0); -- ItemStack itemstack1 = p_299450_.value().getResultItem(p_266740_); -+ ItemStack itemstack1 = ((RecipeHolder>)p_299450_).value().assemble(this, p_266740_); - ItemStack itemstack2 = p_267073_.get(2); - if (itemstack2.isEmpty()) { - p_267073_.set(2, itemstack1.copy()); - } else if (itemstack2.is(itemstack1.getItem())) { -- itemstack2.grow(1); -+ itemstack2.grow(itemstack1.getCount()); - } +- private static boolean burn(RegistryAccess p_266740_, @Nullable RecipeHolder p_299450_, NonNullList p_267073_, int p_267157_) { ++ private boolean burn(RegistryAccess p_266740_, @Nullable RecipeHolder p_299450_, NonNullList p_267073_, int p_267157_) { + if (p_299450_ != null && canBurn(p_266740_, p_299450_, p_267073_, p_267157_)) { + ItemStack itemstack = p_267073_.get(0); +- ItemStack itemstack1 = p_299450_.value().getResultItem(p_266740_); ++ ItemStack itemstack1 = ((RecipeHolder>)p_299450_).value().assemble(this, p_266740_); + ItemStack itemstack2 = p_267073_.get(2); + if (itemstack2.isEmpty()) { + p_267073_.set(2, itemstack1.copy()); + } else if (ItemStack.isSameItemSameComponents(itemstack2, itemstack1)) { +- itemstack2.grow(1); ++ itemstack2.grow(itemstack1.getCount()); + } - if (itemstack.is(Blocks.WET_SPONGE.asItem()) && !p_267073_.get(1).isEmpty() && p_267073_.get(1).is(Items.BUCKET)) { -@@ -344,7 +_,7 @@ - return 0; - } else { - Item item = p_58343_.getItem(); -- return getFuel().getOrDefault(item, 0); -+ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58343_, this.recipeType); - } - } + if (itemstack.is(Blocks.WET_SPONGE.asItem()) && !p_267073_.get(1).isEmpty() && p_267073_.get(1).is(Items.BUCKET)) { +@@ -362,7 +_,7 @@ + return 0; + } else { + Item item = p_58343_.getItem(); +- return getFuel().getOrDefault(item, 0); ++ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58343_, this.recipeType); + } + } -@@ -355,7 +_,7 @@ - } +@@ -371,7 +_,7 @@ + } - public static boolean isFuel(ItemStack p_58400_) { -- return getFuel().containsKey(p_58400_.getItem()); -+ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58400_, null) > 0; - } + public static boolean isFuel(ItemStack p_58400_) { +- return getFuel().containsKey(p_58400_.getItem()); ++ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58400_, null) > 0; + } - public int[] getSlotsForFace(Direction p_58363_) { -@@ -431,7 +_,7 @@ - return true; - } else { - ItemStack itemstack = this.items.get(1); -- return isFuel(p_58390_) || p_58390_.is(Items.BUCKET) && !itemstack.is(Items.BUCKET); -+ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58390_, this.recipeType) > 0 || p_58390_.is(Items.BUCKET) && !itemstack.is(Items.BUCKET); - } - } + @Override +@@ -429,7 +_,7 @@ + return true; + } else { + ItemStack itemstack = this.items.get(1); +- return isFuel(p_58390_) || p_58390_.is(Items.BUCKET) && !itemstack.is(Items.BUCKET); ++ return net.minecraftforge.common.ForgeHooks.getBurnTime(p_58390_, this.recipeType) > 0 || p_58390_.is(Items.BUCKET) && !itemstack.is(Items.BUCKET); + } + } -@@ -496,5 +_,33 @@ - p_58342_.accountStack(itemstack); - } - -+ } +@@ -492,5 +_,34 @@ + for (ItemStack itemstack : this.items) { + p_58342_.accountStack(itemstack); + } ++ } + -+ net.minecraftforge.common.util.LazyOptional[] handlers = -+ net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); ++ net.minecraftforge.common.util.LazyOptional[] handlers = ++ net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.remove) { -+ return switch (facing) { -+ case UP -> handlers[0].cast(); -+ case DOWN -> handlers[1].cast(); -+ default -> handlers[2].cast(); -+ }; -+ } -+ return super.getCapability(capability, facing); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.remove) { ++ return switch (facing) { ++ case UP -> handlers[0].cast(); ++ case DOWN -> handlers[1].cast(); ++ default -> handlers[2].cast(); ++ }; ++ } ++ return super.getCapability(capability, facing); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ for (int x = 0; x < handlers.length; x++) -+ handlers[x].invalidate(); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ for (int x = 0; x < handlers.length; x++) { ++ handlers[x].invalidate(); ++ } ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ this.handlers = net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); - } ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ this.handlers = net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java.patch index da7f9cfbb0..b47fa79d4a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BaseContainerBlockEntity.java -@@ -81,4 +_,27 @@ - } - - protected abstract AbstractContainerMenu createMenu(int p_58627_, Inventory p_58628_); +@@ -166,4 +_,27 @@ + p_329140_.remove("Lock"); + p_329140_.remove("Items"); + } + -+ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> createUnSidedHandler()); -+ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { -+ return new net.minecraftforge.items.wrapper.InvWrapper(this); -+ } ++ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> createUnSidedHandler()); ++ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { ++ return new net.minecraftforge.items.wrapper.InvWrapper(this); ++ } + -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { -+ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) -+ return itemHandler.cast(); -+ return super.getCapability(cap, side); -+ } ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { ++ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) ++ return itemHandler.cast(); ++ return super.getCapability(cap, side); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ itemHandler.invalidate(); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ itemHandler.invalidate(); ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> createUnSidedHandler()); -+ } ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> createUnSidedHandler()); ++ } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch index 530dc3e5b8..2183064ba6 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/entity/BeaconBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BeaconBlockEntity.java -@@ -133,8 +_,8 @@ - for(int i1 = 0; i1 < 10 && blockpos.getY() <= l; ++i1) { - BlockState blockstate = p_155108_.getBlockState(blockpos); - Block block = blockstate.getBlock(); -- if (block instanceof BeaconBeamBlock) { -- float[] afloat = ((BeaconBeamBlock)block).getColor().getTextureDiffuseColors(); -+ float[] afloat = blockstate.getBeaconColorMultiplier(p_155108_, blockpos, p_155109_); -+ if (afloat != null) { - if (p_155111_.checkingBeamSections.size() <= 1) { - beaconblockentity$beaconbeamsection = new BeaconBlockEntity.BeaconBeamSection(afloat); - p_155111_.checkingBeamSections.add(beaconblockentity$beaconbeamsection); +@@ -139,8 +_,8 @@ + for (int i1 = 0; i1 < 10 && blockpos.getY() <= l; i1++) { + BlockState blockstate = p_155108_.getBlockState(blockpos); + Block block = blockstate.getBlock(); +- if (block instanceof BeaconBeamBlock) { +- float[] afloat = ((BeaconBeamBlock)block).getColor().getTextureDiffuseColors(); ++ float[] afloat = blockstate.getBeaconColorMultiplier(p_155108_, blockpos, p_155109_); ++ if (afloat != null) { + if (p_155111_.checkingBeamSections.size() <= 1) { + beaconblockentity$beaconbeamsection = new BeaconBlockEntity.BeaconBeamSection(afloat); + p_155111_.checkingBeamSections.add(beaconblockentity$beaconbeamsection); diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BlockEntity.java.patch index f39985f827..d4ec07b6ce 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BlockEntity.java.patch @@ -1,68 +1,53 @@ --- a/net/minecraft/world/level/block/entity/BlockEntity.java +++ b/net/minecraft/world/level/block/entity/BlockEntity.java -@@ -15,7 +_,7 @@ +@@ -27,7 +_,7 @@ import net.minecraft.world.level.block.state.BlockState; import org.slf4j.Logger; -public abstract class BlockEntity { +public abstract class BlockEntity extends net.minecraftforge.common.capabilities.CapabilityProvider implements net.minecraftforge.common.extensions.IForgeBlockEntity { - private static final Logger LOGGER = LogUtils.getLogger(); - private final BlockEntityType type; - @Nullable -@@ -23,11 +_,14 @@ - protected final BlockPos worldPosition; - protected boolean remove; - private BlockState blockState; -+ private CompoundTag customPersistentData; + private static final Logger LOGGER = LogUtils.getLogger(); + private final BlockEntityType type; + @Nullable +@@ -38,9 +_,11 @@ + private DataComponentMap components = DataComponentMap.EMPTY; - public BlockEntity(BlockEntityType p_155228_, BlockPos p_155229_, BlockState p_155230_) { -+ super(BlockEntity.class); - this.type = p_155228_; - this.worldPosition = p_155229_.immutable(); - this.blockState = p_155230_; -+ this.gatherCapabilities(); - } + public BlockEntity(BlockEntityType p_155228_, BlockPos p_155229_, BlockState p_155230_) { ++ super(BlockEntity.class); + this.type = p_155228_; + this.worldPosition = p_155229_.immutable(); + this.blockState = p_155230_; ++ this.gatherCapabilities(); + } - public static BlockPos getPosFromTag(CompoundTag p_187473_) { -@@ -48,9 +_,13 @@ - } + public static BlockPos getPosFromTag(CompoundTag p_187473_) { +@@ -61,6 +_,7 @@ + } - public void load(CompoundTag p_155245_) { -+ if (p_155245_.contains("ForgeData")) this.customPersistentData = p_155245_.getCompound("ForgeData"); -+ if (getCapabilities() != null && p_155245_.contains("ForgeCaps")) deserializeCaps(p_155245_.getCompound("ForgeCaps")); - } + protected void loadAdditional(CompoundTag p_331149_, HolderLookup.Provider p_333170_) { ++ if (getCapabilities() != null && p_331149_.contains("ForgeCaps")) deserializeCaps(p_331149_.getCompound("ForgeCaps")); + } - protected void saveAdditional(CompoundTag p_187471_) { -+ if (this.customPersistentData != null) p_187471_.put("ForgeData", this.customPersistentData.copy()); -+ if (getCapabilities() != null) p_187471_.put("ForgeCaps", serializeCaps()); - } + public final void loadWithComponents(CompoundTag p_331756_, HolderLookup.Provider p_335164_) { +@@ -76,6 +_,7 @@ + } - public final CompoundTag saveWithFullMetadata() { -@@ -163,6 +_,13 @@ + protected void saveAdditional(CompoundTag p_187471_, HolderLookup.Provider p_327783_) { ++ if (getCapabilities() != null) p_187471_.put("ForgeCaps", serializeCaps()); + } - public void setRemoved() { - this.remove = true; -+ this.invalidateCaps(); -+ requestModelDataUpdate(); -+ } + public final CompoundTag saveWithFullMetadata(HolderLookup.Provider p_331193_) { +@@ -205,6 +_,13 @@ + + public void setRemoved() { + this.remove = true; ++ this.invalidateCaps(); ++ requestModelDataUpdate(); ++ } + -+ @Override -+ public void onChunkUnloaded() { -+ this.invalidateCaps(); - } ++ @Override ++ public void onChunkUnloaded() { ++ this.invalidateCaps(); + } - public void clearRemoved() { -@@ -189,6 +_,13 @@ - - public BlockEntityType getType() { - return this.type; -+ } -+ -+ @Override -+ public CompoundTag getPersistentData() { -+ if (this.customPersistentData == null) -+ this.customPersistentData = new CompoundTag(); -+ return this.customPersistentData; - } - - /** @deprecated */ + public void clearRemoved() { diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch index de5d2917e5..74580fcd59 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch @@ -1,87 +1,69 @@ --- a/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java -@@ -148,6 +_,7 @@ +@@ -170,15 +_,18 @@ + for (int i = 0; i < 3; i++) { + p_155293_.set(i, potionbrewing.mix(itemstack, p_155293_.get(i))); + } ++ net.minecraftforge.event.ForgeEventFactory.onPotionBrewed(p_155293_); - private static boolean isBrewable(NonNullList p_155295_) { - ItemStack itemstack = p_155295_.get(3); -+ if (!itemstack.isEmpty()) return net.minecraftforge.common.brewing.BrewingRecipeRegistry.canBrew(p_155295_, itemstack, SLOTS_FOR_SIDES); // divert to VanillaBrewingRegistry - if (itemstack.isEmpty()) { - return false; - } else if (!PotionBrewing.isIngredient(itemstack)) { -@@ -165,21 +_,21 @@ - } +- itemstack.shrink(1); +- if (itemstack.getItem().hasCraftingRemainingItem()) { +- ItemStack itemstack1 = new ItemStack(itemstack.getItem().getCraftingRemainingItem()); ++ if (itemstack.hasCraftingRemainingItem()) { ++ ItemStack itemstack1 = itemstack.getCraftingRemainingItem(); ++ itemstack.shrink(1); + if (itemstack.isEmpty()) { + itemstack = itemstack1; + } else { + Containers.dropItemStack(p_155291_, (double)p_155292_.getX(), (double)p_155292_.getY(), (double)p_155292_.getZ(), itemstack1); + } ++ } else { ++ itemstack.shrink(1); + } - private static void doBrew(Level p_155291_, BlockPos p_155292_, NonNullList p_155293_) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPotionAttemptBrew(p_155293_)) return; - ItemStack itemstack = p_155293_.get(3); - -- for(int i = 0; i < 3; ++i) { -- p_155293_.set(i, PotionBrewing.mix(itemstack, p_155293_.get(i))); -- } -- -- itemstack.shrink(1); -- if (itemstack.getItem().hasCraftingRemainingItem()) { -- ItemStack itemstack1 = new ItemStack(itemstack.getItem().getCraftingRemainingItem()); -+ net.minecraftforge.common.brewing.BrewingRecipeRegistry.brewPotions(p_155293_, itemstack, SLOTS_FOR_SIDES); -+ net.minecraftforge.event.ForgeEventFactory.onPotionBrewed(p_155293_); -+ if (itemstack.hasCraftingRemainingItem()) { -+ ItemStack itemstack1 = itemstack.getCraftingRemainingItem(); -+ itemstack.shrink(1); - if (itemstack.isEmpty()) { - itemstack = itemstack1; - } else { - Containers.dropItemStack(p_155291_, (double)p_155292_.getX(), (double)p_155292_.getY(), (double)p_155292_.getZ(), itemstack1); - } - } -+ else itemstack.shrink(1); - - p_155293_.set(3, itemstack); - p_155291_.levelEvent(1035, p_155292_, 0); -@@ -225,11 +_,11 @@ - - public boolean canPlaceItem(int p_59017_, ItemStack p_59018_) { - if (p_59017_ == 3) { -- return PotionBrewing.isIngredient(p_59018_); -+ return net.minecraftforge.common.brewing.BrewingRecipeRegistry.isValidIngredient(p_59018_); - } else if (p_59017_ == 4) { - return p_59018_.is(Items.BLAZE_POWDER); - } else { -- return (p_59018_.is(Items.POTION) || p_59018_.is(Items.SPLASH_POTION) || p_59018_.is(Items.LINGERING_POTION) || p_59018_.is(Items.GLASS_BOTTLE)) && this.getItem(p_59017_).isEmpty(); -+ return net.minecraftforge.common.brewing.BrewingRecipeRegistry.isValidInput(p_59018_) && this.getItem(p_59017_).isEmpty(); - } - } - -@@ -255,5 +_,33 @@ - - protected AbstractContainerMenu createMenu(int p_58990_, Inventory p_58991_) { - return new BrewingStandMenu(p_58990_, p_58991_, this, this.dataAccess); -+ } + p_155293_.set(3, itemstack); +@@ -207,6 +_,9 @@ + if (p_59017_ == 3) { + PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; + return potionbrewing.isIngredient(p_59018_); ++ } else if (p_59017_ != 4) { ++ PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; ++ return this.getItem(p_59017_).isEmpty() && potionbrewing.isValidInput(p_59018_); + } else { + return p_59017_ == 4 + ? p_59018_.is(Items.BLAZE_POWDER) +@@ -242,5 +_,34 @@ + @Override + protected AbstractContainerMenu createMenu(int p_58990_, Inventory p_58991_) { + return new BrewingStandMenu(p_58990_, p_58991_, this, this.dataAccess); ++ } + -+ net.minecraftforge.common.util.LazyOptional[] handlers = -+ net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); ++ net.minecraftforge.common.util.LazyOptional[] handlers = ++ net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { -+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.remove) { -+ return switch (facing) { -+ case UP -> handlers[0].cast(); -+ case DOWN -> handlers[1].cast(); -+ default -> handlers[2].cast(); -+ }; -+ } -+ return super.getCapability(capability, facing); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable Direction facing) { ++ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.remove) { ++ return switch (facing) { ++ case UP -> handlers[0].cast(); ++ case DOWN -> handlers[1].cast(); ++ default -> handlers[2].cast(); ++ }; ++ } ++ return super.getCapability(capability, facing); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ for (int x = 0; x < handlers.length; x++) -+ handlers[x].invalidate(); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ for (int x = 0; x < handlers.length; x++) { ++ handlers[x].invalidate(); ++ } ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ this.handlers = net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); - } ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ this.handlers = net.minecraftforge.items.wrapper.SidedInvWrapper.create(this, Direction.UP, Direction.DOWN, Direction.NORTH); + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/ChestBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/ChestBlockEntity.java.patch index 2d6b900e88..4874830f39 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/ChestBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/ChestBlockEntity.java.patch @@ -1,48 +1,46 @@ --- a/net/minecraft/world/level/block/entity/ChestBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ChestBlockEntity.java -@@ -160,6 +_,45 @@ - return ChestMenu.threeRows(p_59082_, p_59083_, this); - } - -+ private net.minecraftforge.common.util.LazyOptional chestHandler; -+ @Override -+ public void setBlockState(BlockState p_155251_) { -+ super.setBlockState(p_155251_); -+ if (this.chestHandler != null) { -+ net.minecraftforge.common.util.LazyOptional oldHandler = this.chestHandler; -+ this.chestHandler = null; -+ oldHandler.invalidate(); -+ } -+ } +@@ -183,4 +_,43 @@ + Block block = p_155335_.getBlock(); + p_155333_.blockEvent(p_155334_, block, 1, p_155337_); + } + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, Direction side) { -+ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) { -+ if (this.chestHandler == null) -+ this.chestHandler = net.minecraftforge.common.util.LazyOptional.of(this::createHandler); -+ return this.chestHandler.cast(); -+ } -+ return super.getCapability(cap, side); -+ } ++ private net.minecraftforge.common.util.LazyOptional chestHandler; ++ @Override ++ public void setBlockState(BlockState p_155251_) { ++ super.setBlockState(p_155251_); ++ if (this.chestHandler != null) { ++ var oldHandler = this.chestHandler; ++ this.chestHandler = null; ++ oldHandler.invalidate(); ++ } ++ } + -+ private net.minecraftforge.items.IItemHandlerModifiable createHandler() { -+ BlockState state = this.getBlockState(); -+ if (!(state.getBlock() instanceof ChestBlock chestBlock)) { -+ return new net.minecraftforge.items.wrapper.InvWrapper(this); -+ } -+ Container inv = ChestBlock.getContainer(chestBlock, state, getLevel(), getBlockPos(), true); -+ return new net.minecraftforge.items.wrapper.InvWrapper(inv == null ? this : inv); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, Direction side) { ++ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) { ++ if (this.chestHandler == null) ++ this.chestHandler = net.minecraftforge.common.util.LazyOptional.of(this::createHandler); ++ return this.chestHandler.cast(); ++ } ++ return super.getCapability(cap, side); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ if (chestHandler != null) { -+ chestHandler.invalidate(); -+ chestHandler = null; -+ } -+ } ++ private net.minecraftforge.items.IItemHandlerModifiable createHandler() { ++ BlockState state = this.getBlockState(); ++ if (!(state.getBlock() instanceof ChestBlock chestBlock)) { ++ return new net.minecraftforge.items.wrapper.InvWrapper(this); ++ } ++ Container inv = ChestBlock.getContainer(chestBlock, state, getLevel(), getBlockPos(), true); ++ return new net.minecraftforge.items.wrapper.InvWrapper(inv == null ? this : inv); ++ } + - public void recheckOpen() { - if (!this.remove) { - this.openersCounter.recheckOpeners(this.getLevel(), this.getBlockPos(), this.getBlockState()); ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ if (chestHandler != null) { ++ chestHandler.invalidate(); ++ chestHandler = null; ++ } ++ } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java.patch index 9df45445d0..6c4a0f7814 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java -@@ -125,4 +_,28 @@ - public int getLastInteractedSlot() { - return this.lastInteractedSlot; - } +@@ -158,4 +_,28 @@ + public void removeComponentsFromTag(CompoundTag p_329882_) { + p_329882_.remove("Items"); + } + -+ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(this::createUnSidedHandler); -+ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { -+ return new net.minecraftforge.items.wrapper.InvWrapper(this); -+ } ++ private net.minecraftforge.common.util.LazyOptional itemHandler = net.minecraftforge.common.util.LazyOptional.of(this::createUnSidedHandler); ++ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { ++ return new net.minecraftforge.items.wrapper.InvWrapper(this); ++ } + -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { -+ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) -+ return itemHandler.cast(); -+ return super.getCapability(cap, side); -+ } ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { ++ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.remove) ++ return itemHandler.cast(); ++ return super.getCapability(cap, side); ++ } + -+ @Override -+ public void invalidateCaps() { -+ super.invalidateCaps(); -+ itemHandler.invalidate(); -+ } ++ @Override ++ public void invalidateCaps() { ++ super.invalidateCaps(); ++ itemHandler.invalidate(); ++ } + -+ @Override -+ public void reviveCaps() { -+ super.reviveCaps(); -+ itemHandler = net.minecraftforge.common.util.LazyOptional.of(this::createUnSidedHandler); -+ } ++ @Override ++ public void reviveCaps() { ++ super.reviveCaps(); ++ itemHandler = net.minecraftforge.common.util.LazyOptional.of(this::createUnSidedHandler); ++ } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch index 200ebc12d4..1ad9ef06b5 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch @@ -1,15 +1,13 @@ --- a/net/minecraft/world/level/block/entity/ConduitBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ConduitBlockEntity.java -@@ -152,10 +_,8 @@ - BlockPos blockpos1 = p_155416_.offset(j1, k1, l1); - BlockState blockstate = p_155415_.getBlockState(blockpos1); +@@ -152,8 +_,8 @@ + BlockPos blockpos1 = p_155416_.offset(j1, k1, l1); + BlockState blockstate = p_155415_.getBlockState(blockpos1); -- for(Block block : VALID_BLOCKS) { -- if (blockstate.is(block)) { -- p_155417_.add(blockpos1); -- } -+ if (blockstate.isConduitFrame(p_155415_, blockpos1, p_155416_)) { -+ p_155417_.add(blockpos1); - } - } - } +- for (Block block : VALID_BLOCKS) { +- if (blockstate.is(block)) { ++ { ++ if (blockstate.isConduitFrame(p_155415_, blockpos1, p_155416_)) { + p_155417_.add(blockpos1); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch index ff564ce088..5aa7c3a45a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch @@ -1,36 +1,34 @@ --- a/net/minecraft/world/level/block/entity/HopperBlockEntity.java +++ b/net/minecraft/world/level/block/entity/HopperBlockEntity.java -@@ -130,7 +_,8 @@ - return true; - } +@@ -137,6 +_,7 @@ + } -- private static boolean ejectItems(Level p_155563_, BlockPos p_155564_, BlockState p_155565_, Container p_155566_) { -+ private static boolean ejectItems(Level p_155563_, BlockPos p_155564_, BlockState p_155565_, HopperBlockEntity p_155566_) { -+ if (net.minecraftforge.items.VanillaInventoryCodeHooks.insertHook(p_155566_)) return true; - Container container = getAttachedContainer(p_155563_, p_155564_, p_155565_); - if (container == null) { - return false; -@@ -175,6 +_,8 @@ - } + private static boolean ejectItems(Level p_155563_, BlockPos p_155564_, HopperBlockEntity p_329427_) { ++ if (net.minecraftforge.items.VanillaInventoryCodeHooks.insertHook(p_329427_)) return true; + Container container = getAttachedContainer(p_155563_, p_155564_, p_329427_); + if (container == null) { + return false; +@@ -212,6 +_,8 @@ + } - public static boolean suckInItems(Level p_155553_, Hopper p_155554_) { -+ Boolean ret = net.minecraftforge.items.VanillaInventoryCodeHooks.extractHook(p_155553_, p_155554_); -+ if (ret != null) return ret; - Container container = getSourceContainer(p_155553_, p_155554_); - if (container != null) { - Direction direction = Direction.DOWN; -@@ -414,5 +_,14 @@ - - protected AbstractContainerMenu createMenu(int p_59312_, Inventory p_59313_) { - return new HopperMenu(p_59312_, p_59313_, this); -+ } + public static boolean suckInItems(Level p_155553_, Hopper p_155554_) { ++ Boolean ret = net.minecraftforge.items.VanillaInventoryCodeHooks.extractHook(p_155553_, p_155554_); ++ if (ret != null) return ret; + BlockPos blockpos = BlockPos.containing(p_155554_.getLevelX(), p_155554_.getLevelY() + 1.0, p_155554_.getLevelZ()); + BlockState blockstate = p_155553_.getBlockState(blockpos); + Container container = getSourceContainer(p_155553_, p_155554_, blockpos, blockstate); +@@ -473,5 +_,14 @@ + @Override + protected AbstractContainerMenu createMenu(int p_59312_, Inventory p_59313_) { + return new HopperMenu(p_59312_, p_59313_, this); ++ } + -+ @Override -+ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { -+ return new net.minecraftforge.items.VanillaHopperItemHandler(this); -+ } ++ @Override ++ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { ++ return new net.minecraftforge.items.VanillaHopperItemHandler(this); ++ } + -+ public long getLastUpdateTime() { -+ return this.tickedGameTime; - } ++ public long getLastUpdateTime() { ++ return this.tickedGameTime; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java.patch index 9124e4d7ca..71a5f0f75e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity.java -@@ -217,7 +_,7 @@ - } +@@ -229,7 +_,7 @@ - public boolean canPlaceItemThroughFace(int p_59663_, ItemStack p_59664_, @Nullable Direction p_59665_) { -- return !(Block.byItem(p_59664_.getItem()) instanceof ShulkerBoxBlock); -+ return !(Block.byItem(p_59664_.getItem()) instanceof ShulkerBoxBlock) && p_59664_.getItem().canFitInsideContainerItems(); // FORGE: Make shulker boxes respect Item#canFitInsideContainerItems - } + @Override + public boolean canPlaceItemThroughFace(int p_59663_, ItemStack p_59664_, @Nullable Direction p_59665_) { +- return !(Block.byItem(p_59664_.getItem()) instanceof ShulkerBoxBlock); ++ return !(Block.byItem(p_59664_.getItem()) instanceof ShulkerBoxBlock) && p_59664_.getItem().canFitInsideContainerItems(); // FORGE: Make shulker boxes respect Item#canFitInsideContainerItems + } - public boolean canTakeItemThroughFace(int p_59682_, ItemStack p_59683_, Direction p_59684_) { -@@ -239,6 +_,11 @@ + @Override +@@ -253,6 +_,11 @@ - public boolean isClosed() { - return this.animationStatus == ShulkerBoxBlockEntity.AnimationStatus.CLOSED; -+ } + public boolean isClosed() { + return this.animationStatus == ShulkerBoxBlockEntity.AnimationStatus.CLOSED; ++ } + -+ @Override -+ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { -+ return new net.minecraftforge.items.wrapper.SidedInvWrapper(this, Direction.UP); - } ++ @Override ++ protected net.minecraftforge.items.IItemHandler createUnSidedHandler() { ++ return new net.minecraftforge.items.wrapper.SidedInvWrapper(this, Direction.UP); + } - public static enum AnimationStatus { + public static enum AnimationStatus { diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/SignBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/SignBlockEntity.java.patch index 50b916abd0..70a713f27c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/SignBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/SignBlockEntity.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/entity/SignBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SignBlockEntity.java -@@ -277,6 +_,11 @@ +@@ -286,6 +_,11 @@ + } + } - } - -+ @Override -+ public net.minecraft.world.phys.AABB getRenderBoundingBox() { -+ return new net.minecraft.world.phys.AABB(this.getBlockPos()); -+ } ++ @Override ++ public net.minecraft.world.phys.AABB getRenderBoundingBox() { ++ return new net.minecraft.world.phys.AABB(this.getBlockPos()); ++ } + - public SoundEvent getSignInteractionFailedSoundEvent() { - return SoundEvents.WAXED_SIGN_INTERACT_FAIL; - } + public SoundEvent getSignInteractionFailedSoundEvent() { + return SoundEvents.WAXED_SIGN_INTERACT_FAIL; + } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch index a6c1454c58..379ca35827 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch @@ -1,12 +1,16 @@ --- a/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java -@@ -28,6 +_,9 @@ - } - - } +@@ -30,6 +_,13 @@ + p_155771_.sendBlockUpdated(p_155772_, blockstate, blockstate, 4); + } + } + -+ @org.jetbrains.annotations.Nullable -+ public net.minecraft.world.level.block.entity.BlockEntity getSpawnerBlockEntity(){ return SpawnerBlockEntity.this; } - }; ++ ++ @Override ++ @Nullable ++ public BlockEntity getSpawnerBlockEntity(){ ++ return SpawnerBlockEntity.this; ++ } + }; - public SpawnerBlockEntity(BlockPos p_155752_, BlockState p_155753_) { + public SpawnerBlockEntity(BlockPos p_155752_, BlockState p_155753_) { diff --git a/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch b/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch index d2c3a66027..33a28aca29 100644 --- a/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/grower/TreeGrower.java +++ b/net/minecraft/world/level/block/grower/TreeGrower.java -@@ -85,6 +_,9 @@ - ResourceKey> resourcekey = this.getConfiguredMegaFeature(p_309951_); - if (resourcekey != null) { - Holder> holder = p_309830_.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).getHolder(resourcekey).orElse((Holder.Reference>)null); -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_309830_, p_309951_, p_310327_, holder); -+ holder = event.getFeature(); -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY) return false; - if (holder != null) { - for(int i = 0; i >= -1; --i) { - for(int j = 0; j >= -1; --j) { +@@ -129,6 +_,9 @@ + ResourceKey> resourcekey = this.getConfiguredMegaFeature(p_309951_); + if (resourcekey != null) { + Holder> holder = p_309830_.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).getHolder(resourcekey).orElse(null); ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(p_309830_, p_309951_, p_310327_, holder); ++ holder = event.getFeature(); ++ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY) return false; + if (holder != null) { + for (int i = 0; i >= -1; i--) { + for (int j = 0; j >= -1; j--) { diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch index 845e484649..625d865187 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch @@ -1,37 +1,38 @@ --- a/net/minecraft/world/level/block/piston/PistonBaseBlock.java +++ b/net/minecraft/world/level/block/piston/PistonBaseBlock.java -@@ -181,6 +_,7 @@ - } +@@ -186,6 +_,7 @@ + } - if (p_60195_ == 0) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(p_60193_, p_60194_, direction, true)) return false; - if (!this.moveBlocks(p_60193_, p_60194_, direction, true)) { - return false; - } -@@ -189,6 +_,7 @@ - p_60193_.playSound((Player)null, p_60194_, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, p_60193_.random.nextFloat() * 0.25F + 0.6F); - p_60193_.gameEvent(GameEvent.BLOCK_ACTIVATE, p_60194_, GameEvent.Context.of(blockstate)); - } else if (p_60195_ == 1 || p_60195_ == 2) { -+ if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(p_60193_, p_60194_, direction, false)) return false; - BlockEntity blockentity1 = p_60193_.getBlockEntity(p_60194_.relative(direction)); - if (blockentity1 instanceof PistonMovingBlockEntity) { - ((PistonMovingBlockEntity)blockentity1).finalTick(); -@@ -229,6 +_,7 @@ - p_60193_.gameEvent(GameEvent.BLOCK_DEACTIVATE, p_60194_, GameEvent.Context.of(blockstate1)); - } + if (p_60195_ == 0) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(p_60193_, p_60194_, direction, true)) return false; + if (!this.moveBlocks(p_60193_, p_60194_, direction, true)) { + return false; + } +@@ -194,6 +_,7 @@ + p_60193_.playSound(null, p_60194_, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, p_60193_.random.nextFloat() * 0.25F + 0.6F); + p_60193_.gameEvent(GameEvent.BLOCK_ACTIVATE, p_60194_, GameEvent.Context.of(blockstate)); + } else if (p_60195_ == 1 || p_60195_ == 2) { ++ if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(p_60193_, p_60194_, direction, false)) return false; + BlockEntity blockentity = p_60193_.getBlockEntity(p_60194_.relative(direction)); + if (blockentity instanceof PistonMovingBlockEntity) { + ((PistonMovingBlockEntity)blockentity).finalTick(); +@@ -241,6 +_,7 @@ + p_60193_.gameEvent(GameEvent.BLOCK_DEACTIVATE, p_60194_, GameEvent.Context.of(blockstate1)); + } -+ net.minecraftforge.event.ForgeEventFactory.onPistonMovePost(p_60193_, p_60194_, direction, (p_60195_ == 0)); - return true; - } ++ net.minecraftforge.event.ForgeEventFactory.onPistonMovePost(p_60193_, p_60194_, direction, (p_60195_ == 0)); + return true; + } -@@ -365,6 +_,10 @@ - - public BlockState rotate(BlockState p_60215_, Rotation p_60216_) { - return p_60215_.setValue(FACING, p_60216_.rotate(p_60215_.getValue(FACING))); -+ } +@@ -380,6 +_,11 @@ + @Override + protected BlockState rotate(BlockState p_60215_, Rotation p_60216_) { + return p_60215_.setValue(FACING, p_60216_.rotate(p_60215_.getValue(FACING))); ++ } + -+ public BlockState rotate(BlockState state, net.minecraft.world.level.LevelAccessor world, BlockPos pos, Rotation direction) { -+ return state.getValue(EXTENDED) ? state : super.rotate(state, world, pos, direction); - } ++ @Override ++ public BlockState rotate(BlockState state, net.minecraft.world.level.LevelAccessor world, BlockPos pos, Rotation direction) { ++ return state.getValue(EXTENDED) ? state : super.rotate(state, world, pos, direction); + } - public BlockState mirror(BlockState p_60212_, Mirror p_60213_) { + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch index de00823d01..94bcbb53d7 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java +++ b/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java -@@ -109,7 +_,7 @@ - List list = p_155911_.getEntities((Entity)null, PistonMath.getMovementArea(aabb, direction, d0).minmax(aabb)); - if (!list.isEmpty()) { - List list1 = voxelshape.toAabbs(); -- boolean flag = p_155914_.movedState.is(Blocks.SLIME_BLOCK); -+ boolean flag = p_155914_.movedState.isSlimeBlock(); //TODO: is this patch really needed the logic of the original seems sound revisit later - Iterator iterator = list.iterator(); +@@ -115,7 +_,7 @@ + List list = p_155911_.getEntities(null, PistonMath.getMovementArea(aabb, direction, d0).minmax(aabb)); + if (!list.isEmpty()) { + List list1 = voxelshape.toAabbs(); +- boolean flag = p_155914_.movedState.is(Blocks.SLIME_BLOCK); ++ boolean flag = p_155914_.movedState.isSlimeBlock(); //TODO: is this patch really needed the logic of the original seems sound revisit later + Iterator iterator = list.iterator(); - while(true) { + while (true) { diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch index d9cdab8759..776b3d8a74 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch @@ -1,70 +1,67 @@ --- a/net/minecraft/world/level/block/piston/PistonStructureResolver.java +++ b/net/minecraft/world/level/block/piston/PistonStructureResolver.java -@@ -51,7 +_,7 @@ - } else { - for(int i = 0; i < this.toPush.size(); ++i) { - BlockPos blockpos = this.toPush.get(i); -- if (isSticky(this.level.getBlockState(blockpos)) && !this.addBranchingBlocks(blockpos)) { -+ if (this.level.getBlockState(blockpos).isStickyBlock() && !this.addBranchingBlocks(blockpos)) { - return false; +@@ -50,7 +_,7 @@ + } else { + for (int i = 0; i < this.toPush.size(); i++) { + BlockPos blockpos = this.toPush.get(i); +- if (isSticky(this.level.getBlockState(blockpos)) && !this.addBranchingBlocks(blockpos)) { ++ if (this.level.getBlockState(blockpos).isStickyBlock() && !this.addBranchingBlocks(blockpos)) { + return false; + } } - } -@@ -60,23 +_,9 @@ - } - } +@@ -59,21 +_,9 @@ + } + } -- private static boolean isSticky(BlockState p_155938_) { -- return p_155938_.is(Blocks.SLIME_BLOCK) || p_155938_.is(Blocks.HONEY_BLOCK); -- } +- private static boolean isSticky(BlockState p_155938_) { +- return p_155938_.is(Blocks.SLIME_BLOCK) || p_155938_.is(Blocks.HONEY_BLOCK); +- } - -- private static boolean canStickToEachOther(BlockState p_155940_, BlockState p_155941_) { -- if (p_155940_.is(Blocks.HONEY_BLOCK) && p_155941_.is(Blocks.SLIME_BLOCK)) { -- return false; -- } else if (p_155940_.is(Blocks.SLIME_BLOCK) && p_155941_.is(Blocks.HONEY_BLOCK)) { -- return false; -- } else { -- return isSticky(p_155940_) || isSticky(p_155941_); -- } -- } +- private static boolean canStickToEachOther(BlockState p_155940_, BlockState p_155941_) { +- if (p_155940_.is(Blocks.HONEY_BLOCK) && p_155941_.is(Blocks.SLIME_BLOCK)) { +- return false; +- } else { +- return p_155940_.is(Blocks.SLIME_BLOCK) && p_155941_.is(Blocks.HONEY_BLOCK) ? false : isSticky(p_155940_) || isSticky(p_155941_); +- } +- } - - private boolean addBlockLine(BlockPos p_60434_, Direction p_60435_) { - BlockState blockstate = this.level.getBlockState(p_60434_); -- if (blockstate.isAir()) { -+ if (level.isEmptyBlock(p_60434_)) { - return true; - } else if (!PistonBaseBlock.isPushable(blockstate, this.level, p_60434_, this.pushDirection, false, p_60435_)) { - return true; -@@ -89,11 +_,12 @@ - if (i + this.toPush.size() > 12) { - return false; - } else { -- while(isSticky(blockstate)) { -+ BlockState oldState; -+ while(blockstate.isStickyBlock()) { - BlockPos blockpos = p_60434_.relative(this.pushDirection.getOpposite(), i); -- BlockState blockstate1 = blockstate; -+ oldState = blockstate; - blockstate = this.level.getBlockState(blockpos); -- if (blockstate.isAir() || !canStickToEachOther(blockstate1, blockstate) || !PistonBaseBlock.isPushable(blockstate, this.level, blockpos, this.pushDirection, false, this.pushDirection.getOpposite()) || blockpos.equals(this.pistonPos)) { -+ if (blockstate.isAir() || !(oldState.canStickTo(blockstate) && blockstate.canStickTo(oldState)) || !PistonBaseBlock.isPushable(blockstate, this.level, blockpos, this.pushDirection, false, this.pushDirection.getOpposite()) || blockpos.equals(this.pistonPos)) { - break; - } + private boolean addBlockLine(BlockPos p_60434_, Direction p_60435_) { + BlockState blockstate = this.level.getBlockState(p_60434_); +- if (blockstate.isAir()) { ++ if (level.isEmptyBlock(p_60434_)) { + return true; + } else if (!PistonBaseBlock.isPushable(blockstate, this.level, p_60434_, this.pushDirection, false, p_60435_)) { + return true; +@@ -86,12 +_,12 @@ + if (i + this.toPush.size() > 12) { + return false; + } else { +- while (isSticky(blockstate)) { ++ while (blockstate.isStickyBlock()) { + BlockPos blockpos = p_60434_.relative(this.pushDirection.getOpposite(), i); + BlockState blockstate1 = blockstate; + blockstate = this.level.getBlockState(blockpos); + if (blockstate.isAir() +- || !canStickToEachOther(blockstate1, blockstate) ++ || !(blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1)) + || !PistonBaseBlock.isPushable(blockstate, this.level, blockpos, this.pushDirection, false, this.pushDirection.getOpposite()) + || blockpos.equals(this.pistonPos)) { + break; +@@ -119,7 +_,7 @@ -@@ -120,7 +_,7 @@ - - for(int k = 0; k <= j + l; ++k) { - BlockPos blockpos2 = this.toPush.get(k); -- if (isSticky(this.level.getBlockState(blockpos2)) && !this.addBranchingBlocks(blockpos2)) { -+ if (this.level.getBlockState(blockpos2).isStickyBlock() && !this.addBranchingBlocks(blockpos2)) { - return false; - } - } -@@ -174,7 +_,7 @@ - if (direction.getAxis() != this.pushDirection.getAxis()) { - BlockPos blockpos = p_60432_.relative(direction); - BlockState blockstate1 = this.level.getBlockState(blockpos); -- if (canStickToEachOther(blockstate1, blockstate) && !this.addBlockLine(blockpos, direction)) { -+ if (blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1) && !this.addBlockLine(blockpos, direction)) { - return false; + for (int k = 0; k <= j + l; k++) { + BlockPos blockpos2 = this.toPush.get(k); +- if (isSticky(this.level.getBlockState(blockpos2)) && !this.addBranchingBlocks(blockpos2)) { ++ if (this.level.getBlockState(blockpos2).isStickyBlock() && !this.addBranchingBlocks(blockpos2)) { + return false; + } + } +@@ -173,7 +_,7 @@ + if (direction.getAxis() != this.pushDirection.getAxis()) { + BlockPos blockpos = p_60432_.relative(direction); + BlockState blockstate1 = this.level.getBlockState(blockpos); +- if (canStickToEachOther(blockstate1, blockstate) && !this.addBlockLine(blockpos, direction)) { ++ if (blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1) && !this.addBlockLine(blockpos, direction)) { + return false; + } } - } diff --git a/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch b/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch index 75d730240f..5042fbc687 100644 --- a/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch @@ -1,159 +1,170 @@ --- a/net/minecraft/world/level/block/state/BlockBehaviour.java +++ b/net/minecraft/world/level/block/state/BlockBehaviour.java -@@ -107,6 +_,17 @@ - this.dynamicShape = p_60452_.dynamicShape; - this.requiredFeatures = p_60452_.requiredFeatures; - this.properties = p_60452_; -+ final ResourceLocation lootTableCache = p_60452_.drops; -+ if (lootTableCache != null) { -+ this.lootTableSupplier = () -> lootTableCache; -+ } else if (p_60452_.lootTableSupplier != null) { -+ this.lootTableSupplier = p_60452_.lootTableSupplier; -+ } else { -+ this.lootTableSupplier = () -> { -+ ResourceLocation registryName = net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey((Block) this); -+ return new ResourceLocation(registryName.getNamespace(), "blocks/" + registryName.getPath()); -+ }; -+ } - } +@@ -97,6 +_,7 @@ + protected final boolean dynamicShape; + protected final FeatureFlagSet requiredFeatures; + protected final BlockBehaviour.Properties properties; ++ private final java.util.function.Supplier> lootTableSupplier; + @Nullable + protected ResourceKey drops; - public BlockBehaviour.Properties properties() { -@@ -171,7 +_,7 @@ - /** @deprecated */ - @Deprecated - public void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) { -- if (p_60515_.hasBlockEntity() && !p_60515_.is(p_60518_.getBlock())) { -+ if (p_60515_.hasBlockEntity() && (!p_60515_.is(p_60518_.getBlock()) || !p_60518_.hasBlockEntity())) { - p_60516_.removeBlockEntity(p_60517_); - } - -@@ -183,7 +_,8 @@ - if (!p_310712_.isAir() && p_312709_.getBlockInteraction() != Explosion.BlockInteraction.TRIGGER_BLOCK) { - Block block = p_310712_.getBlock(); - boolean flag = p_312709_.getIndirectSourceEntity() instanceof Player; -- if (block.dropFromExplosion(p_312709_) && p_311693_ instanceof ServerLevel) { -+ if (p_310712_.canDropFromExplosion(p_311693_, p_311490_, p_312709_) && p_311693_ instanceof ServerLevel) { +@@ -112,6 +_,18 @@ + this.dynamicShape = p_60452_.dynamicShape; + this.requiredFeatures = p_60452_.requiredFeatures; + this.properties = p_60452_; + - ServerLevel serverlevel = (ServerLevel)p_311693_; - BlockEntity blockentity = p_310712_.hasBlockEntity() ? p_311693_.getBlockEntity(p_311490_) : null; - LootParams.Builder lootparams$builder = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(p_311490_)).withParameter(LootContextParams.TOOL, ItemStack.EMPTY).withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockentity).withOptionalParameter(LootContextParams.THIS_ENTITY, p_312709_.getDirectSourceEntity()); -@@ -196,9 +_,7 @@ - p_311277_.accept(p_309419_, p_311490_); - }); - } -- -- p_311693_.setBlock(p_311490_, Blocks.AIR.defaultBlockState(), 3); -- block.wasExploded(p_311693_, p_311490_, p_312709_); -+ p_310712_.onBlockExploded(p_311693_, p_311490_, p_312709_); - } - } ++ final ResourceKey lootTableCache = p_60452_.drops; ++ if (lootTableCache != null) { ++ this.lootTableSupplier = () -> lootTableCache; ++ } else if (p_60452_.lootTableSupplier != null) { ++ this.lootTableSupplier = p_60452_.lootTableSupplier; ++ } else { ++ this.lootTableSupplier = () -> { ++ ResourceLocation resourcelocation = BuiltInRegistries.BLOCK.getKey(this.asBlock()); ++ return ResourceKey.create(Registries.LOOT_TABLE, resourcelocation.withPrefix("blocks/")); ++ }; ++ } + } -@@ -400,14 +_,15 @@ - if (f == -1.0F) { - return 0.0F; - } else { -- int i = p_60467_.hasCorrectToolForDrops(p_60466_) ? 30 : 100; -- return p_60467_.getDestroySpeed(p_60466_) / f / (float)i; -+ int i = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(p_60466_, p_60467_) ? 30 : 100; -+ return p_60467_.getDigSpeed(p_60466_, p_60469_) / f / (float)i; - } - } + public BlockBehaviour.Properties properties() { +@@ -160,7 +_,7 @@ + } - /** @deprecated */ - @Deprecated - public void spawnAfterBreak(BlockState p_222949_, ServerLevel p_222950_, BlockPos p_222951_, ItemStack p_222952_, boolean p_222953_) { -+ if (p_222953_) net.minecraftforge.common.ForgeHooks.dropXpForBlock(p_222949_, p_222950_, p_222951_, p_222952_); - } + protected void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) { +- if (p_60515_.hasBlockEntity() && !p_60515_.is(p_60518_.getBlock())) { ++ if (p_60515_.hasBlockEntity() && (!p_60515_.is(p_60518_.getBlock()) || !p_60518_.hasBlockEntity())) { + p_60516_.removeBlockEntity(p_60517_); + } + } +@@ -169,7 +_,7 @@ + if (!p_310712_.isAir() && p_312709_.getBlockInteraction() != Explosion.BlockInteraction.TRIGGER_BLOCK) { + Block block = p_310712_.getBlock(); + boolean flag = p_312709_.getIndirectSourceEntity() instanceof Player; +- if (block.dropFromExplosion(p_312709_) && p_311693_ instanceof ServerLevel serverlevel) { ++ if (p_310712_.canDropFromExplosion(p_311693_, p_311490_, p_312709_) && p_311693_ instanceof ServerLevel serverlevel) { + BlockEntity blockentity = p_310712_.hasBlockEntity() ? p_311693_.getBlockEntity(p_311490_) : null; + LootParams.Builder lootparams$builder = new LootParams.Builder(serverlevel) + .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(p_311490_)) +@@ -184,8 +_,7 @@ + p_310712_.getDrops(lootparams$builder).forEach(p_309419_ -> p_311277_.accept(p_309419_, p_311490_)); + } - /** @deprecated */ -@@ -434,8 +_,7 @@ +- p_311693_.setBlock(p_311490_, Blocks.AIR.defaultBlockState(), 3); +- block.wasExploded(p_311693_, p_311490_, p_312709_); ++ p_310712_.onBlockExploded(p_311693_, p_311490_, p_312709_); + } + } - public final ResourceLocation getLootTable() { - if (this.drops == null) { -- ResourceLocation resourcelocation = BuiltInRegistries.BLOCK.getKey(this.asBlock()); -- this.drops = resourcelocation.withPrefix("blocks/"); -+ this.drops = this.lootTableSupplier.get(); - } +@@ -336,12 +_,15 @@ + if (f == -1.0F) { + return 0.0F; + } else { +- int i = p_60467_.hasCorrectToolForDrops(p_60466_) ? 30 : 100; +- return p_60467_.getDestroySpeed(p_60466_) / f / (float)i; ++ int i = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(p_60466_, p_60467_) ? 30 : 100; ++ return p_60467_.getDestroySpeed(p_60466_, p_60469_) / f / (float)i; + } + } - return this.drops; -@@ -458,6 +_,14 @@ - return this.properties.destroyTime; - } + protected void spawnAfterBreak(BlockState p_222949_, ServerLevel p_222950_, BlockPos p_222951_, ItemStack p_222952_, boolean p_222953_) { ++ if (p_222953_) { ++ net.minecraftforge.common.ForgeHooks.dropXpForBlock(p_222949_, p_222950_, p_222951_, p_222952_); ++ } + } -+ protected boolean isAir(BlockState state) { -+ return ((BlockStateBase)state).isAir; -+ } + protected void attack(BlockState p_60499_, Level p_60500_, BlockPos p_60501_, Player p_60502_) { +@@ -360,8 +_,7 @@ + + public final ResourceKey getLootTable() { + if (this.drops == null) { +- ResourceLocation resourcelocation = BuiltInRegistries.BLOCK.getKey(this.asBlock()); +- this.drops = ResourceKey.create(Registries.LOOT_TABLE, resourcelocation.withPrefix("blocks/")); ++ this.drops = this.lootTableSupplier.get(); + } + + return this.drops; +@@ -378,6 +_,7 @@ + return this.isRandomlyTicking; + } + ++ /** @deprecated Use more sensitive version {@link IForgeBlockState#getSoundType(IWorldReader, BlockPos, Entity) } */ + protected SoundType getSoundType(BlockState p_328629_) { + return this.soundType; + } +@@ -394,6 +_,10 @@ + return this.properties.destroyTime; + } + ++ protected boolean isAir(BlockState state) { ++ return ((BlockStateBase)state).isAir; ++ } + -+ /* ======================================== FORGE START ===================================== */ -+ private final java.util.function.Supplier lootTableSupplier; -+ /* ========================================= FORGE END ====================================== */ + public abstract static class BlockStateBase extends StateHolder { + private final int lightEmission; + private final boolean useShapeForLightOcclusion; +@@ -523,12 +_,14 @@ + return this.useShapeForLightOcclusion; + } + ++ /** @deprecated Forge: Use {@link BlockState#getLightEmission(BlockGetter, BlockPos)} instead */ ++ @Deprecated + public int getLightEmission() { + return this.lightEmission; + } + + public boolean isAir() { +- return this.isAir; ++ return this.getBlock().isAir((BlockState)this); + } + + public boolean ignitedByLava() { +@@ -541,9 +_,11 @@ + } + + public MapColor getMapColor(BlockGetter p_285002_, BlockPos p_285293_) { +- return this.mapColor; ++ return getBlock().getMapColor(this.asState(), p_285002_, p_285293_, this.mapColor); + } + ++ /** @deprecated use {@link BlockState#rotate(LevelAccessor, BlockPos, Rotation)} */ ++ @Deprecated + public BlockState rotate(Rotation p_60718_) { + return this.getBlock().rotate(this.asState(), p_60718_); + } +@@ -597,6 +_,8 @@ + } + + public PushReaction getPistonPushReaction() { ++ PushReaction reaction = getBlock().getPistonPushReaction(asState()); ++ if (reaction != null) return reaction; + return this.pushReaction; + } + +@@ -959,10 +_,11 @@ + boolean spawnTerrainParticles = true; + NoteBlockInstrument instrument = NoteBlockInstrument.HARP; + boolean replaceable; ++ private java.util.function.Supplier> lootTableSupplier; + BlockBehaviour.StateArgumentPredicate> isValidSpawn = (p_284893_, p_284894_, p_284895_, p_284896_) -> p_284893_.isFaceSturdy( + p_284894_, p_284895_, Direction.UP + ) +- && p_284893_.getLightEmission() < 14; ++ && p_284893_.getLightEmission(p_284894_, p_284895_) < 14; + BlockBehaviour.StatePredicate isRedstoneConductor = (p_284888_, p_284889_, p_284890_) -> p_284888_.isCollisionShapeFullBlock(p_284889_, p_284890_); + BlockBehaviour.StatePredicate isSuffocating = (p_284885_, p_284886_, p_284887_) -> p_284885_.blocksMotion() && p_284885_.isCollisionShapeFullBlock(p_284886_, p_284887_); + BlockBehaviour.StatePredicate isViewBlocking = this.isSuffocating; +@@ -1102,8 +_,14 @@ + return this; + } + ++ @Deprecated // FORGE: Use the variant that takes a Supplier below + public BlockBehaviour.Properties dropsLike(Block p_60917_) { + this.drops = p_60917_.getLootTable(); ++ return this; ++ } + - public abstract static class BlockStateBase extends StateHolder { - private final int lightEmission; - private final boolean useShapeForLightOcclusion; -@@ -593,12 +_,14 @@ - return this.useShapeForLightOcclusion; - } ++ public BlockBehaviour.Properties lootFrom(java.util.function.Supplier blockIn) { ++ this.lootTableSupplier = () -> blockIn.get().getLootTable(); + return this; + } -+ /** @deprecated Forge: Use {@link BlockState#getLightEmission(BlockGetter, BlockPos)} instead */ -+ @Deprecated - public int getLightEmission() { - return this.lightEmission; - } - - public boolean isAir() { -- return this.isAir; -+ return this.getBlock().isAir((BlockState)this); - } - - public boolean ignitedByLava() { -@@ -612,9 +_,11 @@ - } - - public MapColor getMapColor(BlockGetter p_285002_, BlockPos p_285293_) { -- return this.mapColor; -+ return getBlock().getMapColor(this.asState(), p_285002_, p_285293_, this.mapColor); - } - -+ /** @deprecated use {@link BlockState#rotate(LevelAccessor, BlockPos, Rotation)} */ -+ @Deprecated - public BlockState rotate(Rotation p_60718_) { - return this.getBlock().rotate(this.asState(), p_60718_); - } -@@ -668,6 +_,8 @@ - } - - public PushReaction getPistonPushReaction() { -+ PushReaction reaction = getBlock().getPistonPushReaction(asState()); -+ if (reaction != null) return reaction; - return this.pushReaction; - } - -@@ -1032,8 +_,9 @@ - boolean spawnTerrainParticles = true; - NoteBlockInstrument instrument = NoteBlockInstrument.HARP; - boolean replaceable; -+ private java.util.function.Supplier lootTableSupplier; - BlockBehaviour.StateArgumentPredicate> isValidSpawn = (p_284893_, p_284894_, p_284895_, p_284896_) -> { -- return p_284893_.isFaceSturdy(p_284894_, p_284895_, Direction.UP) && p_284893_.getLightEmission() < 14; -+ return p_284893_.isFaceSturdy(p_284894_, p_284895_, Direction.UP) && p_284893_.getLightEmission(p_284894_, p_284895_) < 14; - }; - BlockBehaviour.StatePredicate isRedstoneConductor = (p_284888_, p_284889_, p_284890_) -> { - return p_284888_.isCollisionShapeFullBlock(p_284889_, p_284890_); -@@ -1187,9 +_,15 @@ - return this; - } - -+ @Deprecated // FORGE: Use the variant that takes a Supplier below - public BlockBehaviour.Properties dropsLike(Block p_60917_) { -- this.drops = p_60917_.getLootTable(); -+ this.lootTableSupplier = () -> net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_60917_).get().getLootTable(); - return this; -+ } -+ -+ public BlockBehaviour.Properties lootFrom(java.util.function.Supplier blockIn) { -+ this.lootTableSupplier = () -> blockIn.get().getLootTable(); -+ return this; - } - - public BlockBehaviour.Properties ignitedByLava() { diff --git a/patches/minecraft/net/minecraft/world/level/block/state/BlockState.java.patch b/patches/minecraft/net/minecraft/world/level/block/state/BlockState.java.patch index cc80eaa344..f068008450 100644 --- a/patches/minecraft/net/minecraft/world/level/block/state/BlockState.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/state/BlockState.java.patch @@ -6,6 +6,6 @@ -public class BlockState extends BlockBehaviour.BlockStateBase { +public class BlockState extends BlockBehaviour.BlockStateBase implements net.minecraftforge.common.extensions.IForgeBlockState { - public static final Codec CODEC = codec(BuiltInRegistries.BLOCK.byNameCodec(), Block::defaultBlockState).stable(); + public static final Codec CODEC = codec(BuiltInRegistries.BLOCK.byNameCodec(), Block::defaultBlockState).stable(); - public BlockState(Block p_61042_, ImmutableMap, Comparable> p_61043_, MapCodec p_61044_) { + public BlockState(Block p_61042_, Reference2ObjectArrayMap, Comparable> p_328252_, MapCodec p_61044_) { diff --git a/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch index 1e5d204582..355e9df401 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch @@ -1,46 +1,46 @@ --- a/net/minecraft/world/level/chunk/ChunkAccess.java +++ b/net/minecraft/world/level/chunk/ChunkAccess.java -@@ -299,25 +_,30 @@ - public abstract CompoundTag getBlockEntityNbtForSaving(BlockPos p_62104_); +@@ -311,23 +_,28 @@ - public final void findBlockLightSources(BiConsumer p_285269_) { -- this.findBlocks((p_284897_) -> { -- return p_284897_.getLightEmission() != 0; -+ this.findBlocks((p_284897_, pos) -> { -+ return p_284897_.getLightEmission(this, pos) != 0; - }, p_285269_); - } + @Override + public final void findBlockLightSources(BiConsumer p_285269_) { +- this.findBlocks(p_284897_ -> p_284897_.getLightEmission() != 0, p_285269_); ++ this.findBlocks((p_284897_, pos) -> p_284897_.getLightEmission(this, pos) != 0, p_285269_); + } - public void findBlocks(Predicate p_285343_, BiConsumer p_285030_) { -+ findBlocks((state, pos) -> p_285343_.test(state), p_285030_); -+ } + public void findBlocks(Predicate p_285343_, BiConsumer p_285030_) { ++ findBlocks((state, pos) -> p_285343_.test(state), p_285030_); ++ } + -+ public void findBlocks(java.util.function.BiPredicate p_285343_, BiConsumer p_285030_) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); ++ public void findBlocks(java.util.function.BiPredicate p_285343_, BiConsumer p_285030_) { + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - for(int i = this.getMinSection(); i < this.getMaxSection(); ++i) { - LevelChunkSection levelchunksection = this.getSection(this.getSectionIndexFromSectionY(i)); -- if (levelchunksection.maybeHas(p_285343_)) { -+ if (levelchunksection.maybeHas((state) -> p_285343_.test(state, BlockPos.ZERO))) { - BlockPos blockpos = SectionPos.of(this.chunkPos, i).origin(); + for (int i = this.getMinSection(); i < this.getMaxSection(); i++) { + LevelChunkSection levelchunksection = this.getSection(this.getSectionIndexFromSectionY(i)); +- if (levelchunksection.maybeHas(p_285343_)) { ++ if (levelchunksection.maybeHas(state -> p_285343_.test(state, BlockPos.ZERO))) { + BlockPos blockpos = SectionPos.of(this.chunkPos, i).origin(); - for(int j = 0; j < 16; ++j) { - for(int k = 0; k < 16; ++k) { - for(int l = 0; l < 16; ++l) { - BlockState blockstate = levelchunksection.getBlockState(l, j, k); -- if (p_285343_.test(blockstate)) { -- p_285030_.accept(blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k), blockstate); -+ blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k); -+ if (p_285343_.test(blockstate, blockpos$mutableblockpos.immutable())) { -+ p_285030_.accept(blockpos$mutableblockpos, blockstate); - } - } - } -@@ -463,4 +_,7 @@ + for (int j = 0; j < 16; j++) { + for (int k = 0; k < 16; k++) { + for (int l = 0; l < 16; l++) { + BlockState blockstate = levelchunksection.getBlockState(l, j, k); +- if (p_285343_.test(blockstate)) { +- p_285030_.accept(blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k), blockstate); ++ blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k); ++ if (p_285343_.test(blockstate, blockpos$mutableblockpos.immutable())) { ++ p_285030_.accept(blockpos$mutableblockpos, blockstate); + } + } + } +@@ -471,5 +_,10 @@ + } - public static record TicksToSave(SerializableTickContainer blocks, SerializableTickContainer fluids) { - } + public static record TicksToSave(SerializableTickContainer blocks, SerializableTickContainer fluids) { ++ } + -+ @Nullable -+ public net.minecraft.world.level.LevelAccessor getWorldForge() { return null; } ++ @Nullable ++ public net.minecraft.world.level.LevelAccessor getWorldForge() { ++ return null; + } } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/ImposterProtoChunk.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/ImposterProtoChunk.java.patch index 19bc9721be..b22128f7c4 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/ImposterProtoChunk.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/ImposterProtoChunk.java.patch @@ -1,14 +1,12 @@ --- a/net/minecraft/world/level/chunk/ImposterProtoChunk.java +++ b/net/minecraft/world/level/chunk/ImposterProtoChunk.java -@@ -181,6 +_,11 @@ - this.wrapped.findBlocks(p_285465_, p_285061_); - } - -+ @Override -+ public void findBlocks(java.util.function.BiPredicate p_285343_, BiConsumer p_285030_) { -+ this.wrapped.findBlocks(p_285343_, p_285030_); -+ } +@@ -292,4 +_,9 @@ + public ChunkSkyLightSources getSkyLightSources() { + return this.wrapped.getSkyLightSources(); + } + - public TickContainerAccess getBlockTicks() { - return this.allowWrites ? this.wrapped.getBlockTicks() : BlackholeTickAccess.emptyContainer(); - } ++ @Override ++ public void findBlocks(java.util.function.BiPredicate p_285343_, BiConsumer p_285030_) { ++ this.wrapped.findBlocks(p_285343_, p_285030_); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch index 08310348e9..fb809b29c9 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch @@ -1,203 +1,195 @@ --- a/net/minecraft/world/level/chunk/LevelChunk.java +++ b/net/minecraft/world/level/chunk/LevelChunk.java -@@ -47,7 +_,7 @@ +@@ -50,7 +_,7 @@ import net.minecraft.world.ticks.TickContainerAccess; import org.slf4j.Logger; -public class LevelChunk extends ChunkAccess { +public class LevelChunk extends ChunkAccess implements net.minecraftforge.common.capabilities.ICapabilityProviderImpl { - static final Logger LOGGER = LogUtils.getLogger(); - private static final TickingBlockEntity NULL_TICKER = new TickingBlockEntity() { - public void tick() { -@@ -94,6 +_,7 @@ - this.postLoad = p_196861_; - this.blockTicks = p_196857_; - this.fluidTicks = p_196858_; -+ this.capProvider.initInternal(); - } + static final Logger LOGGER = LogUtils.getLogger(); + private static final TickingBlockEntity NULL_TICKER = new TickingBlockEntity() { + @Override +@@ -111,6 +_,7 @@ + this.postLoad = p_196861_; + this.blockTicks = p_196857_; + this.fluidTicks = p_196858_; ++ this.capProvider.initInternal(); + } - public LevelChunk(ServerLevel p_196850_, ProtoChunk p_196851_, @Nullable LevelChunk.PostLoadProcessor p_196852_) { -@@ -245,14 +_,14 @@ - boolean flag2 = blockstate.hasBlockEntity(); - if (!this.level.isClientSide) { - blockstate.onRemove(this.level, p_62865_, p_62866_, p_62867_); -- } else if (!blockstate.is(block) && flag2) { -+ } else if ((!blockstate.is(block) || !p_62866_.hasBlockEntity()) && flag2) { - this.removeBlockEntity(p_62865_); + public LevelChunk(ServerLevel p_196850_, ProtoChunk p_196851_, @Nullable LevelChunk.PostLoadProcessor p_196852_) { +@@ -270,14 +_,14 @@ + boolean flag2 = blockstate.hasBlockEntity(); + if (!this.level.isClientSide) { + blockstate.onRemove(this.level, p_62865_, p_62866_, p_62867_); +- } else if (!blockstate.is(block) && flag2) { ++ } else if ((!blockstate.is(block) || !p_62866_.hasBlockEntity()) && flag2) { + this.removeBlockEntity(p_62865_); + } + + if (!levelchunksection.getBlockState(j, k, l).is(block)) { + return null; + } else { +- if (!this.level.isClientSide) { ++ if (!this.level.isClientSide && !this.level.captureBlockSnapshots) { + p_62866_.onPlace(this.level, p_62865_, blockstate, p_62867_); + } + +@@ -321,6 +_,12 @@ + @Nullable + public BlockEntity getBlockEntity(BlockPos p_62868_, LevelChunk.EntityCreationType p_62869_) { + BlockEntity blockentity = this.blockEntities.get(p_62868_); ++ ++ if (blockentity != null && blockentity.isRemoved()) { ++ blockEntities.remove(p_62868_); ++ blockentity = null; ++ } ++ + if (blockentity == null) { + CompoundTag compoundtag = this.pendingBlockEntities.remove(p_62868_); + if (compoundtag != null) { +@@ -338,9 +_,6 @@ + this.addAndRegisterBlockEntity(blockentity); + } + } +- } else if (blockentity.isRemoved()) { +- this.blockEntities.remove(p_62868_); +- return null; + } + + return blockentity; +@@ -354,6 +_,7 @@ } - if (!levelchunksection.getBlockState(j, k, l).is(block)) { - return null; - } else { -- if (!this.level.isClientSide) { -+ if (!this.level.isClientSide && !this.level.captureBlockSnapshots) { - p_62866_.onPlace(this.level, p_62865_, blockstate, p_62867_); - } + this.updateBlockEntityTicker(p_156391_); ++ p_156391_.onLoad(); + } + } -@@ -295,6 +_,10 @@ - @Nullable - public BlockEntity getBlockEntity(BlockPos p_62868_, LevelChunk.EntityCreationType p_62869_) { - BlockEntity blockentity = this.blockEntities.get(p_62868_); -+ if (blockentity != null && blockentity.isRemoved()) { -+ blockEntities.remove(p_62868_); -+ blockentity = null; -+ } - if (blockentity == null) { - CompoundTag compoundtag = this.pendingBlockEntities.remove(p_62868_); - if (compoundtag != null) { -@@ -312,9 +_,6 @@ - this.addAndRegisterBlockEntity(blockentity); +@@ -389,9 +_,14 @@ + public CompoundTag getBlockEntityNbtForSaving(BlockPos p_62932_, HolderLookup.Provider p_329605_) { + BlockEntity blockentity = this.getBlockEntity(p_62932_); + if (blockentity != null && !blockentity.isRemoved()) { ++ try { + CompoundTag compoundtag1 = blockentity.saveWithFullMetadata(this.level.registryAccess()); + compoundtag1.putBoolean("keepPacked", false); + return compoundtag1; ++ } catch (Exception e) { ++ LOGGER.error("A BlockEntity type {} has thrown an exception trying to write state. It will not persist, Report this to the mod author", blockentity.getClass().getName(), e); ++ return null; ++ } + } else { + CompoundTag compoundtag = this.pendingBlockEntities.get(p_62932_); + if (compoundtag != null) { +@@ -471,7 +_,7 @@ + p_187974_.accept((p_327409_, p_327410_, p_327411_) -> { + BlockEntity blockentity = this.getBlockEntity(p_327409_, LevelChunk.EntityCreationType.IMMEDIATE); + if (blockentity != null && p_327411_ != null && blockentity.getType() == p_327410_) { +- blockentity.loadWithComponents(p_327411_, this.level.registryAccess()); ++ blockentity.handleUpdateTag(p_327411_, this.level.registryAccess()); } - } -- } else if (blockentity.isRemoved()) { -- this.blockEntities.remove(p_62868_); -- return null; - } + }); + } +@@ -579,6 +_,7 @@ + } - return blockentity; -@@ -330,6 +_,7 @@ - } + public void clearAllBlockEntities() { ++ this.blockEntities.values().forEach(BlockEntity::onChunkUnloaded); + this.blockEntities.values().forEach(BlockEntity::setRemoved); + this.blockEntities.clear(); + this.tickersInLevel.values().forEach(p_187966_ -> p_187966_.rebind(NULL_TICKER)); +@@ -586,6 +_,7 @@ + } - this.updateBlockEntityTicker(p_156391_); -+ p_156391_.onLoad(); - } + public void registerAllBlockEntitiesAfterLevelLoad() { ++ this.level.addFreshBlockEntities(this.blockEntities.values()); + this.blockEntities.values().forEach(p_187988_ -> { + if (this.level instanceof ServerLevel serverlevel) { + this.addGameEventListener(p_187988_, serverlevel); +@@ -637,6 +_,34 @@ + return new LevelChunk.BoundTickingBlockEntity<>(p_156376_, p_156377_); + } - } -@@ -369,9 +_,14 @@ - public CompoundTag getBlockEntityNbtForSaving(BlockPos p_62932_) { - BlockEntity blockentity = this.getBlockEntity(p_62932_); - if (blockentity != null && !blockentity.isRemoved()) { -+ try { - CompoundTag compoundtag1 = blockentity.saveWithFullMetadata(); - compoundtag1.putBoolean("keepPacked", false); - return compoundtag1; -+ } catch (Exception e) { -+ LOGGER.error("A BlockEntity type {} has thrown an exception trying to write state. It will not persist, Report this to the mod author", blockentity.getClass().getName(), e); -+ return null; -+ } - } else { - CompoundTag compoundtag = this.pendingBlockEntities.get(p_62932_); - if (compoundtag != null) { -@@ -455,7 +_,7 @@ - p_187974_.accept((p_187968_, p_187969_, p_187970_) -> { - BlockEntity blockentity = this.getBlockEntity(p_187968_, LevelChunk.EntityCreationType.IMMEDIATE); - if (blockentity != null && p_187970_ != null && blockentity.getType() == p_187969_) { -- blockentity.load(p_187970_); -+ blockentity.handleUpdateTag(p_187970_); - } - - }); -@@ -564,6 +_,7 @@ - } - - public void clearAllBlockEntities() { -+ this.blockEntities.values().forEach(BlockEntity::onChunkUnloaded); - this.blockEntities.values().forEach(BlockEntity::setRemoved); - this.blockEntities.clear(); - this.tickersInLevel.values().forEach((p_187966_) -> { -@@ -573,6 +_,7 @@ - } - - public void registerAllBlockEntitiesAfterLevelLoad() { -+ this.level.addFreshBlockEntities(this.blockEntities.values()); - this.blockEntities.values().forEach((p_187988_) -> { - Level level = this.level; - if (level instanceof ServerLevel serverlevel) { -@@ -621,6 +_,41 @@ - return new LevelChunk.BoundTickingBlockEntity<>(p_156376_, p_156377_); - } - -+ // FORGE START -+ private final net.minecraftforge.common.capabilities.CapabilityProvider.AsField capProvider = new net.minecraftforge.common.capabilities.CapabilityProvider.AsField<>(LevelChunk.class, this); ++ private final net.minecraftforge.common.capabilities.CapabilityProvider.AsField capProvider = new net.minecraftforge.common.capabilities.CapabilityProvider.AsField<>(LevelChunk.class, this); + -+ @org.jetbrains.annotations.NotNull -+ @Override -+ public net.minecraftforge.common.util.LazyOptional getCapability(@org.jetbrains.annotations.NotNull net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) -+ { -+ return capProvider.getCapability(cap, side); -+ } ++ @org.jetbrains.annotations.NotNull ++ @Override ++ public net.minecraftforge.common.util.LazyOptional getCapability(@org.jetbrains.annotations.NotNull net.minecraftforge.common.capabilities.Capability cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { ++ return capProvider.getCapability(cap, side); ++ } + -+ @Override -+ public boolean areCapsCompatible(net.minecraftforge.common.capabilities.CapabilityProvider other) -+ { -+ return capProvider.areCapsCompatible(other); -+ } ++ @Override ++ public boolean areCapsCompatible(net.minecraftforge.common.capabilities.CapabilityProvider other) { ++ return capProvider.areCapsCompatible(other); ++ } + -+ @Override -+ public boolean areCapsCompatible(@org.jetbrains.annotations.Nullable net.minecraftforge.common.capabilities.CapabilityDispatcher other) -+ { -+ return capProvider.areCapsCompatible(other); -+ } ++ @Override ++ public boolean areCapsCompatible(@org.jetbrains.annotations.Nullable net.minecraftforge.common.capabilities.CapabilityDispatcher other) { ++ return capProvider.areCapsCompatible(other); ++ } + -+ @Override -+ public void invalidateCaps() -+ { -+ capProvider.invalidateCaps(); -+ } ++ @Override ++ public void invalidateCaps() { ++ capProvider.invalidateCaps(); ++ } + -+ @Override -+ public void reviveCaps() -+ { -+ capProvider.reviveCaps(); -+ } -+ // FORGE END ++ @Override ++ public void reviveCaps() { ++ capProvider.reviveCaps(); ++ } + - class BoundTickingBlockEntity implements TickingBlockEntity { - private final T blockEntity; - private final BlockEntityTicker ticker; -@@ -637,6 +_,7 @@ - if (LevelChunk.this.isTicking(blockpos)) { - try { - ProfilerFiller profilerfiller = LevelChunk.this.level.getProfiler(); -+ net.minecraftforge.server.timings.TimeTracker.BLOCK_ENTITY_UPDATE.trackStart(blockEntity); - profilerfiller.push(this::getType); - BlockState blockstate = LevelChunk.this.getBlockState(blockpos); - if (this.blockEntity.getType().isValid(blockstate)) { -@@ -652,6 +_,12 @@ - CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking block entity"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Block entity being ticked"); - this.blockEntity.fillCrashReportCategory(crashreportcategory); + class BoundTickingBlockEntity implements TickingBlockEntity { + private final T blockEntity; + private final BlockEntityTicker ticker; +@@ -654,6 +_,7 @@ + if (LevelChunk.this.isTicking(blockpos)) { + try { + ProfilerFiller profilerfiller = LevelChunk.this.level.getProfiler(); ++ net.minecraftforge.server.timings.TimeTracker.BLOCK_ENTITY_UPDATE.trackStart(blockEntity); + profilerfiller.push(this::getType); + BlockState blockstate = LevelChunk.this.getBlockState(blockpos); + if (this.blockEntity.getType().isValid(blockstate)) { +@@ -675,6 +_,11 @@ + CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking block entity"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Block entity being ticked"); + this.blockEntity.fillCrashReportCategory(crashreportcategory); ++ if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringBlockEntities.get()) { ++ LOGGER.error("{}", crashreport.getFriendlyReport()); ++ blockEntity.setRemoved(); ++ LevelChunk.this.removeBlockEntity(blockEntity.getBlockPos()); ++ } else + throw new ReportedException(crashreport); + } + } +@@ -748,5 +_,32 @@ + public String toString() { + return this.ticker + " "; + } ++ } + -+ if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringBlockEntities.get()) { -+ LOGGER.error("{}", crashreport.getFriendlyReport()); -+ blockEntity.setRemoved(); -+ LevelChunk.this.removeBlockEntity(blockEntity.getBlockPos()); -+ } else - throw new ReportedException(crashreport); - } - } -@@ -680,6 +_,34 @@ - IMMEDIATE, - QUEUED, - CHECK; -+ } ++ /** ++ * FOR INTERNAL USE ONLY ++ *

++ * Only public for use in {@link net.minecraft.world.level.chunk.storage.ChunkSerializer}. ++ */ ++ @java.lang.Deprecated ++ @org.jetbrains.annotations.Nullable ++ public final CompoundTag writeCapsToNBT() { ++ return capProvider.serializeInternal(); ++ } + ++ /** ++ * FOR INTERNAL USE ONLY ++ *

++ * Only public for use in {@link net.minecraft.world.level.chunk.storage.ChunkSerializer}. ++ * ++ */ ++ @java.lang.Deprecated ++ public final void readCapsFromNBT(CompoundTag tag) { ++ capProvider.deserializeInternal(tag); ++ } + -+ /** -+ * FOR INTERNAL USE ONLY -+ *

-+ * Only public for use in {@link net.minecraft.world.level.chunk.storage.ChunkSerializer}. -+ */ -+ @java.lang.Deprecated -+ @org.jetbrains.annotations.Nullable -+ public final CompoundTag writeCapsToNBT() { -+ return capProvider.serializeInternal(); -+ } -+ -+ /** -+ * FOR INTERNAL USE ONLY -+ *

-+ * Only public for use in {@link net.minecraft.world.level.chunk.storage.ChunkSerializer}. -+ * -+ */ -+ @java.lang.Deprecated -+ public final void readCapsFromNBT(CompoundTag tag) { -+ capProvider.deserializeInternal(tag); -+ } -+ -+ @Override -+ public Level getWorldForge() { -+ return getLevel(); - } - - @FunctionalInterface ++ @Override ++ public Level getWorldForge() { ++ return getLevel(); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/PalettedContainer.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/PalettedContainer.java.patch deleted file mode 100644 index 6049d8f9ac..0000000000 --- a/patches/minecraft/net/minecraft/world/level/chunk/PalettedContainer.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/world/level/chunk/PalettedContainer.java -+++ b/net/minecraft/world/level/chunk/PalettedContainer.java -@@ -25,6 +_,7 @@ - import net.minecraft.util.ZeroBitStorage; - - public class PalettedContainer implements PaletteResize, PalettedContainerRO { -+ // TODO: forceBits-parametered setBits function. -C - private static final int MIN_PALETTE_BITS = 0; - private final PaletteResize dummyPaletteResize = (p_238275_, p_238276_) -> { - return 0; diff --git a/patches/minecraft/net/minecraft/world/level/chunk/storage/ChunkSerializer.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/storage/ChunkSerializer.java.patch index e0a4e30171..2dd27ed84e 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/storage/ChunkSerializer.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/storage/ChunkSerializer.java.patch @@ -1,41 +1,43 @@ --- a/net/minecraft/world/level/chunk/storage/ChunkSerializer.java +++ b/net/minecraft/world/level/chunk/storage/ChunkSerializer.java -@@ -159,6 +_,7 @@ - return BuiltInRegistries.FLUID.getOptional(ResourceLocation.tryParse(p_258990_)); - }, p_188233_); - chunkaccess = new LevelChunk(p_188231_.getLevel(), p_188233_, upgradedata, levelchunkticks, levelchunkticks1, k1, alevelchunksection, postLoadChunk(p_188231_, p_188234_), blendingdata); -+ if (p_188234_.contains("ForgeCaps")) ((LevelChunk)chunkaccess).readCapsFromNBT(p_188234_.getCompound("ForgeCaps")); - } else { - ProtoChunkTicks protochunkticks = ProtoChunkTicks.load(p_188234_.getList("block_ticks", 10), (p_258992_) -> { - return BuiltInRegistries.BLOCK.getOptional(ResourceLocation.tryParse(p_258992_)); -@@ -212,6 +_,7 @@ - } +@@ -182,6 +_,9 @@ + postLoadChunk(p_188231_, p_188234_), + blendingdata + ); ++ if (p_188234_.contains("ForgeCaps")) { ++ ((LevelChunk)chunkaccess).readCapsFromNBT(p_188234_.getCompound("ForgeCaps")); ++ } + } else { + ProtoChunkTicks protochunkticks = ProtoChunkTicks.load( + p_188234_.getList("block_ticks", 10), p_258992_ -> BuiltInRegistries.BLOCK.getOptional(ResourceLocation.tryParse(p_258992_)), p_188233_ +@@ -240,6 +_,7 @@ + } - if (chunkstatus$chunktype == ChunkStatus.ChunkType.LEVELCHUNK) { -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkDataEvent.Load(chunkaccess, p_188234_, chunkstatus$chunktype)); - return new ImposterProtoChunk((LevelChunk)chunkaccess, false); - } else { - ProtoChunk protochunk1 = (ProtoChunk)chunkaccess; -@@ -235,6 +_,7 @@ - protochunk1.setCarvingMask(generationstep$carving, new CarvingMask(compoundtag4.getLongArray(s1), chunkaccess.getMinBuildHeight())); - } + if (chunktype == ChunkType.LEVELCHUNK) { ++ net.minecraftforge.event.ForgeEventFactory.onChunkDataLoad(chunkaccess, p_188234_, chunktype); + return new ImposterProtoChunk((LevelChunk)chunkaccess, false); + } else { + ProtoChunk protochunk1 = (ProtoChunk)chunkaccess; +@@ -263,6 +_,7 @@ + protochunk1.setCarvingMask(generationstep$carving, new CarvingMask(compoundtag4.getLongArray(s1), chunkaccess.getMinBuildHeight())); + } -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.level.ChunkDataEvent.Load(chunkaccess, p_188234_, chunkstatus$chunktype)); - return protochunk1; - } - } -@@ -340,6 +_,14 @@ - } ++ net.minecraftforge.event.ForgeEventFactory.onChunkDataLoad(chunkaccess, p_188234_, chunktype); + return protochunk1; + } + } +@@ -372,6 +_,14 @@ + } - compoundtag.put("CarvingMasks", compoundtag4); -+ } -+ else if (p_63456_ instanceof LevelChunk levelChunk){ -+ try { -+ final CompoundTag capTag = levelChunk.writeCapsToNBT(); -+ if (capTag != null) compoundtag.put("ForgeCaps", capTag); -+ } catch (Exception exception) { -+ LOGGER.error("A capability provider has thrown an exception trying to write state. It will not persist. Report this to the mod author", exception); -+ } - } + compoundtag.put("CarvingMasks", compoundtag4); ++ } ++ else if (p_63456_ instanceof LevelChunk levelChunk){ ++ try { ++ final CompoundTag capTag = levelChunk.writeCapsToNBT(); ++ if (capTag != null) compoundtag.put("ForgeCaps", capTag); ++ } catch (Exception exception) { ++ LOGGER.error("A capability provider has thrown an exception trying to write state. It will not persist. Report this to the mod author", exception); ++ } + } - saveTicks(p_63455_, compoundtag, p_63456_.getTicksForSerialization()); + saveTicks(p_63455_, compoundtag, p_63456_.getTicksForSerialization()); diff --git a/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch index 9e1f0c6ee6..ff1bf90d45 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/chunk/storage/EntityStorage.java +++ b/net/minecraft/world/level/chunk/storage/EntityStorage.java -@@ -89,8 +_,12 @@ - ListTag listtag = new ListTag(); - p_156559_.getEntities().forEach((p_156567_) -> { - CompoundTag compoundtag1 = new CompoundTag(); -+ try { - if (p_156567_.save(compoundtag1)) { - listtag.add(compoundtag1); -+ } -+ } catch (Exception e) { -+ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", p_156567_.getType(), e); - } - - }); +@@ -88,8 +_,12 @@ + ListTag listtag = new ListTag(); + p_156559_.getEntities().forEach(p_156567_ -> { + CompoundTag compoundtag1 = new CompoundTag(); ++ try { + if (p_156567_.save(compoundtag1)) { + listtag.add(compoundtag1); ++ } ++ } catch (Exception e) { ++ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", p_156567_.getType(), e); + } + }); + CompoundTag compoundtag = NbtUtils.addCurrentDataVersion(new CompoundTag()); diff --git a/patches/minecraft/net/minecraft/world/level/dimension/end/EndDragonFight.java.patch b/patches/minecraft/net/minecraft/world/level/dimension/end/EndDragonFight.java.patch index d4d6e644a8..3f4431941b 100644 --- a/patches/minecraft/net/minecraft/world/level/dimension/end/EndDragonFight.java.patch +++ b/patches/minecraft/net/minecraft/world/level/dimension/end/EndDragonFight.java.patch @@ -1,18 +1,17 @@ --- a/net/minecraft/world/level/dimension/end/EndDragonFight.java +++ b/net/minecraft/world/level/dimension/end/EndDragonFight.java -@@ -517,7 +_,14 @@ - endcrystal.setBeamTarget((BlockPos)null); - } - } -- -+ } -+ -+ public void addPlayer(ServerPlayer player) { -+ this.dragonEvent.addPlayer(player); -+ } -+ -+ public void removePlayer(ServerPlayer player) { -+ this.dragonEvent.removePlayer(player); - } +@@ -545,6 +_,14 @@ + } + } - @Nullable ++ public void addPlayer(ServerPlayer player) { ++ this.dragonEvent.addPlayer(player); ++ } ++ ++ public void removePlayer(ServerPlayer player) { ++ this.dragonEvent.removePlayer(player); ++ } ++ + @Nullable + public UUID getDragonUUID() { + return this.dragonUUID; diff --git a/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch b/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch index 546612586e..15ca57d14f 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch @@ -1,68 +1,60 @@ --- a/net/minecraft/world/level/entity/PersistentEntitySectionManager.java +++ b/net/minecraft/world/level/entity/PersistentEntitySectionManager.java -@@ -71,7 +_,16 @@ - return this.addEntity(p_157534_, false); - } +@@ -71,7 +_,18 @@ + return this.addEntity(p_157534_, false); + } -+ public boolean addNewEntityWithoutEvent(T entity) { -+ return this.addEntityWithoutEvent(entity, false); -+ } ++ public boolean addNewEntityWithoutEvent(T entity) { ++ return this.addEntityWithoutEvent(entity, false); ++ } + - private boolean addEntity(T p_157539_, boolean p_157540_) { -+ if (p_157539_ instanceof Entity entity && net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityJoinLevelEvent(entity, entity.level(), p_157540_))) return false; -+ return addEntityWithoutEvent(p_157539_, p_157540_); -+ } + private boolean addEntity(T p_157539_, boolean p_157540_) { ++ if (p_157539_ instanceof Entity entity && net.minecraftforge.event.ForgeEventFactory.onEntityJoinLevel(entity, entity.level(), p_157540_)) { ++ return false; ++ } ++ return addEntityWithoutEvent(p_157539_, p_157540_); ++ } + -+ private boolean addEntityWithoutEvent(T p_157539_, boolean p_157540_) { - if (!this.addEntityUuid(p_157539_)) { - return false; - } else { -@@ -103,12 +_,14 @@ - public void addLegacyChunkEntities(Stream p_157553_) { - p_157553_.forEach((p_157607_) -> { - this.addEntity(p_157607_, true); -+ if (p_157607_ instanceof Entity entity) entity.onAddedToWorld(); - }); - } ++ private boolean addEntityWithoutEvent(T p_157539_, boolean p_157540_) { + if (!this.addEntityUuid(p_157539_)) { + return false; + } else { +@@ -92,6 +_,10 @@ + this.startTicking(p_157539_); + } - public void addWorldGenChunkEntities(Stream p_157560_) { - p_157560_.forEach((p_157605_) -> { - this.addEntity(p_157605_, false); -+ if (p_157605_ instanceof Entity entity) entity.onAddedToWorld(); - }); - } ++ if (p_157539_ instanceof Entity entity) { ++ entity.onAddedToWorld(); ++ } ++ + return true; + } + } +@@ -367,11 +_,13 @@ -@@ -247,6 +_,7 @@ - while((chunkentities = this.loadingInbox.poll()) != null) { - chunkentities.getEntities().forEach((p_157593_) -> { - this.addEntity(p_157593_, true); -+ if (p_157593_ instanceof Entity entity) entity.onAddedToWorld(); - }); - this.chunkLoadStatuses.put(chunkentities.getPos().toLong(), PersistentEntitySectionManager.ChunkLoadStatus.LOADED); - } -@@ -354,11 +_,13 @@ + class Callback implements EntityInLevelCallback { + private final T entity; ++ private final Entity realEntity; + private long currentSectionKey; + private EntitySection currentSection; - class Callback implements EntityInLevelCallback { - private final T entity; -+ private final Entity realEntity; - private long currentSectionKey; - private EntitySection currentSection; + Callback(final T p_157614_, final long p_157615_, final EntitySection p_157616_) { + this.entity = p_157614_; ++ this.realEntity = p_157614_ instanceof Entity e ? e : null; + this.currentSectionKey = p_157615_; + this.currentSection = p_157616_; + } +@@ -390,9 +_,13 @@ + PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); + EntitySection entitysection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(i); + entitysection.add(this.entity); ++ long oldSectionKey = currentSectionKey; + this.currentSection = entitysection; + this.currentSectionKey = i; + this.updateStatus(visibility, entitysection.getStatus()); ++ if (this.realEntity != null) { ++ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); ++ } + } + } - Callback(T p_157614_, long p_157615_, EntitySection p_157616_) { - this.entity = p_157614_; -+ this.realEntity = p_157614_ instanceof Entity ? (Entity) p_157614_ : null; - this.currentSectionKey = p_157615_; - this.currentSection = p_157616_; - } -@@ -375,9 +_,11 @@ - PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection entitysection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(i); - entitysection.add(this.entity); -+ long oldSectionKey = currentSectionKey; - this.currentSection = entitysection; - this.currentSectionKey = i; - this.updateStatus(visibility, entitysection.getStatus()); -+ if (this.realEntity != null) net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); - } - - } diff --git a/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch b/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch index c9421c9469..6048c4e89c 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch @@ -1,32 +1,34 @@ --- a/net/minecraft/world/level/entity/TransientEntitySectionManager.java +++ b/net/minecraft/world/level/entity/TransientEntitySectionManager.java -@@ -92,11 +_,13 @@ +@@ -82,11 +_,13 @@ - class Callback implements EntityInLevelCallback { - private final T entity; -+ private final Entity realEntity; - private long currentSectionKey; - private EntitySection currentSection; + class Callback implements EntityInLevelCallback { + private final T entity; ++ private final Entity realEntity; + private long currentSectionKey; + private EntitySection currentSection; - Callback(T p_157673_, long p_157674_, EntitySection p_157675_) { - this.entity = p_157673_; -+ this.realEntity = p_157673_ instanceof Entity ? (Entity) p_157673_ : null; - this.currentSectionKey = p_157674_; - this.currentSection = p_157675_; - } -@@ -113,6 +_,7 @@ - TransientEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection entitysection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(i); - entitysection.add(this.entity); -+ long oldSectionKey = currentSectionKey; - this.currentSection = entitysection; - this.currentSectionKey = i; - TransientEntitySectionManager.this.callbacks.onSectionChange(this.entity); -@@ -125,6 +_,7 @@ - TransientEntitySectionManager.this.callbacks.onTickingStart(this.entity); - } + Callback(final T p_157673_, final long p_157674_, final EntitySection p_157675_) { + this.entity = p_157673_; ++ this.realEntity = p_157673_ instanceof Entity ? (Entity) p_157673_ : null; + this.currentSectionKey = p_157674_; + this.currentSection = p_157675_; + } +@@ -105,6 +_,7 @@ + TransientEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); + EntitySection entitysection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(i); + entitysection.add(this.entity); ++ long oldSectionKey = currentSectionKey; + this.currentSection = entitysection; + this.currentSectionKey = i; + TransientEntitySectionManager.this.callbacks.onSectionChange(this.entity); +@@ -116,6 +_,9 @@ + } else if (!flag && flag1) { + TransientEntitySectionManager.this.callbacks.onTickingStart(this.entity); + } ++ } ++ if (this.realEntity != null) { ++ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); + } } -+ if (this.realEntity != null) net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); - } - - } + } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch index 5d31f94d49..bd4a3f606c 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/levelgen/Beardifier.java +++ b/net/minecraft/world/level/levelgen/Beardifier.java -@@ -43,6 +_,11 @@ +@@ -42,6 +_,11 @@ - for(StructurePiece structurepiece : p_223936_.getPieces()) { - if (structurepiece.isCloseToChunk(p_223939_, 12)) { -+ if (structurepiece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { -+ if (pieceBeardifierModifier.getTerrainAdjustment() != TerrainAdjustment.NONE) { -+ objectlist.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); -+ } -+ } else - if (structurepiece instanceof PoolElementStructurePiece) { - PoolElementStructurePiece poolelementstructurepiece = (PoolElementStructurePiece)structurepiece; - StructureTemplatePool.Projection structuretemplatepool$projection = poolelementstructurepiece.getElement().getProjection(); + for (StructurePiece structurepiece : p_223936_.getPieces()) { + if (structurepiece.isCloseToChunk(p_223939_, 12)) { ++ if (structurepiece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { ++ if (pieceBeardifierModifier.getTerrainAdjustment() != TerrainAdjustment.NONE) { ++ objectlist.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); ++ } ++ } else + if (structurepiece instanceof PoolElementStructurePiece) { + PoolElementStructurePiece poolelementstructurepiece = (PoolElementStructurePiece)structurepiece; + StructureTemplatePool.Projection structuretemplatepool$projection = poolelementstructurepiece.getElement().getProjection(); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch index 0bf6ba2c7a..2c6fa5ab23 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch @@ -1,15 +1,13 @@ --- a/net/minecraft/world/level/levelgen/DebugLevelSource.java +++ b/net/minecraft/world/level/levelgen/DebugLevelSource.java -@@ -104,6 +_,12 @@ - return blockstate; - } - -+ public static void initValidStates() { -+ ALL_BLOCKS = StreamSupport.stream(BuiltInRegistries.BLOCK.spliterator(), false).flatMap(block -> block.getStateDefinition().getPossibleStates().stream()).collect(Collectors.toList()); -+ GRID_WIDTH = Mth.ceil(Mth.sqrt(ALL_BLOCKS.size())); -+ GRID_HEIGHT = Mth.ceil((float) (ALL_BLOCKS.size() / GRID_WIDTH)); -+ } +@@ -144,4 +_,10 @@ + public int getSeaLevel() { + return 63; + } + - public void applyCarvers(WorldGenRegion p_223970_, long p_223971_, RandomState p_223972_, BiomeManager p_223973_, StructureManager p_223974_, ChunkAccess p_223975_, GenerationStep.Carving p_223976_) { - } - ++ public static void initValidStates() { ++ ALL_BLOCKS = StreamSupport.stream(BuiltInRegistries.BLOCK.spliterator(), false).flatMap(block -> block.getStateDefinition().getPossibleStates().stream()).collect(Collectors.toList()); ++ GRID_WIDTH = Mth.ceil(Mth.sqrt(ALL_BLOCKS.size())); ++ GRID_HEIGHT = Mth.ceil((float) (ALL_BLOCKS.size() / GRID_WIDTH)); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch index f0f9c04191..03ea85b203 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch @@ -1,29 +1,31 @@ --- a/net/minecraft/world/level/levelgen/PhantomSpawner.java +++ b/net/minecraft/world/level/levelgen/PhantomSpawner.java -@@ -42,19 +_,22 @@ - for(ServerPlayer serverplayer : p_64576_.players()) { - if (!serverplayer.isSpectator()) { - BlockPos blockpos = serverplayer.blockPosition(); -- if (!p_64576_.dimensionType().hasSkyLight() || blockpos.getY() >= p_64576_.getSeaLevel() && p_64576_.canSeeSky(blockpos)) { -- DifficultyInstance difficultyinstance = p_64576_.getCurrentDifficultyAt(blockpos); -+ DifficultyInstance difficultyinstance = p_64576_.getCurrentDifficultyAt(blockpos); -+ var event = new net.minecraftforge.event.entity.player.PlayerSpawnPhantomsEvent(serverplayer, 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1)); -+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY) continue; -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || !p_64576_.dimensionType().hasSkyLight() || blockpos.getY() >= p_64576_.getSeaLevel() && p_64576_.canSeeSky(blockpos)) { - if (difficultyinstance.isHarderThan(randomsource.nextFloat() * 3.0F)) { - ServerStatsCounter serverstatscounter = serverplayer.getStats(); - int j = Mth.clamp(serverstatscounter.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); - int k = 24000; -- if (randomsource.nextInt(j) >= 72000) { -+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || randomsource.nextInt(j) >= 72000) { - BlockPos blockpos1 = blockpos.above(20 + randomsource.nextInt(15)).east(-10 + randomsource.nextInt(21)).south(-10 + randomsource.nextInt(21)); - BlockState blockstate = p_64576_.getBlockState(blockpos1); - FluidState fluidstate = p_64576_.getFluidState(blockpos1); - if (NaturalSpawner.isValidEmptySpawnBlock(p_64576_, blockpos1, blockstate, fluidstate, EntityType.PHANTOM)) { - SpawnGroupData spawngroupdata = null; -- int l = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); -+ int l = event.getPhantomsToSpawn(); +@@ -42,13 +_,17 @@ + for (ServerPlayer serverplayer : p_64576_.players()) { + if (!serverplayer.isSpectator()) { + BlockPos blockpos = serverplayer.blockPosition(); +- if (!p_64576_.dimensionType().hasSkyLight() || blockpos.getY() >= p_64576_.getSeaLevel() && p_64576_.canSeeSky(blockpos)) { + DifficultyInstance difficultyinstance = p_64576_.getCurrentDifficultyAt(blockpos); ++ var vanillaPosition = (!p_64576_.dimensionType().hasSkyLight() || blockpos.getY() >= p_64576_.getSeaLevel() && p_64576_.canSeeSky(blockpos)); ++ var count = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnPhantom(serverplayer, count); ++ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY) continue; ++ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || vanillaPosition) { + if (difficultyinstance.isHarderThan(randomsource.nextFloat() * 3.0F)) { + ServerStatsCounter serverstatscounter = serverplayer.getStats(); + int j = Mth.clamp(serverstatscounter.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); + int k = 24000; +- if (randomsource.nextInt(j) >= 72000) { ++ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || randomsource.nextInt(j) >= 72000) { + BlockPos blockpos1 = blockpos.above(20 + randomsource.nextInt(15)) + .east(-10 + randomsource.nextInt(21)) + .south(-10 + randomsource.nextInt(21)); +@@ -56,7 +_,7 @@ + FluidState fluidstate = p_64576_.getFluidState(blockpos1); + if (NaturalSpawner.isValidEmptySpawnBlock(p_64576_, blockpos1, blockstate, fluidstate, EntityType.PHANTOM)) { + SpawnGroupData spawngroupdata = null; +- int l = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); ++ int l = event.getPhantomsToSpawn(); - for(int i1 = 0; i1 < l; ++i1) { - Phantom phantom = EntityType.PHANTOM.create(p_64576_); + for (int i1 = 0; i1 < l; i1++) { + Phantom phantom = EntityType.PHANTOM.create(p_64576_); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch new file mode 100644 index 0000000000..933d4c4197 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch @@ -0,0 +1,12 @@ +--- a/net/minecraft/world/level/levelgen/WorldDimensions.java ++++ b/net/minecraft/world/level/levelgen/WorldDimensions.java +@@ -36,7 +_,8 @@ + public record WorldDimensions(Map, LevelStem> dimensions) { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec( + p_327457_ -> p_327457_.group( +- Codec.unboundedMap(ResourceKey.codec(Registries.LEVEL_STEM), LevelStem.CODEC) ++ // FORGE: Fix MC-197860 ++ new net.minecraftforge.common.LenientUnboundedMapCodec<>(ResourceKey.codec(Registries.LEVEL_STEM), LevelStem.CODEC) + .fieldOf("dimensions") + .forGetter(WorldDimensions::dimensions) + ) diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/Feature.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/Feature.java.patch index a7303c0bd6..383c830f88 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/Feature.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/Feature.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/levelgen/feature/Feature.java +++ b/net/minecraft/world/level/levelgen/feature/Feature.java -@@ -156,7 +_,7 @@ - } +@@ -186,7 +_,7 @@ + } - protected static boolean isStone(BlockState p_159748_) { -- return p_159748_.is(BlockTags.BASE_STONE_OVERWORLD); -+ return p_159748_.is(net.minecraftforge.common.Tags.Blocks.STONE); - } + protected static boolean isStone(BlockState p_159748_) { +- return p_159748_.is(BlockTags.BASE_STONE_OVERWORLD); ++ return p_159748_.is(net.minecraftforge.common.Tags.Blocks.STONE); + } - public static boolean isDirt(BlockState p_159760_) { + public static boolean isDirt(BlockState p_159760_) { diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch index f4592440b2..013c85cdb3 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java +++ b/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java -@@ -128,6 +_,6 @@ - } +@@ -129,6 +_,6 @@ + } - private EntityType randomEntityId(RandomSource p_225154_) { -- return Util.getRandom(MOBS, p_225154_); -+ return net.minecraftforge.common.DungeonHooks.getRandomDungeonMob(p_225154_); - } + private EntityType randomEntityId(RandomSource p_225154_) { +- return Util.getRandom(MOBS, p_225154_); ++ return net.minecraftforge.common.DungeonHooks.getRandomDungeonMob(p_225154_); + } } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/configurations/TreeConfiguration.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/configurations/TreeConfiguration.java.patch deleted file mode 100644 index 3811a534b5..0000000000 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/configurations/TreeConfiguration.java.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/net/minecraft/world/level/levelgen/feature/configurations/TreeConfiguration.java -+++ b/net/minecraft/world/level/levelgen/feature/configurations/TreeConfiguration.java -@@ -37,6 +_,7 @@ - return p_225470_.forceDirt; - })).apply(p_225468_, TreeConfiguration::new); - }); -+ //TODO: Review this, see if we can hook in the sapling into the Codec - public final BlockStateProvider trunkProvider; - public final BlockStateProvider dirtProvider; - public final TrunkPlacer trunkPlacer; diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch index 1cd7bc11e1..d87cdec678 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch @@ -1,11 +1,13 @@ --- a/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java +++ b/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java -@@ -72,7 +_,7 @@ - for(int i = 2; i >= -3; --i) { - BlockPos blockpos = p_225975_.above(i); - if (Feature.isGrassOrDirt(p_225974_.level(), blockpos)) { -- p_225974_.setBlock(blockpos, this.provider.getState(p_225974_.random(), p_225975_)); -+ p_225974_.setBlock(blockpos, net.minecraftforge.event.ForgeEventFactory.alterGround(p_225974_.level(), p_225974_.random(), blockpos, this.provider.getState(p_225974_.random(), p_225975_))); - break; - } +@@ -70,7 +_,9 @@ + for (int i = 2; i >= -3; i--) { + BlockPos blockpos = p_225975_.above(i); + if (Feature.isGrassOrDirt(p_225974_.level(), blockpos)) { +- p_225974_.setBlock(blockpos, this.provider.getState(p_225974_.random(), p_225975_)); ++ var state = this.provider.getState(p_225974_.random(), p_225975_); ++ state = net.minecraftforge.event.ForgeEventFactory.alterGround(p_225974_.level(), p_225974_.random(), blockpos, state); ++ p_225974_.setBlock(blockpos, state); + break; + } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch index fb44847919..4474b72c74 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java +++ b/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java -@@ -58,7 +_,7 @@ - } - - protected static void setDirtAt(LevelSimulatedReader p_226170_, BiConsumer p_226171_, RandomSource p_226172_, BlockPos p_226173_, TreeConfiguration p_226174_) { -- if (p_226174_.forceDirt || !isDirt(p_226170_, p_226173_)) { -+ if (!(((net.minecraft.world.level.LevelReader) p_226170_).getBlockState(p_226173_).onTreeGrow((net.minecraft.world.level.LevelReader) p_226170_, p_226171_, p_226172_, p_226173_, p_226174_)) && (p_226174_.forceDirt || !isDirt(p_226170_, p_226173_))) { - p_226171_.accept(p_226173_, p_226174_.dirtProvider.getState(p_226172_, p_226173_)); - } - +@@ -64,6 +_,8 @@ + protected static void setDirtAt( + LevelSimulatedReader p_226170_, BiConsumer p_226171_, RandomSource p_226172_, BlockPos p_226173_, TreeConfiguration p_226174_ + ) { ++ var levelReader = (net.minecraft.world.level.LevelReader)p_226170_; ++ if (!levelReader.getBlockState(p_226173_).onTreeGrow(levelReader, p_226171_, p_226172_, p_226173_, p_226174_)) + if (p_226174_.forceDirt || !isDirt(p_226170_, p_226173_)) { + p_226171_.accept(p_226173_, p_226174_.dirtProvider.getState(p_226172_, p_226173_)); + } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/Structure.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/Structure.java.patch index 3221b97910..3ef65ec3fc 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/Structure.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/Structure.java.patch @@ -1,55 +1,69 @@ --- a/net/minecraft/world/level/levelgen/structure/Structure.java +++ b/net/minecraft/world/level/levelgen/structure/Structure.java -@@ -41,11 +_,12 @@ +@@ -42,10 +_,13 @@ public abstract class Structure { - public static final Codec DIRECT_CODEC = BuiltInRegistries.STRUCTURE_TYPE.byNameCodec().dispatch(Structure::type, StructureType::codec); - public static final Codec> CODEC = RegistryFileCodec.create(Registries.STRUCTURE, DIRECT_CODEC); -- protected final Structure.StructureSettings settings; -+ //Forge: Make this field private so that the redirect coremod can target it -+ private final Structure.StructureSettings settings; + public static final Codec DIRECT_CODEC = BuiltInRegistries.STRUCTURE_TYPE.byNameCodec().dispatch(Structure::type, StructureType::codec); + public static final Codec> CODEC = RegistryFileCodec.create(Registries.STRUCTURE, DIRECT_CODEC); +- protected final Structure.StructureSettings settings; ++ //Forge: Make this field private so that the redirect coremod can target it ++ @Deprecated ++ private final Structure.StructureSettings settings; ++ private final net.minecraftforge.common.world.ModifiableStructureInfo modifiableStructureInfo; - public static RecordCodecBuilder settingsCodec(RecordCodecBuilder.Instance p_226568_) { - return Structure.StructureSettings.CODEC.forGetter((p_226595_) -> { -- return p_226595_.settings; -+ return p_226595_.modifiableStructureInfo().getOriginalStructureInfo().structureSettings(); // FORGE: Patch codec to ignore field redirect coremods. - }); - } + public static RecordCodecBuilder settingsCodec(Instance p_226568_) { +- return Structure.StructureSettings.CODEC.forGetter(p_226595_ -> p_226595_.settings); ++ return Structure.StructureSettings.CODEC.forGetter(p_226595_ -> p_226595_.modifiableStructureInfo().getOriginalStructureInfo().structureSettings()); // FORGE: Patch codec to ignore field redirect coremods. + } -@@ -57,6 +_,7 @@ + public static MapCodec simpleCodec(Function p_226608_) { +@@ -54,22 +_,23 @@ - protected Structure(Structure.StructureSettings p_226558_) { - this.settings = p_226558_; -+ this.modifiableStructureInfo = new net.minecraftforge.common.world.ModifiableStructureInfo(new net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo(p_226558_)); // FORGE: cache original structure info on construction so we can bypass our field read coremods where necessary - } + protected Structure(Structure.StructureSettings p_226558_) { + this.settings = p_226558_; ++ this.modifiableStructureInfo = new net.minecraftforge.common.world.ModifiableStructureInfo(new net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo(p_226558_)); // FORGE: cache original structure info on construction so we can bypass our field read coremods where necessary + } - public HolderSet biomes() { -@@ -157,6 +_,29 @@ - } + public HolderSet biomes() { +- return this.settings.biomes; ++ return this.getModifiedStructureSettings().biomes; + } - public abstract StructureType type(); + public Map spawnOverrides() { +- return this.settings.spawnOverrides; ++ return this.getModifiedStructureSettings().spawnOverrides; + } + + public GenerationStep.Decoration step() { +- return this.settings.step; ++ return this.getModifiedStructureSettings().step; + } + + public TerrainAdjustment terrainAdaptation() { +- return this.settings.terrainAdaptation; ++ return this.getModifiedStructureSettings().terrainAdaptation; + } + + public BoundingBox adjustBoundingBox(BoundingBox p_226570_) { +@@ -194,6 +_,22 @@ + } + + public abstract StructureType type(); + -+ // FORGE START ++ /** ++ * {@return Cache of original structure data and structure data modified by structure modifiers} ++ * Modified structure data is set by server after datapacks and serverconfigs load. ++ * Settings field reads are coremodded to redirect to this. ++ **/ ++ public net.minecraftforge.common.world.ModifiableStructureInfo modifiableStructureInfo() { ++ return this.modifiableStructureInfo; ++ } + -+ private final net.minecraftforge.common.world.ModifiableStructureInfo modifiableStructureInfo; -+ -+ /** -+ * {@return Cache of original structure data and structure data modified by structure modifiers} -+ * Modified structure data is set by server after datapacks and serverconfigs load. -+ * Settings field reads are coremodded to redirect to this. -+ **/ -+ public net.minecraftforge.common.world.ModifiableStructureInfo modifiableStructureInfo() -+ { -+ return this.modifiableStructureInfo; -+ } -+ -+ /** -+ * {@return The structure's settings, with modifications if called after modifiers are applied in server init.} -+ */ -+ public StructureSettings getModifiedStructureSettings() { -+ return this.modifiableStructureInfo().get().structureSettings(); -+ } -+ -+ // FORGE END ++ /** ++ * {@return The structure's settings, with modifications if called after modifiers are applied in server init.} ++ */ ++ public StructureSettings getModifiedStructureSettings() { ++ return this.modifiableStructureInfo().get().structureSettings(); ++ } - public static record GenerationContext(RegistryAccess registryAccess, ChunkGenerator chunkGenerator, BiomeSource biomeSource, RandomState randomState, StructureTemplateManager structureTemplateManager, WorldgenRandom random, long seed, ChunkPos chunkPos, LevelHeightAccessor heightAccessor, Predicate> validBiome) { - public GenerationContext(RegistryAccess p_226632_, ChunkGenerator p_226633_, BiomeSource p_226634_, RandomState p_226635_, StructureTemplateManager p_226636_, long p_226637_, ChunkPos p_226638_, LevelHeightAccessor p_226639_, Predicate> p_226640_) { + public static record GenerationContext( + RegistryAccess registryAccess, diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch index c758c6d31a..63803d46c0 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/levelgen/structure/StructurePiece.java +++ b/net/minecraft/world/level/levelgen/structure/StructurePiece.java -@@ -71,6 +_,9 @@ - } +@@ -92,6 +_,9 @@ + } - public final CompoundTag createTag(StructurePieceSerializationContext p_192645_) { -+ if (BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()) == null) { // FORGE: Friendlier error then the Null String error below. -+ throw new RuntimeException("StructurePiece \"" + this.getClass().getName() + "\": \"" + this.getType() + "\" unregistered, serializing impossible."); -+ } - CompoundTag compoundtag = new CompoundTag(); - compoundtag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); - BoundingBox.CODEC.encodeStart(NbtOps.INSTANCE, this.boundingBox).resultOrPartial(LOGGER::error).ifPresent((p_163579_) -> { + public final CompoundTag createTag(StructurePieceSerializationContext p_192645_) { ++ if (BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()) == null) { // FORGE: Friendlier error then the Null String error below. ++ throw new RuntimeException("StructurePiece \"" + this.getClass().getName() + "\": \"" + this.getType() + "\" unregistered, serializing impossible."); ++ } + CompoundTag compoundtag = new CompoundTag(); + compoundtag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); + BoundingBox.CODEC diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch index 146a1a1480..7858491069 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/levelgen/structure/StructureStart.java +++ b/net/minecraft/world/level/levelgen/structure/StructureStart.java -@@ -98,6 +_,9 @@ - public CompoundTag createTag(StructurePieceSerializationContext p_192661_, ChunkPos p_192662_) { - CompoundTag compoundtag = new CompoundTag(); - if (this.isValid()) { -+ if (p_192661_.registryAccess().registryOrThrow(Registries.STRUCTURE).getKey(this.getStructure()) == null) { // FORGE: This is just a more friendly error instead of the 'Null String' below -+ throw new RuntimeException("StructureStart \"" + this.getClass().getName() + "\": \"" + this.getStructure() + "\" unregistered, serializing impossible."); -+ } - compoundtag.putString("id", p_192661_.registryAccess().registryOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); - compoundtag.putInt("ChunkX", p_192662_.x); - compoundtag.putInt("ChunkZ", p_192662_.z); +@@ -100,6 +_,9 @@ + public CompoundTag createTag(StructurePieceSerializationContext p_192661_, ChunkPos p_192662_) { + CompoundTag compoundtag = new CompoundTag(); + if (this.isValid()) { ++ if (p_192661_.registryAccess().registryOrThrow(Registries.STRUCTURE).getKey(this.getStructure()) == null) { // FORGE: This is just a more friendly error instead of the 'Null String' below ++ throw new RuntimeException("StructureStart \"" + this.getClass().getName() + "\": \"" + this.getStructure() + "\" unregistered, serializing impossible."); ++ } + compoundtag.putString("id", p_192661_.registryAccess().registryOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); + compoundtag.putInt("ChunkX", p_192662_.x); + compoundtag.putInt("ChunkZ", p_192662_.z); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java.patch index 87f16465ed..fe0c3bb24a 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java.patch @@ -1,43 +1,37 @@ --- a/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java +++ b/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java -@@ -7,12 +_,40 @@ +@@ -7,6 +_,11 @@ import net.minecraft.world.level.ServerLevelAccessor; public abstract class StructureProcessor { -+ /** -+ * @deprecated Forge: Use {@link #process(LevelReader, BlockPos, BlockPos, StructureTemplate.StructureBlockInfo, StructureTemplate.StructureBlockInfo, StructurePlaceSettings, StructureTemplate)} instead. -+ */ -+ @Deprecated - @Nullable - public StructureTemplate.StructureBlockInfo processBlock(LevelReader p_74416_, BlockPos p_74417_, BlockPos p_74418_, StructureTemplate.StructureBlockInfo p_74419_, StructureTemplate.StructureBlockInfo p_74420_, StructurePlaceSettings p_74421_) { - return p_74420_; - } - - protected abstract StructureProcessorType getType(); + -+ @Nullable -+ public StructureTemplate.StructureBlockInfo process(LevelReader p_74140_, BlockPos p_74141_, BlockPos p_74142_, StructureTemplate.StructureBlockInfo p_74143_, StructureTemplate.StructureBlockInfo p_74144_, StructurePlaceSettings p_74145_, @Nullable StructureTemplate template) { -+ return processBlock(p_74140_, p_74141_, p_74142_, p_74143_, p_74144_, p_74145_); -+ } ++ /** ++ * @deprecated Forge: Use {@link #process(LevelReader, BlockPos, BlockPos, StructureTemplate.StructureBlockInfo, StructureTemplate.StructureBlockInfo, StructurePlaceSettings, StructureTemplate)} instead. ++ */ ++ @Deprecated + @Nullable + public StructureTemplate.StructureBlockInfo processBlock( + LevelReader p_74416_, +@@ -30,5 +_,22 @@ + StructurePlaceSettings p_277497_ + ) { + return p_278053_; ++ } + -+ /** -+ * FORGE: Add entity processing. -+ *

-+ * Use this method to process entities from a structure in much the same way as -+ * blocks, parameters are analogous. -+ * -+ * @param world -+ * @param seedPos -+ * @param rawEntityInfo -+ * @param entityInfo -+ * @param placementSettings -+ * @param template -+ * -+ * @see #process(LevelReader, BlockPos, BlockPos, StructureTemplate.StructureBlockInfo, StructureTemplate.StructureBlockInfo, StructurePlaceSettings, StructureTemplate) -+ */ -+ public StructureTemplate.StructureEntityInfo processEntity(LevelReader world, BlockPos seedPos, StructureTemplate.StructureEntityInfo rawEntityInfo, StructureTemplate.StructureEntityInfo entityInfo, StructurePlaceSettings placementSettings, StructureTemplate template) { -+ return entityInfo; -+ } - - public List finalizeProcessing(ServerLevelAccessor p_278247_, BlockPos p_277590_, BlockPos p_277935_, List p_278070_, List p_278053_, StructurePlaceSettings p_277497_) { - return p_278053_; ++ /** ++ * FORGE: Add entity processing. ++ *

++ * Use this method to process entities from a structure in much the same way as ++ * blocks, parameters are analogous. ++ * ++ * @see #process(LevelReader, BlockPos, BlockPos, StructureTemplate.StructureBlockInfo, StructureTemplate.StructureBlockInfo, StructurePlaceSettings, StructureTemplate) ++ */ ++ public StructureTemplate.StructureEntityInfo processEntity(LevelReader world, BlockPos seedPos, StructureTemplate.StructureEntityInfo rawEntityInfo, StructureTemplate.StructureEntityInfo entityInfo, StructurePlaceSettings placementSettings, StructureTemplate template) { ++ return entityInfo; ++ } ++ ++ @Nullable ++ public StructureTemplate.StructureBlockInfo process(LevelReader level, BlockPos seed, BlockPos offset, StructureTemplate.StructureBlockInfo rawBlock, StructureTemplate.StructureBlockInfo block, StructurePlaceSettings settings, @Nullable StructureTemplate template) { ++ return processBlock(level, seed, offset, rawBlock, block, settings); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch index ba9b813b20..410ea99842 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch @@ -1,106 +1,122 @@ --- a/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java +++ b/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java -@@ -201,6 +_,10 @@ - return transform(p_74565_, p_74564_.getMirror(), p_74564_.getRotation(), p_74564_.getRotationPivot()); - } +@@ -226,6 +_,10 @@ + return transform(p_74565_, p_74564_.getMirror(), p_74564_.getRotation(), p_74564_.getRotationPivot()); + } -+ public static Vec3 transformedVec3d(StructurePlaceSettings placementIn, Vec3 pos) { -+ return transform(pos, placementIn.getMirror(), placementIn.getRotation(), placementIn.getRotationPivot()); -+ } ++ public static Vec3 transformedVec3d(StructurePlaceSettings placementIn, Vec3 pos) { ++ return transform(pos, placementIn.getMirror(), placementIn.getRotation(), placementIn.getRotationPivot()); ++ } + - public boolean placeInWorld(ServerLevelAccessor p_230329_, BlockPos p_230330_, BlockPos p_230331_, StructurePlaceSettings p_230332_, RandomSource p_230333_, int p_230334_) { - if (this.palettes.isEmpty()) { - return false; -@@ -218,7 +_,7 @@ - int i1 = Integer.MIN_VALUE; - int j1 = Integer.MIN_VALUE; + public boolean placeInWorld( + ServerLevelAccessor p_230329_, BlockPos p_230330_, BlockPos p_230331_, StructurePlaceSettings p_230332_, RandomSource p_230333_, int p_230334_ + ) { +@@ -248,7 +_,7 @@ + int i1 = Integer.MIN_VALUE; + int j1 = Integer.MIN_VALUE; -- for(StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : processBlockInfos(p_230329_, p_230330_, p_230331_, p_230332_, list)) { -+ for(StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : processBlockInfos(p_230329_, p_230330_, p_230331_, p_230332_, list, this)) { - BlockPos blockpos = structuretemplate$structureblockinfo.pos; - if (boundingbox == null || boundingbox.isInside(blockpos)) { - FluidState fluidstate = p_230332_.shouldKeepLiquids() ? p_230329_.getFluidState(blockpos) : null; -@@ -330,7 +_,7 @@ +- for (StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : processBlockInfos(p_230329_, p_230330_, p_230331_, p_230332_, list)) { ++ for (StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : processBlockInfos(p_230329_, p_230330_, p_230331_, p_230332_, list, this)) { + BlockPos blockpos = structuretemplate$structureblockinfo.pos; + if (boundingbox == null || boundingbox.isInside(blockpos)) { + FluidState fluidstate = p_230332_.shouldKeepLiquids() ? p_230329_.getFluidState(blockpos) : null; +@@ -360,7 +_,7 @@ + } + + if (!p_230332_.isIgnoreEntities()) { +- this.placeEntities(p_230329_, p_230330_, p_230332_.getMirror(), p_230332_.getRotation(), p_230332_.getRotationPivot(), boundingbox, p_230332_.shouldFinalizeEntities()); ++ this.addEntitiesToWorld(p_230329_, p_230330_, p_230332_); + } + + return true; +@@ -394,12 +_,21 @@ + }); + } + ++ /** ++ * @deprecated Forge: Use {@link #processBlockInfos(ServerLevelAccessor, BlockPos, BlockPos, StructurePlaceSettings, List, StructureTemplate)} instead. ++ */ ++ @Deprecated ++ public static List processBlockInfos(ServerLevelAccessor p_278297_, BlockPos p_74519_, BlockPos p_74520_, StructurePlaceSettings p_74521_, List p_74522_) { ++ return processBlockInfos(p_278297_, p_74519_, p_74520_, p_74521_, p_74522_, null); ++ } ++ + public static List processBlockInfos( + ServerLevelAccessor p_278297_, + BlockPos p_74519_, + BlockPos p_74520_, + StructurePlaceSettings p_74521_, +- List p_74522_ ++ List p_74522_, ++ @Nullable StructureTemplate template + ) { + List list = new ArrayList<>(); + List list1 = new ArrayList<>(); +@@ -415,7 +_,7 @@ + + while (structuretemplate$structureblockinfo1 != null && iterator.hasNext()) { + structuretemplate$structureblockinfo1 = iterator.next() +- .processBlock(p_278297_, p_74519_, p_74520_, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, p_74521_); ++ .process(p_278297_, p_74519_, p_74520_, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, p_74521_, template); } - if (!p_230332_.isIgnoreEntities()) { -- this.placeEntities(p_230329_, p_230330_, p_230332_.getMirror(), p_230332_.getRotation(), p_230332_.getRotationPivot(), boundingbox, p_230332_.shouldFinalizeEntities()); -+ this.addEntitiesToWorld(p_230329_, p_230330_, p_230332_); + if (structuretemplate$structureblockinfo1 != null) { +@@ -431,21 +_,27 @@ + return list1; + } + ++ private void addEntitiesToWorld(ServerLevelAccessor p_74524_, BlockPos p_74525_, StructurePlaceSettings placementIn) { ++ placeEntities(p_74524_, p_74525_, placementIn.getMirror(), placementIn.getRotation(), placementIn.getBoundingBox(), placementIn.shouldFinalizeEntities(), placementIn); ++ } ++ + private void placeEntities( + ServerLevelAccessor p_74524_, + BlockPos p_74525_, + Mirror p_74526_, + Rotation p_74527_, +- BlockPos p_74528_, + @Nullable BoundingBox p_74529_, +- boolean p_74530_ ++ boolean p_74530_, ++ StructurePlaceSettings placementIn + ) { +- for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : this.entityInfoList) { +- BlockPos blockpos = transform(structuretemplate$structureentityinfo.blockPos, p_74526_, p_74527_, p_74528_).offset(p_74525_); ++ var entities = processEntityInfos(this, p_74524_, p_74525_, placementIn, this.entityInfoList); ++ for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : entities) { ++ BlockPos blockpos = structuretemplate$structureentityinfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos + if (p_74529_ == null || p_74529_.isInside(blockpos)) { + CompoundTag compoundtag = structuretemplate$structureentityinfo.nbt.copy(); +- Vec3 vec3 = transform(structuretemplate$structureentityinfo.pos, p_74526_, p_74527_, p_74528_); +- Vec3 vec31 = vec3.add((double)p_74525_.getX(), (double)p_74525_.getY(), (double)p_74525_.getZ()); ++ //Vec3 vec3 = transform(structuretemplate$structureentityinfo.pos, p_74526_, p_74527_, p_74528_); ++ //Vec3 vec31 = vec3.add((double)p_74525_.getX(), (double)p_74525_.getY(), (double)p_74525_.getZ()); ++ Vec3 vec31 = structuretemplate$structureentityinfo.pos; // FORGE: Position will have already been transformed by processEntityInfos + ListTag listtag = new ListTag(); + listtag.add(DoubleTag.valueOf(vec31.x)); + listtag.add(DoubleTag.valueOf(vec31.y)); +@@ -465,6 +_,24 @@ } - - return true; -@@ -359,7 +_,15 @@ - }); - } - -+ /** -+ * @deprecated Forge: Use {@link #processBlockInfos(ServerLevelAccessor, BlockPos, BlockPos, StructurePlaceSettings, List, StructureTemplate)} instead. -+ */ -+ @Deprecated - public static List processBlockInfos(ServerLevelAccessor p_278297_, BlockPos p_74519_, BlockPos p_74520_, StructurePlaceSettings p_74521_, List p_74522_) { -+ return processBlockInfos(p_278297_, p_74519_, p_74520_, p_74521_, p_74522_, null); -+ } + } + } + -+ public static List processBlockInfos(ServerLevelAccessor p_278297_, BlockPos p_74519_, BlockPos p_74520_, StructurePlaceSettings p_74521_, List p_74522_, @Nullable StructureTemplate template) { - List list = new ArrayList<>(); - List list1 = new ArrayList<>(); - -@@ -367,7 +_,7 @@ - BlockPos blockpos = calculateRelativePosition(p_74521_, structuretemplate$structureblockinfo.pos).offset(p_74519_); - StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo1 = new StructureTemplate.StructureBlockInfo(blockpos, structuretemplate$structureblockinfo.state, structuretemplate$structureblockinfo.nbt != null ? structuretemplate$structureblockinfo.nbt.copy() : null); - -- for(Iterator iterator = p_74521_.getProcessors().iterator(); structuretemplate$structureblockinfo1 != null && iterator.hasNext(); structuretemplate$structureblockinfo1 = iterator.next().processBlock(p_278297_, p_74519_, p_74520_, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, p_74521_)) { -+ for(Iterator iterator = p_74521_.getProcessors().iterator(); structuretemplate$structureblockinfo1 != null && iterator.hasNext(); structuretemplate$structureblockinfo1 = iterator.next().process(p_278297_, p_74519_, p_74520_, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, p_74521_, template)) { - } - - if (structuretemplate$structureblockinfo1 != null) { -@@ -383,13 +_,29 @@ - return list1; - } - -- private void placeEntities(ServerLevelAccessor p_74524_, BlockPos p_74525_, Mirror p_74526_, Rotation p_74527_, BlockPos p_74528_, @Nullable BoundingBox p_74529_, boolean p_74530_) { -- for(StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : this.entityInfoList) { -- BlockPos blockpos = transform(structuretemplate$structureentityinfo.blockPos, p_74526_, p_74527_, p_74528_).offset(p_74525_); -- if (p_74529_ == null || p_74529_.isInside(blockpos)) { -+ public static List processEntityInfos(@Nullable StructureTemplate template, LevelAccessor p_215387_0_, BlockPos p_215387_1_, StructurePlaceSettings p_215387_2_, List p_215387_3_) { -+ List list = Lists.newArrayList(); -+ for(StructureTemplate.StructureEntityInfo entityInfo : p_215387_3_) { -+ Vec3 pos = transformedVec3d(p_215387_2_, entityInfo.pos).add(Vec3.atLowerCornerOf(p_215387_1_)); -+ BlockPos blockpos = calculateRelativePosition(p_215387_2_, entityInfo.blockPos).offset(p_215387_1_); -+ StructureTemplate.StructureEntityInfo info = new StructureTemplate.StructureEntityInfo(pos, blockpos, entityInfo.nbt); -+ for (StructureProcessor proc : p_215387_2_.getProcessors()) { -+ info = proc.processEntity(p_215387_0_, p_215387_1_, entityInfo, info, p_215387_2_, template); -+ if (info == null) -+ break; -+ } -+ if (info != null) -+ list.add(info); -+ } -+ return list; -+ } ++ public static List processEntityInfos(@Nullable StructureTemplate template, LevelAccessor level, BlockPos seedPos, StructurePlaceSettings settings, List entities) { ++ var list = new ArrayList(); ++ for (var entityInfo : entities) { ++ var pos = transformedVec3d(settings, entityInfo.pos).add(Vec3.atLowerCornerOf(seedPos)); ++ var blockpos = calculateRelativePosition(settings, entityInfo.blockPos).offset(seedPos); ++ var info = new StructureTemplate.StructureEntityInfo(pos, blockpos, entityInfo.nbt); ++ for (var proc : settings.getProcessors()) { ++ info = proc.processEntity(level, seedPos, entityInfo, info, settings, template); ++ if (info == null) ++ break; ++ } ++ if (info != null) ++ list.add(info); ++ } ++ return list; ++ } + -+ private void addEntitiesToWorld(ServerLevelAccessor p_74524_, BlockPos p_74525_, StructurePlaceSettings placementIn) { -+ for(StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : processEntityInfos(this, p_74524_, p_74525_, placementIn, this.entityInfoList)) { -+ BlockPos blockpos = structuretemplate$structureentityinfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos -+ if (placementIn.getBoundingBox() == null || placementIn.getBoundingBox().isInside(blockpos)) { - CompoundTag compoundtag = structuretemplate$structureentityinfo.nbt.copy(); -- Vec3 vec3 = transform(structuretemplate$structureentityinfo.pos, p_74526_, p_74527_, p_74528_); -- Vec3 vec31 = vec3.add((double)p_74525_.getX(), (double)p_74525_.getY(), (double)p_74525_.getZ()); -+ Vec3 vec31 = structuretemplate$structureentityinfo.pos; // FORGE: Position will have already been transformed by processEntityInfos - ListTag listtag = new ListTag(); - listtag.add(DoubleTag.valueOf(vec31.x)); - listtag.add(DoubleTag.valueOf(vec31.y)); -@@ -397,10 +_,10 @@ - compoundtag.put("Pos", listtag); - compoundtag.remove("UUID"); - createEntityIgnoreException(p_74524_, compoundtag).ifPresent((p_275190_) -> { -- float f = p_275190_.rotate(p_74527_); -- f += p_275190_.mirror(p_74526_) - p_275190_.getYRot(); -+ float f = p_275190_.rotate(placementIn.getRotation()); -+ f += p_275190_.mirror(placementIn.getMirror()) - p_275190_.getYRot(); - p_275190_.moveTo(vec31.x, vec31.y, vec31.z, f, p_275190_.getXRot()); -- if (p_74530_ && p_275190_ instanceof Mob) { -+ if (placementIn.shouldFinalizeEntities() && p_275190_ instanceof Mob) { - ((Mob)p_275190_).finalizeSpawn(p_74524_, p_74524_.getCurrentDifficultyAt(BlockPos.containing(vec31)), MobSpawnType.STRUCTURE, (SpawnGroupData)null, compoundtag); - } + private static Optional createEntityIgnoreException(ServerLevelAccessor p_74544_, CompoundTag p_74545_) { + try { diff --git a/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch b/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch index 48f56d855f..9d61520f29 100644 --- a/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch +++ b/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/level/lighting/BlockLightEngine.java +++ b/net/minecraft/world/level/lighting/BlockLightEngine.java -@@ -105,7 +_,7 @@ - } +@@ -107,7 +_,7 @@ + } - private int getEmission(long p_285243_, BlockState p_284973_) { -- int i = p_284973_.getLightEmission(); -+ int i = p_284973_.getLightEmission(chunkSource.getLevel(), mutablePos); - return i > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(p_285243_)) ? i : 0; - } + private int getEmission(long p_285243_, BlockState p_284973_) { +- int i = p_284973_.getLightEmission(); ++ int i = p_284973_.getLightEmission(chunkSource.getLevel(), mutablePos); + return i > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(p_285243_)) ? i : 0; + } -@@ -114,7 +_,7 @@ - LightChunk lightchunk = this.chunkSource.getChunkForLighting(p_285274_.x, p_285274_.z); - if (lightchunk != null) { - lightchunk.findBlockLightSources((p_285266_, p_285452_) -> { -- int i = p_285452_.getLightEmission(); -+ int i = p_285452_.getLightEmission(chunkSource.getLevel(), p_285266_); - this.enqueueIncrease(p_285266_.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(i, isEmptyShape(p_285452_))); - }); - } +@@ -117,7 +_,7 @@ + LightChunk lightchunk = this.chunkSource.getChunkForLighting(p_285274_.x, p_285274_.z); + if (lightchunk != null) { + lightchunk.findBlockLightSources((p_285266_, p_285452_) -> { +- int i = p_285452_.getLightEmission(); ++ int i = p_285452_.getLightEmission(chunkSource.getLevel(), p_285266_); + this.enqueueIncrease(p_285266_.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(i, isEmptyShape(p_285452_))); + }); + } diff --git a/patches/minecraft/net/minecraft/world/level/lighting/LightEngine.java.patch b/patches/minecraft/net/minecraft/world/level/lighting/LightEngine.java.patch index 9577aae81f..63adb6e17d 100644 --- a/patches/minecraft/net/minecraft/world/level/lighting/LightEngine.java.patch +++ b/patches/minecraft/net/minecraft/world/level/lighting/LightEngine.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/lighting/LightEngine.java +++ b/net/minecraft/world/level/lighting/LightEngine.java @@ -44,7 +_,7 @@ - if (p_285372_ == p_285110_) { - return false; - } else { -- return p_285372_.getLightBlock(p_285159_, p_284985_) != p_285110_.getLightBlock(p_285159_, p_284985_) || p_285372_.getLightEmission() != p_285110_.getLightEmission() || p_285372_.useShapeForLightOcclusion() || p_285110_.useShapeForLightOcclusion(); -+ return p_285372_.getLightBlock(p_285159_, p_284985_) != p_285110_.getLightBlock(p_285159_, p_284985_) || p_285372_.getLightEmission(p_285159_, p_284985_) != p_285110_.getLightEmission(p_285159_, p_284985_) || p_285372_.useShapeForLightOcclusion() || p_285110_.useShapeForLightOcclusion(); - } - } - + return p_285372_ == p_285110_ + ? false + : p_285372_.getLightBlock(p_285159_, p_284985_) != p_285110_.getLightBlock(p_285159_, p_284985_) +- || p_285372_.getLightEmission() != p_285110_.getLightEmission() ++ || p_285372_.getLightEmission(p_285159_, p_284985_) != p_285110_.getLightEmission(p_285159_, p_284985_) + || p_285372_.useShapeForLightOcclusion() + || p_285110_.useShapeForLightOcclusion(); + } diff --git a/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch b/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch index d69cc359c8..527e97d609 100644 --- a/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch @@ -1,36 +1,36 @@ --- a/net/minecraft/world/level/material/FlowingFluid.java +++ b/net/minecraft/world/level/material/FlowingFluid.java -@@ -160,7 +_,7 @@ - BlockState blockstate = p_256464_.getBlockState(blockpos); - FluidState fluidstate = blockstate.getFluidState(); - if (fluidstate.getType().isSame(this) && this.canPassThroughWall(direction, p_256464_, p_76037_, p_76038_, blockpos, blockstate)) { -- if (fluidstate.isSource()) { -+ if (fluidstate.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(p_256464_, blockpos, blockstate, fluidstate.canConvertToSource(p_256464_, blockpos))) { - ++j; +@@ -161,7 +_,7 @@ + BlockState blockstate = p_256464_.getBlockState(blockpos); + FluidState fluidstate = blockstate.getFluidState(); + if (fluidstate.getType().isSame(this) && this.canPassThroughWall(direction, p_256464_, p_76037_, p_76038_, blockpos, blockstate)) { +- if (fluidstate.isSource()) { ++ if (fluidstate.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(p_256464_, blockpos, blockstate, fluidstate.canConvertToSource(p_256464_, blockpos))) { + j++; + } + +@@ -169,7 +_,7 @@ } + } -@@ -168,7 +_,7 @@ - } - } +- if (this.canConvertToSource(p_256464_) && j >= 2) { ++ if (j >= 2) { + BlockState blockstate1 = p_256464_.getBlockState(p_76037_.below()); + FluidState fluidstate1 = blockstate1.getFluidState(); + if (blockstate1.isSolid() || this.isSourceBlockOfThisType(fluidstate1)) { +@@ -235,6 +_,15 @@ + return this.getSource().defaultFluidState().setValue(FALLING, Boolean.valueOf(p_76069_)); + } -- if (this.canConvertToSource(p_256464_) && j >= 2) { -+ if (j >= 2) { - BlockState blockstate1 = p_256464_.getBlockState(p_76037_.below()); - FluidState fluidstate1 = blockstate1.getFluidState(); - if (blockstate1.isSolid() || this.isSourceBlockOfThisType(fluidstate1)) { -@@ -232,6 +_,15 @@ - return this.getSource().defaultFluidState().setValue(FALLING, Boolean.valueOf(p_76069_)); - } - -+ @Override -+ public boolean canConvertToSource(FluidState state, Level level, BlockPos pos) { -+ return this.canConvertToSource(level); -+ } ++ @Override ++ public boolean canConvertToSource(FluidState state, Level level, BlockPos pos) { ++ return this.canConvertToSource(level); ++ } + -+ /** -+ * @deprecated Forge: Use {@link #canConvertToSource(FluidState, Level, BlockPos)} instead. -+ */ -+ @Deprecated - protected abstract boolean canConvertToSource(Level p_256009_); ++ /** ++ * @deprecated Forge: Use {@link #canConvertToSource(FluidState, Level, BlockPos)} instead. ++ */ ++ @Deprecated + protected abstract boolean canConvertToSource(Level p_256009_); - protected void spreadTo(LevelAccessor p_76005_, BlockPos p_76006_, BlockState p_76007_, Direction p_76008_, FluidState p_76009_) { + protected void spreadTo(LevelAccessor p_76005_, BlockPos p_76006_, BlockState p_76007_, Direction p_76008_, FluidState p_76009_) { diff --git a/patches/minecraft/net/minecraft/world/level/material/Fluid.java.patch b/patches/minecraft/net/minecraft/world/level/material/Fluid.java.patch index ff30b23d79..57d3b725d1 100644 --- a/patches/minecraft/net/minecraft/world/level/material/Fluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/Fluid.java.patch @@ -6,20 +6,19 @@ -public abstract class Fluid { +public abstract class Fluid implements net.minecraftforge.common.extensions.IForgeFluid { - public static final IdMapper FLUID_STATE_REGISTRY = new IdMapper<>(); - protected final StateDefinition stateDefinition; - private FluidState defaultFluidState; -@@ -101,6 +_,13 @@ - } - - public abstract VoxelShape getShape(FluidState p_76137_, BlockGetter p_76138_, BlockPos p_76139_); + public static final IdMapper FLUID_STATE_REGISTRY = new IdMapper<>(); + protected final StateDefinition stateDefinition; + private FluidState defaultFluidState; +@@ -108,5 +_,12 @@ + @Deprecated + public Holder.Reference builtInRegistryHolder() { + return this.builtInRegistryHolder; ++ } + -+ private net.minecraftforge.fluids.FluidType forgeFluidType; -+ @Override -+ public net.minecraftforge.fluids.FluidType getFluidType() { -+ if (forgeFluidType == null) forgeFluidType = net.minecraftforge.common.ForgeHooks.getVanillaFluidType(this); -+ return forgeFluidType; -+ } - - public Optional getPickupSound() { - return Optional.empty(); ++ private net.minecraftforge.fluids.FluidType forgeFluidType; ++ @Override ++ public net.minecraftforge.fluids.FluidType getFluidType() { ++ if (forgeFluidType == null) forgeFluidType = net.minecraftforge.common.ForgeHooks.getVanillaFluidType(this); ++ return forgeFluidType; + } + } diff --git a/patches/minecraft/net/minecraft/world/level/material/FluidState.java.patch b/patches/minecraft/net/minecraft/world/level/material/FluidState.java.patch index a0336aeda3..c9b367c5a8 100644 --- a/patches/minecraft/net/minecraft/world/level/material/FluidState.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/FluidState.java.patch @@ -6,14 +6,14 @@ -public final class FluidState extends StateHolder { +public final class FluidState extends StateHolder implements net.minecraftforge.common.extensions.IForgeFluidState { - public static final Codec CODEC = codec(BuiltInRegistries.FLUID.byNameCodec(), Fluid::defaultFluidState).stable(); - public static final int AMOUNT_MAX = 9; - public static final int AMOUNT_FULL = 8; + public static final Codec CODEC = codec(BuiltInRegistries.FLUID.byNameCodec(), Fluid::defaultFluidState).stable(); + public static final int AMOUNT_MAX = 9; + public static final int AMOUNT_FULL = 8; @@ -113,6 +_,7 @@ - return this.getType() == p_192918_; - } + return this.getType() == p_192918_; + } -+ @Deprecated //Forge: Use more sensitive version - public float getExplosionResistance() { - return this.getType().getExplosionResistance(); - } ++ @Deprecated //Forge: Use more sensitive version + public float getExplosionResistance() { + return this.getType().getExplosionResistance(); + } diff --git a/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch b/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch index db862b7d2b..da53eb696e 100644 --- a/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch @@ -1,57 +1,61 @@ --- a/net/minecraft/world/level/material/LavaFluid.java +++ b/net/minecraft/world/level/material/LavaFluid.java -@@ -72,7 +_,7 @@ - BlockState blockstate = p_230572_.getBlockState(blockpos); - if (blockstate.isAir()) { - if (this.hasFlammableNeighbours(p_230572_, blockpos)) { -- p_230572_.setBlockAndUpdate(blockpos, BaseFireBlock.getState(p_230572_, blockpos)); -+ p_230572_.setBlockAndUpdate(blockpos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_230572_, blockpos, p_230573_, Blocks.FIRE.defaultBlockState())); - return; - } - } else if (blockstate.blocksMotion()) { -@@ -86,8 +_,8 @@ - return; - } +@@ -87,7 +_,7 @@ + BlockState blockstate = p_230572_.getBlockState(blockpos); + if (blockstate.isAir()) { + if (this.hasFlammableNeighbours(p_230572_, blockpos)) { +- p_230572_.setBlockAndUpdate(blockpos, BaseFireBlock.getState(p_230572_, blockpos)); ++ p_230572_.setBlockAndUpdate(blockpos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_230572_, blockpos, p_230573_, Blocks.FIRE.defaultBlockState())); + return; + } + } else if (blockstate.blocksMotion()) { +@@ -101,8 +_,8 @@ + return; + } -- if (p_230572_.isEmptyBlock(blockpos1.above()) && this.isFlammable(p_230572_, blockpos1)) { -- p_230572_.setBlockAndUpdate(blockpos1.above(), BaseFireBlock.getState(p_230572_, blockpos1)); -+ if (p_230572_.isEmptyBlock(blockpos1.above()) && this.isFlammable(p_230572_, blockpos1, Direction.UP)) { -+ p_230572_.setBlockAndUpdate(blockpos1.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_230572_, blockpos1.above(), p_230573_, Blocks.FIRE.defaultBlockState())); - } +- if (p_230572_.isEmptyBlock(blockpos1.above()) && this.isFlammable(p_230572_, blockpos1)) { +- p_230572_.setBlockAndUpdate(blockpos1.above(), BaseFireBlock.getState(p_230572_, blockpos1)); ++ if (p_230572_.isEmptyBlock(blockpos1.above()) && this.isFlammable(p_230572_, blockpos1, Direction.UP)) { ++ p_230572_.setBlockAndUpdate(blockpos1.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_230572_, blockpos1.above(), p_230573_, Blocks.FIRE.defaultBlockState())); + } + } } - } -@@ -97,7 +_,7 @@ +@@ -111,7 +_,7 @@ - private boolean hasFlammableNeighbours(LevelReader p_76228_, BlockPos p_76229_) { - for(Direction direction : Direction.values()) { -- if (this.isFlammable(p_76228_, p_76229_.relative(direction))) { -+ if (this.isFlammable(p_76228_, p_76229_.relative(direction), direction.getOpposite())) { - return true; - } - } -@@ -105,10 +_,16 @@ - return false; - } + private boolean hasFlammableNeighbours(LevelReader p_76228_, BlockPos p_76229_) { + for (Direction direction : Direction.values()) { +- if (this.isFlammable(p_76228_, p_76229_.relative(direction))) { ++ if (this.isFlammable(p_76228_, p_76229_.relative(direction), direction.getOpposite())) { + return true; + } + } +@@ -119,12 +_,19 @@ + return false; + } -+ /** @deprecated Forge: use {@link LavaFluid#isFlammable(LevelReader,BlockPos,Direction)} instead */ -+ @Deprecated - private boolean isFlammable(LevelReader p_76246_, BlockPos p_76247_) { - return p_76247_.getY() >= p_76246_.getMinBuildHeight() && p_76247_.getY() < p_76246_.getMaxBuildHeight() && !p_76246_.hasChunkAt(p_76247_) ? false : p_76246_.getBlockState(p_76247_).ignitedByLava(); - } ++ /** @deprecated Forge: use {@link LavaFluid#isFlammable(LevelReader,BlockPos,Direction)} instead */ + private boolean isFlammable(LevelReader p_76246_, BlockPos p_76247_) { + return p_76247_.getY() >= p_76246_.getMinBuildHeight() && p_76247_.getY() < p_76246_.getMaxBuildHeight() && !p_76246_.hasChunkAt(p_76247_) + ? false + : p_76246_.getBlockState(p_76247_).ignitedByLava(); + } -+ private boolean isFlammable(LevelReader level, BlockPos pos, Direction face) { -+ return pos.getY() >= level.getMinBuildHeight() && pos.getY() < level.getMaxBuildHeight() && !level.hasChunkAt(pos) ? false : level.getBlockState(pos).ignitedByLava() && level.getBlockState(pos).isFlammable(level, pos, face); -+ } ++ private boolean isFlammable(LevelReader p_76246_, BlockPos p_76247_, Direction face) { ++ return p_76247_.getY() >= p_76246_.getMinBuildHeight() && p_76247_.getY() < p_76246_.getMaxBuildHeight() && !p_76246_.hasChunkAt(p_76247_) ++ ? false ++ : p_76246_.getBlockState(p_76247_).ignitedByLava() && p_76246_.getBlockState(p_76247_).isFlammable(p_76246_, p_76247_, face); ++ } + - @Nullable - public ParticleOptions getDripParticle() { - return ParticleTypes.DRIPPING_LAVA; -@@ -164,7 +_,7 @@ - FluidState fluidstate = p_76220_.getFluidState(p_76221_); - if (this.is(FluidTags.LAVA) && fluidstate.is(FluidTags.WATER)) { - if (p_76222_.getBlock() instanceof LiquidBlock) { -- p_76220_.setBlock(p_76221_, Blocks.STONE.defaultBlockState(), 3); -+ p_76220_.setBlock(p_76221_, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_76220_, p_76221_, p_76221_, Blocks.STONE.defaultBlockState()), 3); - } + @Nullable + @Override + public ParticleOptions getDripParticle() { +@@ -196,7 +_,8 @@ + FluidState fluidstate = p_76220_.getFluidState(p_76221_); + if (this.is(FluidTags.LAVA) && fluidstate.is(FluidTags.WATER)) { + if (p_76222_.getBlock() instanceof LiquidBlock) { +- p_76220_.setBlock(p_76221_, Blocks.STONE.defaultBlockState(), 3); ++ p_76220_.setBlock(p_76221_, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_76220_, p_76221_, p_76221_, Blocks.STONE.defaultBlockState()), 3); ++ + } - this.fizz(p_76220_, p_76221_); + this.fizz(p_76220_, p_76221_); diff --git a/patches/minecraft/net/minecraft/world/level/pathfinder/AmphibiousNodeEvaluator.java.patch b/patches/minecraft/net/minecraft/world/level/pathfinder/AmphibiousNodeEvaluator.java.patch deleted file mode 100644 index 395a666b16..0000000000 --- a/patches/minecraft/net/minecraft/world/level/pathfinder/AmphibiousNodeEvaluator.java.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/net/minecraft/world/level/pathfinder/AmphibiousNodeEvaluator.java -+++ b/net/minecraft/world/level/pathfinder/AmphibiousNodeEvaluator.java -@@ -46,7 +_,7 @@ - BlockPathTypes blockpathtypes1 = this.getCachedBlockType(this.mob, p_164677_.x, p_164677_.y, p_164677_.z); - int j; - if (this.mob.getPathfindingMalus(blockpathtypes) >= 0.0F && blockpathtypes1 != BlockPathTypes.STICKY_HONEY) { -- j = Mth.floor(Math.max(1.0F, this.mob.maxUpStep())); -+ j = Mth.floor(Math.max(1.0F, this.mob.getStepHeight())); - } else { - j = 0; - } diff --git a/patches/minecraft/net/minecraft/world/level/pathfinder/BlockPathTypes.java.patch b/patches/minecraft/net/minecraft/world/level/pathfinder/BlockPathTypes.java.patch deleted file mode 100644 index f9c36bbfba..0000000000 --- a/patches/minecraft/net/minecraft/world/level/pathfinder/BlockPathTypes.java.patch +++ /dev/null @@ -1,28 +0,0 @@ ---- a/net/minecraft/world/level/pathfinder/BlockPathTypes.java -+++ b/net/minecraft/world/level/pathfinder/BlockPathTypes.java -@@ -1,6 +_,6 @@ - package net.minecraft.world.level.pathfinder; - --public enum BlockPathTypes { -+public enum BlockPathTypes implements net.minecraftforge.common.IExtensibleEnum { - BLOCKED(-1.0F), - OPEN(0.0F), - WALKABLE(0.0F), -@@ -36,5 +_,17 @@ - - public float getMalus() { - return this.malus; -+ } -+ -+ @org.jetbrains.annotations.Nullable -+ public BlockPathTypes getDanger() { -+ return (this == DAMAGE_FIRE || this == DANGER_FIRE ) ? DANGER_FIRE : -+ (this == DAMAGE_OTHER || this == DANGER_OTHER ) ? DANGER_OTHER : -+ (this == LAVA) ? DAMAGE_FIRE : -+ null; -+ } -+ -+ public static BlockPathTypes create(String name, float malus) { -+ throw new IllegalArgumentException("Enum not extended"); - } - } diff --git a/patches/minecraft/net/minecraft/world/level/pathfinder/PathType.java.patch b/patches/minecraft/net/minecraft/world/level/pathfinder/PathType.java.patch new file mode 100644 index 0000000000..410f737542 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/pathfinder/PathType.java.patch @@ -0,0 +1,28 @@ +--- a/net/minecraft/world/level/pathfinder/PathType.java ++++ b/net/minecraft/world/level/pathfinder/PathType.java +@@ -1,6 +_,6 @@ + package net.minecraft.world.level.pathfinder; + +-public enum PathType { ++public enum PathType implements net.minecraftforge.common.IExtensibleEnum { + BLOCKED(-1.0F), + OPEN(0.0F), + WALKABLE(0.0F), +@@ -36,5 +_,17 @@ + + public float getMalus() { + return this.malus; ++ } ++ ++ @org.jetbrains.annotations.Nullable ++ public PathType getDanger() { ++ return (this == DAMAGE_FIRE || this == DANGER_FIRE ) ? DANGER_FIRE : ++ (this == DAMAGE_OTHER || this == DANGER_OTHER ) ? DANGER_OTHER : ++ (this == LAVA) ? DAMAGE_FIRE : ++ null; ++ } ++ ++ public static PathType create(String name, float malus) { ++ throw new IllegalArgumentException("Enum not extended"); + } + } diff --git a/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch b/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch index 30b7ad06fc..97c2a809ff 100644 --- a/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch @@ -1,59 +1,48 @@ --- a/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java +++ b/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java -@@ -112,7 +_,7 @@ - BlockPathTypes blockpathtypes = this.getCachedBlockType(this.mob, p_77641_.x, p_77641_.y + 1, p_77641_.z); - BlockPathTypes blockpathtypes1 = this.getCachedBlockType(this.mob, p_77641_.x, p_77641_.y, p_77641_.z); - if (this.mob.getPathfindingMalus(blockpathtypes) >= 0.0F && blockpathtypes1 != BlockPathTypes.STICKY_HONEY) { -- j = Mth.floor(Math.max(1.0F, this.mob.maxUpStep())); -+ j = Mth.floor(Math.max(1.0F, this.mob.getStepHeight())); - } - - double d0 = this.getFloorLevel(new BlockPos(p_77641_.x, p_77641_.y, p_77641_.z)); -@@ -306,7 +_,7 @@ - } - - private double getMobJumpHeight() { -- return Math.max(1.125D, (double)this.mob.maxUpStep()); -+ return Math.max(1.125D, (double)this.mob.getStepHeight()); - } - - private Node getNodeAndUpdateCostToMax(int p_230620_, int p_230621_, int p_230622_, BlockPathTypes p_230623_, float p_230624_) { -@@ -459,6 +_,11 @@ - if (l != 0 || j1 != 0) { - p_77609_.set(i + l, j + i1, k + j1); - BlockState blockstate = p_77608_.getBlockState(p_77609_); -+ BlockPathTypes blockPathType = blockstate.getAdjacentBlockPathType(p_77608_, p_77609_, null, p_77610_); -+ if (blockPathType != null) return blockPathType; -+ FluidState fluidState = blockstate.getFluidState(); -+ BlockPathTypes fluidPathType = fluidState.getAdjacentBlockPathType(p_77608_, p_77609_, null, p_77610_); -+ if (fluidPathType != null) return fluidPathType; - if (blockstate.is(Blocks.CACTUS) || blockstate.is(Blocks.SWEET_BERRY_BUSH)) { - return BlockPathTypes.DANGER_OTHER; - } -@@ -484,6 +_,8 @@ - - protected static BlockPathTypes getBlockPathTypeRaw(BlockGetter p_77644_, BlockPos p_77645_) { - BlockState blockstate = p_77644_.getBlockState(p_77645_); -+ BlockPathTypes type = blockstate.getBlockPathType(p_77644_, p_77645_, null); -+ if (type != null) return type; - Block block = blockstate.getBlock(); - if (blockstate.isAir()) { - return BlockPathTypes.OPEN; -@@ -497,6 +_,8 @@ - return BlockPathTypes.COCOA; - } else if (!blockstate.is(Blocks.WITHER_ROSE) && !blockstate.is(Blocks.POINTED_DRIPSTONE)) { - FluidState fluidstate = p_77644_.getFluidState(p_77645_); -+ BlockPathTypes nonLoggableFluidPathType = fluidstate.getBlockPathType(p_77644_, p_77645_, null, false); -+ if (nonLoggableFluidPathType != null) return nonLoggableFluidPathType; - if (fluidstate.is(FluidTags.LAVA)) { - return BlockPathTypes.LAVA; - } else if (isBurningBlock(blockstate)) { -@@ -516,6 +_,8 @@ - if (!blockstate.isPathfindable(p_77644_, p_77645_, PathComputationType.LAND)) { - return BlockPathTypes.BLOCKED; - } else { -+ BlockPathTypes loggableFluidPathType = fluidstate.getBlockPathType(p_77644_, p_77645_, null, true); -+ if (loggableFluidPathType != null) return loggableFluidPathType; - return fluidstate.is(FluidTags.WATER) ? BlockPathTypes.WATER : BlockPathTypes.OPEN; - } - } else { +@@ -477,6 +_,16 @@ + for (int k = -1; k <= 1; k++) { + if (i != 0 || k != 0) { + PathType pathtype = p_334221_.getPathTypeFromState(p_336062_ + i, p_335259_ + j, p_336315_ + k); ++ ++ var pos = new BlockPos(p_336062_ + i, p_335259_ + j, p_336315_ + k); ++ var blockstate = p_334221_.level().getBlockState(pos); ++ ++ var blockPathType = blockstate.getAdjacentBlockPathType(p_334221_.level(), pos, null, p_333971_); ++ if (blockPathType != null) return blockPathType; ++ ++ var fluidPathType = blockstate.getFluidState().getAdjacentBlockPathType(p_334221_.level(), pos, null, p_333971_); ++ if (fluidPathType != null) return fluidPathType; ++ + if (pathtype == PathType.DAMAGE_OTHER) { + return PathType.DANGER_OTHER; + } +@@ -503,6 +_,10 @@ + protected static PathType getPathTypeFromState(BlockGetter p_335222_, BlockPos p_331935_) { + BlockState blockstate = p_335222_.getBlockState(p_331935_); + Block block = blockstate.getBlock(); ++ ++ var type = blockstate.getBlockPathType(p_335222_, p_331935_, null); ++ if (type != null) return type; ++ + if (blockstate.isAir()) { + return PathType.OPEN; + } else if (blockstate.is(BlockTags.TRAPDOORS) || blockstate.is(Blocks.LILY_PAD) || blockstate.is(Blocks.BIG_DRIPLEAF)) { +@@ -517,6 +_,8 @@ + return PathType.COCOA; + } else if (!blockstate.is(Blocks.WITHER_ROSE) && !blockstate.is(Blocks.POINTED_DRIPSTONE)) { + FluidState fluidstate = blockstate.getFluidState(); ++ var nonLoggableFluidPathType = fluidstate.getBlockPathType(p_335222_, p_331935_, null, false); ++ if (nonLoggableFluidPathType != null) return nonLoggableFluidPathType; + if (fluidstate.is(FluidTags.LAVA)) { + return PathType.LAVA; + } else if (isBurningBlock(blockstate)) { +@@ -537,6 +_,8 @@ + if (!blockstate.isPathfindable(PathComputationType.LAND)) { + return PathType.BLOCKED; + } else { ++ var loggableFluidPathType = fluidstate.getBlockPathType(p_335222_, p_331935_, null, true); ++ if (loggableFluidPathType != null) return loggableFluidPathType; + return fluidstate.is(FluidTags.WATER) ? PathType.WATER : PathType.OPEN; + } + } else { diff --git a/patches/minecraft/net/minecraft/world/level/portal/PortalForcer.java.patch b/patches/minecraft/net/minecraft/world/level/portal/PortalForcer.java.patch index 6ef7c68bc3..e0f5462f63 100644 --- a/patches/minecraft/net/minecraft/world/level/portal/PortalForcer.java.patch +++ b/patches/minecraft/net/minecraft/world/level/portal/PortalForcer.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/portal/PortalForcer.java +++ b/net/minecraft/world/level/portal/PortalForcer.java -@@ -19,7 +_,7 @@ +@@ -20,7 +_,7 @@ import net.minecraft.world.level.border.WorldBorder; import net.minecraft.world.level.levelgen.Heightmap; -public class PortalForcer { +public class PortalForcer implements net.minecraftforge.common.util.ITeleporter { - private static final int TICKET_RADIUS = 3; - private static final int SEARCH_RADIUS = 128; - private static final int CREATE_RADIUS = 16; + public static final int TICKET_RADIUS = 3; + private static final int SEARCH_RADIUS = 128; + private static final int CREATE_RADIUS = 16; diff --git a/patches/minecraft/net/minecraft/world/level/portal/PortalShape.java.patch b/patches/minecraft/net/minecraft/world/level/portal/PortalShape.java.patch index 2af25fb327..c75bd15130 100644 --- a/patches/minecraft/net/minecraft/world/level/portal/PortalShape.java.patch +++ b/patches/minecraft/net/minecraft/world/level/portal/PortalShape.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/portal/PortalShape.java +++ b/net/minecraft/world/level/portal/PortalShape.java @@ -28,7 +_,7 @@ - private static final int MIN_HEIGHT = 3; - public static final int MAX_HEIGHT = 21; - private static final BlockBehaviour.StatePredicate FRAME = (p_77720_, p_77721_, p_77722_) -> { -- return p_77720_.is(Blocks.OBSIDIAN); -+ return p_77720_.isPortalFrame(p_77721_, p_77722_); - }; - private static final float SAFE_TRAVEL_MAX_ENTITY_XY = 4.0F; - private static final double SAFE_TRAVEL_MAX_VERTICAL_DELTA = 1.0D; + public static final int MAX_WIDTH = 21; + private static final int MIN_HEIGHT = 3; + public static final int MAX_HEIGHT = 21; +- private static final BlockBehaviour.StatePredicate FRAME = (p_77720_, p_77721_, p_77722_) -> p_77720_.is(Blocks.OBSIDIAN); ++ private static final BlockBehaviour.StatePredicate FRAME = (p_77720_, p_77721_, p_77722_) -> p_77720_.isPortalFrame(p_77721_, p_77722_); + private static final float SAFE_TRAVEL_MAX_ENTITY_XY = 4.0F; + private static final double SAFE_TRAVEL_MAX_VERTICAL_DELTA = 1.0; + private final LevelAccessor level; diff --git a/patches/minecraft/net/minecraft/world/level/storage/DimensionDataStorage.java.patch b/patches/minecraft/net/minecraft/world/level/storage/DimensionDataStorage.java.patch index d24905dc59..0151bb6255 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/DimensionDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/DimensionDataStorage.java.patch @@ -1,25 +1,27 @@ --- a/net/minecraft/world/level/storage/DimensionDataStorage.java +++ b/net/minecraft/world/level/storage/DimensionDataStorage.java -@@ -49,9 +_,13 @@ - @Nullable - public T get(SavedData.Factory p_297465_, String p_164860_) { - SavedData saveddata = this.cache.get(p_164860_); -+ if (saveddata == net.minecraftforge.common.util.DummySavedData.DUMMY) return null; - if (saveddata == null && !this.cache.containsKey(p_164860_)) { - saveddata = this.readSavedData(p_297465_.deserializer(), p_297465_.type(), p_164860_); - this.cache.put(p_164860_, saveddata); -+ } else if (saveddata == null) { -+ this.cache.put(p_164860_, net.minecraftforge.common.util.DummySavedData.DUMMY); -+ return null; - } +@@ -54,9 +_,13 @@ + @Nullable + public T get(SavedData.Factory p_297465_, String p_164860_) { + SavedData saveddata = this.cache.get(p_164860_); ++ if (saveddata == net.minecraftforge.common.util.DummySavedData.DUMMY) return null; + if (saveddata == null && !this.cache.containsKey(p_164860_)) { + saveddata = this.readSavedData(p_297465_.deserializer(), p_297465_.type(), p_164860_); + this.cache.put(p_164860_, saveddata); ++ } else if (saveddata == null) { ++ this.cache.put(p_164860_, net.minecraftforge.common.util.DummySavedData.DUMMY); ++ return null; + } - return (T)saveddata; -@@ -94,7 +_,7 @@ - } + return (T)saveddata; +@@ -99,6 +_,10 @@ + } - int i = NbtUtils.getDataVersion(compoundtag, 1343); -- compoundtag1 = p_301060_.update(this.fixerUpper, compoundtag, i, p_78160_); -+ compoundtag1 = p_301060_ == null ? compoundtag : p_301060_.update(this.fixerUpper, compoundtag, i, p_78160_); // Forge: Allow the data fixer to be null, leaving the modder responsible for keeping track of their own data formats - } + int i = NbtUtils.getDataVersion(compoundtag, 1343); ++ // Forge: Allow the data fixer to be null, leaving the modder responsible for keeping track of their own data formats ++ if (p_301060_ == null) ++ compoundtag1 = compoundtag; ++ else + compoundtag1 = p_301060_.update(this.fixerUpper, compoundtag, i, p_78160_); + } - return compoundtag1; diff --git a/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch b/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch index b357f8805c..deb4ab7f62 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch @@ -1,34 +1,33 @@ --- a/net/minecraft/world/level/storage/LevelStorageSource.java +++ b/net/minecraft/world/level/storage/LevelStorageSource.java -@@ -470,6 +_,12 @@ - return this.getDataTag(true); - } +@@ -481,6 +_,11 @@ + return this.getDataTag(true); + } -+ public CompoundTag getDataTagRaw(boolean fallback) throws IOException { -+ this.checkLock(); -+ return LevelStorageSource.readLevelDataTagRaw(fallback ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile()); ++ public CompoundTag getDataTagRaw(boolean fallback) throws IOException { ++ this.checkLock(); ++ return LevelStorageSource.readLevelDataTagRaw(fallback ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile()); ++ } + -+ } + private Dynamic getDataTag(boolean p_310699_) throws IOException { + this.checkLock(); + return LevelStorageSource.readLevelDataTagFixed(p_310699_ ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile(), LevelStorageSource.this.fixerUpper); +@@ -494,6 +_,7 @@ + CompoundTag compoundtag = p_78292_.createTag(p_78291_, p_78293_); + CompoundTag compoundtag1 = new CompoundTag(); + compoundtag1.put("Data", compoundtag); ++ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(p_78292_, compoundtag1); + this.saveLevelData(compoundtag1); + } + +@@ -513,6 +_,10 @@ + + public Optional getIconFile() { + return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile()); ++ } + - private Dynamic getDataTag(boolean p_310699_) throws IOException { - this.checkLock(); - return LevelStorageSource.readLevelDataTagFixed(p_310699_ ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile(), LevelStorageSource.this.fixerUpper); -@@ -483,6 +_,7 @@ - CompoundTag compoundtag = p_78292_.createTag(p_78291_, p_78293_); - CompoundTag compoundtag1 = new CompoundTag(); - compoundtag1.put("Data", compoundtag); -+ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(p_78292_, compoundtag1); - this.saveLevelData(compoundtag1); - } ++ public Path getWorldDir() { ++ return baseDir; + } -@@ -503,6 +_,10 @@ - - public Optional getIconFile() { - return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile()); -+ } -+ -+ public Path getWorldDir() { -+ return baseDir; - } - - public void deleteLevel() throws IOException { + public void deleteLevel() throws IOException { diff --git a/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch b/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch index 8d20ff3e42..88bd8e5d9e 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/storage/LevelSummary.java +++ b/net/minecraft/world/level/storage/LevelSummary.java -@@ -257,6 +_,10 @@ - } - } +@@ -277,6 +_,10 @@ + } + } -+ public boolean isLifecycleExperimental() { -+ return this.settings.getLifecycle().equals(com.mojang.serialization.Lifecycle.experimental()); -+ } ++ public boolean isLifecycleExperimental() { ++ return this.settings.getLifecycle().equals(com.mojang.serialization.Lifecycle.experimental()); ++ } + - public static class SymlinkLevelSummary extends LevelSummary { - private static final Component MORE_INFO_BUTTON = Component.translatable("symlink_warning.more_info"); - private static final Component INFO = Component.translatable("symlink_warning.title").withColor(-65536); + public static class SymlinkLevelSummary extends LevelSummary { + private static final Component MORE_INFO_BUTTON = Component.translatable("symlink_warning.more_info"); + private static final Component INFO = Component.translatable("symlink_warning.title").withColor(-65536); diff --git a/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch b/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch index e59c956c8c..ec56da0f0f 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch @@ -1,28 +1,31 @@ --- a/net/minecraft/world/level/storage/PlayerDataStorage.java +++ b/net/minecraft/world/level/storage/PlayerDataStorage.java -@@ -35,6 +_,7 @@ - Path path2 = path.resolve(p_78434_.getStringUUID() + ".dat"); - Path path3 = path.resolve(p_78434_.getStringUUID() + ".dat_old"); - Util.safeReplaceFile(path2, path1, path3); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerSavingEvent(p_78434_, playerDir, p_78434_.getStringUUID()); - } catch (Exception exception) { - LOGGER.warn("Failed to save player data for {}", (Object)p_78434_.getName().getString()); - } -@@ -59,6 +_,7 @@ - compoundtag = DataFixTypes.PLAYER.updateToCurrentVersion(this.fixerUpper, compoundtag, i); - p_78436_.load(compoundtag); - } -+ net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(p_78436_, playerDir, p_78436_.getStringUUID()); - - return compoundtag; - } -@@ -76,5 +_,9 @@ - } - - return astring; -+ } +@@ -39,6 +_,7 @@ + Path path2 = path.resolve(p_78434_.getStringUUID() + ".dat"); + Path path3 = path.resolve(p_78434_.getStringUUID() + ".dat_old"); + Util.safeReplaceFile(path2, path1, path3); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerSavingEvent(p_78434_, playerDir, p_78434_.getStringUUID()); + } catch (Exception exception) { + LOGGER.warn("Failed to save player data for {}", p_78434_.getName().getString()); + } +@@ -61,7 +_,9 @@ + File file1 = new File(this.playerDir, p_329651_.getStringUUID() + p_330353_); + if (file1.exists() && file1.isFile()) { + try { +- return Optional.of(NbtIo.readCompressed(file1.toPath(), NbtAccounter.unlimitedHeap())); ++ var ret = Optional.of(NbtIo.readCompressed(file1.toPath(), NbtAccounter.unlimitedHeap())); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(p_329651_, playerDir, p_329651_.getStringUUID()); ++ return ret; + } catch (Exception exception) { + LOGGER.warn("Failed to load player data for {}", p_329651_.getName().getString()); + } +@@ -82,5 +_,9 @@ + p_78436_.load(p_328937_); + return p_328937_; + }); ++ } + -+ public File getPlayerDataFolder() { -+ return playerDir; - } ++ public File getPlayerDataFolder() { ++ return playerDir; + } } diff --git a/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch b/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch index ccae437f95..a45927de2f 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch @@ -1,44 +1,45 @@ --- a/net/minecraft/world/level/storage/PrimaryLevelData.java +++ b/net/minecraft/world/level/storage/PrimaryLevelData.java -@@ -77,6 +_,7 @@ - private boolean wasModded; - private final Set removedFeatureFlags; - private final TimerQueue scheduledEvents; -+ private boolean confirmedExperimentalWarning = false; +@@ -74,6 +_,7 @@ + private boolean wasModded; + private final Set removedFeatureFlags; + private final TimerQueue scheduledEvents; ++ private boolean confirmedExperimentalWarning = false; - private PrimaryLevelData(@Nullable CompoundTag p_277888_, boolean p_278109_, int p_277672_, int p_277714_, int p_278088_, float p_277542_, long p_277414_, long p_277635_, int p_278037_, int p_277595_, int p_277794_, boolean p_277943_, int p_278007_, boolean p_277644_, boolean p_277749_, boolean p_278004_, WorldBorder.Settings p_277729_, int p_277674_, int p_277856_, @Nullable UUID p_277341_, Set p_277989_, Set p_277399_, TimerQueue p_277860_, @Nullable CompoundTag p_277936_, EndDragonFight.Data p_289764_, LevelSettings p_278064_, WorldOptions p_278072_, PrimaryLevelData.SpecialWorldProperty p_277548_, Lifecycle p_277915_) { - this.wasModded = p_278109_; -@@ -120,7 +_,7 @@ - return p_78529_.asString().result().stream(); - }).collect(Collectors.toCollection(Sets::newLinkedHashSet)), p_78531_.get("removed_features").asStream().flatMap((p_277335_) -> { - return p_277335_.asString().result().stream(); -- }).collect(Collectors.toSet()), new TimerQueue<>(TimerCallbacks.SERVER_CALLBACKS, p_78531_.get("ScheduledEvents").asStream()), (CompoundTag)p_78531_.get("CustomBossEvents").orElseEmptyMap().getValue(), p_78531_.get("DragonFight").read(EndDragonFight.Data.CODEC).resultOrPartial(LOGGER::error).orElse(EndDragonFight.Data.DEFAULT), p_78535_, p_251864_, p_250651_, p_78538_); -+ }).collect(Collectors.toSet()), new TimerQueue<>(TimerCallbacks.SERVER_CALLBACKS, p_78531_.get("ScheduledEvents").asStream()), (CompoundTag)p_78531_.get("CustomBossEvents").orElseEmptyMap().getValue(), p_78531_.get("DragonFight").read(EndDragonFight.Data.CODEC).resultOrPartial(LOGGER::error).orElse(EndDragonFight.Data.DEFAULT), p_78535_, p_251864_, p_250651_, p_78538_).withConfirmedWarning(p_78538_ != Lifecycle.stable() && p_78531_.get("confirmedExperimentalSettings").asBoolean(false)); - } + private PrimaryLevelData( + @Nullable CompoundTag p_277888_, +@@ -200,7 +_,7 @@ + p_251864_, + p_250651_, + p_78538_ +- ); ++ ).withConfirmedWarning(p_78538_ != Lifecycle.stable() && p_78531_.get("confirmedExperimentalSettings").asBoolean(false)); + } - public CompoundTag createTag(RegistryAccess p_78543_, @Nullable CompoundTag p_78544_) { -@@ -195,6 +_,8 @@ - p_78547_.putUUID("WanderingTraderId", this.wanderingTraderId); - } + @Override +@@ -273,6 +_,8 @@ + if (this.wanderingTraderId != null) { + p_78547_.putUUID("WanderingTraderId", this.wanderingTraderId); + } ++ p_78547_.putString("forgeLifecycle", net.minecraftforge.common.ForgeHooks.encodeLifecycle(this.settings.getLifecycle())); ++ p_78547_.putBoolean("confirmedExperimentalSettings", this.confirmedExperimentalWarning); + } -+ p_78547_.putString("forgeLifecycle", net.minecraftforge.common.ForgeHooks.encodeLifecycle(this.settings.getLifecycle())); -+ p_78547_.putBoolean("confirmedExperimentalSettings", this.confirmedExperimentalWarning); - } - - private static ListTag stringCollectionToTag(Set p_277880_) { -@@ -461,6 +_,15 @@ - - public LevelSettings getLevelSettings() { - return this.settings.copy(); -+ } + private static ListTag stringCollectionToTag(Set p_277880_) { +@@ -571,6 +_,16 @@ + public LevelSettings getLevelSettings() { + return this.settings.copy(); + } + -+ public boolean hasConfirmedExperimentalWarning() { -+ return this.confirmedExperimentalWarning; -+ } ++ public boolean hasConfirmedExperimentalWarning() { ++ return this.confirmedExperimentalWarning; ++ } ++ ++ public PrimaryLevelData withConfirmedWarning(boolean confirmedWarning) { // Builder-like to not patch ctor ++ this.confirmedExperimentalWarning = confirmedWarning; ++ return this; ++ } + -+ public PrimaryLevelData withConfirmedWarning(boolean confirmedWarning) { // Builder-like to not patch ctor -+ this.confirmedExperimentalWarning = confirmedWarning; -+ return this; - } - /** @deprecated */ + @Deprecated + public static enum SpecialWorldProperty { diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch index 084a075280..603f251011 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch @@ -1,79 +1,76 @@ --- a/net/minecraft/world/level/storage/loot/LootContext.java +++ b/net/minecraft/world/level/storage/loot/LootContext.java -@@ -86,15 +_,43 @@ - return new LootContext.VisitedEntry<>(LootDataType.MODIFIER, p_279163_); - } +@@ -23,11 +_,17 @@ + private final RandomSource random; + private final HolderGetter.Provider lootDataResolver; + private final Set> visitedElements = Sets.newLinkedHashSet(); ++ private ResourceLocation queriedLootTableId; -+ // ============================== FORGE START ============================== -+ public int getLootingModifier() { -+ return net.minecraftforge.common.ForgeHooks.getLootingLevel(getParamOrNull(LootContextParams.THIS_ENTITY), getParamOrNull(LootContextParams.KILLER_ENTITY), getParamOrNull(LootContextParams.DAMAGE_SOURCE)); -+ } + LootContext(LootParams p_287722_, RandomSource p_287702_, HolderGetter.Provider p_330439_) { ++ this(p_287722_, p_287702_, p_330439_, null); ++ } + -+ private ResourceLocation queriedLootTableId; -+ -+ private LootContext(LootParams p_287722_, RandomSource p_287702_, LootDataResolver p_287619_, ResourceLocation queriedLootTableId) { -+ this(p_287722_, p_287702_, p_287619_); -+ this.queriedLootTableId = queriedLootTableId; -+ } -+ -+ public void setQueriedLootTableId(ResourceLocation queriedLootTableId) { -+ if (this.queriedLootTableId == null && queriedLootTableId != null) this.queriedLootTableId = queriedLootTableId; -+ } -+ -+ public ResourceLocation getQueriedLootTableId() { -+ return this.queriedLootTableId == null ? net.minecraftforge.common.loot.LootTableIdCondition.UNKNOWN_LOOT_TABLE : this.queriedLootTableId; -+ } -+ // =============================== FORGE END =============================== -+ - public static class Builder { - private final LootParams params; - @Nullable - private RandomSource random; -+ private ResourceLocation queriedLootTableId; // Forge: correctly pass around loot table ID with copy constructor ++ LootContext(LootParams p_287722_, RandomSource p_287702_, HolderGetter.Provider p_330439_, ResourceLocation queriedLootTableId) { + this.params = p_287722_; + this.random = p_287702_; + this.lootDataResolver = p_330439_; ++ this.queriedLootTableId = queriedLootTableId; + } - public Builder(LootParams p_287628_) { - this.params = p_287628_; - } + public boolean hasParam(LootContextParam p_78937_) { +@@ -87,15 +_,34 @@ + return new LootContext.VisitedEntry<>(LootDataType.MODIFIER, p_279163_); + } -+ public Builder(LootContext context) { -+ this.params = context.params; -+ this.random = context.random; -+ this.queriedLootTableId = context.queriedLootTableId; -+ } ++ public int getLootingModifier() { ++ return net.minecraftforge.common.ForgeHooks.getLootingLevel(getParamOrNull(LootContextParams.THIS_ENTITY), getParamOrNull(LootContextParams.KILLER_ENTITY), getParamOrNull(LootContextParams.DAMAGE_SOURCE)); ++ } + - public LootContext.Builder withOptionalRandomSeed(long p_78966_) { - if (p_78966_ != 0L) { - this.random = RandomSource.create(p_78966_); -@@ -103,6 +_,11 @@ - return this; - } - -+ public LootContext.Builder withQueriedLootTableId(ResourceLocation queriedLootTableId) { -+ this.queriedLootTableId = queriedLootTableId; -+ return this; -+ } ++ public void setQueriedLootTableId(ResourceLocation queriedLootTableId) { ++ if (this.queriedLootTableId == null && queriedLootTableId != null) this.queriedLootTableId = queriedLootTableId; ++ } + - public ServerLevel getLevel() { - return this.params.getLevel(); - } -@@ -113,7 +_,7 @@ - RandomSource randomsource = Optional.ofNullable(this.random).or(() -> { - return p_299315_.map(serverlevel::getRandomSequence); - }).orElseGet(serverlevel::getRandom); -- return new LootContext(this.params, randomsource, minecraftserver.getLootData()); -+ return new LootContext(this.params, randomsource, minecraftserver.getLootData(), queriedLootTableId); - } - } - -@@ -134,6 +_,11 @@ - - public LootContextParam getParam() { - return this.param; -+ } ++ public ResourceLocation getQueriedLootTableId() { ++ return this.queriedLootTableId == null ? net.minecraftforge.common.loot.LootTableIdCondition.UNKNOWN_LOOT_TABLE : this.queriedLootTableId; ++ } + -+ // Forge: This method is patched in to expose the same name used in getByName so that ContextNbtProvider#forEntity serializes it properly -+ public String getName() { -+ return this.name; - } + public static class Builder { + private final LootParams params; + @Nullable + private RandomSource random; ++ private ResourceLocation queriedLootTableId; // Forge: correctly pass around loot table ID with copy constructor + + public Builder(LootParams p_287628_) { + this.params = p_287628_; + } + ++ public Builder(LootContext context) { ++ this.params = context.params; ++ this.random = context.random; ++ this.queriedLootTableId = context.queriedLootTableId; ++ } ++ + public LootContext.Builder withOptionalRandomSeed(long p_78966_) { + if (p_78966_ != 0L) { + this.random = RandomSource.create(p_78966_); +@@ -104,6 +_,11 @@ + return this; + } + ++ public LootContext.Builder withQueriedLootTableId(ResourceLocation queriedLootTableId) { ++ this.queriedLootTableId = queriedLootTableId; ++ return this; ++ } ++ + public ServerLevel getLevel() { + return this.params.getLevel(); + } +@@ -112,7 +_,7 @@ + ServerLevel serverlevel = this.getLevel(); + MinecraftServer minecraftserver = serverlevel.getServer(); + RandomSource randomsource = Optional.ofNullable(this.random).or(() -> p_299315_.map(serverlevel::getRandomSequence)).orElseGet(serverlevel::getRandom); +- return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup()); ++ return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup(), queriedLootTableId); + } + } - public static LootContext.EntityTarget getByName(String p_79007_) { diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootDataType.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootDataType.java.patch index c37a47e904..9dcca2f45b 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootDataType.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootDataType.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/storage/loot/LootDataType.java +++ b/net/minecraft/world/level/storage/loot/LootDataType.java -@@ -42,7 +_,12 @@ - dataresult.error().ifPresent((p_297003_) -> { - LOGGER.error("Couldn't parse element {}:{} - {}", this.directory, p_279253_, p_297003_.message()); - }); -- return dataresult.result(); -+ var ret = dataresult.result(); -+ if (ret.orElse(null) instanceof LootTable table) { -+ table.setLootTableId(p_279253_); -+ ret = Optional.ofNullable((T)net.minecraftforge.event.ForgeEventFactory.onLoadLootTable(p_279253_, table)); -+ } -+ return ret; - } +@@ -34,7 +_,12 @@ + public Optional deserialize(ResourceLocation p_279253_, DynamicOps p_335939_, V p_327740_) { + DataResult dataresult = this.codec.parse(p_335939_, p_327740_); + dataresult.error().ifPresent(p_327555_ -> LOGGER.error("Couldn't parse element {}:{} - {}", this.directory, p_279253_, p_327555_.message())); +- return dataresult.result(); ++ var ret = dataresult.result(); ++ if (ret.orElse(null) instanceof LootTable table) { ++ table.setLootTableId(p_279253_); ++ ret = Optional.ofNullable((T)net.minecraftforge.event.ForgeEventFactory.onLoadLootTable(p_279253_, table)); ++ } ++ return ret; + } - public static Stream> values() { + public static Stream> values() { diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch index 642b74420a..f2d7d0cb00 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/storage/loot/LootParams.java +++ b/net/minecraft/world/level/storage/loot/LootParams.java -@@ -124,7 +_,7 @@ +@@ -125,7 +_,7 @@ - public LootParams create(LootContextParamSet p_287701_) { - Set> set = Sets.difference(this.params.keySet(), p_287701_.getAllowed()); -- if (!set.isEmpty()) { -+ if (false && !set.isEmpty()) { // Forge: Allow mods to pass custom loot parameters (not part of the vanilla loot table) to the loot context. - throw new IllegalArgumentException("Parameters not allowed in this parameter set: " + set); - } else { - Set> set1 = Sets.difference(p_287701_.getRequired(), this.params.keySet()); + public LootParams create(LootContextParamSet p_287701_) { + Set> set = Sets.difference(this.params.keySet(), p_287701_.getAllowed()); +- if (!set.isEmpty()) { ++ if (false && !set.isEmpty()) { // Forge: Allow mods to pass custom loot parameters (not part of the vanilla loot table) to the loot context. + throw new IllegalArgumentException("Parameters not allowed in this parameter set: " + set); + } else { + Set> set1 = Sets.difference(p_287701_.getRequired(), this.params.keySet()); diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch index 747145bec1..4acba9b052 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch @@ -1,95 +1,105 @@ --- a/net/minecraft/world/level/storage/loot/LootPool.java +++ b/net/minecraft/world/level/storage/loot/LootPool.java -@@ -38,8 +_,12 @@ - return p_297004_.rolls; - }), NumberProviders.CODEC.fieldOf("bonus_rolls").orElse(ConstantValue.exactly(0.0F)).forGetter((p_297006_) -> { - return p_297006_.bonusRolls; -- })).apply(p_297005_, LootPool::new); -+ }), -+ Codec.STRING.optionalFieldOf("name").forGetter(p -> p.name.filter(n -> !n.startsWith("custom#"))), -+ net.minecraftforge.common.crafting.conditions.ICondition.OPTIONAL_FEILD_CODEC.forGetter(p -> p.forge_condition) -+ ).apply(p_297005_, LootPool::new); - }); -+ public static final Codec CONDITIONAL_CODEC = net.minecraftforge.common.crafting.conditions.ConditionCodec.checkingDecode(CODEC, () -> lootPool().build()); - private final List entries; - private final List conditions; - private final Predicate compositeCondition; -@@ -47,8 +_,13 @@ - private final BiFunction compositeFunction; - private NumberProvider rolls; - private NumberProvider bonusRolls; -+ private java.util.Optional name; -+ private java.util.Optional forge_condition; - - LootPool(List p_298341_, List p_297697_, List p_299722_, NumberProvider p_165131_, NumberProvider p_165132_) { -+ this(p_298341_, p_297697_, p_299722_, p_165131_, p_165132_, java.util.Optional.empty(), java.util.Optional.empty()); -+ } -+ LootPool(List p_298341_, List p_297697_, List p_299722_, NumberProvider p_165131_, NumberProvider p_165132_, java.util.Optional name, java.util.Optional forge_conditions) { - this.entries = p_298341_; - this.conditions = p_297697_; - this.compositeCondition = LootItemConditions.andConditions(p_297697_); -@@ -56,6 +_,8 @@ - this.compositeFunction = LootItemFunctions.compose(p_299722_); - this.rolls = p_165131_; - this.bonusRolls = p_165132_; -+ this.name = name; -+ this.forge_condition = forge_conditions; - } - - private void addRandomItem(Consumer p_79059_, LootContext p_79060_) { -@@ -126,12 +_,35 @@ - return new LootPool.Builder(); - } - -+ private boolean isFrozen = false; -+ public void freeze() { this.isFrozen = true; } -+ public boolean isFrozen(){ return this.isFrozen; } -+ private void checkFrozen() { -+ if (this.isFrozen()) -+ throw new RuntimeException("Attempted to modify LootPool after being frozen!"); -+ } -+ @org.jetbrains.annotations.Nullable -+ public String getName() { return this.name.orElse(null); } -+ void setName(final String name) { -+ if (this.name.isPresent()) -+ throw new UnsupportedOperationException("Cannot change the name of a pool when it has a name set!"); -+ this.name = java.util.Optional.of(name); -+ } -+ public NumberProvider getRolls() { return this.rolls; } -+ public NumberProvider getBonusRolls() { return this.bonusRolls; } -+ public void setRolls (NumberProvider v){ checkFrozen(); this.rolls = v; } -+ public void setBonusRolls(NumberProvider v){ checkFrozen(); this.bonusRolls = v; } +@@ -34,10 +_,13 @@ + LootItemConditions.DIRECT_CODEC.listOf().optionalFieldOf("conditions", List.of()).forGetter(p_297008_ -> p_297008_.conditions), + LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(p_297009_ -> p_297009_.functions), + NumberProviders.CODEC.fieldOf("rolls").forGetter(p_297004_ -> p_297004_.rolls), +- NumberProviders.CODEC.fieldOf("bonus_rolls").orElse(ConstantValue.exactly(0.0F)).forGetter(p_297006_ -> p_297006_.bonusRolls) ++ NumberProviders.CODEC.fieldOf("bonus_rolls").orElse(ConstantValue.exactly(0.0F)).forGetter(p_297006_ -> p_297006_.bonusRolls), ++ Codec.STRING.optionalFieldOf("name").forGetter(p -> p.name.filter(n -> !n.startsWith("custom#"))), ++ net.minecraftforge.common.crafting.conditions.ICondition.OPTIONAL_FEILD_CODEC.forGetter(p -> p.forge_condition) + ) + .apply(p_327556_, LootPool::new) + ); ++ public static final Codec CONDITIONAL_CODEC = net.minecraftforge.common.crafting.conditions.ConditionCodec.checkingDecode(CODEC, () -> lootPool().build()); + private final List entries; + private final List conditions; + private final Predicate compositeCondition; +@@ -45,13 +_,21 @@ + private final BiFunction compositeFunction; + private NumberProvider rolls; + private NumberProvider bonusRolls; ++ private java.util.Optional name; ++ private java.util.Optional forge_condition; + - public static class Builder implements FunctionUserBuilder, ConditionUserBuilder { - private final ImmutableList.Builder entries = ImmutableList.builder(); - private final ImmutableList.Builder conditions = ImmutableList.builder(); - private final ImmutableList.Builder functions = ImmutableList.builder(); - private NumberProvider rolls = ConstantValue.exactly(1.0F); - private NumberProvider bonusRolls = ConstantValue.exactly(0.0F); -+ @org.jetbrains.annotations.Nullable -+ private String name; -+ @org.jetbrains.annotations.Nullable -+ private net.minecraftforge.common.crafting.conditions.ICondition forge_condition; ++ LootPool(List p_298341_, List p_297697_, List p_299722_, NumberProvider p_165131_, NumberProvider p_165132_) { ++ this(p_298341_, p_297697_, p_299722_, p_165131_, p_165132_, java.util.Optional.empty(), java.util.Optional.empty()); ++ } - public LootPool.Builder setRolls(NumberProvider p_165134_) { - this.rolls = p_165134_; -@@ -162,8 +_,18 @@ - return this; - } + LootPool( + List p_298341_, + List p_297697_, + List p_299722_, + NumberProvider p_165131_, +- NumberProvider p_165132_ ++ NumberProvider p_165132_, ++ java.util.Optional name, ++ java.util.Optional forge_condition + ) { + this.entries = p_298341_; + this.conditions = p_297697_; +@@ -60,6 +_,8 @@ + this.compositeFunction = LootItemFunctions.compose(p_299722_); + this.rolls = p_165131_; + this.bonusRolls = p_165132_; ++ this.name = name; ++ this.forge_condition = forge_condition; + } -+ public LootPool.Builder name(String name) { -+ this.name = name; -+ return this; -+ } + private void addRandomItem(Consumer p_79059_, LootContext p_79060_) { +@@ -127,12 +_,35 @@ + return new LootPool.Builder(); + } + ++ private boolean isFrozen = false; ++ public void freeze() { this.isFrozen = true; } ++ public boolean isFrozen(){ return this.isFrozen; } ++ private void checkFrozen() { ++ if (this.isFrozen()) ++ throw new RuntimeException("Attempted to modify LootPool after being frozen!"); ++ } ++ @org.jetbrains.annotations.Nullable ++ public String getName() { return this.name.orElse(null); } ++ void setName(final String name) { ++ if (this.name.isPresent()) ++ throw new UnsupportedOperationException("Cannot change the name of a pool when it has a name set!"); ++ this.name = java.util.Optional.of(name); ++ } ++ public NumberProvider getRolls() { return this.rolls; } ++ public NumberProvider getBonusRolls() { return this.bonusRolls; } ++ public void setRolls (NumberProvider v){ checkFrozen(); this.rolls = v; } ++ public void setBonusRolls(NumberProvider v){ checkFrozen(); this.bonusRolls = v; } + -+ public LootPool.Builder when(net.minecraftforge.common.crafting.conditions.ICondition value) { -+ this.forge_condition = value; -+ return this; -+ } + public static class Builder implements FunctionUserBuilder, ConditionUserBuilder { + private final ImmutableList.Builder entries = ImmutableList.builder(); + private final ImmutableList.Builder conditions = ImmutableList.builder(); + private final ImmutableList.Builder functions = ImmutableList.builder(); + private NumberProvider rolls = ConstantValue.exactly(1.0F); + private NumberProvider bonusRolls = ConstantValue.exactly(0.0F); ++ @org.jetbrains.annotations.Nullable ++ private String name; ++ @org.jetbrains.annotations.Nullable ++ private net.minecraftforge.common.crafting.conditions.ICondition forge_condition; + + public LootPool.Builder setRolls(NumberProvider p_165134_) { + this.rolls = p_165134_; +@@ -163,8 +_,18 @@ + return this; + } + ++ public LootPool.Builder name(String name) { ++ this.name = name; ++ return this; ++ } + - public LootPool build() { -- return new LootPool(this.entries.build(), this.conditions.build(), this.functions.build(), this.rolls, this.bonusRolls); -+ return new LootPool(this.entries.build(), this.conditions.build(), this.functions.build(), this.rolls, this.bonusRolls, java.util.Optional.ofNullable(this.name), java.util.Optional.ofNullable(forge_condition)); - } - } ++ public LootPool.Builder when(net.minecraftforge.common.crafting.conditions.ICondition value) { ++ this.forge_condition = value; ++ return this; ++ } ++ + public LootPool build() { +- return new LootPool(this.entries.build(), this.conditions.build(), this.functions.build(), this.rolls, this.bonusRolls); ++ return new LootPool(this.entries.build(), this.conditions.build(), this.functions.build(), this.rolls, this.bonusRolls, java.util.Optional.ofNullable(this.name), java.util.Optional.ofNullable(forge_condition)); + } + } } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch index 24251e173f..846db054ce 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch @@ -1,114 +1,117 @@ --- a/net/minecraft/world/level/storage/loot/LootTable.java +++ b/net/minecraft/world/level/storage/loot/LootTable.java -@@ -35,7 +_,7 @@ - return p_297013_.paramSet; - }), ExtraCodecs.strictOptionalField(ResourceLocation.CODEC, "random_sequence").forGetter((p_297014_) -> { - return p_297014_.randomSequence; -- }), ExtraCodecs.strictOptionalField(LootPool.CODEC.listOf(), "pools", List.of()).forGetter((p_297012_) -> { -+ }), ExtraCodecs.strictOptionalField(LootPool.CONDITIONAL_CODEC.listOf(), "pools", List.of()).forGetter((p_297012_) -> { - return p_297012_.pools; - }), ExtraCodecs.strictOptionalField(LootItemFunctions.CODEC.listOf(), "functions", List.of()).forGetter((p_297010_) -> { - return p_297010_.functions; -@@ -50,7 +_,7 @@ - LootTable(LootContextParamSet p_287716_, Optional p_298628_, List p_298771_, List p_301234_) { - this.paramSet = p_287716_; - this.randomSequence = p_298628_; -- this.pools = p_298771_; -+ this.pools = Lists.newArrayList(p_298771_); - this.functions = p_301234_; - this.compositeFunction = LootItemFunctions.compose(p_301234_); - } -@@ -74,10 +_,12 @@ - }; - } +@@ -38,7 +_,7 @@ + p_327557_ -> p_327557_.group( + LootContextParamSets.CODEC.lenientOptionalFieldOf("type", DEFAULT_PARAM_SET).forGetter(p_297013_ -> p_297013_.paramSet), + ResourceLocation.CODEC.optionalFieldOf("random_sequence").forGetter(p_297014_ -> p_297014_.randomSequence), +- LootPool.CODEC.listOf().optionalFieldOf("pools", List.of()).forGetter(p_297012_ -> p_297012_.pools), ++ LootPool.CONDITIONAL_CODEC.listOf().optionalFieldOf("pools", List.of()).forGetter(p_297012_ -> p_297012_.pools), + LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(p_297010_ -> p_297010_.functions) + ) + .apply(p_327557_, LootTable::new) +@@ -53,7 +_,7 @@ + LootTable(LootContextParamSet p_287716_, Optional p_298628_, List p_298771_, List p_301234_) { + this.paramSet = p_287716_; + this.randomSequence = p_298628_; +- this.pools = p_298771_; ++ this.pools = Lists.newArrayList(p_298771_); + this.functions = p_301234_; + this.compositeFunction = LootItemFunctions.compose(p_301234_); + } +@@ -76,10 +_,12 @@ + }; + } -+ @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied - public void getRandomItemsRaw(LootParams p_287669_, Consumer p_287781_) { - this.getRandomItemsRaw((new LootContext.Builder(p_287669_)).create(this.randomSequence), p_287781_); - } ++ @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied + public void getRandomItemsRaw(LootParams p_287669_, Consumer p_287781_) { + this.getRandomItemsRaw(new LootContext.Builder(p_287669_).create(this.randomSequence), p_287781_); + } -+ @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied - public void getRandomItemsRaw(LootContext p_79132_, Consumer p_79133_) { - LootContext.VisitedEntry visitedentry = LootContext.createVisitedEntry(this); - if (p_79132_.pushVisitedElement(visitedentry)) { -@@ -95,15 +_,15 @@ - } ++ @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied + public void getRandomItemsRaw(LootContext p_79132_, Consumer p_79133_) { + LootContext.VisitedEntry visitedentry = LootContext.createVisitedEntry(this); + if (p_79132_.pushVisitedElement(visitedentry)) { +@@ -96,15 +_,15 @@ + } - public void getRandomItems(LootParams p_287748_, long p_287729_, Consumer p_287583_) { -- this.getRandomItemsRaw((new LootContext.Builder(p_287748_)).withOptionalRandomSeed(p_287729_).create(this.randomSequence), createStackSplitter(p_287748_.getLevel(), p_287583_)); -+ this.getRandomItems((new LootContext.Builder(p_287748_)).withOptionalRandomSeed(p_287729_).create(this.randomSequence)).forEach(p_287583_); - } + public void getRandomItems(LootParams p_287748_, long p_287729_, Consumer p_287583_) { +- this.getRandomItemsRaw(new LootContext.Builder(p_287748_).withOptionalRandomSeed(p_287729_).create(this.randomSequence), createStackSplitter(p_287748_.getLevel(), p_287583_)); ++ this.getRandomItems(new LootContext.Builder(p_287748_).withOptionalRandomSeed(p_287729_).create(this.randomSequence)).forEach(p_287583_); + } - public void getRandomItems(LootParams p_287704_, Consumer p_287617_) { -- this.getRandomItemsRaw(p_287704_, createStackSplitter(p_287704_.getLevel(), p_287617_)); -+ this.getRandomItems(p_287704_).forEach(p_287617_); - } + public void getRandomItems(LootParams p_287704_, Consumer p_287617_) { +- this.getRandomItemsRaw(p_287704_, createStackSplitter(p_287704_.getLevel(), p_287617_)); ++ this.getRandomItems(p_287704_).forEach(p_287617_); + } - public void getRandomItems(LootContext p_79149_, Consumer p_79150_) { -- this.getRandomItemsRaw(p_79149_, createStackSplitter(p_79149_.getLevel(), p_79150_)); -+ this.getRandomItems(p_79149_).forEach(p_79150_); - } + public void getRandomItems(LootContext p_79149_, Consumer p_79150_) { +- this.getRandomItemsRaw(p_79149_, createStackSplitter(p_79149_.getLevel(), p_79150_)); ++ this.getRandomItems(p_79149_).forEach(p_79150_); + } - public ObjectArrayList getRandomItems(LootParams p_287574_, long p_287773_) { -@@ -116,7 +_,8 @@ + public ObjectArrayList getRandomItems(LootParams p_287574_, long p_287773_) { +@@ -117,7 +_,8 @@ - private ObjectArrayList getRandomItems(LootContext p_230923_) { - ObjectArrayList objectarraylist = new ObjectArrayList<>(); -- this.getRandomItems(p_230923_, objectarraylist::add); -+ this.getRandomItemsRaw(p_230923_, createStackSplitter(p_230923_.getLevel(), objectarraylist::add)); -+ objectarraylist = net.minecraftforge.common.ForgeHooks.modifyLoot(this.getLootTableId(), objectarraylist, p_230923_); - return objectarraylist; - } + private ObjectArrayList getRandomItems(LootContext p_230923_) { + ObjectArrayList objectarraylist = new ObjectArrayList<>(); +- this.getRandomItems(p_230923_, objectarraylist::add); ++ this.getRandomItemsRaw(p_230923_, createStackSplitter(p_230923_.getLevel(), objectarraylist::add)); ++ objectarraylist = net.minecraftforge.common.ForgeHooks.modifyLoot(this.getLootTableId(), objectarraylist, p_230923_); + return objectarraylist; + } -@@ -207,6 +_,51 @@ +@@ -206,6 +_,54 @@ - public static LootTable.Builder lootTable() { - return new LootTable.Builder(); -+ } + public static LootTable.Builder lootTable() { + return new LootTable.Builder(); ++ } + -+ private ResourceLocation lootTableId; -+ public void setLootTableId(final ResourceLocation id) { -+ if (this.lootTableId != null) -+ throw new IllegalStateException("Attempted to rename loot table from '" + this.lootTableId + "' to '" + id + "': this is not supported"); -+ this.lootTableId = java.util.Objects.requireNonNull(id); -+ } ++ private ResourceLocation lootTableId; ++ public void setLootTableId(final ResourceLocation id) { ++ if (this.lootTableId != null) { ++ throw new IllegalStateException("Attempted to rename loot table from '" + this.lootTableId + "' to '" + id + "': this is not supported"); ++ } ++ this.lootTableId = java.util.Objects.requireNonNull(id); ++ } + -+ public ResourceLocation getLootTableId() { -+ return this.lootTableId; -+ } ++ public ResourceLocation getLootTableId() { ++ return this.lootTableId; ++ } + -+ @org.jetbrains.annotations.Nullable -+ public LootPool removePool(String name) { -+ checkFrozen(); -+ for (var pool : this.pools) { -+ if (name.equals(pool.getName())) { -+ this.pools.remove(pool); -+ return pool; -+ } -+ } -+ return null; -+ } ++ @org.jetbrains.annotations.Nullable ++ public LootPool removePool(String name) { ++ checkFrozen(); ++ for (var pool : this.pools) { ++ if (name.equals(pool.getName())) { ++ this.pools.remove(pool); ++ return pool; ++ } ++ } ++ return null; ++ } + -+ public void addPool(LootPool pool) { -+ checkFrozen(); -+ if (pools.stream().anyMatch(e -> e == pool)) -+ throw new RuntimeException("Attempted to add a duplicate pool to loot table: " + pool); -+ this.pools.add(pool); -+ } ++ public void addPool(LootPool pool) { ++ checkFrozen(); ++ if (pools.stream().anyMatch(e -> e == pool)) { ++ throw new RuntimeException("Attempted to add a duplicate pool to loot table: " + pool); ++ } ++ this.pools.add(pool); ++ } + -+ private boolean isFrozen = false; -+ public void freeze() { -+ this.isFrozen = true; -+ this.pools.forEach(LootPool::freeze); -+ } ++ private boolean isFrozen = false; ++ public void freeze() { ++ this.isFrozen = true; ++ this.pools.forEach(LootPool::freeze); ++ } + -+ public boolean isFrozen() { -+ return this.isFrozen; -+ } ++ public boolean isFrozen() { ++ return this.isFrozen; ++ } + -+ private void checkFrozen() { -+ if (this.isFrozen()) -+ throw new RuntimeException("Attempted to modify LootTable after being finalized!"); - } ++ private void checkFrozen() { ++ if (this.isFrozen()) { ++ throw new RuntimeException("Attempted to modify LootTable after being finalized!"); ++ } + } - public static class Builder implements FunctionUserBuilder { + public static class Builder implements FunctionUserBuilder { diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java.patch index 13c9d94db0..cec0dbaea0 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java +++ b/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java -@@ -51,7 +_,7 @@ - public ItemStack run(ItemStack p_80789_, LootContext p_80790_) { - Entity entity = p_80790_.getParamOrNull(LootContextParams.KILLER_ENTITY); - if (entity instanceof LivingEntity) { -- int i = EnchantmentHelper.getMobLooting((LivingEntity)entity); -+ int i = p_80790_.getLootingModifier(); - if (i == 0) { - return p_80789_; - } +@@ -58,7 +_,7 @@ + public ItemStack run(ItemStack p_80789_, LootContext p_80790_) { + Entity entity = p_80790_.getParamOrNull(LootContextParams.KILLER_ENTITY); + if (entity instanceof LivingEntity) { +- int i = EnchantmentHelper.getMobLooting((LivingEntity)entity); ++ int i = p_80790_.getLootingModifier(); + if (i == 0) { + return p_80789_; + } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java.patch index 5fb7f2bd52..22bb631d44 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java +++ b/net/minecraft/world/level/storage/loot/functions/SmeltItemFunction.java -@@ -36,7 +_,7 @@ - if (optional.isPresent()) { - ItemStack itemstack = optional.get().value().getResultItem(p_81269_.getLevel().registryAccess()); - if (!itemstack.isEmpty()) { -- return itemstack.copyWithCount(p_81268_.getCount()); -+ return itemstack.copyWithCount(p_81268_.getCount() * itemstack.getCount()); // Forge: Support smelting returning multiple +@@ -41,7 +_,7 @@ + if (optional.isPresent()) { + ItemStack itemstack = optional.get().value().getResultItem(p_81269_.getLevel().registryAccess()); + if (!itemstack.isEmpty()) { +- return itemstack.copyWithCount(p_81268_.getCount()); ++ return itemstack.copyWithCount(p_81268_.getCount() * itemstack.getCount()); // Forge: Support smelting returning multiple + } } - } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java.patch index 6227bf360a..d9cb0f4865 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java.patch @@ -1,18 +1,20 @@ --- a/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java +++ b/net/minecraft/world/level/storage/loot/parameters/LootContextParamSets.java -@@ -21,6 +_,7 @@ - }); - public static final LootContextParamSet CHEST = register("chest", (p_81452_) -> { - p_81452_.required(LootContextParams.ORIGIN).optional(LootContextParams.THIS_ENTITY); -+ p_81452_.optional(LootContextParams.KILLER_ENTITY); //Forge: Chest Minecarts can have killers. - }); - public static final LootContextParamSet COMMAND = register("command", (p_81450_) -> { - p_81450_.required(LootContextParams.ORIGIN).optional(LootContextParams.THIS_ENTITY); -@@ -30,6 +_,7 @@ - }); - public static final LootContextParamSet FISHING = register("fishing", (p_81446_) -> { - p_81446_.required(LootContextParams.ORIGIN).required(LootContextParams.TOOL).optional(LootContextParams.THIS_ENTITY); -+ p_81446_.optional(LootContextParams.KILLER_ENTITY).optional(LootContextParams.THIS_ENTITY); //Forge: Allow fisher, and bobber - }); - public static final LootContextParamSet ENTITY = register("entity", (p_81444_) -> { - p_81444_.required(LootContextParams.THIS_ENTITY).required(LootContextParams.ORIGIN).required(LootContextParams.DAMAGE_SOURCE).optional(LootContextParams.KILLER_ENTITY).optional(LootContextParams.DIRECT_KILLER_ENTITY).optional(LootContextParams.LAST_DAMAGE_PLAYER); +@@ -20,7 +_,7 @@ + public static final LootContextParamSet EMPTY = register("empty", p_81454_ -> { + }); + public static final LootContextParamSet CHEST = register( +- "chest", p_327636_ -> p_327636_.required(LootContextParams.ORIGIN).optional(LootContextParams.THIS_ENTITY) ++ "chest", p_327636_ -> p_327636_.required(LootContextParams.ORIGIN).optional(LootContextParams.THIS_ENTITY).optional(LootContextParams.KILLER_ENTITY) //Forge: Chest Minecarts can have killers. + ); + public static final LootContextParamSet COMMAND = register( + "command", p_327634_ -> p_327634_.required(LootContextParams.ORIGIN).optional(LootContextParams.THIS_ENTITY) +@@ -29,7 +_,7 @@ + "selector", p_81442_ -> p_81442_.required(LootContextParams.ORIGIN).required(LootContextParams.THIS_ENTITY) + ); + public static final LootContextParamSet FISHING = register( +- "fishing", p_81446_ -> p_81446_.required(LootContextParams.ORIGIN).required(LootContextParams.TOOL).optional(LootContextParams.THIS_ENTITY) ++ "fishing", p_81446_ -> p_81446_.required(LootContextParams.ORIGIN).required(LootContextParams.TOOL).optional(LootContextParams.THIS_ENTITY).optional(LootContextParams.KILLER_ENTITY).optional(LootContextParams.THIS_ENTITY) //Forge: Allow fisher, and bobber + ); + public static final LootContextParamSet ENTITY = register( + "entity", diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java.patch index 577c206617..08fd78e1e7 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java +++ b/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithLootingCondition.java -@@ -25,12 +_,7 @@ - } +@@ -33,12 +_,7 @@ + } - public boolean test(LootContext p_81967_) { -- Entity entity = p_81967_.getParamOrNull(LootContextParams.KILLER_ENTITY); -- int i = 0; -- if (entity instanceof LivingEntity) { -- i = EnchantmentHelper.getMobLooting((LivingEntity)entity); -- } + public boolean test(LootContext p_81967_) { +- Entity entity = p_81967_.getParamOrNull(LootContextParams.KILLER_ENTITY); +- int i = 0; +- if (entity instanceof LivingEntity) { +- i = EnchantmentHelper.getMobLooting((LivingEntity)entity); +- } - -+ int i = p_81967_.getLootingModifier(); - return p_81967_.getRandom().nextFloat() < this.percent + (float)i * this.lootingMultiplier; - } ++ int i = p_81967_.getLootingModifier(); + return p_81967_.getRandom().nextFloat() < this.percent + (float)i * this.lootingMultiplier; + } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java.patch index e645f9fb99..0f804d92a1 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java +++ b/net/minecraft/world/level/storage/loot/providers/nbt/ContextNbtProvider.java -@@ -57,7 +_,7 @@ - } +@@ -60,7 +_,7 @@ - public String getId() { -- return p_165578_.name(); -+ return p_165578_.getName(); - } + @Override + public String getId() { +- return p_165578_.name(); ++ return p_165578_.getSerializedName(); + } - public Set> getReferencedContextParams() { + @Override diff --git a/settings.gradle b/settings.gradle index ab970ae39e..346ad785ff 100644 --- a/settings.gradle +++ b/settings.gradle @@ -25,20 +25,19 @@ plugins { dependencyResolutionManagement { versionCatalogs { libs { - library('forgespi', 'net.minecraftforge:forgespi:7.1.3') // Needs modlauncher - library('modlauncher', 'net.minecraftforge:modlauncher:10.1.2') // Needs securemodules - library('securemodules', 'net.minecraftforge:securemodules:2.2.10') // Needs unsafe + library('forgespi', 'net.minecraftforge:forgespi:7.1.4') // Needs modlauncher + library('modlauncher', 'net.minecraftforge:modlauncher:10.2.1') // Needs securemodules + library('securemodules', 'net.minecraftforge:securemodules:2.2.14') // Needs unsafe library('unsafe', 'net.minecraftforge:unsafe:0.9.2') - library('accesstransformers', 'net.minecraftforge:accesstransformers:8.1.1') - library('antlr-runtime', 'org.antlr:antlr4-runtime:4.9.1') // Needed by Access Transformer because parsing a simple text file was too complicated - library('coremods', 'net.minecraftforge:coremods:5.1.0') - library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.3') // Needed by coremods, because the JRE no longer ships JS - library('eventbus', 'net.minecraftforge:eventbus:6.2.0') + library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.0') + library('coremods', 'net.minecraftforge:coremods:5.1.6') + library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.4') // Needed by coremods, because the JRE no longer ships JS + library('eventbus', 'net.minecraftforge:eventbus:6.2.6') library('typetools', 'net.jodah:typetools:0.6.3') // Needed by EventBus because of lambdas library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0') library('mixin', 'org.spongepowered:mixin:0.8.5') - library('nulls', 'org.jetbrains:annotations:23.0.0') // Got to have our null annotations! + library('nulls', 'org.jetbrains:annotations:24.1.0') // Got to have our null annotations! library('slf4j-api', 'org.slf4j:slf4j-api:2.0.7') library('maven-artifact', 'org.apache.maven:maven-artifact:3.8.5') @@ -53,7 +52,7 @@ dependencyResolutionManagement { library('bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim').versionRef('bootstrap') // ASM it's used for so many of our hacks - version('asm', '9.6') + version('asm', '9.7') library('asm', 'org.ow2.asm', 'asm' ).versionRef('asm') library('asm-tree', 'org.ow2.asm', 'asm-tree' ).versionRef('asm') library('asm-util', 'org.ow2.asm', 'asm-util' ).versionRef('asm') @@ -87,15 +86,18 @@ dependencyResolutionManagement { library('gson', 'com.google.code.gson:gson:2.10.1') library('guava', 'com.google.guava:guava:32.1.2-jre') library('failureaccess', 'com.google.guava:failureaccess:1.0.1') - version('log4j', '2.19.0') + + version('log4j', '2.22.1') library('log4j-api', 'org.apache.logging.log4j', 'log4j-api' ).versionRef('log4j') library('log4j-core', 'org.apache.logging.log4j', 'log4j-core').versionRef('log4j') - library('apache-commons', 'org.apache.commons:commons-lang3:3.12.0') - library('mojang-logging', 'com.mojang:logging:1.1.1') + bundle('log4j', ['log4j-api', 'log4j-core']) + + library('apache-commons', 'org.apache.commons:commons-lang3:3.14.0') + library('mojang-logging', 'com.mojang:logging:1.2.7') library('jopt-simple', 'net.sf.jopt-simple:jopt-simple:5.0.4') - library('commons-io', 'commons-io:commons-io:2.13.0') + library('commons-io', 'commons-io:commons-io:2.15.1') - version('lwjgl', '3.3.2') + version('lwjgl', '3.3.3') library('lwjgl', 'org.lwjgl', 'lwjgl' ).versionRef('lwjgl') library('lwjgl-glfw', 'org.lwjgl', 'lwjgl-glfw' ).versionRef('lwjgl') library('lwjgl-opengl', 'org.lwjgl', 'lwjgl-opengl').versionRef('lwjgl') diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/acacia_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/acacia_leaves.json index 11ce2ce756..aa80edcbe6 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/acacia_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/acacia_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/azalea_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/azalea_leaves.json index fe79b24d21..8218442c07 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/azalea_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/azalea_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/birch_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/birch_leaves.json index f4196b018e..f8a9030f70 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/birch_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/birch_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/cherry_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/cherry_leaves.json index b873d7821f..c0b754e62a 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/cherry_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/cherry_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/cobweb.json b/src/main/generated/data/minecraft/loot_tables/blocks/cobweb.json index f0a5746a81..daaa6c9d6d 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/cobweb.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/cobweb.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/dark_oak_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/dark_oak_leaves.json index 0c3515faf1..fd33f9d5a9 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/dark_oak_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/dark_oak_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -138,14 +142,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/flowering_azalea_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/flowering_azalea_leaves.json index 50ade83fc1..4f13172715 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/flowering_azalea_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/flowering_azalea_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/jungle_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/jungle_leaves.json index 6e55495f1c..e8ca655b01 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/jungle_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/jungle_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -75,14 +77,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/large_fern.json b/src/main/generated/data/minecraft/loot_tables/blocks/large_fern.json index ff6ba4bbc0..22b7513724 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/large_fern.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/large_fern.json @@ -16,9 +16,7 @@ "offsetY": 1, "predicate": { "block": { - "blocks": [ - "minecraft:large_fern" - ], + "blocks": "minecraft:large_fern", "state": { "half": "upper" } @@ -80,9 +78,7 @@ "offsetY": -1, "predicate": { "block": { - "blocks": [ - "minecraft:large_fern" - ], + "blocks": "minecraft:large_fern", "state": { "half": "lower" } diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/mangrove_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/mangrove_leaves.json index e56c3076a5..0e11a3e235 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/mangrove_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/mangrove_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/oak_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/oak_leaves.json index 717ec11f11..08e95aa5db 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/oak_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/oak_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -138,14 +142,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/spruce_leaves.json b/src/main/generated/data/minecraft/loot_tables/blocks/spruce_leaves.json index e785827530..cc8beff636 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/spruce_leaves.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/spruce_leaves.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] @@ -74,14 +76,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/tall_grass.json b/src/main/generated/data/minecraft/loot_tables/blocks/tall_grass.json index 4e8e3e559a..4391e321ef 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/tall_grass.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/tall_grass.json @@ -16,9 +16,7 @@ "offsetY": 1, "predicate": { "block": { - "blocks": [ - "minecraft:tall_grass" - ], + "blocks": "minecraft:tall_grass", "state": { "half": "upper" } @@ -80,9 +78,7 @@ "offsetY": -1, "predicate": { "block": { - "blocks": [ - "minecraft:tall_grass" - ], + "blocks": "minecraft:tall_grass", "state": { "half": "lower" } diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/twisting_vines.json b/src/main/generated/data/minecraft/loot_tables/blocks/twisting_vines.json index 3506f8ffdf..cec38305ba 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/twisting_vines.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/twisting_vines.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/loot_tables/blocks/weeping_vines.json b/src/main/generated/data/minecraft/loot_tables/blocks/weeping_vines.json index 0911910d8f..f3ed202e5e 100644 --- a/src/main/generated/data/minecraft/loot_tables/blocks/weeping_vines.json +++ b/src/main/generated/data/minecraft/loot_tables/blocks/weeping_vines.json @@ -20,14 +20,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "minecraft:silk_touch", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "minecraft:silk_touch", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/main/generated/data/minecraft/recipes/acacia_chest_boat.json b/src/main/generated/data/minecraft/recipes/acacia_chest_boat.json index f20818e69a..5fd961adc7 100644 --- a/src/main/generated/data/minecraft/recipes/acacia_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/acacia_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:acacia_chest_boat" + "count": 1, + "id": "minecraft:acacia_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/acacia_fence.json b/src/main/generated/data/minecraft/recipes/acacia_fence.json index d545c439a6..703625a37e 100644 --- a/src/main/generated/data/minecraft/recipes/acacia_fence.json +++ b/src/main/generated/data/minecraft/recipes/acacia_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:acacia_fence" + "id": "minecraft:acacia_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/acacia_fence_gate.json b/src/main/generated/data/minecraft/recipes/acacia_fence_gate.json index 027948967b..68a5ec59f1 100644 --- a/src/main/generated/data/minecraft/recipes/acacia_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/acacia_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:acacia_fence_gate" + "count": 1, + "id": "minecraft:acacia_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/acacia_sign.json b/src/main/generated/data/minecraft/recipes/acacia_sign.json index ab7495d12d..374bc7a676 100644 --- a/src/main/generated/data/minecraft/recipes/acacia_sign.json +++ b/src/main/generated/data/minecraft/recipes/acacia_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:acacia_sign" + "id": "minecraft:acacia_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/activator_rail.json b/src/main/generated/data/minecraft/recipes/activator_rail.json index 9f682df753..53b3dde6a0 100644 --- a/src/main/generated/data/minecraft/recipes/activator_rail.json +++ b/src/main/generated/data/minecraft/recipes/activator_rail.json @@ -19,6 +19,6 @@ ], "result": { "count": 6, - "item": "minecraft:activator_rail" + "id": "minecraft:activator_rail" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/andesite.json b/src/main/generated/data/minecraft/recipes/andesite.json index 4f70b2cea2..7e79c6d520 100644 --- a/src/main/generated/data/minecraft/recipes/andesite.json +++ b/src/main/generated/data/minecraft/recipes/andesite.json @@ -11,6 +11,6 @@ ], "result": { "count": 2, - "item": "minecraft:andesite" + "id": "minecraft:andesite" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/anvil.json b/src/main/generated/data/minecraft/recipes/anvil.json index 33203f2d58..309ede352d 100644 --- a/src/main/generated/data/minecraft/recipes/anvil.json +++ b/src/main/generated/data/minecraft/recipes/anvil.json @@ -15,6 +15,7 @@ "iii" ], "result": { - "item": "minecraft:anvil" + "count": 1, + "id": "minecraft:anvil" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/armor_stand.json b/src/main/generated/data/minecraft/recipes/armor_stand.json index 54da4b9a02..d902e13f9e 100644 --- a/src/main/generated/data/minecraft/recipes/armor_stand.json +++ b/src/main/generated/data/minecraft/recipes/armor_stand.json @@ -15,6 +15,7 @@ "/_/" ], "result": { - "item": "minecraft:armor_stand" + "count": 1, + "id": "minecraft:armor_stand" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/arrow.json b/src/main/generated/data/minecraft/recipes/arrow.json index c4eba0d814..94ac427382 100644 --- a/src/main/generated/data/minecraft/recipes/arrow.json +++ b/src/main/generated/data/minecraft/recipes/arrow.json @@ -19,6 +19,6 @@ ], "result": { "count": 4, - "item": "minecraft:arrow" + "id": "minecraft:arrow" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bamboo_chest_raft.json b/src/main/generated/data/minecraft/recipes/bamboo_chest_raft.json index b602612c1b..7622276dbe 100644 --- a/src/main/generated/data/minecraft/recipes/bamboo_chest_raft.json +++ b/src/main/generated/data/minecraft/recipes/bamboo_chest_raft.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:bamboo_chest_raft" + "count": 1, + "id": "minecraft:bamboo_chest_raft" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bamboo_fence.json b/src/main/generated/data/minecraft/recipes/bamboo_fence.json index 94bfe53d33..171403e8c5 100644 --- a/src/main/generated/data/minecraft/recipes/bamboo_fence.json +++ b/src/main/generated/data/minecraft/recipes/bamboo_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:bamboo_fence" + "id": "minecraft:bamboo_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bamboo_fence_gate.json b/src/main/generated/data/minecraft/recipes/bamboo_fence_gate.json index 23fdba6fe7..8effebacef 100644 --- a/src/main/generated/data/minecraft/recipes/bamboo_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/bamboo_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:bamboo_fence_gate" + "count": 1, + "id": "minecraft:bamboo_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bamboo_sign.json b/src/main/generated/data/minecraft/recipes/bamboo_sign.json index 1c78cf6ddb..886608f9d2 100644 --- a/src/main/generated/data/minecraft/recipes/bamboo_sign.json +++ b/src/main/generated/data/minecraft/recipes/bamboo_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:bamboo_sign" + "id": "minecraft:bamboo_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/birch_chest_boat.json b/src/main/generated/data/minecraft/recipes/birch_chest_boat.json index 7fe3c649ab..6dfbb297f9 100644 --- a/src/main/generated/data/minecraft/recipes/birch_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/birch_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:birch_chest_boat" + "count": 1, + "id": "minecraft:birch_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/birch_fence.json b/src/main/generated/data/minecraft/recipes/birch_fence.json index 170c1c2520..d8237d2cac 100644 --- a/src/main/generated/data/minecraft/recipes/birch_fence.json +++ b/src/main/generated/data/minecraft/recipes/birch_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:birch_fence" + "id": "minecraft:birch_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/birch_fence_gate.json b/src/main/generated/data/minecraft/recipes/birch_fence_gate.json index 325773a2eb..1fb9a55a35 100644 --- a/src/main/generated/data/minecraft/recipes/birch_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/birch_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:birch_fence_gate" + "count": 1, + "id": "minecraft:birch_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/birch_sign.json b/src/main/generated/data/minecraft/recipes/birch_sign.json index 7a98a35feb..7ed02f64d4 100644 --- a/src/main/generated/data/minecraft/recipes/birch_sign.json +++ b/src/main/generated/data/minecraft/recipes/birch_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:birch_sign" + "id": "minecraft:birch_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/black_banner.json b/src/main/generated/data/minecraft/recipes/black_banner.json index 8f0a69aab4..c985e981fa 100644 --- a/src/main/generated/data/minecraft/recipes/black_banner.json +++ b/src/main/generated/data/minecraft/recipes/black_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:black_banner" + "count": 1, + "id": "minecraft:black_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/blast_furnace.json b/src/main/generated/data/minecraft/recipes/blast_furnace.json index 1c34a6149c..f6e082c3b9 100644 --- a/src/main/generated/data/minecraft/recipes/blast_furnace.json +++ b/src/main/generated/data/minecraft/recipes/blast_furnace.json @@ -18,6 +18,7 @@ "###" ], "result": { - "item": "minecraft:blast_furnace" + "count": 1, + "id": "minecraft:blast_furnace" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/blue_banner.json b/src/main/generated/data/minecraft/recipes/blue_banner.json index 2270bf926c..e635e9e4b7 100644 --- a/src/main/generated/data/minecraft/recipes/blue_banner.json +++ b/src/main/generated/data/minecraft/recipes/blue_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:blue_banner" + "count": 1, + "id": "minecraft:blue_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bow.json b/src/main/generated/data/minecraft/recipes/bow.json index 6148fed74c..bec8213e14 100644 --- a/src/main/generated/data/minecraft/recipes/bow.json +++ b/src/main/generated/data/minecraft/recipes/bow.json @@ -15,6 +15,7 @@ " #X" ], "result": { - "item": "minecraft:bow" + "count": 1, + "id": "minecraft:bow" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/brown_banner.json b/src/main/generated/data/minecraft/recipes/brown_banner.json index 71bb73f30a..62b1f8182a 100644 --- a/src/main/generated/data/minecraft/recipes/brown_banner.json +++ b/src/main/generated/data/minecraft/recipes/brown_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:brown_banner" + "count": 1, + "id": "minecraft:brown_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/brush.json b/src/main/generated/data/minecraft/recipes/brush.json index 3c5b69dabe..58ad243e4c 100644 --- a/src/main/generated/data/minecraft/recipes/brush.json +++ b/src/main/generated/data/minecraft/recipes/brush.json @@ -18,6 +18,7 @@ "I" ], "result": { - "item": "minecraft:brush" + "count": 1, + "id": "minecraft:brush" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/bucket.json b/src/main/generated/data/minecraft/recipes/bucket.json index 22912ba151..24775d35ea 100644 --- a/src/main/generated/data/minecraft/recipes/bucket.json +++ b/src/main/generated/data/minecraft/recipes/bucket.json @@ -11,6 +11,7 @@ " # " ], "result": { - "item": "minecraft:bucket" + "count": 1, + "id": "minecraft:bucket" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/calibrated_sculk_sensor.json b/src/main/generated/data/minecraft/recipes/calibrated_sculk_sensor.json index e71178e156..604e3775cb 100644 --- a/src/main/generated/data/minecraft/recipes/calibrated_sculk_sensor.json +++ b/src/main/generated/data/minecraft/recipes/calibrated_sculk_sensor.json @@ -14,6 +14,7 @@ "#X#" ], "result": { - "item": "minecraft:calibrated_sculk_sensor" + "count": 1, + "id": "minecraft:calibrated_sculk_sensor" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/campfire.json b/src/main/generated/data/minecraft/recipes/campfire.json index d329eb4738..5926f49c1b 100644 --- a/src/main/generated/data/minecraft/recipes/campfire.json +++ b/src/main/generated/data/minecraft/recipes/campfire.json @@ -18,6 +18,7 @@ "LLL" ], "result": { - "item": "minecraft:campfire" + "count": 1, + "id": "minecraft:campfire" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/candle.json b/src/main/generated/data/minecraft/recipes/candle.json index add9d35c83..74497a1cbf 100644 --- a/src/main/generated/data/minecraft/recipes/candle.json +++ b/src/main/generated/data/minecraft/recipes/candle.json @@ -14,6 +14,7 @@ "H" ], "result": { - "item": "minecraft:candle" + "count": 1, + "id": "minecraft:candle" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cauldron.json b/src/main/generated/data/minecraft/recipes/cauldron.json index 982e8e6aa0..ff9f04b469 100644 --- a/src/main/generated/data/minecraft/recipes/cauldron.json +++ b/src/main/generated/data/minecraft/recipes/cauldron.json @@ -12,6 +12,7 @@ "###" ], "result": { - "item": "minecraft:cauldron" + "count": 1, + "id": "minecraft:cauldron" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/chain.json b/src/main/generated/data/minecraft/recipes/chain.json index 0834b8f1ae..35f853027d 100644 --- a/src/main/generated/data/minecraft/recipes/chain.json +++ b/src/main/generated/data/minecraft/recipes/chain.json @@ -15,6 +15,7 @@ "N" ], "result": { - "item": "minecraft:chain" + "count": 1, + "id": "minecraft:chain" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cherry_chest_boat.json b/src/main/generated/data/minecraft/recipes/cherry_chest_boat.json index c8e78832c6..4a97b67070 100644 --- a/src/main/generated/data/minecraft/recipes/cherry_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/cherry_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:cherry_chest_boat" + "count": 1, + "id": "minecraft:cherry_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cherry_fence.json b/src/main/generated/data/minecraft/recipes/cherry_fence.json index 7dd13ae3ac..33785d0974 100644 --- a/src/main/generated/data/minecraft/recipes/cherry_fence.json +++ b/src/main/generated/data/minecraft/recipes/cherry_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:cherry_fence" + "id": "minecraft:cherry_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cherry_fence_gate.json b/src/main/generated/data/minecraft/recipes/cherry_fence_gate.json index 5d4ed45afc..39f103640d 100644 --- a/src/main/generated/data/minecraft/recipes/cherry_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/cherry_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:cherry_fence_gate" + "count": 1, + "id": "minecraft:cherry_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cherry_sign.json b/src/main/generated/data/minecraft/recipes/cherry_sign.json index 091031dca4..80b8c6ee23 100644 --- a/src/main/generated/data/minecraft/recipes/cherry_sign.json +++ b/src/main/generated/data/minecraft/recipes/cherry_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:cherry_sign" + "id": "minecraft:cherry_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/chest_minecart.json b/src/main/generated/data/minecraft/recipes/chest_minecart.json index 99c7780621..c05cc49207 100644 --- a/src/main/generated/data/minecraft/recipes/chest_minecart.json +++ b/src/main/generated/data/minecraft/recipes/chest_minecart.json @@ -10,6 +10,7 @@ } ], "result": { - "item": "minecraft:chest_minecart" + "count": 1, + "id": "minecraft:chest_minecart" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/clock.json b/src/main/generated/data/minecraft/recipes/clock.json index 31e02ad116..72012b9797 100644 --- a/src/main/generated/data/minecraft/recipes/clock.json +++ b/src/main/generated/data/minecraft/recipes/clock.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:clock" + "count": 1, + "id": "minecraft:clock" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/coast_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/coast_armor_trim_smithing_template.json index 1389c117ea..181489696b 100644 --- a/src/main/generated/data/minecraft/recipes/coast_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/coast_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:coast_armor_trim_smithing_template" + "id": "minecraft:coast_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/compass.json b/src/main/generated/data/minecraft/recipes/compass.json index f1b6226133..2b51feb2ac 100644 --- a/src/main/generated/data/minecraft/recipes/compass.json +++ b/src/main/generated/data/minecraft/recipes/compass.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:compass" + "count": 1, + "id": "minecraft:compass" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/crimson_fence.json b/src/main/generated/data/minecraft/recipes/crimson_fence.json index fd4c99174e..0221149187 100644 --- a/src/main/generated/data/minecraft/recipes/crimson_fence.json +++ b/src/main/generated/data/minecraft/recipes/crimson_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:crimson_fence" + "id": "minecraft:crimson_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/crimson_fence_gate.json b/src/main/generated/data/minecraft/recipes/crimson_fence_gate.json index b8d6cb88dd..d48c0cdb26 100644 --- a/src/main/generated/data/minecraft/recipes/crimson_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/crimson_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:crimson_fence_gate" + "count": 1, + "id": "minecraft:crimson_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/crimson_sign.json b/src/main/generated/data/minecraft/recipes/crimson_sign.json index 2d26330c3d..f3601e46fd 100644 --- a/src/main/generated/data/minecraft/recipes/crimson_sign.json +++ b/src/main/generated/data/minecraft/recipes/crimson_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:crimson_sign" + "id": "minecraft:crimson_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/crossbow.json b/src/main/generated/data/minecraft/recipes/crossbow.json index bfacf24beb..67c055e31b 100644 --- a/src/main/generated/data/minecraft/recipes/crossbow.json +++ b/src/main/generated/data/minecraft/recipes/crossbow.json @@ -21,6 +21,7 @@ " # " ], "result": { - "item": "minecraft:crossbow" + "count": 1, + "id": "minecraft:crossbow" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/cyan_banner.json b/src/main/generated/data/minecraft/recipes/cyan_banner.json index 2eae740c43..182eeb1b4f 100644 --- a/src/main/generated/data/minecraft/recipes/cyan_banner.json +++ b/src/main/generated/data/minecraft/recipes/cyan_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:cyan_banner" + "count": 1, + "id": "minecraft:cyan_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dark_oak_chest_boat.json b/src/main/generated/data/minecraft/recipes/dark_oak_chest_boat.json index 783c44a9fc..91e1cb56f0 100644 --- a/src/main/generated/data/minecraft/recipes/dark_oak_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/dark_oak_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:dark_oak_chest_boat" + "count": 1, + "id": "minecraft:dark_oak_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dark_oak_fence.json b/src/main/generated/data/minecraft/recipes/dark_oak_fence.json index f25b7a205a..5dd6fe5251 100644 --- a/src/main/generated/data/minecraft/recipes/dark_oak_fence.json +++ b/src/main/generated/data/minecraft/recipes/dark_oak_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:dark_oak_fence" + "id": "minecraft:dark_oak_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dark_oak_fence_gate.json b/src/main/generated/data/minecraft/recipes/dark_oak_fence_gate.json index 53d878a102..3176272821 100644 --- a/src/main/generated/data/minecraft/recipes/dark_oak_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/dark_oak_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:dark_oak_fence_gate" + "count": 1, + "id": "minecraft:dark_oak_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dark_oak_sign.json b/src/main/generated/data/minecraft/recipes/dark_oak_sign.json index 286e275709..5bf030e3cc 100644 --- a/src/main/generated/data/minecraft/recipes/dark_oak_sign.json +++ b/src/main/generated/data/minecraft/recipes/dark_oak_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:dark_oak_sign" + "id": "minecraft:dark_oak_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/detector_rail.json b/src/main/generated/data/minecraft/recipes/detector_rail.json index ddafa7ab5b..404b89b4b2 100644 --- a/src/main/generated/data/minecraft/recipes/detector_rail.json +++ b/src/main/generated/data/minecraft/recipes/detector_rail.json @@ -19,6 +19,6 @@ ], "result": { "count": 6, - "item": "minecraft:detector_rail" + "id": "minecraft:detector_rail" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_axe.json b/src/main/generated/data/minecraft/recipes/diamond_axe.json index fa33917a09..fe7138e260 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_axe.json +++ b/src/main/generated/data/minecraft/recipes/diamond_axe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:diamond_axe" + "count": 1, + "id": "minecraft:diamond_axe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_boots.json b/src/main/generated/data/minecraft/recipes/diamond_boots.json index 0ab7eb99fe..666fd9f64e 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_boots.json +++ b/src/main/generated/data/minecraft/recipes/diamond_boots.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:diamond_boots" + "count": 1, + "id": "minecraft:diamond_boots" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_chestplate.json b/src/main/generated/data/minecraft/recipes/diamond_chestplate.json index 1cd18f4c75..c591e77abd 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_chestplate.json +++ b/src/main/generated/data/minecraft/recipes/diamond_chestplate.json @@ -12,6 +12,7 @@ "XXX" ], "result": { - "item": "minecraft:diamond_chestplate" + "count": 1, + "id": "minecraft:diamond_chestplate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_helmet.json b/src/main/generated/data/minecraft/recipes/diamond_helmet.json index 9671c540d3..5e1275ac7f 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_helmet.json +++ b/src/main/generated/data/minecraft/recipes/diamond_helmet.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:diamond_helmet" + "count": 1, + "id": "minecraft:diamond_helmet" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_hoe.json b/src/main/generated/data/minecraft/recipes/diamond_hoe.json index ccd0e48768..221b7feef1 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_hoe.json +++ b/src/main/generated/data/minecraft/recipes/diamond_hoe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:diamond_hoe" + "count": 1, + "id": "minecraft:diamond_hoe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_leggings.json b/src/main/generated/data/minecraft/recipes/diamond_leggings.json index f9cbdcd738..4d8aaf1b90 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_leggings.json +++ b/src/main/generated/data/minecraft/recipes/diamond_leggings.json @@ -12,6 +12,7 @@ "X X" ], "result": { - "item": "minecraft:diamond_leggings" + "count": 1, + "id": "minecraft:diamond_leggings" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_pickaxe.json b/src/main/generated/data/minecraft/recipes/diamond_pickaxe.json index affd0a3083..64d7a3aa1e 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_pickaxe.json +++ b/src/main/generated/data/minecraft/recipes/diamond_pickaxe.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:diamond_pickaxe" + "count": 1, + "id": "minecraft:diamond_pickaxe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_shovel.json b/src/main/generated/data/minecraft/recipes/diamond_shovel.json index cb8282be2c..b900245b8d 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_shovel.json +++ b/src/main/generated/data/minecraft/recipes/diamond_shovel.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:diamond_shovel" + "count": 1, + "id": "minecraft:diamond_shovel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diamond_sword.json b/src/main/generated/data/minecraft/recipes/diamond_sword.json index de7b7d161b..775f8970e9 100644 --- a/src/main/generated/data/minecraft/recipes/diamond_sword.json +++ b/src/main/generated/data/minecraft/recipes/diamond_sword.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:diamond_sword" + "count": 1, + "id": "minecraft:diamond_sword" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/diorite.json b/src/main/generated/data/minecraft/recipes/diorite.json index 6dfb532dcf..94624af531 100644 --- a/src/main/generated/data/minecraft/recipes/diorite.json +++ b/src/main/generated/data/minecraft/recipes/diorite.json @@ -15,6 +15,6 @@ ], "result": { "count": 2, - "item": "minecraft:diorite" + "id": "minecraft:diorite" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dispenser.json b/src/main/generated/data/minecraft/recipes/dispenser.json index 20076eae31..2b6bdb4d0d 100644 --- a/src/main/generated/data/minecraft/recipes/dispenser.json +++ b/src/main/generated/data/minecraft/recipes/dispenser.json @@ -18,6 +18,7 @@ "#R#" ], "result": { - "item": "minecraft:dispenser" + "count": 1, + "id": "minecraft:dispenser" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dropper.json b/src/main/generated/data/minecraft/recipes/dropper.json index 76c51a4fa6..79fb49ce4d 100644 --- a/src/main/generated/data/minecraft/recipes/dropper.json +++ b/src/main/generated/data/minecraft/recipes/dropper.json @@ -15,6 +15,7 @@ "#R#" ], "result": { - "item": "minecraft:dropper" + "count": 1, + "id": "minecraft:dropper" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/dune_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/dune_armor_trim_smithing_template.json index f115d552d8..6beacb0184 100644 --- a/src/main/generated/data/minecraft/recipes/dune_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/dune_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:dune_armor_trim_smithing_template" + "id": "minecraft:dune_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/enchanting_table.json b/src/main/generated/data/minecraft/recipes/enchanting_table.json index a238995fb9..c61097cb80 100644 --- a/src/main/generated/data/minecraft/recipes/enchanting_table.json +++ b/src/main/generated/data/minecraft/recipes/enchanting_table.json @@ -18,6 +18,7 @@ "###" ], "result": { - "item": "minecraft:enchanting_table" + "count": 1, + "id": "minecraft:enchanting_table" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/eye_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/eye_armor_trim_smithing_template.json index 8b4a3fd515..6c50da8466 100644 --- a/src/main/generated/data/minecraft/recipes/eye_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/eye_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:eye_armor_trim_smithing_template" + "id": "minecraft:eye_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/fishing_rod.json b/src/main/generated/data/minecraft/recipes/fishing_rod.json index 8d6a571149..2ad4deb283 100644 --- a/src/main/generated/data/minecraft/recipes/fishing_rod.json +++ b/src/main/generated/data/minecraft/recipes/fishing_rod.json @@ -15,6 +15,7 @@ "# X" ], "result": { - "item": "minecraft:fishing_rod" + "count": 1, + "id": "minecraft:fishing_rod" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/flint_and_steel.json b/src/main/generated/data/minecraft/recipes/flint_and_steel.json index 7181ac5d08..1f5287d743 100644 --- a/src/main/generated/data/minecraft/recipes/flint_and_steel.json +++ b/src/main/generated/data/minecraft/recipes/flint_and_steel.json @@ -10,6 +10,7 @@ } ], "result": { - "item": "minecraft:flint_and_steel" + "count": 1, + "id": "minecraft:flint_and_steel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_apple.json b/src/main/generated/data/minecraft/recipes/golden_apple.json index 674bf883d3..fb31a6440d 100644 --- a/src/main/generated/data/minecraft/recipes/golden_apple.json +++ b/src/main/generated/data/minecraft/recipes/golden_apple.json @@ -15,6 +15,7 @@ "###" ], "result": { - "item": "minecraft:golden_apple" + "count": 1, + "id": "minecraft:golden_apple" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_axe.json b/src/main/generated/data/minecraft/recipes/golden_axe.json index 4811c860ad..a11290c050 100644 --- a/src/main/generated/data/minecraft/recipes/golden_axe.json +++ b/src/main/generated/data/minecraft/recipes/golden_axe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:golden_axe" + "count": 1, + "id": "minecraft:golden_axe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_boots.json b/src/main/generated/data/minecraft/recipes/golden_boots.json index d5e15bc24f..239bb244ce 100644 --- a/src/main/generated/data/minecraft/recipes/golden_boots.json +++ b/src/main/generated/data/minecraft/recipes/golden_boots.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:golden_boots" + "count": 1, + "id": "minecraft:golden_boots" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_chestplate.json b/src/main/generated/data/minecraft/recipes/golden_chestplate.json index a06e7c25eb..515f55100a 100644 --- a/src/main/generated/data/minecraft/recipes/golden_chestplate.json +++ b/src/main/generated/data/minecraft/recipes/golden_chestplate.json @@ -12,6 +12,7 @@ "XXX" ], "result": { - "item": "minecraft:golden_chestplate" + "count": 1, + "id": "minecraft:golden_chestplate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_helmet.json b/src/main/generated/data/minecraft/recipes/golden_helmet.json index 2161b20de7..15c8788a47 100644 --- a/src/main/generated/data/minecraft/recipes/golden_helmet.json +++ b/src/main/generated/data/minecraft/recipes/golden_helmet.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:golden_helmet" + "count": 1, + "id": "minecraft:golden_helmet" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_hoe.json b/src/main/generated/data/minecraft/recipes/golden_hoe.json index 9626f019d7..1d8de6dbb2 100644 --- a/src/main/generated/data/minecraft/recipes/golden_hoe.json +++ b/src/main/generated/data/minecraft/recipes/golden_hoe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:golden_hoe" + "count": 1, + "id": "minecraft:golden_hoe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_leggings.json b/src/main/generated/data/minecraft/recipes/golden_leggings.json index a377fbc982..64d4400810 100644 --- a/src/main/generated/data/minecraft/recipes/golden_leggings.json +++ b/src/main/generated/data/minecraft/recipes/golden_leggings.json @@ -12,6 +12,7 @@ "X X" ], "result": { - "item": "minecraft:golden_leggings" + "count": 1, + "id": "minecraft:golden_leggings" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_pickaxe.json b/src/main/generated/data/minecraft/recipes/golden_pickaxe.json index b953212ba9..073fca2609 100644 --- a/src/main/generated/data/minecraft/recipes/golden_pickaxe.json +++ b/src/main/generated/data/minecraft/recipes/golden_pickaxe.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:golden_pickaxe" + "count": 1, + "id": "minecraft:golden_pickaxe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_shovel.json b/src/main/generated/data/minecraft/recipes/golden_shovel.json index 5e4bbd536c..207db046c2 100644 --- a/src/main/generated/data/minecraft/recipes/golden_shovel.json +++ b/src/main/generated/data/minecraft/recipes/golden_shovel.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:golden_shovel" + "count": 1, + "id": "minecraft:golden_shovel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/golden_sword.json b/src/main/generated/data/minecraft/recipes/golden_sword.json index c237f1afa5..bf3cb69d90 100644 --- a/src/main/generated/data/minecraft/recipes/golden_sword.json +++ b/src/main/generated/data/minecraft/recipes/golden_sword.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:golden_sword" + "count": 1, + "id": "minecraft:golden_sword" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/gray_banner.json b/src/main/generated/data/minecraft/recipes/gray_banner.json index 3a0bb04ef4..e31c6e3953 100644 --- a/src/main/generated/data/minecraft/recipes/gray_banner.json +++ b/src/main/generated/data/minecraft/recipes/gray_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:gray_banner" + "count": 1, + "id": "minecraft:gray_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/green_banner.json b/src/main/generated/data/minecraft/recipes/green_banner.json index 000083bcf5..9d60eec45d 100644 --- a/src/main/generated/data/minecraft/recipes/green_banner.json +++ b/src/main/generated/data/minecraft/recipes/green_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:green_banner" + "count": 1, + "id": "minecraft:green_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/grindstone.json b/src/main/generated/data/minecraft/recipes/grindstone.json index beb54f35ee..447414e0db 100644 --- a/src/main/generated/data/minecraft/recipes/grindstone.json +++ b/src/main/generated/data/minecraft/recipes/grindstone.json @@ -17,6 +17,7 @@ "# #" ], "result": { - "item": "minecraft:grindstone" + "count": 1, + "id": "minecraft:grindstone" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/heavy_weighted_pressure_plate.json b/src/main/generated/data/minecraft/recipes/heavy_weighted_pressure_plate.json index 1ffbcccce9..655f73eea7 100644 --- a/src/main/generated/data/minecraft/recipes/heavy_weighted_pressure_plate.json +++ b/src/main/generated/data/minecraft/recipes/heavy_weighted_pressure_plate.json @@ -10,6 +10,7 @@ "##" ], "result": { - "item": "minecraft:heavy_weighted_pressure_plate" + "count": 1, + "id": "minecraft:heavy_weighted_pressure_plate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/hopper.json b/src/main/generated/data/minecraft/recipes/hopper.json index 31bff00da6..927b1a67e7 100644 --- a/src/main/generated/data/minecraft/recipes/hopper.json +++ b/src/main/generated/data/minecraft/recipes/hopper.json @@ -15,6 +15,7 @@ " I " ], "result": { - "item": "minecraft:hopper" + "count": 1, + "id": "minecraft:hopper" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/host_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/host_armor_trim_smithing_template.json index 12343eb0d6..04403fefd1 100644 --- a/src/main/generated/data/minecraft/recipes/host_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/host_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:host_armor_trim_smithing_template" + "id": "minecraft:host_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_axe.json b/src/main/generated/data/minecraft/recipes/iron_axe.json index 09ad3b86e2..201f97fa81 100644 --- a/src/main/generated/data/minecraft/recipes/iron_axe.json +++ b/src/main/generated/data/minecraft/recipes/iron_axe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:iron_axe" + "count": 1, + "id": "minecraft:iron_axe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_bars.json b/src/main/generated/data/minecraft/recipes/iron_bars.json index 37a55f1b4d..fcff6a22c6 100644 --- a/src/main/generated/data/minecraft/recipes/iron_bars.json +++ b/src/main/generated/data/minecraft/recipes/iron_bars.json @@ -12,6 +12,6 @@ ], "result": { "count": 16, - "item": "minecraft:iron_bars" + "id": "minecraft:iron_bars" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_boots.json b/src/main/generated/data/minecraft/recipes/iron_boots.json index a5b13c1270..41355032dd 100644 --- a/src/main/generated/data/minecraft/recipes/iron_boots.json +++ b/src/main/generated/data/minecraft/recipes/iron_boots.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:iron_boots" + "count": 1, + "id": "minecraft:iron_boots" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_chestplate.json b/src/main/generated/data/minecraft/recipes/iron_chestplate.json index c22d896eca..3356b627ca 100644 --- a/src/main/generated/data/minecraft/recipes/iron_chestplate.json +++ b/src/main/generated/data/minecraft/recipes/iron_chestplate.json @@ -12,6 +12,7 @@ "XXX" ], "result": { - "item": "minecraft:iron_chestplate" + "count": 1, + "id": "minecraft:iron_chestplate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_door.json b/src/main/generated/data/minecraft/recipes/iron_door.json index f138c8898a..889e015b2c 100644 --- a/src/main/generated/data/minecraft/recipes/iron_door.json +++ b/src/main/generated/data/minecraft/recipes/iron_door.json @@ -13,6 +13,6 @@ ], "result": { "count": 3, - "item": "minecraft:iron_door" + "id": "minecraft:iron_door" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_helmet.json b/src/main/generated/data/minecraft/recipes/iron_helmet.json index fc376406b6..843d002ee0 100644 --- a/src/main/generated/data/minecraft/recipes/iron_helmet.json +++ b/src/main/generated/data/minecraft/recipes/iron_helmet.json @@ -11,6 +11,7 @@ "X X" ], "result": { - "item": "minecraft:iron_helmet" + "count": 1, + "id": "minecraft:iron_helmet" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_hoe.json b/src/main/generated/data/minecraft/recipes/iron_hoe.json index d9ddbbf1a5..770f5d335f 100644 --- a/src/main/generated/data/minecraft/recipes/iron_hoe.json +++ b/src/main/generated/data/minecraft/recipes/iron_hoe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:iron_hoe" + "count": 1, + "id": "minecraft:iron_hoe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_leggings.json b/src/main/generated/data/minecraft/recipes/iron_leggings.json index 9249dfa36e..ef619451a2 100644 --- a/src/main/generated/data/minecraft/recipes/iron_leggings.json +++ b/src/main/generated/data/minecraft/recipes/iron_leggings.json @@ -12,6 +12,7 @@ "X X" ], "result": { - "item": "minecraft:iron_leggings" + "count": 1, + "id": "minecraft:iron_leggings" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_pickaxe.json b/src/main/generated/data/minecraft/recipes/iron_pickaxe.json index 381e76055b..69e5633c9b 100644 --- a/src/main/generated/data/minecraft/recipes/iron_pickaxe.json +++ b/src/main/generated/data/minecraft/recipes/iron_pickaxe.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:iron_pickaxe" + "count": 1, + "id": "minecraft:iron_pickaxe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_shovel.json b/src/main/generated/data/minecraft/recipes/iron_shovel.json index fa186c42f6..4a2fa9c256 100644 --- a/src/main/generated/data/minecraft/recipes/iron_shovel.json +++ b/src/main/generated/data/minecraft/recipes/iron_shovel.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:iron_shovel" + "count": 1, + "id": "minecraft:iron_shovel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_sword.json b/src/main/generated/data/minecraft/recipes/iron_sword.json index d1b1fa9ff4..4ad561140d 100644 --- a/src/main/generated/data/minecraft/recipes/iron_sword.json +++ b/src/main/generated/data/minecraft/recipes/iron_sword.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:iron_sword" + "count": 1, + "id": "minecraft:iron_sword" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/iron_trapdoor.json b/src/main/generated/data/minecraft/recipes/iron_trapdoor.json index 71777b8ca6..444aee2d6a 100644 --- a/src/main/generated/data/minecraft/recipes/iron_trapdoor.json +++ b/src/main/generated/data/minecraft/recipes/iron_trapdoor.json @@ -11,6 +11,7 @@ "##" ], "result": { - "item": "minecraft:iron_trapdoor" + "count": 1, + "id": "minecraft:iron_trapdoor" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/item_frame.json b/src/main/generated/data/minecraft/recipes/item_frame.json index 7383dc21ac..c0daade8a4 100644 --- a/src/main/generated/data/minecraft/recipes/item_frame.json +++ b/src/main/generated/data/minecraft/recipes/item_frame.json @@ -15,6 +15,7 @@ "###" ], "result": { - "item": "minecraft:item_frame" + "count": 1, + "id": "minecraft:item_frame" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/jukebox.json b/src/main/generated/data/minecraft/recipes/jukebox.json index 23851e3783..ae7df738d3 100644 --- a/src/main/generated/data/minecraft/recipes/jukebox.json +++ b/src/main/generated/data/minecraft/recipes/jukebox.json @@ -15,6 +15,7 @@ "###" ], "result": { - "item": "minecraft:jukebox" + "count": 1, + "id": "minecraft:jukebox" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/jungle_chest_boat.json b/src/main/generated/data/minecraft/recipes/jungle_chest_boat.json index 3d03d82aae..4a783b554d 100644 --- a/src/main/generated/data/minecraft/recipes/jungle_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/jungle_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:jungle_chest_boat" + "count": 1, + "id": "minecraft:jungle_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/jungle_fence.json b/src/main/generated/data/minecraft/recipes/jungle_fence.json index 28ab3e0b5b..2de11023a4 100644 --- a/src/main/generated/data/minecraft/recipes/jungle_fence.json +++ b/src/main/generated/data/minecraft/recipes/jungle_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:jungle_fence" + "id": "minecraft:jungle_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/jungle_fence_gate.json b/src/main/generated/data/minecraft/recipes/jungle_fence_gate.json index eeb195ecbe..fbfd10f333 100644 --- a/src/main/generated/data/minecraft/recipes/jungle_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/jungle_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:jungle_fence_gate" + "count": 1, + "id": "minecraft:jungle_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/jungle_sign.json b/src/main/generated/data/minecraft/recipes/jungle_sign.json index 5c14ff95ef..824fd4cfac 100644 --- a/src/main/generated/data/minecraft/recipes/jungle_sign.json +++ b/src/main/generated/data/minecraft/recipes/jungle_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:jungle_sign" + "id": "minecraft:jungle_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/ladder.json b/src/main/generated/data/minecraft/recipes/ladder.json index 50326bf053..db2a2e4a4d 100644 --- a/src/main/generated/data/minecraft/recipes/ladder.json +++ b/src/main/generated/data/minecraft/recipes/ladder.json @@ -13,6 +13,6 @@ ], "result": { "count": 3, - "item": "minecraft:ladder" + "id": "minecraft:ladder" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/lead.json b/src/main/generated/data/minecraft/recipes/lead.json index 56fcc01256..eac3ce67ab 100644 --- a/src/main/generated/data/minecraft/recipes/lead.json +++ b/src/main/generated/data/minecraft/recipes/lead.json @@ -16,6 +16,6 @@ ], "result": { "count": 2, - "item": "minecraft:lead" + "id": "minecraft:lead" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/lever.json b/src/main/generated/data/minecraft/recipes/lever.json index 23666a3173..163ffc6659 100644 --- a/src/main/generated/data/minecraft/recipes/lever.json +++ b/src/main/generated/data/minecraft/recipes/lever.json @@ -14,6 +14,7 @@ "#" ], "result": { - "item": "minecraft:lever" + "count": 1, + "id": "minecraft:lever" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/light_blue_banner.json b/src/main/generated/data/minecraft/recipes/light_blue_banner.json index 2f7d401abc..867c279872 100644 --- a/src/main/generated/data/minecraft/recipes/light_blue_banner.json +++ b/src/main/generated/data/minecraft/recipes/light_blue_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:light_blue_banner" + "count": 1, + "id": "minecraft:light_blue_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/light_gray_banner.json b/src/main/generated/data/minecraft/recipes/light_gray_banner.json index 0564f26f74..23e5a8d215 100644 --- a/src/main/generated/data/minecraft/recipes/light_gray_banner.json +++ b/src/main/generated/data/minecraft/recipes/light_gray_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:light_gray_banner" + "count": 1, + "id": "minecraft:light_gray_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/light_weighted_pressure_plate.json b/src/main/generated/data/minecraft/recipes/light_weighted_pressure_plate.json index 8c0044b28c..2f4d1f2f2a 100644 --- a/src/main/generated/data/minecraft/recipes/light_weighted_pressure_plate.json +++ b/src/main/generated/data/minecraft/recipes/light_weighted_pressure_plate.json @@ -10,6 +10,7 @@ "##" ], "result": { - "item": "minecraft:light_weighted_pressure_plate" + "count": 1, + "id": "minecraft:light_weighted_pressure_plate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/lightning_rod.json b/src/main/generated/data/minecraft/recipes/lightning_rod.json index 8d1a5eca19..088f10d61e 100644 --- a/src/main/generated/data/minecraft/recipes/lightning_rod.json +++ b/src/main/generated/data/minecraft/recipes/lightning_rod.json @@ -12,6 +12,7 @@ "#" ], "result": { - "item": "minecraft:lightning_rod" + "count": 1, + "id": "minecraft:lightning_rod" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/lime_banner.json b/src/main/generated/data/minecraft/recipes/lime_banner.json index 603a2a1ae2..59396857ad 100644 --- a/src/main/generated/data/minecraft/recipes/lime_banner.json +++ b/src/main/generated/data/minecraft/recipes/lime_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:lime_banner" + "count": 1, + "id": "minecraft:lime_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/lodestone.json b/src/main/generated/data/minecraft/recipes/lodestone.json index 8741c3f76e..269a87350b 100644 --- a/src/main/generated/data/minecraft/recipes/lodestone.json +++ b/src/main/generated/data/minecraft/recipes/lodestone.json @@ -15,6 +15,7 @@ "SSS" ], "result": { - "item": "minecraft:lodestone" + "count": 1, + "id": "minecraft:lodestone" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/loom.json b/src/main/generated/data/minecraft/recipes/loom.json index 2893af442a..1ac1072eb5 100644 --- a/src/main/generated/data/minecraft/recipes/loom.json +++ b/src/main/generated/data/minecraft/recipes/loom.json @@ -14,6 +14,7 @@ "##" ], "result": { - "item": "minecraft:loom" + "count": 1, + "id": "minecraft:loom" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/magenta_banner.json b/src/main/generated/data/minecraft/recipes/magenta_banner.json index 5b02fea383..549b5fbad5 100644 --- a/src/main/generated/data/minecraft/recipes/magenta_banner.json +++ b/src/main/generated/data/minecraft/recipes/magenta_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:magenta_banner" + "count": 1, + "id": "minecraft:magenta_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mangrove_chest_boat.json b/src/main/generated/data/minecraft/recipes/mangrove_chest_boat.json index ef18815307..7c8a0afb6a 100644 --- a/src/main/generated/data/minecraft/recipes/mangrove_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/mangrove_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:mangrove_chest_boat" + "count": 1, + "id": "minecraft:mangrove_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mangrove_fence.json b/src/main/generated/data/minecraft/recipes/mangrove_fence.json index a799b071ac..1bdd4efc0d 100644 --- a/src/main/generated/data/minecraft/recipes/mangrove_fence.json +++ b/src/main/generated/data/minecraft/recipes/mangrove_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:mangrove_fence" + "id": "minecraft:mangrove_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mangrove_fence_gate.json b/src/main/generated/data/minecraft/recipes/mangrove_fence_gate.json index a3bcbde9ff..de9a8d6bb0 100644 --- a/src/main/generated/data/minecraft/recipes/mangrove_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/mangrove_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:mangrove_fence_gate" + "count": 1, + "id": "minecraft:mangrove_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mangrove_sign.json b/src/main/generated/data/minecraft/recipes/mangrove_sign.json index 9fce4bbc44..b557bc8582 100644 --- a/src/main/generated/data/minecraft/recipes/mangrove_sign.json +++ b/src/main/generated/data/minecraft/recipes/mangrove_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:mangrove_sign" + "id": "minecraft:mangrove_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/minecart.json b/src/main/generated/data/minecraft/recipes/minecart.json index aa5a1ea93d..55244ac2de 100644 --- a/src/main/generated/data/minecraft/recipes/minecart.json +++ b/src/main/generated/data/minecraft/recipes/minecart.json @@ -11,6 +11,7 @@ "###" ], "result": { - "item": "minecraft:minecart" + "count": 1, + "id": "minecraft:minecart" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_moss_block.json b/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_moss_block.json index a59fa3296a..322539b081 100644 --- a/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_moss_block.json +++ b/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_moss_block.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:mossy_cobblestone" + "count": 1, + "id": "minecraft:mossy_cobblestone" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_vine.json b/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_vine.json index 79051c2fa1..51ade6cbcc 100644 --- a/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_vine.json +++ b/src/main/generated/data/minecraft/recipes/mossy_cobblestone_from_vine.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:mossy_cobblestone" + "count": 1, + "id": "minecraft:mossy_cobblestone" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/netherite_ingot.json b/src/main/generated/data/minecraft/recipes/netherite_ingot.json index 21ffad1650..391bb43369 100644 --- a/src/main/generated/data/minecraft/recipes/netherite_ingot.json +++ b/src/main/generated/data/minecraft/recipes/netherite_ingot.json @@ -29,6 +29,7 @@ } ], "result": { - "item": "minecraft:netherite_ingot" + "count": 1, + "id": "minecraft:netherite_ingot" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/netherite_upgrade_smithing_template.json b/src/main/generated/data/minecraft/recipes/netherite_upgrade_smithing_template.json index af5054afbd..461c35d725 100644 --- a/src/main/generated/data/minecraft/recipes/netherite_upgrade_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/netherite_upgrade_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:netherite_upgrade_smithing_template" + "id": "minecraft:netherite_upgrade_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/oak_chest_boat.json b/src/main/generated/data/minecraft/recipes/oak_chest_boat.json index 638735a211..04762bc990 100644 --- a/src/main/generated/data/minecraft/recipes/oak_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/oak_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:oak_chest_boat" + "count": 1, + "id": "minecraft:oak_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/oak_fence.json b/src/main/generated/data/minecraft/recipes/oak_fence.json index e3f9961507..5e868f7af0 100644 --- a/src/main/generated/data/minecraft/recipes/oak_fence.json +++ b/src/main/generated/data/minecraft/recipes/oak_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:oak_fence" + "id": "minecraft:oak_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/oak_fence_gate.json b/src/main/generated/data/minecraft/recipes/oak_fence_gate.json index 956d67d1a1..5d2f53fbf9 100644 --- a/src/main/generated/data/minecraft/recipes/oak_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/oak_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:oak_fence_gate" + "count": 1, + "id": "minecraft:oak_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/oak_sign.json b/src/main/generated/data/minecraft/recipes/oak_sign.json index 13132c63a0..a9387bdcfc 100644 --- a/src/main/generated/data/minecraft/recipes/oak_sign.json +++ b/src/main/generated/data/minecraft/recipes/oak_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:oak_sign" + "id": "minecraft:oak_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/observer.json b/src/main/generated/data/minecraft/recipes/observer.json index f9304ff07a..9f73b3a1c9 100644 --- a/src/main/generated/data/minecraft/recipes/observer.json +++ b/src/main/generated/data/minecraft/recipes/observer.json @@ -18,6 +18,7 @@ "###" ], "result": { - "item": "minecraft:observer" + "count": 1, + "id": "minecraft:observer" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/orange_banner.json b/src/main/generated/data/minecraft/recipes/orange_banner.json index c260165899..303b3d81ae 100644 --- a/src/main/generated/data/minecraft/recipes/orange_banner.json +++ b/src/main/generated/data/minecraft/recipes/orange_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:orange_banner" + "count": 1, + "id": "minecraft:orange_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/painting.json b/src/main/generated/data/minecraft/recipes/painting.json index dfe4ad0caa..3cc7157613 100644 --- a/src/main/generated/data/minecraft/recipes/painting.json +++ b/src/main/generated/data/minecraft/recipes/painting.json @@ -15,6 +15,7 @@ "###" ], "result": { - "item": "minecraft:painting" + "count": 1, + "id": "minecraft:painting" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/pink_banner.json b/src/main/generated/data/minecraft/recipes/pink_banner.json index 1965e7dffc..1848ebbf0a 100644 --- a/src/main/generated/data/minecraft/recipes/pink_banner.json +++ b/src/main/generated/data/minecraft/recipes/pink_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:pink_banner" + "count": 1, + "id": "minecraft:pink_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/piston.json b/src/main/generated/data/minecraft/recipes/piston.json index 74f40060e5..90eed7fc1e 100644 --- a/src/main/generated/data/minecraft/recipes/piston.json +++ b/src/main/generated/data/minecraft/recipes/piston.json @@ -21,6 +21,7 @@ "#R#" ], "result": { - "item": "minecraft:piston" + "count": 1, + "id": "minecraft:piston" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/polished_deepslate.json b/src/main/generated/data/minecraft/recipes/polished_deepslate.json index 2163aba74f..057b63d86e 100644 --- a/src/main/generated/data/minecraft/recipes/polished_deepslate.json +++ b/src/main/generated/data/minecraft/recipes/polished_deepslate.json @@ -12,6 +12,6 @@ ], "result": { "count": 4, - "item": "minecraft:polished_deepslate" + "id": "minecraft:polished_deepslate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/powered_rail.json b/src/main/generated/data/minecraft/recipes/powered_rail.json index c8b5b6e014..6573defe19 100644 --- a/src/main/generated/data/minecraft/recipes/powered_rail.json +++ b/src/main/generated/data/minecraft/recipes/powered_rail.json @@ -19,6 +19,6 @@ ], "result": { "count": 6, - "item": "minecraft:powered_rail" + "id": "minecraft:powered_rail" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/purple_banner.json b/src/main/generated/data/minecraft/recipes/purple_banner.json index 9c9baa1d93..b8be8bf84a 100644 --- a/src/main/generated/data/minecraft/recipes/purple_banner.json +++ b/src/main/generated/data/minecraft/recipes/purple_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:purple_banner" + "count": 1, + "id": "minecraft:purple_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/rail.json b/src/main/generated/data/minecraft/recipes/rail.json index a14f5d7786..927d917f76 100644 --- a/src/main/generated/data/minecraft/recipes/rail.json +++ b/src/main/generated/data/minecraft/recipes/rail.json @@ -16,6 +16,6 @@ ], "result": { "count": 16, - "item": "minecraft:rail" + "id": "minecraft:rail" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/raiser_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/raiser_armor_trim_smithing_template.json index 579235dae5..d07fc6bd24 100644 --- a/src/main/generated/data/minecraft/recipes/raiser_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/raiser_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:raiser_armor_trim_smithing_template" + "id": "minecraft:raiser_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/red_banner.json b/src/main/generated/data/minecraft/recipes/red_banner.json index ece467fb8a..3fcd38c067 100644 --- a/src/main/generated/data/minecraft/recipes/red_banner.json +++ b/src/main/generated/data/minecraft/recipes/red_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:red_banner" + "count": 1, + "id": "minecraft:red_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/redstone_torch.json b/src/main/generated/data/minecraft/recipes/redstone_torch.json index 3fef11c1ec..06ce327652 100644 --- a/src/main/generated/data/minecraft/recipes/redstone_torch.json +++ b/src/main/generated/data/minecraft/recipes/redstone_torch.json @@ -14,6 +14,7 @@ "#" ], "result": { - "item": "minecraft:redstone_torch" + "count": 1, + "id": "minecraft:redstone_torch" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/rib_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/rib_armor_trim_smithing_template.json index d15c589c64..969475ef06 100644 --- a/src/main/generated/data/minecraft/recipes/rib_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/rib_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:rib_armor_trim_smithing_template" + "id": "minecraft:rib_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/scaffolding.json b/src/main/generated/data/minecraft/recipes/scaffolding.json index 9340d3da6d..6cbb8217cc 100644 --- a/src/main/generated/data/minecraft/recipes/scaffolding.json +++ b/src/main/generated/data/minecraft/recipes/scaffolding.json @@ -16,6 +16,6 @@ ], "result": { "count": 6, - "item": "minecraft:scaffolding" + "id": "minecraft:scaffolding" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/sentry_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/sentry_armor_trim_smithing_template.json index bccef0e6f5..7f61e4a2f8 100644 --- a/src/main/generated/data/minecraft/recipes/sentry_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/sentry_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:sentry_armor_trim_smithing_template" + "id": "minecraft:sentry_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/shaper_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/shaper_armor_trim_smithing_template.json index e08dc1ce55..d0449b9df7 100644 --- a/src/main/generated/data/minecraft/recipes/shaper_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/shaper_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:shaper_armor_trim_smithing_template" + "id": "minecraft:shaper_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/shears.json b/src/main/generated/data/minecraft/recipes/shears.json index 920ff4fd1d..50ac77b03b 100644 --- a/src/main/generated/data/minecraft/recipes/shears.json +++ b/src/main/generated/data/minecraft/recipes/shears.json @@ -11,6 +11,7 @@ "# " ], "result": { - "item": "minecraft:shears" + "count": 1, + "id": "minecraft:shears" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/shield.json b/src/main/generated/data/minecraft/recipes/shield.json index d746ab4ede..4385c42213 100644 --- a/src/main/generated/data/minecraft/recipes/shield.json +++ b/src/main/generated/data/minecraft/recipes/shield.json @@ -15,6 +15,7 @@ " W " ], "result": { - "item": "minecraft:shield" + "count": 1, + "id": "minecraft:shield" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/shulker_box.json b/src/main/generated/data/minecraft/recipes/shulker_box.json index 15c67ec58d..18421b43c0 100644 --- a/src/main/generated/data/minecraft/recipes/shulker_box.json +++ b/src/main/generated/data/minecraft/recipes/shulker_box.json @@ -15,6 +15,7 @@ "-" ], "result": { - "item": "minecraft:shulker_box" + "count": 1, + "id": "minecraft:shulker_box" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/silence_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/silence_armor_trim_smithing_template.json index 9fa1c8204d..204b2bdcf3 100644 --- a/src/main/generated/data/minecraft/recipes/silence_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/silence_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:silence_armor_trim_smithing_template" + "id": "minecraft:silence_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/smithing_table.json b/src/main/generated/data/minecraft/recipes/smithing_table.json index e1ba2b4749..2f24008f09 100644 --- a/src/main/generated/data/minecraft/recipes/smithing_table.json +++ b/src/main/generated/data/minecraft/recipes/smithing_table.json @@ -15,6 +15,7 @@ "##" ], "result": { - "item": "minecraft:smithing_table" + "count": 1, + "id": "minecraft:smithing_table" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/snout_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/snout_armor_trim_smithing_template.json index 5bffa9a875..96ab3b1e0d 100644 --- a/src/main/generated/data/minecraft/recipes/snout_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/snout_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:snout_armor_trim_smithing_template" + "id": "minecraft:snout_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/soul_campfire.json b/src/main/generated/data/minecraft/recipes/soul_campfire.json index 4e1d80e502..54c6c84b24 100644 --- a/src/main/generated/data/minecraft/recipes/soul_campfire.json +++ b/src/main/generated/data/minecraft/recipes/soul_campfire.json @@ -18,6 +18,7 @@ "LLL" ], "result": { - "item": "minecraft:soul_campfire" + "count": 1, + "id": "minecraft:soul_campfire" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/soul_torch.json b/src/main/generated/data/minecraft/recipes/soul_torch.json index 55f4104c79..06598e3d8a 100644 --- a/src/main/generated/data/minecraft/recipes/soul_torch.json +++ b/src/main/generated/data/minecraft/recipes/soul_torch.json @@ -24,6 +24,6 @@ ], "result": { "count": 4, - "item": "minecraft:soul_torch" + "id": "minecraft:soul_torch" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spire_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/spire_armor_trim_smithing_template.json index d77a357eb4..ead22db42f 100644 --- a/src/main/generated/data/minecraft/recipes/spire_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/spire_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:spire_armor_trim_smithing_template" + "id": "minecraft:spire_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spruce_chest_boat.json b/src/main/generated/data/minecraft/recipes/spruce_chest_boat.json index 399ef2beab..7de6923cc9 100644 --- a/src/main/generated/data/minecraft/recipes/spruce_chest_boat.json +++ b/src/main/generated/data/minecraft/recipes/spruce_chest_boat.json @@ -11,6 +11,7 @@ } ], "result": { - "item": "minecraft:spruce_chest_boat" + "count": 1, + "id": "minecraft:spruce_chest_boat" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spruce_fence.json b/src/main/generated/data/minecraft/recipes/spruce_fence.json index b4eab9c13f..07b68fd0ae 100644 --- a/src/main/generated/data/minecraft/recipes/spruce_fence.json +++ b/src/main/generated/data/minecraft/recipes/spruce_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:spruce_fence" + "id": "minecraft:spruce_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spruce_fence_gate.json b/src/main/generated/data/minecraft/recipes/spruce_fence_gate.json index 258057d801..d7a967a6cc 100644 --- a/src/main/generated/data/minecraft/recipes/spruce_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/spruce_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:spruce_fence_gate" + "count": 1, + "id": "minecraft:spruce_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spruce_sign.json b/src/main/generated/data/minecraft/recipes/spruce_sign.json index fb28d8c03e..de06f65de8 100644 --- a/src/main/generated/data/minecraft/recipes/spruce_sign.json +++ b/src/main/generated/data/minecraft/recipes/spruce_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:spruce_sign" + "id": "minecraft:spruce_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/spyglass.json b/src/main/generated/data/minecraft/recipes/spyglass.json index f649bfc44a..0dbfd0500b 100644 --- a/src/main/generated/data/minecraft/recipes/spyglass.json +++ b/src/main/generated/data/minecraft/recipes/spyglass.json @@ -15,6 +15,7 @@ " X " ], "result": { - "item": "minecraft:spyglass" + "count": 1, + "id": "minecraft:spyglass" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stone_axe.json b/src/main/generated/data/minecraft/recipes/stone_axe.json index 58ce1597f6..82d3b87b80 100644 --- a/src/main/generated/data/minecraft/recipes/stone_axe.json +++ b/src/main/generated/data/minecraft/recipes/stone_axe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:stone_axe" + "count": 1, + "id": "minecraft:stone_axe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stone_hoe.json b/src/main/generated/data/minecraft/recipes/stone_hoe.json index 2827ae1eab..134fb97266 100644 --- a/src/main/generated/data/minecraft/recipes/stone_hoe.json +++ b/src/main/generated/data/minecraft/recipes/stone_hoe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:stone_hoe" + "count": 1, + "id": "minecraft:stone_hoe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stone_pickaxe.json b/src/main/generated/data/minecraft/recipes/stone_pickaxe.json index 8d02352c43..fb79525bcd 100644 --- a/src/main/generated/data/minecraft/recipes/stone_pickaxe.json +++ b/src/main/generated/data/minecraft/recipes/stone_pickaxe.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:stone_pickaxe" + "count": 1, + "id": "minecraft:stone_pickaxe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stone_shovel.json b/src/main/generated/data/minecraft/recipes/stone_shovel.json index 609f6e511a..4880055697 100644 --- a/src/main/generated/data/minecraft/recipes/stone_shovel.json +++ b/src/main/generated/data/minecraft/recipes/stone_shovel.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:stone_shovel" + "count": 1, + "id": "minecraft:stone_shovel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stone_sword.json b/src/main/generated/data/minecraft/recipes/stone_sword.json index 7afc9ceec6..109c0729b6 100644 --- a/src/main/generated/data/minecraft/recipes/stone_sword.json +++ b/src/main/generated/data/minecraft/recipes/stone_sword.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:stone_sword" + "count": 1, + "id": "minecraft:stone_sword" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/stonecutter.json b/src/main/generated/data/minecraft/recipes/stonecutter.json index 4fa791814f..60d93a46bd 100644 --- a/src/main/generated/data/minecraft/recipes/stonecutter.json +++ b/src/main/generated/data/minecraft/recipes/stonecutter.json @@ -14,6 +14,7 @@ "###" ], "result": { - "item": "minecraft:stonecutter" + "count": 1, + "id": "minecraft:stonecutter" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/tide_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/tide_armor_trim_smithing_template.json index 7663db553b..3bdc887b6c 100644 --- a/src/main/generated/data/minecraft/recipes/tide_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/tide_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:tide_armor_trim_smithing_template" + "id": "minecraft:tide_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/tinted_glass.json b/src/main/generated/data/minecraft/recipes/tinted_glass.json index 2017014aff..46b280d96d 100644 --- a/src/main/generated/data/minecraft/recipes/tinted_glass.json +++ b/src/main/generated/data/minecraft/recipes/tinted_glass.json @@ -16,6 +16,6 @@ ], "result": { "count": 2, - "item": "minecraft:tinted_glass" + "id": "minecraft:tinted_glass" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/torch.json b/src/main/generated/data/minecraft/recipes/torch.json index 71147ae0aa..0167972ab3 100644 --- a/src/main/generated/data/minecraft/recipes/torch.json +++ b/src/main/generated/data/minecraft/recipes/torch.json @@ -20,6 +20,6 @@ ], "result": { "count": 4, - "item": "minecraft:torch" + "id": "minecraft:torch" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/trapped_chest.json b/src/main/generated/data/minecraft/recipes/trapped_chest.json index 0ccc058c06..2f61a7f613 100644 --- a/src/main/generated/data/minecraft/recipes/trapped_chest.json +++ b/src/main/generated/data/minecraft/recipes/trapped_chest.json @@ -10,6 +10,7 @@ } ], "result": { - "item": "minecraft:trapped_chest" + "count": 1, + "id": "minecraft:trapped_chest" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/tripwire_hook.json b/src/main/generated/data/minecraft/recipes/tripwire_hook.json index a02479f770..f4a08d358c 100644 --- a/src/main/generated/data/minecraft/recipes/tripwire_hook.json +++ b/src/main/generated/data/minecraft/recipes/tripwire_hook.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:tripwire_hook" + "id": "minecraft:tripwire_hook" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/vex_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/vex_armor_trim_smithing_template.json index 981c13b403..edb9f53ba8 100644 --- a/src/main/generated/data/minecraft/recipes/vex_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/vex_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:vex_armor_trim_smithing_template" + "id": "minecraft:vex_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/ward_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/ward_armor_trim_smithing_template.json index b263c2f356..e2b473d3b1 100644 --- a/src/main/generated/data/minecraft/recipes/ward_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/ward_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:ward_armor_trim_smithing_template" + "id": "minecraft:ward_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/warped_fence.json b/src/main/generated/data/minecraft/recipes/warped_fence.json index 052fa02e71..32cfd1457f 100644 --- a/src/main/generated/data/minecraft/recipes/warped_fence.json +++ b/src/main/generated/data/minecraft/recipes/warped_fence.json @@ -16,6 +16,6 @@ ], "result": { "count": 3, - "item": "minecraft:warped_fence" + "id": "minecraft:warped_fence" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/warped_fence_gate.json b/src/main/generated/data/minecraft/recipes/warped_fence_gate.json index f176822579..b2ac7eed9c 100644 --- a/src/main/generated/data/minecraft/recipes/warped_fence_gate.json +++ b/src/main/generated/data/minecraft/recipes/warped_fence_gate.json @@ -15,6 +15,7 @@ "#W#" ], "result": { - "item": "minecraft:warped_fence_gate" + "count": 1, + "id": "minecraft:warped_fence_gate" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/warped_sign.json b/src/main/generated/data/minecraft/recipes/warped_sign.json index cbaa3b7b87..08315ccfc2 100644 --- a/src/main/generated/data/minecraft/recipes/warped_sign.json +++ b/src/main/generated/data/minecraft/recipes/warped_sign.json @@ -17,6 +17,6 @@ ], "result": { "count": 3, - "item": "minecraft:warped_sign" + "id": "minecraft:warped_sign" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wayfinder_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/wayfinder_armor_trim_smithing_template.json index a35c9bbf95..64d2fa3dd2 100644 --- a/src/main/generated/data/minecraft/recipes/wayfinder_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/wayfinder_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:wayfinder_armor_trim_smithing_template" + "id": "minecraft:wayfinder_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/white_banner.json b/src/main/generated/data/minecraft/recipes/white_banner.json index 9957dc5b0a..e6401a48ab 100644 --- a/src/main/generated/data/minecraft/recipes/white_banner.json +++ b/src/main/generated/data/minecraft/recipes/white_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:white_banner" + "count": 1, + "id": "minecraft:white_banner" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wild_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipes/wild_armor_trim_smithing_template.json index ed91ecb02d..e0355182ae 100644 --- a/src/main/generated/data/minecraft/recipes/wild_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipes/wild_armor_trim_smithing_template.json @@ -19,6 +19,6 @@ ], "result": { "count": 2, - "item": "minecraft:wild_armor_trim_smithing_template" + "id": "minecraft:wild_armor_trim_smithing_template" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wooden_axe.json b/src/main/generated/data/minecraft/recipes/wooden_axe.json index 1f6cabc9b3..c637ef036d 100644 --- a/src/main/generated/data/minecraft/recipes/wooden_axe.json +++ b/src/main/generated/data/minecraft/recipes/wooden_axe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:wooden_axe" + "count": 1, + "id": "minecraft:wooden_axe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wooden_hoe.json b/src/main/generated/data/minecraft/recipes/wooden_hoe.json index 0faec2df65..41539fc6a1 100644 --- a/src/main/generated/data/minecraft/recipes/wooden_hoe.json +++ b/src/main/generated/data/minecraft/recipes/wooden_hoe.json @@ -15,6 +15,7 @@ " #" ], "result": { - "item": "minecraft:wooden_hoe" + "count": 1, + "id": "minecraft:wooden_hoe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wooden_pickaxe.json b/src/main/generated/data/minecraft/recipes/wooden_pickaxe.json index 70c46788bc..027909c9ad 100644 --- a/src/main/generated/data/minecraft/recipes/wooden_pickaxe.json +++ b/src/main/generated/data/minecraft/recipes/wooden_pickaxe.json @@ -15,6 +15,7 @@ " # " ], "result": { - "item": "minecraft:wooden_pickaxe" + "count": 1, + "id": "minecraft:wooden_pickaxe" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wooden_shovel.json b/src/main/generated/data/minecraft/recipes/wooden_shovel.json index e5d95dbe8f..f77ac8803f 100644 --- a/src/main/generated/data/minecraft/recipes/wooden_shovel.json +++ b/src/main/generated/data/minecraft/recipes/wooden_shovel.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:wooden_shovel" + "count": 1, + "id": "minecraft:wooden_shovel" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/wooden_sword.json b/src/main/generated/data/minecraft/recipes/wooden_sword.json index f16e202780..9eca62b965 100644 --- a/src/main/generated/data/minecraft/recipes/wooden_sword.json +++ b/src/main/generated/data/minecraft/recipes/wooden_sword.json @@ -15,6 +15,7 @@ "#" ], "result": { - "item": "minecraft:wooden_sword" + "count": 1, + "id": "minecraft:wooden_sword" } } \ No newline at end of file diff --git a/src/main/generated/data/minecraft/recipes/yellow_banner.json b/src/main/generated/data/minecraft/recipes/yellow_banner.json index 80eb283553..1a431e5792 100644 --- a/src/main/generated/data/minecraft/recipes/yellow_banner.json +++ b/src/main/generated/data/minecraft/recipes/yellow_banner.json @@ -16,6 +16,7 @@ " | " ], "result": { - "item": "minecraft:yellow_banner" + "count": 1, + "id": "minecraft:yellow_banner" } } \ No newline at end of file diff --git a/src/main/generated/pack.mcmeta b/src/main/generated/pack.mcmeta index 7a29f312aa..09ae8ae4c3 100644 --- a/src/main/generated/pack.mcmeta +++ b/src/main/generated/pack.mcmeta @@ -3,6 +3,6 @@ "description": { "translate": "pack.forge.description" }, - "pack_format": 22 + "pack_format": 32 } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/client/FireworkShapeFactoryRegistry.java b/src/main/java/net/minecraftforge/client/FireworkShapeFactoryRegistry.java index 6a56eb5879..050ff39487 100644 --- a/src/main/java/net/minecraftforge/client/FireworkShapeFactoryRegistry.java +++ b/src/main/java/net/minecraftforge/client/FireworkShapeFactoryRegistry.java @@ -8,28 +8,28 @@ package net.minecraftforge.client; import java.util.HashMap; import java.util.Map; +import net.minecraft.world.item.component.FireworkExplosion; import org.jetbrains.annotations.Nullable; import net.minecraft.client.particle.FireworkParticles; -import net.minecraft.world.item.FireworkRocketItem; /** * Keeps track of custom firework shape types, because Particle is client side only this can't be on the Shape itself. * So sometime during your client initalization call register. */ public class FireworkShapeFactoryRegistry { - private static final Map factories = new HashMap<>(); + private static final Map factories = new HashMap<>(); - public static interface Factory { + public interface Factory { void build(FireworkParticles.Starter starter, boolean trail, boolean flicker, int[] colors, int[] fadecolors); } - public static void register(FireworkRocketItem.Shape shape, Factory factory) { + public static void register(FireworkExplosion.Shape shape, Factory factory) { factories.put(shape, factory); } @Nullable - public static Factory get(FireworkRocketItem.Shape shape) { + public static Factory get(FireworkExplosion.Shape shape) { return factories.get(shape); } } diff --git a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java index ef16e06977..ec70520bea 100644 --- a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java +++ b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java @@ -6,6 +6,7 @@ package net.minecraftforge.client; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.shaders.FogShape; @@ -70,6 +71,8 @@ import net.minecraft.client.resources.sounds.SoundInstance; import net.minecraft.client.sounds.SoundEngine; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.RegistryAccess; import net.minecraft.locale.Language; import net.minecraft.network.Connection; import net.minecraft.network.chat.ChatType; @@ -112,12 +115,12 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ClientChatEvent; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.ClientPauseChangeEvent; -import net.minecraftforge.client.event.ClientPauseEvent; import net.minecraftforge.client.event.ClientPlayerChangeGameTypeEvent; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.client.event.ComputeFovModifierEvent; import net.minecraftforge.client.event.CustomizeGuiOverlayEvent; import net.minecraftforge.client.event.EntityRenderersEvent; +import net.minecraftforge.client.event.ForgeEventFactoryClient; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.MovementInputUpdateEvent; @@ -144,7 +147,6 @@ import net.minecraftforge.client.extensions.common.IClientItemExtensions; import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions; import net.minecraftforge.client.gui.ClientTooltipComponentManager; import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen; -import net.minecraftforge.client.gui.overlay.GuiOverlayManager; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.textures.ForgeTextureMetadata; import net.minecraftforge.client.textures.TextureAtlasSpriteLoaderManager; @@ -256,7 +258,6 @@ public class ForgeHooksClient { public static void onClientPauseChangePost(boolean pause) { MinecraftForge.EVENT_BUS.post(new ClientPauseChangeEvent.Post(pause)); - MinecraftForge.EVENT_BUS.post(new ClientPauseEvent(pause)); } public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) { @@ -264,7 +265,9 @@ public class ForgeHooksClient { return result != null ? result : _default; } - public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) { + public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, Matrix4f ctxPos, MultiBufferSource bufferSource) { + var poseStack = new PoseStack(); + poseStack.mulPose(ctxPos); switch (target.getType()) { case BLOCK: if (!(target instanceof BlockHitResult blockTarget)) return false; @@ -277,7 +280,7 @@ public class ForgeHooksClient { } } - public static void dispatchRenderStage(RenderType renderType, LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) { + public static void dispatchRenderStage(RenderType renderType, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) { RenderLevelStageEvent.Stage stage = RenderLevelStageEvent.Stage.fromRenderType(renderType); if (stage != null) stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum); @@ -287,10 +290,6 @@ public class ForgeHooksClient { return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack)); } - public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) { - return MinecraftForge.EVENT_BUS.post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm)); - } - public static void onTextureStitchedPost(TextureAtlas map) { ModLoader.get().postEvent(new TextureStitchEvent.Post(map)); } @@ -342,12 +341,6 @@ public class ForgeHooksClient { return fovModifierEvent.getNewFovModifier(); } - public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) { - ViewportEvent.ComputeFov event = new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov); - MinecraftForge.EVENT_BUS.post(event); - return event.getFOV(); - } - /** * Initialization of Forge Renderers. */ @@ -429,12 +422,6 @@ public class ForgeHooksClient { } } - public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) { - ViewportEvent.ComputeCameraAngles event = new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0); - MinecraftForge.EVENT_BUS.post(event); - return event; - } - public static void onModifyBakingResult(Map models, ModelBakery modelBakery) { ModLoader.get().postEvent(new ModelEvent.ModifyBakingResult(models, modelBakery)); } @@ -443,11 +430,6 @@ public class ForgeHooksClient { ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery)); } - public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) { - model = model.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform); - return model; - } - @SuppressWarnings("deprecation") public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) { IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn); @@ -548,12 +530,6 @@ public class ForgeHooksClient { return evt; } - public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) { - ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile); - MinecraftForge.EVENT_BUS.post(event); - return event; - } - public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) { if (currentGameMode != newGameMode) { ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode); @@ -565,34 +541,22 @@ public class ForgeHooksClient { MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput)); } - public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) { - Event event = new ScreenEvent.KeyPressed.Pre(guiScreen, keyCode, scanCode, modifiers); - return MinecraftForge.EVENT_BUS.post(event); + public static void onScreenKeyPressed(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) { + state[0] = ForgeEventFactoryClient.onScreenKeyPressedPre(screen, keyCode, scanCode, modifiers) + || screen.keyPressed(keyCode, scanCode, modifiers) + || ForgeEventFactoryClient.onScreenKeyPressedPost(screen, keyCode, scanCode, modifiers); } - public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) { - Event event = new ScreenEvent.KeyPressed.Post(guiScreen, keyCode, scanCode, modifiers); - return MinecraftForge.EVENT_BUS.post(event); + public static void onScreenKeyReleased(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) { + state[0] = ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, keyCode, scanCode, modifiers) + || screen.keyReleased(keyCode, scanCode, modifiers) + || ForgeEventFactoryClient.onScreenKeyReleasedPost(screen, keyCode, scanCode, modifiers); } - public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) { - Event event = new ScreenEvent.KeyReleased.Pre(guiScreen, keyCode, scanCode, modifiers); - return MinecraftForge.EVENT_BUS.post(event); - } - - public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) { - Event event = new ScreenEvent.KeyReleased.Post(guiScreen, keyCode, scanCode, modifiers); - return MinecraftForge.EVENT_BUS.post(event); - } - - public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) { - Event event = new ScreenEvent.CharacterTyped.Pre(guiScreen, codePoint, modifiers); - return MinecraftForge.EVENT_BUS.post(event); - } - - public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) { - Event event = new ScreenEvent.CharacterTyped.Post(guiScreen, codePoint, modifiers); - MinecraftForge.EVENT_BUS.post(event); + public static boolean onScreenCharTyped(Screen screen, char codePoint, int modifiers) { + return ForgeEventFactoryClient.onScreenCharTypedPre(screen, codePoint, modifiers) + || screen.charTyped(codePoint, modifiers) + || ForgeEventFactoryClient.onScreenCharTypedPost(screen, codePoint, modifiers); } public static void onRecipesUpdated(RecipeManager mgr) { @@ -604,15 +568,9 @@ public class ForgeHooksClient { MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers)); } - public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) { - InputEvent.InteractionKeyMappingTriggered event = new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand); - MinecraftForge.EVENT_BUS.post(event); - return event; - } - public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) { - if (entity instanceof LivingEntity) { - final AttributeInstance attribute = ((LivingEntity) entity).getAttribute(ForgeMod.NAMETAG_DISTANCE.get()); + if (entity instanceof LivingEntity living) { + var attribute = living.getAttribute(ForgeMod.NAMETAG_DISTANCE.getHolder().get()); if (attribute != null) { return !(squareDistance > (attribute.getValue() * attribute.getValue())); } @@ -620,14 +578,6 @@ public class ForgeHooksClient { return !(squareDistance > 4096.0f); } - public static void renderPistonMovedBlocks(BlockPos pos, BlockState state, PoseStack stack, MultiBufferSource bufferSource, Level level, boolean checkSides, int packedOverlay, BlockRenderDispatcher blockRenderer) { - var model = blockRenderer.getBlockModel(state); - for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) { - VertexConsumer vertexConsumer = bufferSource.getBuffer(RenderTypeHelper.getMovingBlockRenderType(renderType)); - blockRenderer.getModelRenderer().tesselateBlock(level, model, state, pos, stack, vertexConsumer, checkSides, RandomSource.create(), state.getSeed(pos), packedOverlay, ModelData.EMPTY, renderType); - } - } - public static boolean shouldRenderEffect(MobEffectInstance effectInstance) { return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance); } @@ -757,7 +707,8 @@ public class ForgeHooksClient { if(relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26) { //this is not the most proper way to do it, //but works best here and has the least maintenance overhead - gui.setToolTip(Arrays.stream(tooltip.split("\n")).map(Component::literal).collect(Collectors.toList())); + var lines = Arrays.stream(tooltip.split("\n")).map(Component::literal).toList(); + gui.setTooltipForNextRenderPass(Lists.transform(lines, Component::getVisualOrderText)); } } @@ -772,18 +723,6 @@ public class ForgeHooksClient { GameData.revertToFrozen(); } - public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) { - MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggingIn(pc, player, networkManager)); - } - - public static void firePlayerLogout(@Nullable MultiPlayerGameMode pc, @Nullable LocalPlayer player) { - MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggingOut(pc, player, player != null ? player.connection != null ? player.connection.getConnection() : null : null)); - } - - public static void firePlayerRespawn(MultiPlayerGameMode pc, LocalPlayer oldPlayer, LocalPlayer newPlayer, Connection networkManager) { - MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.Clone(pc, oldPlayer, newPlayer, networkManager)); - } - public static void onRegisterParticleProviders(ParticleEngine particleEngine) { ModLoader.get().postEvent(new RegisterParticleProvidersEvent(particleEngine)); } @@ -808,14 +747,14 @@ public class ForgeHooksClient { return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage(); } - private static final ChatTypeDecoration SYSTEM_CHAT_TYPE_DECORATION = new ChatTypeDecoration("forge.chatType.system", List.of(ChatTypeDecoration.Parameter.CONTENT), Style.EMPTY); - private static final ChatType SYSTEM_CHAT_TYPE = new ChatType(SYSTEM_CHAT_TYPE_DECORATION, SYSTEM_CHAT_TYPE_DECORATION); - private static final ChatType.Bound SYSTEM_CHAT_TYPE_BOUND = SYSTEM_CHAT_TYPE.bind(Component.literal("System")); - @Nullable - public static Component onClientSystemChat(Component message, boolean overlay) { - ClientChatReceivedEvent.System event = new ClientChatReceivedEvent.System(SYSTEM_CHAT_TYPE_BOUND, message, overlay); + public static Component onClientSystemChat(Component message, boolean overlay, RegistryAccess registry) { + return message; + /* + var bound = ChatType.bind(ForgeMod.SYSTEM_CHAT_TYPE.getKey(), registry, Component.literal("System")); + var event = new ClientChatReceivedEvent.System(bound, message, overlay); return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage(); + */ } @NotNull @@ -1050,7 +989,7 @@ public class ForgeHooksClient { EntitySpectatorShaderManager.init(); ForgeHooksClient.onRegisterKeyMappings(mc.options); RecipeBookManager.init(); - GuiOverlayManager.init(); + //GuiOverlayManager.init(); DimensionSpecialEffectsManager.init(); NamedRenderTypeManager.init(); ColorResolverManager.init(); @@ -1065,4 +1004,12 @@ public class ForgeHooksClient { mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch)); return true; } + + public static void onScreenMouseDrag(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) { + if (ForgeEventFactoryClient.onScreenMouseDragPre(screen, mouseX, mouseY, mouseButton, dragX, dragY)) + return; + if (screen.mouseDragged(mouseX, mouseY, mouseButton, dragX, dragY)) + return; + ForgeEventFactoryClient.onScreenMouseDragPost(screen, mouseX, mouseY, mouseButton, dragX, dragY); + } } diff --git a/src/main/java/net/minecraftforge/client/RecipeBookManager.java b/src/main/java/net/minecraftforge/client/RecipeBookManager.java index a8919f8ac8..de621fe8ad 100644 --- a/src/main/java/net/minecraftforge/client/RecipeBookManager.java +++ b/src/main/java/net/minecraftforge/client/RecipeBookManager.java @@ -28,8 +28,7 @@ import java.util.function.Function; *

* Provides a recipe category lookup. */ -public final class RecipeBookManager -{ +public final class RecipeBookManager { // Not using ConcurrentHashMap here because it's slower for lookups, so we only use it during init private static final Map> AGGREGATE_CATEGORIES = new HashMap<>(); private static final Map> TYPE_CATEGORIES = new HashMap<>(); @@ -40,27 +39,23 @@ public final class RecipeBookManager * Finds the category the specified recipe should display in, or null if none. */ @Nullable - public static > RecipeBookCategories findCategories(RecipeType type, RecipeHolder recipe) - { + public static > RecipeBookCategories findCategories(RecipeType type, RecipeHolder recipe) { var lookup = RECIPE_CATEGORY_LOOKUPS.get(type); return lookup != null ? lookup.apply(recipe.value()) : null; } @ApiStatus.Internal - public static Map> getAggregateCategories() - { + public static Map> getAggregateCategories(Map> vanilla) { return AGGREGATE_CATEGORIES_VIEW; } @ApiStatus.Internal - public static List getCustomCategoriesOrEmpty(RecipeBookType recipeBookType) - { + public static List getCustomCategoriesOrEmpty(RecipeBookType recipeBookType) { return TYPE_CATEGORIES.getOrDefault(recipeBookType, List.of()); } @ApiStatus.Internal - public static void init() - { + public static void init() { // The ImmutableMap is the patched out value of AGGREGATE_CATEGORIES var aggregateCategories = new HashMap<>(ImmutableMap.of( RecipeBookCategories.CRAFTING_SEARCH, ImmutableList.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE), diff --git a/src/main/java/net/minecraftforge/client/RenderTypeGroup.java b/src/main/java/net/minecraftforge/client/RenderTypeGroup.java index 4f5e10826a..3135d715b2 100644 --- a/src/main/java/net/minecraftforge/client/RenderTypeGroup.java +++ b/src/main/java/net/minecraftforge/client/RenderTypeGroup.java @@ -13,26 +13,22 @@ import net.minecraft.client.renderer.RenderType; * {@code entityFabulous} may support custom render targets and other aspects of the fabulous pipeline, or can otherwise * be the same as {@code entity}. */ -public record RenderTypeGroup(RenderType block, RenderType entity, RenderType entityFabulous) -{ +public record RenderTypeGroup(RenderType block, RenderType entity, RenderType entityFabulous) { public static RenderTypeGroup EMPTY = new RenderTypeGroup(null, null, null); - public RenderTypeGroup - { + public RenderTypeGroup { if ((block == null) != (entity == null) || (block == null) != (entityFabulous == null)) throw new IllegalArgumentException("The render types in a group must either be all null, or all non-null."); } - public RenderTypeGroup(RenderType block, RenderType entity) - { + public RenderTypeGroup(RenderType block, RenderType entity) { this(block, entity, entity); } /** * {@return true if this group has render types or not. It either has all, or none} */ - public boolean isEmpty() - { + public boolean isEmpty() { // We throw an exception in the constructor if nullability doesn't match, so checking this is enough return block == null; } diff --git a/src/main/java/net/minecraftforge/client/RenderTypeHelper.java b/src/main/java/net/minecraftforge/client/RenderTypeHelper.java index 38aebf5b22..4ade29d0ec 100644 --- a/src/main/java/net/minecraftforge/client/RenderTypeHelper.java +++ b/src/main/java/net/minecraftforge/client/RenderTypeHelper.java @@ -21,8 +21,7 @@ import org.jetbrains.annotations.NotNull; /** * Provides helper functions replacing those in {@link ItemBlockRenderTypes}. */ -public final class RenderTypeHelper -{ +public final class RenderTypeHelper { /** * Provides a {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for the given {@link DefaultVertexFormat#BLOCK} format. * This should be called for each {@link RenderType} returned by {@link BakedModel#getRenderTypes(BlockState, RandomSource, ModelData)}. @@ -30,8 +29,7 @@ public final class RenderTypeHelper * Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getRenderType(BlockState, boolean)}. */ @NotNull - public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) - { + public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) { if (chunkRenderType != RenderType.translucent()) return Sheets.cutoutBlockSheet(); return cull || !Minecraft.useShaderTransparency() ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet(); @@ -44,8 +42,7 @@ public final class RenderTypeHelper * Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getMovingBlockRenderType(BlockState)}. */ @NotNull - public static RenderType getMovingBlockRenderType(RenderType renderType) - { + public static RenderType getMovingBlockRenderType(RenderType renderType) { if (renderType == RenderType.translucent()) return RenderType.translucentMovingBlock(); return renderType; @@ -58,10 +55,8 @@ public final class RenderTypeHelper * but removes the need to query the model again if the item is a {@link BlockItem}. */ @NotNull - public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model, boolean cull) - { - if (stack.getItem() instanceof BlockItem blockItem) - { + public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model, boolean cull) { + if (stack.getItem() instanceof BlockItem blockItem) { var renderTypes = model.getRenderTypes(blockItem.getBlock().defaultBlockState(), RandomSource.create(42), ModelData.EMPTY); if (renderTypes.contains(RenderType.translucent())) return getEntityRenderType(RenderType.translucent(), cull); @@ -70,7 +65,5 @@ public final class RenderTypeHelper return cull ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet(); } - private RenderTypeHelper() - { - } + private RenderTypeHelper() {} } diff --git a/src/main/java/net/minecraftforge/client/event/ClientPauseEvent.java b/src/main/java/net/minecraftforge/client/event/ClientPauseEvent.java deleted file mode 100644 index fc5333bddc..0000000000 --- a/src/main/java/net/minecraftforge/client/event/ClientPauseEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.client.event; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.Cancelable; -import net.minecraftforge.eventbus.api.Event; - -import net.minecraft.client.Minecraft; -import net.minecraftforge.fml.LogicalSide; - -/** - * Fired when {@linkplain Minecraft#pause Minecraft.pause} value got updated by - * the {@linkplain Minecraft#runTick(boolean) Minecraft.runTick(...)} on a single-player world - * - *

This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.

- * - *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, - * only on the {@linkplain LogicalSide#CLIENT logical client}.

- * - * @deprecated use {@linkplain ClientPauseChangeEvent.Post ClientPauseChangeEvent.Post} instead - * @see ClientPauseChangeEvent.Pre - * @see ClientPauseChangeEvent.Post - */ -@Deprecated(forRemoval = true, since="1.20.4") -public class ClientPauseEvent extends Event -{ - private final boolean paused; - - public ClientPauseEvent(boolean isPaused) - { - this.paused = isPaused; - } - - /** - * {@return game is paused} - */ - public boolean isPaused() - { - return paused; - } -} diff --git a/src/main/java/net/minecraftforge/client/event/ClientPlayerNetworkEvent.java b/src/main/java/net/minecraftforge/client/event/ClientPlayerNetworkEvent.java index f19f9a4f33..fb83376fde 100644 --- a/src/main/java/net/minecraftforge/client/event/ClientPlayerNetworkEvent.java +++ b/src/main/java/net/minecraftforge/client/event/ClientPlayerNetworkEvent.java @@ -26,15 +26,13 @@ import org.jetbrains.annotations.Nullable; * @see LoggingOut * @see Clone **/ -public abstract class ClientPlayerNetworkEvent extends Event -{ +public abstract class ClientPlayerNetworkEvent extends Event { private final MultiPlayerGameMode multiPlayerGameMode; private final LocalPlayer player; private final Connection connection; @ApiStatus.Internal - protected ClientPlayerNetworkEvent(final MultiPlayerGameMode multiPlayerGameMode, final LocalPlayer player, final Connection connection) - { + protected ClientPlayerNetworkEvent(final MultiPlayerGameMode multiPlayerGameMode, final LocalPlayer player, final Connection connection) { this.multiPlayerGameMode = multiPlayerGameMode; this.player = player; this.connection = connection; @@ -43,24 +41,21 @@ public abstract class ClientPlayerNetworkEvent extends Event /** * {@return the multiplayer game mode controller for the player} */ - public MultiPlayerGameMode getMultiPlayerGameMode() - { + public MultiPlayerGameMode getMultiPlayerGameMode() { return multiPlayerGameMode; } /** * {@return the player instance} */ - public LocalPlayer getPlayer() - { + public LocalPlayer getPlayer() { return player; } /** * {@return the network connection for the player} */ - public Connection getConnection() - { + public Connection getConnection() { return connection; } @@ -72,11 +67,9 @@ public abstract class ClientPlayerNetworkEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class LoggingIn extends ClientPlayerNetworkEvent - { + public static class LoggingIn extends ClientPlayerNetworkEvent { @ApiStatus.Internal - public LoggingIn(final MultiPlayerGameMode controller, final LocalPlayer player, final Connection networkManager) - { + public LoggingIn(final MultiPlayerGameMode controller, final LocalPlayer player, final Connection networkManager) { super(controller, player, networkManager); } } @@ -91,11 +84,9 @@ public abstract class ClientPlayerNetworkEvent extends Event */ @SuppressWarnings("NullableProblems") // Shush IntelliJ, we override non-nullables as nullables in this specific event; see later comment - public static class LoggingOut extends ClientPlayerNetworkEvent - { + public static class LoggingOut extends ClientPlayerNetworkEvent { @ApiStatus.Internal - public LoggingOut(@Nullable final MultiPlayerGameMode controller, @Nullable final LocalPlayer player, @Nullable final Connection networkManager) - { + public LoggingOut(@Nullable final MultiPlayerGameMode controller, @Nullable final LocalPlayer player, @Nullable final Connection networkManager) { //noinspection ConstantConditions we know these are nullable, but we don't want to annotate the super as nullable since this is the only event with nullables super(controller, player, networkManager); } @@ -107,8 +98,7 @@ public abstract class ClientPlayerNetworkEvent extends Event */ @Nullable @Override - public MultiPlayerGameMode getMultiPlayerGameMode() - { + public MultiPlayerGameMode getMultiPlayerGameMode() { return super.getMultiPlayerGameMode(); } @@ -119,8 +109,7 @@ public abstract class ClientPlayerNetworkEvent extends Event */ @Nullable @Override - public LocalPlayer getPlayer() - { + public LocalPlayer getPlayer() { return super.getPlayer(); } @@ -131,8 +120,7 @@ public abstract class ClientPlayerNetworkEvent extends Event */ @Nullable @Override - public Connection getConnection() - { + public Connection getConnection() { return super.getConnection(); } } @@ -145,13 +133,11 @@ public abstract class ClientPlayerNetworkEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class Clone extends ClientPlayerNetworkEvent - { + public static class Clone extends ClientPlayerNetworkEvent { private final LocalPlayer oldPlayer; @ApiStatus.Internal - public Clone(final MultiPlayerGameMode pc, final LocalPlayer oldPlayer, final LocalPlayer newPlayer, final Connection networkManager) - { + public Clone(final MultiPlayerGameMode pc, final LocalPlayer oldPlayer, final LocalPlayer newPlayer, final Connection networkManager) { super(pc, newPlayer, networkManager); this.oldPlayer = oldPlayer; } @@ -159,16 +145,14 @@ public abstract class ClientPlayerNetworkEvent extends Event /** * {@return the previous player instance} */ - public LocalPlayer getOldPlayer() - { + public LocalPlayer getOldPlayer() { return oldPlayer; } /** * {@return the newly created player instance} */ - public LocalPlayer getNewPlayer() - { + public LocalPlayer getNewPlayer() { return super.getPlayer(); } @@ -178,8 +162,7 @@ public abstract class ClientPlayerNetworkEvent extends Event * @see #getNewPlayer() */ @Override - public LocalPlayer getPlayer() - { + public LocalPlayer getPlayer() { return super.getPlayer(); } } diff --git a/src/main/java/net/minecraftforge/client/event/ContainerScreenEvent.java b/src/main/java/net/minecraftforge/client/event/ContainerScreenEvent.java index 3c0f4fc910..23fee30834 100644 --- a/src/main/java/net/minecraftforge/client/event/ContainerScreenEvent.java +++ b/src/main/java/net/minecraftforge/client/event/ContainerScreenEvent.java @@ -23,21 +23,18 @@ import org.jetbrains.annotations.ApiStatus; * @see Render.Foreground * @see Render.Background */ -public abstract class ContainerScreenEvent extends Event -{ +public abstract class ContainerScreenEvent extends Event { private final AbstractContainerScreen containerScreen; @ApiStatus.Internal - protected ContainerScreenEvent(AbstractContainerScreen containerScreen) - { + protected ContainerScreenEvent(AbstractContainerScreen containerScreen) { this.containerScreen = containerScreen; } /** * {@return the container screen} */ - public AbstractContainerScreen getContainerScreen() - { + public AbstractContainerScreen getContainerScreen() { return containerScreen; } @@ -51,15 +48,13 @@ public abstract class ContainerScreenEvent extends Event * @see Foreground * @see Background */ - public static abstract class Render extends ContainerScreenEvent - { + public static abstract class Render extends ContainerScreenEvent { private final GuiGraphics guiGraphics; private final int mouseX; private final int mouseY; @ApiStatus.Internal - protected Render(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) - { + protected Render(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) { super(guiContainer); this.guiGraphics = guiGraphics; this.mouseX = mouseX; @@ -69,24 +64,21 @@ public abstract class ContainerScreenEvent extends Event /** * {@return the gui graphics used for rendering} */ - public GuiGraphics getGuiGraphics() - { + public GuiGraphics getGuiGraphics() { return guiGraphics; } /** * {@return the X coordinate of the mouse pointer} */ - public int getMouseX() - { + public int getMouseX() { return mouseX; } /** * {@return the Y coordinate of the mouse pointer} */ - public int getMouseY() - { + public int getMouseY() { return mouseY; } @@ -102,11 +94,9 @@ public abstract class ContainerScreenEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class Foreground extends Render - { + public static class Foreground extends Render { @ApiStatus.Internal - public Foreground(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) - { + public Foreground(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) { super(guiContainer, guiGraphics, mouseX, mouseY); } } @@ -120,11 +110,9 @@ public abstract class ContainerScreenEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class Background extends Render - { + public static class Background extends Render { @ApiStatus.Internal - public Background(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) - { + public Background(AbstractContainerScreen guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) { super(guiContainer, guiGraphics, mouseX, mouseY); } } diff --git a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java index 2d90910bb7..72009724ce 100644 --- a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java +++ b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java @@ -5,28 +5,59 @@ package net.minecraftforge.client.event; +import java.io.File; +import java.util.List; import java.util.Map; +import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import com.mojang.blaze3d.audio.Channel; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.datafixers.util.Pair; +import net.minecraft.client.Camera; +import net.minecraft.client.KeyMapping; import net.minecraft.client.MouseHandler; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.model.EntityModel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererProvider.Context; +import net.minecraft.client.renderer.entity.ItemFrameRenderer; +import net.minecraft.client.renderer.entity.LivingEntityRenderer; +import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.client.resources.PlayerSkin.Model; import net.minecraft.client.resources.sounds.SoundInstance; import net.minecraft.client.sounds.SoundEngine; +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.server.packs.resources.ResourceProvider; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.player.Player; import net.minecraftforge.client.event.sound.PlaySoundSourceEvent; import net.minecraftforge.client.event.sound.PlayStreamingSourceEvent; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.ModLoader; -public class ForgeEventFactoryClient { +public final class ForgeEventFactoryClient { + private ForgeEventFactoryClient() {} + private static boolean post(Event e) { return MinecraftForge.EVENT_BUS.post(e); } @@ -36,27 +67,33 @@ public class ForgeEventFactoryClient { return e; } - public static void gatherLayers(Map, EntityRenderer> renderers, Map> playerRenderers, Context context) { + public static void onGatherLayers(Map, EntityRenderer> renderers, Map> playerRenderers, Context context) { // TODO: Why is this a ModLoader event... ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context)); } - public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) { - return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button)); + public static void onRegisterShaders(ResourceProvider resourceProvider, List>> shaderList) { + // TODO: Why i this a ModLoader event... + ModLoader.get().postEvent(new RegisterShadersEvent(resourceProvider, shaderList)); } - public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { - var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); - return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; + public static void onScreenMouseReleased(boolean[] state, Screen screen, double mouseX, double mouseY, int button) { + state[0] = post(new ScreenEvent.MouseButtonReleased.Pre(screen, mouseX, mouseY, button)); + if (!state[0]) { + state[0] = screen.mouseReleased(mouseX, mouseY, button); + var result = fire(new ScreenEvent.MouseButtonReleased.Post(screen, mouseX, mouseY, button, state[0])).getResult(); + state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW; + } } - public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) { - return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button)); - } + public static void onScreenMouseClicked(boolean[] state, Screen screen, double mouseX, double mouseY, int button) { + state[0] = post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, button)); + if (!state[0]) { + state[0] = screen.mouseClicked(mouseX, mouseY, button); + } - public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) { - var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult(); - return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW; + var result = fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, button, state[0])).getResult(); + state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW; } public static boolean onMouseButtonPre(int button, int action, int mods) { @@ -105,4 +142,96 @@ public class ForgeEventFactoryClient { public static void onPlayStreamingSource(SoundEngine engine, SoundInstance sound, Channel channel) { post(new PlayStreamingSourceEvent(engine, sound, channel)); } + + public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) { + return fire(new ScreenshotEvent(image, screenshotFile)); + } + + public static boolean onScreenKeyPressedPre(Screen screen, int keyCode, int scanCode, int modifiers) { + return post(new ScreenEvent.KeyPressed.Pre(screen, keyCode, scanCode, modifiers)); + } + + public static boolean onScreenKeyPressedPost(Screen screen, int keyCode, int scanCode, int modifiers) { + return post(new ScreenEvent.KeyPressed.Post(screen, keyCode, scanCode, modifiers)); + } + + public static boolean onScreenKeyReleasedPre(Screen screen, int keyCode, int scanCode, int modifiers) { + return post(new ScreenEvent.KeyReleased.Pre(screen, keyCode, scanCode, modifiers)); + } + + public static boolean onScreenKeyReleasedPost(Screen screen, int keyCode, int scanCode, int modifiers) { + return post(new ScreenEvent.KeyReleased.Post(screen, keyCode, scanCode, modifiers)); + } + + public static boolean onScreenCharTypedPre(Screen screen, char codePoint, int modifiers) { + return post(new ScreenEvent.CharacterTyped.Pre(screen, codePoint, modifiers)); + } + + public static boolean onScreenCharTypedPost(Screen screen, char codePoint, int modifiers) { + return post(new ScreenEvent.CharacterTyped.Post(screen, codePoint, modifiers)); + } + + public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) { + return fire(new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand)); + } + + public static void onContainerRenderBackground(AbstractContainerScreen screen, GuiGraphics graphics, int mouseX, int mouseY) { + post(new ContainerScreenEvent.Render.Background(screen, graphics, mouseX, mouseY)); + } + + public static void onContainerRenderForeground(AbstractContainerScreen screen, GuiGraphics graphics, int mouseX, int mouseY) { + post(new ContainerScreenEvent.Render.Foreground(screen, graphics, mouseX, mouseY)); + } + + public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) { + post(new ClientPlayerNetworkEvent.LoggingIn(pc, player, networkManager)); + } + + public static void firePlayerLogout(@Nullable MultiPlayerGameMode pc, @Nullable LocalPlayer player) { + post(new ClientPlayerNetworkEvent.LoggingOut(pc, player, player != null ? player.connection != null ? player.connection.getConnection() : null : null)); + } + + public static void firePlayerRespawn(MultiPlayerGameMode pc, LocalPlayer oldPlayer, LocalPlayer newPlayer, Connection networkManager) { + post(new ClientPlayerNetworkEvent.Clone(pc, oldPlayer, newPlayer, networkManager)); + } + + public static ViewportEvent.ComputeFov fireComputeFov(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) { + return fire(new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov)); + } + + public static ViewportEvent.ComputeCameraAngles fireComputeCameraAngles(GameRenderer renderer, Camera camera, float partial) { + return fire(new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0)); + } + + public static > boolean onRenderLivingPre(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { + return post(new RenderLivingEvent.Pre(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight)); + } + + public static > boolean onRenderLivingPost(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { + return post(new RenderLivingEvent.Post(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight)); + } + + public static boolean onRenderPlayerPre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { + return post(new RenderPlayerEvent.Pre(player, renderer, partialTick, poseStack, multiBufferSource, packedLight)); + } + + public static boolean onRenderPlayerPost(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { + return post(new RenderPlayerEvent.Post(player, renderer, partialTick, poseStack, multiBufferSource, packedLight)); + } + + public static boolean onRenderArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) { + return post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm)); + } + + public static boolean onRenderItemInFrame(ItemFrame itemFrame, ItemFrameRenderer renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { + return post(new RenderItemInFrameEvent(itemFrame, renderItemFrame, poseStack, multiBufferSource, packedLight)); + } + + public static RenderNameTagEvent fireRenderNameTagEvent(Entity entity, Component content, EntityRenderer entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) { + return fire(new RenderNameTagEvent(entity, content, entityRenderer, poseStack, multiBufferSource, packedLight, partialTick)); + } + + public static void onRenderScreenBackground(Screen screen, GuiGraphics guiGraphics) { + fire(new ScreenEvent.BackgroundRendered(screen, guiGraphics)); + } } diff --git a/src/main/java/net/minecraftforge/client/event/InputEvent.java b/src/main/java/net/minecraftforge/client/event/InputEvent.java index 6f4db92f73..5e8e8f0432 100644 --- a/src/main/java/net/minecraftforge/client/event/InputEvent.java +++ b/src/main/java/net/minecraftforge/client/event/InputEvent.java @@ -295,6 +295,7 @@ public abstract class InputEvent extends Event { *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ + // TODO: Change the 'button' to sub events. - Lex 0422202 @Cancelable public static class InteractionKeyMappingTriggered extends InputEvent { private final int button; diff --git a/src/main/java/net/minecraftforge/client/event/RegisterGuiOverlaysEvent.java b/src/main/java/net/minecraftforge/client/event/RegisterGuiOverlaysEvent.java index dba0ddeb14..2d7c88b93f 100644 --- a/src/main/java/net/minecraftforge/client/event/RegisterGuiOverlaysEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RegisterGuiOverlaysEvent.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.event; import com.google.common.base.Preconditions; @@ -29,7 +30,7 @@ import java.util.Map; * *

This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

- */ + * / public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent { private final Map overlays; @@ -47,7 +48,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent * * @param id A unique resource id for this overlay * @param overlay The overlay - */ + * / public void registerBelowAll(@NotNull String id, @NotNull IGuiOverlay overlay) { register(Ordering.BEFORE, null, id, overlay); @@ -60,7 +61,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent * {@link VanillaGuiOverlay vanilla overlay}. Do not use other mods' overlays. * @param id A unique resource id for this overlay * @param overlay The overlay - */ + * / public void registerBelow(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay) { register(Ordering.BEFORE, other, id, overlay); @@ -73,7 +74,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent * {@link VanillaGuiOverlay vanilla overlay}. Do not use other mods' overlays. * @param id A unique resource id for this overlay * @param overlay The overlay - */ + * / public void registerAbove(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay) { register(Ordering.AFTER, other, id, overlay); @@ -84,7 +85,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent * * @param id A unique resource id for this overlay * @param overlay The overlay - */ + * / public void registerAboveAll(@NotNull String id, @NotNull IGuiOverlay overlay) { register(Ordering.AFTER, null, id, overlay); @@ -116,3 +117,4 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent BEFORE, AFTER } } +*/ diff --git a/src/main/java/net/minecraftforge/client/event/RegisterShadersEvent.java b/src/main/java/net/minecraftforge/client/event/RegisterShadersEvent.java index ed6ea20b7e..f4cea57042 100644 --- a/src/main/java/net/minecraftforge/client/event/RegisterShadersEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RegisterShadersEvent.java @@ -7,7 +7,6 @@ package net.minecraftforge.client.event; import com.mojang.datafixers.util.Pair; import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceProvider; import net.minecraftforge.eventbus.api.Cancelable; import net.minecraftforge.eventbus.api.Event; @@ -28,14 +27,12 @@ import java.util.function.Consumer; *

This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ -public class RegisterShadersEvent extends Event implements IModBusEvent -{ +public class RegisterShadersEvent extends Event implements IModBusEvent { private final ResourceProvider resourceProvider; private final List>> shaderList; @ApiStatus.Internal - public RegisterShadersEvent(ResourceProvider resourceProvider, List>> shaderList) - { + public RegisterShadersEvent(ResourceProvider resourceProvider, List>> shaderList) { this.resourceProvider = resourceProvider; this.shaderList = shaderList; } @@ -43,8 +40,7 @@ public class RegisterShadersEvent extends Event implements IModBusEvent /** * {@return the client-side resource provider} */ - public ResourceProvider getResourceProvider() - { + public ResourceProvider getResourceProvider() { return resourceProvider; } @@ -60,8 +56,7 @@ public class RegisterShadersEvent extends Event implements IModBusEvent * @param shaderInstance a shader * @param onLoaded a callback for when the shader is loaded */ - public void registerShader(ShaderInstance shaderInstance, Consumer onLoaded) - { + public void registerShader(ShaderInstance shaderInstance, Consumer onLoaded) { shaderList.add(Pair.of(shaderInstance, onLoaded)); } } diff --git a/src/main/java/net/minecraftforge/client/event/RenderArmEvent.java b/src/main/java/net/minecraftforge/client/event/RenderArmEvent.java index a8c28ec119..2ec47314f6 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderArmEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderArmEvent.java @@ -28,8 +28,7 @@ import org.jetbrains.annotations.ApiStatus; * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ @Cancelable -public class RenderArmEvent extends Event -{ +public class RenderArmEvent extends Event { private final PoseStack poseStack; private final MultiBufferSource multiBufferSource; private final int packedLight; @@ -37,8 +36,7 @@ public class RenderArmEvent extends Event private final HumanoidArm arm; @ApiStatus.Internal - public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) - { + public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) { this.poseStack = poseStack; this.multiBufferSource = multiBufferSource; this.packedLight = packedLight; @@ -49,24 +47,21 @@ public class RenderArmEvent extends Event /** * {@return the arm being rendered} */ - public HumanoidArm getArm() - { + public HumanoidArm getArm() { return arm; } /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() - { + public PoseStack getPoseStack() { return poseStack; } /** * {@return the source of rendering buffers} */ - public MultiBufferSource getMultiBufferSource() - { + public MultiBufferSource getMultiBufferSource() { return multiBufferSource; } @@ -75,8 +70,7 @@ public class RenderArmEvent extends Event * * @see LightTexture */ - public int getPackedLight() - { + public int getPackedLight() { return packedLight; } @@ -84,8 +78,7 @@ public class RenderArmEvent extends Event * {@return the client player that is having their arm rendered} In general, this will be the same as * {@link net.minecraft.client.Minecraft#player}. */ - public AbstractClientPlayer getPlayer() - { + public AbstractClientPlayer getPlayer() { return player; } } diff --git a/src/main/java/net/minecraftforge/client/event/RenderGuiEvent.java b/src/main/java/net/minecraftforge/client/event/RenderGuiEvent.java index 3c853e082c..16e85a0dd3 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderGuiEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderGuiEvent.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.event; import com.mojang.blaze3d.platform.Window; @@ -12,14 +13,13 @@ import net.minecraftforge.eventbus.api.Cancelable; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.LogicalSide; import org.jetbrains.annotations.ApiStatus; - /** * Fired when the HUD is rendered to the screen. * See the two subclasses for listening to the two possible phases. * * @see Pre * @see Post - */ + * / public abstract class RenderGuiEvent extends Event { private final Window window; @@ -60,7 +60,7 @@ public abstract class RenderGuiEvent extends Event * only on the {@linkplain LogicalSide#CLIENT logical client}.

* * @see Post - */ + * / @Cancelable public static class Pre extends RenderGuiEvent { @@ -78,7 +78,7 @@ public abstract class RenderGuiEvent extends Event * *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

- */ + * / public static class Post extends RenderGuiEvent { @ApiStatus.Internal @@ -88,3 +88,4 @@ public abstract class RenderGuiEvent extends Event } } } +*/ diff --git a/src/main/java/net/minecraftforge/client/event/RenderGuiOverlayEvent.java b/src/main/java/net/minecraftforge/client/event/RenderGuiOverlayEvent.java index c8bd73ad60..5a086d24b9 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderGuiOverlayEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderGuiOverlayEvent.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.event; import com.mojang.blaze3d.platform.Window; @@ -22,7 +23,7 @@ import org.jetbrains.annotations.ApiStatus; * * @see Pre * @see Post - */ + * / public abstract class RenderGuiOverlayEvent extends Event { private final Window window; @@ -70,7 +71,7 @@ public abstract class RenderGuiOverlayEvent extends Event * only on the {@linkplain LogicalSide#CLIENT logical client}.

* * @see Post - */ + * / @Cancelable public static class Pre extends RenderGuiOverlayEvent { @@ -88,7 +89,7 @@ public abstract class RenderGuiOverlayEvent extends Event * *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

- */ + * / public static class Post extends RenderGuiOverlayEvent { @ApiStatus.Internal @@ -98,3 +99,4 @@ public abstract class RenderGuiOverlayEvent extends Event } } } +*/ diff --git a/src/main/java/net/minecraftforge/client/event/RenderItemInFrameEvent.java b/src/main/java/net/minecraftforge/client/event/RenderItemInFrameEvent.java index a0e39146b5..289aea55e6 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderItemInFrameEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderItemInFrameEvent.java @@ -30,8 +30,7 @@ import org.jetbrains.annotations.ApiStatus; * @see ItemFrameRenderer */ @Cancelable -public class RenderItemInFrameEvent extends Event -{ +public class RenderItemInFrameEvent extends Event { private final ItemStack itemStack; private final ItemFrame itemFrameEntity; private final ItemFrameRenderer renderer; @@ -40,9 +39,7 @@ public class RenderItemInFrameEvent extends Event private final int packedLight; @ApiStatus.Internal - public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer renderItemFrame, PoseStack poseStack, - MultiBufferSource multiBufferSource, int packedLight) - { + public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { itemStack = itemFrame.getItem(); itemFrameEntity = itemFrame; renderer = renderItemFrame; @@ -54,40 +51,35 @@ public class RenderItemInFrameEvent extends Event /** * {@return the item stack being rendered} */ - public ItemStack getItemStack() - { + public ItemStack getItemStack() { return itemStack; } /** * {@return the item frame entity} */ - public ItemFrame getItemFrameEntity() - { + public ItemFrame getItemFrameEntity() { return itemFrameEntity; } /** * {@return the renderer for the item frame entity} */ - public ItemFrameRenderer getRenderer() - { + public ItemFrameRenderer getRenderer() { return renderer; } /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() - { + public PoseStack getPoseStack() { return poseStack; } /** * {@return the source of rendering buffers} */ - public MultiBufferSource getMultiBufferSource() - { + public MultiBufferSource getMultiBufferSource() { return multiBufferSource; } @@ -96,8 +88,7 @@ public class RenderItemInFrameEvent extends Event * * @see LightTexture */ - public int getPackedLight() - { + public int getPackedLight() { return packedLight; } } diff --git a/src/main/java/net/minecraftforge/client/event/RenderLevelStageEvent.java b/src/main/java/net/minecraftforge/client/event/RenderLevelStageEvent.java index 647ae7353d..e96b307043 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderLevelStageEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderLevelStageEvent.java @@ -43,14 +43,14 @@ import org.joml.Matrix4f; public class RenderLevelStageEvent extends Event { private final Stage stage; private final LevelRenderer levelRenderer; - private final PoseStack poseStack; + private final Matrix4f poseStack; private final Matrix4f projectionMatrix; private final int renderTick; private final float partialTick; private final Camera camera; private final Frustum frustum; - public RenderLevelStageEvent(Stage stage, LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, float partialTick, Camera camera, Frustum frustum) { + public RenderLevelStageEvent(Stage stage, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, float partialTick, Camera camera, Frustum frustum) { this.stage = stage; this.levelRenderer = levelRenderer; this.poseStack = poseStack; @@ -79,7 +79,7 @@ public class RenderLevelStageEvent extends Event { /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() { + public Matrix4f getPoseStack() { return poseStack; } @@ -235,7 +235,7 @@ public class RenderLevelStageEvent extends Event { /** Internal just to make our patch smaller, it just fires the event. If you have good reason for this to be external, ask. */ @ApiStatus.Internal - public void dispatch(LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) { + public void dispatch(LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) { var mc = Minecraft.getInstance(); var profiler = mc.getProfiler(); profiler.push(this.toString()); diff --git a/src/main/java/net/minecraftforge/client/event/RenderLivingEvent.java b/src/main/java/net/minecraftforge/client/event/RenderLivingEvent.java index 9eb7859ae5..fbf6e06ad9 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderLivingEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderLivingEvent.java @@ -31,8 +31,7 @@ import org.jetbrains.annotations.ApiStatus; * @see RenderPlayerEvent * @see LivingEntityRenderer */ -public abstract class RenderLivingEvent> extends Event -{ +public abstract class RenderLivingEvent> extends Event { private final LivingEntity entity; private final LivingEntityRenderer renderer; private final float partialTick; @@ -41,9 +40,7 @@ public abstract class RenderLivingEvent renderer, float partialTick, PoseStack poseStack, - MultiBufferSource multiBufferSource, int packedLight) - { + protected RenderLivingEvent(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { this.entity = entity; this.renderer = renderer; this.partialTick = partialTick; @@ -55,40 +52,35 @@ public abstract class RenderLivingEvent getRenderer() - { + public LivingEntityRenderer getRenderer() { return renderer; } /** * {@return the partial tick} */ - public float getPartialTick() - { + public float getPartialTick() { return partialTick; } /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() - { + public PoseStack getPoseStack() { return poseStack; } /** * {@return the source of rendering buffers} */ - public MultiBufferSource getMultiBufferSource() - { + public MultiBufferSource getMultiBufferSource() { return multiBufferSource; } @@ -97,8 +89,7 @@ public abstract class RenderLivingEvent the model for the living entity */ @Cancelable - public static class Pre> extends RenderLivingEvent - { + public static class Pre> extends RenderLivingEvent { @ApiStatus.Internal - public Pre(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) - { + public Pre(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight); } } @@ -137,11 +126,9 @@ public abstract class RenderLivingEvent the living entity that was rendered * @param the model for the living entity */ - public static class Post> extends RenderLivingEvent - { + public static class Post> extends RenderLivingEvent { @ApiStatus.Internal - public Post(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) - { + public Post(LivingEntity entity, LivingEntityRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight); } } diff --git a/src/main/java/net/minecraftforge/client/event/RenderNameTagEvent.java b/src/main/java/net/minecraftforge/client/event/RenderNameTagEvent.java index aafaa8f1c1..27df85a2c7 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderNameTagEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderNameTagEvent.java @@ -33,8 +33,7 @@ import org.jetbrains.annotations.ApiStatus; * @see EntityRenderer */ @Event.HasResult -public class RenderNameTagEvent extends EntityEvent -{ +public class RenderNameTagEvent extends EntityEvent { private Component nameplateContent; private final Component originalContent; private final EntityRenderer entityRenderer; @@ -44,8 +43,7 @@ public class RenderNameTagEvent extends EntityEvent private final float partialTick; @ApiStatus.Internal - public RenderNameTagEvent(Entity entity, Component content, EntityRenderer entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) - { + public RenderNameTagEvent(Entity entity, Component content, EntityRenderer entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) { super(entity); this.originalContent = content; this.setContent(this.originalContent); @@ -61,48 +59,42 @@ public class RenderNameTagEvent extends EntityEvent * * @param contents the new text */ - public void setContent(Component contents) - { + public void setContent(Component contents) { this.nameplateContent = contents; } /** * {@return the text on the nameplate that will be rendered, if the event is not {@link Result#DENY DENIED}} */ - public Component getContent() - { + public Component getContent() { return this.nameplateContent; } /** * {@return the original text on the nameplate} */ - public Component getOriginalContent() - { + public Component getOriginalContent() { return this.originalContent; } /** * {@return the entity renderer rendering the nameplate} */ - public EntityRenderer getEntityRenderer() - { + public EntityRenderer getEntityRenderer() { return this.entityRenderer; } /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() - { + public PoseStack getPoseStack() { return this.poseStack; } /** * {@return the source of rendering buffers} */ - public MultiBufferSource getMultiBufferSource() - { + public MultiBufferSource getMultiBufferSource() { return this.multiBufferSource; } @@ -111,16 +103,14 @@ public class RenderNameTagEvent extends EntityEvent * * @see net.minecraft.client.renderer.LightTexture */ - public int getPackedLight() - { + public int getPackedLight() { return this.packedLight; } /** * {@return the partial tick} */ - public float getPartialTick() - { + public float getPartialTick() { return this.partialTick; } } diff --git a/src/main/java/net/minecraftforge/client/event/RenderPlayerEvent.java b/src/main/java/net/minecraftforge/client/event/RenderPlayerEvent.java index 4990d62e53..3d754dbf24 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderPlayerEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderPlayerEvent.java @@ -24,8 +24,7 @@ import org.jetbrains.annotations.ApiStatus; * @see RenderPlayerEvent.Post * @see PlayerRenderer */ -public abstract class RenderPlayerEvent extends PlayerEvent -{ +public abstract class RenderPlayerEvent extends PlayerEvent { private final PlayerRenderer renderer; private final float partialTick; private final PoseStack poseStack; @@ -33,8 +32,7 @@ public abstract class RenderPlayerEvent extends PlayerEvent private final int packedLight; @ApiStatus.Internal - protected RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) - { + protected RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { super(player); this.renderer = renderer; this.partialTick = partialTick; @@ -46,32 +44,28 @@ public abstract class RenderPlayerEvent extends PlayerEvent /** * {@return the player entity renderer} */ - public PlayerRenderer getRenderer() - { + public PlayerRenderer getRenderer() { return renderer; } /** * {@return the partial tick} */ - public float getPartialTick() - { + public float getPartialTick() { return partialTick; } /** * {@return the pose stack used for rendering} */ - public PoseStack getPoseStack() - { + public PoseStack getPoseStack() { return poseStack; } /** * {@return the source of rendering buffers} */ - public MultiBufferSource getMultiBufferSource() - { + public MultiBufferSource getMultiBufferSource() { return multiBufferSource; } @@ -80,8 +74,7 @@ public abstract class RenderPlayerEvent extends PlayerEvent * * @see LightTexture */ - public int getPackedLight() - { + public int getPackedLight() { return packedLight; } @@ -97,11 +90,9 @@ public abstract class RenderPlayerEvent extends PlayerEvent * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ @Cancelable - public static class Pre extends RenderPlayerEvent - { + public static class Pre extends RenderPlayerEvent { @ApiStatus.Internal - public Pre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) - { + public Pre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight); } } @@ -114,11 +105,9 @@ public abstract class RenderPlayerEvent extends PlayerEvent *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class Post extends RenderPlayerEvent - { + public static class Post extends RenderPlayerEvent { @ApiStatus.Internal - public Post(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) - { + public Post(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) { super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight); } } diff --git a/src/main/java/net/minecraftforge/client/event/ViewportEvent.java b/src/main/java/net/minecraftforge/client/event/ViewportEvent.java index 1520de9f74..4cd977dc58 100644 --- a/src/main/java/net/minecraftforge/client/event/ViewportEvent.java +++ b/src/main/java/net/minecraftforge/client/event/ViewportEvent.java @@ -30,15 +30,13 @@ import org.jetbrains.annotations.ApiStatus; * @see ComputeCameraAngles * @see ComputeFov */ -public abstract class ViewportEvent extends Event -{ +public abstract class ViewportEvent extends Event { private final GameRenderer renderer; private final Camera camera; private final double partialTick; @ApiStatus.Internal - public ViewportEvent(GameRenderer renderer, Camera camera, double partialTick) - { + public ViewportEvent(GameRenderer renderer, Camera camera, double partialTick) { this.renderer = renderer; this.camera = camera; this.partialTick = partialTick; @@ -47,24 +45,21 @@ public abstract class ViewportEvent extends Event /** * {@return the game renderer} */ - public GameRenderer getRenderer() - { + public GameRenderer getRenderer() { return renderer; } /** * {@return the camera information} */ - public Camera getCamera() - { + public Camera getCamera() { return camera; } /** * {@return the partial tick} */ - public double getPartialTick() - { + public double getPartialTick() { return partialTick; } @@ -78,8 +73,7 @@ public abstract class ViewportEvent extends Event * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ @Cancelable - public static class RenderFog extends ViewportEvent - { + public static class RenderFog extends ViewportEvent { private final FogMode mode; private final FogType type; private float farPlaneDistance; @@ -87,8 +81,7 @@ public abstract class ViewportEvent extends Event private FogShape fogShape; @ApiStatus.Internal - public RenderFog(FogMode mode, FogType type, Camera camera, float partialTicks, float nearPlaneDistance, float farPlaneDistance, FogShape fogShape) - { + public RenderFog(FogMode mode, FogType type, Camera camera, float partialTicks, float nearPlaneDistance, float farPlaneDistance, FogShape fogShape) { super(Minecraft.getInstance().gameRenderer, camera, partialTicks); this.mode = mode; this.type = type; @@ -100,40 +93,35 @@ public abstract class ViewportEvent extends Event /** * {@return the mode of fog being rendered} */ - public FogMode getMode() - { + public FogMode getMode() { return mode; } /** * {@return the type of fog being rendered} */ - public FogType getType() - { + public FogType getType() { return type; } /** * {@return the distance to the far plane where the fog ends} */ - public float getFarPlaneDistance() - { + public float getFarPlaneDistance() { return farPlaneDistance; } /** * {@return the distance to the near plane where the fog starts} */ - public float getNearPlaneDistance() - { + public float getNearPlaneDistance() { return nearPlaneDistance; } /** * {@return the shape of the fog being rendered} */ - public FogShape getFogShape() - { + public FogShape getFogShape() { return fogShape; } @@ -143,8 +131,7 @@ public abstract class ViewportEvent extends Event * @param distance the new distance to the far place * @see #scaleFarPlaneDistance(float) */ - public void setFarPlaneDistance(float distance) - { + public void setFarPlaneDistance(float distance) { farPlaneDistance = distance; } @@ -154,8 +141,7 @@ public abstract class ViewportEvent extends Event * @param distance the new distance to the near plane * @see #scaleNearPlaneDistance(float) */ - public void setNearPlaneDistance(float distance) - { + public void setNearPlaneDistance(float distance) { nearPlaneDistance = distance; } @@ -164,8 +150,7 @@ public abstract class ViewportEvent extends Event * * @param shape the new shape of the fog */ - public void setFogShape(FogShape shape) - { + public void setFogShape(FogShape shape) { fogShape = shape; } @@ -174,8 +159,7 @@ public abstract class ViewportEvent extends Event * * @param factor the factor to scale the far plane distance by */ - public void scaleFarPlaneDistance(float factor) - { + public void scaleFarPlaneDistance(float factor) { farPlaneDistance *= factor; } @@ -184,8 +168,7 @@ public abstract class ViewportEvent extends Event * * @param factor the factor to scale the near plane distance by */ - public void scaleNearPlaneDistance(float factor) - { + public void scaleNearPlaneDistance(float factor) { nearPlaneDistance *= factor; } } @@ -198,15 +181,13 @@ public abstract class ViewportEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class ComputeFogColor extends ViewportEvent - { + public static class ComputeFogColor extends ViewportEvent { private float red; private float green; private float blue; @ApiStatus.Internal - public ComputeFogColor(Camera camera, float partialTicks, float red, float green, float blue) - { + public ComputeFogColor(Camera camera, float partialTicks, float red, float green, float blue) { super(Minecraft.getInstance().gameRenderer, camera, partialTicks); this.setRed(red); this.setGreen(green); @@ -216,8 +197,7 @@ public abstract class ViewportEvent extends Event /** * {@return the red color value of the fog} */ - public float getRed() - { + public float getRed() { return red; } @@ -226,16 +206,14 @@ public abstract class ViewportEvent extends Event * * @param red the new red color value */ - public void setRed(float red) - { + public void setRed(float red) { this.red = red; } /** * {@return the green color value of the fog} */ - public float getGreen() - { + public float getGreen() { return green; } @@ -244,16 +222,14 @@ public abstract class ViewportEvent extends Event * * @param green the new blue color value */ - public void setGreen(float green) - { + public void setGreen(float green) { this.green = green; } /** * {@return the blue color value of the fog} */ - public float getBlue() - { + public float getBlue() { return blue; } @@ -262,8 +238,7 @@ public abstract class ViewportEvent extends Event * * @param blue the new blue color value */ - public void setBlue(float blue) - { + public void setBlue(float blue) { this.blue = blue; } } @@ -277,15 +252,13 @@ public abstract class ViewportEvent extends Event *

This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain LogicalSide#CLIENT logical client}.

*/ - public static class ComputeCameraAngles extends ViewportEvent - { + public static class ComputeCameraAngles extends ViewportEvent { private float yaw; private float pitch; private float roll; @ApiStatus.Internal - public ComputeCameraAngles(GameRenderer renderer, Camera camera, double renderPartialTicks, float yaw, float pitch, float roll) - { + public ComputeCameraAngles(GameRenderer renderer, Camera camera, double renderPartialTicks, float yaw, float pitch, float roll) { super(renderer, camera, renderPartialTicks); this.setYaw(yaw); this.setPitch(pitch); @@ -295,8 +268,7 @@ public abstract class ViewportEvent extends Event /** * {@return the yaw of the player's camera} */ - public float getYaw() - { + public float getYaw() { return yaw; } @@ -305,16 +277,14 @@ public abstract class ViewportEvent extends Event * * @param yaw the new yaw */ - public void setYaw(float yaw) - { + public void setYaw(float yaw) { this.yaw = yaw; } /** * {@return the pitch of the player's camera} */ - public float getPitch() - { + public float getPitch() { return pitch; } @@ -323,16 +293,14 @@ public abstract class ViewportEvent extends Event * * @param pitch the new pitch */ - public void setPitch(float pitch) - { + public void setPitch(float pitch) { this.pitch = pitch; } /** * {@return the roll of the player's camera} */ - public float getRoll() - { + public float getRoll() { return roll; } @@ -341,8 +309,7 @@ public abstract class ViewportEvent extends Event * * @param roll the new roll */ - public void setRoll(float roll) - { + public void setRoll(float roll) { this.roll = roll; } } @@ -358,14 +325,12 @@ public abstract class ViewportEvent extends Event * * @see ComputeFovModifierEvent */ - public static class ComputeFov extends ViewportEvent - { + public static class ComputeFov extends ViewportEvent { private final boolean usedConfiguredFov; private double fov; @ApiStatus.Internal - public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, double fov, boolean usedConfiguredFov) - { + public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, double fov, boolean usedConfiguredFov) { super(renderer, camera, renderPartialTicks); this.usedConfiguredFov = usedConfiguredFov; this.setFOV(fov); @@ -374,8 +339,7 @@ public abstract class ViewportEvent extends Event /** * {@return the raw field of view value} */ - public double getFOV() - { + public double getFOV() { return fov; } @@ -384,16 +348,14 @@ public abstract class ViewportEvent extends Event * * @param fov the new FOV value */ - public void setFOV(double fov) - { + public void setFOV(double fov) { this.fov = fov; } /** * {@return whether the base fov value started with a constant or was sourced from the fov set in the options} */ - public boolean usedConfiguredFov() - { + public boolean usedConfiguredFov() { return usedConfiguredFov; } } diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgeBakedModel.java b/src/main/java/net/minecraftforge/client/extensions/IForgeBakedModel.java index 382f8d6fb6..4db1bd5df8 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgeBakedModel.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgeBakedModel.java @@ -30,29 +30,24 @@ import java.util.List; /** * Extension interface for {@link IForgeBakedModel}. */ -public interface IForgeBakedModel -{ - private BakedModel self() - { - return (BakedModel) this; +public interface IForgeBakedModel { + private BakedModel self() { + return (BakedModel)this; } /** * A null {@link RenderType} is used for the breaking overlay as well as non-standard rendering, so models should return all their quads. */ @NotNull - default List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) - { + default List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) { return self().getQuads(state, side, rand); } - default boolean useAmbientOcclusion(BlockState state) - { + default boolean useAmbientOcclusion(BlockState state) { return self().useAmbientOcclusion(); } - default boolean useAmbientOcclusion(BlockState state, RenderType renderType) - { + default boolean useAmbientOcclusion(BlockState state, RenderType renderType) { return self().useAmbientOcclusion(state); } @@ -60,19 +55,16 @@ public interface IForgeBakedModel * Applies a transform for the given {@link ItemTransforms.TransformType} and {@code applyLeftHandTransform}, and * returns the model to be rendered. */ - default BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform) - { + default BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform) { self().getTransforms().getTransform(transformType).apply(applyLeftHandTransform, poseStack); return self(); } - default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) - { + default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) { return modelData; } - default TextureAtlasSprite getParticleIcon(@NotNull ModelData data) - { + default TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { return self().getParticleIcon(); } @@ -82,8 +74,7 @@ public interface IForgeBakedModel *

* By default, defers query to {@link ItemBlockRenderTypes}. */ - default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) - { + default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) { return ItemBlockRenderTypes.getRenderLayers(state); } @@ -97,8 +88,7 @@ public interface IForgeBakedModel * * @see #getRenderPasses(ItemStack, boolean) */ - default List getRenderTypes(ItemStack itemStack, boolean fabulous) - { + default List getRenderTypes(ItemStack itemStack, boolean fabulous) { return List.of(RenderTypeHelper.getFallbackItemRenderType(itemStack, self(), fabulous)); } @@ -110,8 +100,7 @@ public interface IForgeBakedModel * * @see #getRenderTypes(ItemStack, boolean) */ - default List getRenderPasses(ItemStack itemStack, boolean fabulous) - { + default List getRenderPasses(ItemStack itemStack, boolean fabulous) { return List.of(self()); } } diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgeDimensionSpecialEffects.java b/src/main/java/net/minecraftforge/client/extensions/IForgeDimensionSpecialEffects.java index 4e87e29cb2..df064208b9 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgeDimensionSpecialEffects.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgeDimensionSpecialEffects.java @@ -16,11 +16,9 @@ import org.joml.Vector3f; /** * Extension interface for {@link DimensionSpecialEffects}. */ -public interface IForgeDimensionSpecialEffects -{ - private DimensionSpecialEffects self() - { - return (DimensionSpecialEffects) this; +public interface IForgeDimensionSpecialEffects { + private DimensionSpecialEffects self() { + return (DimensionSpecialEffects)this; } /** @@ -28,8 +26,7 @@ public interface IForgeDimensionSpecialEffects * * @return true to prevent vanilla cloud rendering */ - default boolean renderClouds(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, double camX, double camY, double camZ, Matrix4f projectionMatrix) - { + default boolean renderClouds(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, double camX, double camY, double camZ, Matrix4f projectionMatrix) { return false; } @@ -38,8 +35,7 @@ public interface IForgeDimensionSpecialEffects * * @return true to prevent vanilla sky rendering */ - default boolean renderSky(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, Camera camera, Matrix4f projectionMatrix, boolean isFoggy, Runnable setupFog) - { + default boolean renderSky(ClientLevel level, int ticks, float partialTick, Camera camera, Matrix4f projectionMatrix, boolean isFoggy, Runnable setupFog) { return false; } @@ -48,8 +44,7 @@ public interface IForgeDimensionSpecialEffects * * @return true to prevent vanilla snow and rain rendering */ - default boolean renderSnowAndRain(ClientLevel level, int ticks, float partialTick, LightTexture lightTexture, double camX, double camY, double camZ) - { + default boolean renderSnowAndRain(ClientLevel level, int ticks, float partialTick, LightTexture lightTexture, double camX, double camY, double camZ) { return false; } @@ -58,8 +53,7 @@ public interface IForgeDimensionSpecialEffects * * @return true to prevent vanilla rain ticking */ - default boolean tickRain(ClientLevel level, int ticks, Camera camera) - { + default boolean tickRain(ClientLevel level, int ticks, Camera camera) { return false; } diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgeModelBaker.java b/src/main/java/net/minecraftforge/client/extensions/IForgeModelBaker.java index fb15970e58..cc907bc319 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgeModelBaker.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgeModelBaker.java @@ -13,8 +13,7 @@ import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; import java.util.function.Function; -public interface IForgeModelBaker -{ +public interface IForgeModelBaker { @Nullable BakedModel bake(ResourceLocation location, ModelState state, Function sprites); diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgePoseStack.java b/src/main/java/net/minecraftforge/client/extensions/IForgePoseStack.java index 94e73a5cc5..897fc79eff 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgePoseStack.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgePoseStack.java @@ -12,11 +12,9 @@ import org.joml.Vector3f; /** * Extension interface for {@link com.mojang.blaze3d.vertex.PoseStack}. */ -public interface IForgePoseStack -{ - private PoseStack self() - { - return (PoseStack) this; +public interface IForgePoseStack { + private PoseStack self() { + return (PoseStack)this; } /** @@ -25,8 +23,7 @@ public interface IForgePoseStack * * @param transformation the transformation to push */ - default void pushTransformation(Transformation transformation) - { + default void pushTransformation(Transformation transformation) { final PoseStack self = self(); self.pushPose(); diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgeVertexConsumer.java b/src/main/java/net/minecraftforge/client/extensions/IForgeVertexConsumer.java index e758cd22d7..b9efeb089c 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgeVertexConsumer.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgeVertexConsumer.java @@ -18,11 +18,9 @@ import java.nio.ByteBuffer; /** * Extension interface for {@link VertexConsumer}. */ -public interface IForgeVertexConsumer -{ - private VertexConsumer self() - { - return (VertexConsumer) this; +public interface IForgeVertexConsumer { + private VertexConsumer self() { + return (VertexConsumer)this; } /** @@ -30,21 +28,18 @@ public interface IForgeVertexConsumer *

* If the consumer needs to store the data for later use, it must copy it. There are no guarantees on immutability. */ - default VertexConsumer misc(VertexFormatElement element, int... rawData) - { + default VertexConsumer misc(VertexFormatElement element, int... rawData) { return self(); } /** * Variant with no per-vertex shading. */ - default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay, boolean readExistingColor) - { + default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay, boolean readExistingColor) { self().putBulkData(pose, bakedQuad, new float[] { 1.0F, 1.0F, 1.0F, 1.0F }, red, green, blue, alpha, new int[] { packedLight, packedLight, packedLight, packedLight }, packedOverlay, readExistingColor); } - default int applyBakedLighting(int packedLight, ByteBuffer data) - { + default int applyBakedLighting(int packedLight, ByteBuffer data) { int bl = packedLight & 0xFFFF; int sl = (packedLight >> 16) & 0xFFFF; int offset = IQuadTransformer.UV2 * 4; // int offset for vertex 0 * 4 bytes per int @@ -55,13 +50,11 @@ public interface IForgeVertexConsumer return bl | (sl << 16); } - default void applyBakedNormals(Vector3f generated, ByteBuffer data, Matrix3f normalTransform) - { + default void applyBakedNormals(Vector3f generated, ByteBuffer data, Matrix3f normalTransform) { byte nx = data.get(28); byte ny = data.get(29); byte nz = data.get(30); - if (nx != 0 || ny != 0 || nz != 0) - { + if (nx != 0 || ny != 0 || nz != 0) { generated.set(nx / 127f, ny / 127f, nz / 127f); generated.mul(normalTransform); } diff --git a/src/main/java/net/minecraftforge/client/extensions/common/IClientBlockExtensions.java b/src/main/java/net/minecraftforge/client/extensions/common/IClientBlockExtensions.java index 48dd2520ca..bf7b8eaafe 100644 --- a/src/main/java/net/minecraftforge/client/extensions/common/IClientBlockExtensions.java +++ b/src/main/java/net/minecraftforge/client/extensions/common/IClientBlockExtensions.java @@ -30,23 +30,20 @@ import java.util.function.Consumer; * * @see Block#initializeClient(Consumer) */ -public interface IClientBlockExtensions -{ +public interface IClientBlockExtensions { IClientBlockExtensions DEFAULT = new IClientBlockExtensions() { }; - static IClientBlockExtensions of(BlockState state) - { + static IClientBlockExtensions of(BlockState state) { return of(state.getBlock()); } - static IClientBlockExtensions of(Block block) - { + static IClientBlockExtensions of(Block block) { return block.getRenderPropertiesInternal() instanceof IClientBlockExtensions e ? e : DEFAULT; } /** * Spawn a digging particle effect in the level, this is a wrapper - * around EffectRenderer.addBlockHitEffects to allow the block more + * around EffectRenderer.crack to allow the block more * control over the particles. Useful when you have entirely different * texture sheets for different sides/locations in the level. * @@ -56,8 +53,7 @@ public interface IClientBlockExtensions * @param manager A reference to the current particle manager. * @return True to prevent vanilla digging particles form spawning. */ - default boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) - { + default boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) { return false; } @@ -72,8 +68,7 @@ public interface IClientBlockExtensions * @param manager A reference to the current particle manager. * @return True to prevent vanilla break particles from spawning. */ - default boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) - { + default boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) { return !state.shouldSpawnTerrainParticles(); } @@ -90,27 +85,20 @@ public interface IClientBlockExtensions * @param originalColor The current fog color, You are not expected to use this, Return as the default if applicable. * @return The new fog color. */ - default Vector3d getFogColor(BlockState state, LevelReader level, BlockPos pos, Entity entity, Vector3d originalColor, float partialTick) - { + default Vector3d getFogColor(BlockState state, LevelReader level, BlockPos pos, Entity entity, Vector3d originalColor, float partialTick) { FluidState fluidState = level.getFluidState(pos); - if (fluidState.is(FluidTags.WATER)) - { + if (fluidState.is(FluidTags.WATER)) { float f12 = 0.0F; - if (entity instanceof LivingEntity) - { - LivingEntity ent = (LivingEntity) entity; + if (entity instanceof LivingEntity ent) { f12 = (float) EnchantmentHelper.getRespiration(ent) * 0.2F; - if (ent.hasEffect(MobEffects.WATER_BREATHING)) - { + if (ent.hasEffect(MobEffects.WATER_BREATHING)) { f12 = f12 * 0.3F + 0.6F; } } return new Vector3d(0.02F + f12, 0.02F + f12, 0.2F + f12); - } - else if (fluidState.is(FluidTags.LAVA)) - { + } else if (fluidState.is(FluidTags.LAVA)) { return new Vector3d(0.6F, 0.1F, 0.0F); } return originalColor; @@ -124,8 +112,7 @@ public interface IClientBlockExtensions * @param pos The position of the block * @return {@code true} if the particles should be tinted. */ - default boolean areBreakingParticlesTinted(BlockState state, ClientLevel level, BlockPos pos) - { + default boolean areBreakingParticlesTinted(BlockState state, ClientLevel level, BlockPos pos) { return !state.is(Blocks.GRASS_BLOCK); } } diff --git a/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java b/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java index 3a7d858d4d..8a00f73b49 100644 --- a/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java +++ b/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java @@ -19,17 +19,14 @@ import java.util.function.Consumer; * * @see MobEffect#initializeClient(Consumer) */ -public interface IClientMobEffectExtensions -{ +public interface IClientMobEffectExtensions { IClientMobEffectExtensions DEFAULT = new IClientMobEffectExtensions() { }; - static IClientMobEffectExtensions of(MobEffectInstance instance) - { - return of(instance.getEffect()); + static IClientMobEffectExtensions of(MobEffectInstance instance) { + return of(instance.getEffect().value()); } - static IClientMobEffectExtensions of(MobEffect effect) - { + static IClientMobEffectExtensions of(MobEffect effect) { return effect.getEffectRendererInternal() instanceof IClientMobEffectExtensions r ? r : DEFAULT; } @@ -38,8 +35,7 @@ public interface IClientMobEffectExtensions *

* By default, this returns {@code true}. */ - default boolean isVisibleInInventory(MobEffectInstance instance) - { + default boolean isVisibleInInventory(MobEffectInstance instance) { return true; } @@ -48,8 +44,7 @@ public interface IClientMobEffectExtensions *

* By default, this returns {@code true}. */ - default boolean isVisibleInGui(MobEffectInstance instance) - { + default boolean isVisibleInGui(MobEffectInstance instance) { return true; } @@ -65,8 +60,7 @@ public interface IClientMobEffectExtensions * @param blitOffset The blit offset * @return true to prevent default rendering, false otherwise */ - default boolean renderInventoryIcon(MobEffectInstance instance, EffectRenderingInventoryScreen screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) - { + default boolean renderInventoryIcon(MobEffectInstance instance, EffectRenderingInventoryScreen screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) { return false; } @@ -81,8 +75,7 @@ public interface IClientMobEffectExtensions * @param blitOffset The blit offset * @return true to prevent default rendering, false otherwise */ - default boolean renderInventoryText(MobEffectInstance instance, EffectRenderingInventoryScreen screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) - { + default boolean renderInventoryText(MobEffectInstance instance, EffectRenderingInventoryScreen screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) { return false; } @@ -99,8 +92,7 @@ public interface IClientMobEffectExtensions * @param alpha The alpha value. Blinks when the effect is about to run out * @return true to prevent default rendering, false otherwise */ - default boolean renderGuiIcon(MobEffectInstance instance, Gui gui, GuiGraphics guiGraphics, int x, int y, float z, float alpha) - { + default boolean renderGuiIcon(MobEffectInstance instance, Gui gui, GuiGraphics guiGraphics, int x, int y, float z, float alpha) { return false; } } diff --git a/src/main/java/net/minecraftforge/client/gui/TitleScreenModUpdateIndicator.java b/src/main/java/net/minecraftforge/client/gui/TitleScreenModUpdateIndicator.java index 079e33870c..34bddc9e5f 100644 --- a/src/main/java/net/minecraftforge/client/gui/TitleScreenModUpdateIndicator.java +++ b/src/main/java/net/minecraftforge/client/gui/TitleScreenModUpdateIndicator.java @@ -66,7 +66,7 @@ public class TitleScreenModUpdateIndicator extends Screen public static TitleScreenModUpdateIndicator init(TitleScreen guiMainMenu, Button modButton) { TitleScreenModUpdateIndicator titleScreenModUpdateIndicator = new TitleScreenModUpdateIndicator(modButton); - titleScreenModUpdateIndicator.resize(guiMainMenu.getMinecraft(), guiMainMenu.width, guiMainMenu.height); + //titleScreenModUpdateIndicator.resize(guiMainMenu.getMinecraft(), guiMainMenu.width, guiMainMenu.height); titleScreenModUpdateIndicator.init(); return titleScreenModUpdateIndicator; } diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeGui.java b/src/main/java/net/minecraftforge/client/gui/overlay/ForgeGui.java index e049fe9726..3c010cb736 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeGui.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/ForgeGui.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.gui.overlay; import com.mojang.blaze3d.platform.Window; @@ -47,7 +48,7 @@ import java.util.List; /** * Forge wrapper around {@link Gui} to be able to render {@link IGuiOverlay HUD overlays}. - */ + * / public class ForgeGui extends Gui { private static final Logger LOGGER = LogManager.getLogger(); @@ -55,14 +56,14 @@ public class ForgeGui extends Gui { /* * If the Euclidean distance to the moused-over block in meters is less than this value, the "Looking at" text will appear on the debug overlay. - */ + * / public static double rayTraceDistance = 20.0D; public int leftHeight = 39; public int rightHeight = 39; public ForgeGui(Minecraft mc) { - super(mc, mc.getItemRenderer()); + super(mc); this.debugOverlay = new OverlayAccess(mc); } @@ -457,7 +458,7 @@ public class ForgeGui extends Gui { guiGraphics.pose().translate(event.getPosX(), (event.getPosY() - height + 40) / chat.getScale(), 0.0D); int mouseX = Mth.floor(minecraft.mouseHandler.xpos() * window.getGuiScaledWidth() / window.getScreenWidth()); int mouseY = Mth.floor(minecraft.mouseHandler.ypos() * window.getGuiScaledHeight() / window.getScreenHeight()); - chat.render(guiGraphics, tickCount, mouseX, mouseY); + chat.render(guiGraphics, tickCount, mouseX, mouseY, false); guiGraphics.pose().popPose(); minecraft.getProfiler().pop(); @@ -533,3 +534,4 @@ public class ForgeGui extends Gui { @Override protected void renderLines(GuiGraphics gfx, List lines, boolean leftAlign) { super.renderLines(gfx, lines, leftAlign); } } } +*/ \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/GuiOverlayManager.java b/src/main/java/net/minecraftforge/client/gui/overlay/GuiOverlayManager.java index cd094a2c4a..d2d78911c1 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/GuiOverlayManager.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/GuiOverlayManager.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.gui.overlay; import com.google.common.collect.ImmutableList; @@ -21,7 +22,7 @@ import java.util.function.Function; * Manager for {@linkplain IGuiOverlay HUD overlays}. *

* Provides a lookup by ID, as well as all registered {@link IGuiOverlay overlays}. - */ + * / public final class GuiOverlayManager { private static ImmutableList OVERLAYS; @@ -29,7 +30,7 @@ public final class GuiOverlayManager /** * Retrieves an ordered list of all registered overlays. - */ + * / public static ImmutableList getOverlays() { return OVERLAYS; @@ -38,7 +39,7 @@ public final class GuiOverlayManager /** * Finds the overlay corresponding to a given ID. * Do not call this before {@link RegisterGuiOverlaysEvent} has finished firing. - */ + * / @Nullable public static NamedGuiOverlay findOverlay(ResourceLocation id) { @@ -63,7 +64,7 @@ public final class GuiOverlayManager /** * Pre-registers vanilla overlays so they are available for ordering. - */ + * / private static void preRegisterVanillaOverlays(HashMap overlays, ArrayList orderedOverlays) { for (var entry : VanillaGuiOverlay.values()) @@ -83,3 +84,4 @@ public final class GuiOverlayManager { } } +*/ diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/IGuiOverlay.java b/src/main/java/net/minecraftforge/client/gui/overlay/IGuiOverlay.java index 40b4eeaab8..bc413926e5 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/IGuiOverlay.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/IGuiOverlay.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.gui.overlay; import net.minecraft.client.gui.GuiGraphics; @@ -12,8 +13,9 @@ import net.minecraftforge.client.event.RegisterGuiOverlaysEvent; * A HUD overlay. * * @see RegisterGuiOverlaysEvent - */ + * / @FunctionalInterface public interface IGuiOverlay { void render(ForgeGui gui, GuiGraphics guiGraphics, float partialTick, int screenWidth, int screenHeight); } +*/ diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/NamedGuiOverlay.java b/src/main/java/net/minecraftforge/client/gui/overlay/NamedGuiOverlay.java index 03bf94ea19..a7c0a13968 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/NamedGuiOverlay.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/NamedGuiOverlay.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.gui.overlay; import net.minecraft.resources.ResourceLocation; @@ -14,7 +15,7 @@ import org.jetbrains.annotations.ApiStatus; * Useful to identify overlays in {@link net.minecraftforge.client.event.RenderGuiOverlayEvent}. *

* Users should not be instantiating this themselves. Retrieve from {@link GuiOverlayManager}. - */ + * / public record NamedGuiOverlay(ResourceLocation id, IGuiOverlay overlay) { @ApiStatus.Internal @@ -22,3 +23,4 @@ public record NamedGuiOverlay(ResourceLocation id, IGuiOverlay overlay) { } } +*/ diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/VanillaGuiOverlay.java b/src/main/java/net/minecraftforge/client/gui/overlay/VanillaGuiOverlay.java index 19011d0d4f..647746010b 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/VanillaGuiOverlay.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/VanillaGuiOverlay.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724 package net.minecraftforge.client.gui.overlay; import com.mojang.blaze3d.systems.RenderSystem; @@ -22,7 +23,7 @@ import org.lwjgl.opengl.GL11; /** * All the vanilla {@linkplain IGuiOverlay HUD overlays} in the order that they render. - */ + * / @SuppressWarnings("resource") public enum VanillaGuiOverlay { VIGNETTE("vignette", (gui, guiGraphics, partialTick, screenWidth, screenHeight) -> { @@ -233,3 +234,4 @@ public enum VanillaGuiOverlay { return type; } } +*/ diff --git a/src/main/java/net/minecraftforge/client/gui/widget/ScrollPanel.java b/src/main/java/net/minecraftforge/client/gui/widget/ScrollPanel.java index b047fdd29f..7ce820a792 100644 --- a/src/main/java/net/minecraftforge/client/gui/widget/ScrollPanel.java +++ b/src/main/java/net/minecraftforge/client/gui/widget/ScrollPanel.java @@ -155,7 +155,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen if (this.client.level != null) { this.drawGradientRect(guiGraphics, this.left, this.top, this.right, this.bottom, bgColorFrom, bgColorTo); - } else { // Draw dark dirt background + } /* else { // Draw dark dirt background RenderSystem.setShader(GameRenderer::getPositionTexColorShader); RenderSystem.setShaderTexture(0, Screen.BACKGROUND_LOCATION); final float texScale = 32.0F; @@ -166,6 +166,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen worldr.vertex(this.left, this.top, 0.0D).uv(this.left / texScale, (this.top + (int)this.scrollDistance) / texScale).color(0x20, 0x20, 0x20, 0xFF).endVertex(); tess.end(); } + */ } /** diff --git a/src/main/java/net/minecraftforge/client/model/ForgeFaceData.java b/src/main/java/net/minecraftforge/client/model/ForgeFaceData.java index ca0b046817..d46cd11b2b 100644 --- a/src/main/java/net/minecraftforge/client/model/ForgeFaceData.java +++ b/src/main/java/net/minecraftforge/client/model/ForgeFaceData.java @@ -39,7 +39,7 @@ public record ForgeFaceData(int color, int blockLight, int skyLight, boolean amb public static final ForgeFaceData DEFAULT = new ForgeFaceData(0xFFFFFFFF, 0, 0, true, false); - public static final Codec COLOR = ExtraCodecs.either(Codec.INT, Codec.STRING).xmap( + public static final Codec COLOR = Codec.either(Codec.INT, Codec.STRING).xmap( either -> either.map(Function.identity(), str -> (int) Long.parseLong(str, 16)), color -> Either.right(Integer.toHexString(color))); @@ -65,6 +65,6 @@ public record ForgeFaceData(int color, int blockLight, int skyLight, boolean amb { return fallback; } - return CODEC.parse(JsonOps.INSTANCE, obj).getOrThrow(false, JsonParseException::new); + return CODEC.parse(JsonOps.INSTANCE, obj).getOrThrow(JsonParseException::new); } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/client/model/ForgeItemModelShaper.java b/src/main/java/net/minecraftforge/client/model/ForgeItemModelShaper.java index eda74760c9..760d3f76a8 100644 --- a/src/main/java/net/minecraftforge/client/model/ForgeItemModelShaper.java +++ b/src/main/java/net/minecraftforge/client/model/ForgeItemModelShaper.java @@ -23,43 +23,36 @@ import java.util.Map; /** * Wrapper around {@link ItemModelShaper} that cleans up the internal maps to respect ID remapping. */ -public class ForgeItemModelShaper extends ItemModelShaper -{ +public class ForgeItemModelShaper extends ItemModelShaper { private final Map, ModelResourceLocation> locations = Maps.newHashMap(); private final Map, BakedModel> models = Maps.newHashMap(); - public ForgeItemModelShaper(ModelManager manager) - { + public ForgeItemModelShaper(ModelManager manager) { super(manager); } @Override @Nullable - public BakedModel getItemModel(Item item) - { + public BakedModel getItemModel(Item item) { return models.get(ForgeRegistries.ITEMS.getDelegateOrThrow(item)); } @Override - public void register(Item item, ModelResourceLocation location) - { + public void register(Item item, ModelResourceLocation location) { Holder.Reference key = ForgeRegistries.ITEMS.getDelegateOrThrow(item); locations.put(key, location); models.put(key, getModelManager().getModel(location)); } @Override - public void rebuildCache() - { + public void rebuildCache() { final ModelManager manager = this.getModelManager(); - for (Map.Entry, ModelResourceLocation> e : locations.entrySet()) - { + for (Map.Entry, ModelResourceLocation> e : locations.entrySet()) { models.put(e.getKey(), manager.getModel(e.getValue())); } } - public ModelResourceLocation getLocation(@NotNull ItemStack stack) - { + public ModelResourceLocation getLocation(@NotNull ItemStack stack) { ModelResourceLocation location = locations.get(ForgeRegistries.ITEMS.getDelegateOrThrow(stack.getItem())); return location == null ? ModelBakery.MISSING_MODEL_LOCATION : location; } diff --git a/src/main/java/net/minecraftforge/client/model/IDynamicBakedModel.java b/src/main/java/net/minecraftforge/client/model/IDynamicBakedModel.java index 4bb1f5cbf3..79452a6ca4 100644 --- a/src/main/java/net/minecraftforge/client/model/IDynamicBakedModel.java +++ b/src/main/java/net/minecraftforge/client/model/IDynamicBakedModel.java @@ -21,11 +21,9 @@ import java.util.List; /** * Convenience interface with default implementation of {@link IForgeBakedModel#getQuads(BlockState, Direction, RandomSource, ModelData, RenderType)}. */ -public interface IDynamicBakedModel extends BakedModel -{ +public interface IDynamicBakedModel extends BakedModel { @Override - default @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand) - { + default @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand) { return getQuads(state, side, rand, ModelData.EMPTY, null); } diff --git a/src/main/java/net/minecraftforge/client/model/IModelBuilder.java b/src/main/java/net/minecraftforge/client/model/IModelBuilder.java index 457082fcfa..ccb06792f5 100644 --- a/src/main/java/net/minecraftforge/client/model/IModelBuilder.java +++ b/src/main/java/net/minecraftforge/client/model/IModelBuilder.java @@ -80,7 +80,7 @@ public interface IModelBuilder> @Override public BakedModel build() { - return builder.build(renderTypes); + return builder.renderTypes(renderTypes).build(); } } diff --git a/src/main/java/net/minecraftforge/client/model/generators/loaders/ItemLayerModelBuilder.java b/src/main/java/net/minecraftforge/client/model/generators/loaders/ItemLayerModelBuilder.java index 2ace668347..cd4edc7f57 100644 --- a/src/main/java/net/minecraftforge/client/model/generators/loaders/ItemLayerModelBuilder.java +++ b/src/main/java/net/minecraftforge/client/model/generators/loaders/ItemLayerModelBuilder.java @@ -154,7 +154,9 @@ public class ItemLayerModelBuilder> extends CustomLoad for(Int2ObjectMap.Entry entry : this.faceData.int2ObjectEntrySet()) { - layerObj.add(String.valueOf(entry.getIntKey()), ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, entry.getValue()).getOrThrow(false, s -> {})); + layerObj.add(String.valueOf(entry.getIntKey()), ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, entry.getValue()).getOrThrow(s -> { + return new RuntimeException(); // Perhaps not the best way to deal with this? - MangoRage + })); } forgeData.add("layers", layerObj); diff --git a/src/main/java/net/minecraftforge/client/model/lighting/QuadLighter.java b/src/main/java/net/minecraftforge/client/model/lighting/QuadLighter.java index b3f0141643..bca9f81bdf 100644 --- a/src/main/java/net/minecraftforge/client/model/lighting/QuadLighter.java +++ b/src/main/java/net/minecraftforge/client/model/lighting/QuadLighter.java @@ -131,7 +131,7 @@ public abstract class QuadLighter } var color = quad.isTinted() ? getColorFast(quad.getTintIndex()) : WHITE; - consumer.putBulkData(pose, quad, brightness, color[0], color[1], color[2], lightmap, overlay, true); + consumer.putBulkData(pose, quad, brightness, color[0], color[1], color[2], 1.0f, lightmap, overlay, true); } private float[] getColorFast(int tintIndex) diff --git a/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java b/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java index 25566dfd1b..6625068cdb 100644 --- a/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java +++ b/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java @@ -6,13 +6,13 @@ package net.minecraftforge.client.model.obj; import com.google.common.collect.Maps; -import joptsimple.internal.Strings; import org.joml.Vector4f; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.NoSuchElementException; +import java.util.stream.Collectors; /** * An OBJ material library (MTL), composed of named {@link Material materials}. @@ -37,7 +37,7 @@ public class ObjMaterialLibrary { case "newmtl": { - String name = Strings.join(Arrays.copyOfRange(line, 1, line.length), " "); + String name = Arrays.asList(Arrays.copyOfRange(line, 1, line.length)).stream().collect(Collectors.joining(" ")); currentMaterial = new Material(name); materials.put(name, currentMaterial); break; diff --git a/src/main/java/net/minecraftforge/client/model/obj/ObjModel.java b/src/main/java/net/minecraftforge/client/model/obj/ObjModel.java index 5a51631fd2..71a4fb0c67 100644 --- a/src/main/java/net/minecraftforge/client/model/obj/ObjModel.java +++ b/src/main/java/net/minecraftforge/client/model/obj/ObjModel.java @@ -9,7 +9,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.mojang.math.Transformation; -import joptsimple.internal.Strings; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -145,7 +144,8 @@ public class ObjModel extends SimpleUnbakedGeometry case "usemtl": // Sets the current material (starts new mesh) { - String mat = Strings.join(Arrays.copyOfRange(line, 1, line.length), " "); + + String mat = Arrays.asList(Arrays.copyOfRange(line, 1, line.length)).stream().collect(Collectors.joining(" ")); ObjMaterialLibrary.Material newMat = mtllib.getMaterial(mat); if (!Objects.equals(newMat, currentMat)) { @@ -201,7 +201,7 @@ public class ObjModel extends SimpleUnbakedGeometry { String vertexData = line[i + 1]; String[] vertexParts = vertexData.split("/"); - int[] vertex = Arrays.stream(vertexParts).mapToInt(num -> Strings.isNullOrEmpty(num) ? 0 : Integer.parseInt(num)).toArray(); + int[] vertex = Arrays.stream(vertexParts).mapToInt(num -> num == null || num.isEmpty() ? 0 : Integer.parseInt(num)).toArray(); if (vertex[0] < 0) vertex[0] = model.positions.size() + vertex[0]; else vertex[0]--; if (vertex.length > 1) diff --git a/src/main/java/net/minecraftforge/client/model/renderable/CompositeRenderable.java b/src/main/java/net/minecraftforge/client/model/renderable/CompositeRenderable.java index f7adc8b82c..d6bc932bdc 100644 --- a/src/main/java/net/minecraftforge/client/model/renderable/CompositeRenderable.java +++ b/src/main/java/net/minecraftforge/client/model/renderable/CompositeRenderable.java @@ -60,7 +60,7 @@ public class CompositeRenderable implements IRenderable()); } - /** Replaced by {@link #getAll(InputConstants.Key) getAll} */ - @Deprecated(forRemoval = true, since = "1.20.1") - @Nullable - public KeyMapping get(InputConstants.Key keyCode) { - var activeModifier = KeyModifier.getActiveModifier(); - if (!activeModifier.matches(keyCode)) { - var binding = get(keyCode, activeModifier); - if (binding != null) - return binding; - } - return get(keyCode, KeyModifier.NONE); - } - - @Nullable - @Deprecated(forRemoval = true, since = "1.20.1") - private KeyMapping get(InputConstants.Key keyCode, KeyModifier keyModifier) { - var bindings = map.get(keyModifier).get(keyCode); - if (bindings != null) { - for (var binding : bindings) { - if (binding.isActiveAndMatches(keyCode)) - return binding; - } - } - return null; - } - /** * Returns all active keys associated with the given key code and the active * modifiers and conflict context. diff --git a/src/main/java/net/minecraftforge/common/BasicItemListing.java b/src/main/java/net/minecraftforge/common/BasicItemListing.java deleted file mode 100644 index b506185c46..0000000000 --- a/src/main/java/net/minecraftforge/common/BasicItemListing.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common; - -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.npc.VillagerTrades.ItemListing; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.trading.MerchantOffer; - -/** - * A default, exposed implementation of ITrade. All of the other implementations of ITrade (in VillagerTrades) are not public. - * This class contains everything needed to make a MerchantOffer, the actual "trade" object shown in trading guis. - */ -public class BasicItemListing implements ItemListing -{ - - protected final ItemStack price; - protected final ItemStack price2; - protected final ItemStack forSale; - protected final int maxTrades; - protected final int xp; - protected final float priceMult; - - public BasicItemListing(ItemStack price, ItemStack price2, ItemStack forSale, int maxTrades, int xp, float priceMult) - { - this.price = price; - this.price2 = price2; - this.forSale = forSale; - this.maxTrades = maxTrades; - this.xp = xp; - this.priceMult = priceMult; - } - - public BasicItemListing(ItemStack price, ItemStack forSale, int maxTrades, int xp, float priceMult) - { - this(price, ItemStack.EMPTY, forSale, maxTrades, xp, priceMult); - } - - public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp, float mult) - { - this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, mult); - } - - public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp) - { - this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, 1); - } - - @org.jetbrains.annotations.Nullable - @Override - public MerchantOffer getOffer(Entity p_219693_, RandomSource p_219694_) { - return new MerchantOffer(price, price2, forSale, maxTrades, xp, priceMult); - } -} diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index 6134a989ea..aa51c196a7 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -8,6 +8,7 @@ package net.minecraftforge.common; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -23,6 +24,7 @@ import java.util.stream.Stream; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; @@ -46,24 +48,24 @@ import net.minecraft.core.Direction; import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; +import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.core.registries.Registries; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextColor; import net.minecraft.network.chat.contents.PlainTextContents.LiteralContents; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerLevel; -import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap; -import net.minecraft.util.ExtraCodecs; import net.minecraft.util.GsonHelper; import net.minecraft.util.Mth; import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix; -import net.minecraft.world.Difficulty; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.effect.MobEffectUtil; @@ -73,22 +75,15 @@ import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ExperienceOrb; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.Brain; -import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.DefaultAttributes; import net.minecraft.world.entity.monster.EnderMan; -import net.minecraft.world.entity.SlotAccess; -import net.minecraft.world.inventory.ClickAction; import net.minecraft.world.inventory.ContainerLevelAccess; -import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.*; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.WorldData; @@ -108,20 +103,16 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.network.syncher.EntityDataSerializer; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; -import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; -import net.minecraft.world.item.alchemy.Potion; -import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.stats.Stats; import net.minecraft.world.phys.Vec3; import net.minecraft.world.level.block.entity.FurnaceBlockEntity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraftforge.common.crafting.conditions.ConditionCodec; import net.minecraftforge.common.crafting.conditions.ICondition; import net.minecraftforge.common.crafting.conditions.ICondition.IContext; import net.minecraftforge.common.crafting.ingredients.IIngredientSerializer; @@ -133,22 +124,17 @@ import net.minecraftforge.common.util.MutableHashedLinkedMap; import net.minecraftforge.entity.IEntityAdditionalSpawnData; import net.minecraftforge.event.AnvilUpdateEvent; import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; -import net.minecraftforge.event.DifficultyChangeEvent; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.GrindstoneEvent; -import net.minecraftforge.event.ItemAttributeModifierEvent; -import net.minecraftforge.event.ItemStackedOnOtherEvent; import net.minecraftforge.event.ModMismatchEvent; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.RegisterStructureConversionsEvent; -import net.minecraftforge.event.VanillaGameEvent; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.event.entity.EntityAttributeModificationEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; import net.minecraftforge.event.entity.living.EnderManAngerEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingBreatheEvent; -import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingDropsEvent; @@ -156,18 +142,14 @@ import net.minecraftforge.event.entity.living.LivingDrownEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; -import net.minecraftforge.event.entity.living.LivingChangeTargetEvent.ILivingTargetType; import net.minecraftforge.event.entity.living.LivingHurtEvent; -import net.minecraftforge.event.entity.living.LivingKnockBackEvent; import net.minecraftforge.event.entity.living.LivingMakeBrainEvent; import net.minecraftforge.event.entity.living.LivingUseTotemEvent; import net.minecraftforge.event.entity.living.LootingLevelEvent; -import net.minecraftforge.event.entity.player.AnvilRepairEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.CriticalHitEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.living.LivingGetProjectileEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.level.BlockEvent; import net.minecraftforge.event.level.NoteBlockEvent; import net.minecraftforge.event.network.CustomPayloadEvent; @@ -197,7 +179,7 @@ import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import net.minecraft.ChatFormatting; -import net.minecraft.Util; +import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.damagesource.DamageSource; @@ -213,15 +195,18 @@ import org.jetbrains.annotations.Nullable; /** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */ @ApiStatus.Internal -public class ForgeHooks { +public final class ForgeHooks { private static final Logger LOGGER = LogManager.getLogger(); @SuppressWarnings("unused") private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS"); private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP"); + private ForgeHooks() {} + public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to) { - if (!from.isEmpty() && !to.isEmpty()) + if (!from.isEmpty() && !to.isEmpty()) { return from.getItem().canContinueUsing(from, to); + } return false; } @@ -232,21 +217,6 @@ public class ForgeHooks { return player.hasCorrectToolForDrops(state); } - public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) { - return MinecraftForge.EVENT_BUS.post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess)); - } - - public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) { - MinecraftForge.EVENT_BUS.post(new DifficultyChangeEvent(difficulty, oldDifficulty)); - } - - public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) { - LivingChangeTargetEvent event = new LivingChangeTargetEvent(entity, originalTarget, targetType); - MinecraftForge.EVENT_BUS.post(event); - - return event; - } - public static Brain onLivingMakeBrain(LivingEntity entity, Brain originalBrain, Dynamic dynamic) { BrainBuilder brainBuilder = originalBrain.createBuilder(); LivingMakeBrainEvent event = new LivingMakeBrainEvent(entity, brainBuilder); @@ -266,12 +236,6 @@ public class ForgeHooks { return !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount)); } - public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) { - LivingKnockBackEvent event = new LivingKnockBackEvent(target, strength, ratioX, ratioZ); - MinecraftForge.EVENT_BUS.post(event); - return event; - } - public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) { return !MinecraftForge.EVENT_BUS.post(new LivingUseTotemEvent(entity, damageSource, totem, hand)); } @@ -362,10 +326,6 @@ public class ForgeHooks { return event.getEntity(); } - public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context) { - return !MinecraftForge.EVENT_BUS.post(new VanillaGameEvent(level, vanillaEvent, pos, context)); - } - @Nullable public static Component onServerChatSubmittedEvent(ServerPlayer player, Component message) { var plain = message.getContents() instanceof LiteralContents literalContents ? literalContents.text() : ""; @@ -395,7 +355,7 @@ public class ForgeHooks { // Append the previous left overs. String part = string.substring(lastEnd, start); - if (part.length() > 0) { + if (!part.isEmpty()) { if (ichat == null) ichat = Component.literal(part); else @@ -436,13 +396,13 @@ public class ForgeHooks { String end = string.substring(lastEnd); if (ichat == null) ichat = Component.literal(end); - else if (end.length() > 0) + else if (!end.isEmpty()) ichat.append(Component.literal(string.substring(lastEnd))); return ichat; } public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack) { - int fortuneLevel = stack.getEnchantmentLevel(Enchantments.BLOCK_FORTUNE); + int fortuneLevel = stack.getEnchantmentLevel(Enchantments.FORTUNE); int silkTouchLevel = stack.getEnchantmentLevel(Enchantments.SILK_TOUCH); int exp = state.getExpDrop(level, level.random, pos, fortuneLevel, silkTouchLevel); if (exp > 0) @@ -453,26 +413,23 @@ public class ForgeHooks { // Logic from tryHarvestBlock for pre-canceling the event boolean preCancelEvent = false; ItemStack itemstack = entityPlayer.getMainHandItem(); - if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) + if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) { preCancelEvent = true; - - if (gameType.isBlockPlacingRestricted()) { - if (gameType == GameType.SPECTATOR) - preCancelEvent = true; - - if (!entityPlayer.mayBuild()) { - if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, pos, false))) - preCancelEvent = true; - } } - // Tell client the block is gone immediately then process events - if (level.getBlockEntity(pos) == null) - entityPlayer.connection.send(new ClientboundBlockUpdatePacket(pos, level.getFluidState(pos).createLegacyBlock())); + if (entityPlayer.blockActionRestricted(level, pos, gameType)) { + preCancelEvent = true; + } // Post the block break event BlockState state = level.getBlockState(pos); - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(level, pos, state, entityPlayer); + + // Tell client the block is gone immediately then process events + if (level.getBlockEntity(pos) == null) { + level.sendBlockUpdated(pos, state, state, 3); + } + + var event = new BlockEvent.BreakEvent(level, pos, state, entityPlayer); event.setCanceled(preCancelEvent); MinecraftForge.EVENT_BUS.post(event); @@ -497,39 +454,29 @@ public class ForgeHooks { Level level = context.getLevel(); Player player = context.getPlayer(); - if (player != null && !player.getAbilities().mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, context.getClickedPos(), false))) + if (player != null && !player.getAbilities().mayBuild && !itemstack.canPlaceOnBlockInAdventureMode(new BlockInWorld(level, context.getClickedPos(), false))) { return InteractionResult.PASS; + } - // handle all placement events here - Item item = itemstack.getItem(); - int size = itemstack.getCount(); - CompoundTag nbt = null; - if (itemstack.getTag() != null) - nbt = itemstack.getTag().copy(); if (!(itemstack.getItem() instanceof BucketItem)) // if not bucket level.captureBlockSnapshots = true; - ItemStack copy = itemstack.copy(); + ItemStack preUse = itemstack.copy(); InteractionResult ret = itemstack.getItem().useOn(context); if (itemstack.isEmpty()) - ForgeEventFactory.onPlayerDestroyItem(player, copy, context.getHand()); + ForgeEventFactory.onPlayerDestroyItem(player, preUse, context.getHand()); level.captureBlockSnapshots = false; if (ret.consumesAction()) { - // save new item data - int newSize = itemstack.getCount(); - CompoundTag newNBT = null; - if (itemstack.getTag() != null) - newNBT = itemstack.getTag().copy(); - @SuppressWarnings("unchecked") - List blockSnapshots = (List)level.capturedBlockSnapshots.clone(); + var postUse = itemstack.copy(); + + var blockSnapshots = new ArrayList<>(level.capturedBlockSnapshots); level.capturedBlockSnapshots.clear(); // make sure to set pre-placement item data for event - itemstack.setCount(size); - itemstack.setTag(nbt); + player.setItemInHand(context.getHand(), preUse); Direction side = context.getClickedFace(); @@ -549,8 +496,8 @@ public class ForgeHooks { } } else { // Change the stack to its new content - itemstack.setCount(newSize); - itemstack.setTag(newNBT); + if (!player.isCreative()) + player.setItemInHand(context.getHand(), postUse); for (BlockSnapshot snap : blockSnapshots) { int updateFlag = snap.getFlag(); @@ -561,7 +508,7 @@ public class ForgeHooks { level.markAndNotifyBlock(snap.getPos(), level.getChunkAt(snap.getPos()), oldBlock, newBlock, updateFlag, 512); } if (player != null) - player.awardStat(Stats.ITEM_USED.get(item)); + player.awardStat(Stats.ITEM_USED.get(preUse.getItem())); } } level.capturedBlockSnapshots.clear(); @@ -569,35 +516,17 @@ public class ForgeHooks { return ret; } - public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player) { + public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, long baseCost, Player player) { AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost, player); if (MinecraftForge.EVENT_BUS.post(e)) return false; if (e.getOutput().isEmpty()) return true; outputSlot.setItem(0, e.getOutput()); - container.setMaximumCost(e.getCost()); + container.setMaximumCost((int)e.getCost()); container.repairItemCountCost = e.getMaterialCost(); return false; } - public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) { - AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output); - MinecraftForge.EVENT_BUS.post(e); - return e.getBreakChance(); - } - - public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) { - GrindstoneEvent.OnPlaceItem e = new GrindstoneEvent.OnPlaceItem(top, bottom, xp); - if (MinecraftForge.EVENT_BUS.post(e)) { - outputSlot.setItem(0, ItemStack.EMPTY); - return -1; - } - if (e.getOutput().isEmpty()) return Integer.MIN_VALUE; - - outputSlot.setItem(0, e.getOutput()); - return e.getXp(); - } - public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function xpFunction) { access.execute((l,p) -> { int xp = xpFunction.apply(l); @@ -616,13 +545,13 @@ public class ForgeHooks { return true; } - private static ThreadLocal craftingPlayer = new ThreadLocal(); + private static final ThreadLocal CRAFTING_PLAYER = new ThreadLocal<>(); public static void setCraftingPlayer(Player player) { - craftingPlayer.set(player); + CRAFTING_PLAYER.set(player); } public static Player getCraftingPlayer() { - return craftingPlayer.get(); + return CRAFTING_PLAYER.get(); } @NotNull @@ -630,7 +559,7 @@ public class ForgeHooks { if (stack.getItem().hasCraftingRemainingItem(stack)) { stack = stack.getItem().getCraftingRemainingItem(stack); if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) { - ForgeEventFactory.onPlayerDestroyItem(craftingPlayer.get(), stack, null); + ForgeEventFactory.onPlayerDestroyItem(CRAFTING_PLAYER.get(), stack, (EquipmentSlot)null); return ItemStack.EMPTY; } return stack; @@ -644,55 +573,11 @@ public class ForgeHooks { return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target); } - public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) { - Vec3 vec3d = ray.getLocation().subtract(entity.position()); - return onInteractEntityAt(player, entity, vec3d, hand); - } - - public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) { - PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d); - MinecraftForge.EVENT_BUS.post(evt); - return evt.isCanceled() ? evt.getCancellationResult() : null; - } - - public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) { - PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity); - MinecraftForge.EVENT_BUS.post(evt); - return evt.isCanceled() ? evt.getCancellationResult() : null; - } - public static InteractionResult onItemRightClick(Player player, InteractionHand hand) { - PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand); - MinecraftForge.EVENT_BUS.post(evt); + var evt = ForgeEventFactory.onRightClickItem(player, hand); return evt.isCanceled() ? evt.getCancellationResult() : null; } - public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) { - PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.convert(action)); - MinecraftForge.EVENT_BUS.post(evt); - return evt; - } - - public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) { - PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.CLIENT_HOLD); - MinecraftForge.EVENT_BUS.post(evt); - return evt; - } - - public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) { - PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec); - MinecraftForge.EVENT_BUS.post(evt); - return evt; - } - - public static void onEmptyClick(Player player, InteractionHand hand) { - MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand)); - } - - public static void onEmptyLeftClick(Player player) { - MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player)); - } - public static GameType onChangeGameType(Player player, GameType currentGameType, GameType newGameType) { if (currentGameType == newGameType) return currentGameType; @@ -740,6 +625,7 @@ public class ForgeHooks { throw new RuntimeException("Mod fluids must override getFluidType."); } + /* public static TagKey getTagFromVanillaTier(Tiers tier) { return switch(tier) { case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL; @@ -750,6 +636,7 @@ public class ForgeHooks { case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL; }; } + */ @FunctionalInterface public interface BiomeCallbackFunction { @@ -775,15 +662,6 @@ public class ForgeHooks { return null; } - /** - * Hook to fire {@link ItemAttributeModifierEvent}. Modders should use {@link ItemStack#getAttributeModifiers(EquipmentSlot)} instead. - */ - public static Multimap getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap attributes) { - ItemAttributeModifierEvent event = new ItemAttributeModifierEvent(stack, equipmentSlot, attributes); - MinecraftForge.EVENT_BUS.post(event); - return event.getModifiers(); - } - /** * Hook to fire {@link LivingGetProjectileEvent}. Returns the ammo to be used. */ @@ -803,20 +681,19 @@ public class ForgeHooks { String modId = registryName == null ? null : registryName.getNamespace(); if ("minecraft".equals(modId)) { if (item instanceof EnchantedBookItem) { - ListTag enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack); - if (enchantmentsNbt.size() == 1) { - CompoundTag nbttagcompound = enchantmentsNbt.getCompound(0); - ResourceLocation resourceLocation = ResourceLocation.tryParse(nbttagcompound.getString("id")); - if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation)) - return resourceLocation.getNamespace(); + var enchants = EnchantmentHelper.getEnchantmentsForCrafting(itemStack); + if (enchants.size() == 1) { + var enchant = enchants.keySet().iterator().next(); + var name = enchant.unwrapKey(); + if (name.isPresent()) + return name.get().location().getNamespace(); } - } else if (item instanceof PotionItem || item instanceof TippedArrowItem) { - Potion potionType = PotionUtils.getPotion(itemStack); - ResourceLocation resourceLocation = ForgeRegistries.POTIONS.getKey(potionType); - if (resourceLocation != null) - return resourceLocation.getNamespace(); + } else if (itemStack.has(DataComponents.POTION_CONTENTS)) { + var potion = itemStack.get(DataComponents.POTION_CONTENTS).potion().orElse(null); + if (potion != null && potion.unwrapKey().isPresent()) + return potion.unwrapKey().get().location().getNamespace(); } else if (item instanceof SpawnEggItem egg) { - ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null)); + var resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null)); if (resourceLocation != null) return resourceLocation.getNamespace(); } @@ -1167,7 +1044,7 @@ public class ForgeHooks { @ApiStatus.Internal public static HolderLookup.RegistryLookup wrapRegistryLookup(final HolderLookup.RegistryLookup lookup) { return new HolderLookup.RegistryLookup.Delegate<>() { - @Override protected RegistryLookup parent() { return lookup; } + @Override public RegistryLookup parent() { return lookup; } @Override public Stream> listTags() { return Stream.empty(); } @SuppressWarnings("deprecation") @Override public Optional> get(TagKey key) { return Optional.of(HolderSet.emptyNamed(lookup, key)); } @@ -1188,18 +1065,18 @@ public class ForgeHooks { // Check things that vanilla considers to be air - these will cause the air supply to be increased. boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN); // The following effects cause the entity to not drown, but do not cause the air supply to be increased. - boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player && ((Player) entity).getAbilities().invulnerable); - LivingBreatheEvent breatheEvent = new LivingBreatheEvent(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir); - MinecraftForge.EVENT_BUS.post(breatheEvent); + boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player player && player.getAbilities().invulnerable); + var breatheEvent = ForgeEventFactory.onLivingBreathe(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir); if (breatheEvent.canBreathe()) { - if (breatheEvent.canRefillAir()) + if (breatheEvent.canRefillAir()) { entity.setAirSupply(Math.min(entity.getAirSupply() + breatheEvent.getRefillAirAmount(), entity.getMaxAirSupply())); + } } else entity.setAirSupply(entity.getAirSupply() - breatheEvent.getConsumeAirAmount()); - if (entity.getAirSupply() <= 0) { - LivingDrownEvent drownEvent = new LivingDrownEvent(entity, entity.getAirSupply() <= -20, 2.0F, 8); - if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning()) { + if (entity.getAirSupply() <= -20) { + var drownEvent = ForgeEventFactory.onLivingDrown(entity, entity.getAirSupply() <= -20, 2.0F, 8); + if (!drownEvent.isCanceled() && drownEvent.isDrowning()) { entity.setAirSupply(0); Vec3 vec3 = entity.getDeltaMovement(); @@ -1210,12 +1087,15 @@ public class ForgeHooks { entity.level().addParticle(ParticleTypes.BUBBLE, entity.getX() + d2, entity.getY() + d3, entity.getZ() + d4, vec3.x, vec3.y, vec3.z); } - if (drownEvent.getDamageAmount() > 0) entity.hurt(entity.damageSources().drown(), drownEvent.getDamageAmount()); + if (drownEvent.getDamageAmount() > 0) { + entity.hurt(entity.damageSources().drown(), drownEvent.getDamageAmount()); + } } } - if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity)) + if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity)) { entity.stopRiding(); + } } public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) { @@ -1289,30 +1169,27 @@ public class ForgeHooks { } @ApiStatus.Internal - public static boolean readAndTestCondition(@Nullable ICondition.IContext context, JsonObject json) { - if (context == null) - context = IContext.EMPTY; - + public static boolean readAndTestCondition(RegistryOps ops, JsonObject json) { if (!json.has(ICondition.DEFAULT_FIELD)) return true; - var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, json.getAsJsonObject(ICondition.DEFAULT_FIELD)), JsonParseException::new); - return condition.test(context); + var condition = ICondition.SAFE_CODEC.parse(ops, json.getAsJsonObject(ICondition.DEFAULT_FIELD)) + .getOrThrow(JsonParseException::new); + + return condition.test(ConditionCodec.getContext(ops), ops); } @ApiStatus.Internal public static void writeCondition(ICondition condition, JsonObject out) { if (condition == null) return; - var data = ICondition.CODEC.encode(condition, JsonOps.INSTANCE, JsonOps.INSTANCE.empty()).getOrThrow(false, JsonSyntaxException::new); + var data = ICondition.CODEC.encode(condition, JsonOps.INSTANCE, JsonOps.INSTANCE.empty()).getOrThrow(JsonSyntaxException::new); out.add(ICondition.DEFAULT_FIELD, data); } @Nullable @ApiStatus.Internal - public static JsonObject readConditionalAdvancement(@Nullable ICondition.IContext context, JsonObject json) { - if (context == null) - context = IContext.EMPTY; + public static JsonObject readConditionalAdvancement(RegistryOps context, JsonObject json) { var entries = GsonHelper.getAsJsonArray(json, "advancements", null); if (entries == null) return readAndTestCondition(context, json) ? json : null; @@ -1333,8 +1210,8 @@ public class ForgeHooks { @ApiStatus.Internal public static Codec enhanceIngredientCodec(Codec vanilla) { - return ExtraCodecs.lazyInitializedCodec(() -> - ExtraCodecs.either( + return Codec.lazyInitialized(() -> + Codec.either( ForgeRegistries.INGREDIENT_SERIALIZERS.get().getCodec().dispatch(Ingredient::serializer, IIngredientSerializer::codec), vanilla ) @@ -1345,29 +1222,43 @@ public class ForgeHooks { ); } - @ApiStatus.Internal - public static boolean ingredientToNetwork(FriendlyByteBuf buffer, T ingredient) { - if (ingredient.isVanilla()) - return true; + public static StreamCodec ingredientStreamCodec() { + return StreamCodec.of( + (buf, value) -> { + if (value.isVanilla()) { + var items = value.getItems(); + ByteBufCodecs.writeCount(buf, items.length, Integer.MAX_VALUE); + for (var item : items) { + ItemStack.STREAM_CODEC.encode(buf, item); + } + } else { + @SuppressWarnings("unchecked") + var serializer = (IIngredientSerializer)value.serializer(); + var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(serializer); + if (key == null) + throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + value); - @SuppressWarnings("unchecked") - var serializer = (IIngredientSerializer)ingredient.serializer(); - var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(ingredient.serializer()); - if (key == null) - throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + ingredient); - - buffer.writeVarInt(-1); // Our Marker - buffer.writeResourceLocation(key); - serializer.write(buffer, ingredient); - return false; - } - - public static Ingredient ingredientFromNetwork(FriendlyByteBuf buffer) { - // We have already read our marker - var key = buffer.readResourceLocation(); - var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key); - if (serializer == null) - throw new DecoderException("Could not read ingredient of type: " + key); - return serializer.read(buffer); + buf.writeVarInt(-1); // Our Marker + buf.writeResourceLocation(key); + serializer.write(buf, value); + } + }, + (buf) -> { + var size = ByteBufCodecs.readCount(buf, Integer.MAX_VALUE); + if (size != -1) { + var ret = NonNullList.createWithCapacity(size); + for (int x = 0; x < size; x++) { + ret.add(ItemStack.STREAM_CODEC.decode(buf)); + } + return Ingredient.fromValues(ret.stream().map(Ingredient.ItemValue::new)); + } else { + var key = buf.readResourceLocation(); + var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key); + if (serializer == null) + throw new DecoderException("Could not read ingredient of type: " + key); + return serializer.read(buf); + } + } + ); } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java index 1a466cb704..2890d9e3f6 100644 --- a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java +++ b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java @@ -108,7 +108,6 @@ public class ForgeInternalHandler { @SubscribeEvent public void resourceReloadListeners(AddReloadListenerEvent event) { - event.addListener(TierSortingRegistry.getReloadListener()); event.addListener(CreativeModeTabRegistry.getReloadListener()); } diff --git a/src/main/java/net/minecraftforge/common/ForgeMod.java b/src/main/java/net/minecraftforge/common/ForgeMod.java index b3d44c9531..82f84dc159 100644 --- a/src/main/java/net/minecraftforge/common/ForgeMod.java +++ b/src/main/java/net/minecraftforge/common/ForgeMod.java @@ -17,7 +17,10 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; import net.minecraft.data.metadata.PackMetadataGenerator; +import net.minecraft.network.chat.ChatType; +import net.minecraft.network.chat.ChatTypeDecoration; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.metadata.pack.PackMetadataSection; import net.minecraft.sounds.SoundEvents; @@ -36,7 +39,7 @@ import net.minecraft.world.level.material.Fluid; import net.minecraft.world.item.Items; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; @@ -46,8 +49,6 @@ import net.minecraftforge.common.data.ForgeFluidTagsProvider; import net.minecraftforge.common.data.ForgeLootTableProvider; import net.minecraftforge.common.data.ForgeSpriteSourceProvider; import net.minecraftforge.common.data.VanillaSoundDefinitionsProvider; -import net.minecraftforge.common.extensions.IForgeEntity; -import net.minecraftforge.common.extensions.IForgePlayer; import net.minecraftforge.common.loot.CanToolPerformAction; import net.minecraftforge.common.loot.LootTableIdCondition; import net.minecraftforge.common.world.BiomeModifier; @@ -116,6 +117,8 @@ import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import org.jetbrains.annotations.Nullable; import java.lang.reflect.Method; @@ -150,32 +153,8 @@ public class ForgeMod { private static final DeferredRegister ATTRIBUTES = deferred(ForgeRegistries.Keys.ATTRIBUTES); public static final RegistryObject SWIM_SPEED = ATTRIBUTES.register("swim_speed", () -> new RangedAttribute("forge.swim_speed", 1.0D, 0.0D, 1024.0D).setSyncable(true)); public static final RegistryObject NAMETAG_DISTANCE = ATTRIBUTES.register("nametag_distance", () -> new RangedAttribute("forge.name_tag_distance", 64.0D, 0.0D, 64.0).setSyncable(true)); - public static final RegistryObject ENTITY_GRAVITY = ATTRIBUTES.register("entity_gravity", () -> new RangedAttribute("forge.entity_gravity", 0.08D, -8.0D, 8.0D).setSyncable(true)); - /** - * Reach Distance represents the distance at which a player may interact with the world. The default is 4.5 blocks. Players in creative mode have an additional 0.5 blocks of block reach. - * @see IForgePlayer#getBlockReach() - * @see IForgePlayer#canReach(BlockPos, double) - */ - public static final RegistryObject BLOCK_REACH = ATTRIBUTES.register("block_reach", () -> new RangedAttribute("forge.block_reach", 4.5D, 0.0D, 1024.0D).setSyncable(true)); - - /** - * Attack Range represents the distance at which a player may attack an entity. The default is 3 blocks. Players in creative mode have an additional 3 blocks of entity reach. - * The default of 3.0 is technically considered a bug by Mojang - see MC-172289 and MC-92484. However, updating this value would allow for longer-range attacks on vanilla servers, which makes some people mad. - * @see IForgePlayer#getEntityReach() - * @see IForgePlayer#canReach(Entity, double) - * @see IForgePlayer#canReach(Vec3, double) - */ - public static final RegistryObject ENTITY_REACH = ATTRIBUTES.register("entity_reach", () -> new RangedAttribute("forge.entity_reach", 3.0D, 0.0D, 1024.0D).setSyncable(true)); - - /** - * Step Height Addition modifies the amount of blocks an entity may walk up without jumping. - * @see IForgeEntity#getStepHeight() - */ - public static final RegistryObject STEP_HEIGHT_ADDITION = ATTRIBUTES.register("step_height_addition", () -> new RangedAttribute("forge.step_height", 0.0D, -512.0D, 512.0D).setSyncable(true)); - - - private static final DeferredRegister> BIOME_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS); + private static final DeferredRegister> BIOME_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS); static { BIOME_MODIFIER_SERIALIZERS.register("none", () -> NoneBiomeModifier.CODEC); BIOME_MODIFIER_SERIALIZERS.register("add_features", () -> AddFeaturesBiomeModifier.CODEC); @@ -184,7 +163,7 @@ public class ForgeMod { BIOME_MODIFIER_SERIALIZERS.register("remove_spawns", () -> RemoveSpawnsBiomeModifier.CODEC); } - private static final DeferredRegister> STRUCTURE_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS); + private static final DeferredRegister> STRUCTURE_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS); static { STRUCTURE_MODIFIER_SERIALIZERS.register("none", () -> NoneStructureModifier.CODEC); } @@ -247,7 +226,7 @@ public class ForgeMod { .canHydrate(true)) { @Override - public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { + public @Nullable PathType getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null; } @@ -298,7 +277,7 @@ public class ForgeMod { .descriptionId("block.minecraft.lava") .canSwim(false) .canDrown(false) - .pathType(BlockPathTypes.LAVA) + .pathType(PathType.LAVA) .adjacentPathType(null) .sound(SoundActions.BUCKET_FILL, SoundEvents.BUCKET_FILL_LAVA) .sound(SoundActions.BUCKET_EMPTY, SoundEvents.BUCKET_EMPTY_LAVA) @@ -343,7 +322,7 @@ public class ForgeMod { LOOT_CONDITION_TYPES.register("can_tool_perform_action", () -> CanToolPerformAction.TYPE); } - private static final DeferredRegister> CONDITION_SERIALIZERS = deferred(ForgeRegistries.Keys.CONDITION_SERIALIZERS); + private static final DeferredRegister> CONDITION_SERIALIZERS = deferred(ForgeRegistries.Keys.CONDITION_SERIALIZERS); static { CONDITION_SERIALIZERS.register("and", () -> AndCondition.CODEC); CONDITION_SERIALIZERS.register("false", () -> FalseCondition.CODEC); @@ -377,6 +356,12 @@ public class ForgeMod { public static final RegistryObject MILK = RegistryObject.create(new ResourceLocation("milk"), ForgeRegistries.FLUIDS); public static final RegistryObject FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS); + /* + private static final ChatTypeDecoration SYSTEM_CHAT_TYPE_DECORATION = new ChatTypeDecoration("forge.chatType.system", List.of(ChatTypeDecoration.Parameter.CONTENT), Style.EMPTY); + private static final DeferredRegister CHAT_TYPES = deferred(Registries.CHAT_TYPE); + public static final RegistryObject SYSTEM_CHAT_TYPE = CHAT_TYPES.register("syste_chat", () -> new ChatType(SYSTEM_CHAT_TYPE_DECORATION, SYSTEM_CHAT_TYPE_DECORATION)); + */ + private static ForgeMod INSTANCE; public static ForgeMod getInstance() { return INSTANCE; @@ -482,8 +467,8 @@ public class ForgeMod { gen.addProvider(event.includeServer(), new ForgeItemTagsProvider(packOutput, lookupProvider, blockTags.contentsGetter(), existingFileHelper)); gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(packOutput, lookupProvider, existingFileHelper)); gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(packOutput, lookupProvider, existingFileHelper)); - gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput)); - gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput)); + gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput, lookupProvider)); + gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput, lookupProvider)); gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper)); gen.addProvider(event.includeClient(), new ForgeSpriteSourceProvider(packOutput, existingFileHelper)); diff --git a/src/main/java/net/minecraftforge/common/ForgeSpawnEggItem.java b/src/main/java/net/minecraftforge/common/ForgeSpawnEggItem.java index 3e1351d3e9..f90950ceef 100644 --- a/src/main/java/net/minecraftforge/common/ForgeSpawnEggItem.java +++ b/src/main/java/net/minecraftforge/common/ForgeSpawnEggItem.java @@ -7,7 +7,6 @@ package net.minecraftforge.common; import net.minecraft.core.Direction; import net.minecraft.core.dispenser.DispenseItemBehavior; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; @@ -42,12 +41,6 @@ public class ForgeSpawnEggItem extends SpawnEggItem { MOD_EGGS.add(this); } - @Override - public EntityType getType(@Nullable CompoundTag tag) { - EntityType type = super.getType(tag); - return type != null ? type : typeSupplier.get(); - } - @Nullable protected DispenseItemBehavior createDispenseBehavior() { return DEFAULT_DISPENSE_BEHAVIOR; @@ -66,7 +59,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem { private static final DispenseItemBehavior DEFAULT_DISPENSE_BEHAVIOR = (source, stack) -> { Direction face = source.state().getValue(DispenserBlock.FACING); - EntityType type = ((SpawnEggItem)stack.getItem()).getType(stack.getTag()); + EntityType type = ((SpawnEggItem)stack.getItem()).getType(stack); try { type.spawn(source.level(), stack, null, source.pos().relative(face), MobSpawnType.DISPENSER, face != Direction.UP, false); diff --git a/src/main/java/net/minecraftforge/common/ForgeTier.java b/src/main/java/net/minecraftforge/common/ForgeTier.java index f0ddc720af..86fa764c5a 100644 --- a/src/main/java/net/minecraftforge/common/ForgeTier.java +++ b/src/main/java/net/minecraftforge/common/ForgeTier.java @@ -17,9 +17,7 @@ import java.util.function.Supplier; * Helper class to define a custom tier */ @SuppressWarnings("ClassCanBeRecord") // can't make it a record because the method names will be obfuscated -public final class ForgeTier implements Tier -{ - private final int level; +public final class ForgeTier implements Tier { private final int uses; private final float speed; private final float attackDamageBonus; @@ -28,72 +26,66 @@ public final class ForgeTier implements Tier private final TagKey tag; @NotNull private final Supplier repairIngredient; + @NotNull + public final TagKey incorrectBlocks; - public ForgeTier(int level, int uses, float speed, float attackDamageBonus, int enchantmentValue, - @NotNull TagKey tag, @NotNull Supplier repairIngredient) - { - this.level = level; + public ForgeTier(int uses, float speed, float attackDamageBonus, int enchantmentValue, + @NotNull TagKey tag, @NotNull Supplier repairIngredient, + @NotNull TagKey incorrectBlocks) { this.uses = uses; this.speed = speed; this.attackDamageBonus = attackDamageBonus; this.enchantmentValue = enchantmentValue; this.tag = tag; this.repairIngredient = repairIngredient; + this.incorrectBlocks = incorrectBlocks; } @Override - public int getUses() - { + public int getUses() { return this.uses; } @Override - public float getSpeed() - { + public float getSpeed() { return this.speed; } @Override - public float getAttackDamageBonus() - { + public float getAttackDamageBonus() { return this.attackDamageBonus; } @Override - public int getLevel() - { - return this.level; - } - - @Override - public int getEnchantmentValue() - { + public int getEnchantmentValue() { return this.enchantmentValue; } @NotNull - public TagKey getTag() - { + public TagKey getTag() { return this.tag; } + @Override + public TagKey getIncorrectBlocksForDrops() { + return this.incorrectBlocks; + } + @NotNull @Override - public Ingredient getRepairIngredient() - { + public Ingredient getRepairIngredient() { return this.repairIngredient.get(); } @Override - public String toString() - { + public String toString() { return "ForgeTier[" + - "level=" + level + ", " + "uses=" + uses + ", " + "speed=" + speed + ", " + "attackDamageBonus=" + attackDamageBonus + ", " + "enchantmentValue=" + enchantmentValue + ", " + "tag=" + tag + ", " + + "incorrect=" + incorrectBlocks+ ", " + "repairIngredient=" + repairIngredient + ']'; } } diff --git a/src/main/java/net/minecraftforge/common/IExtensibleEnum.java b/src/main/java/net/minecraftforge/common/IExtensibleEnum.java index 1f5338fdf5..a091dbbb05 100644 --- a/src/main/java/net/minecraftforge/common/IExtensibleEnum.java +++ b/src/main/java/net/minecraftforge/common/IExtensibleEnum.java @@ -47,14 +47,14 @@ public interface IExtensibleEnum { static & StringRepresentable> Codec createCodecForExtensibleEnum(Supplier valuesSupplier, Function enumValueFromNameFunction) { return Codec.either(Codec.STRING, Codec.INT).comapFlatMap( either -> either.map( - str -> { - var val = enumValueFromNameFunction.apply(str); - return val != null ? DataResult.success(val) : DataResult.error(() -> "Unknown enum value name: " + str); - }, - num -> { - var values = valuesSupplier.get(); - return num >= 0 && num < values.length ? DataResult.success(values[num]) : DataResult.error(() -> "Unknown enum id: " + num); - } + str -> { + var val = enumValueFromNameFunction.apply(str); + return val != null ? DataResult.success(val) : DataResult.error(() -> "Unknown enum value name: " + str); + }, + num -> { + var values = valuesSupplier.get(); + return num >= 0 && num < values.length ? DataResult.success(values[num]) : DataResult.error(() -> "Unknown enum id: " + num); + } ), value -> Either.left(value.getSerializedName()) ); diff --git a/src/main/java/net/minecraftforge/common/MinecraftForge.java b/src/main/java/net/minecraftforge/common/MinecraftForge.java index 24abd79ee3..a0ee6c3f4e 100644 --- a/src/main/java/net/minecraftforge/common/MinecraftForge.java +++ b/src/main/java/net/minecraftforge/common/MinecraftForge.java @@ -52,7 +52,6 @@ public class MinecraftForge LOGGER.info(FORGE,"MinecraftForge v{} Initialized", ForgeVersion.getVersion()); UsernameCache.load(); - TierSortingRegistry.init(); if (FMLEnvironment.dist == Dist.CLIENT) ClientCommandHandler.init(); DualStackUtils.initialise(); } diff --git a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java b/src/main/java/net/minecraftforge/common/TierSortingRegistry.java deleted file mode 100644 index 89356bc894..0000000000 --- a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common; - -import com.google.common.collect.*; -import com.google.common.graph.ElementOrder; -import com.google.common.graph.GraphBuilder; -import com.google.common.graph.MutableGraph; -import com.google.gson.*; -import it.unimi.dsi.fastutil.booleans.BooleanConsumer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.packs.resources.PreparableReloadListener; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.SimplePreparableReloadListener; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagKey; -import net.minecraft.util.GsonHelper; -import net.minecraft.util.profiling.ProfilerFiller; -import net.minecraft.world.item.DiggerItem; -import net.minecraft.world.item.Tier; -import net.minecraft.world.item.Tiers; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.ClientPlayerNetworkEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.network.CustomPayloadEvent; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.fml.loading.toposort.TopologicalSort; -import net.minecraftforge.network.ChannelBuilder; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.PacketDistributor; -import net.minecraftforge.network.SimpleChannel; -import net.minecraftforge.server.ServerLifecycleHooks; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -public class TierSortingRegistry { - private static final Logger LOGGER = LogManager.getLogger(); - private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json"); - - /** - * Registers a tier into the tier sorting registry. - * @param tier The tier to register - * @param name The name to use internally for dependency resolution - * @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers) - * @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers) - */ - public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List after, List before) { - if (tier == null) - throw new NullPointerException("Registering a new Tier requires a nonnull tier! ResourceLocation name: " + name); - if (tiers.containsKey(name)) - throw new IllegalStateException("Duplicate tier name " + name); - - processTier(tier, name, after, before); - - hasCustomTiers = true; - return tier; - } - - /** - * Returns the list of tiers in the order defined by the dependencies. - * This list will remain valid - * @return An unmodifiable list of tiers ordered lesser to greater - */ - public static List getSortedTiers() { - return sortedTiersUnmodifiable; - } - - /** - * Returns the tier associated with a name, if registered into the sorting system. - * @param name The name to look up - * @return The tier, or null if not registered - */ - @Nullable - public static Tier byName(ResourceLocation name) { - return tiers.get(name); - } - - /** - * Returns the name associated with a tier, if the tier is registered into the sorting system. - * @param tier The tier to look up - * @return The name for the tier, or null if not registered - */ - @Nullable - public static ResourceLocation getName(Tier tier) { - return tiers.inverse().get(tier); - } - - /** - * Queries if a tier should be evaluated using the sorting system, by calling isCorrectTierForDrops - * @param tier The tier to query - * @return True if isCorrectTierForDrops should be called for the tier - */ - public static boolean isTierSorted(Tier tier) { - return getName(tier) != null; - } - - /** - * Queries if a tier is high enough to be able to get drops for the given blockstate. - * @param tier The tier to look up - * @param state The state to test against - * @return True if the tier is good enough - */ - public static boolean isCorrectTierForDrops(Tier tier, BlockState state) { - if (!isTierSorted(tier)) - return isCorrectTierVanilla(tier, state); - - for (int x = sortedTiers.indexOf(tier) + 1; x < sortedTiers.size(); x++) { - TagKey tag = sortedTiers.get(x).getTag(); - if (tag != null && state.is(tag)) - return false; - } - return true; - } - - /** - * Helper to query all tiers that are lower than the given tier - * @param tier The tier - * @return All the lower tiers - */ - public static List getTiersLowerThan(Tier tier) { - if (!isTierSorted(tier)) return List.of(); - return sortedTiers.stream().takeWhile(t -> t != tier).toList(); - } - - // ===================== PRIVATE INTERNAL STUFFS BELOW THIS LINE ===================== - - /** - * Fallback for when a tier isn't in the registry, copy of the logic in {@link DiggerItem#isCorrectToolForDrops} - */ - private static boolean isCorrectTierVanilla(Tier tier, BlockState state) { - @SuppressWarnings("deprecation") - int i = tier.getLevel(); - if (i < 3 && state.is(BlockTags.NEEDS_DIAMOND_TOOL)) - return false; - else if (i < 2 && state.is(BlockTags.NEEDS_IRON_TOOL)) - return false; - else if (i < 1 && state.is(BlockTags.NEEDS_STONE_TOOL)) - return false; - return true; - } - - private static void processTier(Tier tier, ResourceLocation name, List afters, List befores) { - tiers.put(name, tier); - for(Object after : afters) - edges.put(getTierName(after), name); - for(Object before : befores) - edges.put(name, getTierName(before)); - } - - private static ResourceLocation getTierName(Object entry) { - if (entry instanceof String s) - return new ResourceLocation(s); - if (entry instanceof ResourceLocation rl) - return rl; - if (entry instanceof Tier t) - return Objects.requireNonNull(getName(t), "Can't have sorting dependencies for tiers not registered in the TierSortingRegistry"); - throw new IllegalStateException("Invalid object type passed into the tier dependencies " + entry.getClass()); - } - - private static boolean hasCustomTiers = false; - private static final BiMap tiers = HashBiMap.create(); - private static final Multimap edges = HashMultimap.create(); - private static final Multimap vanillaEdges = HashMultimap.create(); - - static { - var wood = new ResourceLocation("wood"); - var stone = new ResourceLocation("stone"); - var iron = new ResourceLocation("iron"); - var diamond = new ResourceLocation("diamond"); - var netherite = new ResourceLocation("netherite"); - var gold = new ResourceLocation("gold"); - processTier(Tiers.WOOD, wood, List.of(), List.of()); - processTier(Tiers.GOLD, gold, List.of(wood), List.of(stone)); - processTier(Tiers.STONE, stone, List.of(wood), List.of(iron)); - processTier(Tiers.IRON, iron, List.of(stone), List.of(diamond)); - processTier(Tiers.DIAMOND, diamond, List.of(iron), List.of(netherite)); - processTier(Tiers.NETHERITE, netherite, List.of(diamond), List.of()); - vanillaEdges.putAll(edges); - } - - private static final List sortedTiers = new ArrayList<>(); - private static final List sortedTiersUnmodifiable = Collections.unmodifiableList(sortedTiers); - - private static final ResourceLocation CHANNEL_NAME = new ResourceLocation("forge:tier_sorting"); - private static final SimpleChannel SYNC_CHANNEL = ChannelBuilder - .named(CHANNEL_NAME) - .networkProtocolVersion(1) - .acceptedVersions((s, v) -> v == 1 || allowVanilla()) // Accepts vanilla unless we've got custom tiers - .simpleChannel() - .messageBuilder(SyncPacket.class, NetworkDirection.PLAY_TO_CLIENT) - .encoder(SyncPacket::encode) - .decoder(TierSortingRegistry::receive) - .consumerNetworkThread(TierSortingRegistry::handle) - .add(); - - static boolean allowVanilla() { - return !hasCustomTiers; - } - - /*package private*/ - static void init() { - MinecraftForge.EVENT_BUS.addListener(TierSortingRegistry::playerLoggedIn); - if (FMLEnvironment.dist == Dist.CLIENT) - ClientEvents.init(); - } - - /*package private*/ - static PreparableReloadListener getReloadListener() { - return new SimplePreparableReloadListener() { - final Gson gson = (new GsonBuilder()).create(); - - @NotNull - @Override - protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) { - Optional res = resourceManager.getResource(ITEM_TIER_ORDERING_JSON); - if (res.isEmpty()) - return new JsonObject(); - - try (var reader = res.get().openAsReader()) { - return gson.fromJson(reader, JsonObject.class); - } catch (IOException e) { - LOGGER.error("Could not read Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); - return new JsonObject(); - } - } - - @Override - protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) { - try { - if (data.size() > 0) { - JsonArray order = GsonHelper.getAsJsonArray(data, "order"); - List customOrder = new ArrayList<>(); - for (JsonElement entry : order) { - ResourceLocation id = new ResourceLocation(entry.getAsString()); - Tier tier = byName(id); - if (tier == null) throw new IllegalStateException("Tier not found with name " + id); - customOrder.add(tier); - } - - List missingTiers = tiers.values().stream().filter(tier -> !customOrder.contains(tier)).toList(); - if (missingTiers.size() > 0) - throw new IllegalStateException("Tiers missing from the ordered list: " + missingTiers.stream().map(tier -> Objects.toString(TierSortingRegistry.getName(tier))).collect(Collectors.joining(", "))); - - setTierOrder(customOrder); - return; - } - } catch(Exception e) { - LOGGER.error("Error parsing Tier sorting file " + ITEM_TIER_ORDERING_JSON, e); - } - - recalculateItemTiers(); - } - }; - } - - private static void recalculateItemTiers() { - final MutableGraph graph = GraphBuilder.directed().nodeOrder(ElementOrder.insertion()).build(); - - for(Tier tier : tiers.values()) - graph.addNode(tier); - - edges.forEach((key, value) -> { - if (tiers.containsKey(key) && tiers.containsKey(value)) - graph.putEdge(tiers.get(key), tiers.get(value)); - }); - List tierList = TopologicalSort.topologicalSort(graph, null); - - setTierOrder(tierList); - } - - private static void setTierOrder(List tierList) { - runInServerThreadIfPossible(hasServer -> { - sortedTiers.clear(); - sortedTiers.addAll(tierList); - if (hasServer) - syncToAll(); - }); - } - - private static void runInServerThreadIfPossible(BooleanConsumer runnable) { - MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); - if (server != null) - server.execute(() -> runnable.accept(true)); - else - runnable.accept(false); - } - - private static void syncToAll() { - for (ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers()) - syncToPlayer(serverPlayer); - } - - private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { - if (event.getEntity() instanceof ServerPlayer serverPlayer) - syncToPlayer(serverPlayer); - } - - private static void syncToPlayer(ServerPlayer serverPlayer) { - if (SYNC_CHANNEL.isRemotePresent(serverPlayer.connection.getConnection()) && !serverPlayer.connection.getConnection().isMemoryConnection()) - SYNC_CHANNEL.send(new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList()), PacketDistributor.PLAYER.with(serverPlayer)); - } - - private static SyncPacket receive(FriendlyByteBuf buffer) { - int count = buffer.readVarInt(); - List list = new ArrayList<>(); - for(int i = 0; i < count; i++) - list.add(buffer.readResourceLocation()); - return new SyncPacket(list); - } - - private static void handle(SyncPacket packet, CustomPayloadEvent.Context context) { - setTierOrder(packet.tiers.stream().map(TierSortingRegistry::byName).toList()); - context.setPacketHandled(true); - } - - private record SyncPacket(List tiers) { - private void encode(FriendlyByteBuf buffer) { - buffer.writeVarInt(tiers.size()); - for(ResourceLocation loc : tiers) - buffer.writeResourceLocation(loc); - } - } - - private static class ClientEvents { - public static void init() { - MinecraftForge.EVENT_BUS.addListener(ClientEvents::clientLogInToServer); - } - - private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) { - if (event.getConnection() == null || !event.getConnection().isMemoryConnection()) - recalculateItemTiers(); - } - } -} diff --git a/src/main/java/net/minecraftforge/common/ToolAction.java b/src/main/java/net/minecraftforge/common/ToolAction.java index 96cca64475..c23bc11f8c 100644 --- a/src/main/java/net/minecraftforge/common/ToolAction.java +++ b/src/main/java/net/minecraftforge/common/ToolAction.java @@ -11,10 +11,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.mojang.serialization.Codec; +import org.jetbrains.annotations.ApiStatus; -public final class ToolAction { +public record ToolAction(String name) { public static final Codec CODEC = Codec.STRING.xmap(ToolAction::get, ToolAction::name).stable(); - private static final Map actions = new ConcurrentHashMap<>(); + private static final Map ACTIONS = new ConcurrentHashMap<>(); /** * Returns all registered actions. @@ -22,14 +23,14 @@ public final class ToolAction { * See {@link ConcurrentHashMap#values()} for details. */ public static Collection getActions() { - return Collections.unmodifiableCollection(actions.values()); + return Collections.unmodifiableCollection(ACTIONS.values()); } /** * Gets or creates a new ToolAction for the given name. */ public static ToolAction get(String name) { - return actions.computeIfAbsent(name, ToolAction::new); + return ACTIONS.computeIfAbsent(name, ToolAction::new); } /** @@ -39,17 +40,7 @@ public final class ToolAction { return name; } - @Override - public String toString() { - return "ToolAction[" + name + "]"; - } - - private final String name; - - /** - * Use {@link #get(String)} to get or create a ToolAction - */ - private ToolAction(String name) { - this.name = name; - } + /** Use {@link #get(String)} to get or create a ToolAction */ + @ApiStatus.Internal + public ToolAction {} } diff --git a/src/main/java/net/minecraftforge/common/brewing/BrewingRecipe.java b/src/main/java/net/minecraftforge/common/brewing/BrewingRecipe.java index ccb8d3f9ae..9beae4e873 100644 --- a/src/main/java/net/minecraftforge/common/brewing/BrewingRecipe.java +++ b/src/main/java/net/minecraftforge/common/brewing/BrewingRecipe.java @@ -9,49 +9,41 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.jetbrains.annotations.NotNull; -public class BrewingRecipe implements IBrewingRecipe -{ +public class BrewingRecipe implements IBrewingRecipe { @NotNull private final Ingredient input; @NotNull private final Ingredient ingredient; @NotNull private final ItemStack output; - public BrewingRecipe(Ingredient input, Ingredient ingredient, ItemStack output) - { + public BrewingRecipe(Ingredient input, Ingredient ingredient, ItemStack output) { this.input = input; this.ingredient = ingredient; this.output = output; } @Override - public boolean isInput(@NotNull ItemStack stack) - { + public boolean isInput(@NotNull ItemStack stack) { return this.input.test(stack); } @Override - public ItemStack getOutput(ItemStack input, ItemStack ingredient) - { + public ItemStack getOutput(ItemStack input, ItemStack ingredient) { return isInput(input) && isIngredient(ingredient) ? getOutput().copy() : ItemStack.EMPTY; } - public Ingredient getInput() - { + public Ingredient getInput() { return input; } - public Ingredient getIngredient() - { + public Ingredient getIngredient() { return ingredient; } - public ItemStack getOutput() - { + public ItemStack getOutput() { return output; } @Override - public boolean isIngredient(ItemStack ingredient) - { + public boolean isIngredient(ItemStack ingredient) { return this.ingredient.test(ingredient); } } diff --git a/src/main/java/net/minecraftforge/common/brewing/BrewingRecipeRegistry.java b/src/main/java/net/minecraftforge/common/brewing/BrewingRecipeRegistry.java index 20e23cfab0..5a7e8aa86d 100644 --- a/src/main/java/net/minecraftforge/common/brewing/BrewingRecipeRegistry.java +++ b/src/main/java/net/minecraftforge/common/brewing/BrewingRecipeRegistry.java @@ -12,57 +12,20 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.core.NonNullList; +/* public class BrewingRecipeRegistry { - private static List recipes = new ArrayList(); - - static - { - addRecipe(new VanillaBrewingRecipe()); - } - - /** - * Adds a recipe to the registry. Due to the nature of the brewing stand - * inputs that stack (a.k.a max stack size > 1) are not allowed. - * - * @param input - * The Ingredient that goes in same slots as the water bottles - * would. - * @param ingredient - * The Ingredient that goes in the same slot as nether wart would. - * @param output - * The ItemStack that will replace the input once the brewing is - * done. - * @return true if the recipe was added. - */ - public static boolean addRecipe(Ingredient input, Ingredient ingredient, ItemStack output) - { - return addRecipe(new BrewingRecipe(input, ingredient, output)); - } - - /** - * Adds a recipe to the registry. Due to the nature of the brewing stand - * inputs that stack (a.k.a max stack size > 1) are not allowed. - */ - public static boolean addRecipe(IBrewingRecipe recipe) - { - return recipes.add(recipe); - } - /** * Returns the output ItemStack obtained by brewing the passed input and * ingredient. - */ - public static ItemStack getOutput(ItemStack input, ItemStack ingredient) - { + * / + public static ItemStack getOutput(ItemStack input, ItemStack ingredient) { if (input.isEmpty() || input.getCount() != 1) return ItemStack.EMPTY; if (ingredient.isEmpty()) return ItemStack.EMPTY; - for (IBrewingRecipe recipe : recipes) - { + for (IBrewingRecipe recipe : recipes) { ItemStack output = recipe.getOutput(input, ingredient); - if (!output.isEmpty()) - { + if (!output.isEmpty()) { return output; } } @@ -71,9 +34,8 @@ public class BrewingRecipeRegistry { /** * Returns true if the passed input and ingredient have an output - */ - public static boolean hasOutput(ItemStack input, ItemStack ingredient) - { + * / + public static boolean hasOutput(ItemStack input, ItemStack ingredient) { return !getOutput(input, ingredient).isEmpty(); } @@ -81,15 +43,12 @@ public class BrewingRecipeRegistry { * Used by the brewing stand to determine if its contents can be brewed. * Extra parameters exist to allow modders to create bigger brewing stands * without much hassle - */ - public static boolean canBrew(NonNullList inputs, ItemStack ingredient, int[] inputIndexes) - { + * / + public static boolean canBrew(NonNullList inputs, ItemStack ingredient, int[] inputIndexes) { if (ingredient.isEmpty()) return false; - for (int i : inputIndexes) - { - if (hasOutput(inputs.get(i), ingredient)) - { + for (int i : inputIndexes) { + if (hasOutput(inputs.get(i), ingredient)) { return true; } } @@ -100,58 +59,14 @@ public class BrewingRecipeRegistry { /** * Used by the brewing stand to brew its inventory Extra parameters exist to * allow modders to create bigger brewing stands without much hassle - */ - public static void brewPotions(NonNullList inputs, ItemStack ingredient, int[] inputIndexes) - { - for (int i : inputIndexes) - { + * / + public static void brewPotions(NonNullList inputs, ItemStack ingredient, int[] inputIndexes) { + for (int i : inputIndexes) { ItemStack output = getOutput(inputs.get(i), ingredient); - if (!output.isEmpty()) - { + if (!output.isEmpty()) { inputs.set(i, output); } } } - - /** - * Returns true if the passed ItemStack is a valid ingredient for any of the - * recipes in the registry. - */ - public static boolean isValidIngredient(ItemStack stack) - { - if (stack.isEmpty()) return false; - - for (IBrewingRecipe recipe : recipes) - { - if (recipe.isIngredient(stack)) - { - return true; - } - } - return false; - } - - /** - * Returns true if the passed ItemStack is a valid input for any of the - * recipes in the registry. - */ - public static boolean isValidInput(ItemStack stack) - { - for (IBrewingRecipe recipe : recipes) - { - if (recipe.isInput(stack)) - { - return true; - } - } - return false; - } - - /** - * Returns an unmodifiable list containing all the recipes in the registry - */ - public static List getRecipes() - { - return Collections.unmodifiableList(recipes); - } } +*/ diff --git a/src/main/java/net/minecraftforge/common/brewing/VanillaBrewingRecipe.java b/src/main/java/net/minecraftforge/common/brewing/VanillaBrewingRecipe.java index 9c9c9db2c6..d07e60e58a 100644 --- a/src/main/java/net/minecraftforge/common/brewing/VanillaBrewingRecipe.java +++ b/src/main/java/net/minecraftforge/common/brewing/VanillaBrewingRecipe.java @@ -5,8 +5,9 @@ package net.minecraftforge.common.brewing; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.Item; +import java.util.function.BiFunction; + +import net.minecraft.world.inventory.BrewingStandMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.alchemy.PotionBrewing; @@ -16,24 +17,28 @@ import net.minecraft.world.item.alchemy.PotionBrewing; * Most of the code was simply adapted from net.minecraft.tileentity.TileEntityBrewingStand */ public class VanillaBrewingRecipe implements IBrewingRecipe { + private final PotionBrewing vanilla; + private final BiFunction vanillaMix; - /** - * Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack) - */ - @Override - public boolean isInput(ItemStack stack) - { - Item item = stack.getItem(); - return item == Items.POTION || item == Items.SPLASH_POTION || item == Items.LINGERING_POTION || item == Items.GLASS_BOTTLE; + public VanillaBrewingRecipe(PotionBrewing vanilla, BiFunction vanillaMix) { + this.vanilla = vanilla; + this.vanillaMix = vanillaMix; } /** * Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack) */ @Override - public boolean isIngredient(ItemStack stack) - { - return PotionBrewing.isIngredient(stack); + public boolean isInput(ItemStack stack) { + return BrewingStandMenu.PotionSlot.mayPlaceItem(stack); + } + + /** + * Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack) + */ + @Override + public boolean isIngredient(ItemStack stack) { + return vanilla.isContainerIngredient(stack) || vanilla.isPotionIngredient(stack); } /** @@ -42,13 +47,10 @@ public class VanillaBrewingRecipe implements IBrewingRecipe { * or if the new potion is a splash potion when the old one wasn't. */ @Override - public ItemStack getOutput(ItemStack input, ItemStack ingredient) - { - if (!input.isEmpty() && !ingredient.isEmpty() && isIngredient(ingredient)) - { - ItemStack result = PotionBrewing.mix(ingredient, input); - if (result != input) - { + public ItemStack getOutput(ItemStack input, ItemStack ingredient) { + if (!input.isEmpty() && !ingredient.isEmpty() && isIngredient(ingredient)) { + ItemStack result = vanillaMix.apply(ingredient, input); + if (result != input) { return result; } return ItemStack.EMPTY; diff --git a/src/main/java/net/minecraftforge/common/crafting/ConditionalAdvancement.java b/src/main/java/net/minecraftforge/common/crafting/ConditionalAdvancement.java index d187b1ef7a..bca5e39395 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ConditionalAdvancement.java +++ b/src/main/java/net/minecraftforge/common/crafting/ConditionalAdvancement.java @@ -9,12 +9,14 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.serialization.JsonOps; -import net.minecraft.Util; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.core.HolderLookup; +import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.crafting.conditions.ICondition; @@ -37,7 +39,7 @@ public class ConditionalAdvancement { public static class Builder { private static final ResourceLocation DOESNT_MATTER = new ResourceLocation("doesnt", "matter"); - private List advancements = new ArrayList<>(); + private List advancements = new ArrayList<>(); private ICondition condition; public Builder condition(ICondition value) { @@ -58,26 +60,41 @@ public class ConditionalAdvancement { return advancement(holder.value()); } + public Builder advancement(JsonObject value) { + return advancement(null, value); + } + private Builder advancement(Advancement value) { + return advancement(value, null); + } + + private Builder advancement(Advancement value, JsonObject json) { if (condition == null) throw new IllegalStateException("Can not add a advancement with no conditions."); if (value == null) throw new IllegalStateException("Can not add a null advancement"); - this.advancements.add(new Pair(this.condition, value)); + this.advancements.add(new Adv(this.condition, value, json)); this.condition = null; return this; } - public JsonObject build() { + public JsonObject build(HolderLookup.Provider lookup) { var json = new JsonObject(); var array = new JsonArray(); json.add("advancements", array); + var ops = lookup.createSerializationContext(JsonOps.INSTANCE); + for (var pair : advancements) { - JsonObject holder = (JsonObject)Util.getOrThrow(Advancement.CODEC.encodeStart(JsonOps.INSTANCE, pair.adv()), IllegalStateException::new); + JsonObject holder = null; + if (pair.json != null) + holder = pair.json; + else + holder = (JsonObject)Advancement.CODEC.encodeStart(ops, pair.adv()).getOrThrow(IllegalStateException::new); + if (holder.has(ICondition.DEFAULT_FIELD)) throw new IllegalStateException("Recipe already serialized conditions!"); ForgeHooks.writeCondition(pair.condition(), holder); @@ -88,5 +105,5 @@ public class ConditionalAdvancement { } } - private record Pair(ICondition condition, Advancement adv) {} + private record Adv(ICondition condition, Advancement adv, JsonObject json) {} } diff --git a/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java b/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java index 7f2ae81734..726fd01ac9 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java +++ b/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java @@ -13,20 +13,20 @@ import java.util.stream.Stream; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapDecoder; import com.mojang.serialization.MapEncoder; import com.mojang.serialization.MapLike; import com.mojang.serialization.RecordBuilder; -import net.minecraft.Util; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderLookup.Provider; import net.minecraft.data.recipes.RecipeBuilder; import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.world.Container; @@ -35,12 +35,12 @@ import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; import net.minecraftforge.common.crafting.conditions.ConditionCodec; import net.minecraftforge.common.crafting.conditions.ICondition; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraftforge.common.crafting.conditions.ICondition.IContext; import org.jetbrains.annotations.Nullable; /** @@ -79,11 +79,16 @@ public class ConditionalRecipe { public void accept(ResourceLocation id, Recipe recipe, ResourceLocation advancementId, JsonElement advancement) { AdvancementHolder holder = null; if (advancement != null) { - Advancement adv = Util.getOrThrow(Advancement.CODEC.parse(JsonOps.INSTANCE, advancement), JsonParseException::new); + Advancement adv = Advancement.CODEC.parse(JsonOps.INSTANCE, advancement).getOrThrow(JsonParseException::new); holder = new AdvancementHolder(advancementId, adv); } accept(id, recipe, holder); } + + @Override + public Provider registry() { + return null; + } }; @Nullable @@ -118,7 +123,7 @@ public class ConditionalRecipe { throw new IllegalStateException("Can not add a recipe with no conditions."); recipes.add(new InnerRecipe(this.condition, recipe)); if (advancement != null) - advancements.add(new InnerAdvancement(this.condition, advancement)); + advancements.add(new InnerAdvancement(this.condition, advancement, null)); condition = null; return this; } @@ -143,12 +148,15 @@ public class ConditionalRecipe { if (!advancements.isEmpty()) { var adv = ConditionalAdvancement.builder(); for (var data : advancements) { - adv.condition(data.condition()) - .advancement(data.advancement()); + adv.condition(data.condition()); + if (data.json != null) + adv.advancement(data.json()); + else + adv.advancement(data.advancement()); } if (advancementId == null) advancementId = id.withPrefix("recipes/"); - advancement = adv.build(); + advancement = adv.build(out.registry()); } else { advancementId = null; } @@ -158,13 +166,13 @@ public class ConditionalRecipe { } private record InnerRecipe(ICondition condition, Recipe recipe) {} - private record InnerAdvancement(ICondition condition, AdvancementHolder advancement) {} + private record InnerAdvancement(ICondition condition, AdvancementHolder advancement, JsonObject json) {} private static class Wrapper implements Recipe { @Override public boolean matches(Container inv, Level level) { return false; } - @Override public ItemStack assemble(Container inv, RegistryAccess reg) { return null; } + @Override public ItemStack assemble(Container inv, HolderLookup.Provider reg) { return null; } @Override public boolean canCraftInDimensions(int width, int height) { return false; } - @Override public ItemStack getResultItem(RegistryAccess reg) { return null; } + @Override public ItemStack getResultItem(HolderLookup.Provider reg) { return null; } @Override public RecipeSerializer getSerializer() { return ConditionalRecipe.SERIALZIER; } @Override public RecipeType getType() { throw new UnsupportedOperationException(); } @@ -176,7 +184,7 @@ public class ConditionalRecipe { } } - private static final Codec> CODEC = Codec.of(new MapEncoder.Implementation<>() { + private static final MapCodec> CODEC = Codec.of(new MapEncoder.Implementation<>() { @Override public RecordBuilder encode(Recipe input, DynamicOps ops, RecordBuilder prefix) { if (!(input instanceof Wrapper)) @@ -188,14 +196,15 @@ public class ConditionalRecipe { else if (wrapper.recipes.size() == 1) prefix.add(ICondition.DEFAULT_FIELD, ICondition.CODEC.encodeStart(ops, wrapper.recipes.get(0).condition())); - var recipes = new ArrayList(); + var recipes = ops.listBuilder(); for (var recipe : wrapper.recipes) { - var json = (JsonObject)json(Recipe.CODEC, recipe.recipe()); - if (wrapper.recipes.size() > 1) - json.add(ICondition.DEFAULT_FIELD, json(ICondition.CODEC, recipe.condition())); - recipes.add(JsonOps.INSTANCE.convertTo(ops, json)); + var map = ops.mapBuilder(); + if (wrapper.main != null || wrapper.recipes.size() != 1) + map.add(ICondition.DEFAULT_FIELD, recipe.condition(), ICondition.CODEC); + map.add("recipe", recipe.recipe(), Recipe.CODEC); + recipes.add(map.build(ops.emptyMap())); } - prefix.add("recipes", ops.createList(recipes.stream())); + prefix.add("recipes", recipes.build(ops.emptyList())); return prefix; } @@ -203,65 +212,67 @@ public class ConditionalRecipe { public Stream keys(DynamicOps ops) { return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes")); } - - - private static JsonElement json(Codec codec, T object) { - return Util.getOrThrow(codec.encodeStart(JsonOps.INSTANCE, object), IllegalStateException::new); - } }, new MapDecoder.Implementation>() { @Override public DataResult> decode(DynamicOps ops, MapLike input) { var context = ConditionCodec.getContext(ops); - var json = ops.convertTo(JsonOps.INSTANCE, input.get("recipes")); - try { - var recipes = GsonHelper.convertToJsonArray(json, "recipes"); - int idx = 0; - for (var entry : recipes) { - var object = GsonHelper.convertToJsonObject(entry, "recipe[" + idx++ + "]"); - if (object.has(ICondition.DEFAULT_FIELD)) { - var conditionjson = GsonHelper.getAsJsonObject(object, ICondition.DEFAULT_FIELD); - var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, conditionjson), JsonSyntaxException::new); - if (!condition.test(context)) - continue; - } - var type = new ResourceLocation(GsonHelper.getAsString(object, "type")); - var serializer = ForgeRegistries.RECIPE_SERIALIZERS.getValue(type); - if (serializer == null) - return DataResult.error(() -> "Invalid or unsupported recipe type '" + type + "' Conditions were successful, but unknown type"); - var parsed = serializer.codec().parse(JsonOps.INSTANCE, object); - if (parsed.error().isPresent()) - return DataResult.error(parsed.error().get()::message); - else if (!parsed.result().isPresent()) - return DataResult.error(() -> "Recipe passed all conditions but did not parse a valid return"); - else - return DataResult.success(parsed.result().get()); - } + return ops.getStream(input.get("recipes")).flatMap(stream -> { + var count = new Holder(); + count.value = -1; + var ret = stream.map(entry -> accept(context, ops, count, entry)) + .filter(entry -> entry != null) + .findFirst() + .orElse(null); + + if (ret != null) + return ret; + return DataResult.error(() -> "No recipe passed conditions, if this is the case, you should have an outer condition."); - } catch (JsonSyntaxException e) { - return DataResult.error(() -> e.getMessage()); + }); + } + + private DataResult> accept(IContext context, DynamicOps ops, Holder count, T entry) { + count.value = count.value + 1; + var map = ops.getMap(entry).result().orElse(null); + if (map == null) + return DataResult.error(() -> "Entry " + count.value + " was not MapLike " + entry.getClass()); + + if (map.get(ICondition.DEFAULT_FIELD) != null) { + var parsed = ICondition.SAFE_CODEC.parse(ops, (T)map.get(ICondition.DEFAULT_FIELD)); + if (parsed.result().isPresent()) { + var condition = parsed.result().get(); + if (!condition.test(context, ops)) + return null; + } } + + var recipe = map.get("recipe"); + if (recipe == null) + return DataResult.error(() -> "Missing `recipe` entry " + count.value); + + var ret = Recipe.CODEC.parse(ops, (T)recipe); + return ret; } @Override public Stream keys(DynamicOps ops) { return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes")); } - }).codec(); + }); public static final RecipeSerializer> SERIALZIER = new RecipeSerializer>() { @Override - public Codec> codec() { + public MapCodec> codec() { return CODEC; } @Override - public Recipe fromNetwork(FriendlyByteBuf buffer) { - throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support decoding from network"); - } - - @Override - public void toNetwork(FriendlyByteBuf buffer, Recipe recipe) { + public StreamCodec> streamCodec() { throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network"); } }; + + private static class Holder { + private T value; + } } diff --git a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java b/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java deleted file mode 100644 index a5d8254aa8..0000000000 --- a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common.crafting; - -import java.util.Objects; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.nbt.TagParser; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.util.GsonHelper; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.ForgeRegistries; - -public class CraftingHelper { - private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - - public static ItemStack getItemStack(JsonObject json, boolean readNBT) { - return getItemStack(json, readNBT, false); - } - - public static Item getItem(String itemName, boolean disallowsAirInRecipe) { - ResourceLocation itemKey = new ResourceLocation(itemName); - if (!ForgeRegistries.ITEMS.containsKey(itemKey)) - throw new JsonSyntaxException("Unknown item '" + itemName + "'"); - - Item item = ForgeRegistries.ITEMS.getValue(itemKey); - if (disallowsAirInRecipe && item == Items.AIR) - throw new JsonSyntaxException("Invalid item: " + itemName); - return Objects.requireNonNull(item); - } - - public static CompoundTag getNBT(JsonElement element) { - try { - if (element.isJsonObject()) - return TagParser.parseTag(GSON.toJson(element)); - else - return TagParser.parseTag(GsonHelper.convertToString(element, "nbt")); - } catch (CommandSyntaxException e) { - throw new JsonSyntaxException("Invalid NBT Entry: " + e); - } - } - - public static ItemStack getItemStack(JsonObject json, boolean readNBT, boolean disallowsAirInRecipe) { - String itemName = GsonHelper.getAsString(json, "item"); - Item item = getItem(itemName, disallowsAirInRecipe); - if (readNBT && json.has("nbt")) { - CompoundTag nbt = getNBT(json.get("nbt")); - CompoundTag tmp = new CompoundTag(); - if (nbt.contains("ForgeCaps")) { - tmp.put("ForgeCaps", nbt.get("ForgeCaps")); - nbt.remove("ForgeCaps"); - } - - tmp.put("tag", nbt); - tmp.putString("id", itemName); - tmp.putInt("Count", GsonHelper.getAsInt(json, "count", 1)); - - return ItemStack.of(tmp); - } - - return new ItemStack(item, GsonHelper.getAsInt(json, "count", 1)); - } -} diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/AndCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/AndCondition.java index 5d276112c4..fc1a872916 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/AndCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/AndCondition.java @@ -8,18 +8,19 @@ package net.minecraftforge.common.crafting.conditions; import java.util.List; import com.google.common.base.Joiner; -import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; public record AndCondition(List children) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ICondition.CODEC.listOf().fieldOf("values").forGetter(AndCondition::children) ).apply(b, AndCondition::new)); @Override - public boolean test(IContext context) { + public boolean test(IContext context, DynamicOps ops) { for (ICondition child : children) { - if (!child.test(context)) + if (!child.test(context, ops)) return false; } return true; @@ -31,7 +32,7 @@ public record AndCondition(List children) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java b/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java index 60284a6562..b3829f7d7b 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java @@ -62,7 +62,7 @@ public class ConditionCodec { return DataResult.error(() -> conditionDecoded.error().get().message()); var condition = conditionDecoded.result().get(); - if (!condition.test(getContext(ops))) + if (!condition.test(getContext(ops), ops)) return DataResult.success(Pair.of(Optional.empty(), ops.empty())); return normal.decode(ops, input).map(p -> p.mapFirst(Optional::of)); diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/FalseCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/FalseCondition.java index b003d080e3..d3fea8b7b6 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/FalseCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/FalseCondition.java @@ -5,16 +5,17 @@ package net.minecraftforge.common.crafting.conditions; -import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; public final class FalseCondition implements ICondition { public static final FalseCondition INSTANCE = new FalseCondition(); - public static final Codec CODEC = Codec.unit(INSTANCE).stable(); + public static final MapCodec CODEC = MapCodec.unit(INSTANCE).stable(); private FalseCondition() { } @Override - public boolean test(IContext condition) { + public boolean test(IContext condition, DynamicOps ops) { return false; } @@ -24,7 +25,7 @@ public final class FalseCondition implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/ICondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/ICondition.java index a77cc2bbae..43154be66b 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/ICondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/ICondition.java @@ -6,6 +6,7 @@ package net.minecraftforge.common.crafting.conditions; import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; import com.mojang.serialization.MapCodec; import net.minecraft.core.Holder; @@ -13,7 +14,6 @@ import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; -import net.minecraft.util.ExtraCodecs; import net.minecraftforge.registries.ForgeRegistries; import java.util.Collection; @@ -26,14 +26,14 @@ import java.util.function.Function; import org.jetbrains.annotations.ApiStatus; public interface ICondition { - Codec CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.CONDITION_SERIALIZERS.get().getCodec().dispatch(ICondition::codec, Function.identity())); + Codec CODEC = Codec.lazyInitialized(() -> ForgeRegistries.CONDITION_SERIALIZERS.get().getCodec().dispatch(ICondition::codec, Function.identity())); String DEFAULT_FIELD = "forge:condition"; MapCodec> OPTIONAL_FEILD_CODEC = CODEC.optionalFieldOf(DEFAULT_FIELD); Codec SAFE_CODEC = CODEC.orElse(FalseCondition.INSTANCE); - boolean test(IContext context); + boolean test(IContext context, DynamicOps ops); - Codec codec(); + MapCodec codec(); interface IContext { /* Key used to attach this context option to a DynamicOps instance */ diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/ItemExistsCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/ItemExistsCondition.java index 92fc2c9f5d..24db37e188 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/ItemExistsCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/ItemExistsCondition.java @@ -5,19 +5,36 @@ package net.minecraftforge.common.crafting.conditions; -import com.mojang.serialization.Codec; +import java.util.Optional; + +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; import net.minecraftforge.registries.ForgeRegistries; public record ItemExistsCondition(ResourceLocation item) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ResourceLocation.CODEC.fieldOf("item").forGetter(ItemExistsCondition::item) ).apply(b, ItemExistsCondition::new)); @Override - public boolean test(IContext context) { + public boolean test(IContext context, DynamicOps ops) { + // Check the actual deserialization context if possible + if (ops instanceof RegistryOps reg) { + Optional> items = reg.getter(Registries.ITEM); + if (items.isPresent()) { + var key = ResourceKey.create(Registries.ITEM, this.item); + return items.get().get(key).isPresent(); + } + } + // Default to the active registry if its missing return ForgeRegistries.ITEMS.containsKey(item); } @@ -27,7 +44,7 @@ public record ItemExistsCondition(ResourceLocation item) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/ModLoadedCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/ModLoadedCondition.java index c30623b14d..d82a3631e7 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/ModLoadedCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/ModLoadedCondition.java @@ -6,17 +6,19 @@ package net.minecraftforge.common.crafting.conditions; import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraftforge.fml.ModList; public record ModLoadedCondition(String modid) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( Codec.STRING.fieldOf("modid").forGetter(ModLoadedCondition::modid) ).apply(b, ModLoadedCondition::new)); @Override - public boolean test(IContext context) { + public boolean test(IContext context, DynamicOps ops) { return ModList.get().isLoaded(modid); } @@ -26,7 +28,7 @@ public record ModLoadedCondition(String modid) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/NotCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/NotCondition.java index 2018c0ccfb..47c174da41 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/NotCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/NotCondition.java @@ -5,17 +5,18 @@ package net.minecraftforge.common.crafting.conditions; -import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; public record NotCondition(ICondition child) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ICondition.CODEC.fieldOf("value").forGetter(NotCondition::child) ).apply(b, NotCondition::new)); @Override - public boolean test(IContext context) { - return !child.test(context); + public boolean test(IContext context, DynamicOps ops) { + return !child.test(context, ops); } @Override @@ -24,7 +25,7 @@ public record NotCondition(ICondition child) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/OrCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/OrCondition.java index 18e4ebce13..e49b69cf5a 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/OrCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/OrCondition.java @@ -8,19 +8,20 @@ package net.minecraftforge.common.crafting.conditions; import java.util.List; import com.google.common.base.Joiner; -import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; public record OrCondition(List children) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ICondition.CODEC.listOf().fieldOf("values").forGetter(OrCondition::children) ).apply(b, OrCondition::new)); @Override - public boolean test(IContext context) { + public boolean test(IContext context, DynamicOps ops) { for (ICondition child : children) { - if (child.test(context)) + if (child.test(context, ops)) return true; } @@ -33,7 +34,7 @@ public record OrCondition(List children) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/TagEmptyCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/TagEmptyCondition.java index a6ba226f12..4068d5441c 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/TagEmptyCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/TagEmptyCondition.java @@ -5,22 +5,36 @@ package net.minecraftforge.common.crafting.conditions; -import com.mojang.serialization.Codec; +import java.util.Optional; + +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderGetter; import net.minecraft.core.registries.Registries; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; public record TagEmptyCondition(TagKey tag) implements ICondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ResourceLocation.CODEC.xmap(loc -> TagKey.create(Registries.ITEM, loc), TagKey::location).fieldOf("tag").forGetter(TagEmptyCondition::tag) ).apply(b, TagEmptyCondition::new)); @Override - public boolean test(ICondition.IContext context) { + public boolean test(ICondition.IContext context, DynamicOps ops) { + // Check the actual deserialization context if possible + if (ops instanceof RegistryOps reg) { + Optional> items = reg.getter(Registries.ITEM); + if (items.isPresent()) { + var optional = items.get().get(this.tag); + return optional.isPresent(); + } + } return context.getTag(tag).isEmpty(); } @@ -30,7 +44,7 @@ public record TagEmptyCondition(TagKey tag) implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/conditions/TrueCondition.java b/src/main/java/net/minecraftforge/common/crafting/conditions/TrueCondition.java index 0f048e70ac..90a6e56921 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/TrueCondition.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/TrueCondition.java @@ -5,16 +5,17 @@ package net.minecraftforge.common.crafting.conditions; -import com.mojang.serialization.Codec; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; public final class TrueCondition implements ICondition { public static final TrueCondition INSTANCE = new TrueCondition(); - public static final Codec CODEC = Codec.unit(INSTANCE).stable(); + public static final MapCodec CODEC = MapCodec.unit(INSTANCE).stable(); private TrueCondition() {} @Override - public boolean test(IContext context) { + public boolean test(IContext context, DynamicOps ops) { return true; } @@ -24,7 +25,7 @@ public final class TrueCondition implements ICondition { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/AbstractIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/AbstractIngredient.java index e57581a3fc..dadafe5b06 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/AbstractIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/AbstractIngredient.java @@ -5,7 +5,6 @@ package net.minecraftforge.common.crafting.ingredients; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -72,10 +71,4 @@ public abstract class AbstractIngredient extends Ingredient { public static Ingredient of(TagKey tag) { throw new UnsupportedOperationException("Use Ingredient.of()"); } - - /** @deprecated use {@link Ingredient#fromNetwork(FriendlyByteBuf)} */ - @Deprecated - public static Ingredient fromNetwork(FriendlyByteBuf buffer) { - throw new UnsupportedOperationException("Use Ingredient.fromNetwork()"); - } } diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java index 4ec9f374a6..ea9f0f1c5e 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java @@ -10,7 +10,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.common.collect.Lists; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.ints.IntArrayList; @@ -18,7 +18,8 @@ import it.unimi.dsi.fastutil.ints.IntComparators; import it.unimi.dsi.fastutil.ints.IntList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -97,7 +98,7 @@ public class CompoundIngredient extends AbstractIngredient { return SERIALIZER; } - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Ingredient.CODEC_NONEMPTY.listOf().fieldOf("children").forGetter(i -> i.children) ).apply(builder, CompoundIngredient::new) @@ -105,23 +106,18 @@ public class CompoundIngredient extends AbstractIngredient { public static final IIngredientSerializer SERIALIZER = new IIngredientSerializer<>() { @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } @Override - public void write(FriendlyByteBuf buffer, CompoundIngredient value) { - buffer.writeVarInt(value.children.size()); - for (var child : value.children) - child.toNetwork(buffer); + public void write(RegistryFriendlyByteBuf buffer, CompoundIngredient value) { + buffer.writeCollection(value.children, (buf, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); } @Override - public CompoundIngredient read(FriendlyByteBuf buffer) { - int size = buffer.readVarInt(); - var children = new ArrayList(size); - for (int x = 0; x < size; x++) - children.add(Ingredient.fromNetwork(buffer)); + public CompoundIngredient read(RegistryFriendlyByteBuf buffer) { + var children = buffer.readCollection(ArrayList::new, buf -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer)); return new CompoundIngredient(children); } }; diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/DifferenceIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/DifferenceIngredient.java index c79af58629..db790810e9 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/DifferenceIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/DifferenceIngredient.java @@ -5,13 +5,13 @@ package net.minecraftforge.common.crafting.ingredients; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntComparators; import it.unimi.dsi.fastutil.ints.IntList; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.StackedContents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -93,7 +93,7 @@ public class DifferenceIngredient extends AbstractIngredient { return SERIALIZER; } - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Ingredient.CODEC.fieldOf("base").forGetter(i -> i.base), Ingredient.CODEC.fieldOf("subtracted").forGetter(i -> i.subtracted) @@ -102,21 +102,21 @@ public class DifferenceIngredient extends AbstractIngredient { public static final IIngredientSerializer SERIALIZER = new IIngredientSerializer<>() { @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } @Override - public DifferenceIngredient read(FriendlyByteBuf buffer) { - Ingredient base = Ingredient.fromNetwork(buffer); - Ingredient without = Ingredient.fromNetwork(buffer); + public DifferenceIngredient read(RegistryFriendlyByteBuf buffer) { + Ingredient base = Ingredient.CONTENTS_STREAM_CODEC.decode(buffer); + Ingredient without = Ingredient.CONTENTS_STREAM_CODEC.decode(buffer); return new DifferenceIngredient(base, without); } @Override - public void write(FriendlyByteBuf buffer, DifferenceIngredient ingredient) { - ingredient.base.toNetwork(buffer); - ingredient.subtracted.toNetwork(buffer); + public void write(RegistryFriendlyByteBuf buffer, DifferenceIngredient ingredient) { + Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, ingredient.base); + Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, ingredient.subtracted); } }; } diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/IIngredientSerializer.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/IIngredientSerializer.java index 6375cca443..a0e3ea355f 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/IIngredientSerializer.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/IIngredientSerializer.java @@ -5,30 +5,35 @@ package net.minecraftforge.common.crafting.ingredients; -import com.mojang.serialization.Codec; +import java.util.Arrays; +import com.mojang.serialization.MapCodec; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.network.FriendlyByteBuf; public interface IIngredientSerializer { - Codec codec(); - void write(FriendlyByteBuf buffer, T value); - T read(FriendlyByteBuf buffer); + MapCodec codec(); + + void write(RegistryFriendlyByteBuf buffer, T value); + T read(RegistryFriendlyByteBuf buffer); + IIngredientSerializer VANILLA = new IIngredientSerializer<>() { @Override - public Codec codec() { - return Ingredient.VANILLA_CODEC; + public MapCodec codec() { + return Ingredient.VANILLA_MAP_CODEC; } @Override - public void write(FriendlyByteBuf buffer, Ingredient value) { - value.toNetwork(buffer); + public void write(RegistryFriendlyByteBuf buffer, Ingredient value) { + ItemStack.LIST_STREAM_CODEC.encode(buffer, Arrays.asList(value.getItems())); } @Override - public Ingredient read(FriendlyByteBuf buffer) { - return Ingredient.fromNetwork(buffer); + public Ingredient read(RegistryFriendlyByteBuf buffer) { + return Ingredient.of(ItemStack.LIST_STREAM_CODEC.decode(buffer).stream()); } }; } diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java index 897122b391..c79df879ea 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java @@ -5,18 +5,19 @@ package net.minecraftforge.common.crafting.ingredients; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntComparators; import it.unimi.dsi.fastutil.ints.IntList; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.StackedContents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -113,7 +114,7 @@ public class IntersectionIngredient extends AbstractIngredient { return SERIALIZER; } - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Ingredient.CODEC.listOf().fieldOf("children").forGetter(i -> i.children) ) @@ -122,18 +123,19 @@ public class IntersectionIngredient extends AbstractIngredient { public static final IIngredientSerializer SERIALIZER = new IIngredientSerializer<>() { @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } @Override - public IntersectionIngredient read(FriendlyByteBuf buffer) { - return new IntersectionIngredient(buffer.readList(Ingredient::fromNetwork)); + public IntersectionIngredient read(RegistryFriendlyByteBuf buffer) { + var children = buffer.readCollection(ArrayList::new, buf -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer)); + return new IntersectionIngredient(children); } @Override - public void write(FriendlyByteBuf buffer, IntersectionIngredient value) { - buffer.writeCollection(value.children, (b, i) -> i.toNetwork(b)); + public void write(RegistryFriendlyByteBuf buffer, IntersectionIngredient value) { + buffer.writeCollection(value.children, (b, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); } }; } diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/PartialNBTIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/PartialNBTIngredient.java index a04cfaefb2..610fe9bb47 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/PartialNBTIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/PartialNBTIngredient.java @@ -5,15 +5,17 @@ package net.minecraftforge.common.crafting.ingredients; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.advancements.critereon.NbtPredicate; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.TagParser; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; import net.minecraftforge.registries.ForgeRegistries; @@ -39,7 +41,7 @@ public class PartialNBTIngredient extends AbstractIngredient { super(items.stream().map(item -> { var stack = new ItemStack(item); // copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag - stack.setTag(nbt.copy()); + stack.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt.copy())); return new Ingredient.ItemValue(stack); })); @@ -65,7 +67,8 @@ public class PartialNBTIngredient extends AbstractIngredient { public boolean test(@Nullable ItemStack input) { if (input == null) return false; - return items.contains(input.getItem()) && predicate.matches(input.getShareTag()); + var nbt = input.get(DataComponents.CUSTOM_DATA); + return nbt != null && items.contains(input.getItem()) && predicate.matches(nbt.copyTag()); } @Override @@ -78,7 +81,7 @@ public class PartialNBTIngredient extends AbstractIngredient { return SERIALIZER; } - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( ForgeRegistries.ITEMS.getCodec().listOf().fieldOf("items").forGetter(i -> i.items), TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt) @@ -87,20 +90,20 @@ public class PartialNBTIngredient extends AbstractIngredient { public static final IIngredientSerializer SERIALIZER = new IIngredientSerializer<>() { @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } @Override - public PartialNBTIngredient read(FriendlyByteBuf buffer) { - var items = buffer.readList(b -> b.readRegistryIdUnsafe(ForgeRegistries.ITEMS)); + public PartialNBTIngredient read(RegistryFriendlyByteBuf buffer) { + var items = buffer.readList(b -> Item.STREAM_CODEC.decode(buffer).get()); var nbt = buffer.readNbt(); return new PartialNBTIngredient(items, Objects.requireNonNull(nbt)); } @Override - public void write(FriendlyByteBuf buffer, PartialNBTIngredient value) { - buffer.writeCollection(value.items, (b, item) -> b.writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item)); + public void write(RegistryFriendlyByteBuf buffer, PartialNBTIngredient value) { + buffer.writeCollection(value.items, (b, item) -> Item.STREAM_CODEC.encode(buffer, item.builtInRegistryHolder())); buffer.writeNbt(value.nbt); } }; diff --git a/src/main/java/net/minecraftforge/common/crafting/ingredients/StrictNBTIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/StrictNBTIngredient.java index 9691e61f00..91bc754d9e 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/StrictNBTIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/StrictNBTIngredient.java @@ -7,12 +7,13 @@ package net.minecraftforge.common.crafting.ingredients; import java.util.stream.Stream; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.jetbrains.annotations.Nullable; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; /** Ingredient that matches the given stack, performing an exact NBT match. Use {@link PartialNBTIngredient} if you need partial match. */ @@ -32,7 +33,12 @@ public class StrictNBTIngredient extends AbstractIngredient { if (input == null) return false; //Can't use areItemStacksEqualUsingNBTShareTag because it compares stack size as well - return this.stack.getItem() == input.getItem() && this.stack.getDamageValue() == input.getDamageValue() && this.stack.areShareTagsEqual(input); + var inbt = input.get(DataComponents.CUSTOM_DATA); + var tnbt = this.stack.get(DataComponents.CUSTOM_DATA); + if(inbt == null || tnbt == null) + return false; + + return this.stack.getItem() == input.getItem() && tnbt.matchedBy(inbt.copyTag()); } @Override @@ -45,24 +51,25 @@ public class StrictNBTIngredient extends AbstractIngredient { return SERIALIZER; } - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ItemStack.CODEC.fieldOf("stack").forGetter(i -> i.stack) ).apply(b, StrictNBTIngredient::new)); public static final IIngredientSerializer SERIALIZER = new IIngredientSerializer<>() { @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } @Override - public void write(FriendlyByteBuf buffer, StrictNBTIngredient value) { - buffer.writeItem(value.stack); + public void write(RegistryFriendlyByteBuf buffer, StrictNBTIngredient value) { + ItemStack.STREAM_CODEC.encode(buffer, value.stack); } @Override - public StrictNBTIngredient read(FriendlyByteBuf buffer) { - return new StrictNBTIngredient(buffer.readItem()); + public StrictNBTIngredient read(RegistryFriendlyByteBuf buffer) { + var stack = ItemStack.STREAM_CODEC.decode(buffer); + return new StrictNBTIngredient(stack); } }; } diff --git a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java index 91159722e9..da5520f26c 100644 --- a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java +++ b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java @@ -7,10 +7,12 @@ package net.minecraftforge.common.data; import java.io.File; import java.io.FileNotFoundException; +import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Optional; import java.util.Set; import com.google.common.collect.HashMultimap; @@ -19,15 +21,22 @@ import com.google.common.collect.Multimap; import net.minecraft.client.resources.ClientPackSource; import net.minecraft.client.resources.IndexedAssetSource; import net.minecraft.data.DataProvider; +import net.minecraft.network.chat.Component; import net.minecraft.server.packs.FilePackResources; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.FilePackResources.FileResourcesSupplier; import net.minecraft.server.packs.PathPackResources; +import net.minecraft.server.packs.repository.FolderRepositorySource; +import net.minecraft.server.packs.repository.PackSource; import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.server.packs.resources.MultiPackResourceManager; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.world.level.validation.DirectoryValidator; +import net.minecraft.world.level.validation.ForbiddenSymlinkInfo; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.PathPackResources.PathResourcesSupplier; import net.minecraft.server.packs.VanillaPackResources; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.client.model.generators.ModelBuilder; @@ -102,16 +111,29 @@ public class ExistingFileHelper { candidateClientResources.add(ClientPackSource.createVanillaPackSource(IndexedAssetSource.createIndexFs(assetsDir.toPath(), assetIndex))); } candidateServerResources.add(ServerPacksSource.createVanillaPackSource()); + + var symlinks = new ArrayList(); + var folder = new FolderRepositorySource.FolderPackDetector(new DirectoryValidator(p -> true)); + for (Path existing : existingPacks) { - File file = existing.toFile(); - PackResources pack = file.isDirectory() ? new PathPackResources(file.getName(), file.toPath(), false) : new FileResourcesSupplier(file, false).openPrimary(file.getName()); // FilePackResources(file.getName(), file, false, ""); - candidateClientResources.add(pack); - candidateServerResources.add(pack); + try { + var info = new PackLocationInfo(existing.getFileName().toString(), Component.literal("data_gen"), PackSource.DEFAULT, Optional.empty()); + var supplier = folder.detectPackResources(existing, symlinks, false); + PackResources pack = supplier.openPrimary(info); + candidateClientResources.add(pack); + candidateServerResources.add(pack); + }catch (IOException e) { + throw new RuntimeException(e); + } } + for (String existingMod : existingMods) { IModFileInfo modFileInfo = ModList.get().getModFileById(existingMod); if (modFileInfo != null) { - PackResources pack = ResourcePackLoader.createPackForMod(modFileInfo); + var root = modFileInfo.getFile().findResource("/"); + var supplier = new PathResourcesSupplier(root); + var info = new PackLocationInfo("mod:" + existingMod, Component.literal("data_gen:" + existingMod), PackSource.DEFAULT, Optional.empty()); + var pack = supplier.openPrimary(info); candidateClientResources.add(pack); candidateServerResources.add(pack); } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java index 704b15df34..2e4e3f14ce 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java @@ -6,13 +6,15 @@ package net.minecraftforge.common.data; import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; import net.minecraft.data.PackOutput; import net.minecraft.data.loot.LootTableProvider; import net.minecraft.data.loot.LootTableSubProvider; import net.minecraft.data.loot.packs.VanillaLootTableProvider; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.ProblemReporter; import net.minecraft.world.level.storage.loot.predicates.CompositeLootItemCondition; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.world.level.storage.loot.predicates.InvertedLootItemCondition; @@ -24,8 +26,8 @@ import net.minecraftforge.fml.util.ObfuscationReflectionHelper; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; @@ -47,12 +49,12 @@ public final class ForgeLootTableProvider extends LootTableProvider { private static final String ENTRY_CONDITION = "f_7963" + "6_"; // LootPoolEntryContainer.conditions private static final String TERMS = "f_28560" + "9_"; // CompositeLootItemCondition.terms - public ForgeLootTableProvider(PackOutput packOutput) { - super(packOutput, Set.of(), VanillaLootTableProvider.create(packOutput).getTables()); + public ForgeLootTableProvider(PackOutput pack, CompletableFuture lookup) { + super(pack, Set.of(), VanillaLootTableProvider.create(pack, lookup).getTables(), lookup); } @Override - protected void validate(Map map, ValidationContext validationcontext) { + protected void validate(Registry map, ValidationContext validationcontext, ProblemReporter report) { // Do not validate against all registered loot tables } @@ -65,7 +67,7 @@ public final class ForgeLootTableProvider extends LootTableProvider { } private LootTableSubProvider replaceAndFilterChangesOnly(LootTableSubProvider subProvider) { - return newConsumer -> subProvider.generate((resourceLocation, builder) -> { + return (provider, newConsumer) -> subProvider.generate(provider, (resourceLocation, builder) -> { if (findAndReplaceInLootTableBuilder(builder, Items.SHEARS, ToolActions.SHEARS_DIG)) { newConsumer.accept(resourceLocation, builder); } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java index 5dc564689c..e18a377508 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java @@ -8,6 +8,8 @@ package net.minecraftforge.common.data; import com.google.gson.JsonElement; import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.Advancement.Builder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderLookup.Provider; import net.minecraft.data.CachedOutput; import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.RecipeOutput; @@ -44,8 +46,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { private final Map> replacements = new HashMap<>(); private final Set excludes = new HashSet<>(); - public ForgeRecipeProvider(PackOutput packOutput) { - super(packOutput); + public ForgeRecipeProvider(PackOutput packOutput, CompletableFuture lookup) { + super(packOutput, lookup); } private void exclude(ItemLike item) { @@ -110,6 +112,11 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { @Override public void accept(ResourceLocation id, Recipe recipe, ResourceLocation advancementId, JsonElement advancement) { } + + @Override + public Provider registry() { + return consumer.registry(); + } }); } @@ -144,7 +151,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { } @Override - protected CompletableFuture buildAdvancement(CachedOutput p_253674_, AdvancementHolder p_297687_) { + protected CompletableFuture buildAdvancement(CachedOutput p_253674_, HolderLookup.Provider p_335995_, AdvancementHolder p_297687_) { // NOOP - We don't replace any of the advancement things yet... return CompletableFuture.allOf(); } @@ -172,7 +179,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { boolean modified = false; List items = new ArrayList<>(); - Value[] vanillaItems = getField(Ingredient.class, vanilla, 2); //This will probably crash between versions, if null fix index + Value[] vanillaItems = getField(Ingredient.class, vanilla, 3); //This will probably crash between versions, if null fix index for (Value entry : vanillaItems) { if (entry instanceof ItemValue) { ItemStack stack = entry.getItems().stream().findFirst().orElse(ItemStack.EMPTY); diff --git a/src/main/java/net/minecraftforge/common/data/GlobalLootModifierProvider.java b/src/main/java/net/minecraftforge/common/data/GlobalLootModifierProvider.java index bc63f6115c..effa85d476 100644 --- a/src/main/java/net/minecraftforge/common/data/GlobalLootModifierProvider.java +++ b/src/main/java/net/minecraftforge/common/data/GlobalLootModifierProvider.java @@ -8,10 +8,10 @@ package net.minecraftforge.common.data; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.serialization.JsonOps; import cpw.mods.modlauncher.api.LamdbaExceptionUtils; +import net.minecraft.core.HolderLookup; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; @@ -32,25 +32,24 @@ import java.util.stream.Collectors; * * This provider only requires implementing {@link #start()} and calling {@link #add} from it. */ -public abstract class GlobalLootModifierProvider implements DataProvider -{ +public abstract class GlobalLootModifierProvider implements DataProvider { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private final PackOutput output; private final String modid; - private final Map toSerialize = new HashMap<>(); + private final CompletableFuture registries; + private final Map toSerialize = new HashMap<>(); private boolean replace = false; - public GlobalLootModifierProvider(PackOutput output, String modid) - { + public GlobalLootModifierProvider(PackOutput output, String modid, CompletableFuture registries) { this.output = output; this.modid = modid; + this.registries = registries; } /** * Sets the "replace" key in global_loot_modifiers to true. */ - protected void replacing() - { + protected void replacing() { this.replace = true; } @@ -60,18 +59,25 @@ public abstract class GlobalLootModifierProvider implements DataProvider protected abstract void start(); @Override - public CompletableFuture run(CachedOutput cache) - { + public CompletableFuture run(CachedOutput cache) { + return this.registries.thenCompose(p -> this.run(cache, p)); + } + + private CompletableFuture run(CachedOutput cache, HolderLookup.Provider registries) { start(); - Path forgePath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("forge").resolve("loot_modifiers").resolve("global_loot_modifiers.json"); + Path forgePath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("forge/loot_modifiers/global_loot_modifiers.json"); Path modifierFolderPath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(this.modid).resolve("loot_modifiers"); List entries = new ArrayList<>(); ImmutableList.Builder> futuresBuilder = new ImmutableList.Builder<>(); - toSerialize.forEach(LamdbaExceptionUtils.rethrowBiConsumer((name, json) -> - { + + var ops = registries.createSerializationContext(JsonOps.INSTANCE); + var codec = IGlobalLootModifier.DIRECT_CODEC; + + toSerialize.forEach(LamdbaExceptionUtils.rethrowBiConsumer((name, instance) -> { + var json = codec.encodeStart(ops, instance).getOrThrow(); entries.add(new ResourceLocation(modid, name)); Path modifierPath = modifierFolderPath.resolve(name + ".json"); futuresBuilder.add(DataProvider.saveStable(cache, json, modifierPath)); @@ -92,15 +98,12 @@ public abstract class GlobalLootModifierProvider implements DataProvider * @param modifier The name of the modifier, which will be the file name. * @param instance The instance to serialize */ - public void add(String modifier, T instance) - { - JsonElement json = IGlobalLootModifier.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, instance).getOrThrow(false, s -> {}); - this.toSerialize.put(modifier, json); + public void add(String modifier, T instance) { + this.toSerialize.put(modifier, instance); } @Override - public String getName() - { + public String getName() { return "Global Loot Modifiers : " + modid; } } diff --git a/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java b/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java index c93364847b..bf108915d6 100644 --- a/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java +++ b/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java @@ -87,7 +87,7 @@ public class JsonCodecProvider implements DataProvider gather(LamdbaExceptionUtils.rethrowBiConsumer((id, value) -> { final Path path = outputFolder.resolve(id.getNamespace()).resolve(this.directory).resolve(id.getPath() + ".json"); JsonElement encoded = this.codec.encodeStart(this.dynamicOps, value) - .getOrThrow(false, msg -> LOGGER.error("Failed to encode {}: {}", path, msg)); + .getOrThrow( msg -> new IllegalStateException(String.format("Failed to encode {}: {}", path, msg))); /* TODO: Conditional JSONS ICondition[] conditions = this.conditions.get(id); if (conditions != null && conditions.length > 0) diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeBlock.java b/src/main/java/net/minecraftforge/common/extensions/IForgeBlock.java index aae32ae48f..ab2fbc0801 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeBlock.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeBlock.java @@ -12,8 +12,8 @@ import net.minecraft.client.Camera; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.SpawnPlacementType; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.entity.boss.wither.WitherBoss; @@ -31,7 +31,7 @@ import net.minecraft.world.level.levelgen.feature.configurations.TreeConfigurati import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.MapColor; import net.minecraft.world.level.material.PushReaction; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.tags.BlockTags; import net.minecraft.core.Direction; import net.minecraft.core.BlockPos; @@ -58,11 +58,9 @@ import net.minecraftforge.fml.loading.FMLEnvironment; import org.jetbrains.annotations.Nullable; @SuppressWarnings("deprecation") -public interface IForgeBlock -{ - private Block self() - { - return (Block) this; +public interface IForgeBlock { + private Block self() { + return (Block)this; } /** @@ -80,8 +78,7 @@ public interface IForgeBlock * @param entity the entity in question * @return the factor by which the entity's motion should be multiplied */ - default float getFriction(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity) - { + default float getFriction(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity) { return self().getFriction(); } @@ -110,8 +107,7 @@ public interface IForgeBlock * * */ - default int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) - { + default int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { return state.getLightEmission(); } @@ -124,8 +120,7 @@ public interface IForgeBlock * @param entity The entity trying to use the ladder, CAN be null. * @return True if the block should act like a ladder */ - default boolean isLadder(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) - { + default boolean isLadder(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) { return state.is(BlockTags.CLIMBABLE); } @@ -138,8 +133,7 @@ public interface IForgeBlock * @param trapdoorState The current state of the open trapdoor above * @return True if the block should act like a ladder */ - default boolean makesOpenTrapdoorAboveClimbable(BlockState state, LevelReader level, BlockPos pos, BlockState trapdoorState) - { + default boolean makesOpenTrapdoorAboveClimbable(BlockState state, LevelReader level, BlockPos pos, BlockState trapdoorState) { return state.getBlock() instanceof LadderBlock && state.getValue(LadderBlock.FACING) == trapdoorState.getValue(TrapDoorBlock.FACING); } @@ -151,8 +145,7 @@ public interface IForgeBlock * @param pos Block position in level * @return True if the block should deal damage */ - default boolean isBurning(BlockState state, BlockGetter level, BlockPos pos) - { + default boolean isBurning(BlockState state, BlockGetter level, BlockPos pos) { return this == Blocks.FIRE || this == Blocks.LAVA; } @@ -164,8 +157,7 @@ public interface IForgeBlock * @param player The player damaging the block * @return True to spawn the drops */ - default public boolean canHarvestBlock(BlockState state, BlockGetter level, BlockPos pos, Player player) - { + default public boolean canHarvestBlock(BlockState state, BlockGetter level, BlockPos pos, Player player) { return ForgeHooks.isCorrectToolForDrops(state, player); } @@ -189,8 +181,7 @@ public interface IForgeBlock * @param fluid The current fluid state at current position * @return True if the block is actually destroyed. */ - default boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) - { + default boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) { self().playerWillDestroy(level, pos, state, player); return level.setBlock(pos, fluid.createLegacyBlock(), level.isClientSide ? 11 : 3); } @@ -206,8 +197,7 @@ public interface IForgeBlock * @param player The player or camera entity, null in some cases. * @return True to treat this as a bed */ - default boolean isBed(BlockState state, BlockGetter level, BlockPos pos, @Nullable Entity player) - { + default boolean isBed(BlockState state, BlockGetter level, BlockPos pos, @Nullable Entity player) { return self() instanceof BedBlock; //TODO: Forge: Keep isBed function? } @@ -223,10 +213,8 @@ public interface IForgeBlock * @param entity The entity respawning, often null * @return The spawn position or the empty optional if respawning here is not possible */ - default Optional getRespawnPosition(BlockState state, EntityType type, LevelReader levelReader, BlockPos pos, float orientation, @Nullable LivingEntity entity) - { - if (isBed(state, levelReader, pos, entity) && levelReader instanceof Level level && BedBlock.canSetSpawn(level)) - { + default Optional getRespawnPosition(BlockState state, EntityType type, LevelReader levelReader, BlockPos pos, float orientation, @Nullable LivingEntity entity) { + if (isBed(state, levelReader, pos, entity) && levelReader instanceof Level level && BedBlock.canSetSpawn(level)) { return BedBlock.findStandUpPosition(type, levelReader, pos, state.getValue(BedBlock.FACING), orientation); } return Optional.empty(); @@ -242,8 +230,7 @@ public interface IForgeBlock * @param type The Mob Category Type * @return True to allow a mob of the specified category to spawn, false to prevent it. */ - default boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type, EntityType entityType) - { + default boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacementType type, EntityType entityType) { return state.isValidSpawn(level, pos, entityType); } @@ -255,8 +242,7 @@ public interface IForgeBlock * @param sleeper The sleeper or camera entity, null in some cases. * @param occupied True if we are occupying the bed, or false if they are stopping use of the bed */ - default void setBedOccupied(BlockState state, Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) - { + default void setBedOccupied(BlockState state, Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) { level.setBlock(pos, state.setValue(BedBlock.OCCUPIED, occupied), 3); } @@ -269,8 +255,7 @@ public interface IForgeBlock * @param pos Block position in level * @return Bed direction */ - default Direction getBedDirection(BlockState state, LevelReader level, BlockPos pos) - { + default Direction getBedDirection(BlockState state, LevelReader level, BlockPos pos) { return state.getValue(HorizontalDirectionalBlock.FACING); } @@ -282,8 +267,7 @@ public interface IForgeBlock * @param explosion The explosion * @return The amount of the explosion absorbed. */ - default float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) - { + default float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) { return self().getExplosionResistance(); } @@ -294,8 +278,7 @@ public interface IForgeBlock * @param target The full target the player is looking at * @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added. */ - default ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) - { + default ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { return self().getCloneItemStack(level, pos, state); } @@ -311,8 +294,7 @@ public interface IForgeBlock * @param numberOfParticles That vanilla level have spawned * @return True to prevent vanilla landing particles from spawning */ - default boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) - { + default boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) { return false; } @@ -328,8 +310,7 @@ public interface IForgeBlock * @param entity The entity running on the block. * @return True to prevent vanilla running particles from spawning. */ - default boolean addRunningEffects(BlockState state, Level level, BlockPos pos, Entity entity) - { + default boolean addRunningEffects(BlockState state, Level level, BlockPos pos, Entity entity) { return false; } @@ -372,8 +353,7 @@ public interface IForgeBlock * @param config Configuration of the trunk placer. Consider azalea trees, which should place rooted dirt instead of regular dirt. * @return True to ignore vanilla behaviour */ - default boolean onTreeGrow(BlockState state, LevelReader level, BiConsumer placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) - { + default boolean onTreeGrow(BlockState state, LevelReader level, BiConsumer placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) { return false; } @@ -386,8 +366,7 @@ public interface IForgeBlock * @param pos Block position in level * @return True if the soil should be considered fertile. */ - default boolean isFertile(BlockState state, BlockGetter level, BlockPos pos) - { + default boolean isFertile(BlockState state, BlockGetter level, BlockPos pos) { if (state.is(Blocks.FARMLAND)) return state.getValue(FarmBlock.MOISTURE) > 0; @@ -402,8 +381,7 @@ public interface IForgeBlock * @param conduit Conduit position in level * @return True, to support the conduit, and make it active with this block. */ - default boolean isConduitFrame(BlockState state, LevelReader level, BlockPos pos, BlockPos conduit) - { + default boolean isConduitFrame(BlockState state, LevelReader level, BlockPos pos, BlockPos conduit) { return state.getBlock() == Blocks.PRISMARINE || state.getBlock() == Blocks.PRISMARINE_BRICKS || state.getBlock() == Blocks.SEA_LANTERN || @@ -418,8 +396,7 @@ public interface IForgeBlock * @param pos Block position in level * @return True, to support being part of a nether portal frame, false otherwise. */ - default boolean isPortalFrame(BlockState state, BlockGetter level, BlockPos pos) - { + default boolean isPortalFrame(BlockState state, BlockGetter level, BlockPos pos) { return state.is(Blocks.OBSIDIAN); } @@ -434,13 +411,11 @@ public interface IForgeBlock * @param silkTouchLevel silk touch enchantment level of tool being used * @return Amount of XP from breaking this block. */ - default int getExpDrop(BlockState state, LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) - { + default int getExpDrop(BlockState state, LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { return 0; } - default BlockState rotate(BlockState state, LevelAccessor level, BlockPos pos, Rotation direction) - { + default BlockState rotate(BlockState state, LevelAccessor level, BlockPos pos, Rotation direction) { return state.rotate(direction); } @@ -450,8 +425,7 @@ public interface IForgeBlock * @param pos Block position in level * @return The amount of enchanting power this block produces. */ - default float getEnchantPowerBonus(BlockState state, LevelReader level, BlockPos pos) - { + default float getEnchantPowerBonus(BlockState state, LevelReader level, BlockPos pos) { return state.is(BlockTags.ENCHANTMENT_POWER_PROVIDER) ? 1: 0; } @@ -470,8 +444,7 @@ public interface IForgeBlock * @param side The INPUT side of the block to be powered - ie the opposite of this block's output side * @return Whether Block#isProvidingWeakPower should be called when determining indirect power */ - default boolean shouldCheckWeakPower(BlockState state, SignalGetter level, BlockPos pos, Direction side) - { + default boolean shouldCheckWeakPower(BlockState state, SignalGetter level, BlockPos pos, Direction side) { return state.isRedstoneConductor(level, pos); } @@ -484,8 +457,7 @@ public interface IForgeBlock * @param pos Block position in level * @return true To be notified of changes */ - default boolean getWeakChanges(BlockState state, LevelReader level, BlockPos pos) - { + default boolean getWeakChanges(BlockState state, LevelReader level, BlockPos pos) { return false; } @@ -497,10 +469,7 @@ public interface IForgeBlock * @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context * @return A SoundType to use */ - default SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity) - { - return self().getSoundType(state); - } + SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity); /** * @param state The state @@ -510,10 +479,9 @@ public interface IForgeBlock * @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam */ @Nullable - default float[] getBeaconColorMultiplier(BlockState state, LevelReader level, BlockPos pos, BlockPos beaconPos) - { - if (self() instanceof BeaconBeamBlock) - return ((BeaconBeamBlock) self()).getColor().getTextureDiffuseColors(); + default float[] getBeaconColorMultiplier(BlockState state, LevelReader level, BlockPos pos, BlockPos beaconPos) { + if (self() instanceof BeaconBeamBlock beam) + return beam.getColor().getTextureDiffuseColors(); return null; } @@ -528,8 +496,7 @@ public interface IForgeBlock * @param viewpoint the viewpoint * @return the block state that should be 'seen' */ - default BlockState getStateAtViewpoint(BlockState state, BlockGetter level, BlockPos pos, Vec3 viewpoint) - { + default BlockState getStateAtViewpoint(BlockState state, BlockGetter level, BlockPos pos, Vec3 viewpoint) { return state; } @@ -544,9 +511,8 @@ public interface IForgeBlock * @return the path type of this block */ @Nullable - default BlockPathTypes getBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob) - { - return state.getBlock() == Blocks.LAVA ? BlockPathTypes.LAVA : state.isBurning(level, pos) ? BlockPathTypes.DAMAGE_FIRE : null; + default PathType getBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob) { + return state.getBlock() == Blocks.LAVA ? PathType.LAVA : state.isBurning(level, pos) ? PathType.DAMAGE_FIRE : null; } /** @@ -563,10 +529,9 @@ public interface IForgeBlock * @return the path type of this block */ @Nullable - default BlockPathTypes getAdjacentBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) - { - if (state.is(Blocks.SWEET_BERRY_BUSH)) return BlockPathTypes.DANGER_OTHER; - else if (WalkNodeEvaluator.isBurningBlock(state)) return BlockPathTypes.DANGER_FIRE; + default PathType getAdjacentBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) { + if (state.is(Blocks.SWEET_BERRY_BUSH)) return PathType.DANGER_OTHER; + else if (WalkNodeEvaluator.isBurningBlock(state)) return PathType.DANGER_FIRE; else return null; } @@ -574,8 +539,7 @@ public interface IForgeBlock * @param state The state * @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston) */ - default boolean isSlimeBlock(BlockState state) - { + default boolean isSlimeBlock(BlockState state) { return state.getBlock() == Blocks.SLIME_BLOCK; } @@ -583,8 +547,7 @@ public interface IForgeBlock * @param state The state * @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston) */ - default boolean isStickyBlock(BlockState state) - { + default boolean isStickyBlock(BlockState state) { return state.getBlock() == Blocks.SLIME_BLOCK || state.getBlock() == Blocks.HONEY_BLOCK; } @@ -594,8 +557,7 @@ public interface IForgeBlock * @param other Other block * @return True to link blocks */ - default boolean canStickTo(BlockState state, BlockState other) - { + default boolean canStickTo(BlockState state, BlockState other) { if (state.getBlock() == Blocks.HONEY_BLOCK && other.getBlock() == Blocks.SLIME_BLOCK) return false; if (state.getBlock() == Blocks.SLIME_BLOCK && other.getBlock() == Blocks.HONEY_BLOCK) return false; return state.isStickyBlock() || other.isStickyBlock(); @@ -611,8 +573,7 @@ public interface IForgeBlock * @param direction The direction that the fire is coming from * @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire */ - default int getFlammability(BlockState state, BlockGetter level, BlockPos pos, Direction direction) - { + default int getFlammability(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { return ((FireBlock)Blocks.FIRE).getBurnOdds(state); } @@ -626,8 +587,7 @@ public interface IForgeBlock * @param direction The direction that the fire is coming from * @return True if the face can be on fire, false otherwise. */ - default boolean isFlammable(BlockState state, BlockGetter level, BlockPos pos, Direction direction) - { + default boolean isFlammable(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { return state.getFlammability(level, pos, direction) > 0; } @@ -652,8 +612,7 @@ public interface IForgeBlock * @param direction The direction that the fire is coming from * @return A number that is used to determine the speed of fire growth around the block */ - default int getFireSpreadSpeed(BlockState state, BlockGetter level, BlockPos pos, Direction direction) - { + default int getFireSpreadSpeed(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { return ((FireBlock)Blocks.FIRE).getIgniteOdds(state); } @@ -668,8 +627,7 @@ public interface IForgeBlock * @param direction The direction that the fire is coming from * @return True if this block sustains fire, meaning it will never go out. */ - default boolean isFireSource(BlockState state, LevelReader level, BlockPos pos, Direction direction) - { + default boolean isFireSource(BlockState state, LevelReader level, BlockPos pos, Direction direction) { return state.is(level.dimensionType().infiniburn()); } @@ -681,15 +639,11 @@ public interface IForgeBlock * @param pos Block position in level * @return True to allow the ender dragon to destroy this block */ - default boolean canEntityDestroy(BlockState state, BlockGetter level, BlockPos pos, Entity entity) - { - if (entity instanceof EnderDragon) - { + default boolean canEntityDestroy(BlockState state, BlockGetter level, BlockPos pos, Entity entity) { + if (entity instanceof EnderDragon) { return !this.self().defaultBlockState().is(BlockTags.DRAGON_IMMUNE); - } - else if ((entity instanceof WitherBoss) || - (entity instanceof WitherSkull)) - { + } else if ((entity instanceof WitherBoss) || + (entity instanceof WitherSkull)) { return state.isAir() || WitherBoss.canDestroy(state); } @@ -699,8 +653,7 @@ public interface IForgeBlock /** * Determines if this block should drop loot when exploded. */ - default boolean canDropFromExplosion(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) - { + default boolean canDropFromExplosion(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) { return state.getBlock().dropFromExplosion(explosion); } @@ -713,8 +666,7 @@ public interface IForgeBlock * @param pos Block position in level * @param explosion The explosion instance affecting the block */ - default void onBlockExploded(BlockState state, Level level, BlockPos pos, Explosion explosion) - { + default void onBlockExploded(BlockState state, Level level, BlockPos pos, Explosion explosion) { level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); self().wasExploded(level, pos, explosion); } @@ -723,8 +675,7 @@ public interface IForgeBlock * Determines if this block's collision box should be treated as though it can extend above its block space. * Use this to replicate fence and wall behavior. */ - default boolean collisionExtendsVertically(BlockState state, BlockGetter level, BlockPos pos, Entity collidingEntity) - { + default boolean collisionExtendsVertically(BlockState state, BlockGetter level, BlockPos pos, Entity collidingEntity) { return state.is(BlockTags.FENCES) || state.is(BlockTags.WALLS) || self() instanceof FenceGateBlock; } @@ -737,8 +688,7 @@ public interface IForgeBlock * @param fluidState The state of the fluid * @return Whether the fluid overlay texture should be used */ - default boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter level, BlockPos pos, FluidState fluidState) - { + default boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter level, BlockPos pos, FluidState fluidState) { return state.getBlock() instanceof HalfTransparentBlock || state.getBlock() instanceof LeavesBlock; } @@ -755,38 +705,29 @@ public interface IForgeBlock * @return The resulting state after the action has been performed */ @Nullable - default BlockState getToolModifiedState(BlockState state, UseOnContext context, ToolAction toolAction, boolean simulate) - { + default BlockState getToolModifiedState(BlockState state, UseOnContext context, ToolAction toolAction, boolean simulate) { ItemStack itemStack = context.getItemInHand(); if (!itemStack.canPerformAction(toolAction)) return null; - if (ToolActions.AXE_STRIP == toolAction) - { + if (ToolActions.AXE_STRIP == toolAction) { return AxeItem.getAxeStrippingState(state); - } else if (ToolActions.AXE_SCRAPE == toolAction) - { + } else if (ToolActions.AXE_SCRAPE == toolAction) { return WeatheringCopper.getPrevious(state).orElse(null); - } else if (ToolActions.AXE_WAX_OFF == toolAction) - { + } else if (ToolActions.AXE_WAX_OFF == toolAction) { return Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(state.getBlock())).map(block -> block.withPropertiesOf(state)).orElse(null); - } else if (ToolActions.SHOVEL_FLATTEN == toolAction) - { + } else if (ToolActions.SHOVEL_FLATTEN == toolAction) { return ShovelItem.getShovelPathingState(state); - } else if (ToolActions.HOE_TILL == toolAction) - { + } else if (ToolActions.HOE_TILL == toolAction) { // Logic copied from HoeItem#TILLABLES; needs to be kept in sync during updating Block block = state.getBlock(); - if (block == Blocks.ROOTED_DIRT) - { - if (!simulate && !context.getLevel().isClientSide) - { + if (block == Blocks.ROOTED_DIRT) { + if (!simulate && !context.getLevel().isClientSide) { Block.popResourceFromFace(context.getLevel(), context.getClickedPos(), context.getClickedFace(), new ItemStack(Items.HANGING_ROOTS)); } return Blocks.DIRT.defaultBlockState(); } else if ((block == Blocks.GRASS_BLOCK || block == Blocks.DIRT_PATH || block == Blocks.DIRT || block == Blocks.COARSE_DIRT) && - context.getLevel().getBlockState(context.getClickedPos().above()).isAir()) - { + context.getLevel().getBlockState(context.getClickedPos().above()).isAir()) { return block == Blocks.COARSE_DIRT ? Blocks.DIRT.defaultBlockState() : Blocks.FARMLAND.defaultBlockState(); } } @@ -803,8 +744,7 @@ public interface IForgeBlock * @param entity The entity on the scaffolding * @return True if the block should act like scaffolding */ - default boolean isScaffolding(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) - { + default boolean isScaffolding(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) { return state.is(Blocks.SCAFFOLDING); } @@ -837,23 +777,15 @@ public interface IForgeBlock * 2. {@code neighborState.updateShape(fromDirection, stateOfYourBlock, level, neighborBlockPos, yourBlockPos)}, * where {@code fromDirection} is defined from the neighbor block's point of view. */ - default boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) - { - if (state.is(Blocks.REDSTONE_WIRE)) - { + default boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) { + if (state.is(Blocks.REDSTONE_WIRE)) { return true; - } - else if (state.is(Blocks.REPEATER)) - { + } else if (state.is(Blocks.REPEATER)) { Direction facing = state.getValue(RepeaterBlock.FACING); return facing == direction || facing.getOpposite() == direction; - } - else if (state.is(Blocks.OBSERVER)) - { + } else if (state.is(Blocks.OBSERVER)) { return direction == state.getValue(ObserverBlock.FACING); - } - else - { + } else { return state.isSignalSource() && direction != null; } } @@ -878,8 +810,7 @@ public interface IForgeBlock * @param neighborState The neighboring blocks {@link BlockState} * @param dir The direction towards the neighboring block */ - default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState state, BlockState neighborState, Direction dir) - { + default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState state, BlockState neighborState, Direction dir) { return false; } @@ -888,10 +819,8 @@ public interface IForgeBlock * If this returns true, {@link IForgeBlockState#hidesNeighborFace(BlockGetter, BlockPos, BlockState, Direction)} * will be called on the neighboring block. */ - default boolean supportsExternalFaceHiding(BlockState state) - { - if (FMLEnvironment.dist.isClient()) - { + default boolean supportsExternalFaceHiding(BlockState state) { + if (FMLEnvironment.dist.isClient()) { return !ForgeHooksClient.isBlockInSolidLayer(state); } return true; @@ -927,8 +856,7 @@ public interface IForgeBlock * @param fluidPos the position of the fluid * @return {@code true} if the block can be hydrated, {@code false} otherwise */ - default boolean canBeHydrated(BlockState state, BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) - { + default boolean canBeHydrated(BlockState state, BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) { return fluid.canHydrate(getter, fluidPos, state, pos); } @@ -940,8 +868,7 @@ public interface IForgeBlock * @param pos The blocks position in the level * @param defaultColor The {@code MapColor} configured for the given {@code BlockState} in the {@link BlockBehaviour.Properties} */ - default MapColor getMapColor(BlockState state, BlockGetter level, BlockPos pos, MapColor defaultColor) - { + default MapColor getMapColor(BlockState state, BlockGetter level, BlockPos pos, MapColor defaultColor) { return defaultColor; } @@ -968,8 +895,7 @@ public interface IForgeBlock * @return The appearance of this block on the given side. By default, the current state * @see IForgeBlockState#getAppearance(BlockAndTintGetter, BlockPos, Direction, BlockState, BlockPos) */ - default BlockState getAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) - { + default BlockState getAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) { return state; } @@ -988,8 +914,7 @@ public interface IForgeBlock * @return the PushReaction of this state or {@code null} if the one passed into the block properties should be used */ @Nullable - default PushReaction getPistonPushReaction(BlockState state) - { + default PushReaction getPistonPushReaction(BlockState state) { return null; } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java index 48863ac3e7..c186b2593b 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java @@ -19,26 +19,16 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.AABB; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.level.Level; import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.common.capabilities.ICapabilitySerializable; +import net.minecraftforge.common.capabilities.ICapabilityProvider; import org.jetbrains.annotations.NotNull; -public interface IForgeBlockEntity extends ICapabilitySerializable -{ - private BlockEntity self() { return (BlockEntity) this; } - - @Override - default void deserializeNBT(CompoundTag nbt) - { - self().load(nbt); - } - - @Override - default CompoundTag serializeNBT() - { - return self().saveWithFullMetadata(); +public interface IForgeBlockEntity extends ICapabilityProvider { + private BlockEntity self() { + return (BlockEntity)this; } /** @@ -50,34 +40,24 @@ public interface IForgeBlockEntity extends ICapabilitySerializable * @param net The NetworkManager the packet originated from * @param pkt The data packet */ - default void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) - { + default void onDataPacket(Connection connection, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider lookup) { CompoundTag compoundtag = pkt.getTag(); if (compoundtag != null) { - self().load(compoundtag); + self().loadWithComponents(compoundtag, lookup); } } /** * Called when the chunk's TE update tag, gotten from {@link BlockEntity#getUpdateTag()}, is received on the client. *

- * Used to handle this tag in a special way. By default this simply calls {@link BlockEntity#load(CompoundTag)}. + * Used to handle this tag in a special way. By default this simply calls {@link BlockEntity#loadWithComponents(CompoundTag, HolderLookup.Provider)}. * * @param tag The {@link CompoundTag} sent from {@link BlockEntity#getUpdateTag()} */ - default void handleUpdateTag(CompoundTag tag) - { - self().load(tag); + default void handleUpdateTag(CompoundTag tag, HolderLookup.Provider holders) { + self().loadWithComponents(tag, holders); } - /** - * Gets a {@link CompoundTag} that can be used to store custom data for this block entity. - * It will be written, and read from disc, so it persists over world saves. - * - * @return A compound tag for custom persistent data - */ - CompoundTag getPersistentData(); - default void onChunkUnloaded(){} /** @@ -85,8 +65,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable * or right before the first tick when the chunk is generated or loaded from disk. * Override instead of adding {@code if (firstTick)} stuff in update. */ - default void onLoad() - { + default void onLoad() { requestModelDataUpdate(); } @@ -137,15 +116,12 @@ public interface IForgeBlockEntity extends ICapabilitySerializable * Requests a refresh for the model data of your TE * Call this every time your {@link #getModelData()} changes */ - default void requestModelDataUpdate() - { + default void requestModelDataUpdate() { BlockEntity te = self(); Level level = te.getLevel(); - if (level != null && level.isClientSide) - { + if (level != null && level.isClientSide) { var modelDataManager = level.getModelDataManager(); - if (modelDataManager != null) - { + if (modelDataManager != null) { modelDataManager.requestRefresh(te); } } @@ -158,8 +134,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable * Note that this method may be called on a chunk render thread instead of the main client thread * @return Your model data */ - default @NotNull ModelData getModelData() - { + default @NotNull ModelData getModelData() { return ModelData.EMPTY; } @@ -169,8 +144,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable * @param player the local player currently viewing this {@code BlockEntity} * @return {@code true} to enable outline processing */ - default boolean hasCustomOutlineRendering(Player player) - { + default boolean hasCustomOutlineRendering(Player player) { return false; } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockState.java b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockState.java index 4097647c5c..f5315e8e70 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockState.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockState.java @@ -13,7 +13,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.SpawnPlacements.Type; +import net.minecraft.world.entity.SpawnPlacementType; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; @@ -23,7 +23,7 @@ import net.minecraft.world.level.SignalGetter; import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; @@ -45,10 +45,8 @@ import net.minecraftforge.common.ToolActions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public interface IForgeBlockState -{ - private BlockState self() - { +public interface IForgeBlockState { + private BlockState self() { return (BlockState)this; } @@ -66,16 +64,14 @@ public interface IForgeBlockState * @param entity the entity in question * @return the factor by which the entity's motion should be multiplied */ - default float getFriction(LevelReader level, BlockPos pos, @Nullable Entity entity) - { + default float getFriction(LevelReader level, BlockPos pos, @Nullable Entity entity) { return self().getBlock().getFriction(self(), level, pos, entity); } /** * Get a light value for this block, taking into account the given state and coordinates, normal ranges are between 0 and 15 */ - default int getLightEmission(BlockGetter level, BlockPos pos) - { + default int getLightEmission(BlockGetter level, BlockPos pos) { return self().getBlock().getLightEmission(self(), level, pos); } @@ -87,8 +83,7 @@ public interface IForgeBlockState * @param entity The entity trying to use the ladder, CAN be null. * @return True if the block should act like a ladder */ - default boolean isLadder(LevelReader level, BlockPos pos, LivingEntity entity) - { + default boolean isLadder(LevelReader level, BlockPos pos, LivingEntity entity) { return self().getBlock().isLadder(self(), level, pos, entity); } @@ -100,8 +95,7 @@ public interface IForgeBlockState * @param player The player damaging the block * @return True to spawn the drops */ - default boolean canHarvestBlock(BlockGetter level, BlockPos pos, Player player) - { + default boolean canHarvestBlock(BlockGetter level, BlockPos pos, Player player) { return self().getBlock().canHarvestBlock(self(), level, pos, player); } @@ -124,8 +118,7 @@ public interface IForgeBlockState * @param fluid The current fluid and block state for the position in the level. * @return True if the block is actually destroyed. */ - default boolean onDestroyedByPlayer(Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) - { + default boolean onDestroyedByPlayer(Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) { return self().getBlock().onDestroyedByPlayer(self(), level, pos, player, willHarvest, fluid); } @@ -139,8 +132,7 @@ public interface IForgeBlockState * @param sleeper The sleeper or camera entity, null in some cases. * @return True to treat this as a bed */ - default boolean isBed(BlockGetter level, BlockPos pos, @Nullable LivingEntity sleeper) - { + default boolean isBed(BlockGetter level, BlockPos pos, @Nullable LivingEntity sleeper) { return self().getBlock().isBed(self(), level, pos, sleeper); } @@ -153,8 +145,7 @@ public interface IForgeBlockState * @param type The Mob Category Type * @return True to allow a mob of the specified category to spawn, false to prevent it. */ - default boolean isValidSpawn(LevelReader level, BlockPos pos, Type type, EntityType entityType) - { + default boolean isValidSpawn(LevelReader level, BlockPos pos, SpawnPlacementType type, EntityType entityType) { return self().getBlock().isValidSpawn(self(), level, pos, type, entityType); } @@ -169,8 +160,7 @@ public interface IForgeBlockState * @param entity The entity respawning, often null * @return The spawn position or the empty optional if respawning here is not possible */ - default Optional getRespawnPosition(EntityType type, LevelReader level, BlockPos pos, float orientation, @Nullable LivingEntity entity) - { + default Optional getRespawnPosition(EntityType type, LevelReader level, BlockPos pos, float orientation, @Nullable LivingEntity entity) { return self().getBlock().getRespawnPosition(self(), type, level, pos, orientation, entity); } @@ -182,8 +172,7 @@ public interface IForgeBlockState * @param sleeper The sleeper or camera entity, null in some cases. * @param occupied True if we are occupying the bed, or false if they are stopping use of the bed */ - default void setBedOccupied(Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) - { + default void setBedOccupied(Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) { self().getBlock().setBedOccupied(self(), level, pos, sleeper, occupied); } @@ -195,8 +184,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return Bed direction */ - default Direction getBedDirection(LevelReader level, BlockPos pos) - { + default Direction getBedDirection(LevelReader level, BlockPos pos) { return self().getBlock().getBedDirection(self(), level, pos); } @@ -208,8 +196,7 @@ public interface IForgeBlockState * @param explosion The explosion * @return The amount of the explosion absorbed. */ - default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion) - { + default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion) { return self().getBlock().getExplosionResistance(self(), level, pos, explosion); } @@ -220,8 +207,7 @@ public interface IForgeBlockState * @param target The full target the player is looking at * @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added. */ - default ItemStack getCloneItemStack(HitResult target, LevelReader level, BlockPos pos, Player player) - { + default ItemStack getCloneItemStack(HitResult target, LevelReader level, BlockPos pos, Player player) { return self().getBlock().getCloneItemStack(self(), target, level, pos, player); } @@ -237,10 +223,10 @@ public interface IForgeBlockState * @param numberOfParticles That vanilla world have spawned * @return True to prevent vanilla landing particles from spawning */ - default boolean addLandingEffects(ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) - { + default boolean addLandingEffects(ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) { return self().getBlock().addLandingEffects(self(), level, pos, state2, entity, numberOfParticles); } + /** * Allows a block to override the standard vanilla running particles. * This is called from {@code Entity#spawnSprintParticle()} and is called both, @@ -252,8 +238,7 @@ public interface IForgeBlockState * @param entity The entity running on the block. * @return True to prevent vanilla running particles from spawning. */ - default boolean addRunningEffects(Level level, BlockPos pos, Entity entity) - { + default boolean addRunningEffects(Level level, BlockPos pos, Entity entity) { return self().getBlock().addRunningEffects(self(), level, pos, entity); } @@ -273,8 +258,7 @@ public interface IForgeBlockState * @param plantable The plant that wants to check * @return True to allow the plant to be planted/stay. */ - default boolean canSustainPlant(BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable) - { + default boolean canSustainPlant(BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable) { return self().getBlock().canSustainPlant(self(), level, pos, facing, plantable); } @@ -296,8 +280,7 @@ public interface IForgeBlockState * @param config Configuration of the trunk placer. Consider azalea trees, which should place rooted dirt instead of regular dirt. * @return True to ignore vanilla behaviour */ - default boolean onTreeGrow(LevelReader level, BiConsumer placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) - { + default boolean onTreeGrow(LevelReader level, BiConsumer placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) { return self().getBlock().onTreeGrow(self(), level, placeFunction, randomSource, pos, config); } @@ -310,8 +293,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return True if the soil should be considered fertile. */ - default boolean isFertile(BlockGetter level, BlockPos pos) - { + default boolean isFertile(BlockGetter level, BlockPos pos) { return self().getBlock().isFertile(self(), level, pos); } @@ -323,8 +305,7 @@ public interface IForgeBlockState * @param conduit Conduit position in level * @return True, to support the conduit, and make it active with this block. */ - default boolean isConduitFrame(LevelReader level, BlockPos pos, BlockPos conduit) - { + default boolean isConduitFrame(LevelReader level, BlockPos pos, BlockPos conduit) { return self().getBlock().isConduitFrame(self(), level, pos, conduit); } @@ -335,8 +316,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return True, to support being part of a nether portal frame, false otherwise. */ - default boolean isPortalFrame(BlockGetter level, BlockPos pos) - { + default boolean isPortalFrame(BlockGetter level, BlockPos pos) { return self().getBlock().isPortalFrame(self(), level, pos); } @@ -350,13 +330,11 @@ public interface IForgeBlockState * @param silkTouchLevel silk touch enchantment level of tool being used * @return Amount of XP from breaking this block. */ - default int getExpDrop(LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) - { + default int getExpDrop(LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) { return self().getBlock().getExpDrop(self(), level, randomSource, pos, fortuneLevel, silkTouchLevel); } - default BlockState rotate(LevelAccessor level, BlockPos pos, Rotation direction) - { + default BlockState rotate(LevelAccessor level, BlockPos pos, Rotation direction) { return self().getBlock().rotate(self(), level, pos, direction); } @@ -366,8 +344,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return The amount of enchanting power this block produces. */ - default float getEnchantPowerBonus(LevelReader level, BlockPos pos) - { + default float getEnchantPowerBonus(LevelReader level, BlockPos pos) { return self().getBlock().getEnchantPowerBonus(self(), level, pos); } @@ -377,8 +354,7 @@ public interface IForgeBlockState * @param pos Block position in level * @param neighbor Block position of neighbor */ - default void onNeighborChange(LevelReader level, BlockPos pos, BlockPos neighbor) - { + default void onNeighborChange(LevelReader level, BlockPos pos, BlockPos neighbor) { self().getBlock().onNeighborChange(self(), level, pos, neighbor); } @@ -389,8 +365,7 @@ public interface IForgeBlockState * @param side The INPUT side of the block to be powered - ie the opposite of this block's output side * @return Whether Block#isProvidingWeakPower should be called when determining indirect power */ - default boolean shouldCheckWeakPower(SignalGetter level, BlockPos pos, Direction side) - { + default boolean shouldCheckWeakPower(SignalGetter level, BlockPos pos, Direction side) { return self().getBlock().shouldCheckWeakPower(self(), level, pos, side); } @@ -403,8 +378,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return true To be notified of changes */ - default boolean getWeakChanges(LevelReader level, BlockPos pos) - { + default boolean getWeakChanges(LevelReader level, BlockPos pos) { return self().getBlock().getWeakChanges(self(), level, pos); } @@ -415,8 +389,7 @@ public interface IForgeBlockState * @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context * @return A SoundType to use */ - default SoundType getSoundType(LevelReader level, BlockPos pos, @Nullable Entity entity) - { + default SoundType getSoundType(LevelReader level, BlockPos pos, @Nullable Entity entity) { return self().getBlock().getSoundType(self(), level, pos, entity); } @@ -427,8 +400,7 @@ public interface IForgeBlockState * @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam */ @Nullable - default float[] getBeaconColorMultiplier(LevelReader level, BlockPos pos, BlockPos beacon) - { + default float[] getBeaconColorMultiplier(LevelReader level, BlockPos pos, BlockPos beacon) { return self().getBlock().getBeaconColorMultiplier(self(), level, pos, beacon); } @@ -442,24 +414,21 @@ public interface IForgeBlockState * @param viewpoint the viewpoint * @return the block state that should be 'seen' */ - default BlockState getStateAtViewpoint(BlockGetter level, BlockPos pos, Vec3 viewpoint) - { + default BlockState getStateAtViewpoint(BlockGetter level, BlockPos pos, Vec3 viewpoint) { return self().getBlock().getStateAtViewpoint(self(), level, pos, viewpoint); } /** * @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston) */ - default boolean isSlimeBlock() - { + default boolean isSlimeBlock() { return self().getBlock().isSlimeBlock(self()); } /** * @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston) */ - default boolean isStickyBlock() - { + default boolean isStickyBlock() { return self().getBlock().isStickyBlock(self()); } @@ -468,8 +437,7 @@ public interface IForgeBlockState * @param other Other block * @return True to link blocks */ - default boolean canStickTo(@NotNull BlockState other) - { + default boolean canStickTo(@NotNull BlockState other) { return self().getBlock().canStickTo(self(), other); } @@ -482,8 +450,7 @@ public interface IForgeBlockState * @param face The face that the fire is coming from * @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire */ - default int getFlammability(BlockGetter level, BlockPos pos, Direction face) - { + default int getFlammability(BlockGetter level, BlockPos pos, Direction face) { return self().getBlock().getFlammability(self(), level, pos, face); } @@ -495,8 +462,7 @@ public interface IForgeBlockState * @param face The face that the fire is coming from * @return True if the face can be on fire, false otherwise. */ - default boolean isFlammable(BlockGetter level, BlockPos pos, Direction face) - { + default boolean isFlammable(BlockGetter level, BlockPos pos, Direction face) { return self().getBlock().isFlammable(self(), level, pos, face); } @@ -508,8 +474,7 @@ public interface IForgeBlockState * @param face The face that the fire is coming from * @param igniter The entity that lit the fire */ - default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) - { + default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) { self().getBlock().onCaughtFire(self(), level, pos, face, igniter); } @@ -522,8 +487,7 @@ public interface IForgeBlockState * @param face The face that the fire is coming from * @return A number that is used to determine the speed of fire growth around the block */ - default int getFireSpreadSpeed(BlockGetter level, BlockPos pos, Direction face) - { + default int getFireSpreadSpeed(BlockGetter level, BlockPos pos, Direction face) { return self().getBlock().getFireSpreadSpeed(self(), level, pos, face); } @@ -537,8 +501,7 @@ public interface IForgeBlockState * @param side The face that the fire is coming from * @return True if this block sustains fire, meaning it will never go out. */ - default boolean isFireSource(LevelReader level, BlockPos pos, Direction side) - { + default boolean isFireSource(LevelReader level, BlockPos pos, Direction side) { return self().getBlock().isFireSource(self(), level, pos, side); } @@ -549,8 +512,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return True to allow the ender dragon to destroy this block */ - default boolean canEntityDestroy(BlockGetter level, BlockPos pos, Entity entity) - { + default boolean canEntityDestroy(BlockGetter level, BlockPos pos, Entity entity) { return self().getBlock().canEntityDestroy(self(), level, pos, entity); } @@ -562,8 +524,7 @@ public interface IForgeBlockState * @param pos Block position in level * @return True if the block should deal damage */ - default boolean isBurning(BlockGetter level, BlockPos pos) - { + default boolean isBurning(BlockGetter level, BlockPos pos) { return self().getBlock().isBurning(self(), level, pos); } @@ -577,8 +538,7 @@ public interface IForgeBlockState * @return the path type of this block */ @Nullable - default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob) - { + default PathType getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob) { return self().getBlock().getBlockPathType(self(), level, pos, mob); } @@ -595,16 +555,14 @@ public interface IForgeBlockState * @return the path type of this block */ @Nullable - default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) - { + default PathType getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) { return self().getBlock().getAdjacentBlockPathType(self(), level, pos, mob, originalType); } /** * Determines if this block should drop loot when exploded. */ - default boolean canDropFromExplosion(BlockGetter level, BlockPos pos, Explosion explosion) - { + default boolean canDropFromExplosion(BlockGetter level, BlockPos pos, Explosion explosion) { return self().getBlock().canDropFromExplosion(self(), level, pos, explosion); } @@ -617,8 +575,7 @@ public interface IForgeBlockState * @param pos Block position in level * @param explosion The explosion instance affecting the block */ - default void onBlockExploded(Level level, BlockPos pos, Explosion explosion) - { + default void onBlockExploded(Level level, BlockPos pos, Explosion explosion) { self().getBlock().onBlockExploded(self(), level, pos, explosion); } @@ -626,8 +583,7 @@ public interface IForgeBlockState * Determines if this block's collision box should be treated as though it can extend above its block space. * This can be used to replicate fence and wall behavior. */ - default boolean collisionExtendsVertically(BlockGetter level, BlockPos pos, Entity collidingEntity) - { + default boolean collisionExtendsVertically(BlockGetter level, BlockPos pos, Entity collidingEntity) { return self().getBlock().collisionExtendsVertically(self(), level, pos, collidingEntity); } @@ -639,8 +595,7 @@ public interface IForgeBlockState * @param fluidState The state of the fluid * @return Whether the fluid overlay texture should be used */ - default boolean shouldDisplayFluidOverlay(BlockAndTintGetter level, BlockPos pos, FluidState fluidState) - { + default boolean shouldDisplayFluidOverlay(BlockAndTintGetter level, BlockPos pos, FluidState fluidState) { return self().getBlock().shouldDisplayFluidOverlay(self(), level, pos, fluidState); } @@ -656,8 +611,7 @@ public interface IForgeBlockState * @return The resulting state after the action has been performed */ @Nullable - default BlockState getToolModifiedState(UseOnContext context, ToolAction toolAction, boolean simulate) - { + default BlockState getToolModifiedState(UseOnContext context, ToolAction toolAction, boolean simulate) { BlockState eventState = net.minecraftforge.event.ForgeEventFactory.onToolUse(self(), context, toolAction, simulate); return eventState != self() ? eventState : self().getBlock().getToolModifiedState(self(), context, toolAction, simulate); } @@ -668,8 +622,7 @@ public interface IForgeBlockState * @param entity The entity on the scaffolding * @return True if the block should act like scaffolding */ - default boolean isScaffolding(LivingEntity entity) - { + default boolean isScaffolding(LivingEntity entity) { return self().getBlock().isScaffolding(self(), entity.level(), entity.blockPosition(), entity); } @@ -683,8 +636,7 @@ public interface IForgeBlockState * @param direction The coming direction of the redstone dust connection (with respect to the block at pos) * @return True if redstone dust should visually connect on the side passed */ - default boolean canRedstoneConnectTo(BlockGetter level, BlockPos pos, @Nullable Direction direction) - { + default boolean canRedstoneConnectTo(BlockGetter level, BlockPos pos, @Nullable Direction direction) { return self().getBlock().canConnectRedstone(self(), level, pos, direction); } @@ -700,8 +652,7 @@ public interface IForgeBlockState * @param neighborState The neighboring blocks {@link BlockState} * @param dir The direction towards the neighboring block */ - default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState neighborState, Direction dir) - { + default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState neighborState, Direction dir) { return self().getBlock().hidesNeighborFace(level, pos, self(), neighborState, dir); } @@ -710,8 +661,7 @@ public interface IForgeBlockState * If this returns true, {@link IForgeBlockState#hidesNeighborFace(BlockGetter, BlockPos, BlockState, Direction)} * will be called on the neighboring block. */ - default boolean supportsExternalFaceHiding() - { + default boolean supportsExternalFaceHiding() { return self().getBlock().supportsExternalFaceHiding(self()); } @@ -725,8 +675,7 @@ public interface IForgeBlockState * @param pos The blocks position in the level * @param oldState The previous state of the block at the given position, may be a different block than this one */ - default void onBlockStateChange(LevelReader level, BlockPos pos, BlockState oldState) - { + default void onBlockStateChange(LevelReader level, BlockPos pos, BlockState oldState) { self().getBlock().onBlockStateChange(level, pos, oldState, self()); } @@ -746,8 +695,7 @@ public interface IForgeBlockState * @param fluidPos the position of the fluid * @return {@code true} if the block can be hydrated, {@code false} otherwise */ - default boolean canBeHydrated(BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) - { + default boolean canBeHydrated(BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) { return self().getBlock().canBeHydrated(self(), getter, pos, fluid, fluidPos); } @@ -762,8 +710,7 @@ public interface IForgeBlockState * @return The appearance of this block from the given side * @see IForgeBlock#getAppearance(BlockState, BlockAndTintGetter, BlockPos, Direction, BlockState, BlockPos) */ - default BlockState getAppearance(BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) - { + default BlockState getAppearance(BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) { return self().getBlock().getAppearance(self(), level, pos, side, queryState, queryPos); } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeEnchantment.java b/src/main/java/net/minecraftforge/common/extensions/IForgeEnchantment.java index 0135675971..5751324ed1 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeEnchantment.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeEnchantment.java @@ -5,12 +5,10 @@ package net.minecraftforge.common.extensions; -import net.minecraft.world.entity.MobType; -import net.minecraft.world.item.Item; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentCategory; -import java.util.Set; +import javax.annotation.Nullable; public interface IForgeEnchantment { private Enchantment self() { @@ -25,18 +23,23 @@ public interface IForgeEnchantment { * @return the damage bonus */ @SuppressWarnings("deprecation") - default float getDamageBonus(int level, MobType mobType, ItemStack enchantedItem) { + default float getDamageBonus(int level, @Nullable EntityType mobType, ItemStack enchantedItem) { return self().getDamageBonus(level, mobType); } /** - * Determines whether item variants of this enchantment can be added to a given creative tab with the allowed categories. - * - * @param book the item being added to the creative tab - * @param allowedCategories the enchantment categories allowed in the creative tab - * @return whether item variants of this enchantment can be added to a given creative tab with the allowed categories + * Is this enchantment allowed to be enchanted on books via Enchantment Table + * @return false to disable the vanilla feature */ - default boolean allowedInCreativeTab(Item book, Set allowedCategories) { - return self().isAllowedOnBooks() && allowedCategories.contains(self().category); + default boolean isAllowedOnBooks() { + return true; + } + + /** + * This applies specifically to applying at the enchanting table. The other method {@link #canEnchant(ItemStack)} + * applies for all possible enchantments. + */ + default boolean canApplyAtEnchatingTable(ItemStack stack) { + return stack.canApplyAtEnchantingTable(null); } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java b/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java index 2b4bcc282e..2450d9654b 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java @@ -9,24 +9,19 @@ import java.util.Collection; import java.util.function.BiPredicate; import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.entity.Pose; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.core.BlockPos; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.ForgeSpawnEggItem; import net.minecraftforge.common.SoundAction; import net.minecraftforge.common.capabilities.ICapabilitySerializable; @@ -189,23 +184,6 @@ public interface IForgeEntity extends ICapabilitySerializable { return null; } - /** - * @return Return the height in blocks the Entity can step up without needing to jump - * This is the sum of vanilla's {@link Entity#maxUpStep()} method and the current value - * of the {@link net.minecraftforge.common.ForgeMod#STEP_HEIGHT_ADDITION} attribute - * (if this Entity is a {@link LivingEntity} and has the attribute), clamped at 0. - */ - default float getStepHeight() { - @SuppressWarnings("deprecation") - float vanillaStep = self().maxUpStep(); - if (self() instanceof LivingEntity living) { - AttributeInstance stepHeightAttribute = living.getAttribute(ForgeMod.STEP_HEIGHT_ADDITION.get()); - if (stepHeightAttribute != null) - return (float) Math.max(0, vanillaStep + stepHeightAttribute.getValue()); - } - return vanillaStep; - } - /** * Returns the height of the fluid type in relation to the bounding box of * the entity. If the entity is not in the fluid type, then {@code 0} @@ -398,11 +376,6 @@ public interface IForgeEntity extends ICapabilitySerializable { return false; } - @Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned - default float getEyeHeightForge(Pose pose, EntityDimensions size) { - return self().getEyeHeightAccess(pose, size); - } - /** * When {@code false}, the fluid will no longer update its height value while * within a boat while it is not within a fluid ({@link Boat#isUnderWater()}. diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeFluid.java b/src/main/java/net/minecraftforge/common/extensions/IForgeFluid.java index d53f56b7da..a59d48ae04 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeFluid.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeFluid.java @@ -15,7 +15,7 @@ import net.minecraft.world.level.Explosion; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.fluids.FluidType; import org.jetbrains.annotations.Nullable; @@ -109,7 +109,7 @@ public interface IForgeFluid { * @return the path type of this fluid */ @Nullable - default BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { + default PathType getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { return getFluidType().getBlockPathType(state, level, pos, mob, canFluidLog); } @@ -127,7 +127,7 @@ public interface IForgeFluid { * @return the path type of this fluid */ @Nullable - default BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) { + default PathType getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) { return getFluidType().getAdjacentBlockPathType(state, level, pos, mob, originalType); } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeFluidState.java b/src/main/java/net/minecraftforge/common/extensions/IForgeFluidState.java index 5337d53266..36f087c474 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeFluidState.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeFluidState.java @@ -15,7 +15,7 @@ import net.minecraft.world.level.Explosion; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.fluids.FluidType; import org.jetbrains.annotations.Nullable; @@ -105,7 +105,7 @@ public interface IForgeFluidState { * @return the path type of this fluid */ @Nullable - default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { + default PathType getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { return self().getType().getBlockPathType(self(), level, pos, mob, canFluidLog); } @@ -122,7 +122,7 @@ public interface IForgeFluidState { * @return the path type of this fluid */ @Nullable - default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) { + default PathType getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) { return self().getType().getAdjacentBlockPathType(self(), level, pos, mob, originalType); } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java b/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java index 9eeb131a34..3e3dfebfba 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeFriendlyByteBuf.java @@ -18,7 +18,7 @@ import java.util.Objects; /** * Extension-Interface providing methods for writing registry-id's instead of their registry-names. - */ + * / public interface IForgeFriendlyByteBuf { private FriendlyByteBuf self() { return (FriendlyByteBuf)this; @@ -30,7 +30,7 @@ public interface IForgeFriendlyByteBuf { * @param registry The registry containing the given entry * @param entry The entry who's registryName is to be written * @param The type of the entry. - */ + * / default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull T entry) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = forgeRegistry.getID(entry); @@ -42,7 +42,7 @@ public interface IForgeFriendlyByteBuf { * in the given registry. Therefore no safety checks can be performed whilst reading it and if the entry is not in the registry a default value will be written. * @param registry The registry containing the entry represented by this key * @param entryKey The registry-name of an entry in this {@link IForgeRegistry} - */ + * / default void writeRegistryIdUnsafe(@NotNull IForgeRegistry registry, @NotNull ResourceLocation entryKey) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = forgeRegistry.getID(entryKey); @@ -53,7 +53,7 @@ public interface IForgeFriendlyByteBuf { * Reads an integer value from the buffer, which will be interpreted as an registry-id in the given registry. Notice that if there is no value in the specified registry for the * read id, that the registry's default value will be returned. * @param registry The registry containing the entry - */ + * / default T readRegistryIdUnsafe(@NotNull IForgeRegistry registry) { ForgeRegistry forgeRegistry = (ForgeRegistry) registry; int id = self().readVarInt(); @@ -71,7 +71,7 @@ public interface IForgeFriendlyByteBuf { * @param The type of the registry-entry * @throws NullPointerException if the registry or entry was null * @throws IllegalArgumentException if the registry does not contain the specified value - */ + * / default void writeRegistryId(@NotNull IForgeRegistry registry, @NotNull T entry) { Objects.requireNonNull(registry, "Cannot write a null registry key!"); Objects.requireNonNull(entry,"Cannot write a null registry entry!"); @@ -87,7 +87,7 @@ public interface IForgeFriendlyByteBuf { * - see {@link #readRegistryIdSafe(Class)} for an safe version. * @param The type of the registry-entry. Notice that this should match the actual type written to the buffer. * @throws NullPointerException if the registry could not be found. - */ + * / default T readRegistryId() { ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's ForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(location); @@ -99,7 +99,7 @@ public interface IForgeFriendlyByteBuf { * @param The type of the registry-entry. * @throws IllegalArgumentException if the retrieved entries registryType doesn't match the one passed in. * @throws NullPointerException if the registry could not be found. - */ + * / default T readRegistryIdSafe(Class registrySuperType) { T value = readRegistryId(); if (!registrySuperType.isAssignableFrom(value.getClass())) @@ -112,7 +112,7 @@ public interface IForgeFriendlyByteBuf { * This behavior provides parity with the ItemStack method in PacketBuffer. * * @param stack FluidStack to be written to the packet buffer. - */ + * / default void writeFluidStack(FluidStack stack) { if (stack.isEmpty()) self().writeBoolean(false); @@ -124,8 +124,9 @@ public interface IForgeFriendlyByteBuf { /** * Reads a FluidStack from this buffer. - */ + * / default FluidStack readFluidStack() { return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self()); } } +*/ diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java b/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java index 017ccdbc72..4220b7a956 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java @@ -15,7 +15,9 @@ import net.minecraft.gametest.framework.GameTestAssertException; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.network.Connection; import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.GameProtocols; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.ServerGamePacketListenerImpl; @@ -37,7 +39,7 @@ public interface IForgeGameTestHelper { default ServerPlayer makeMockServerPlayer() { var level = self().getLevel(); - var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player")); + var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"), false); var player = new ServerPlayer(level.getServer(), level, cookie.gameProfile(), cookie.clientInformation()) { public boolean isSpectator() { return false; @@ -49,9 +51,11 @@ public interface IForgeGameTestHelper { }; var connection = new Connection(PacketFlow.SERVERBOUND); var channel = new EmbeddedChannel(connection); - channel.attr(Connection.ATTRIBUTE_SERVERBOUND_PROTOCOL).set(ConnectionProtocol.PLAY.codec(PacketFlow.SERVERBOUND)); - // This sets the connection/listener in the player - new ServerGamePacketListenerImpl(level.getServer(), connection, player, cookie); + var server = level.getServer(); + + var listener = new ServerGamePacketListenerImpl(server, connection, player, cookie); + var info = GameProtocols.SERVERBOUND.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess())); + connection.setupInboundProtocol(info, listener); return player; } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java b/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java index b3dd00eaf8..15e3dbd64e 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java @@ -7,37 +7,34 @@ package net.minecraftforge.common.extensions; import net.minecraft.core.HolderSet.ListBacked; -public interface IForgeHolderSet -{ +public interface IForgeHolderSet { /** *

Adds a callback to run when this holderset's contents invalidate (i.e. because tags were rebound).

- * + * *

The intended usage and use case is with composite holdersets that need to cache sets/list based on other * holdersets, which may be mutable (because they are tag-based or themselves composite holdersets). * Composite holdersets should use this to add callbacks to each of their component holdersets when constructed.

- * + * * @param runnable Runnable to invoke when this component holderset's contents are no longer valid. * This runnable should only clear caches and allow them to be lazily reevaluated later, * as not all tag holdersets may have been rebound when this is called. * This runnable should also invalidate all of the caller's listeners. */ - default public void addInvalidationListener(Runnable runnable) - { + default public void addInvalidationListener(Runnable runnable) { // noop by default, mutable/composite holdersets must override } /** * What format this holderset serializes to in json/nbt/etc */ - default public SerializationType serializationType() - { + default public SerializationType serializationType() { // handle vanilla holderset types return this instanceof ListBacked listBacked ? listBacked.unwrap().map( - // serializes as tag name if this holderset is named - tag -> SerializationType.STRING, + // serializes as tag name if this holderset is named + tag -> SerializationType.STRING, list -> list.size() == 1 - // if list has exactly one element then we have to check what kind, otherwise it's a list + // if list has exactly one element then we have to check what kind, otherwise it's a list ? list.get(0).unwrap().map( // if holder has a key bound then it's serialized as that string, otherwise it's inlined as an object key -> key == null ? SerializationType.OBJECT : SerializationType.STRING, @@ -45,12 +42,11 @@ public interface IForgeHolderSet : SerializationType.LIST) : SerializationType.UNKNOWN; // unsupported holderset impl, could be anything } - + /** * What format a holderset serializes to in json/nbt/etc */ - public static enum SerializationType - { + public static enum SerializationType { /** Unhandled/unsupported holderset implementation, could serialize as potentially anything **/ UNKNOWN, STRING, diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeItem.java b/src/main/java/net/minecraftforge/common/extensions/IForgeItem.java index 3d38e22362..38496f5599 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeItem.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeItem.java @@ -5,28 +5,19 @@ package net.minecraftforge.common.extensions; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; import java.util.function.Consumer; -import com.google.common.collect.Multimap; - import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.*; +import net.minecraft.world.item.component.ItemAttributeModifiers; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.monster.EnderMan; import net.minecraft.world.entity.monster.piglin.PiglinAi; @@ -34,7 +25,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.InteractionResult; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -42,8 +32,6 @@ import net.minecraft.world.level.Level; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.ToolAction; import net.minecraftforge.common.ToolActions; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.items.wrapper.ShulkerItemStackInvWrapper; import net.minecraftforge.registries.IForgeRegistry; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,8 +46,8 @@ public interface IForgeItem { * ItemStack sensitive version of getItemAttributeModifiers */ @SuppressWarnings("deprecation") - default Multimap getAttributeModifiers(EquipmentSlot slot, ItemStack stack) { - return self().getDefaultAttributeModifiers(slot); + default ItemAttributeModifiers getAttributeModifiers(EquipmentSlot slot, ItemStack stack) { + return self().getDefaultAttributeModifiers(); } /** @@ -117,13 +105,6 @@ public interface IForgeItem { return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterials.GOLD; } - /** - * Called by CraftingManager to determine if an item is reparable. - * - * @return True if reparable - */ - boolean isRepairable(ItemStack stack); - /** * Determines the amount of durability the mending enchantment * will repair, on average, per point of experience. @@ -132,38 +113,6 @@ public interface IForgeItem { return 2f; } - /** - * Override this method to change the NBT data being sent to the client. You - * should ONLY override this when you have no other choice, as this might change - * behavior client side! - * - * Note that this will sometimes be applied multiple times, the following MUST - * be supported: - * Item item = stack.getItem(); - * NBTTagCompound nbtShare1 = item.getNBTShareTag(stack); - * stack.setTagCompound(nbtShare1); - * NBTTagCompound nbtShare2 = item.getNBTShareTag(stack); - * assert nbtShare1.equals(nbtShare2); - * - * @param stack The stack to send the NBT tag for - * @return The NBT tag - */ - @Nullable - default CompoundTag getShareTag(ItemStack stack) { - return stack.getTag(); - } - - /** - * Override this method to decide what to do with the NBT data received from - * getNBTShareTag(). - * - * @param stack The stack that received NBT - * @param nbt Received NBT, can be null - */ - default void readShareTag(ItemStack stack, @Nullable CompoundTag nbt) { - stack.setTag(nbt); - } - /** * Called before a block is broken. Return true to prevent default block * harvesting. @@ -395,51 +344,6 @@ public interface IForgeItem { return false; } - /** - * Return the itemDamage represented by this ItemStack. Defaults to the Damage - * entry in the stack NBT, but can be overridden here for other sources. - * - * @param stack The itemstack that is damaged - * @return the damage value - */ - default int getDamage(ItemStack stack) { - return !stack.hasTag() ? 0 : stack.getTag().getInt("Damage"); - } - - /** - * Return the maxDamage for this ItemStack. Defaults to the maxDamage field in - * this item, but can be overridden here for other sources such as NBT. - * - * @param stack The itemstack that is damaged - * @return the damage value - */ - @SuppressWarnings("deprecation") - default int getMaxDamage(ItemStack stack) { - return self().getMaxDamage(); - } - - /** - * Return if this itemstack is damaged. Note only called if - * {@link ItemStack#isDamageableItem()} is true. - * - * @param stack the stack - * @return if the stack is damaged - */ - default boolean isDamaged(ItemStack stack) { - return stack.getDamageValue() > 0; - } - - /** - * Set the damage for this itemstack. Note, this method is responsible for zero - * checking. - * - * @param stack the stack - * @param damage the new damage value - */ - default void setDamage(ItemStack stack, int damage) { - stack.getOrCreateTag().putInt(ItemStack.TAG_DAMAGE, Math.max(0, damage)); - } - /** * Queries if an item can perform the given action. * See {@link ToolActions} for a description of each stock action @@ -451,29 +355,6 @@ public interface IForgeItem { return false; } - /** - * ItemStack sensitive version of {@link Item#isCorrectToolForDrops(BlockState)} - * - * @param stack The itemstack used to harvest the block - * @param state The block trying to harvest - * @return true if the stack can harvest the block - */ - default boolean isCorrectToolForDrops(ItemStack stack, BlockState state) { - return self().isCorrectToolForDrops(state); - } - - /** - * Gets the maximum number of items that this stack should be able to hold. This - * is a ItemStack (and thus NBT) sensitive version of {@link Item#getMaxStackSize()}. - * - * @param stack The ItemStack - * @return The maximum size this item can be stacked to - */ - @SuppressWarnings("deprecation") - default int getMaxStackSize(ItemStack stack) { - return self().getMaxStackSize(); - } - /** * ItemStack sensitive version of {@link Item#getEnchantmentValue()}. * @@ -499,7 +380,7 @@ public interface IForgeItem { * @return true if the enchantment can be applied to this item */ default boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) { - return enchantment.category.canEnchant(stack.getItem()); + return self().builtInRegistryHolder().is(enchantment.getSupportedItems()) && enchantment.isPrimaryItem(stack); } /** @@ -513,20 +394,7 @@ public interface IForgeItem { * @see #getAllEnchantments(ItemStack) */ default int getEnchantmentLevel(ItemStack stack, Enchantment enchantment) { - return EnchantmentHelper.getTagEnchantmentLevel(enchantment, stack); - } - - /** - * Gets a map of all enchantments present on the stack. By default, returns the enchantments present in NBT. - * Used in several places in code including armor enchantment hooks. - * For consistency, any enchantments in the returned map should include the same level in {@link #getEnchantmentLevel(ItemStack, Enchantment)} - * - * @param stack the item stack being checked - * @return Map of all enchantments on the stack, empty if no enchantments are present - * @see #getEnchantmentLevel(ItemStack, Enchantment) - */ - default Map getAllEnchantments(ItemStack stack) { - return EnchantmentHelper.deserializeEnchantments(stack.getEnchantmentTags()); + return EnchantmentHelper.getEnchantmentsForCrafting(stack).getLevel(enchantment); } /** @@ -553,31 +421,12 @@ public interface IForgeItem { * @return True to reset block break progress */ default boolean shouldCauseBlockBreakReset(ItemStack oldStack, ItemStack newStack) { - // Fix MC-176559 mending resets mining progress / breaking animation if (!newStack.is(oldStack.getItem())) return true; - if (!newStack.isDamageableItem() || !oldStack.isDamageableItem()) - return !ItemStack.isSameItemSameTags(newStack, oldStack); + // TODO: Fix MC-176559 mending resets mining progress / breaking animation by removing damange component - CompoundTag newTag = newStack.getTag(); - CompoundTag oldTag = oldStack.getTag(); - - if (newTag == null || oldTag == null) - return !(newTag == null && oldTag == null); - - Set newKeys = new HashSet<>(newTag.getAllKeys()); - Set oldKeys = new HashSet<>(oldTag.getAllKeys()); - - newKeys.remove(ItemStack.TAG_DAMAGE); - oldKeys.remove(ItemStack.TAG_DAMAGE); - - if (!newKeys.equals(oldKeys)) - return true; - - return !newKeys.stream().allMatch(key -> Objects.equals(newTag.get(key), oldTag.get(key))); - // return !(newStack.is(oldStack.getItem()) && ItemStack.tagMatches(newStack, oldStack) - // && (newStack.isDamageableItem() || newStack.getDamageValue() == oldStack.getDamageValue())); + return !ItemStack.isSameItemSameComponents(oldStack, newStack); } /** @@ -628,11 +477,15 @@ public interface IForgeItem { * @param nbt NBT of this item serialized, or null. * @return A holder instance associated with this ItemStack where you can hold * capabilities for the life of this item. - */ + * + * + * Forge: TODO: Forge ItemStack capabilities - Lex 042724 + * / @Nullable default ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { return ShulkerItemStackInvWrapper.createDefaultProvider(stack); } + */ /** * Can this Item disable a shield @@ -666,20 +519,6 @@ public interface IForgeItem { */ default void onHorseArmorTick(ItemStack stack, Level level, Mob horse) { } - /** - * Reduce the durability of this item by the amount given. - * This can be used to e.g. consume power from NBT before durability. - * - * @param stack The itemstack to damage - * @param amount The amount to damage - * @param entity The entity damaging the item - * @param onBroken The on-broken callback from vanilla - * @return The amount of damage to pass to the vanilla logic - */ - default int damageItem(ItemStack stack, int amount, T entity, Consumer onBroken) { - return amount; - } - /** * Called when an item entity for this stack is destroyed. Note: The {@link ItemStack} can be retrieved from the item entity. * @@ -744,16 +583,6 @@ public interface IForgeItem { return stack.is(Items.LEATHER_BOOTS); } - /** - * Used to test if this item can be damaged, but with the ItemStack in question. - * Please note that in some cases no ItemStack is available, so the stack-less method will be used. - * - * @param stack ItemStack in the Chest slot of the entity. - */ - default boolean isDamageable(ItemStack stack) { - return self().canBeDepleted(); - } - /** * Get a bounding box ({@link AABB}) of a sweep attack. * @@ -777,23 +606,6 @@ public interface IForgeItem { return 0; } - /** - * Get the food properties for this item. - * Use this instead of the {@link Item#getFoodProperties()} method, for ItemStack sensitivity. - * - * The @Nullable annotation was only added, due to the default method, also being @Nullable. - * Use this with a grain of salt, as if you return null here and true at {@link Item#isEdible()}, NPEs will occur! - * - * @param stack The ItemStack the entity wants to eat. - * @param entity The entity which wants to eat the food. Be aware that this can be null! - * @return The current FoodProperties for the item. - */ - @SuppressWarnings("deprecation") - @Nullable // read javadoc to find a potential problem - default FoodProperties getFoodProperties(ItemStack stack, @Nullable LivingEntity entity) { - return self().getFoodProperties(); - } - /** * Whether the given ItemStack should be excluded (if possible) when selecting the target hotbar slot of a "pick" action. * By default, this returns true for enchanted stacks. diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeItemStack.java b/src/main/java/net/minecraftforge/common/extensions/IForgeItemStack.java index 09757edf44..da973f3542 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeItemStack.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeItemStack.java @@ -5,14 +5,10 @@ package net.minecraftforge.common.extensions; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.monster.EnderMan; import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.pattern.BlockInWorld; import net.minecraft.world.phys.AABB; import net.minecraft.world.item.enchantment.Enchantment; @@ -25,7 +21,6 @@ import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.nbt.CompoundTag; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionResult; import net.minecraft.core.BlockPos; @@ -33,21 +28,15 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.level.Level; import net.minecraftforge.common.ToolAction; import net.minecraftforge.common.ToolActions; -import net.minecraftforge.common.capabilities.ICapabilitySerializable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; -import java.util.Objects; - /* * Extension added to ItemStack that bounces to ItemSack sensitive Item methods. Typically this is just for convince. */ -public interface IForgeItemStack extends ICapabilitySerializable -{ +public interface IForgeItemStack { // Helpers for accessing Item data - private ItemStack self() - { + private ItemStack self() { return (ItemStack)this; } @@ -57,8 +46,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * * @return The resulting ItemStack */ - default ItemStack getCraftingRemainingItem() - { + default ItemStack getCraftingRemainingItem() { return self().getItem().getCraftingRemainingItem(self()); } @@ -67,8 +55,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * * @return True if this item has a crafting remaining item */ - default boolean hasCraftingRemainingItem() - { + default boolean hasCraftingRemainingItem() { return self().getItem().hasCraftingRemainingItem(self()); } @@ -77,18 +64,16 @@ public interface IForgeItemStack extends ICapabilitySerializable * it not act as a fuel. Return -1 to let the default vanilla logic * decide. */ - default int getBurnTime(@Nullable RecipeType recipeType) - { + default int getBurnTime(@Nullable RecipeType recipeType) { return self().getItem().getBurnTime(self(), recipeType); } - default InteractionResult onItemUseFirst(UseOnContext context) - { + default InteractionResult onItemUseFirst(UseOnContext context) { Player entityplayer = context.getPlayer(); BlockPos blockpos = context.getClickedPos(); BlockInWorld blockworldstate = new BlockInWorld(context.getLevel(), blockpos, false); - Registry registry = entityplayer.level().registryAccess().registryOrThrow(Registries.BLOCK); - if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !self().hasAdventureModePlaceTagForBlock(registry, blockworldstate)) { + var adventure = (self().canBreakBlockInAdventureMode(blockworldstate) || self().canPlaceOnBlockInAdventureMode(blockworldstate)); + if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !adventure) { return InteractionResult.PASS; } else { Item item = self().getItem(); @@ -101,21 +86,13 @@ public interface IForgeItemStack extends ICapabilitySerializable } } - default CompoundTag serializeNBT() - { - CompoundTag ret = new CompoundTag(); - self().save(ret); - return ret; - } - /** * Queries if an item can perform the given action. * See {@link ToolActions} for a description of each stock action * @param toolAction The action being queried * @return True if the stack can perform the action */ - default boolean canPerformAction(ToolAction toolAction) - { + default boolean canPerformAction(ToolAction toolAction) { return self().getItem().canPerformAction(self(), toolAction); } @@ -129,8 +106,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param player The Player that is wielding the item * @return True to prevent harvesting, false to continue as normal */ - default boolean onBlockStartBreak(BlockPos pos, Player player) - { + default boolean onBlockStartBreak(BlockPos pos, Player player) { return !self().isEmpty() && self().getItem().onBlockStartBreak(self(), pos, player); } @@ -141,8 +117,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param newStack The new stack * @return True to reset block break progress */ - default boolean shouldCauseBlockBreakReset(ItemStack newStack) - { + default boolean shouldCauseBlockBreakReset(ItemStack newStack) { return self().getItem().shouldCauseBlockBreakReset(self(), newStack); } @@ -158,8 +133,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param enchantment the enchantment to be applied * @return true if the enchantment can be applied to this item */ - default boolean canApplyAtEnchantingTable(Enchantment enchantment) - { + default boolean canApplyAtEnchantingTable(Enchantment enchantment) { return self().getItem().canApplyAtEnchantingTable(self(), enchantment); } @@ -175,33 +149,16 @@ public interface IForgeItemStack extends ICapabilitySerializable * @see #getAllEnchantments() * @see net.minecraft.world.item.enchantment.EnchantmentHelper#getTagEnchantmentLevel(Enchantment, ItemStack) */ - default int getEnchantmentLevel(Enchantment enchantment) - { + default int getEnchantmentLevel(Enchantment enchantment) { return self().getItem().getEnchantmentLevel(self(), enchantment); } - /** - * Gets a map of all enchantments present on the stack. By default, returns the enchantments present in NBT, ignoring book enchantments. - * - * Use in place of {@link net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack)} for checking presence of an enchantment in logic implementing the enchantment behavior. - * Use {@link net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack)} instead when modifying an item's enchantments. - * - * @return Map of all enchantments on the stack, empty if no enchantments are present - * @see #getEnchantmentLevel(Enchantment) - * @see net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack) - */ - default Map getAllEnchantments() - { - return self().getItem().getAllEnchantments(self()); - } - /** * ItemStack sensitive version of {@link Item#getEnchantmentValue()}. * * @return the enchantment value of this ItemStack */ - default int getEnchantmentValue() - { + default int getEnchantmentValue() { return self().getItem().getEnchantmentValue(self()); } @@ -215,8 +172,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * decide */ @Nullable - default EquipmentSlot getEquipmentSlot() - { + default EquipmentSlot getEquipmentSlot() { return self().getItem().getEquipmentSlot(self()); } @@ -228,8 +184,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param attacker The LivingEntity holding the ItemStack * @return True if this ItemStack can disable the shield in question. */ - default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker) - { + default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker) { return self().getItem().canDisableShield(self(), shield, entity, attacker); } @@ -239,8 +194,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param entity The entity swinging the item. * @return True to cancel any further processing by EntityLiving */ - default boolean onEntitySwing(LivingEntity entity) - { + default boolean onEntitySwing(LivingEntity entity) { return self().getItem().onEntitySwing(self(), entity); } @@ -250,8 +204,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param entity The entity using the item, typically a player * @param count The amount of time in tick the item has been used for continuously */ - default void onStopUsing(LivingEntity entity, int count) - { + default void onStopUsing(LivingEntity entity, int count) { self().getItem().onStopUsing(self(), entity, count); } @@ -262,8 +215,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param level The level the entity is in * @return The normal lifespan in ticks. */ - default int getEntityLifespan(Level level) - { + default int getEntityLifespan(Level level) { return self().getItem().getEntityLifespan(self(), level); } @@ -275,8 +227,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param entity The entity Item * @return Return true to skip any further update code. */ - default boolean onEntityItemUpdate(ItemEntity entity) - { + default boolean onEntityItemUpdate(ItemEntity entity) { return self().getItem().onEntityItemUpdate(self(), entity); } @@ -284,26 +235,15 @@ public interface IForgeItemStack extends ICapabilitySerializable * Determines the amount of durability the mending enchantment * will repair, on average, per point of experience. */ - default float getXpRepairRatio() - { + default float getXpRepairRatio() { return self().getItem().getXpRepairRatio(self()); } - /** - * Called to tick armor in the armor slot. Override to do something - */ - @Deprecated(forRemoval = true, since = "1.20.1") // Use onInventoryTick - default void onArmorTick(Level level, Player player) - { - self().getItem().onArmorTick(self(), level, player); - } - /** * Called to tick this items in a players inventory, the indexes are the global slot index. */ - default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex) - { - self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex); + default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex) { + self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex); } @@ -314,8 +254,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param level the level the horse is in * @param horse the horse wearing this armor */ - default void onHorseArmorTick(Level level, Mob horse) - { + default void onHorseArmorTick(Level level, Mob horse) { self().getItem().onHorseArmorTick(self(), level, horse); } @@ -327,8 +266,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param entity The entity trying to equip the armor * @return True if the given ItemStack can be inserted in the slot */ - default boolean canEquip(EquipmentSlot armorType, Entity entity) - { + default boolean canEquip(EquipmentSlot armorType, Entity entity) { return self().getItem().canEquip(self(), armorType, entity); } @@ -338,8 +276,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param book The book * @return if the enchantment is allowed */ - default boolean isBookEnchantable(ItemStack book) - { + default boolean isBookEnchantable(ItemStack book) { return self().getItem().isBookEnchantable(self(), book); } @@ -351,8 +288,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * * @param player The player that dropped the item */ - default boolean onDroppedByPlayer(Player player) - { + default boolean onDroppedByPlayer(Player player) { return self().getItem().onDroppedByPlayer(self(), player); } @@ -364,41 +300,10 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param displayName the name that will be displayed unless it is changed in * this method. */ - default Component getHighlightTip(Component displayName) - { + default Component getHighlightTip(Component displayName) { return self().getItem().getHighlightTip(self(), displayName); } - /** - * Get the NBT data to be sent to the client. The Item can control what data is kept in the tag. - * - * Note that this will sometimes be applied multiple times, the following MUST - * be supported: - * Item item = stack.getItem(); - * NBTTagCompound nbtShare1 = item.getNBTShareTag(stack); - * stack.setTagCompound(nbtShare1); - * NBTTagCompound nbtShare2 = item.getNBTShareTag(stack); - * assert nbtShare1.equals(nbtShare2); - * - * @return The NBT tag - */ - @Nullable - default CompoundTag getShareTag() - { - return self().getItem().getShareTag(self()); - } - - /** - * Override this method to decide what to do with the NBT data received from - * getNBTShareTag(). - * - * @param nbt Received NBT, can be null - */ - default void readShareTag(@Nullable CompoundTag nbt) - { - self().getItem().readShareTag(self(), nbt); - } - /** * * Should this item, when held, allow sneak-clicks to pass through to the underlying block? @@ -407,59 +312,16 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param pos Block position in level * @param player The Player that is wielding the item */ - default boolean doesSneakBypassUse(net.minecraft.world.level.LevelReader level, BlockPos pos, Player player) - { + default boolean doesSneakBypassUse(net.minecraft.world.level.LevelReader level, BlockPos pos, Player player) { return self().isEmpty() || self().getItem().doesSneakBypassUse(self(), level, pos, player); } - /** - * Modeled after ItemStack.areItemStackTagsEqual - * Uses Item.getNBTShareTag for comparison instead of NBT and capabilities. - * Only used for comparing itemStacks that were transferred from server to client using Item.getNBTShareTag. - */ - default boolean areShareTagsEqual(ItemStack other) - { - CompoundTag shareTagA = self().getShareTag(); - CompoundTag shareTagB = other.getShareTag(); - if (shareTagA == null) - return shareTagB == null; - else - return shareTagB != null && shareTagA.equals(shareTagB); - } - - /** - * Determines if the ItemStack is equal to the other item stack, including Item, Count, and NBT. - * - * @param other The other stack - * @param limitTags True to use shareTag False to use full NBT tag - * @return true if equals - */ - default boolean equals(ItemStack other, boolean limitTags) - { - if (self().isEmpty()) - return other.isEmpty(); - else - return !other.isEmpty() && self().getCount() == other.getCount() && self().getItem() == other.getItem() && - (limitTags ? self().areShareTagsEqual(other) : Objects.equals(self().getTag(), other.getTag())); - } - - /** - * Determines if a item is reparable, used by Repair recipes and Grindstone. - * - * @return True if reparable - */ - default boolean isRepairable() - { - return self().getItem().isRepairable(self()); - } - /** * Called by Piglins when checking to see if they will give an item or something in exchange for this item. * * @return True if this item can be used as "currency" by piglins */ - default boolean isPiglinCurrency() - { + default boolean isPiglinCurrency() { return self().getItem().isPiglinCurrency(self()); } @@ -471,8 +333,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * * @return True if piglins are neutral to players wearing this item in an armor slot */ - default boolean makesPiglinsNeutral(LivingEntity wearer) - { + default boolean makesPiglinsNeutral(LivingEntity wearer) { return self().getItem().makesPiglinsNeutral(self(), wearer); } @@ -483,8 +344,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param endermanEntity The enderman that the player look * @return true if this Item can be used. */ - default boolean isEnderMask(Player player, EnderMan endermanEntity) - { + default boolean isEnderMask(Player player, EnderMan endermanEntity) { return self().getItem().isEnderMask(self(), player, endermanEntity); } @@ -495,8 +355,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param entity The entity trying to fly. * @return True if the entity can use Elytra flight. */ - default boolean canElytraFly(LivingEntity entity) - { + default boolean canElytraFly(LivingEntity entity) { return self().getItem().canElytraFly(self(), entity); } @@ -511,8 +370,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param flightTicks The number of ticks the entity has been Elytra flying for. * @return True if the entity should continue Elytra flight or False to stop. */ - default boolean elytraFlightTick(LivingEntity entity, int flightTicks) - { + default boolean elytraFlightTick(LivingEntity entity, int flightTicks) { return self().getItem().elytraFlightTick(self(), entity, flightTicks); } @@ -524,8 +382,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * * @return True if the entity can walk on powdered snow */ - default boolean canWalkOnPowderedSnow(LivingEntity wearer) - { + default boolean canWalkOnPowderedSnow(LivingEntity wearer) { return self().getItem().canWalkOnPowderedSnow(self(), wearer); } @@ -537,8 +394,7 @@ public interface IForgeItemStack extends ICapabilitySerializable * @return the bounding box. */ @NotNull - default AABB getSweepHitBox(@NotNull Player player, @NotNull Entity target) - { + default AABB getSweepHitBox(@NotNull Player player, @NotNull Entity target) { return self().getItem().getSweepHitBox(self(), player, target); } @@ -548,27 +404,10 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param itemEntity The item entity that was destroyed. * @param damageSource Damage source that caused the item entity to "die". */ - default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource) - { + default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource) { self().getItem().onDestroyed(itemEntity, damageSource); } - /** - * Get the food properties for this item. - * This is a bouncer for easier use of {@link IForgeItem#getFoodProperties(ItemStack, LivingEntity)} - * - * The @Nullable annotation was only added, due to the default method, also being @Nullable. - * Use this with a grain of salt, as if you return null here and true at {@link Item#isEdible()}, NPEs will occur! - * - * @param entity The entity which wants to eat the food. Be aware that this can be null! - * @return The current FoodProperties for the item. - */ - @Nullable // read javadoc to find a potential problem - default FoodProperties getFoodProperties(@Nullable LivingEntity entity) - { - return self().getItem().getFoodProperties(self(), entity); - } - /** * Whether this stack should be excluded (if possible) when selecting the target hotbar slot of a "pick" action. * By default, this returns true for enchanted stacks. @@ -578,16 +417,14 @@ public interface IForgeItemStack extends ICapabilitySerializable * @param inventorySlot the inventory slot of the item being up for replacement * @return true to leave this stack in the hotbar if possible */ - default boolean isNotReplaceableByPickAction(Player player, int inventorySlot) - { + default boolean isNotReplaceableByPickAction(Player player, int inventorySlot) { return self().getItem().isNotReplaceableByPickAction(self(), player, inventorySlot); } /** * {@return true if the given ItemStack can be put into a grindstone to be repaired and/or stripped of its enchantments} */ - default boolean canGrindstoneRepair() - { + default boolean canGrindstoneRepair() { return self().getItem().canGrindstoneRepair(self()); } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeLivingEntity.java b/src/main/java/net/minecraftforge/common/extensions/IForgeLivingEntity.java index 7d582921fc..922582e2a3 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeLivingEntity.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeLivingEntity.java @@ -30,7 +30,7 @@ public interface IForgeLivingEntity extends IForgeEntity { * @param type the type of the fluid */ default void jumpInFluid(FluidType type) { - self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D)); + self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.getHolder().get()), 0.0D)); } /** @@ -39,7 +39,7 @@ public interface IForgeLivingEntity extends IForgeEntity { * @param type the type of the fluid */ default void sinkInFluid(FluidType type) { - self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D)); + self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.getHolder().get()), 0.0D)); } /** diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeMobEffectInstance.java b/src/main/java/net/minecraftforge/common/extensions/IForgeMobEffectInstance.java deleted file mode 100644 index d3971f45e2..0000000000 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeMobEffectInstance.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common.extensions; - -import java.util.List; - -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.item.ItemStack; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; - -public interface IForgeMobEffectInstance { - /*** - * Returns a list of curative items for the potion effect - * By default, this list is initialized using {@link MobEffect#getCurativeItems()} - * - * @return The list (ItemStack) of curative items for the potion effect - */ - List getCurativeItems(); - - /*** - * Checks the given ItemStack to see if it is in the list of curative items for the potion effect - * @param stack The ItemStack being checked against the list of curative items for this PotionEffect - * @return true if the given ItemStack is in the list of curative items for this PotionEffect, false otherwise - */ - default boolean isCurativeItem(ItemStack stack) { - return this.getCurativeItems().stream().anyMatch(e -> ItemStack.isSameItem(e, stack)); - } - - /*** - * Sets the list of curative items for this potion effect, overwriting any already present - * @param curativeItems The list of ItemStacks being set to the potion effect - */ - void setCurativeItems(List curativeItems); - - /*** - * Adds the given stack to the list of curative items for this PotionEffect - * @param stack The ItemStack being added to the curative item list - */ - default void addCurativeItem(ItemStack stack) { - if (!this.isCurativeItem(stack)) - this.getCurativeItems().add(stack); - } - - default void writeCurativeItems(CompoundTag nbt) { - ListTag list = new ListTag(); - getCurativeItems().forEach(s -> list.add(s.save(new CompoundTag()))); - nbt.put("CurativeItems", list); - } -} diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgePlayer.java b/src/main/java/net/minecraftforge/common/extensions/IForgePlayer.java index a6a89b3cf5..1177fb30d4 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgePlayer.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgePlayer.java @@ -5,73 +5,16 @@ package net.minecraftforge.common.extensions; -import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.ForgeMod; public interface IForgePlayer { private Player self() { return (Player)this; } - /** - * The entity reach is increased by 3 for creative players, unless it is currently zero, which disables attacks and entity interactions. - * @return The entity reach of this player. - */ - default double getEntityReach() { - double range = self().getAttributeValue(ForgeMod.ENTITY_REACH.get()); - return range == 0 ? 0 : range + (self().isCreative() ? 3 : 0); - } - - /** - * The reach distance is increased by 0.5 for creative players, unless it is currently zero, which disables interactions. - * @return The reach distance of this player. - */ - default double getBlockReach() { - double reach = self().getAttributeValue(ForgeMod.BLOCK_REACH.get()); - return reach == 0 ? 0 : reach + (self().isCreative() ? 0.5 : 0); - } - - /** - * Checks if the player can reach an entity by targeting the passed vector.
- * On the server, additional padding is added to account for movement/lag. - * @param entityHitVec The vector being range-checked. - * @param padding Extra validation distance. - * @return If the player can attack the entity. - * @apiNote Do not use for block checks, as this method uses {@link #getEntityReach()} - */ - default boolean canReach(Vec3 entityHitVec, double padding) { - return self().getEyePosition().closerThan(entityHitVec, getEntityReach() + padding); - } - - /** - * Checks if the player can reach an entity.
- * On the server, additional padding is added to account for movement/lag. - * @param entity The entity being range-checked. - * @param padding Extra validation distance. - * @return If the player can attack the passed entity. - * @apiNote Prefer using {@link #canReach(Vec3, double)} if you have a {@link HitResult} available. - */ - default boolean canReach(Entity entity, double padding) { - return isCloseEnough(entity, getEntityReach() + padding); - } - - /** - * Checks if the player can reach a block.
- * On the server, additional padding is added to account for movement/lag. - * @param pos The position being range-checked. - * @param padding Extra validation distance. - * @return If the player can interact with this location. - */ - default boolean canReach(BlockPos pos, double padding) { - double reach = this.getBlockReach() + padding; - return self().getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) < reach * reach; - } - /** * Utility check to see if the player is close enough to a target entity. Uses "eye-to-closest-corner" checks. * @param entity The entity being checked against diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgePotion.java b/src/main/java/net/minecraftforge/common/extensions/IForgePotion.java deleted file mode 100644 index aa26e0ce6c..0000000000 --- a/src/main/java/net/minecraftforge/common/extensions/IForgePotion.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common.extensions; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.alchemy.PotionUtils; - -public interface IForgePotion { - /** - * Determines whether the potion bottle item should be enchanted. - * Not called for tipped arrows or if the item is already enchanted. - * @param stack The potion bottle - * @return whether the item should appear enchanted. - */ - default boolean isFoil(ItemStack stack) { - return !PotionUtils.getMobEffects(stack).isEmpty(); - } -} diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeRawTagBuilder.java b/src/main/java/net/minecraftforge/common/extensions/IForgeRawTagBuilder.java index e43669f8d3..fd90f979dd 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeRawTagBuilder.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeRawTagBuilder.java @@ -13,7 +13,7 @@ import net.minecraft.tags.TagEntry; public interface IForgeRawTagBuilder { default TagBuilder getRawBuilder() { - return (TagBuilder)this; + return (TagBuilder) this; } /** @@ -51,4 +51,11 @@ public interface IForgeRawTagBuilder { default TagBuilder removeTag(final ResourceLocation tagID, final String source) { return this.remove(TagEntry.tag(tagID), source); } + + /** + * Shorthand version of {@code replace(true)} + */ + default TagBuilder replace() { + return this.getRawBuilder().replace(true); + } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeTransformation.java b/src/main/java/net/minecraftforge/common/extensions/IForgeTransformation.java index 8a23dc5107..fe7f49ca77 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeTransformation.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeTransformation.java @@ -15,11 +15,9 @@ import org.joml.Vector4f; /** * Extension interface for {@link Transformation}. */ -public interface IForgeTransformation -{ - private Transformation self() - { - return (Transformation) this; +public interface IForgeTransformation { + private Transformation self() { + return (Transformation)this; } /** @@ -27,8 +25,7 @@ public interface IForgeTransformation * * @see Transformation#identity() */ - default boolean isIdentity() - { + default boolean isIdentity() { return self().equals(Transformation.identity()); } @@ -37,8 +34,7 @@ public interface IForgeTransformation * * @param position the position to transform */ - default void transformPosition(Vector4f position) - { + default void transformPosition(Vector4f position) { position.mul(self().getMatrix()); } @@ -47,8 +43,7 @@ public interface IForgeTransformation * * @param normal the normal to transform */ - default void transformNormal(Vector3f normal) - { + default void transformNormal(Vector3f normal) { normal.mul(self().getNormalMatrix()); normal.normalize(); } @@ -61,8 +56,7 @@ public interface IForgeTransformation * @return the {@code Direction} value nearest to the resulting transformed direction * @see Direction#rotate(Matrix4f, Direction) */ - default Direction rotateTransform(Direction facing) - { + default Direction rotateTransform(Direction facing) { return Direction.rotate(self().getMatrix(), facing); } @@ -72,8 +66,7 @@ public interface IForgeTransformation * * @return a new transformation using the opposing-corner-block system */ - default Transformation blockCenterToCorner() - { + default Transformation blockCenterToCorner() { return applyOrigin(new Vector3f(.5f, .5f, .5f)); } @@ -83,8 +76,7 @@ public interface IForgeTransformation * * @return a new transformation using the center-block system */ - default Transformation blockCornerToCenter() - { + default Transformation blockCornerToCenter() { return applyOrigin(new Vector3f(-.5f, -.5f, -.5f)); } @@ -95,8 +87,7 @@ public interface IForgeTransformation * @param origin the new origin as relative to the current origin * @return a new transformation with a changed origin */ - default Transformation applyOrigin(Vector3f origin) - { + default Transformation applyOrigin(Vector3f origin) { Transformation transform = self(); if (transform.isIdentity()) return Transformation.identity(); diff --git a/src/main/java/net/minecraftforge/common/loot/CanToolPerformAction.java b/src/main/java/net/minecraftforge/common/loot/CanToolPerformAction.java index 52a0047438..88c8695b8e 100644 --- a/src/main/java/net/minecraftforge/common/loot/CanToolPerformAction.java +++ b/src/main/java/net/minecraftforge/common/loot/CanToolPerformAction.java @@ -6,7 +6,7 @@ package net.minecraftforge.common.loot; import com.google.common.collect.ImmutableSet; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.ItemStack; @@ -24,7 +24,7 @@ import java.util.Set; * This LootItemCondition "forge:can_tool_perform_action" can be used to check if a tool can perform a given ToolAction. */ public record CanToolPerformAction(ToolAction action) implements LootItemCondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ToolAction.CODEC.fieldOf("action").forGetter(CanToolPerformAction::action) ).apply(b, CanToolPerformAction::new)); public static final LootItemConditionType TYPE = new LootItemConditionType(CODEC); diff --git a/src/main/java/net/minecraftforge/common/loot/IGlobalLootModifier.java b/src/main/java/net/minecraftforge/common/loot/IGlobalLootModifier.java index 3def7a1d4f..2358ad66cf 100644 --- a/src/main/java/net/minecraftforge/common/loot/IGlobalLootModifier.java +++ b/src/main/java/net/minecraftforge/common/loot/IGlobalLootModifier.java @@ -9,8 +9,9 @@ import com.google.gson.JsonElement; import com.mojang.serialization.Codec; import com.mojang.serialization.Dynamic; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; + import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; @@ -28,10 +29,9 @@ import java.util.function.Function; * Individual instances of modifiers must be registered via json, see forge:loot_modifiers/global_loot_modifiers */ public interface IGlobalLootModifier { - Codec DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.GLOBAL_LOOT_MODIFIER_SERIALIZERS.get().getCodec()) - .dispatch(IGlobalLootModifier::codec, Function.identity()); + Codec DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.GLOBAL_LOOT_MODIFIER_SERIALIZERS.get().getCodec().dispatch(IGlobalLootModifier::codec, Function.identity())); - Codec LOOT_CONDITIONS_CODEC = LootItemConditions.CODEC.listOf().xmap(list -> list.toArray(LootItemCondition[]::new), List::of); + Codec LOOT_CONDITIONS_CODEC = LootItemConditions.DIRECT_CODEC.listOf().xmap(list -> list.toArray(LootItemCondition[]::new), List::of); @SuppressWarnings("unchecked") static JsonElement getJson(Dynamic dynamic) { @@ -54,5 +54,5 @@ public interface IGlobalLootModifier { /** * Returns the registered codec for this modifier */ - Codec codec(); + MapCodec codec(); } diff --git a/src/main/java/net/minecraftforge/common/loot/LootModifier.java b/src/main/java/net/minecraftforge/common/loot/LootModifier.java index 8f3efc79cf..2bfd13d82e 100644 --- a/src/main/java/net/minecraftforge/common/loot/LootModifier.java +++ b/src/main/java/net/minecraftforge/common/loot/LootModifier.java @@ -11,11 +11,11 @@ import java.util.function.Predicate; import com.mojang.datafixers.Products; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.Util; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.levelgen.feature.trunkplacers.BendingTrunkPlacer; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.predicates.LootItemConditions; import org.jetbrains.annotations.NotNull; /** @@ -46,7 +46,7 @@ public abstract class LootModifier implements IGlobalLootModifier { */ protected LootModifier(LootItemCondition[] conditionsIn) { this.conditions = conditionsIn; - this.combinedConditions = LootItemConditions.andConditions(Arrays.asList(conditionsIn)); + this.combinedConditions = Util.allOf(Arrays.asList(conditionsIn)); } @NotNull diff --git a/src/main/java/net/minecraftforge/common/loot/LootTableIdCondition.java b/src/main/java/net/minecraftforge/common/loot/LootTableIdCondition.java index 05802e2230..18713299ad 100644 --- a/src/main/java/net/minecraftforge/common/loot/LootTableIdCondition.java +++ b/src/main/java/net/minecraftforge/common/loot/LootTableIdCondition.java @@ -5,7 +5,7 @@ package net.minecraftforge.common.loot; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; @@ -14,7 +14,7 @@ import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.resources.ResourceLocation; public record LootTableIdCondition(ResourceLocation id) implements LootItemCondition { - public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(b -> b.group( ResourceLocation.CODEC.fieldOf("loot_table_id").forGetter(LootTableIdCondition::id) ).apply(b, LootTableIdCondition::new)); diff --git a/src/main/java/net/minecraftforge/common/util/BlockSnapshot.java b/src/main/java/net/minecraftforge/common/util/BlockSnapshot.java index 803d3859bb..4bb4f8a55e 100644 --- a/src/main/java/net/minecraftforge/common/util/BlockSnapshot.java +++ b/src/main/java/net/minecraftforge/common/util/BlockSnapshot.java @@ -15,6 +15,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.resources.ResourceKey; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.Level; import net.minecraftforge.server.ServerLifecycleHooks; @@ -27,8 +28,7 @@ import org.jetbrains.annotations.Nullable; * Unlike Block, which only one object can exist per coordinate, BlockSnapshot * can exist multiple times for any given Block. */ -public class BlockSnapshot -{ +public class BlockSnapshot { private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("forge.debugBlockSnapshot", "false")); private final ResourceKey dim; @@ -42,8 +42,7 @@ public class BlockSnapshot private WeakReference level; private String toString = null; - private BlockSnapshot(ResourceKey dim, LevelAccessor level, BlockPos pos, BlockState state, @Nullable CompoundTag nbt, int flags) - { + private BlockSnapshot(ResourceKey dim, LevelAccessor level, BlockPos pos, BlockState state, @Nullable CompoundTag nbt, int flags) { this.dim = dim; this.pos = pos.immutable(); this.block = state; @@ -56,75 +55,64 @@ public class BlockSnapshot System.out.println("Created " + this.toString()); } - public static BlockSnapshot create(ResourceKey dim, LevelAccessor world, BlockPos pos) - { + public static BlockSnapshot create(ResourceKey dim, LevelAccessor world, BlockPos pos) { return create(dim, world, pos, 3); } - public static BlockSnapshot create(ResourceKey dim, LevelAccessor world, BlockPos pos, int flag) - { - return new BlockSnapshot(dim, world, pos, world.getBlockState(pos), getBlockEntityTag(world.getBlockEntity(pos)), flag); + public static BlockSnapshot create(ResourceKey dim, LevelAccessor world, BlockPos pos, int flag) { + return new BlockSnapshot(dim, world, pos, world.getBlockState(pos), getBlockEntityTag(world.getBlockEntity(pos), world.registryAccess()), flag); } @Nullable - private static CompoundTag getBlockEntityTag(@Nullable BlockEntity te) - { - return te == null ? null : te.saveWithFullMetadata(); + private static CompoundTag getBlockEntityTag(@Nullable BlockEntity te, HolderLookup.Provider lookup) { + return te == null ? null : te.saveCustomAndMetadata(lookup); } - public BlockState getCurrentBlock() - { + public BlockState getCurrentBlock() { LevelAccessor world = getLevel(); return world == null ? Blocks.AIR.defaultBlockState() : world.getBlockState(this.pos); } @Nullable - public LevelAccessor getLevel() - { + public LevelAccessor getLevel() { LevelAccessor world = this.level != null ? this.level.get() : null; - if (world == null) - { + if (world == null) { world = ServerLifecycleHooks.getCurrentServer().getLevel(this.dim); this.level = new WeakReference(world); } return world; } - public BlockState getReplacedBlock() - { + public BlockState getReplacedBlock() { return this.block; } + /* @Nullable - public BlockEntity getBlockEntity() - { + public BlockEntity getBlockEntity() { return getTag() != null ? BlockEntity.loadStatic(getPos(), getReplacedBlock(), getTag()) : null; } + */ - public boolean restore() - { + public boolean restore() { return restore(false); } - public boolean restore(boolean force) - { + public boolean restore(boolean force) { return restore(force, true); } - public boolean restore(boolean force, boolean notifyNeighbors) - { + public boolean restore(boolean force, boolean notifyNeighbors) { return restoreToLocation(getLevel(), getPos(), force, notifyNeighbors); } - public boolean restoreToLocation(LevelAccessor world, BlockPos pos, boolean force, boolean notifyNeighbors) - { + public boolean restoreToLocation(LevelAccessor world, BlockPos pos, boolean force, boolean notifyNeighbors) { BlockState current = getCurrentBlock(); BlockState replaced = getReplacedBlock(); int flags = notifyNeighbors ? Block.UPDATE_ALL : Block.UPDATE_CLIENTS; - if (current != replaced) - { + if (current != replaced) { if (force) world.setBlock(pos, replaced, flags); else @@ -136,12 +124,10 @@ public class BlockSnapshot ((Level)world).sendBlockUpdated(pos, current, replaced, flags); BlockEntity te = null; - if (getTag() != null) - { + if (getTag() != null) { te = world.getBlockEntity(pos); - if (te != null) - { - te.load(getTag()); + if (te != null) { + te.loadWithComponents(nbt, world.registryAccess()); te.setChanged(); } } @@ -152,8 +138,7 @@ public class BlockSnapshot } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) @@ -168,8 +153,7 @@ public class BlockSnapshot } @Override - public int hashCode() - { + public int hashCode() { int hash = 7; hash = 73 * hash + this.dim.hashCode(); hash = 73 * hash + this.pos.hashCode(); @@ -180,10 +164,8 @@ public class BlockSnapshot } @Override - public String toString() - { - if (toString == null) - { + public String toString() { + if (toString == null) { this.toString = "BlockSnapshot[" + "World:" + this.dim.location() + ',' + diff --git a/src/main/java/net/minecraftforge/common/util/DummySavedData.java b/src/main/java/net/minecraftforge/common/util/DummySavedData.java index 5a10ddf7aa..5a63675814 100644 --- a/src/main/java/net/minecraftforge/common/util/DummySavedData.java +++ b/src/main/java/net/minecraftforge/common/util/DummySavedData.java @@ -5,6 +5,7 @@ package net.minecraftforge.common.util; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.saveddata.SavedData; @@ -15,8 +16,7 @@ public class DummySavedData extends SavedData { } @Override - public CompoundTag save(final CompoundTag compound) { - // NOOP + public CompoundTag save(final CompoundTag compound, HolderLookup.Provider lookup) { return null; } } diff --git a/src/main/java/net/minecraftforge/common/util/INBTSerializable.java b/src/main/java/net/minecraftforge/common/util/INBTSerializable.java index aee0b6d963..2adc13439f 100644 --- a/src/main/java/net/minecraftforge/common/util/INBTSerializable.java +++ b/src/main/java/net/minecraftforge/common/util/INBTSerializable.java @@ -5,14 +5,22 @@ package net.minecraftforge.common.util; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.Tag; /** * An interface designed to unify various things in the Minecraft * code base that can be serialized to and from a NBT tag. + * + * @deprecated // Mojang has switched most things to Codecs and registry context, probably worth deleting this. */ -public interface INBTSerializable -{ - T serializeNBT(); - void deserializeNBT(T nbt); +public interface INBTSerializable { + default T serializeNBT() { return null; } + default T serializeNBT(HolderLookup.Provider registryAccess) { + return serializeNBT(); + } + default void deserializeNBT(T nbt) { } + default void deserializeNBT(HolderLookup.Provider registryAccess, T nbt) { + deserializeNBT(nbt); + } } diff --git a/src/main/java/net/minecraftforge/common/util/LevelCapabilityData.java b/src/main/java/net/minecraftforge/common/util/LevelCapabilityData.java index 7c395aa1d2..68cd6d2afc 100644 --- a/src/main/java/net/minecraftforge/common/util/LevelCapabilityData.java +++ b/src/main/java/net/minecraftforge/common/util/LevelCapabilityData.java @@ -5,6 +5,8 @@ package net.minecraftforge.common.util; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderLookup.Provider; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.saveddata.SavedData; import net.minecraft.world.level.storage.DimensionDataStorage; @@ -30,7 +32,7 @@ public class LevelCapabilityData extends SavedData { } @Override - public CompoundTag save(CompoundTag nbt) { + public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) { if (serializable != null) nbt = serializable.serializeNBT(); return nbt; @@ -52,7 +54,7 @@ public class LevelCapabilityData extends SavedData { public static LevelCapabilityData compute(DimensionDataStorage data, @Nullable INBTSerializable caps) { var factory = new Factory<>( () -> new LevelCapabilityData(caps), - (tag) -> { + (tag, lookup) -> { var ret = new LevelCapabilityData(caps); ret.read(tag); return ret; diff --git a/src/main/java/net/minecraftforge/common/util/PacketLogger.java b/src/main/java/net/minecraftforge/common/util/PacketLogger.java index 0ca3fb1b76..f7e53dc228 100644 --- a/src/main/java/net/minecraftforge/common/util/PacketLogger.java +++ b/src/main/java/net/minecraftforge/common/util/PacketLogger.java @@ -47,11 +47,8 @@ public class PacketLogger { if (packet instanceof ClientboundFinishConfigurationPacket) enabled = false; - if (packet instanceof ICustomPacket) { - var data = new FriendlyByteBuf(Unpooled.buffer()); - - packet.write(data); - LOGGER.info(MARKER, "{} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), HexDumper.dump(data)); + if (packet instanceof ICustomPacket custom && custom.getInternalData() != null) { + LOGGER.info(MARKER, "{} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), HexDumper.dump(custom.getInternalData())); } else { LOGGER.info(MARKER, "{} {} {}", side(side), dir(flow), packet.getClass().getName()); } diff --git a/src/main/java/net/minecraftforge/common/world/BiomeModifier.java b/src/main/java/net/minecraftforge/common/world/BiomeModifier.java index 16d39e6b25..07d17e4d9f 100644 --- a/src/main/java/net/minecraftforge/common/world/BiomeModifier.java +++ b/src/main/java/net/minecraftforge/common/world/BiomeModifier.java @@ -6,12 +6,13 @@ package net.minecraftforge.common.world; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.RegistryCodecs; import net.minecraft.resources.RegistryFileCodec; import net.minecraft.resources.RegistryOps; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.level.biome.Biome; import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo; import net.minecraftforge.registries.ForgeRegistries; @@ -31,14 +32,12 @@ import java.util.function.Function; *

* Datapacks can also disable a biome modifier by overriding the json and using {@code "type": "forge:none"}.

*/ -public interface BiomeModifier -{ +public interface BiomeModifier { /** * Codec for (de)serializing biome modifiers inline. * Mods can use this for data generation. */ - Codec DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.BIOME_MODIFIER_SERIALIZERS.get().getCodec()) - .dispatch(BiomeModifier::codec, Function.identity()); + Codec DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.BIOME_MODIFIER_SERIALIZERS.get().getCodec().dispatch(BiomeModifier::codec, Function.identity())); /** * Codec for referring to biome modifiers by id in other datapack registry files. @@ -66,10 +65,9 @@ public interface BiomeModifier /** * @return the codec which serializes and deserializes this biome modifier */ - Codec codec(); + MapCodec codec(); - enum Phase - { + enum Phase { /** * Catch-all for anything that needs to run before standard phases. */ diff --git a/src/main/java/net/minecraftforge/common/world/ForgeBiomeModifiers.java b/src/main/java/net/minecraftforge/common/world/ForgeBiomeModifiers.java index c14ccab1a1..be5257d7bd 100644 --- a/src/main/java/net/minecraftforge/common/world/ForgeBiomeModifiers.java +++ b/src/main/java/net/minecraftforge/common/world/ForgeBiomeModifiers.java @@ -12,12 +12,12 @@ import java.util.function.Function; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.RegistryCodecs; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.level.biome.Biome; @@ -47,7 +47,7 @@ public final class ForgeBiomeModifiers { * @param step Decoration step to run features in. */ public static record AddFeaturesBiomeModifier(HolderSet biomes, HolderSet features, Decoration step) implements BiomeModifier { - public static final Codec CODEC = RecordCodecBuilder.create(builder -> builder.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddFeaturesBiomeModifier::biomes), PlacedFeature.LIST_CODEC.fieldOf("features").forGetter(AddFeaturesBiomeModifier::features), Decoration.CODEC.fieldOf("step").forGetter(AddFeaturesBiomeModifier::step) @@ -62,7 +62,7 @@ public final class ForgeBiomeModifiers { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } @@ -83,11 +83,11 @@ public final class ForgeBiomeModifiers { * @param steps Decoration steps to remove features from. */ public static record RemoveFeaturesBiomeModifier(HolderSet biomes, HolderSet features, Set steps) implements BiomeModifier { - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Biome.LIST_CODEC.fieldOf("biomes").forGetter(RemoveFeaturesBiomeModifier::biomes), PlacedFeature.LIST_CODEC.fieldOf("features").forGetter(RemoveFeaturesBiomeModifier::features), - ExtraCodecs.either(Decoration.CODEC.listOf(), Decoration.CODEC).>xmap( + Codec.either(Decoration.CODEC.listOf(), Decoration.CODEC).>xmap( either -> either.map(Set::copyOf, Set::of), // convert list/singleton to set when decoding set -> set.size() == 1 ? Either.right(set.toArray(Decoration[]::new)[0]) : Either.left(List.copyOf(set)) ).optionalFieldOf("steps", EnumSet.allOf(Decoration.class)).forGetter(RemoveFeaturesBiomeModifier::steps) @@ -112,7 +112,7 @@ public final class ForgeBiomeModifiers { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } @@ -156,11 +156,11 @@ public final class ForgeBiomeModifiers { * @param spawners List of SpawnerDatas specifying EntityType, weight, and pack size. */ public record AddSpawnsBiomeModifier(HolderSet biomes, List spawners) implements BiomeModifier { - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddSpawnsBiomeModifier::biomes), // Allow either a list or single spawner, attempting to decode the list format first. - ExtraCodecs.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap( + Codec.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap( either -> either.map(Function.identity(), List::of), // convert list/singleton to list when decoding list -> list.size() == 1 ? Either.right(list.get(0)) : Either.left(list) // convert list to singleton/list when encoding ).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners) @@ -186,7 +186,7 @@ public final class ForgeBiomeModifiers { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } @@ -205,7 +205,7 @@ public final class ForgeBiomeModifiers { * @param entityTypes EntityTypes to remove from spawn lists. */ public record RemoveSpawnsBiomeModifier(HolderSet biomes, HolderSet> entityTypes) implements BiomeModifier { - public static final Codec CODEC = RecordCodecBuilder.create(builder -> + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group( Biome.LIST_CODEC.fieldOf("biomes").forGetter(RemoveSpawnsBiomeModifier::biomes), RegistryCodecs.homogeneousList(ForgeRegistries.Keys.ENTITY_TYPES).fieldOf("entity_types").forGetter(RemoveSpawnsBiomeModifier::entityTypes) @@ -221,7 +221,7 @@ public final class ForgeBiomeModifiers { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/world/ForgeChunkManager.java b/src/main/java/net/minecraftforge/common/world/ForgeChunkManager.java index 586374db24..86a76bc3ec 100644 --- a/src/main/java/net/minecraftforge/common/world/ForgeChunkManager.java +++ b/src/main/java/net/minecraftforge/common/world/ForgeChunkManager.java @@ -15,6 +15,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.function.BiConsumer; import java.util.function.Function; @@ -324,10 +325,12 @@ public class ForgeChunkManager */ private static void readBlockForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map, LongSet> blockForcedChunks) { - ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_COMPOUND); + ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_INT_ARRAY); for (int k = 0; k < forcedBlocks.size(); k++) { - blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, NbtUtils.readBlockPos(forcedBlocks.getCompound(k))), owner -> new LongOpenHashSet()).add(chunkPos); + var aint = forcedBlocks.getIntArray(k); + var pos = aint.length == 3 ? new BlockPos(aint[0], aint[1], aint[2]) : BlockPos.ZERO; + blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, pos), owner -> new LongOpenHashSet()).add(chunkPos); } } diff --git a/src/main/java/net/minecraftforge/common/world/NoneBiomeModifier.java b/src/main/java/net/minecraftforge/common/world/NoneBiomeModifier.java index fd14659045..0c0b27a76e 100644 --- a/src/main/java/net/minecraftforge/common/world/NoneBiomeModifier.java +++ b/src/main/java/net/minecraftforge/common/world/NoneBiomeModifier.java @@ -5,7 +5,8 @@ package net.minecraftforge.common.world; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import net.minecraft.core.Holder; import net.minecraft.world.level.biome.Biome; import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo.Builder; @@ -15,14 +16,14 @@ import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo.Builder; */ public class NoneBiomeModifier implements BiomeModifier { public static final NoneBiomeModifier INSTANCE = new NoneBiomeModifier(); - public static final Codec CODEC = Codec.unit(NoneBiomeModifier.INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(NoneBiomeModifier.INSTANCE); @Override public void modify(Holder biome, Phase phase, Builder builder) { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/world/NoneStructureModifier.java b/src/main/java/net/minecraftforge/common/world/NoneStructureModifier.java index 79e02f14b6..cde4469f35 100644 --- a/src/main/java/net/minecraftforge/common/world/NoneStructureModifier.java +++ b/src/main/java/net/minecraftforge/common/world/NoneStructureModifier.java @@ -5,7 +5,8 @@ package net.minecraftforge.common.world; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import net.minecraft.core.Holder; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo.Builder; @@ -16,13 +17,13 @@ import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo.Bui */ public class NoneStructureModifier implements StructureModifier { public static final NoneStructureModifier INSTANCE = new NoneStructureModifier(); - public static final Codec CODEC = Codec.unit(NoneStructureModifier.INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(NoneStructureModifier.INSTANCE); @Override public void modify(Holder structure, Phase phase, Builder builder) {} @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/net/minecraftforge/common/world/StructureModifier.java b/src/main/java/net/minecraftforge/common/world/StructureModifier.java index 82266bd464..94b56b0820 100644 --- a/src/main/java/net/minecraftforge/common/world/StructureModifier.java +++ b/src/main/java/net/minecraftforge/common/world/StructureModifier.java @@ -6,13 +6,14 @@ package net.minecraftforge.common.world; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import java.util.function.Function; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.RegistryCodecs; import net.minecraft.resources.RegistryFileCodec; import net.minecraft.resources.RegistryOps; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo; import net.minecraftforge.registries.ForgeRegistries; @@ -31,14 +32,12 @@ import net.minecraftforge.registries.ForgeRegistries; *

* Datapacks can also disable a structure modifier by overriding the json and using {@code "type": "forge:none"}.

*/ -public interface StructureModifier -{ +public interface StructureModifier { /** * Codec for (de)serializing structure modifiers inline. * Mods can use this for data generation. */ - Codec DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.STRUCTURE_MODIFIER_SERIALIZERS.get().getCodec()) - .dispatch(StructureModifier::codec, Function.identity()); + Codec DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.STRUCTURE_MODIFIER_SERIALIZERS.get().getCodec().dispatch(StructureModifier::codec, Function.identity())); /** * Codec for referring to structure modifiers by id in other datapack registry files. @@ -66,10 +65,9 @@ public interface StructureModifier /** * @return the codec which serializes and deserializes this structure modifier */ - Codec codec(); + MapCodec codec(); - enum Phase - { + enum Phase { /** * Catch-all for anything that needs to run before standard phases. */ diff --git a/src/main/java/net/minecraftforge/event/AnvilUpdateEvent.java b/src/main/java/net/minecraftforge/event/AnvilUpdateEvent.java index efb8e0d93d..2fc290cdaa 100644 --- a/src/main/java/net/minecraftforge/event/AnvilUpdateEvent.java +++ b/src/main/java/net/minecraftforge/event/AnvilUpdateEvent.java @@ -21,19 +21,16 @@ import org.jetbrains.annotations.Nullable; * if the output is empty, and the event is not canceled, vanilla behavior will execute.
*/ @Cancelable -public class AnvilUpdateEvent extends Event -{ - +public class AnvilUpdateEvent extends Event { private final ItemStack left; private final ItemStack right; private final String name; private ItemStack output; - private int cost; + private long cost; private int materialCost; private final Player player; - public AnvilUpdateEvent(ItemStack left, ItemStack right, String name, int cost, Player player) - { + public AnvilUpdateEvent(ItemStack left, ItemStack right, String name, long cost, Player player) { this.left = left; this.right = right; this.output = ItemStack.EMPTY; @@ -46,16 +43,14 @@ public class AnvilUpdateEvent extends Event /** * @return The item in the left input (leftmost) anvil slot. */ - public ItemStack getLeft() - { + public ItemStack getLeft() { return left; } /** * @return The item in the right input (center) anvil slot. */ - public ItemStack getRight() - { + public ItemStack getRight() { return right; } @@ -65,8 +60,7 @@ public class AnvilUpdateEvent extends Event * @return The name that the output item will be set to, if applicable. */ @Nullable - public String getName() - { + public String getName() { return name; } @@ -77,8 +71,7 @@ public class AnvilUpdateEvent extends Event * If this event is cancelled, this output stack is discarded. * @return The item to set in the output (rightmost) anvil slot. */ - public ItemStack getOutput() - { + public ItemStack getOutput() { return output; } @@ -86,8 +79,7 @@ public class AnvilUpdateEvent extends Event * Sets the output slot to a specific itemstack. * @param output The stack to change the output to. */ - public void setOutput(ItemStack output) - { + public void setOutput(ItemStack output) { this.output = output; } @@ -96,8 +88,7 @@ public class AnvilUpdateEvent extends Event * When unchanged, it is guaranteed to be left.getRepairCost() + right.getRepairCost(). * @return The level cost of this anvil operation. */ - public int getCost() - { + public long getCost() { return cost; } @@ -107,8 +98,7 @@ public class AnvilUpdateEvent extends Event * That is, a player without enough experience may not take the output. * @param cost The new level cost. */ - public void setCost(int cost) - { + public void setCost(long cost) { this.cost = cost; } @@ -116,8 +106,7 @@ public class AnvilUpdateEvent extends Event * The material cost is how many units of the right input stack are consumed. * @return The material cost of this anvil operation. */ - public int getMaterialCost() - { + public int getMaterialCost() { return materialCost; } @@ -129,16 +118,14 @@ public class AnvilUpdateEvent extends Event * The material cost does not prevent the output from being available. * @param materialCost The new material cost. */ - public void setMaterialCost(int materialCost) - { + public void setMaterialCost(int materialCost) { this.materialCost = materialCost; } /** * @return The player using this anvil container. */ - public Player getPlayer() - { + public Player getPlayer() { return this.player; } } diff --git a/src/main/java/net/minecraftforge/event/DifficultyChangeEvent.java b/src/main/java/net/minecraftforge/event/DifficultyChangeEvent.java index 53f106ccc5..5421e2f6e3 100644 --- a/src/main/java/net/minecraftforge/event/DifficultyChangeEvent.java +++ b/src/main/java/net/minecraftforge/event/DifficultyChangeEvent.java @@ -19,24 +19,20 @@ import net.minecraftforge.eventbus.api.Event; *
* This event is fired on the {@link MinecraftForge#EVENT_BUS}. **/ -public class DifficultyChangeEvent extends Event -{ +public class DifficultyChangeEvent extends Event { private final Difficulty difficulty; private final Difficulty oldDifficulty; - public DifficultyChangeEvent(Difficulty difficulty, Difficulty oldDifficulty) - { + public DifficultyChangeEvent(Difficulty difficulty, Difficulty oldDifficulty) { this.difficulty = difficulty; this.oldDifficulty = oldDifficulty; } - public Difficulty getDifficulty() - { + public Difficulty getDifficulty() { return difficulty; } - public Difficulty getOldDifficulty() - { + public Difficulty getOldDifficulty() { return oldDifficulty; } } diff --git a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java index 5f98e5e971..2c920fbe86 100644 --- a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java +++ b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java @@ -13,90 +13,116 @@ import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Consumer; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import com.mojang.authlib.GameProfile; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementProgress; import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.core.Holder; +import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ReloadableServerResources; import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.RepositorySource; +import net.minecraft.server.packs.resources.PreparableReloadListener; import net.minecraft.server.players.PlayerList; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.util.random.WeightedRandomList; import net.minecraft.world.Container; +import net.minecraft.world.Difficulty; import net.minecraft.world.DifficultyInstance; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.entity.projectile.Projectile; -import net.minecraft.world.entity.projectile.ThrownEnderpearl; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.level.LevelSimulatedReader; -import net.minecraft.world.level.biome.MobSpawnSettings; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.portal.PortalShape; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.SpawnGroupData; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.LightningBolt; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.monster.Zombie; -import net.minecraft.world.entity.animal.Animal; -import net.minecraft.world.entity.player.Player; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ConfigurationTask; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.server.packs.resources.PreparableReloadListener; -import net.minecraft.world.level.BaseSpawner; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.InteractionResult; -import net.minecraft.core.Direction; -import net.minecraft.world.InteractionHand; -import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.SoundSource; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.core.BlockPos; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LightningBolt; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SlotAccess; +import net.minecraft.world.entity.SpawnGroupData; +import net.minecraft.world.entity.animal.Animal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.FishingHook; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.ThrownEnderpearl; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ClickAction; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.alchemy.PotionBrewing.Builder; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.BaseSpawner; import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.phys.HitResult; -import net.minecraft.network.Connection; -import net.minecraft.network.chat.Component; import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelSimulatedReader; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.SpawnData; -import net.minecraft.world.level.Level; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.level.biome.MobSpawnSettings; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.status.ChunkType; +import net.minecraft.world.level.gameevent.GameEvent; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.portal.PortalShape; import net.minecraft.world.level.storage.PlayerDataStorage; +import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.ToolAction; import net.minecraftforge.common.capabilities.CapabilityDispatcher; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.BlockSnapshot; +import net.minecraftforge.event.brewing.BrewingRecipeRegisterEvent; import net.minecraftforge.event.brewing.PlayerBrewedPotionEvent; import net.minecraftforge.event.brewing.PotionBrewEvent; import net.minecraftforge.event.enchanting.EnchantmentLevelSetEvent; import net.minecraftforge.event.entity.EntityEvent; +import net.minecraftforge.event.entity.EntityJoinLevelEvent; +import net.minecraftforge.event.entity.EntityLeaveLevelEvent; import net.minecraftforge.event.entity.EntityMobGriefingEvent; import net.minecraftforge.event.entity.EntityMountEvent; import net.minecraftforge.event.entity.EntityStruckByLightningEvent; @@ -105,37 +131,51 @@ import net.minecraftforge.event.entity.EntityTravelToDimensionEvent; import net.minecraftforge.event.entity.ProjectileImpactEvent; import net.minecraftforge.event.entity.item.ItemExpireEvent; import net.minecraftforge.event.entity.living.AnimalTameEvent; +import net.minecraftforge.event.entity.living.BabyEntitySpawnEvent; +import net.minecraftforge.event.entity.living.LivingAttackEvent; +import net.minecraftforge.event.entity.living.LivingBreatheEvent; +import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; import net.minecraftforge.event.entity.living.LivingConversionEvent; import net.minecraftforge.event.entity.living.LivingDestroyBlockEvent; +import net.minecraftforge.event.entity.living.LivingDrownEvent; import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent; +import net.minecraftforge.event.entity.living.LivingEquipmentChangeEvent; import net.minecraftforge.event.entity.living.LivingExperienceDropEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.living.LivingHealEvent; +import net.minecraftforge.event.entity.living.LivingKnockBackEvent; import net.minecraftforge.event.entity.living.LivingPackSizeEvent; import net.minecraftforge.event.entity.living.LivingSwapItemsEvent; +import net.minecraftforge.event.entity.living.MobEffectEvent; import net.minecraftforge.event.entity.living.MobSpawnEvent; -import net.minecraftforge.event.entity.living.ShieldBlockEvent; import net.minecraftforge.event.entity.living.MobSpawnEvent.AllowDespawn; import net.minecraftforge.event.entity.living.MobSpawnEvent.PositionCheck; import net.minecraftforge.event.entity.living.MobSpawnEvent.SpawnPlacementCheck; +import net.minecraftforge.event.entity.living.ShieldBlockEvent; +import net.minecraftforge.event.entity.living.LivingChangeTargetEvent.ILivingTargetType; import net.minecraftforge.event.entity.living.ZombieEvent.SummonAidEvent; import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementEarnEvent; import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent; import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType; +import net.minecraftforge.event.entity.player.AnvilRepairEvent; import net.minecraftforge.event.entity.player.ArrowLooseEvent; import net.minecraftforge.event.entity.player.ArrowNockEvent; import net.minecraftforge.event.entity.player.BonemealEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.FillBucketEvent; +import net.minecraftforge.event.entity.player.ItemFishedEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.entity.player.PermissionsChangedEvent; import net.minecraftforge.event.entity.player.PlayerContainerEvent; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerFlyableFallEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerSetSpawnEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; +import net.minecraftforge.event.entity.player.PlayerSpawnPhantomsEvent; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent; +import net.minecraftforge.event.entity.player.PlayerXpEvent; import net.minecraftforge.event.entity.player.SleepingLocationCheckEvent; import net.minecraftforge.event.entity.player.SleepingTimeCheckEvent; import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; @@ -150,31 +190,37 @@ import net.minecraftforge.event.level.ChunkEvent; import net.minecraftforge.event.level.ChunkTicketLevelUpdatedEvent; import net.minecraftforge.event.level.ChunkWatchEvent; import net.minecraftforge.event.level.ExplosionEvent; +import net.minecraftforge.event.level.LevelEvent; +import net.minecraftforge.event.level.NoteBlockEvent; import net.minecraftforge.event.level.PistonEvent; import net.minecraftforge.event.level.SaplingGrowTreeEvent; import net.minecraftforge.event.level.SleepFinishedTimeEvent; import net.minecraftforge.event.network.ChannelRegistrationChangeEvent; import net.minecraftforge.event.network.ConnectionStartEvent; import net.minecraftforge.event.network.GatherLoginConfigurationTasksEvent; -import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.fml.LogicalSide; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import net.minecraftforge.fml.ModLoader; +import net.minecraftforge.fml.event.IModBusEvent; @ApiStatus.Internal -public class ForgeEventFactory { +public final class ForgeEventFactory { + private ForgeEventFactory() {} + private static boolean post(Event e) { return MinecraftForge.EVENT_BUS.post(e); } private static E fire(E e) { - MinecraftForge.EVENT_BUS.post(e); + post(e); return e; } + private static void postModBus(T e) { + ModLoader.get().postEvent(e); + } + public static boolean onMultiBlockPlace(@Nullable Entity entity, List blockSnapshots, Direction direction) { var snap = blockSnapshots.get(0); var placedAgainst = snap.getLevel().getBlockState(snap.getPos().relative(direction.getOpposite())); @@ -202,7 +248,11 @@ public class ForgeEventFactory { } public static void onPlayerDestroyItem(Player player, @NotNull ItemStack stack, @Nullable InteractionHand hand) { - post(new PlayerDestroyItemEvent(player, stack, hand)); + onPlayerDestroyItem(player, stack, LivingEntity.getSlotForHand(hand)); + } + + public static void onPlayerDestroyItem(Player player, @NotNull ItemStack stack, @Nullable EquipmentSlot slot) { + post(new PlayerDestroyItemEvent(player, stack, slot)); } public static boolean checkSpawnPlacements(EntityType entityType, ServerLevelAccessor level, MobSpawnType spawnType, BlockPos pos, RandomSource random, boolean defaultResult) { @@ -272,12 +322,12 @@ public class ForgeEventFactory { */ @Nullable @SuppressWarnings("deprecation") // Call to deprecated Mob#finalizeSpawn is expected. - public static SpawnGroupData onFinalizeSpawn(Mob mob, ServerLevelAccessor level, DifficultyInstance difficulty, MobSpawnType spawnType, @Nullable SpawnGroupData spawnData, @Nullable CompoundTag spawnTag) { - var event = new MobSpawnEvent.FinalizeSpawn(mob, level, mob.getX(), mob.getY(), mob.getZ(), difficulty, spawnType, spawnData, spawnTag, null); + public static SpawnGroupData onFinalizeSpawn(Mob mob, ServerLevelAccessor level, DifficultyInstance difficulty, MobSpawnType spawnType, @Nullable SpawnGroupData spawnData) { + var event = new MobSpawnEvent.FinalizeSpawn(mob, level, mob.getX(), mob.getY(), mob.getZ(), difficulty, spawnType, spawnData, null, null); boolean cancel = post(event); if (!cancel) - mob.finalizeSpawn(level, event.getDifficulty(), event.getSpawnType(), event.getSpawnData(), event.getSpawnTag()); + mob.finalizeSpawn(level, event.getDifficulty(), event.getSpawnType(), event.getSpawnData()); return cancel ? null : event.getSpawnData(); } @@ -454,6 +504,10 @@ public class ForgeEventFactory { return post(new AnimalTameEvent(animal, tamer)); } + public static boolean onPlayerPickupXp(Player player, ExperienceOrb orb) { + return post(new PlayerXpEvent.PickupXp(player, orb)); + } + public static Player.BedSleepingProblem onPlayerSleepInBed(Player player, Optional pos) { return fire(new PlayerSleepInBedEvent(player, pos)).getResultStatus(); } @@ -470,6 +524,10 @@ public class ForgeEventFactory { return post(new PlayerSetSpawnEvent(player, levelKey, pos, forced)); } + public static PlayerSpawnPhantomsEvent onPlayerSpawnPhantom(Player player, int phantomsToSpawn) { + return fire(new PlayerSpawnPhantomsEvent(player, phantomsToSpawn)); + } + public static void onPlayerClone(Player player, Player oldPlayer, boolean wasDeath) { post(new PlayerEvent.Clone(player, oldPlayer, wasDeath)); } @@ -659,6 +717,11 @@ public class ForgeEventFactory { post(new LivingConversionEvent.Post(entity, outcome)); } + public static BabyEntitySpawnEvent onBabySpawn(Mob parentA, Mob parentB, @Nullable AgeableMob proposedChild) { + return fire(new BabyEntitySpawnEvent(parentA, parentB, proposedChild)); + + } + public static EntityTeleportEvent.TeleportCommand onEntityTeleportCommand(Entity entity, double targetX, double targetY, double targetZ) { return fire(new EntityTeleportEvent.TeleportCommand(entity, targetX, targetY, targetZ)); } @@ -806,9 +869,18 @@ public class ForgeEventFactory { post(new LevelEvent.Load(level)); } + public static void onLevelSave(Level level) { + post(new LevelEvent.Save(level)); + } + public static void onChunkDataSave(ChunkAccess chunk, LevelAccessor world, CompoundTag data) { post(new ChunkDataEvent.Save(chunk, world, data)); } + + public static void onChunkDataLoad(ChunkAccess chunk, CompoundTag data, ChunkType status) { + post(new ChunkDataEvent.Load(chunk, data, status)); + } + public static void onGameShuttingDown() { post(new GameShuttingDownEvent()); } @@ -840,4 +912,145 @@ public class ForgeEventFactory { public static LivingFallEvent onLivingFall(LivingEntity entity, float distance, float damageMultiplier) { return fire(new LivingFallEvent(entity, distance, damageMultiplier)); } + + public static LivingBreatheEvent onLivingBreathe(LivingEntity entity, boolean canBreathe, int consumeAirAmount, int refillAirAmount, boolean canRefillAir) { + return fire(new LivingBreatheEvent(entity, canBreathe, consumeAirAmount, refillAirAmount, canRefillAir)); + } + + public static LivingDrownEvent onLivingDrown(LivingEntity entity, boolean isDrowning, float damageAmount, int bubbleCount) { + return fire(new LivingDrownEvent(entity, isDrowning, damageAmount, bubbleCount)); + } + + public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) { + return fire(new LivingKnockBackEvent(target, strength, ratioX, ratioZ)); + } + + public static void onLeftClickEmpty(Player player) { + post(new PlayerInteractEvent.LeftClickEmpty(player)); + } + + public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) { + return fire(new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.convert(action))); + } + + public static PlayerInteractEvent.LeftClickBlock onLeftClickBlockHold(Player player, BlockPos pos, Direction face) { + return fire(new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.CLIENT_HOLD)); + } + + public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) { + return fire(new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec)); + } + + public static PlayerInteractEvent.RightClickItem onRightClickItem(Player player, InteractionHand hand) { + return fire(new PlayerInteractEvent.RightClickItem(player, hand)); + } + + public static PlayerInteractEvent.EntityInteract onEntityInteract(Player player, Entity entity, InteractionHand hand) { + return fire(new PlayerInteractEvent.EntityInteract(player, hand, entity)); + } + + public static PlayerInteractEvent.EntityInteractSpecific onEntityInteractSpecific(Player player, Entity entity, InteractionHand hand, Vec3 vec3d) { + return fire(new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d)); + } + + public static void onRightClickEmpty(Player player, InteractionHand hand) { + post(new PlayerInteractEvent.RightClickEmpty(player, hand)); + } + + // TODO: Remove from mod bus - Lex 04222024 + public static void addPackFindersServer(Consumer consumer) { + postModBus(new AddPackFindersEvent(PackType.SERVER_DATA, consumer)); + } + + public static boolean onEntityJoinLevel(Entity entity, Level level) { + return post(new EntityJoinLevelEvent(entity, level)); + } + public static boolean onEntityJoinLevel(Entity entity, Level level, boolean loadedFromDisk) { + return post(new EntityJoinLevelEvent(entity, level, loadedFromDisk)); + } + + public static boolean onEntityLeaveLevel(Entity entity, Level level) { + return post(new EntityLeaveLevelEvent(entity, level)); + } + + public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) { + post(new DifficultyChangeEvent(difficulty, oldDifficulty)); + } + + public static void onTagsUpdated(RegistryAccess registryAccess, boolean fromClientPacket, boolean isIntegratedServerConnection) { + post(new TagsUpdatedEvent(registryAccess, fromClientPacket, isIntegratedServerConnection)); + } + + public static boolean onLivingAttackEntity(LivingEntity entity, DamageSource src, float amount) { + return post(new LivingAttackEvent(entity, src, amount)); + } + + public static boolean onVanillaGameEvent(Level level, Holder vanillaEvent, Vec3 pos, GameEvent.Context context) { + return post(new VanillaGameEvent(level, vanillaEvent.get(), pos, context)); + } + + public static boolean onLivingEffectExpire(LivingEntity entity, MobEffectInstance effect) { + return post(new MobEffectEvent.Expired(entity, effect)); + } + + public static boolean onLivingEffectAdd(LivingEntity entity, MobEffectInstance oldEffect, MobEffectInstance newEffect, Entity source) { + return post(new MobEffectEvent.Added(entity, oldEffect, newEffect, source)); + } + + public static boolean onLivingEffectRemove(LivingEntity entity, MobEffect effect) { + return post(new MobEffectEvent.Remove(entity, effect)); + } + + public static boolean onLivingEffectRemove(LivingEntity entity, MobEffectInstance effect) { + return post(new MobEffectEvent.Remove(entity, effect)); + } + + public static MobEffectEvent.Applicable onLivingEffectCanApply(LivingEntity entity, MobEffectInstance effect) { + return fire(new MobEffectEvent.Applicable(entity, effect)); + } + + public static void onLivingEquipmentChange(LivingEntity entity, EquipmentSlot slot, ItemStack from, ItemStack to) { + fire(new LivingEquipmentChangeEvent(entity, slot, from, to)); + } + + public static LivingChangeTargetEvent onLivingChangeTargetMob(LivingEntity entity, LivingEntity originalTarget) { + return fire(new LivingChangeTargetEvent(entity, originalTarget, LivingChangeTargetEvent.LivingTargetType.MOB_TARGET)); + } + + public static LivingChangeTargetEvent onLivingChangeTargetBehavior(LivingEntity entity, LivingEntity originalTarget) { + return fire(new LivingChangeTargetEvent(entity, originalTarget, LivingChangeTargetEvent.LivingTargetType.BEHAVIOR_TARGET)); + } + + public static ItemFishedEvent onPlayerFishedItem(List stacks, int rodDamage, FishingHook hook) { + return fire(new ItemFishedEvent(stacks, rodDamage, hook)); + } + + public static PlayerXpEvent.XpChange onPlayerXpChange(Player player, int xp) { + return fire(new PlayerXpEvent.XpChange(player, xp)); + } + + public static PlayerXpEvent.LevelChange onPlayerLevelChange(Player player, int levels) { + return fire(new PlayerXpEvent.LevelChange(player, levels)); + } + + + public static GrindstoneEvent.OnPlaceItem onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) { + return fire(new GrindstoneEvent.OnPlaceItem(top, bottom, xp)); + } + + public static void onBrewingRecipeRegister(Builder builder, FeatureFlagSet features) { + fire(new BrewingRecipeRegisterEvent(builder, features)); + } + + public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) { + return post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess)); + } + + public static NoteBlockEvent.Play onNotePlay(Level world, BlockPos pos, BlockState state, int note, NoteBlockInstrument instrument) { + return fire(new NoteBlockEvent.Play(world, pos, state, note, instrument)); + } + + public static AnvilRepairEvent onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) { + return fire(new AnvilRepairEvent(player, left, right, output)); + } } diff --git a/src/main/java/net/minecraftforge/event/ItemAttributeModifierEvent.java b/src/main/java/net/minecraftforge/event/ItemAttributeModifierEvent.java index ac5d1e0ea9..8dfb6b3913 100644 --- a/src/main/java/net/minecraftforge/event/ItemAttributeModifierEvent.java +++ b/src/main/java/net/minecraftforge/event/ItemAttributeModifierEvent.java @@ -26,7 +26,7 @@ import java.util.Collection; * ignored when attributes are overridden, you can check for the presence of the {@code AttributeModifiers} tag. *
* This event is fired on the {@link net.minecraftforge.common.MinecraftForge#EVENT_BUS}. - */ + * / public class ItemAttributeModifierEvent extends Event { private final ItemStack stack; @@ -47,7 +47,7 @@ public class ItemAttributeModifierEvent extends Event * Returns an unmodifiable view of the attribute multimap. Use other methods from this event to modify the attributes map. * Note that adding attributes based on existing attributes may lead to inconsistent results between the tooltip (client) * and the actual attributes (server) if the listener order is different. Using {@link #getOriginalModifiers()} instead will give more consistent results. - */ + * / public Multimap getModifiers() { return this.unmodifiableModifiers; @@ -55,7 +55,7 @@ public class ItemAttributeModifierEvent extends Event /** * Returns the attribute map before any changes from other event listeners was made. - */ + * / public Multimap getOriginalModifiers() { return this.originalModifiers; @@ -63,7 +63,7 @@ public class ItemAttributeModifierEvent extends Event /** * Gets a modifiable map instance, creating it if the current map is currently unmodifiable - */ + * / private Multimap getModifiableMap() { if (this.modifiableModifiers == null) @@ -81,7 +81,7 @@ public class ItemAttributeModifierEvent extends Event * @param attribute Attribute * @param modifier Modifier instance. * @return True if the attribute was added, false if it was already present - */ + * / public boolean addModifier(Attribute attribute, AttributeModifier modifier) { return getModifiableMap().put(attribute, modifier); @@ -92,7 +92,7 @@ public class ItemAttributeModifierEvent extends Event * @param attribute Attribute * @param modifier Modifier instance * @return True if an attribute was removed, false if no change - */ + * / public boolean removeModifier(Attribute attribute, AttributeModifier modifier) { return getModifiableMap().remove(attribute, modifier); @@ -102,7 +102,7 @@ public class ItemAttributeModifierEvent extends Event * Removes all modifiers for the given attribute * @param attribute Attribute * @return Collection of removed modifiers - */ + * / public Collection removeAttribute(Attribute attribute) { return getModifiableMap().removeAll(attribute); @@ -110,21 +110,22 @@ public class ItemAttributeModifierEvent extends Event /** * Removes all modifiers for all attributes - */ + * / public void clearModifiers() { getModifiableMap().clear(); } - /** Gets the slot containing this stack */ + /** Gets the slot containing this stack * / public EquipmentSlot getSlotType() { return this.slotType; } - /** Gets the item stack instance */ + /** Gets the item stack instance * / public ItemStack getItemStack() { return this.stack; } -} \ No newline at end of file +} +*/ \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/event/PlayLevelSoundEvent.java b/src/main/java/net/minecraftforge/event/PlayLevelSoundEvent.java index eaaeca2e3e..c13db41f5f 100644 --- a/src/main/java/net/minecraftforge/event/PlayLevelSoundEvent.java +++ b/src/main/java/net/minecraftforge/event/PlayLevelSoundEvent.java @@ -38,8 +38,7 @@ import java.util.Objects; * This event is fired on the {@link MinecraftForge#EVENT_BUS}. */ @Cancelable -public class PlayLevelSoundEvent extends Event -{ +public class PlayLevelSoundEvent extends Event { private final Level level; private final float originalVolume; private final float originalPitch; @@ -48,8 +47,7 @@ public class PlayLevelSoundEvent extends Event private float newVolume; private float newPitch; - public PlayLevelSoundEvent(@NotNull Level level, @NotNull Holder sound, @NotNull SoundSource source, float volume, float pitch) - { + public PlayLevelSoundEvent(@NotNull Level level, @NotNull Holder sound, @NotNull SoundSource source, float volume, float pitch) { this.level = level; this.sound = sound; this.source = source; @@ -63,8 +61,7 @@ public class PlayLevelSoundEvent extends Event * {@return the level the sound is being played in} */ @NotNull - public Level getLevel() - { + public Level getLevel() { return this.level; } @@ -72,16 +69,14 @@ public class PlayLevelSoundEvent extends Event * {@return the sound event to be played} */ @Nullable - public Holder getSound() - { + public Holder getSound() { return this.sound; } /** * Sets the sound event to be played. */ - public void setSound(@Nullable Holder sound) - { + public void setSound(@Nullable Holder sound) { this.sound = sound; } @@ -89,16 +84,14 @@ public class PlayLevelSoundEvent extends Event * {@return the sound source} */ @NotNull - public SoundSource getSource() - { + public SoundSource getSource() { return this.source; } /** * Sets the sound source. */ - public void setSource(@NotNull SoundSource source) - { + public void setSource(@NotNull SoundSource source) { Objects.requireNonNull(source, "Sound source cannot be null"); this.source = source; } @@ -106,48 +99,42 @@ public class PlayLevelSoundEvent extends Event /** * {@return the original volume for the sound to be played at} */ - public float getOriginalVolume() - { + public float getOriginalVolume() { return this.originalVolume; } /** * {@return the original pitch for the sound to be played at} */ - public float getOriginalPitch() - { + public float getOriginalPitch() { return this.originalPitch; } /** * {@return the volume the sound will be played at} */ - public float getNewVolume() - { + public float getNewVolume() { return this.newVolume; } /** * Sets the volume the sound will be played at. */ - public void setNewVolume(float newVolume) - { + public void setNewVolume(float newVolume) { this.newVolume = newVolume; } /** * {@return the pitch the sound will be played at} */ - public float getNewPitch() - { + public float getNewPitch() { return this.newPitch; } /** * Sets the pitch the sound will be played at. */ - public void setNewPitch(float newPitch) - { + public void setNewPitch(float newPitch) { this.newPitch = newPitch; } @@ -162,12 +149,10 @@ public class PlayLevelSoundEvent extends Event *

* This event is fired on the {@link MinecraftForge#EVENT_BUS}. */ - public static class AtEntity extends PlayLevelSoundEvent - { + public static class AtEntity extends PlayLevelSoundEvent { private final Entity entity; - public AtEntity(Entity entity, Holder sound, SoundSource source, float volume, float pitch) - { + public AtEntity(Entity entity, Holder sound, SoundSource source, float volume, float pitch) { super(entity.level(), sound, source, volume, pitch); this.entity = entity; } @@ -175,8 +160,7 @@ public class PlayLevelSoundEvent extends Event /** * {@return the entity the sound is being played on} */ - public Entity getEntity() - { + public Entity getEntity() { return this.entity; } } @@ -192,12 +176,10 @@ public class PlayLevelSoundEvent extends Event *

* This event is fired on the {@link MinecraftForge#EVENT_BUS}. */ - public static class AtPosition extends PlayLevelSoundEvent - { + public static class AtPosition extends PlayLevelSoundEvent { private final Vec3 position; - public AtPosition(Level level, Vec3 position, Holder sound, SoundSource source, float volume, float pitch) - { + public AtPosition(Level level, Vec3 position, Holder sound, SoundSource source, float volume, float pitch) { super(level, sound, source, volume, pitch); this.position = position; } @@ -205,8 +187,7 @@ public class PlayLevelSoundEvent extends Event /** * {@return the position the sound is being played at} */ - public Vec3 getPosition() - { + public Vec3 getPosition() { return this.position; } } diff --git a/src/main/java/net/minecraftforge/event/brewing/BrewingRecipeRegisterEvent.java b/src/main/java/net/minecraftforge/event/brewing/BrewingRecipeRegisterEvent.java new file mode 100644 index 0000000000..679c8141e3 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/brewing/BrewingRecipeRegisterEvent.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.event.brewing; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.alchemy.PotionBrewing; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraftforge.common.brewing.BrewingRecipe; +import net.minecraftforge.common.brewing.IBrewingRecipe; +import net.minecraftforge.eventbus.api.Event; + +public class BrewingRecipeRegisterEvent extends Event { + private final PotionBrewing.Builder builder; + private final FeatureFlagSet features; + + @ApiStatus.Internal + public BrewingRecipeRegisterEvent(PotionBrewing.Builder builder, FeatureFlagSet features) { + this.builder = builder; + this.features = features; + } + + public PotionBrewing.Builder getBuilder() { + return this.builder; + } + + public FeatureFlagSet getFeatures() { + return this.features; + } + + /** + * Adds a recipe to the registry. Due to the nature of the brewing stand + * inputs that stack (a.k.a max stack size > 1) are not allowed. + * + * @param input + * The Ingredient that goes in same slots as the water bottles + * would. + * @param ingredient + * The Ingredient that goes in the same slot as nether wart would. + * @param output + * The ItemStack that will replace the input once the brewing is + * done. + */ + public void addRecipe(Ingredient input, Ingredient ingredient, ItemStack output) { + addRecipe(new BrewingRecipe(input, ingredient, output)); + } + + /** + * Adds a recipe to the registry. Due to the nature of the brewing stand + * inputs that stack (a.k.a max stack size > 1) are not allowed. + */ + public void addRecipe(IBrewingRecipe recipe) { + getBuilder().add(recipe); + } +} diff --git a/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java b/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java index d01c4a16bd..9bc920b902 100644 --- a/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java @@ -6,6 +6,8 @@ package net.minecraftforge.event.entity; import com.google.common.collect.ImmutableList; + +import net.minecraft.core.Holder; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attribute; @@ -26,14 +28,12 @@ import java.util.stream.Collectors; *
* Fired on the Mod bus {@link IModBusEvent}.
**/ -public class EntityAttributeModificationEvent extends Event implements IModBusEvent -{ +public class EntityAttributeModificationEvent extends Event implements IModBusEvent { private final Map, AttributeSupplier.Builder> entityAttributes; private final List> entityTypes; @SuppressWarnings("unchecked") - public EntityAttributeModificationEvent(Map, AttributeSupplier.Builder> mapIn) - { + public EntityAttributeModificationEvent(Map, AttributeSupplier.Builder> mapIn) { this.entityAttributes = mapIn; this.entityTypes = ImmutableList.copyOf( ForgeRegistries.ENTITY_TYPES.getValues().stream() @@ -43,27 +43,21 @@ public class EntityAttributeModificationEvent extends Event implements IModBusEv ); } - public void add(EntityType entityType, Attribute attribute, double value) - { - AttributeSupplier.Builder attributes = entityAttributes.computeIfAbsent(entityType, - (type) -> new AttributeSupplier.Builder()); + public void add(EntityType entityType, Holder attribute, double value) { + var attributes = entityAttributes.computeIfAbsent(entityType, (type) -> new AttributeSupplier.Builder()); attributes.add(attribute, value); } - public void add(EntityType entityType, Attribute attribute) - { - add(entityType, attribute, attribute.getDefaultValue()); + public void add(EntityType entityType, Holder attribute) { + add(entityType, attribute, attribute.get().getDefaultValue()); } - public boolean has(EntityType entityType, Attribute attribute) - { + public boolean has(EntityType entityType, Holder attribute) { AttributeSupplier globalMap = DefaultAttributes.getSupplier(entityType); return globalMap.hasAttribute(attribute) || (entityAttributes.get(entityType) != null && entityAttributes.get(entityType).hasAttribute(attribute)); } - public List> getTypes() - { + public List> getTypes() { return entityTypes; } - } diff --git a/src/main/java/net/minecraftforge/event/entity/EntityJoinLevelEvent.java b/src/main/java/net/minecraftforge/event/entity/EntityJoinLevelEvent.java index 35dfcd67d0..ffdcf1ae84 100644 --- a/src/main/java/net/minecraftforge/event/entity/EntityJoinLevelEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/EntityJoinLevelEvent.java @@ -7,7 +7,6 @@ package net.minecraftforge.event.entity; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Cancelable; @@ -28,18 +27,15 @@ import net.minecraftforge.fml.LogicalSide; * on both logical sides. **/ @Cancelable -public class EntityJoinLevelEvent extends EntityEvent -{ +public class EntityJoinLevelEvent extends EntityEvent { private final Level level; private final boolean loadedFromDisk; - public EntityJoinLevelEvent(Entity entity, Level level) - { + public EntityJoinLevelEvent(Entity entity, Level level) { this(entity, level, false); } - public EntityJoinLevelEvent(Entity entity, Level level, boolean loadedFromDisk) - { + public EntityJoinLevelEvent(Entity entity, Level level, boolean loadedFromDisk) { super(entity); this.level = level; this.loadedFromDisk = loadedFromDisk; @@ -48,8 +44,7 @@ public class EntityJoinLevelEvent extends EntityEvent /** * {@return the level that the entity is set to join} */ - public Level getLevel() - { + public Level getLevel() { return level; } @@ -57,8 +52,7 @@ public class EntityJoinLevelEvent extends EntityEvent * @return {@code true} if the entity was loaded from disk, {@code false} otherwise. * On the {@linkplain LogicalSide#CLIENT logical client}, this will always return {@code false}. */ - public boolean loadedFromDisk() - { + public boolean loadedFromDisk() { return loadedFromDisk; } } diff --git a/src/main/java/net/minecraftforge/event/entity/EntityLeaveLevelEvent.java b/src/main/java/net/minecraftforge/event/entity/EntityLeaveLevelEvent.java index 25dd5a5a42..72faf077c0 100644 --- a/src/main/java/net/minecraftforge/event/entity/EntityLeaveLevelEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/EntityLeaveLevelEvent.java @@ -20,12 +20,10 @@ import net.minecraftforge.eventbus.api.Cancelable; * This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus} * on both logical sides. **/ -public class EntityLeaveLevelEvent extends EntityEvent -{ +public class EntityLeaveLevelEvent extends EntityEvent { private final Level level; - public EntityLeaveLevelEvent(Entity entity, Level level) - { + public EntityLeaveLevelEvent(Entity entity, Level level) { super(entity); this.level = level; } @@ -33,8 +31,7 @@ public class EntityLeaveLevelEvent extends EntityEvent /** * {@return the level the entity is set to leave} */ - public Level getLevel() - { + public Level getLevel() { return level; } } diff --git a/src/main/java/net/minecraftforge/event/entity/SpawnPlacementRegisterEvent.java b/src/main/java/net/minecraftforge/event/entity/SpawnPlacementRegisterEvent.java index f971191404..8bbf2e65a7 100644 --- a/src/main/java/net/minecraftforge/event/entity/SpawnPlacementRegisterEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/SpawnPlacementRegisterEvent.java @@ -12,6 +12,7 @@ import java.util.Map; import javax.annotation.Nullable; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.SpawnPlacementType; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.levelgen.Heightmap; @@ -41,29 +42,25 @@ import org.jetbrains.annotations.ApiStatus; * * Fired on the Mod bus {@link IModBusEvent}.
*/ -public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent -{ +public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent { private final Map, MergedSpawnPredicate> map; @ApiStatus.Internal - public SpawnPlacementRegisterEvent(Map, MergedSpawnPredicate> map) - { + public SpawnPlacementRegisterEvent(Map, MergedSpawnPredicate> map) { this.map = map; } /** * Register an optional spawn placement {@code predicate} for a given {@code entityType} */ - public void register(EntityType entityType, SpawnPlacements.SpawnPredicate predicate) - { + public void register(EntityType entityType, SpawnPlacements.SpawnPredicate predicate) { register(entityType, null, null, predicate, Operation.OR); } /** * Register a {@code predicate} for a given {@code entityType} with a given {@code operation} for handling */ - public void register(EntityType entityType, SpawnPlacements.SpawnPredicate predicate, Operation operation) - { + public void register(EntityType entityType, SpawnPlacements.SpawnPredicate predicate, Operation operation) { register(entityType, null, null, predicate, operation); } @@ -73,32 +70,27 @@ public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent * Use {@code null} for the placement or heightmap to leave them as is (which should be done in almost every case) */ @SuppressWarnings("unchecked") - public void register(EntityType entityType, @Nullable SpawnPlacements.Type placementType, @Nullable Heightmap.Types heightmap, SpawnPlacements.SpawnPredicate predicate, Operation operation) - { - if (!map.containsKey(entityType)) - { - if (placementType == null) - { + public void register(EntityType entityType, @Nullable SpawnPlacementType placementType, @Nullable Heightmap.Types heightmap, SpawnPlacements.SpawnPredicate predicate, Operation operation) { + if (!map.containsKey(entityType)) { + if (placementType == null) { throw new NullPointerException("Registering a new Spawn Predicate requires a nonnull placement type! Entity Type: " + ForgeRegistries.ENTITY_TYPES.getKey(entityType)); } - if (heightmap == null) - { + + if (heightmap == null) { throw new NullPointerException("Registering a new Spawn Predicate requires a nonnull heightmap type! Entity Type: "+ ForgeRegistries.ENTITY_TYPES.getKey(entityType)); } + map.put(entityType, new MergedSpawnPredicate<>(predicate, placementType, heightmap)); - } - else - { - if (operation != Operation.REPLACE && (heightmap != null || placementType != null)) - { + } else { + if (operation != Operation.REPLACE && (heightmap != null || placementType != null)) { throw new IllegalStateException("Nonnull heightmap types or spawn placement types may only be used with the REPLACE operation. Entity Type: "+ ForgeRegistries.ENTITY_TYPES.getKey(entityType)); } + ((MergedSpawnPredicate) map.get(entityType)).merge(operation, predicate, placementType, heightmap); } } - public enum Operation - { + public enum Operation { /** * Checked third, these predicates must all pass along with the original predicate */ @@ -113,17 +105,15 @@ public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent REPLACE } - public static class MergedSpawnPredicate - { + public static class MergedSpawnPredicate { private final SpawnPlacements.SpawnPredicate originalPredicate; private final List> orPredicates; private final List> andPredicates; @Nullable private SpawnPlacements.SpawnPredicate replacementPredicate; - private SpawnPlacements.Type spawnType; + private SpawnPlacementType spawnType; private Heightmap.Types heightmapType; - public MergedSpawnPredicate(SpawnPlacements.SpawnPredicate originalPredicate, SpawnPlacements.Type spawnType, Heightmap.Types heightmapType) - { + public MergedSpawnPredicate(SpawnPlacements.SpawnPredicate originalPredicate, SpawnPlacementType spawnType, Heightmap.Types heightmapType) { this.originalPredicate = originalPredicate; this.orPredicates = new ArrayList<>(); this.andPredicates = new ArrayList<>(); @@ -132,58 +122,46 @@ public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent this.heightmapType = heightmapType; } - public SpawnPlacements.Type getSpawnType() - { + public SpawnPlacementType getSpawnType() { return spawnType; } - public Heightmap.Types getHeightmapType() - { + public Heightmap.Types getHeightmapType() { return heightmapType; } - private void merge(Operation operation, SpawnPlacements.SpawnPredicate predicate, @Nullable SpawnPlacements.Type spawnType, @Nullable Heightmap.Types heightmapType) - { - if (operation == Operation.AND) - { + private void merge(Operation operation, SpawnPlacements.SpawnPredicate predicate, @Nullable SpawnPlacementType spawnType, @Nullable Heightmap.Types heightmapType) { + if (operation == Operation.AND) { andPredicates.add(predicate); - } - else if (operation == Operation.OR) - { + } else if (operation == Operation.OR) { orPredicates.add(predicate); - } - else if (operation == Operation.REPLACE) - { + } else if (operation == Operation.REPLACE) { replacementPredicate = predicate; - if (spawnType != null) - { + if (spawnType != null) { this.spawnType = spawnType; } - if (heightmapType != null) - { + + if (heightmapType != null) { this.heightmapType = heightmapType; } } } @ApiStatus.Internal - public SpawnPlacements.SpawnPredicate build() - { - if (replacementPredicate != null) - { + public SpawnPlacements.SpawnPredicate build() { + if (replacementPredicate != null) { return replacementPredicate; } + final var original = originalPredicate; final SpawnPlacements.SpawnPredicate compiledOrPredicate = (entityType, level, spawnType, pos, random) -> { - if (original.test(entityType, level, spawnType, pos, random)) - { + if (original.test(entityType, level, spawnType, pos, random)) { return true; } - for (SpawnPlacements.SpawnPredicate predicate : orPredicates) - { - if (predicate.test(entityType, level, spawnType, pos, random)) - { + + for (SpawnPlacements.SpawnPredicate predicate : orPredicates) { + if (predicate.test(entityType, level, spawnType, pos, random)) { return true; } } @@ -191,14 +169,12 @@ public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent }; final SpawnPlacements.SpawnPredicate compiledAndPredicate = (entityType, level, spawnType, pos, random) -> { - if (!compiledOrPredicate.test(entityType, level, spawnType, pos, random)) - { + if (!compiledOrPredicate.test(entityType, level, spawnType, pos, random)) { return false; } - for (SpawnPlacements.SpawnPredicate predicate : andPredicates) - { - if (!predicate.test(entityType, level, spawnType, pos, random)) - { + + for (SpawnPlacements.SpawnPredicate predicate : andPredicates) { + if (!predicate.test(entityType, level, spawnType, pos, random)) { return false; } } @@ -208,5 +184,4 @@ public class SpawnPlacementRegisterEvent extends Event implements IModBusEvent return compiledAndPredicate; } } - } diff --git a/src/main/java/net/minecraftforge/event/entity/living/BabyEntitySpawnEvent.java b/src/main/java/net/minecraftforge/event/entity/living/BabyEntitySpawnEvent.java index d34ef1245a..59d780499a 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/BabyEntitySpawnEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/BabyEntitySpawnEvent.java @@ -13,6 +13,8 @@ import net.minecraft.world.entity.animal.Fox; import net.minecraft.world.entity.player.Player; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Cancelable; +import net.minecraftforge.eventbus.api.Event; + import org.jetbrains.annotations.Nullable; /** @@ -36,24 +38,21 @@ import org.jetbrains.annotations.Nullable; * This event is fired on the {@link MinecraftForge#EVENT_BUS}. **/ @Cancelable -public class BabyEntitySpawnEvent extends net.minecraftforge.eventbus.api.Event -{ +public class BabyEntitySpawnEvent extends Event { private final Mob parentA; private final Mob parentB; private final Player causedByPlayer; private AgeableMob child; - public BabyEntitySpawnEvent(Mob parentA, Mob parentB, @Nullable AgeableMob proposedChild) - { + public BabyEntitySpawnEvent(Mob parentA, Mob parentB, @Nullable AgeableMob proposedChild) { //causedByPlayer calculated here to simplify the patch. Player causedByPlayer = null; - if (parentA instanceof Animal) { - causedByPlayer = ((Animal)parentA).getLoveCause(); + if (parentA instanceof Animal animal) { + causedByPlayer = animal.getLoveCause(); } - if (causedByPlayer == null && parentB instanceof Animal) - { - causedByPlayer = ((Animal)parentB).getLoveCause(); + if (causedByPlayer == null && parentB instanceof Animal animal) { + causedByPlayer = animal.getLoveCause(); } this.parentA = parentA; @@ -62,30 +61,25 @@ public class BabyEntitySpawnEvent extends net.minecraftforge.eventbus.api.Event this.child = proposedChild; } - public Mob getParentA() - { + public Mob getParentA() { return parentA; } - public Mob getParentB() - { + public Mob getParentB() { return parentB; } @Nullable - public Player getCausedByPlayer() - { + public Player getCausedByPlayer() { return causedByPlayer; } @Nullable - public AgeableMob getChild() - { + public AgeableMob getChild() { return child; } - public void setChild(AgeableMob proposedChild) - { + public void setChild(AgeableMob proposedChild) { child = proposedChild; } } diff --git a/src/main/java/net/minecraftforge/event/entity/living/LivingBreatheEvent.java b/src/main/java/net/minecraftforge/event/entity/living/LivingBreatheEvent.java index db9763dacf..bb684a2be4 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/LivingBreatheEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/LivingBreatheEvent.java @@ -29,12 +29,6 @@ public class LivingBreatheEvent extends LivingEvent { private int consumeAirAmount; private int refillAirAmount; - @ApiStatus.Internal - @Deprecated(forRemoval = true, since = "1.20.1") - public LivingBreatheEvent(LivingEntity entity, boolean canBreathe, int consumeAirAmount, int refillAirAmount) { - this(entity, canBreathe, consumeAirAmount, refillAirAmount, canBreathe); - } - @ApiStatus.Internal public LivingBreatheEvent(LivingEntity entity, boolean canBreathe, int consumeAirAmount, int refillAirAmount, boolean canRefillAir) { super(entity); diff --git a/src/main/java/net/minecraftforge/event/entity/living/LivingChangeTargetEvent.java b/src/main/java/net/minecraftforge/event/entity/living/LivingChangeTargetEvent.java index 968a382697..9e3a3460cb 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/LivingChangeTargetEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/LivingChangeTargetEvent.java @@ -34,14 +34,12 @@ import net.minecraftforge.eventbus.api.Cancelable; * This event is fired on the {@link MinecraftForge#EVENT_BUS}. */ @Cancelable -public class LivingChangeTargetEvent extends LivingEvent -{ +public class LivingChangeTargetEvent extends LivingEvent { private final ILivingTargetType targetType; private final LivingEntity originalTarget; private LivingEntity newTarget; - - public LivingChangeTargetEvent(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) - { + + public LivingChangeTargetEvent(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) { super(entity); this.originalTarget = originalTarget; this.newTarget = originalTarget; @@ -51,8 +49,7 @@ public class LivingChangeTargetEvent extends LivingEvent /** * {@return the new target of this entity.} */ - public LivingEntity getNewTarget() - { + public LivingEntity getNewTarget() { return newTarget; } @@ -60,43 +57,36 @@ public class LivingChangeTargetEvent extends LivingEvent * Sets the new target this entity shall have. * @param newTarget The new target of this entity. */ - public void setNewTarget(LivingEntity newTarget) - { + public void setNewTarget(LivingEntity newTarget) { this.newTarget = newTarget; } - + /** * {@return the living target type.} */ - public ILivingTargetType getTargetType() - { + public ILivingTargetType getTargetType() { return targetType; } /** * {@return the original entity MC intended to use as a target before firing this event.} */ - public LivingEntity getOriginalTarget() - { + public LivingEntity getOriginalTarget() { return originalTarget; } - - + + /** * A living target type indicates what kind of system caused a change of * targets. For a list of default target types, take a look at * {@link LivingTargetType}. */ - public static interface ILivingTargetType - { - - } - + public static interface ILivingTargetType { } + /** * This enum contains two default living target types. */ - public static enum LivingTargetType implements ILivingTargetType - { + public static enum LivingTargetType implements ILivingTargetType { /** * This target type indicates that the target has been set by calling {@link Mob#setTarget(LivingEntity)}. */ diff --git a/src/main/java/net/minecraftforge/event/entity/living/LivingDrownEvent.java b/src/main/java/net/minecraftforge/event/entity/living/LivingDrownEvent.java index dfcd5f75fd..acbcabd4c1 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/LivingDrownEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/LivingDrownEvent.java @@ -47,13 +47,6 @@ public class LivingDrownEvent extends LivingEvent { this.bubbleCount = bubbleCount; } - - @ApiStatus.Internal - @Deprecated(forRemoval = true, since = "1.20.1") - public LivingDrownEvent(LivingEntity entity, boolean isDrowning) { - this(entity, isDrowning, 2.0F, 8); - } - /** * This method returns true if the entity is "actively" drowning.
* For most entities, this happens when their air supply reaches -20.
diff --git a/src/main/java/net/minecraftforge/event/entity/living/LivingEquipmentChangeEvent.java b/src/main/java/net/minecraftforge/event/entity/living/LivingEquipmentChangeEvent.java index e75d4c09e0..457feea57c 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/LivingEquipmentChangeEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/LivingEquipmentChangeEvent.java @@ -28,23 +28,29 @@ import org.jetbrains.annotations.NotNull; *
* This event is fired on the {@link MinecraftForge#EVENT_BUS}. **/ -public class LivingEquipmentChangeEvent extends LivingEvent -{ +public class LivingEquipmentChangeEvent extends LivingEvent { private final EquipmentSlot slot; private final ItemStack from; private final ItemStack to; - public LivingEquipmentChangeEvent(LivingEntity entity, EquipmentSlot slot, @NotNull ItemStack from, @NotNull ItemStack to) - { + public LivingEquipmentChangeEvent(LivingEntity entity, EquipmentSlot slot, @NotNull ItemStack from, @NotNull ItemStack to) { super(entity); this.slot = slot; this.from = from; this.to = to; } - public EquipmentSlot getSlot() { return this.slot; } + public EquipmentSlot getSlot() { + return this.slot; + } + @NotNull - public ItemStack getFrom() { return this.from; } + public ItemStack getFrom() { + return this.from; + } + @NotNull - public ItemStack getTo() { return this.to; } + public ItemStack getTo() { + return this.to; + } } diff --git a/src/main/java/net/minecraftforge/event/entity/living/MobEffectEvent.java b/src/main/java/net/minecraftforge/event/entity/living/MobEffectEvent.java index d6dc629903..ff82d0f76b 100644 --- a/src/main/java/net/minecraftforge/event/entity/living/MobEffectEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/living/MobEffectEvent.java @@ -5,6 +5,7 @@ package net.minecraftforge.event.entity.living; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.Entity; @@ -19,20 +20,17 @@ import org.jetbrains.annotations.Nullable; *

* All children of this event are fired on the {@link MinecraftForge#EVENT_BUS}. */ -public class MobEffectEvent extends LivingEvent -{ +public class MobEffectEvent extends LivingEvent { @Nullable protected final MobEffectInstance effectInstance; - public MobEffectEvent(LivingEntity living, MobEffectInstance effectInstance) - { + public MobEffectEvent(LivingEntity living, MobEffectInstance effectInstance) { super(living); this.effectInstance = effectInstance; } @Nullable - public MobEffectInstance getEffectInstance() - { + public MobEffectInstance getEffectInstance() { return effectInstance; } @@ -42,27 +40,23 @@ public class MobEffectEvent extends LivingEvent * This Event does not have a result. */ @Cancelable - public static class Remove extends MobEffectEvent - { + public static class Remove extends MobEffectEvent { private final MobEffect effect; - public Remove(LivingEntity living, MobEffect effect) - { - super(living, living.getEffect(effect)); + public Remove(LivingEntity living, MobEffect effect) { + super(living, living.getEffect(BuiltInRegistries.MOB_EFFECT.wrapAsHolder(effect))); this.effect = effect; } - public Remove(LivingEntity living, MobEffectInstance effectInstance) - { + public Remove(LivingEntity living, MobEffectInstance effectInstance) { super(living, effectInstance); - this.effect = effectInstance.getEffect(); + this.effect = effectInstance.getEffect().get(); } /** * @return the {@link MobEffectEvent} which is being removed from the entity */ - public MobEffect getEffect() - { + public MobEffect getEffect() { return this.effect; } @@ -71,8 +65,7 @@ public class MobEffectEvent extends LivingEvent */ @Override @Nullable - public MobEffectInstance getEffectInstance() - { + public MobEffectInstance getEffectInstance() { return super.getEffectInstance(); } } @@ -87,17 +80,14 @@ public class MobEffectEvent extends LivingEvent * {@link Result#DEFAULT DEFAULT} will run vanilla logic to determine if this mob effect is applicable in {@link LivingEntity#canBeAffected}. */ @HasResult - public static class Applicable extends MobEffectEvent - { - public Applicable(LivingEntity living, @NotNull MobEffectInstance effectInstance) - { + public static class Applicable extends MobEffectEvent { + public Applicable(LivingEntity living, @NotNull MobEffectInstance effectInstance) { super(living, effectInstance); } @Override @NotNull - public MobEffectInstance getEffectInstance() - { + public MobEffectInstance getEffectInstance() { return super.getEffectInstance(); } } @@ -108,13 +98,11 @@ public class MobEffectEvent extends LivingEvent * This event is not {@link Cancelable}. * This event does not have a result. */ - public static class Added extends MobEffectEvent - { + public static class Added extends MobEffectEvent { private final MobEffectInstance oldEffectInstance; private final Entity source; - public Added(LivingEntity living, MobEffectInstance oldEffectInstance, MobEffectInstance newEffectInstance, Entity source) - { + public Added(LivingEntity living, MobEffectInstance oldEffectInstance, MobEffectInstance newEffectInstance, Entity source) { super(living, newEffectInstance); this.oldEffectInstance = oldEffectInstance; this.source = source; @@ -125,8 +113,7 @@ public class MobEffectEvent extends LivingEvent */ @Override @NotNull - public MobEffectInstance getEffectInstance() - { + public MobEffectInstance getEffectInstance() { return super.getEffectInstance(); } @@ -134,8 +121,7 @@ public class MobEffectEvent extends LivingEvent * @return the old {@link MobEffectInstance}. This can be null if the entity did not have an effect of this kind before. */ @Nullable - public MobEffectInstance getOldEffectInstance() - { + public MobEffectInstance getOldEffectInstance() { return oldEffectInstance; } @@ -143,8 +129,7 @@ public class MobEffectEvent extends LivingEvent * @return the entity source of the effect, or {@code null} if none exists */ @Nullable - public Entity getEffectSource() - { + public Entity getEffectSource() { return source; } } @@ -154,11 +139,9 @@ public class MobEffectEvent extends LivingEvent * This event is not {@link Cancelable}. * This event does not have a result. */ - public static class Expired extends MobEffectEvent - { - public Expired(LivingEntity living, MobEffectInstance effectInstance) - { - super(living, effectInstance); + public static class Expired extends MobEffectEvent { + public Expired(LivingEntity living, MobEffectInstance effect) { + super(living, effect); } } } diff --git a/src/main/java/net/minecraftforge/event/entity/living/PotionColorCalculationEvent.java b/src/main/java/net/minecraftforge/event/entity/living/PotionColorCalculationEvent.java deleted file mode 100644 index 0aee8d32f4..0000000000 --- a/src/main/java/net/minecraftforge/event/entity/living/PotionColorCalculationEvent.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.event.entity.living; - -import java.util.Collection; -import java.util.Collections; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.Cancelable; - -/** - * Fires after Potion Color Calculation. - * - * this event is not {@link Cancelable} - * - * This event is fired on the {@link MinecraftForge#EVENT_BUS}. - */ -public class PotionColorCalculationEvent extends LivingEvent -{ - private int color; - private boolean hideParticle; - private final Collection effectList; - - public PotionColorCalculationEvent(LivingEntity entity, int color, boolean hideParticle, - Collection effectList) - { - super(entity); - this.color = color; - this.effectList = effectList; - this.hideParticle = hideParticle; - } - - public int getColor() - { - return color; - } - - public void setColor(int color) - { - this.color = color; - } - - public boolean areParticlesHidden() - { - return hideParticle; - } - - public void shouldHideParticles(boolean hideParticle) - { - this.hideParticle = hideParticle; - } - - /** - * Note that returned list is unmodifiable. - * - * @return effects - */ - public Collection getEffects() - { - return Collections.unmodifiableCollection(effectList); - } -} diff --git a/src/main/java/net/minecraftforge/event/entity/player/ItemFishedEvent.java b/src/main/java/net/minecraftforge/event/entity/player/ItemFishedEvent.java index 28e1ef87f8..3425cffd5f 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/ItemFishedEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/ItemFishedEvent.java @@ -22,14 +22,12 @@ import java.util.List; * The hook will still take the damage specified */ @Cancelable -public class ItemFishedEvent extends PlayerEvent -{ +public class ItemFishedEvent extends PlayerEvent { private final NonNullList stacks = NonNullList.create(); private final FishingHook hook; private int rodDamage; - public ItemFishedEvent(List stacks, int rodDamage, FishingHook hook) - { + public ItemFishedEvent(List stacks, int rodDamage, FishingHook hook) { super(hook.getPlayerOwner()); this.stacks.addAll(stacks); this.rodDamage = rodDamage; @@ -40,8 +38,7 @@ public class ItemFishedEvent extends PlayerEvent * Get the damage the rod will take. * @return The damage the rod will take */ - public int getRodDamage() - { + public int getRodDamage() { return rodDamage; } @@ -50,8 +47,7 @@ public class ItemFishedEvent extends PlayerEvent * This is not added to the pre-existing damage to be taken. * @param rodDamage The damage the rod will take. Must be nonnegative */ - public void damageRodBy(@Nonnegative int rodDamage) - { + public void damageRodBy(@Nonnegative int rodDamage) { Preconditions.checkArgument(rodDamage >= 0); this.rodDamage = rodDamage; } @@ -61,16 +57,14 @@ public class ItemFishedEvent extends PlayerEvent * You cannot use this to modify the drops the player will get. * If you want to affect the loot, you should use LootTables. */ - public NonNullList getDrops() - { + public NonNullList getDrops() { return stacks; } /** * Use this to stuff related to the hook itself, like the position of the bobber. */ - public FishingHook getHookEntity() - { + public FishingHook getHookEntity() { return hook; } } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerDestroyItemEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerDestroyItemEvent.java index aca1d8e4bb..5733f00528 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerDestroyItemEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerDestroyItemEvent.java @@ -11,6 +11,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayerGameMode; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionHand; @@ -47,22 +48,26 @@ import org.jetbrains.annotations.Nullable; * This event is fired from {@link ForgeEventFactory#onPlayerDestroyItem(Player, ItemStack, InteractionHand)}.
* This event is fired on the {@link MinecraftForge#EVENT_BUS}. **/ -public class PlayerDestroyItemEvent extends PlayerEvent -{ +public class PlayerDestroyItemEvent extends PlayerEvent { @NotNull private final ItemStack original; @Nullable - private final InteractionHand hand; // May be null if this player destroys the item by any use besides holding it. - public PlayerDestroyItemEvent(Player player, @NotNull ItemStack original, @Nullable InteractionHand hand) - { + private final EquipmentSlot slot; // May be null if this player destroys the item by any use besides holding it. + + public PlayerDestroyItemEvent(Player player, @NotNull ItemStack original, @Nullable EquipmentSlot slot) { super(player); this.original = original; - this.hand = hand; + this.slot = slot; } @NotNull - public ItemStack getOriginal() { return this.original; } + public ItemStack getOriginal() { + return this.original; + } + @Nullable - public InteractionHand getHand() { return this.hand; } + public EquipmentSlot getSlot() { + return this.slot; + } } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java index 812817c879..cd6ae78ad9 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java @@ -37,16 +37,14 @@ import org.jetbrains.annotations.Nullable; * All subclasses are fired on {@link MinecraftForge#EVENT_BUS}. * See the individual documentation on each subevent for more details. **/ -public class PlayerInteractEvent extends PlayerEvent -{ +public class PlayerInteractEvent extends PlayerEvent { private final InteractionHand hand; private final BlockPos pos; @Nullable private final Direction face; private InteractionResult cancellationResult = InteractionResult.PASS; - private PlayerInteractEvent(Player player, InteractionHand hand, BlockPos pos, @Nullable Direction face) - { + private PlayerInteractEvent(Player player, InteractionHand hand, BlockPos pos, @Nullable Direction face) { super(Preconditions.checkNotNull(player, "Null player in PlayerInteractEvent!")); this.hand = Preconditions.checkNotNull(hand, "Null hand in PlayerInteractEvent!"); this.pos = Preconditions.checkNotNull(pos, "Null position in PlayerInteractEvent!"); @@ -56,20 +54,18 @@ public class PlayerInteractEvent extends PlayerEvent /** * This event is fired on both sides whenever a player right clicks an entity. * - * "Interact at" is an interact where the local vector (which part of the entity you clicked) is known. + * "Specific" is an interact where the local vector (which part of the entity you clicked) is known. * The state of this event affects whether {@link Entity#interactAt(Player, Vec3, InteractionHand)} is called. * * Let result be the return value of {@link Entity#interactAt(Player, Vec3, InteractionHand)}, or {@link #cancellationResult} if the event is cancelled. * If we are on the client and result is not {@link InteractionResult#SUCCESS}, the client will then try {@link EntityInteract}. */ @Cancelable - public static class EntityInteractSpecific extends PlayerInteractEvent - { + public static class EntityInteractSpecific extends PlayerInteractEvent { private final Vec3 localPos; private final Entity target; - public EntityInteractSpecific(Player player, InteractionHand hand, Entity target, Vec3 localPos) - { + public EntityInteractSpecific(Player player, InteractionHand hand, Entity target, Vec3 localPos) { super(player, hand, target.blockPosition(), null); this.localPos = localPos; this.target = target; @@ -81,13 +77,11 @@ public class PlayerInteractEvent extends PlayerEvent * [-width / 2, width / 2] while Y values will be in the range [0, height] * @return The local position */ - public Vec3 getLocalPos() - { + public Vec3 getLocalPos() { return localPos; } - public Entity getTarget() - { + public Entity getTarget() { return target; } } @@ -106,18 +100,15 @@ public class PlayerInteractEvent extends PlayerEvent * If we are on the client and result is not {@link InteractionResult#SUCCESS}, the client will then try {@link RightClickItem}. */ @Cancelable - public static class EntityInteract extends PlayerInteractEvent - { + public static class EntityInteract extends PlayerInteractEvent { private final Entity target; - public EntityInteract(Player player, InteractionHand hand, Entity target) - { + public EntityInteract(Player player, InteractionHand hand, Entity target) { super(player, hand, target.blockPosition(), null); this.target = target; } - public Entity getTarget() - { + public Entity getTarget() { return target; } } @@ -136,8 +127,7 @@ public class PlayerInteractEvent extends PlayerEvent * Note that handling things differently on the client vs server may cause desynchronizations! */ @Cancelable - public static class RightClickBlock extends PlayerInteractEvent - { + public static class RightClickBlock extends PlayerInteractEvent { private Result useBlock = Result.DEFAULT; private Result useItem = Result.DEFAULT; private BlockHitResult hitVec; @@ -150,24 +140,21 @@ public class PlayerInteractEvent extends PlayerEvent /** * @return If {@link Block#use(BlockState, Level, BlockPos, Player, InteractionHand, BlockHitResult)} should be called */ - public Result getUseBlock() - { + public Result getUseBlock() { return useBlock; } /** * @return If {@link Item#onItemUseFirst} and {@link Item#useOn(UseOnContext)} should be called */ - public Result getUseItem() - { + public Result getUseItem() { return useItem; } /** * @return The ray trace result targeting the block. */ - public BlockHitResult getHitVec() - { + public BlockHitResult getHitVec() { return hitVec; } @@ -177,8 +164,7 @@ public class PlayerInteractEvent extends PlayerEvent * Note that default activation can be blocked if the user is sneaking and holding an item that does not return true to {@link Item#doesSneakBypassUse}.
* ALLOW: {@link Block#updateOrDestroy(BlockState, BlockState, LevelAccessor, BlockPos, int, int)} will always be called, unless {@link Item#onItemUseFirst} does not pass.
*/ - public void setUseBlock(Result triggerBlock) - { + public void setUseBlock(Result triggerBlock) { this.useBlock = triggerBlock; } @@ -187,17 +173,14 @@ public class PlayerInteractEvent extends PlayerEvent * DEFAULT: {@link Item#onItemUseFirst} will always be called, and {@link Item#useOn(UseOnContext)} will be called if the block passes.
* ALLOW: {@link Item#onItemUseFirst} will always be called, and {@link Item#useOn(UseOnContext)} will be called if the block passes, regardless of cooldowns or emptiness.
*/ - public void setUseItem(Result triggerItem) - { + public void setUseItem(Result triggerItem) { this.useItem = triggerItem; } @Override - public void setCanceled(boolean canceled) - { + public void setCanceled(boolean canceled) { super.setCanceled(canceled); - if (canceled) - { + if (canceled) { useBlock = Result.DENY; useItem = Result.DENY; } @@ -212,10 +195,8 @@ public class PlayerInteractEvent extends PlayerEvent * If we are on the client and result is not {@link InteractionResult#SUCCESS}, the client will then continue to other hands. */ @Cancelable - public static class RightClickItem extends PlayerInteractEvent - { - public RightClickItem(Player player, InteractionHand hand) - { + public static class RightClickItem extends PlayerInteractEvent { + public RightClickItem(Player player, InteractionHand hand) { super(player, hand, player.blockPosition(), null); } } @@ -225,10 +206,8 @@ public class PlayerInteractEvent extends PlayerEvent * The server is not aware of when the client right clicks empty space with an empty hand, you will need to tell the server yourself. * This event cannot be canceled. */ - public static class RightClickEmpty extends PlayerInteractEvent - { - public RightClickEmpty(Player player, InteractionHand hand) - { + public static class RightClickEmpty extends PlayerInteractEvent { + public RightClickEmpty(Player player, InteractionHand hand) { super(player, hand, player.blockPosition(), null); } } @@ -249,21 +228,13 @@ public class PlayerInteractEvent extends PlayerEvent * Therefore, in creative mode, {@link #setUseBlock} and {@link #setUseItem} have no effect. */ @Cancelable - public static class LeftClickBlock extends PlayerInteractEvent - { + public static class LeftClickBlock extends PlayerInteractEvent { private Result useBlock = Result.DEFAULT; private Result useItem = Result.DEFAULT; private final Action action; - @Deprecated(since = "1.20.1", forRemoval = true) - public LeftClickBlock(Player player, BlockPos pos, Direction face) - { - this(player, pos, face, Action.START); - } - @ApiStatus.Internal - public LeftClickBlock(Player player, BlockPos pos, Direction face, Action action) - { + public LeftClickBlock(Player player, BlockPos pos, Direction face, Action action) { super(player, InteractionHand.MAIN_HAND, pos, face); this.action = action; } @@ -271,16 +242,14 @@ public class PlayerInteractEvent extends PlayerEvent /** * @return If {@link Block#attack(BlockState, Level, BlockPos, Player)} should be called. Changing this has no effect in creative mode */ - public Result getUseBlock() - { + public Result getUseBlock() { return useBlock; } /** * @return If the block should be attempted to be mined with the current item. Changing this has no effect in creative mode */ - public Result getUseItem() - { + public Result getUseItem() { return useItem; } @@ -292,22 +261,18 @@ public class PlayerInteractEvent extends PlayerEvent return this.action; } - public void setUseBlock(Result triggerBlock) - { + public void setUseBlock(Result triggerBlock) { this.useBlock = triggerBlock; } - public void setUseItem(Result triggerItem) - { + public void setUseItem(Result triggerItem) { this.useItem = triggerItem; } @Override - public void setCanceled(boolean canceled) - { + public void setCanceled(boolean canceled) { super.setCanceled(canceled); - if (canceled) - { + if (canceled) { useBlock = Result.DENY; useItem = Result.DENY; } @@ -334,10 +299,10 @@ public class PlayerInteractEvent extends PlayerEvent public static Action convert(ServerboundPlayerActionPacket.Action action) { return switch (action) { - default -> START; - case START_DESTROY_BLOCK -> START; - case STOP_DESTROY_BLOCK -> STOP; - case ABORT_DESTROY_BLOCK -> ABORT; + default -> START; + case START_DESTROY_BLOCK -> START; + case STOP_DESTROY_BLOCK -> STOP; + case ABORT_DESTROY_BLOCK -> ABORT; }; } } @@ -348,10 +313,8 @@ public class PlayerInteractEvent extends PlayerEvent * The server is not aware of when the client left clicks empty space, you will need to tell the server yourself. * This event cannot be canceled. */ - public static class LeftClickEmpty extends PlayerInteractEvent - { - public LeftClickEmpty(Player player) - { + public static class LeftClickEmpty extends PlayerInteractEvent { + public LeftClickEmpty(Player player) { super(player, InteractionHand.MAIN_HAND, player.blockPosition(), null); } } @@ -360,8 +323,7 @@ public class PlayerInteractEvent extends PlayerEvent * @return The hand involved in this interaction. Will never be null. */ @NotNull - public InteractionHand getHand() - { + public InteractionHand getHand() { return hand; } @@ -369,8 +331,7 @@ public class PlayerInteractEvent extends PlayerEvent * @return The itemstack involved in this interaction, {@code ItemStack.EMPTY} if the hand was empty. */ @NotNull - public ItemStack getItemStack() - { + public ItemStack getItemStack() { return getEntity().getItemInHand(hand); } @@ -382,8 +343,7 @@ public class PlayerInteractEvent extends PlayerEvent * @return The position involved in this interaction. */ @NotNull - public BlockPos getPos() - { + public BlockPos getPos() { return pos; } @@ -391,24 +351,21 @@ public class PlayerInteractEvent extends PlayerEvent * @return The face involved in this interaction. For all non-block interactions, this will return null. */ @Nullable - public Direction getFace() - { + public Direction getFace() { return face; } /** * @return Convenience method to get the level of this interaction. */ - public Level getLevel() - { + public Level getLevel() { return getEntity().level(); } /** * @return The effective, i.e. logical, side of this interaction. This will be {@link LogicalSide#CLIENT} on the client thread, and {@link LogicalSide#SERVER} on the server thread. */ - public LogicalSide getSide() - { + public LogicalSide getSide() { return getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER; } @@ -417,8 +374,7 @@ public class PlayerInteractEvent extends PlayerEvent * method of the event. By default, this is {@link InteractionResult#PASS}, meaning cancelled events will cause * the client to keep trying more interactions until something works. */ - public InteractionResult getCancellationResult() - { + public InteractionResult getCancellationResult() { return cancellationResult; } @@ -427,9 +383,7 @@ public class PlayerInteractEvent extends PlayerEvent * method of the event. * Note that this only has an effect on {@link RightClickBlock}, {@link RightClickItem}, {@link EntityInteract}, and {@link EntityInteractSpecific}. */ - public void setCancellationResult(InteractionResult result) - { + public void setCancellationResult(InteractionResult result) { this.cancellationResult = result; } - } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerSpawnPhantomsEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerSpawnPhantomsEvent.java index b24723effa..b07b8bdc17 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerSpawnPhantomsEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerSpawnPhantomsEvent.java @@ -23,12 +23,10 @@ import org.jetbrains.annotations.NotNull; * @see PlayerSpawnPhantomsEvent#setResult for the effects of each result. */ @Event.HasResult -public class PlayerSpawnPhantomsEvent extends PlayerEvent -{ +public class PlayerSpawnPhantomsEvent extends PlayerEvent { private int phantomsToSpawn; - public PlayerSpawnPhantomsEvent(Player player, int phantomsToSpawn) - { + public PlayerSpawnPhantomsEvent(Player player, int phantomsToSpawn) { super(player); this.phantomsToSpawn = phantomsToSpawn; } @@ -36,8 +34,7 @@ public class PlayerSpawnPhantomsEvent extends PlayerEvent /** * @return How many phantoms will be spawned, if spawning is successful. The default value is randomly generated. */ - public int getPhantomsToSpawn() - { + public int getPhantomsToSpawn() { return phantomsToSpawn; } @@ -45,8 +42,7 @@ public class PlayerSpawnPhantomsEvent extends PlayerEvent * Sets the number of phantoms to be spawned. * @param phantomsToSpawn How many phantoms should spawn, given checks are passed. */ - public void setPhantomsToSpawn(int phantomsToSpawn) - { + public void setPhantomsToSpawn(int phantomsToSpawn) { this.phantomsToSpawn = phantomsToSpawn; } @@ -59,8 +55,7 @@ public class PlayerSpawnPhantomsEvent extends PlayerEvent * */ @Override - public void setResult(@NotNull Result result) - { + public void setResult(@NotNull Result result) { super.setResult(result); } } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerXpEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerXpEvent.java index 46d810a85f..329faf625c 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerXpEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerXpEvent.java @@ -17,11 +17,8 @@ import net.minecraftforge.eventbus.api.Cancelable; *
* All children of this event are fired on the {@link MinecraftForge#EVENT_BUS}. */ -public class PlayerXpEvent extends PlayerEvent -{ - - public PlayerXpEvent(Player player) - { +public class PlayerXpEvent extends PlayerEvent { + public PlayerXpEvent(Player player) { super(player); } @@ -30,22 +27,17 @@ public class PlayerXpEvent extends PlayerEvent * It can be cancelled, and no further processing will be done. */ @Cancelable - public static class PickupXp extends PlayerXpEvent - { - + public static class PickupXp extends PlayerXpEvent { private final ExperienceOrb orb; - public PickupXp(Player player, ExperienceOrb orb) - { + public PickupXp(Player player, ExperienceOrb orb) { super(player); this.orb = orb; } - public ExperienceOrb getOrb() - { + public ExperienceOrb getOrb() { return orb; } - } /** @@ -53,27 +45,21 @@ public class PlayerXpEvent extends PlayerEvent * It can be cancelled, and no further processing will be done. */ @Cancelable - public static class XpChange extends PlayerXpEvent - { - + public static class XpChange extends PlayerXpEvent { private int amount; - public XpChange(Player player, int amount) - { + public XpChange(Player player, int amount) { super(player); this.amount = amount; } - public int getAmount() - { + public int getAmount() { return this.amount; } - public void setAmount(int amount) - { + public void setAmount(int amount) { this.amount = amount; } - } /** @@ -81,27 +67,20 @@ public class PlayerXpEvent extends PlayerEvent * It can be cancelled, and no further processing will be done. */ @Cancelable - public static class LevelChange extends PlayerXpEvent - { - + public static class LevelChange extends PlayerXpEvent { private int levels; - public LevelChange(Player player, int levels) - { + public LevelChange(Player player, int levels) { super(player); this.levels = levels; } - public int getLevels() - { + public int getLevels() { return this.levels; } - public void setLevels(int levels) - { + public void setLevels(int levels) { this.levels = levels; } - } - } diff --git a/src/main/java/net/minecraftforge/event/level/BlockEvent.java b/src/main/java/net/minecraftforge/event/level/BlockEvent.java index a50e69d928..49ec66325e 100644 --- a/src/main/java/net/minecraftforge/event/level/BlockEvent.java +++ b/src/main/java/net/minecraftforge/event/level/BlockEvent.java @@ -12,7 +12,6 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.block.BaseFireBlock; import net.minecraft.world.level.portal.PortalShape; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.enchantment.Enchantments; @@ -20,7 +19,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.Level; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.ToolAction; @@ -33,32 +31,28 @@ import com.google.common.collect.ImmutableList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class BlockEvent extends Event -{ +public class BlockEvent extends Event { private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("forge.debugBlockEvent", "false")); private final LevelAccessor level; private final BlockPos pos; private final BlockState state; - public BlockEvent(LevelAccessor level, BlockPos pos, BlockState state) - { + + public BlockEvent(LevelAccessor level, BlockPos pos, BlockState state) { this.pos = pos; this.level = level; this.state = state; } - public LevelAccessor getLevel() - { + public LevelAccessor getLevel() { return level; } - public BlockPos getPos() - { + public BlockPos getPos() { return pos; } - public BlockState getState() - { + public BlockState getState() { return state; } @@ -67,31 +61,25 @@ public class BlockEvent extends Event * Canceling this event will prevent the Block from being broken. */ @Cancelable - public static class BreakEvent extends BlockEvent - { + public static class BreakEvent extends BlockEvent { /** Reference to the Player who broke the block. If no player is available, use a EntityFakePlayer */ private final Player player; private int exp; - public BreakEvent(Level level, BlockPos pos, BlockState state, Player player) - { + public BreakEvent(Level level, BlockPos pos, BlockState state, Player player) { super(level, pos, state); this.player = player; - if (state == null || !ForgeHooks.isCorrectToolForDrops(state, player)) // Handle empty block or player unable to break block scenario - { + if (state == null || !ForgeHooks.isCorrectToolForDrops(state, player)) { // Handle empty block or player unable to break block scenario this.exp = 0; - } - else - { - int fortuneLevel = player.getMainHandItem().getEnchantmentLevel(Enchantments.BLOCK_FORTUNE); + } else { + int fortuneLevel = player.getMainHandItem().getEnchantmentLevel(Enchantments.FORTUNE); int silkTouchLevel = player.getMainHandItem().getEnchantmentLevel(Enchantments.SILK_TOUCH); this.exp = state.getExpDrop(level, level.random, pos, fortuneLevel, silkTouchLevel); } } - public Player getPlayer() - { + public Player getPlayer() { return player; } @@ -100,8 +88,7 @@ public class BlockEvent extends Event * * @return The experience to drop or 0 if the event was canceled */ - public int getExpToDrop() - { + public int getExpToDrop() { return this.isCanceled() ? 0 : exp; } @@ -110,8 +97,7 @@ public class BlockEvent extends Event * * @param exp 1 or higher to drop experience, else nothing will drop */ - public void setExpToDrop(int exp) - { + public void setExpToDrop(int exp) { this.exp = exp; } } @@ -122,23 +108,20 @@ public class BlockEvent extends Event * If a Block Place event is cancelled, the block will not be placed. */ @Cancelable - public static class EntityPlaceEvent extends BlockEvent - { + public static class EntityPlaceEvent extends BlockEvent { private final Entity entity; private final BlockSnapshot blockSnapshot; private final BlockState placedBlock; private final BlockState placedAgainst; - public EntityPlaceEvent(@NotNull BlockSnapshot blockSnapshot, @NotNull BlockState placedAgainst, @Nullable Entity entity) - { + public EntityPlaceEvent(@NotNull BlockSnapshot blockSnapshot, @NotNull BlockState placedAgainst, @Nullable Entity entity) { super(blockSnapshot.getLevel(), blockSnapshot.getPos(), !(entity instanceof Player) ? blockSnapshot.getReplacedBlock() : blockSnapshot.getCurrentBlock()); this.entity = entity; this.blockSnapshot = blockSnapshot; this.placedBlock = !(entity instanceof Player) ? blockSnapshot.getReplacedBlock() : blockSnapshot.getCurrentBlock(); this.placedAgainst = placedAgainst; - if (DEBUG) - { + if (DEBUG) { System.out.printf("Created EntityPlaceEvent - [PlacedBlock: %s ][PlacedAgainst: %s ][Entity: %s ]\n", getPlacedBlock(), placedAgainst, entity); } } @@ -158,15 +141,13 @@ public class BlockEvent extends Event * block. */ @Cancelable - public static class EntityMultiPlaceEvent extends EntityPlaceEvent - { + public static class EntityMultiPlaceEvent extends EntityPlaceEvent { private final List blockSnapshots; public EntityMultiPlaceEvent(@NotNull List blockSnapshots, @NotNull BlockState placedAgainst, @Nullable Entity entity) { super(blockSnapshots.get(0), placedAgainst, entity); this.blockSnapshots = ImmutableList.copyOf(blockSnapshots); - if (DEBUG) - { + if (DEBUG) { System.out.printf("Created EntityMultiPlaceEvent - [PlacedAgainst: %s ][Entity: %s ]\n", placedAgainst, entity); } } @@ -177,8 +158,7 @@ public class BlockEvent extends Event * * @return immutable list of replaced BlockSnapshots */ - public List getReplacedBlockSnapshots() - { + public List getReplacedBlockSnapshots() { return blockSnapshots; } } @@ -189,13 +169,11 @@ public class BlockEvent extends Event * does. This event is only called on the server. */ @Cancelable - public static class NeighborNotifyEvent extends BlockEvent - { + public static class NeighborNotifyEvent extends BlockEvent { private final EnumSet notifiedSides; private final boolean forceRedstoneUpdate; - public NeighborNotifyEvent(Level level, BlockPos pos, BlockState state, EnumSet notifiedSides, boolean forceRedstoneUpdate) - { + public NeighborNotifyEvent(Level level, BlockPos pos, BlockState state, EnumSet notifiedSides, boolean forceRedstoneUpdate) { super(level, pos, state); this.notifiedSides = notifiedSides; this.forceRedstoneUpdate = forceRedstoneUpdate; @@ -206,8 +184,7 @@ public class BlockEvent extends Event * * @return list of notified directions */ - public EnumSet getNotifiedSides() - { + public EnumSet getNotifiedSides() { return notifiedSides; } @@ -215,8 +192,7 @@ public class BlockEvent extends Event * Get if redstone update was forced during setBlock call (0x16 to flags) * @return if the flag was set */ - public boolean getForceRedstoneUpdate() - { + public boolean getForceRedstoneUpdate() { return forceRedstoneUpdate; } } @@ -228,31 +204,26 @@ public class BlockEvent extends Event * even if the liquid usually does do that (like water). */ @HasResult - public static class CreateFluidSourceEvent extends Event - { + public static class CreateFluidSourceEvent extends Event { private final Level level; private final BlockPos pos; private final BlockState state; - public CreateFluidSourceEvent(Level level, BlockPos pos, BlockState state) - { + public CreateFluidSourceEvent(Level level, BlockPos pos, BlockState state) { this.level = level; this.pos = pos; this.state = state; } - public Level getLevel() - { + public Level getLevel() { return level; } - public BlockPos getPos() - { + public BlockPos getPos() { return pos; } - public BlockState getState() - { + public BlockState getState() { return state; } } @@ -266,14 +237,12 @@ public class BlockEvent extends Event * {@link #getPos()} will return the position of the block to be changed. */ @Cancelable - public static class FluidPlaceBlockEvent extends BlockEvent - { + public static class FluidPlaceBlockEvent extends BlockEvent { private final BlockPos liquidPos; private BlockState newState; private BlockState origState; - public FluidPlaceBlockEvent(LevelAccessor level, BlockPos pos, BlockPos liquidPos, BlockState state) - { + public FluidPlaceBlockEvent(LevelAccessor level, BlockPos pos, BlockPos liquidPos, BlockState state) { super(level, pos, state); this.liquidPos = liquidPos; this.newState = state; @@ -283,29 +252,25 @@ public class BlockEvent extends Event /** * @return The position of the liquid this event originated from. This may be the same as {@link #getPos()}. */ - public BlockPos getLiquidPos() - { + public BlockPos getLiquidPos() { return liquidPos; } /** * @return The block state that will be placed after this event resolves. */ - public BlockState getNewState() - { + public BlockState getNewState() { return newState; } - public void setNewState(BlockState state) - { + public void setNewState(BlockState state) { this.newState = state; } /** * @return The state of the block to be changed before the event was fired. */ - public BlockState getOriginalState() - { + public BlockState getOriginalState() { return origState; } } @@ -314,10 +279,8 @@ public class BlockEvent extends Event * Fired when a crop block grows. See subevents. * */ - public static class CropGrowEvent extends BlockEvent - { - public CropGrowEvent(Level level, BlockPos pos, BlockState state) - { + public static class CropGrowEvent extends BlockEvent { + public CropGrowEvent(Level level, BlockPos pos, BlockState state) { super(level, pos, state); } @@ -333,10 +296,8 @@ public class BlockEvent extends Event *
*/ @HasResult - public static class Pre extends CropGrowEvent - { - public Pre(Level level, BlockPos pos, BlockState state) - { + public static class Pre extends CropGrowEvent { + public Pre(Level level, BlockPos pos, BlockState state) { super(level, pos, state); } } @@ -350,17 +311,15 @@ public class BlockEvent extends Event *
* This event does not have a result. {@link HasResult}
*/ - public static class Post extends CropGrowEvent - { + public static class Post extends CropGrowEvent { private final BlockState originalState; - public Post(Level level, BlockPos pos, BlockState original, BlockState state) - { + + public Post(Level level, BlockPos pos, BlockState original, BlockState state) { super(level, pos, state); originalState = original; } - public BlockState getOriginalState() - { + public BlockState getOriginalState() { return originalState; } } @@ -371,14 +330,11 @@ public class BlockEvent extends Event * This event is {@link Cancelable} */ @Cancelable - public static class FarmlandTrampleEvent extends BlockEvent - { - + public static class FarmlandTrampleEvent extends BlockEvent { private final Entity entity; private final float fallDistance; - public FarmlandTrampleEvent(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) - { + public FarmlandTrampleEvent(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) { super(level, pos, state); this.entity = entity; this.fallDistance = fallDistance; @@ -400,18 +356,15 @@ public class BlockEvent extends Event * If cancelled, the portal will not be spawned. */ @Cancelable - public static class PortalSpawnEvent extends BlockEvent - { + public static class PortalSpawnEvent extends BlockEvent { private final PortalShape size; - public PortalSpawnEvent(LevelAccessor level, BlockPos pos, BlockState state, PortalShape size) - { + public PortalSpawnEvent(LevelAccessor level, BlockPos pos, BlockState state, PortalShape size) { super(level, pos, state); this.size = size; } - public PortalShape getPortalSize() - { + public PortalShape getPortalSize() { return size; } } @@ -427,15 +380,13 @@ public class BlockEvent extends Event * from changing the block's state. */ @Cancelable - public static class BlockToolModificationEvent extends BlockEvent - { + public static class BlockToolModificationEvent extends BlockEvent { private final UseOnContext context; private final ToolAction toolAction; private final boolean simulate; private BlockState state; - public BlockToolModificationEvent(BlockState originalState, @NotNull UseOnContext context, ToolAction toolAction, boolean simulate) - { + public BlockToolModificationEvent(BlockState originalState, @NotNull UseOnContext context, ToolAction toolAction, boolean simulate) { super(context.getLevel(), context.getClickedPos(), originalState); this.context = context; this.state = originalState; @@ -448,24 +399,21 @@ public class BlockEvent extends Event * May be null based on what was provided by {@link #getContext() the use on context}. */ @Nullable - public Player getPlayer() - { + public Player getPlayer() { return this.context.getPlayer(); } /** * @return the tool being used */ - public ItemStack getHeldItemStack() - { + public ItemStack getHeldItemStack() { return this.context.getItemInHand(); } /** * @return the action being performed */ - public ToolAction getToolAction() - { + public ToolAction getToolAction() { return this.toolAction; } @@ -476,8 +424,7 @@ public class BlockEvent extends Event * @return {@code true} if this event should not perform any actions that modify the level. * If {@code false}, then level-modifying actions can be performed. */ - public boolean isSimulated() - { + public boolean isSimulated() { return this.simulate; } @@ -487,8 +434,7 @@ public class BlockEvent extends Event * @return the nonnull use on context that this event was performed in */ @NotNull - public UseOnContext getContext() - { + public UseOnContext getContext() { return context; } @@ -498,8 +444,7 @@ public class BlockEvent extends Event * @param finalState the state to transform the block into after tool use * @see #getFinalState() */ - public void setFinalState(@Nullable BlockState finalState) - { + public void setFinalState(@Nullable BlockState finalState) { this.state = finalState; } @@ -510,8 +455,7 @@ public class BlockEvent extends Event * * @return the state to transform the block into after tool use */ - public BlockState getFinalState() - { + public BlockState getFinalState() { return state; } } diff --git a/src/main/java/net/minecraftforge/event/level/ChunkDataEvent.java b/src/main/java/net/minecraftforge/event/level/ChunkDataEvent.java index bcd5c56515..e7a725929d 100644 --- a/src/main/java/net/minecraftforge/event/level/ChunkDataEvent.java +++ b/src/main/java/net/minecraftforge/event/level/ChunkDataEvent.java @@ -10,7 +10,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.ai.village.poi.PoiManager; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkType; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.storage.ChunkSerializer; import net.minecraftforge.common.MinecraftForge; @@ -55,14 +55,14 @@ public class ChunkDataEvent extends ChunkEvent { * This event is fired on the {@link MinecraftForge#EVENT_BUS}.
**/ public static class Load extends ChunkDataEvent { - private ChunkStatus.ChunkType status; + private ChunkType status; - public Load(ChunkAccess chunk, CompoundTag data, ChunkStatus.ChunkType status) { + public Load(ChunkAccess chunk, CompoundTag data, ChunkType status) { super(chunk, data); this.status = status; } - public ChunkStatus.ChunkType getStatus() { + public ChunkType getStatus() { return this.status; } } diff --git a/src/main/java/net/minecraftforge/event/level/ChunkEvent.java b/src/main/java/net/minecraftforge/event/level/ChunkEvent.java index 94e757bfbf..60efa8284e 100644 --- a/src/main/java/net/minecraftforge/event/level/ChunkEvent.java +++ b/src/main/java/net/minecraftforge/event/level/ChunkEvent.java @@ -7,7 +7,6 @@ package net.minecraftforge.event.level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Cancelable; diff --git a/src/main/java/net/minecraftforge/event/level/NoteBlockEvent.java b/src/main/java/net/minecraftforge/event/level/NoteBlockEvent.java index f88e1f9fc5..b6c7abbba6 100644 --- a/src/main/java/net/minecraftforge/event/level/NoteBlockEvent.java +++ b/src/main/java/net/minecraftforge/event/level/NoteBlockEvent.java @@ -17,12 +17,10 @@ import com.google.common.base.Preconditions; * Base class for Noteblock Events * */ -public class NoteBlockEvent extends BlockEvent -{ +public class NoteBlockEvent extends BlockEvent { private int noteId; - protected NoteBlockEvent(Level world, BlockPos pos, BlockState state, int note) - { + protected NoteBlockEvent(Level world, BlockPos pos, BlockState state, int note) { super(world, pos, state); this.noteId = note; } @@ -31,8 +29,7 @@ public class NoteBlockEvent extends BlockEvent * Get the Note the Noteblock is tuned to * @return the Note */ - public Note getNote() - { + public Note getNote() { return Note.fromId(noteId); } @@ -40,8 +37,7 @@ public class NoteBlockEvent extends BlockEvent * Get the Octave of the note this Noteblock is tuned to * @return the Octave */ - public Octave getOctave() - { + public Octave getOctave() { return Octave.fromId(noteId); } @@ -49,8 +45,7 @@ public class NoteBlockEvent extends BlockEvent * get the vanilla note-id, which contains information about both Note and Octave. Most modders should not need this. * @return an ID for the note */ - public int getVanillaNoteId() - { + public int getVanillaNoteId() { return noteId; } @@ -60,8 +55,7 @@ public class NoteBlockEvent extends BlockEvent * @param note the Note * @param octave the Octave */ - public void setNote(Note note, Octave octave) - { + public void setNote(Note note, Octave octave) { Preconditions.checkArgument(octave != Octave.HIGH || note == Note.F_SHARP, "Octave.HIGH is only valid for Note.F_SHARP!"); this.noteId = note.ordinal() + octave.ordinal() * 12; } @@ -71,23 +65,19 @@ public class NoteBlockEvent extends BlockEvent * Canceling this event will stop the note from playing. */ @Cancelable - public static class Play extends NoteBlockEvent - { + public static class Play extends NoteBlockEvent { private NoteBlockInstrument instrument; - public Play(Level world, BlockPos pos, BlockState state, int note, NoteBlockInstrument instrument) - { + public Play(Level world, BlockPos pos, BlockState state, int note, NoteBlockInstrument instrument) { super(world, pos, state, note); this.instrument = instrument; } - public NoteBlockInstrument getInstrument() - { + public NoteBlockInstrument getInstrument() { return instrument; } - public void setInstrument(NoteBlockInstrument instrument) - { + public void setInstrument(NoteBlockInstrument instrument) { this.instrument = instrument; } } @@ -97,25 +87,21 @@ public class NoteBlockEvent extends BlockEvent * Canceling this event will not change the note and also stop the Noteblock from playing it's note. */ @Cancelable - public static class Change extends NoteBlockEvent - { + public static class Change extends NoteBlockEvent { private final Note oldNote; private final Octave oldOctave; - public Change(Level world, BlockPos pos, BlockState state, int oldNote, int newNote) - { + public Change(Level world, BlockPos pos, BlockState state, int oldNote, int newNote) { super(world, pos, state, newNote); this.oldNote = Note.fromId(oldNote); this.oldOctave = Octave.fromId(oldNote); } - public Note getOldNote() - { + public Note getOldNote() { return oldNote; } - public Octave getOldOctave() - { + public Octave getOldOctave() { return oldOctave; } } @@ -125,8 +111,7 @@ public class NoteBlockEvent extends BlockEvent * For altered notes such as G-Sharp / A-Flat the Sharp variant is used here. * */ - public static enum Note - { + public static enum Note { F_SHARP, G, G_SHARP, @@ -142,8 +127,7 @@ public class NoteBlockEvent extends BlockEvent private static final Note[] values = values(); - static Note fromId(int id) - { + static Note fromId(int id) { return values[id % 12]; } } @@ -153,16 +137,13 @@ public class NoteBlockEvent extends BlockEvent * Together with {@link Note} it fully describes the note. * */ - public static enum Octave - { + public static enum Octave { LOW, MID, HIGH; // only valid for F_SHARP - static Octave fromId(int id) - { + static Octave fromId(int id) { return id < 12 ? LOW : id == 24 ? HIGH : MID; } } - } diff --git a/src/main/java/net/minecraftforge/event/village/VillagerTradesEvent.java b/src/main/java/net/minecraftforge/event/village/VillagerTradesEvent.java index 2aeabe757f..e270eaea95 100644 --- a/src/main/java/net/minecraftforge/event/village/VillagerTradesEvent.java +++ b/src/main/java/net/minecraftforge/event/village/VillagerTradesEvent.java @@ -11,7 +11,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import net.minecraft.world.entity.npc.VillagerData; import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.entity.npc.VillagerTrades.ItemListing; -import net.minecraftforge.common.BasicItemListing; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.event.server.ServerAboutToStartEvent; diff --git a/src/main/java/net/minecraftforge/event/village/WandererTradesEvent.java b/src/main/java/net/minecraftforge/event/village/WandererTradesEvent.java index 4063a41b0d..6c7c0cdac4 100644 --- a/src/main/java/net/minecraftforge/event/village/WandererTradesEvent.java +++ b/src/main/java/net/minecraftforge/event/village/WandererTradesEvent.java @@ -8,7 +8,6 @@ package net.minecraftforge.event.village; import java.util.List; import net.minecraft.world.entity.npc.VillagerTrades.ItemListing; -import net.minecraftforge.common.BasicItemListing; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.event.server.ServerAboutToStartEvent; diff --git a/src/main/java/net/minecraftforge/fluids/FluidStack.java b/src/main/java/net/minecraftforge/fluids/FluidStack.java index 8b5eeba3a8..f609fb9ddb 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidStack.java +++ b/src/main/java/net/minecraftforge/fluids/FluidStack.java @@ -131,22 +131,6 @@ public class FluidStack return nbt; } - public void writeToPacket(FriendlyByteBuf buf) - { - buf.writeRegistryId(ForgeRegistries.FLUIDS, getFluid()); - buf.writeVarInt(getAmount()); - buf.writeNbt(tag); - } - - public static FluidStack readFromPacket(FriendlyByteBuf buf) - { - Fluid fluid = buf.readRegistryId(); - int amount = buf.readVarInt(); - CompoundTag tag = buf.readNbt(); - if (fluid == Fluids.EMPTY) return EMPTY; - return new FluidStack(fluid, amount, tag); - } - public final Fluid getFluid() { return isEmpty ? Fluids.EMPTY : fluidDelegate.get(); diff --git a/src/main/java/net/minecraftforge/fluids/FluidType.java b/src/main/java/net/minecraftforge/fluids/FluidType.java index f50bf2e6ee..6e34d76938 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidType.java +++ b/src/main/java/net/minecraftforge/fluids/FluidType.java @@ -31,14 +31,17 @@ import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.pathfinder.BlockPathTypes; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.SoundAction; import net.minecraftforge.common.SoundActions; import net.minecraftforge.common.util.Lazy; +import net.minecraftforge.fml.loading.FMLEnvironment; +import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.registries.ForgeRegistries; import org.jetbrains.annotations.Nullable; @@ -57,8 +60,7 @@ import java.util.function.Consumer; * can be implemented by overriding methods further in the call chain (on fluids, * entities, etc.). */ -public class FluidType -{ +public class FluidType { /** * The number of fluid units that a bucket represents. */ @@ -80,7 +82,7 @@ public class FluidType private final boolean canConvertToSource; private final boolean supportsBoating; @Nullable - private final BlockPathTypes pathType, adjacentPathType; + private final PathType pathType, adjacentPathType; private final boolean canHydrate; private final int lightLevel; private final int density; @@ -98,8 +100,7 @@ public class FluidType * * @param properties the general properties of the fluid type */ - public FluidType(final Properties properties) - { + public FluidType(final Properties properties) { this.descriptionId = properties.descriptionId; this.motionScale = properties.motionScale; this.canPushEntity = properties.canPushEntity; @@ -129,8 +130,7 @@ public class FluidType * * @return the component representing the name of the fluid type */ - public Component getDescription() - { + public Component getDescription() { return Component.translatable(this.getDescriptionId()); } @@ -141,8 +141,7 @@ public class FluidType * * @return the identifier representing the name of the fluid type */ - public String getDescriptionId() - { + public String getDescriptionId() { if (this.descriptionId == null) this.descriptionId = Util.makeDescriptionId("fluid_type", ForgeRegistries.FLUID_TYPES.get().getKey(this)); return this.descriptionId; @@ -159,8 +158,7 @@ public class FluidType * * @return the light level emitted by the fluid */ - public int getLightLevel() - { + public int getLightLevel() { return this.lightLevel; } @@ -173,8 +171,7 @@ public class FluidType * * @return the density of the fluid */ - public int getDensity() - { + public int getDensity() { return this.density; } @@ -187,8 +184,7 @@ public class FluidType * * @return the temperature of the fluid */ - public int getTemperature() - { + public int getTemperature() { return this.temperature; } @@ -202,8 +198,7 @@ public class FluidType * * @return the viscosity of the fluid */ - public int getViscosity() - { + public int getViscosity() { return this.viscosity; } @@ -214,8 +209,7 @@ public class FluidType * * @return the rarity of the fluid */ - public Rarity getRarity() - { + public Rarity getRarity() { return this.rarity; } @@ -227,8 +221,7 @@ public class FluidType * @return the sound to play when performing the action */ @Nullable - public SoundEvent getSound(SoundAction action) - { + public SoundEvent getSound(SoundAction action) { return this.sounds.get(action); } @@ -241,8 +234,7 @@ public class FluidType * @param entity the entity in the fluid * @return a scalar to multiply to the fluid velocity */ - public double motionScale(Entity entity) - { + public double motionScale(Entity entity) { return this.motionScale; } @@ -252,8 +244,7 @@ public class FluidType * @param entity the entity in the fluid * @return {@code true} if the entity can be pushed by the fluid, {@code false} otherwise */ - public boolean canPushEntity(Entity entity) - { + public boolean canPushEntity(Entity entity) { return this.canPushEntity; } @@ -263,8 +254,7 @@ public class FluidType * @param entity the entity in the fluid * @return {@code true} if the entity can swim in the fluid, {@code false} otherwise */ - public boolean canSwim(Entity entity) - { + public boolean canSwim(Entity entity) { return this.canSwim; } @@ -278,8 +268,7 @@ public class FluidType * @param entity the entity in the fluid * @return a scalar to multiply to the fall damage */ - public float getFallDistanceModifier(Entity entity) - { + public float getFallDistanceModifier(Entity entity) { return this.fallDistanceModifier; } @@ -289,8 +278,7 @@ public class FluidType * @param entity the entity in the fluid * @return {@code true} if the entity can be extinguished, {@code false} otherwise */ - public boolean canExtinguish(Entity entity) - { + public boolean canExtinguish(Entity entity) { return this.canExtinguish; } @@ -305,8 +293,7 @@ public class FluidType * @param gravity the gravity to apply to the entity * @return {@code true} if custom movement logic is performed, {@code false} otherwise */ - public boolean move(FluidState state, LivingEntity entity, Vec3 movementVector, double gravity) - { + public boolean move(FluidState state, LivingEntity entity, Vec3 movementVector, double gravity) { return false; } @@ -316,8 +303,7 @@ public class FluidType * @param entity the entity in the fluid * @return {@code true} if the entity can drown in the fluid, {@code false} otherwise */ - public boolean canDrownIn(LivingEntity entity) - { + public boolean canDrownIn(LivingEntity entity) { return this.canDrown; } @@ -326,8 +312,7 @@ public class FluidType * * @param entity the item in the fluid */ - public void setItemMovement(ItemEntity entity) - { + public void setItemMovement(ItemEntity entity) { Vec3 vec3 = entity.getDeltaMovement(); entity.setDeltaMovement(vec3.x * (double)0.99F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.99F); } @@ -338,8 +323,7 @@ public class FluidType * @param boat the boat trying to be used on the fluid * @return {@code true} if the boat can be used, {@code false} otherwise */ - public boolean supportsBoating(Boat boat) - { + public boolean supportsBoating(Boat boat) { return this.supportsBoating; } @@ -350,8 +334,7 @@ public class FluidType * @param boat the boat trying to be used on the fluid * @return {@code true} if the boat can be used, {@code false} otherwise */ - public boolean supportsBoating(FluidState state, Boat boat) - { + public boolean supportsBoating(FluidState state, Boat boat) { return this.supportsBoating(boat); } @@ -364,8 +347,7 @@ public class FluidType * @param rider the rider of the boat * @return {@code true} if the fluid height should be updated, {@code false} otherwise */ - public boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider) - { + public boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider) { return !this.supportsBoating(state, boat); } @@ -377,8 +359,7 @@ public class FluidType * @return {@code true} if the vehicle can be ridden in under this fluid, * {@code false} otherwise */ - public boolean canRideVehicleUnder(Entity vehicle, Entity rider) - { + public boolean canRideVehicleUnder(Entity vehicle, Entity rider) { if (this == ForgeMod.WATER_TYPE.get()) return !vehicle.dismountsUnderwater(); return true; } @@ -392,8 +373,7 @@ public class FluidType * @return {@code true} if the entity can be hydrated, {@code false} * otherwise */ - public boolean canHydrate(Entity entity) - { + public boolean canHydrate(Entity entity) { return this.canHydrate; } @@ -407,8 +387,7 @@ public class FluidType * @return the sound to play when performing the action */ @Nullable - public SoundEvent getSound(Entity entity, SoundAction action) - { + public SoundEvent getSound(Entity entity, SoundAction action) { return this.getSound(action); } @@ -422,8 +401,7 @@ public class FluidType * @param pos the position of the fluid * @return {@code true} if the block can be extinguished, {@code false} otherwise */ - public boolean canExtinguish(FluidState state, BlockGetter getter, BlockPos pos) - { + public boolean canExtinguish(FluidState state, BlockGetter getter, BlockPos pos) { return this.canExtinguish; } @@ -435,8 +413,7 @@ public class FluidType * @param pos the location of the fluid * @return {@code true} if the fluid can create a source, {@code false} otherwise */ - public boolean canConvertToSource(FluidState state, LevelReader reader, BlockPos pos) - { + public boolean canConvertToSource(FluidState state, LevelReader reader, BlockPos pos) { return this.canConvertToSource; } @@ -453,8 +430,7 @@ public class FluidType * @return the path type of this fluid */ @Nullable - public BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) - { + public PathType getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) { return this.pathType; } @@ -472,8 +448,7 @@ public class FluidType * @return the path type of this fluid */ @Nullable - public BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) - { + public PathType getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) { return this.adjacentPathType; } @@ -488,8 +463,7 @@ public class FluidType * @return the sound to play when performing the action */ @Nullable - public SoundEvent getSound(@Nullable Player player, BlockGetter getter, BlockPos pos, SoundAction action) - { + public SoundEvent getSound(@Nullable Player player, BlockGetter getter, BlockPos pos, SoundAction action) { return this.getSound(action); } @@ -510,8 +484,7 @@ public class FluidType * @param sourcePos the position of the block being hydrated * @return {@code true} if the block can be hydrated, {@code false} otherwise */ - public boolean canHydrate(FluidState state, BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos) - { + public boolean canHydrate(FluidState state, BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos) { return this.canHydrate; } @@ -526,8 +499,7 @@ public class FluidType * @param pos the position of the fluid * @return the light level emitted by the fluid */ - public int getLightLevel(FluidState state, BlockAndTintGetter getter, BlockPos pos) - { + public int getLightLevel(FluidState state, BlockAndTintGetter getter, BlockPos pos) { return this.getLightLevel(); } @@ -543,8 +515,7 @@ public class FluidType * @param pos the position of the fluid * @return the density of the fluid */ - public int getDensity(FluidState state, BlockAndTintGetter getter, BlockPos pos) - { + public int getDensity(FluidState state, BlockAndTintGetter getter, BlockPos pos) { return this.getDensity(); } @@ -560,8 +531,7 @@ public class FluidType * @param pos the position of the fluid * @return the temperature of the fluid */ - public int getTemperature(FluidState state, BlockAndTintGetter getter, BlockPos pos) - { + public int getTemperature(FluidState state, BlockAndTintGetter getter, BlockPos pos) { return this.getTemperature(); } @@ -578,8 +548,7 @@ public class FluidType * @param pos the position of the fluid * @return the viscosity of the fluid */ - public int getViscosity(FluidState state, BlockAndTintGetter getter, BlockPos pos) - { + public int getViscosity(FluidState state, BlockAndTintGetter getter, BlockPos pos) { return this.getViscosity(); } @@ -591,8 +560,7 @@ public class FluidType * @param stack the stack holding the fluid * @return {@code true} if the fluid can create a source, {@code false} otherwise */ - public boolean canConvertToSource(FluidStack stack) - { + public boolean canConvertToSource(FluidStack stack) { return this.canConvertToSource; } @@ -605,8 +573,7 @@ public class FluidType * @return the sound to play when performing the action */ @Nullable - public SoundEvent getSound(FluidStack stack, SoundAction action) - { + public SoundEvent getSound(FluidStack stack, SoundAction action) { return this.getSound(action); } @@ -616,8 +583,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the component representing the name of the fluid type */ - public Component getDescription(FluidStack stack) - { + public Component getDescription(FluidStack stack) { return Component.translatable(this.getDescriptionId(stack)); } @@ -629,8 +595,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the identifier representing the name of the fluid */ - public String getDescriptionId(FluidStack stack) - { + public String getDescriptionId(FluidStack stack) { return this.getDescriptionId(); } @@ -642,8 +607,7 @@ public class FluidType * @param stack the stack holding the fluid * @return {@code true} if the fluid can hydrate, {@code false} otherwise */ - public boolean canHydrate(FluidStack stack) - { + public boolean canHydrate(FluidStack stack) { return this.canHydrate; } @@ -656,8 +620,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the light level emitted by the fluid */ - public int getLightLevel(FluidStack stack) - { + public int getLightLevel(FluidStack stack) { return this.getLightLevel(); } @@ -671,8 +634,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the density of the fluid */ - public int getDensity(FluidStack stack) - { + public int getDensity(FluidStack stack) { return this.getDensity(); } @@ -686,8 +648,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the temperature of the fluid */ - public int getTemperature(FluidStack stack) - { + public int getTemperature(FluidStack stack) { return this.getTemperature(); } @@ -702,8 +663,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the viscosity of the fluid */ - public int getViscosity(FluidStack stack) - { + public int getViscosity(FluidStack stack) { return this.getViscosity(); } @@ -715,8 +675,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the rarity of the fluid */ - public Rarity getRarity(FluidStack stack) - { + public Rarity getRarity(FluidStack stack) { return this.getRarity(); } @@ -727,8 +686,7 @@ public class FluidType * * @return {@code true} if the type represents air, {@code false} otherwise */ - public final boolean isAir() - { + public final boolean isAir() { return this == ForgeMod.EMPTY_TYPE.get(); } @@ -737,8 +695,7 @@ public class FluidType * * @return {@code true} if the type is from vanilla, {@code false} otherwise */ - public final boolean isVanilla() - { + public final boolean isVanilla() { return this == ForgeMod.LAVA_TYPE.get() || this == ForgeMod.WATER_TYPE.get(); } @@ -748,8 +705,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the bucket containing the fluid */ - public ItemStack getBucket(FluidStack stack) - { + public ItemStack getBucket(FluidStack stack) { return new ItemStack(stack.getFluid().getBucket()); } @@ -761,8 +717,7 @@ public class FluidType * @param state the state of the fluid * @return the {@link BlockState} of a fluid */ - public BlockState getBlockForFluidState(BlockAndTintGetter getter, BlockPos pos, FluidState state) - { + public BlockState getBlockForFluidState(BlockAndTintGetter getter, BlockPos pos, FluidState state) { return state.createLegacyBlock(); } @@ -775,8 +730,7 @@ public class FluidType * @param stack the stack holding the fluid * @return the {@link FluidState} being placed */ - public FluidState getStateForPlacement(BlockAndTintGetter getter, BlockPos pos, FluidStack stack) - { + public FluidState getStateForPlacement(BlockAndTintGetter getter, BlockPos pos, FluidStack stack) { return stack.getFluid().defaultFluidState(); } @@ -788,8 +742,7 @@ public class FluidType * @param state the state of the fluid being placed * @return {@code true} if the fluid can be placed, {@code false} otherwise */ - public final boolean canBePlacedInLevel(BlockAndTintGetter getter, BlockPos pos, FluidState state) - { + public final boolean canBePlacedInLevel(BlockAndTintGetter getter, BlockPos pos, FluidState state) { return !this.getBlockForFluidState(getter, pos, state).isAir(); } @@ -801,8 +754,7 @@ public class FluidType * @param stack the stack holding the fluid * @return {@code true} if the fluid can be placed, {@code false} otherwise */ - public final boolean canBePlacedInLevel(BlockAndTintGetter getter, BlockPos pos, FluidStack stack) - { + public final boolean canBePlacedInLevel(BlockAndTintGetter getter, BlockPos pos, FluidStack stack) { return this.canBePlacedInLevel(getter, pos, this.getStateForPlacement(getter, pos, stack)); } @@ -817,8 +769,7 @@ public class FluidType * * @return {@code true} if the fluid is lighter than air, {@code false} otherwise */ - public final boolean isLighterThanAir() - { + public final boolean isLighterThanAir() { return this.getDensity() <= 0; } @@ -835,10 +786,8 @@ public class FluidType * * @see BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult) */ - public boolean isVaporizedOnPlacement(Level level, BlockPos pos, FluidStack stack) - { - if (level.dimensionType().ultraWarm()) - { + public boolean isVaporizedOnPlacement(Level level, BlockPos pos, FluidStack stack) { + if (level.dimensionType().ultraWarm()) { return this == ForgeMod.WATER_TYPE.get() || this.getStateForPlacement(level, pos, stack).is(FluidTags.WATER); } return false; @@ -856,8 +805,7 @@ public class FluidType * * @see BucketItem#emptyContents(Player, Level, BlockPos, BlockHitResult) */ - public void onVaporize(@Nullable Player player, Level level, BlockPos pos, FluidStack stack) - { + public void onVaporize(@Nullable Player player, Level level, BlockPos pos, FluidStack stack) { SoundEvent sound = this.getSound(player, level, pos, SoundActions.FLUID_VAPORIZE); level.playSound(player, pos, sound != null ? sound : SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS, 0.5F, 2.6F + (level.random.nextFloat() - level.random.nextFloat()) * 0.8F); @@ -877,18 +825,14 @@ public class FluidType DO NOT CALL, IT WILL DISAPPEAR IN THE FUTURE Call RenderProperties.get instead */ - public Object getRenderPropertiesInternal() - { + public Object getRenderPropertiesInternal() { return renderProperties; } - private void initClient() - { + private void initClient() { // Minecraft instance isn't available in datagen, so don't call initializeClient if in datagen - if (net.minecraftforge.fml.loading.FMLEnvironment.dist == net.minecraftforge.api.distmarker.Dist.CLIENT && !net.minecraftforge.fml.loading.FMLLoader.getLaunchHandler().isData()) - { - initializeClient(properties -> - { + if (FMLEnvironment.dist == Dist.CLIENT && !FMLLoader.getLaunchHandler().isData()) { + initializeClient(properties -> { if (properties == this) throw new IllegalStateException("Don't extend IFluidTypeRenderProperties in your fluid type, use an anonymous class instead."); this.renderProperties = properties; @@ -896,16 +840,13 @@ public class FluidType } } - public void initializeClient(Consumer consumer) - { - } + public void initializeClient(Consumer consumer) { } /** * The properties of the fluid. The simple forms of each property can * be specified while more complex logic can be overridden in the {@link FluidType}. */ - public static final class Properties - { + public static final class Properties { private String descriptionId; private double motionScale = 0.014D; private boolean canPushEntity = true; @@ -916,8 +857,8 @@ public class FluidType private boolean canConvertToSource = false; private boolean supportsBoating = false; @Nullable - private BlockPathTypes pathType = BlockPathTypes.WATER, - adjacentPathType = BlockPathTypes.WATER_BORDER; + private PathType pathType = PathType.WATER, + adjacentPathType = PathType.WATER_BORDER; private final Map sounds = new HashMap<>(); private boolean canHydrate = false; private int lightLevel = 0, @@ -933,8 +874,7 @@ public class FluidType * * @return the property holder instance */ - public static Properties create() - { + public static Properties create() { return new Properties(); } @@ -944,8 +884,7 @@ public class FluidType * @param descriptionId the identifier representing the name of the fluid type * @return the property holder instance */ - public Properties descriptionId(String descriptionId) - { + public Properties descriptionId(String descriptionId) { this.descriptionId = descriptionId; return this; } @@ -956,8 +895,7 @@ public class FluidType * @param motionScale a scalar to multiply to the fluid velocity * @return the property holder instance */ - public Properties motionScale(double motionScale) - { + public Properties motionScale(double motionScale) { this.motionScale = motionScale; return this; } @@ -968,8 +906,7 @@ public class FluidType * @param canPushEntity if the fluid can push an entity * @return the property holder instance */ - public Properties canPushEntity(boolean canPushEntity) - { + public Properties canPushEntity(boolean canPushEntity) { this.canPushEntity = canPushEntity; return this; } @@ -980,8 +917,7 @@ public class FluidType * @param canSwim if the fluid can be swum in * @return the property holder instance */ - public Properties canSwim(boolean canSwim) - { + public Properties canSwim(boolean canSwim) { this.canSwim = canSwim; return this; } @@ -992,8 +928,7 @@ public class FluidType * @param canDrown if the fluid can drown something * @return the property holder instance */ - public Properties canDrown(boolean canDrown) - { + public Properties canDrown(boolean canDrown) { this.canDrown = canDrown; return this; } @@ -1005,8 +940,7 @@ public class FluidType * @param fallDistanceModifier a scalar to multiply to the fall damage * @return the property holder instance */ - public Properties fallDistanceModifier(float fallDistanceModifier) - { + public Properties fallDistanceModifier(float fallDistanceModifier) { this.fallDistanceModifier = fallDistanceModifier; return this; } @@ -1017,8 +951,7 @@ public class FluidType * @param canExtinguish if the fluid can extinguish * @return the property holder instance */ - public Properties canExtinguish(boolean canExtinguish) - { + public Properties canExtinguish(boolean canExtinguish) { this.canExtinguish = canExtinguish; return this; } @@ -1029,8 +962,7 @@ public class FluidType * @param canConvertToSource if the fluid can create a source * @return the property holder instance */ - public Properties canConvertToSource(boolean canConvertToSource) - { + public Properties canConvertToSource(boolean canConvertToSource) { this.canConvertToSource = canConvertToSource; return this; } @@ -1041,8 +973,7 @@ public class FluidType * @param supportsBoating if the fluid supports boating * @return the property holder instance */ - public Properties supportsBoating(boolean supportsBoating) - { + public Properties supportsBoating(boolean supportsBoating) { this.supportsBoating = supportsBoating; return this; } @@ -1053,8 +984,7 @@ public class FluidType * @param pathType the path type of this fluid * @return the property holder instance */ - public Properties pathType(@Nullable BlockPathTypes pathType) - { + public Properties pathType(@Nullable PathType pathType) { this.pathType = pathType; return this; } @@ -1067,8 +997,7 @@ public class FluidType * @param adjacentPathType the path type of this fluid * @return the property holder instance */ - public Properties adjacentPathType(@Nullable BlockPathTypes adjacentPathType) - { + public Properties adjacentPathType(@Nullable PathType adjacentPathType) { this.adjacentPathType = adjacentPathType; return this; } @@ -1080,8 +1009,7 @@ public class FluidType * @param sound the sound to play when performing the action * @return the property holder instance */ - public Properties sound(SoundAction action, SoundEvent sound) - { + public Properties sound(SoundAction action, SoundEvent sound) { this.sounds.put(action, sound); return this; } @@ -1094,8 +1022,7 @@ public class FluidType * @param canHydrate if the fluid can hydrate * @return the property holder instance */ - public Properties canHydrate(boolean canHydrate) - { + public Properties canHydrate(boolean canHydrate) { this.canHydrate = canHydrate; return this; } @@ -1107,8 +1034,7 @@ public class FluidType * @return the property holder instance * @throws IllegalArgumentException if light level is not between [0,15] */ - public Properties lightLevel(int lightLevel) - { + public Properties lightLevel(int lightLevel) { if (lightLevel < 0 || lightLevel > 15) throw new IllegalArgumentException("The light level should be between [0,15]."); this.lightLevel = lightLevel; @@ -1121,8 +1047,7 @@ public class FluidType * @param density the density of the fluid * @return the property holder instance */ - public Properties density(int density) - { + public Properties density(int density) { this.density = density; return this; } @@ -1133,8 +1058,7 @@ public class FluidType * @param temperature the temperature of the fluid * @return the property holder instance */ - public Properties temperature(int temperature) - { + public Properties temperature(int temperature) { this.temperature = temperature; return this; } @@ -1146,8 +1070,7 @@ public class FluidType * @return the property holder instance * @throws IllegalArgumentException if viscosity is negative */ - public Properties viscosity(int viscosity) - { + public Properties viscosity(int viscosity) { if (viscosity < 0) throw new IllegalArgumentException("The viscosity should never be negative."); this.viscosity = viscosity; @@ -1160,8 +1083,7 @@ public class FluidType * @param rarity the rarity of the fluid * @return the property holder instance */ - public Properties rarity(Rarity rarity) - { + public Properties rarity(Rarity rarity) { this.rarity = rarity; return this; } diff --git a/src/main/java/net/minecraftforge/fluids/FluidUtil.java b/src/main/java/net/minecraftforge/fluids/FluidUtil.java index 6ec56e7901..eaed4a94cd 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidUtil.java +++ b/src/main/java/net/minecraftforge/fluids/FluidUtil.java @@ -430,7 +430,8 @@ public class FluidUtil */ public static LazyOptional getFluidHandler(@NotNull ItemStack itemStack) { - return itemStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM); + return LazyOptional.empty(); // TEMP FIX - MangoRage + // return itemStack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM); } /** diff --git a/src/main/java/net/minecraftforge/fluids/capability/FluidHandlerBlockEntity.java b/src/main/java/net/minecraftforge/fluids/capability/FluidHandlerBlockEntity.java index 9f8b964fc2..5a1b13daca 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/FluidHandlerBlockEntity.java +++ b/src/main/java/net/minecraftforge/fluids/capability/FluidHandlerBlockEntity.java @@ -6,6 +6,7 @@ package net.minecraftforge.fluids.capability; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; @@ -30,17 +31,17 @@ public class FluidHandlerBlockEntity extends BlockEntity super(blockEntityType, pos, state); } + @Override - public void load(CompoundTag tag) - { - super.load(tag); + protected void loadAdditional(CompoundTag tag, HolderLookup.Provider provider) { + super.loadAdditional(tag, provider); tank.readFromNBT(tag); } @Override - protected void saveAdditional(CompoundTag tag) + protected void saveAdditional(CompoundTag tag, HolderLookup.Provider provider) { - super.saveAdditional(tag); + super.saveAdditional(tag, provider); tank.writeToNBT(tag); } diff --git a/src/main/java/net/minecraftforge/fluids/capability/ItemFluidContainer.java b/src/main/java/net/minecraftforge/fluids/capability/ItemFluidContainer.java index 4e175ffcaa..a6fc1bf871 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/ItemFluidContainer.java +++ b/src/main/java/net/minecraftforge/fluids/capability/ItemFluidContainer.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge: TODO: Forge ItemStack capabilities - Lex 042724 package net.minecraftforge.fluids.capability; import net.minecraft.world.item.Item; @@ -17,14 +18,14 @@ import org.jetbrains.annotations.Nullable; * A simple fluid container, to replace the functionality of the old FluidContainerRegistry and IFluidContainerItem. * This fluid container may be set so that is can only completely filled or empty. (binary) * It may also be set so that it gets consumed when it is drained. (consumable) - */ + * / public class ItemFluidContainer extends Item { protected final int capacity; /** * @param capacity The maximum capacity of this fluid container. - */ + * / public ItemFluidContainer(Item.Properties properties, int capacity) { super(properties); @@ -37,3 +38,4 @@ public class ItemFluidContainer extends Item return new FluidHandlerItemStack(stack, capacity); } } +*/ diff --git a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStack.java b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStack.java index 431bf3461d..f56d17b39a 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStack.java +++ b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStack.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge: TODO: Forge ItemStack capabilities - Lex 042724 package net.minecraftforge.fluids.capability.templates; import net.minecraft.world.item.ItemStack; @@ -26,7 +27,7 @@ import org.jetbrains.annotations.Nullable; * * Additional examples are provided to enable consumable fluid containers (see {@link Consumable}), * fluid containers with different empty and full items (see {@link SwapEmpty}, - */ + * / public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProvider { public static final String FLUID_NBT_KEY = "Fluid"; @@ -40,7 +41,7 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv /** * @param container The container itemStack, data is stored on it directly as NBT. * @param capacity The maximum capacity of this fluid tank. - */ + * / public FluidHandlerItemStack(@NotNull ItemStack container, int capacity) { this.container = container; @@ -202,7 +203,7 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv /** * Override this method for special handling. * Can be used to swap out or destroy the container. - */ + * / protected void setContainerToEmpty() { container.removeTagKey(FLUID_NBT_KEY); @@ -217,7 +218,7 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv /** * Destroys the container item when it's emptied. - */ + * / public static class Consumable extends FluidHandlerItemStack { public Consumable(ItemStack container, int capacity) @@ -235,7 +236,7 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv /** * Swaps the container item for a different one when it's emptied. - */ + * / public static class SwapEmpty extends FluidHandlerItemStack { protected final ItemStack emptyContainer; @@ -254,3 +255,4 @@ public class FluidHandlerItemStack implements IFluidHandlerItem, ICapabilityProv } } } +*/ diff --git a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStackSimple.java b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStackSimple.java index 4b6b6dc857..eb5390a6a0 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStackSimple.java +++ b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidHandlerItemStackSimple.java @@ -3,6 +3,7 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/** Forge: TODO: Forge ItemStack capabilities - Lex 042724 package net.minecraftforge.fluids.capability.templates; import net.minecraft.world.item.ItemStack; @@ -23,7 +24,7 @@ import org.jetbrains.annotations.Nullable; * Data is stored directly in the vanilla NBT, in the same way as the old ItemFluidContainer. * * This implementation only allows item containers to be fully filled or emptied, similar to vanilla buckets. - */ + * / public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabilityProvider { public static final String FLUID_NBT_KEY = "Fluid"; @@ -37,7 +38,7 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili /** * @param container The container itemStack, data is stored on it directly as NBT. * @param capacity The maximum capacity of this fluid tank. - */ + * / public FluidHandlerItemStackSimple(@NotNull ItemStack container, int capacity) { this.container = container; @@ -179,7 +180,7 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili * Override this method for special handling. * Can be used to swap out the container's item for a different one with "container.setItem". * Can be used to destroy the container with "container.stackSize--" - */ + * / protected void setContainerToEmpty() { container.removeTagKey(FLUID_NBT_KEY); @@ -194,7 +195,7 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili /** * Destroys the container item when it's emptied. - */ + * / public static class Consumable extends FluidHandlerItemStackSimple { public Consumable(ItemStack container, int capacity) @@ -212,7 +213,7 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili /** * Swaps the container item for a different one when it's emptied. - */ + * / public static class SwapEmpty extends FluidHandlerItemStackSimple { protected final ItemStack emptyContainer; @@ -231,3 +232,4 @@ public class FluidHandlerItemStackSimple implements IFluidHandlerItem, ICapabili } } } +*/ \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java b/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java index 1b02647e27..84c35327d8 100644 --- a/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java +++ b/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java @@ -173,13 +173,13 @@ public class ForgeGameTestHooks { } public static void addTest(Collection functions, Set classes, Set filters, TestFunction func) { - boolean allowed = filters.isEmpty() || filters.stream().anyMatch(f -> f.equals(func.getBatchName()) || func.getBatchName().startsWith(f + '.')); + boolean allowed = filters.isEmpty() || filters.stream().anyMatch(f -> f.equals(func.batchName()) || func.batchName().startsWith(f + '.')); if (!allowed) return; functions.add(func); - var batch = func.getBatchName(); + var batch = func.batchName(); classes.add(batch); int idx = batch.indexOf('.'); diff --git a/src/main/java/net/minecraftforge/internal/TextComponentMessageFormatHandler.java b/src/main/java/net/minecraftforge/internal/TextComponentMessageFormatHandler.java index b94d732582..b7266da0db 100644 --- a/src/main/java/net/minecraftforge/internal/TextComponentMessageFormatHandler.java +++ b/src/main/java/net/minecraftforge/internal/TextComponentMessageFormatHandler.java @@ -13,7 +13,7 @@ import net.minecraftforge.common.ForgeI18n; import java.util.function.Consumer; -public class TextComponentMessageFormatHandler { +public final class TextComponentMessageFormatHandler { public static int handle(final TranslatableContents parent, final Consumer addChild, final Object[] formatArgs, final String format) { try { final String formattedString = ForgeI18n.parseFormat(format, formatArgs); diff --git a/src/main/java/net/minecraftforge/items/ItemHandlerHelper.java b/src/main/java/net/minecraftforge/items/ItemHandlerHelper.java index 3ae1961783..c689e8b79a 100644 --- a/src/main/java/net/minecraftforge/items/ItemHandlerHelper.java +++ b/src/main/java/net/minecraftforge/items/ItemHandlerHelper.java @@ -16,19 +16,15 @@ import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class ItemHandlerHelper -{ +public class ItemHandlerHelper { @NotNull - public static ItemStack insertItem(IItemHandler dest, @NotNull ItemStack stack, boolean simulate) - { + public static ItemStack insertItem(IItemHandler dest, @NotNull ItemStack stack, boolean simulate) { if (dest == null || stack.isEmpty()) return stack; - for (int i = 0; i < dest.getSlots(); i++) - { + for (int i = 0; i < dest.getSlots(); i++) { stack = dest.insertItem(i, stack, simulate); - if (stack.isEmpty()) - { + if (stack.isEmpty()) { return ItemStack.EMPTY; } } @@ -36,42 +32,12 @@ public class ItemHandlerHelper return stack; } - public static boolean canItemStacksStack(@NotNull ItemStack a, @NotNull ItemStack b) - { - if (a.isEmpty() || !ItemStack.isSameItem(a, b) || a.hasTag() != b.hasTag()) - return false; - - return (!a.hasTag() || a.getTag().equals(b.getTag())) && a.areCapsCompatible(b); - } - - /** - * A relaxed version of canItemStacksStack that stacks itemstacks with different metadata if they don't have subtypes. - * This usually only applies when players pick up items. - */ - public static boolean canItemStacksStackRelaxed(@NotNull ItemStack a, @NotNull ItemStack b) - { - if (a.isEmpty() || b.isEmpty() || a.getItem() != b.getItem()) - return false; - - if (!a.isStackable()) - return false; - - // Metadata value only matters when the item has subtypes - // Vanilla stacks non-subtype items with different metadata together - // TODO Item subtypes, is this still necessary? - /* e.g. a stick with metadata 0 and a stick with metadata 1 stack - if (a.getHasSubtypes() && a.getMetadata() != b.getMetadata()) - return false; -*/ - if (a.hasTag() != b.hasTag()) - return false; - - return (!a.hasTag() || a.getTag().equals(b.getTag())) && a.areCapsCompatible(b); + public static boolean canItemStacksStack(@NotNull ItemStack a, @NotNull ItemStack b) { + return ItemStack.isSameItemSameComponents(a, b); } @NotNull - public static ItemStack copyStackWithSize(@NotNull ItemStack itemStack, int size) - { + public static ItemStack copyStackWithSize(@NotNull ItemStack itemStack, int size) { if (size == 0) return ItemStack.EMPTY; ItemStack copy = itemStack.copy(); @@ -85,45 +51,36 @@ public class ItemHandlerHelper * Note: This function stacks items without subtypes with different metadata together. */ @NotNull - public static ItemStack insertItemStacked(IItemHandler inventory, @NotNull ItemStack stack, boolean simulate) - { + public static ItemStack insertItemStacked(IItemHandler inventory, @NotNull ItemStack stack, boolean simulate) { if (inventory == null || stack.isEmpty()) return stack; // not stackable -> just insert into a new slot - if (!stack.isStackable()) - { + if (!stack.isStackable()) { return insertItem(inventory, stack, simulate); } int sizeInventory = inventory.getSlots(); // go through the inventory and try to fill up already existing items - for (int i = 0; i < sizeInventory; i++) - { + for (int i = 0; i < sizeInventory; i++) { ItemStack slot = inventory.getStackInSlot(i); - if (canItemStacksStackRelaxed(slot, stack)) - { + if (canItemStacksStack(slot, stack)) { stack = inventory.insertItem(i, stack, simulate); - if (stack.isEmpty()) - { + if (stack.isEmpty()) { break; } } } // insert remainder into empty slots - if (!stack.isEmpty()) - { + if (!stack.isEmpty()) { // find empty slot - for (int i = 0; i < sizeInventory; i++) - { - if (inventory.getStackInSlot(i).isEmpty()) - { + for (int i = 0; i < sizeInventory; i++) { + if (inventory.getStackInSlot(i).isEmpty()) { stack = inventory.insertItem(i, stack, simulate); - if (stack.isEmpty()) - { + if (stack.isEmpty()) { break; } } @@ -145,8 +102,7 @@ public class ItemHandlerHelper * @param player The player to give the item to * @param stack The itemstack to insert */ - public static void giveItemToPlayer(Player player, @NotNull ItemStack stack, int preferredSlot) - { + public static void giveItemToPlayer(Player player, @NotNull ItemStack stack, int preferredSlot) { if (stack.isEmpty()) return; IItemHandler inventory = new PlayerMainInvWrapper(player.getInventory()); @@ -155,26 +111,23 @@ public class ItemHandlerHelper // try adding it into the inventory ItemStack remainder = stack; // insert into preferred slot first - if (preferredSlot >= 0 && preferredSlot < inventory.getSlots()) - { + if (preferredSlot >= 0 && preferredSlot < inventory.getSlots()) { remainder = inventory.insertItem(preferredSlot, stack, false); } + // then into the inventory in general - if (!remainder.isEmpty()) - { + if (!remainder.isEmpty()) { remainder = insertItemStacked(inventory, remainder, false); } // play sound if something got picked up - if (remainder.isEmpty() || remainder.getCount() != stack.getCount()) - { + if (remainder.isEmpty() || remainder.getCount() != stack.getCount()) { level.playSound(null, player.getX(), player.getY() + 0.5, player.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, ((level.random.nextFloat() - level.random.nextFloat()) * 0.7F + 1.0F) * 2.0F); } // drop remaining itemstack into the level - if (!remainder.isEmpty() && !level.isClientSide) - { + if (!remainder.isEmpty() && !level.isClientSide) { ItemEntity entityitem = new ItemEntity(level, player.getX(), player.getY() + 0.5, player.getZ(), remainder); entityitem.setPickUpDelay(40); entityitem.setDeltaMovement(entityitem.getDeltaMovement().multiply(0, 1, 0)); @@ -189,23 +142,17 @@ public class ItemHandlerHelper * @param inv The inventory handler to test. * @return A redstone value in the range [0,15] representing how "full" this inventory is. */ - public static int calcRedstoneFromInventory(@Nullable IItemHandler inv) - { - if (inv == null) - { + public static int calcRedstoneFromInventory(@Nullable IItemHandler inv) { + if (inv == null) { return 0; - } - else - { + } else { int itemsFound = 0; float proportion = 0.0F; - for (int j = 0; j < inv.getSlots(); ++j) - { + for (int j = 0; j < inv.getSlots(); ++j) { ItemStack itemstack = inv.getStackInSlot(j); - if (!itemstack.isEmpty()) - { + if (!itemstack.isEmpty()) { proportion += (float)itemstack.getCount() / (float)Math.min(inv.getSlotLimit(j), itemstack.getMaxStackSize()); ++itemsFound; } diff --git a/src/main/java/net/minecraftforge/items/ItemStackHandler.java b/src/main/java/net/minecraftforge/items/ItemStackHandler.java index ff9f1f1fec..9593960d55 100644 --- a/src/main/java/net/minecraftforge/items/ItemStackHandler.java +++ b/src/main/java/net/minecraftforge/items/ItemStackHandler.java @@ -5,64 +5,55 @@ package net.minecraftforge.items; -import net.minecraft.nbt.Tag; +import net.minecraft.world.ContainerHelper; import net.minecraft.world.item.ItemStack; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraftforge.common.util.INBTSerializable; import org.jetbrains.annotations.NotNull; -public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, INBTSerializable -{ +public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, INBTSerializable { protected NonNullList stacks; - public ItemStackHandler() - { + public ItemStackHandler() { this(1); } - public ItemStackHandler(int size) - { + public ItemStackHandler(int size) { stacks = NonNullList.withSize(size, ItemStack.EMPTY); } - public ItemStackHandler(NonNullList stacks) - { + public ItemStackHandler(NonNullList stacks) { this.stacks = stacks; } - public void setSize(int size) - { + public void setSize(int size) { stacks = NonNullList.withSize(size, ItemStack.EMPTY); } @Override - public void setStackInSlot(int slot, @NotNull ItemStack stack) - { + public void setStackInSlot(int slot, @NotNull ItemStack stack) { validateSlotIndex(slot); this.stacks.set(slot, stack); onContentsChanged(slot); } @Override - public int getSlots() - { + public int getSlots() { return stacks.size(); } @Override @NotNull - public ItemStack getStackInSlot(int slot) - { + public ItemStack getStackInSlot(int slot) { validateSlotIndex(slot); return this.stacks.get(slot); } @Override @NotNull - public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) - { + public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { if (stack.isEmpty()) return ItemStack.EMPTY; @@ -75,8 +66,7 @@ public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, I int limit = getStackLimit(slot, stack); - if (!existing.isEmpty()) - { + if (!existing.isEmpty()) { if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) return stack; @@ -88,14 +78,10 @@ public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, I boolean reachedLimit = stack.getCount() > limit; - if (!simulate) - { - if (existing.isEmpty()) - { + if (!simulate) { + if (existing.isEmpty()) { this.stacks.set(slot, reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack); - } - else - { + } else { existing.grow(reachedLimit ? limit : stack.getCount()); } onContentsChanged(slot); @@ -106,8 +92,7 @@ public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, I @Override @NotNull - public ItemStack extractItem(int slot, int amount, boolean simulate) - { + public ItemStack extractItem(int slot, int amount, boolean simulate) { if (amount == 0) return ItemStack.EMPTY; @@ -120,23 +105,16 @@ public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, I int toExtract = Math.min(amount, existing.getMaxStackSize()); - if (existing.getCount() <= toExtract) - { - if (!simulate) - { + if (existing.getCount() <= toExtract) { + if (!simulate) { this.stacks.set(slot, ItemStack.EMPTY); onContentsChanged(slot); return existing; - } - else - { + } else { return existing.copy(); } - } - else - { - if (!simulate) - { + } else { + if (!simulate) { this.stacks.set(slot, ItemHandlerHelper.copyStackWithSize(existing, existing.getCount() - toExtract)); onContentsChanged(slot); } @@ -146,73 +124,40 @@ public class ItemStackHandler implements IItemHandler, IItemHandlerModifiable, I } @Override - public int getSlotLimit(int slot) - { + public int getSlotLimit(int slot) { return 64; } - protected int getStackLimit(int slot, @NotNull ItemStack stack) - { + protected int getStackLimit(int slot, @NotNull ItemStack stack) { return Math.min(getSlotLimit(slot), stack.getMaxStackSize()); } @Override - public boolean isItemValid(int slot, @NotNull ItemStack stack) - { + public boolean isItemValid(int slot, @NotNull ItemStack stack) { return true; } @Override - public CompoundTag serializeNBT() - { - ListTag nbtTagList = new ListTag(); - for (int i = 0; i < stacks.size(); i++) - { - if (!stacks.get(i).isEmpty()) - { - CompoundTag itemTag = new CompoundTag(); - itemTag.putInt("Slot", i); - stacks.get(i).save(itemTag); - nbtTagList.add(itemTag); - } - } - CompoundTag nbt = new CompoundTag(); - nbt.put("Items", nbtTagList); - nbt.putInt("Size", stacks.size()); - return nbt; + public CompoundTag serializeNBT(HolderLookup.Provider lookup) { + var tag = new CompoundTag(); + ContainerHelper.saveAllItems(tag, this.stacks, lookup); + return tag; } @Override - public void deserializeNBT(CompoundTag nbt) - { - setSize(nbt.contains("Size", Tag.TAG_INT) ? nbt.getInt("Size") : stacks.size()); - ListTag tagList = nbt.getList("Items", Tag.TAG_COMPOUND); - for (int i = 0; i < tagList.size(); i++) - { - CompoundTag itemTags = tagList.getCompound(i); - int slot = itemTags.getInt("Slot"); - - if (slot >= 0 && slot < stacks.size()) - { - stacks.set(slot, ItemStack.of(itemTags)); - } - } + public void deserializeNBT(HolderLookup.Provider lookup, CompoundTag nbt) { + ContainerHelper.loadAllItems(nbt, stacks, lookup); onLoad(); } - protected void validateSlotIndex(int slot) - { + protected void validateSlotIndex(int slot) { if (slot < 0 || slot >= stacks.size()) throw new RuntimeException("Slot " + slot + " not in valid range - [0," + stacks.size() + ")"); } - protected void onLoad() - { - + protected void onLoad() { } - protected void onContentsChanged(int slot) - { - + protected void onContentsChanged(int slot) { } } diff --git a/src/main/java/net/minecraftforge/items/wrapper/ShulkerItemStackInvWrapper.java b/src/main/java/net/minecraftforge/items/wrapper/ShulkerItemStackInvWrapper.java index deec48690e..87ad4badee 100644 --- a/src/main/java/net/minecraftforge/items/wrapper/ShulkerItemStackInvWrapper.java +++ b/src/main/java/net/minecraftforge/items/wrapper/ShulkerItemStackInvWrapper.java @@ -3,10 +3,12 @@ * SPDX-License-Identifier: LGPL-2.1-only */ +/* package net.minecraftforge.items.wrapper; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.ContainerHelper; @@ -14,6 +16,7 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; @@ -30,12 +33,10 @@ import java.util.Objects; import java.util.Set; @ApiStatus.Internal -public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapabilityProvider -{ +public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapabilityProvider { @ApiStatus.Internal @Nullable - public static ICapabilityProvider createDefaultProvider(ItemStack itemStack) - { + public static ICapabilityProvider createDefaultProvider(ItemStack itemStack) { var item = itemStack.getItem(); if (item == Items.SHULKER_BOX || item == Items.BLACK_SHULKER_BOX || @@ -62,32 +63,28 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa private final ItemStack stack; private final LazyOptional holder = LazyOptional.of(() -> this); - private CompoundTag cachedTag; + private CustomData cachedData; private NonNullList itemStacksCache; - private ShulkerItemStackInvWrapper(ItemStack stack) - { + private ShulkerItemStackInvWrapper(ItemStack stack) { this.stack = stack; } @Override - public int getSlots() - { + public int getSlots() { return 27; } @Override @NotNull - public ItemStack getStackInSlot(int slot) - { + public ItemStack getStackInSlot(int slot) { validateSlotIndex(slot); return getItemList().get(slot); } @Override @NotNull - public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) - { + public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { if (stack.isEmpty()) return ItemStack.EMPTY; @@ -102,8 +99,7 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa int limit = Math.min(getSlotLimit(slot), stack.getMaxStackSize()); - if (!existing.isEmpty()) - { + if (!existing.isEmpty()) { if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) return stack; @@ -115,14 +111,10 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa boolean reachedLimit = stack.getCount() > limit; - if (!simulate) - { - if (existing.isEmpty()) - { + if (!simulate) { + if (existing.isEmpty()) { itemStacks.set(slot, reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack); - } - else - { + } else { existing.grow(reachedLimit ? limit : stack.getCount()); } setItemList(itemStacks); @@ -133,8 +125,7 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa @Override @NotNull - public ItemStack extractItem(int slot, int amount, boolean simulate) - { + public ItemStack extractItem(int slot, int amount, boolean simulate) { NonNullList itemStacks = getItemList(); if (amount == 0) return ItemStack.EMPTY; @@ -148,23 +139,16 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa int toExtract = Math.min(amount, existing.getMaxStackSize()); - if (existing.getCount() <= toExtract) - { - if (!simulate) - { + if (existing.getCount() <= toExtract) { + if (!simulate) { itemStacks.set(slot, ItemStack.EMPTY); setItemList(itemStacks); return existing; - } - else - { + } else { return existing.copy(); } - } - else - { - if (!simulate) - { + } else { + if (!simulate) { itemStacks.set(slot, ItemHandlerHelper.copyStackWithSize(existing, existing.getCount() - toExtract)); setItemList(itemStacks); } @@ -173,27 +157,23 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa } } - private void validateSlotIndex(int slot) - { + private void validateSlotIndex(int slot) { if (slot < 0 || slot >= getSlots()) throw new RuntimeException("Slot " + slot + " not in valid range - [0," + getSlots() + ")"); } @Override - public int getSlotLimit(int slot) - { + public int getSlotLimit(int slot) { return 64; } @Override - public boolean isItemValid(int slot, @NotNull ItemStack stack) - { + public boolean isItemValid(int slot, @NotNull ItemStack stack) { return stack.getItem().canFitInsideContainerItems(); } @Override - public void setStackInSlot(int slot, @NotNull ItemStack stack) - { + public void setStackInSlot(int slot, @NotNull ItemStack stack) { validateSlotIndex(slot); if (!isItemValid(slot, stack)) throw new RuntimeException("Invalid stack " + stack + " for slot " + slot + ")"); NonNullList itemStacks = getItemList(); @@ -201,37 +181,34 @@ public class ShulkerItemStackInvWrapper implements IItemHandlerModifiable, ICapa setItemList(itemStacks); } - private NonNullList getItemList() - { - CompoundTag rootTag = BlockItem.getBlockEntityData(this.stack); - if (cachedTag == null || !cachedTag.equals(rootTag)) + private NonNullList getItemList() { + var rootTag = this.stack.get(DataComponents.BLOCK_ENTITY_DATA); + if (cachedData == null || !cachedData.equals(rootTag)) itemStacksCache = refreshItemList(rootTag); return itemStacksCache; } - private NonNullList refreshItemList(CompoundTag rootTag) - { - NonNullList itemStacks = NonNullList.withSize(getSlots(), ItemStack.EMPTY); - if (rootTag != null && rootTag.contains("Items", CompoundTag.TAG_LIST)) - { + private NonNullList refreshItemList(CustomData data) { + var itemStacks = NonNullList.withSize(getSlots(), ItemStack.EMPTY); + var rootTag = data.copyTag(); + if (rootTag != null && rootTag.contains("Items", CompoundTag.TAG_LIST)) { ContainerHelper.loadAllItems(rootTag, itemStacks); } - cachedTag = rootTag; + cachedData = data; return itemStacks; } - private void setItemList(NonNullList itemStacks) - { - CompoundTag existing = BlockItem.getBlockEntityData(this.stack); + private void setItemList(NonNullList itemStacks) { + var exisiting = this.stack.get(DataComponents.BLOCK_ENTITY_DATA); CompoundTag rootTag = ContainerHelper.saveAllItems(existing == null ? new CompoundTag() : existing, itemStacks); BlockItem.setBlockEntityData(this.stack, BlockEntityType.SHULKER_BOX, rootTag); - cachedTag = rootTag; + cachedData = rootTag; } @Override @NotNull - public LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) - { + public LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) { return ForgeCapabilities.ITEM_HANDLER.orEmpty(cap, this.holder); } } +*/ diff --git a/src/main/java/net/minecraftforge/logging/CrashReportExtender.java b/src/main/java/net/minecraftforge/logging/CrashReportExtender.java index 2bc2c1bdc8..49fe34e64b 100644 --- a/src/main/java/net/minecraftforge/logging/CrashReportExtender.java +++ b/src/main/java/net/minecraftforge/logging/CrashReportExtender.java @@ -6,7 +6,6 @@ package net.minecraftforge.logging; import cpw.mods.modlauncher.log.TransformingThrowablePatternConverter; -import joptsimple.internal.Strings; import net.minecraft.CrashReport; import net.minecraft.CrashReportCategory; import net.minecraft.SystemReport; @@ -22,6 +21,7 @@ import java.text.SimpleDateFormat; import java.util.*; public class CrashReportExtender { + private static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); public static void extendSystemReport(final SystemReport systemReport) { for (final ISystemReportExtender call : CrashReportCallables.allCrashCallables()) { if (call.isActive()) @@ -41,7 +41,7 @@ public class CrashReportExtender { public static String generateEnhancedStackTrace(final Throwable throwable, boolean header) { final String s = TransformingThrowablePatternConverter.generateEnhancedStackTrace(throwable); - return header ? s : s.substring(s.indexOf(Strings.LINE_SEPARATOR)); + return header ? s : s.substring(s.indexOf(LINE_SEPARATOR)); } public static File dumpModLoadingCrashReport(final Logger logger, final LoadingFailedException error, final File topLevelDir) { @@ -52,7 +52,7 @@ public class CrashReportExtender { Throwable cause = mle.getCause(); int depth = 0; while (cause != null && cause.getCause() != null && cause.getCause()!=cause) { - category.setDetail("Caused by "+(depth++), cause + generateEnhancedStackTrace(cause.getStackTrace()).replaceAll(Strings.LINE_SEPARATOR+"\t", "\n\t\t")); + category.setDetail("Caused by "+(depth++), cause + generateEnhancedStackTrace(cause.getStackTrace()).replaceAll(LINE_SEPARATOR+"\t", "\n\t\t")); cause = cause.getCause(); } if (cause != null) diff --git a/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java b/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java index bc6b000996..2f30e09ec9 100644 --- a/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java +++ b/src/main/java/net/minecraftforge/network/filters/VanillaConnectionNetworkFilter.java @@ -62,7 +62,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter { ClientboundUpdateAttributesPacket newPacket = new ClientboundUpdateAttributesPacket(msg.getEntityId(), Collections.emptyList()); msg.getValues().stream() .filter(snapshot -> { - ResourceLocation key = ForgeRegistries.ATTRIBUTES.getKey(snapshot.getAttribute()); + ResourceLocation key = ForgeRegistries.ATTRIBUTES.getKey(snapshot.attribute().get()); return key != null && key.getNamespace().equals("minecraft"); }) .forEach(snapshot -> newPacket.getValues().add(snapshot)); diff --git a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java index be430e2695..a8cbb76f40 100644 --- a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java +++ b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java @@ -13,6 +13,7 @@ import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraftforge.event.network.CustomPayloadEvent; @@ -41,14 +42,19 @@ public class OpenContainer { public static void encode(OpenContainer msg, FriendlyByteBuf buf) { buf.writeVarInt(msg.id); buf.writeVarInt(msg.windowId); - buf.writeComponent(msg.name); + ComponentSerialization.TRUSTED_CONTEXT_FREE_STREAM_CODEC.encode(buf, msg.name); msg.additionalData.markReaderIndex(); buf.writeByteArray(msg.additionalData.readByteArray()); msg.additionalData.resetReaderIndex(); } public static OpenContainer decode(FriendlyByteBuf buf) { - return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600)))); + return new OpenContainer( + buf.readVarInt(), + buf.readVarInt(), + ComponentSerialization.TRUSTED_CONTEXT_FREE_STREAM_CODEC.decode(buf), + new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600))) + ); } @SuppressWarnings("unchecked") diff --git a/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java b/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java index 867d9b563d..ce68c36b75 100644 --- a/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java +++ b/src/main/java/net/minecraftforge/registries/DataPackRegistriesHooks.java @@ -19,13 +19,13 @@ import java.util.stream.Stream; public final class DataPackRegistriesHooks { private DataPackRegistriesHooks() {} // utility class - private static final Map>, RegistrySynchronization.NetworkedRegistryData> NETWORKABLE_REGISTRIES = new LinkedHashMap<>(); + private static final Map>, RegistryDataLoader.RegistryData> NETWORKABLE_REGISTRIES = new LinkedHashMap<>(); private static final List> WORLDGEN_REGISTRIES = new ArrayList<>(); private static final Set>> SYNCED_CUSTOM_REGISTRIES = new HashSet<>(); private static final Set>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES); /* Internal forge hook for retaining mutable access to RegistryAccess's codec registry when it bootstraps. */ - public static Map>, RegistrySynchronization.NetworkedRegistryData> grabNetworkableRegistries(ImmutableMap.Builder>, RegistrySynchronization.NetworkedRegistryData> builder) { + public static Map>, RegistryDataLoader.RegistryData> grabNetworkableRegistries(ImmutableMap.Builder>, RegistryDataLoader.RegistryData> builder) { if (!StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass().equals(RegistrySynchronization.class)) throw new IllegalCallerException("Attempted to call DataPackRegistriesHooks#grabNetworkableRegistries!"); NETWORKABLE_REGISTRIES.forEach(builder::put); @@ -40,7 +40,7 @@ public final class DataPackRegistriesHooks { WORLDGEN_REGISTRIES.add(loaderData); if (data.networkCodec() != null) { SYNCED_CUSTOM_REGISTRIES.add(loaderData.key()); - NETWORKABLE_REGISTRIES.put(loaderData.key(), new RegistrySynchronization.NetworkedRegistryData<>(loaderData.key(), data.networkCodec())); + NETWORKABLE_REGISTRIES.put(loaderData.key(), new RegistryDataLoader.RegistryData<>(loaderData.key(), data.networkCodec())); } } diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistries.java b/src/main/java/net/minecraftforge/registries/ForgeRegistries.java index b3b9709922..11f34cb571 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistries.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistries.java @@ -6,6 +6,8 @@ package net.minecraftforge.registries; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.network.syncher.EntityDataSerializer; import net.minecraft.world.entity.decoration.PaintingVariant; @@ -32,11 +34,11 @@ import net.minecraft.world.effect.MobEffect; import net.minecraft.world.item.alchemy.Potion; import net.minecraft.stats.StatType; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProviderType; import net.minecraft.world.level.levelgen.carver.WorldCarver; import net.minecraft.world.level.levelgen.feature.Feature; @@ -112,13 +114,13 @@ public class ForgeRegistries { // Custom forge registries public static final Supplier>> ENTITY_DATA_SERIALIZERS = registry(Keys.ENTITY_DATA_SERIALIZERS, GameData::getDataSerializersRegistryBuilder); - public static final Supplier>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = registry(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, GameData::getGLMSerializersRegistryBuilder); - public static final Supplier>> BIOME_MODIFIER_SERIALIZERS = registry(Keys.BIOME_MODIFIER_SERIALIZERS, GameData::makeUnsavedAndUnsynced); - public static final Supplier>> STRUCTURE_MODIFIER_SERIALIZERS = registry(Keys.STRUCTURE_MODIFIER_SERIALIZERS, GameData::makeUnsavedAndUnsynced); + public static final Supplier>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = registry(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, GameData::getGLMSerializersRegistryBuilder); + public static final Supplier>> BIOME_MODIFIER_SERIALIZERS = registry(Keys.BIOME_MODIFIER_SERIALIZERS, GameData::makeUnsavedAndUnsynced); + public static final Supplier>> STRUCTURE_MODIFIER_SERIALIZERS = registry(Keys.STRUCTURE_MODIFIER_SERIALIZERS, GameData::makeUnsavedAndUnsynced); public static final Supplier> FLUID_TYPES = registry(Keys.FLUID_TYPES, GameData::getFluidTypeRegistryBuilder); public static final Supplier> HOLDER_SET_TYPES = registry(Keys.HOLDER_SET_TYPES, GameData::makeUnsavedAndUnsynced); public static final Supplier> DISPLAY_CONTEXTS = registry(Keys.DISPLAY_CONTEXTS, GameData::getItemDisplayContextRegistryBuilder); - public static final Supplier>> CONDITION_SERIALIZERS = registry(Keys.CONDITION_SERIALIZERS, GameData::makeUnsavedAndUnsynced); + public static final Supplier>> CONDITION_SERIALIZERS = registry(Keys.CONDITION_SERIALIZERS, GameData::makeUnsavedAndUnsynced); public static final Supplier>> INGREDIENT_SERIALIZERS = registry(Keys.INGREDIENT_SERIALIZERS, GameData::makeUnsavedAndUnsynced); public static final class Keys { @@ -158,13 +160,13 @@ public class ForgeRegistries { // Forge public static final ResourceKey>> ENTITY_DATA_SERIALIZERS = key("forge:entity_data_serializers"); - public static final ResourceKey>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = key("forge:global_loot_modifier_serializers"); - public static final ResourceKey>> BIOME_MODIFIER_SERIALIZERS = key("forge:biome_modifier_serializers"); - public static final ResourceKey>> STRUCTURE_MODIFIER_SERIALIZERS = key("forge:structure_modifier_serializers"); + public static final ResourceKey>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = key("forge:global_loot_modifier_serializers"); + public static final ResourceKey>> BIOME_MODIFIER_SERIALIZERS = key("forge:biome_modifier_serializers"); + public static final ResourceKey>> STRUCTURE_MODIFIER_SERIALIZERS = key("forge:structure_modifier_serializers"); public static final ResourceKey> FLUID_TYPES = key("forge:fluid_type"); public static final ResourceKey> HOLDER_SET_TYPES = key("forge:holder_set_type"); public static final ResourceKey> DISPLAY_CONTEXTS = key("forge:display_contexts"); - public static final ResourceKey>> CONDITION_SERIALIZERS = key("forge:condition_codecs"); + public static final ResourceKey>> CONDITION_SERIALIZERS = key("forge:condition_codecs"); public static final ResourceKey>> INGREDIENT_SERIALIZERS = key("forge:ingredient_serializers"); // Forge Dynamic diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java index f18ac54bcb..709f595529 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java @@ -72,7 +72,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist private final BiMap names = HashBiMap.create(); private final BiMap, V> keys = HashBiMap.create(); private final Map aliases = new HashMap<>(); - final Map slaves = new HashMap<>(); + final Map, ?> slaves = new HashMap<>(); private final ResourceLocation defaultKey; //private final ResourceKey defaultResourceKey; private final CreateCallback create; @@ -230,9 +230,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist if (!this.hasWrapper) return null; - return this.defaultKey != null - ? this.getSlaveMap(NamespacedDefaultedWrapper.Factory.ID, NamespacedDefaultedWrapper.class) - : this.getSlaveMap(NamespacedWrapper.Factory.ID, NamespacedWrapper.class); + return (NamespacedWrapper)this.getSlaveMap(GameData.WrapperFactory.WRAPPER); } @NotNull @@ -299,14 +297,14 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist @SuppressWarnings("unchecked") @Override - public T getSlaveMap(ResourceLocation name, Class type) { - return (T)this.slaves.get(name); + public T getSlaveMap(SlaveKey key) { + return (T)this.slaves.get(key); } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void setSlaveMap(ResourceLocation name, Object obj) { - ((Map)this.slaves).put(name, obj); + public void setSlaveMap(SlaveKey name, T obj) { + ((Map)this.slaves).put(name, obj); } public int getID(V value) { diff --git a/src/main/java/net/minecraftforge/registries/GameData.java b/src/main/java/net/minecraftforge/registries/GameData.java index c58fcc8085..66f730c0f1 100644 --- a/src/main/java/net/minecraftforge/registries/GameData.java +++ b/src/main/java/net/minecraftforge/registries/GameData.java @@ -8,8 +8,8 @@ package net.minecraftforge.registries; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; -import com.mojang.serialization.Codec; -import com.mojang.serialization.Lifecycle; +import com.mojang.serialization.MapCodec; + import java.util.Collection; import java.util.Comparator; import java.util.HashMap; @@ -21,18 +21,21 @@ import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; +import java.util.function.BiFunction; import java.util.stream.Collectors; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; +import net.minecraft.core.DefaultedRegistry; +import net.minecraft.core.Holder; import net.minecraft.core.IdMapper; import net.minecraft.core.MappedRegistry; import net.minecraft.core.Registry; +import net.minecraft.core.WritableRegistry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.syncher.EntityDataSerializer; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.entity.ai.attributes.Attribute; @@ -41,7 +44,6 @@ import net.minecraft.world.entity.ai.village.poi.PoiType; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -61,7 +63,13 @@ import net.minecraftforge.fml.StartupMessageManager; import net.minecraftforge.fml.util.EnhancedRuntimeException; import net.minecraftforge.fml.util.thread.EffectiveSide; import net.minecraftforge.registries.ForgeRegistries.Keys; -import org.apache.commons.lang3.Validate; +import net.minecraftforge.registries.IForgeRegistry.AddCallback; +import net.minecraftforge.registries.IForgeRegistry.BakeCallback; +import net.minecraftforge.registries.IForgeRegistry.ClearCallback; +import net.minecraftforge.registries.IForgeRegistry.CreateCallback; +import net.minecraftforge.registries.IForgeRegistry.SlaveKey; +import net.minecraftforge.registries.IForgeRegistry.ValidateCallback; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -74,16 +82,11 @@ import org.jetbrains.annotations.Nullable; *

Use the public {@link IForgeRegistry} and {@link ForgeRegistries} APIs to get the data

*/ @ApiStatus.Internal -public class GameData -{ +public class GameData { private static final Logger LOGGER = LogManager.getLogger(); private static final Marker REGISTRIES = ForgeRegistry.REGISTRIES; private static final int MAX_VARINT = Integer.MAX_VALUE - 1; //We were told it is their intention to have everything in a reg be unlimited, so assume that until we find cases where it isnt. - private static final ResourceLocation BLOCK_TO_ITEM = new ResourceLocation("minecraft:blocktoitemmap"); - private static final ResourceLocation BLOCKSTATE_TO_ID = new ResourceLocation("minecraft:blockstatetoid"); - private static final ResourceLocation BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE = new ResourceLocation("minecraft:blockstatetopointofinteresttype"); - private static boolean hasInit = false; private static final boolean DISABLE_VANILLA_REGISTRIES = Boolean.parseBoolean(System.getProperty("forge.disableVanillaGameData", "false")); // Use for unit tests/debugging private static final BiConsumer> LOCK_VANILLA = (name, reg) -> reg.slaves.values().stream().filter(o -> o instanceof ILockableRegistry).forEach(o -> ((ILockableRegistry)o).lock()); @@ -93,24 +96,24 @@ public class GameData } @SuppressWarnings("deprecation") - public static void init() - { - if (DISABLE_VANILLA_REGISTRIES) - { + public static void init() { + if (DISABLE_VANILLA_REGISTRIES) { LOGGER.warn(REGISTRIES, "DISABLING VANILLA REGISTRY CREATION AS PER SYSTEM VARIABLE SETTING! forge.disableVanillaGameData"); return; } + if (hasInit) return; + hasInit = true; // Game objects makeRegistry(Keys.BLOCKS, "air").addCallback(BlockCallbacks.INSTANCE).legacyName("blocks").intrusiveHolderCallback(Block::builtInRegistryHolder).create(); makeRegistry(Keys.FLUIDS, "empty").intrusiveHolderCallback(Fluid::builtInRegistryHolder).create(); makeRegistry(Keys.ITEMS, "air").addCallback(ItemCallbacks.INSTANCE).legacyName("items").intrusiveHolderCallback(Item::builtInRegistryHolder).create(); - makeRegistry(Keys.MOB_EFFECTS).legacyName("potions").intrusiveHolderCallback(MobEffect::builtInRegistryHolder).create(); - makeRegistry(Keys.SOUND_EVENTS).legacyName("soundevents").create(); - makeRegistry(Keys.POTIONS, "empty").legacyName("potiontypes").intrusiveHolderCallback(Potion::builtInRegistryHolder).create(); + makeRegistry(Keys.MOB_EFFECTS).create(); + makeRegistry(Keys.SOUND_EVENTS).create(); + makeRegistry(Keys.POTIONS).create(); makeRegistry(Keys.ENCHANTMENTS).legacyName("enchantments").intrusiveHolderCallback(Enchantment::builtInRegistryHolder).create(); makeRegistry(Keys.ENTITY_TYPES, "pig").legacyName("entities").intrusiveHolderCallback(EntityType::builtInRegistryHolder).create(); makeRegistry(Keys.BLOCK_ENTITY_TYPES).disableSaving().legacyName("blockentities").intrusiveHolderCallback(BlockEntityType::builtInRegistryHolder).create(); @@ -125,7 +128,7 @@ public class GameData // Villagers makeRegistry(Keys.VILLAGER_PROFESSIONS, "none").create(); - makeRegistry(Keys.POI_TYPES).addCallback(PointOfInterestTypeCallbacks.INSTANCE).disableSync().create(); + makeRegistry(Keys.POI_TYPES).addCallback(PoiTypeCallbacks.INSTANCE).disableSync().create(); makeRegistry(Keys.MEMORY_MODULE_TYPES, "dummy").disableSync().create(); makeRegistry(Keys.SENSOR_TYPES, "dummy").disableSaving().disableSync().create(); makeRegistry(Keys.SCHEDULES).disableSaving().disableSync().create(); @@ -143,18 +146,15 @@ public class GameData makeRegistry(Keys.BIOMES).disableSync().create(); } - static RegistryBuilder> getDataSerializersRegistryBuilder() - { + static RegistryBuilder> getDataSerializersRegistryBuilder() { return makeRegistry(Keys.ENTITY_DATA_SERIALIZERS, 256 /*vanilla space*/, MAX_VARINT).disableSaving().disableOverrides(); } - static RegistryBuilder> getGLMSerializersRegistryBuilder() - { + static RegistryBuilder> getGLMSerializersRegistryBuilder() { return makeRegistry(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS).disableSaving().disableSync(); } - static RegistryBuilder getFluidTypeRegistryBuilder() - { + static RegistryBuilder getFluidTypeRegistryBuilder() { return makeRegistry(Keys.FLUID_TYPES).disableSaving(); } @@ -162,63 +162,71 @@ public class GameData return RegistryBuilder.of().disableSaving().disableSync(); } - static RegistryBuilder getItemDisplayContextRegistryBuilder() - { + static RegistryBuilder getItemDisplayContextRegistryBuilder() { return new RegistryBuilder() .setMaxID(128 * 2) /* 0 -> 127 gets positive ID, 128 -> 256 gets negative ID */.disableOverrides().disableSaving() .setDefaultKey(new ResourceLocation("minecraft:none")) .onAdd(ItemDisplayContext.ADD_CALLBACK); } - private static RegistryBuilder makeRegistry(ResourceKey> key) - { + private static RegistryBuilder makeRegistry(ResourceKey> key) { return new RegistryBuilder().setName(key.location()).setMaxID(MAX_VARINT).hasWrapper(); } - private static RegistryBuilder makeRegistry(ResourceKey> key, int min, int max) - { + + private static RegistryBuilder makeRegistry(ResourceKey> key, int min, int max) { return new RegistryBuilder().setName(key.location()).setIDRange(min, max).hasWrapper(); } - private static RegistryBuilder makeRegistry(ResourceKey> key, String _default) - { + + private static RegistryBuilder makeRegistry(ResourceKey> key, String _default) { return new RegistryBuilder().setName(key.location()).setMaxID(MAX_VARINT).hasWrapper().setDefaultKey(new ResourceLocation(_default)); } - public static MappedRegistry getWrapper(ResourceKey> key, Lifecycle lifecycle) - { - IForgeRegistry reg = RegistryManager.ACTIVE.getRegistry(key); - Validate.notNull(reg, "Attempted to get vanilla wrapper for unknown registry: " + key.toString()); - @SuppressWarnings("unchecked") - MappedRegistry ret = reg.getSlaveMap(NamespacedWrapper.Factory.ID, NamespacedWrapper.class); - Validate.notNull(ret, "Attempted to get vanilla wrapper for registry created incorrectly: " + key.toString()); - return ret; - } - - public static MappedRegistry getWrapper(ResourceKey> key, Lifecycle lifecycle, String defKey) - { - IForgeRegistry reg = RegistryManager.ACTIVE.getRegistry(key); - Validate.notNull(reg, "Attempted to get vanilla wrapper for unknown registry: " + key.toString()); - @SuppressWarnings("unchecked") - MappedRegistry ret = reg.getSlaveMap(NamespacedDefaultedWrapper.Factory.ID, NamespacedDefaultedWrapper.class); - Validate.notNull(ret, "Attempted to get vanilla wrapper for registry created incorrectly: " + key.toString()); - return ret; - } - @SuppressWarnings("unchecked") - public static Map getBlockItemMap() - { - return RegistryManager.ACTIVE.getRegistry(Keys.ITEMS).getSlaveMap(BLOCK_TO_ITEM, Map.class); + public static > R getWrapper(ResourceKey> key, R vanilla) { + var reg = RegistryManager.ACTIVE.getRegistry(key.location()); + if (reg == null) + return vanilla; + + var wrapper = reg.getSlaveMap(WrapperFactory.WRAPPER); + if (wrapper == null) + return vanilla; + + var vanillaD = vanilla instanceof DefaultedRegistry tmp ? tmp : null; + var wrapperD = wrapper instanceof DefaultedRegistry tmp ? tmp : null; + + if (vanillaD == null && wrapperD != null) + throw new IllegalStateException("Invalid wrapper " + key.location() + " was defaulted when not expected"); + + if (vanillaD != null && wrapperD == null) + throw new IllegalStateException("Invalid wrapper " + key.location() + " was normal when should be expected"); + + if (vanillaD != null && !vanillaD.getDefaultKey().equals(wrapperD.getDefaultKey())) + throw new IllegalStateException("Invalid wrapper " + key.location() + " mismatched default key " + vanillaD.getDefaultKey() + " != " + wrapperD.getDefaultKey()); + + return (R)wrapper; } - @SuppressWarnings("unchecked") - public static IdMapper getBlockStateIDMap() - { - return RegistryManager.ACTIVE.getRegistry(Keys.BLOCKS).getSlaveMap(BLOCKSTATE_TO_ID, IdMapper.class); + static WrapperFactory createWrapperFactory(boolean defaulted) { + BiFunction, RegistryManager, WritableRegistry> factory = defaulted + ? (reg, stage) -> new NamespacedDefaultedWrapper<>(reg, reg.getBuilder().getIntrusiveHolderCallback(), stage) + : (reg, stage) -> new NamespacedWrapper(reg, reg.getBuilder().getIntrusiveHolderCallback(), stage); + return new WrapperFactory<>(factory); } - @SuppressWarnings("unchecked") - public static Map getBlockStatePointOfInterestTypeMap() - { - return RegistryManager.ACTIVE.getRegistry(Keys.POI_TYPES).getSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, Map.class); + + static record WrapperFactory(BiFunction, RegistryManager, WritableRegistry> factory) implements CreateCallback, AddCallback { + static SlaveKey> WRAPPER = SlaveKey.create("forge:vanilla_wrapper"); + @Override + public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) { + owner.setSlaveMap(WRAPPER, factory.apply((ForgeRegistry)owner, stage)); + } + + @Override + public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, V value, V oldValue) { + @SuppressWarnings("unchecked") + var wrapper = (NamespacedWrapper)owner.getSlaveMap(WRAPPER); + wrapper.onAdded(stage, id, key, value, oldValue); + } } public static void vanillaSnapshot() @@ -379,21 +387,23 @@ public class GameData } } - private static class BlockCallbacks implements IForgeRegistry.AddCallback, IForgeRegistry.ClearCallback, IForgeRegistry.BakeCallback, IForgeRegistry.CreateCallback - { + public static class BlockCallbacks implements AddCallback, ClearCallback, BakeCallback, CreateCallback { static final BlockCallbacks INSTANCE = new BlockCallbacks(); + private static final SlaveKey> STATE_TO_ID = SlaveKey.create("state_to_id"); + + public static IdMapper getBlockStateIDMap() { + return RegistryManager.ACTIVE.getRegistry(Keys.BLOCKS).getSlaveMap(STATE_TO_ID); + } + @Override - public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, Block block, @Nullable Block oldBlock) - { - if (oldBlock != null) - { + public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, Block block, @Nullable Block oldBlock) { + if (oldBlock != null) { StateDefinition oldContainer = oldBlock.getStateDefinition(); StateDefinition newContainer = block.getStateDefinition(); // Test vanilla blockstates, if the number matches, make sure they also match in their string representations - if (key.location().getNamespace().equals("minecraft") && !oldContainer.getProperties().equals(newContainer.getProperties())) - { + if (key.location().getNamespace().equals("minecraft") && !oldContainer.getProperties().equals(newContainer.getProperties())) { String oldSequence = oldContainer.getProperties().stream() .map(s -> String.format(Locale.ENGLISH, "%s={%s}", s.getName(), s.getPossibleValues().stream().map(Object::toString).collect(Collectors.joining( "," )))) @@ -415,37 +425,28 @@ public class GameData } @Override - public void onClear(IForgeRegistryInternal owner, RegistryManager stage) - { - owner.getSlaveMap(BLOCKSTATE_TO_ID, ClearableObjectIntIdentityMap.class).clear(); + public void onClear(IForgeRegistryInternal owner, RegistryManager stage) { + owner.getSlaveMap(STATE_TO_ID).clear(); } @Override - public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) - { - final ClearableObjectIntIdentityMap idMap = new ClearableObjectIntIdentityMap<>() - { + public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) { + var idMap = new ClearableObjectIntIdentityMap() { @SuppressWarnings("deprecation") @Override - public int getId(BlockState key) - { + public int getId(BlockState key) { return this.tToId.containsKey(key) ? this.tToId.getInt(key) : -1; } }; - owner.setSlaveMap(BLOCKSTATE_TO_ID, idMap); - owner.setSlaveMap(BLOCK_TO_ITEM, new HashMap<>()); + owner.setSlaveMap(STATE_TO_ID, idMap); } @Override - public void onBake(IForgeRegistryInternal owner, RegistryManager stage) - { - @SuppressWarnings("unchecked") - ClearableObjectIntIdentityMap blockstateMap = owner.getSlaveMap(BLOCKSTATE_TO_ID, ClearableObjectIntIdentityMap.class); + public void onBake(IForgeRegistryInternal owner, RegistryManager stage) { + var blockstateMap = owner.getSlaveMap(STATE_TO_ID); - for (Block block : owner) - { - for (BlockState state : block.getStateDefinition().getPossibleStates()) - { + for (Block block : owner) { + for (BlockState state : block.getStateDefinition().getPossibleStates()) { blockstateMap.add(state); state.initCache(); } @@ -456,87 +457,82 @@ public class GameData } } - private static class ItemCallbacks implements IForgeRegistry.AddCallback, IForgeRegistry.ClearCallback, IForgeRegistry.CreateCallback - { + public static class ItemCallbacks implements AddCallback, ClearCallback, CreateCallback { static final ItemCallbacks INSTANCE = new ItemCallbacks(); + private static final SlaveKey> BLOCK_TO_ITEM = SlaveKey.create("block_to_item"); + + public static Map getBlockItemMap() { + return RegistryManager.ACTIVE.getRegistry(Keys.ITEMS).getSlaveMap(BLOCK_TO_ITEM); + } @Override - public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, Item item, @Nullable Item oldItem) - { - if (oldItem instanceof BlockItem) - { - @SuppressWarnings("unchecked") - Map blockToItem = owner.getSlaveMap(BLOCK_TO_ITEM, Map.class); - ((BlockItem)oldItem).removeFromBlockToItemMap(blockToItem, item); + public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, Item item, @Nullable Item oldItem) { + if (oldItem instanceof BlockItem block) { + block.removeFromBlockToItemMap(owner.getSlaveMap(BLOCK_TO_ITEM), item); } - if (item instanceof BlockItem) - { - @SuppressWarnings("unchecked") - Map blockToItem = owner.getSlaveMap(BLOCK_TO_ITEM, Map.class); - ((BlockItem)item).registerBlocks(blockToItem, item); + + if (item instanceof BlockItem block) { + block.registerBlocks(owner.getSlaveMap(BLOCK_TO_ITEM), item); } } @Override - public void onClear(IForgeRegistryInternal owner, RegistryManager stage) - { - owner.getSlaveMap(BLOCK_TO_ITEM, Map.class).clear(); + public void onClear(IForgeRegistryInternal owner, RegistryManager stage) { + owner.getSlaveMap(BLOCK_TO_ITEM).clear(); } @Override - public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) - { - // We share the blockItem map between items and blocks registries - Map map = stage.getRegistry(Keys.BLOCKS).getSlaveMap(BLOCK_TO_ITEM, Map.class); - owner.setSlaveMap(BLOCK_TO_ITEM, map); + public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) { + owner.setSlaveMap(BLOCK_TO_ITEM, new HashMap<>()); } } - private static class AttributeCallbacks implements IForgeRegistry.ValidateCallback { - + private static class AttributeCallbacks implements ValidateCallback { static final AttributeCallbacks INSTANCE = new AttributeCallbacks(); @Override - public void onValidate(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceLocation key, Attribute obj) - { + public void onValidate(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceLocation key, Attribute obj) { // some stuff hard patched in can cause this to derp if it's JUST vanilla, so skip if (stage!=RegistryManager.VANILLA) DefaultAttributes.validate(); } } - private static class PointOfInterestTypeCallbacks implements IForgeRegistry.AddCallback, IForgeRegistry.ClearCallback, IForgeRegistry.CreateCallback - { - static final PointOfInterestTypeCallbacks INSTANCE = new PointOfInterestTypeCallbacks(); + public static class PoiTypeCallbacks implements AddCallback, ClearCallback, CreateCallback { + static final PoiTypeCallbacks INSTANCE = new PoiTypeCallbacks(); + private static final SlaveKey>> STATE_TO_POI = SlaveKey.create("state_to_poi"); + + public static Map> getStateToPoi() { + return RegistryManager.ACTIVE.getRegistry(Keys.POI_TYPES).getSlaveMap(STATE_TO_POI); + } @Override - public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, PoiType obj, @Nullable PoiType oldObj) - { - @SuppressWarnings("unchecked") - Map map = owner.getSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, Map.class); - if (oldObj != null) - { + public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, PoiType obj, @Nullable PoiType oldObj) { + var map = owner.getSlaveMap(STATE_TO_POI); + if (oldObj != null) { oldObj.matchingStates().forEach(map::remove); } - obj.matchingStates().forEach((state) -> - { - PoiType oldType = map.put(state, obj); - if (oldType != null) - { + + var holder = owner.getHolder(obj).orElse(null); + if (holder == null) { + throw new IllegalStateException("Could not get holder for " + key + " " + obj); + } + + obj.matchingStates().forEach((state) -> { + var oldType = map.put(state, holder); + if (oldType != null) { throw new IllegalStateException(String.format(Locale.ENGLISH, "Point of interest types %s and %s both list %s in their blockstates, this is not allowed. Blockstates can only have one point of interest type each.", oldType, obj, state)); } }); } @Override - public void onClear(IForgeRegistryInternal owner, RegistryManager stage) - { - owner.getSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, Map.class).clear(); + public void onClear(IForgeRegistryInternal owner, RegistryManager stage) { + owner.getSlaveMap(STATE_TO_POI).clear(); } @Override - public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) - { - owner.setSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, new HashMap<>()); + public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) { + owner.setSlaveMap(STATE_TO_POI, new HashMap<>()); } } diff --git a/src/main/java/net/minecraftforge/registries/IForgeRegistry.java b/src/main/java/net/minecraftforge/registries/IForgeRegistry.java index 341932ed74..d5dd275cf7 100644 --- a/src/main/java/net/minecraftforge/registries/IForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/IForgeRegistry.java @@ -24,8 +24,7 @@ import java.util.Set; * * @param The top level type for the registry */ -public interface IForgeRegistry extends Iterable -{ +public interface IForgeRegistry extends Iterable { ResourceKey> getRegistryKey(); ResourceLocation getRegistryName(); @@ -92,15 +91,14 @@ public interface IForgeRegistry extends Iterable * @param Type to return * @return The slavemap if present */ - T getSlaveMap(ResourceLocation slaveMapName, Class type); + T getSlaveMap(SlaveKey key); /** * Callback fired when objects are added to the registry. This will fire when the registry is rebuilt * on the client side from a server side synchronization, or when a world is loaded. */ @FunctionalInterface - interface AddCallback - { + interface AddCallback { void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, V obj, @Nullable V oldObj); } @@ -109,8 +107,7 @@ public interface IForgeRegistry extends Iterable * or server. */ @FunctionalInterface - interface ClearCallback - { + interface ClearCallback { void onClear(IForgeRegistryInternal owner, RegistryManager stage); } @@ -118,8 +115,7 @@ public interface IForgeRegistry extends Iterable * Callback fired when a registry instance is created. Populate slave maps here. */ @FunctionalInterface - interface CreateCallback - { + interface CreateCallback { void onCreate(IForgeRegistryInternal owner, RegistryManager stage); } @@ -127,8 +123,7 @@ public interface IForgeRegistry extends Iterable * Callback fired when the registry contents are validated. */ @FunctionalInterface - interface ValidateCallback - { + interface ValidateCallback { void onValidate(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceLocation key, V obj); } @@ -136,14 +131,22 @@ public interface IForgeRegistry extends Iterable * Callback fired when the registry is done processing. Used to calculate state ID maps. */ @FunctionalInterface - interface BakeCallback - { + interface BakeCallback { void onBake(IForgeRegistryInternal owner, RegistryManager stage); } @FunctionalInterface - interface MissingFactory - { + interface MissingFactory { V createMissing(ResourceLocation key, boolean isNetwork); } + + public record SlaveKey(ResourceLocation name) { + public static SlaveKey create(String name) { + return create(new ResourceLocation(name)); + } + + public static SlaveKey create(ResourceLocation name) { + return new SlaveKey(name); + } + } } diff --git a/src/main/java/net/minecraftforge/registries/IForgeRegistryInternal.java b/src/main/java/net/minecraftforge/registries/IForgeRegistryInternal.java index ad2c8bfd01..931f8ee795 100644 --- a/src/main/java/net/minecraftforge/registries/IForgeRegistryInternal.java +++ b/src/main/java/net/minecraftforge/registries/IForgeRegistryInternal.java @@ -7,9 +7,8 @@ package net.minecraftforge.registries; import net.minecraft.resources.ResourceLocation; -public interface IForgeRegistryInternal extends IForgeRegistry -{ - void setSlaveMap(ResourceLocation name, Object obj); +public interface IForgeRegistryInternal extends IForgeRegistry { + void setSlaveMap(SlaveKey name, T obj); void register(int id, ResourceLocation key, V value); V getValue(int id); diff --git a/src/main/java/net/minecraftforge/registries/NamespacedDefaultedWrapper.java b/src/main/java/net/minecraftforge/registries/NamespacedDefaultedWrapper.java index c5cbbf6fe2..750b5fcb38 100644 --- a/src/main/java/net/minecraftforge/registries/NamespacedDefaultedWrapper.java +++ b/src/main/java/net/minecraftforge/registries/NamespacedDefaultedWrapper.java @@ -15,8 +15,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import org.jetbrains.annotations.Nullable; -class NamespacedDefaultedWrapper extends NamespacedWrapper implements DefaultedRegistry -{ +class NamespacedDefaultedWrapper extends NamespacedWrapper implements DefaultedRegistry { private final ForgeRegistry delegate; private final ResourceLocation defaultKey; private Holder.Reference defaultHolder; @@ -29,14 +28,12 @@ class NamespacedDefaultedWrapper extends NamespacedWrapper implements Defa // Reading Functions @Override - public T get(@Nullable ResourceLocation name) - { + public T get(@Nullable ResourceLocation name) { return this.delegate.getValue(name); //getOrDefault } @Override - public Optional> getRandom(RandomSource rand) - { + public Optional> getRandom(RandomSource rand) { if (this.defaultHolder != null) return super.getRandom(rand).or(() -> Optional.of(this.defaultHolder)); @@ -44,15 +41,13 @@ class NamespacedDefaultedWrapper extends NamespacedWrapper implements Defa } @Override - public ResourceLocation getDefaultKey() - { + public ResourceLocation getDefaultKey() { return this.delegate.getDefaultKey(); } @Nullable @Override - Holder.Reference onAdded(RegistryManager stage, int id, ResourceKey key, T newValue, T oldValue) - { + Holder.Reference onAdded(RegistryManager stage, int id, ResourceKey key, T newValue, T oldValue) { Holder.Reference newHolder = super.onAdded(stage, id, key, newValue, oldValue); if (newHolder != null && this.defaultKey != null && this.defaultKey.equals(key.location())) @@ -60,23 +55,4 @@ class NamespacedDefaultedWrapper extends NamespacedWrapper implements Defa return newHolder; } - - public static class Factory implements IForgeRegistry.CreateCallback, IForgeRegistry.AddCallback - { - public static final ResourceLocation ID = new ResourceLocation("forge", "registry_defaulted_wrapper"); - - @Override - public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) - { - ForgeRegistry fowner = (ForgeRegistry) owner; - owner.setSlaveMap(ID, new NamespacedDefaultedWrapper(fowner, fowner.getBuilder().getIntrusiveHolderCallback(), stage)); - } - - @Override - @SuppressWarnings("unchecked") - public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, V value, V oldValue) - { - owner.getSlaveMap(ID, NamespacedDefaultedWrapper.class).onAdded(stage, id, key, value, oldValue); - } - } } diff --git a/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java b/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java index 980e60ba14..b57e58d975 100644 --- a/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java +++ b/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java @@ -18,12 +18,12 @@ import net.minecraft.core.Holder; import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderSet; import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.util.RandomSource; -import org.apache.commons.lang3.Validate; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -42,8 +42,7 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -class NamespacedWrapper extends MappedRegistry implements ILockableRegistry -{ +class NamespacedWrapper extends MappedRegistry implements ILockableRegistry { static final Logger LOGGER = LogUtils.getLogger(); private final ForgeRegistry delegate; @Nullable @@ -59,9 +58,9 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr private Map> holders = new IdentityHashMap<>(); private RegistryManager stage; private volatile Map, HolderSet.Named> tags = new IdentityHashMap<>(); + private final Map, RegistrationInfo> registrationInfos = new IdentityHashMap<>(); - NamespacedWrapper(ForgeRegistry fowner, Function> intrusiveHolderCallback, RegistryManager stage) - { + NamespacedWrapper(ForgeRegistry fowner, Function> intrusiveHolderCallback, RegistryManager stage) { super(fowner.getRegistryKey(), Lifecycle.stable(), intrusiveHolderCallback != null); this.delegate = fowner; this.intrusiveHolderCallback = intrusiveHolderCallback; @@ -69,132 +68,103 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } @Override - public Holder.Reference registerMapping(int id, ResourceKey key, T value, Lifecycle lifecycle) - { + public Holder.Reference register(ResourceKey key, T value, RegistrationInfo info) { if (locked) throw new IllegalStateException("Can not register to a locked registry. Modder should use Forge Register methods."); - Validate.notNull(value); + Objects.requireNonNull(value); markKnown(); - this.registryLifecycle = this.registryLifecycle.add(lifecycle); - int realId = this.delegate.add(id, key.location(), value); - if (realId != id && id != -1) - LOGGER.warn("Registered object did not get ID it asked for. Name: {} Expected: {} Got: {}", key, id, realId); + this.registrationInfos.put(key, info); + this.registryLifecycle = this.registryLifecycle.add(info.lifecycle()); + + this.delegate.add(-1, key.location(), value); return getHolder(key, value); } - @Override - public Holder.Reference register(ResourceKey key, T value, Lifecycle lifecycle) - { - return registerMapping(-1, key, value, lifecycle); - } - // Reading Functions @Override @Nullable - public T get(@Nullable ResourceLocation name) - { + public T get(@Nullable ResourceLocation name) { return this.delegate.getRaw(name); //get without default } @Override - public Optional getOptional(@Nullable ResourceLocation name) - { + public Optional getOptional(@Nullable ResourceLocation name) { return Optional.ofNullable(this.delegate.getRaw(name)); //get without default } @Override @Nullable - public T get(@Nullable ResourceKey name) - { + public T get(@Nullable ResourceKey name) { return name == null ? null : this.delegate.getRaw(name.location()); //get without default } @Override @Nullable - public ResourceLocation getKey(T value) - { + public ResourceLocation getKey(T value) { return this.delegate.getKey(value); } @Override - public Optional> getResourceKey(T p_122755_) - { - return this.delegate.getResourceKey(p_122755_); + public Optional> getResourceKey(T value) { + return this.delegate.getResourceKey(value); } @Override - public boolean containsKey(ResourceLocation key) - { + public boolean containsKey(ResourceLocation key) { return this.delegate.containsKey(key); } @Override - public boolean containsKey(ResourceKey key) - { + public boolean containsKey(ResourceKey key) { return this.delegate.getRegistryName().equals(key.registry()) && containsKey(key.location()); } @Override - public int getId(@Nullable T value) - { + public int getId(@Nullable T value) { return this.delegate.getID(value); } @Override @Nullable - public T byId(int id) - { + public T byId(int id) { return this.delegate.getValue(id); } @Override - public Lifecycle lifecycle(T value) - { - return Lifecycle.stable(); - } - - @Override - public Lifecycle registryLifecycle() - { + public Lifecycle registryLifecycle() { return this.registryLifecycle; } @Override - public Iterator iterator() - { + public Iterator iterator() { return this.delegate.iterator(); } @Override - public Set keySet() - { + public Set keySet() { return this.delegate.getKeys(); } @Override - public Set> registryKeySet() - { + public Set> registryKeySet() { return this.delegate.getResourceKeys(); } @Override - public Set, T>> entrySet() - { + public Set, T>> entrySet() { return this.delegate.getEntries(); } @Override - public boolean isEmpty() - { + public boolean isEmpty() { return this.delegate.isEmpty(); } @Override - public int size() - { + public int size() { return this.delegate.size(); } @@ -203,89 +173,76 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr */ @Deprecated @Override - public void lock() - { + public void lock() { this.locked = true; } @Override - public Optional> getHolder(int id) - { + public Optional> getHolder(int id) { return id >= 0 && id < this.holdersById.size() ? Optional.ofNullable(this.holdersById.get(id)) : Optional.empty(); } @Override - public Optional> getHolder(ResourceKey key) - { + public Optional> getHolder(ResourceKey key) { return Optional.ofNullable(this.holdersByName.get(key.location())); } @Override - public @NotNull Holder wrapAsHolder(@NotNull T value) - { + public @NotNull Holder wrapAsHolder(@NotNull T value) { final Holder holder = this.holders.get(value); return holder == null ? Holder.direct(value) : holder; } - Optional> getHolder(ResourceLocation location) - { + @Override + public Optional registrationInfo(ResourceKey p_331530_) { + return Optional.ofNullable(this.registrationInfos.get(p_331530_)); + } + + public Optional> getHolder(ResourceLocation location) { return Optional.ofNullable(this.holdersByName.get(location)); } - Optional> getHolder(T value) - { + Optional> getHolder(T value) { return Optional.ofNullable(this.holders.get(value)); } @Override - public HolderGetter createRegistrationLookup() - { + public HolderGetter createRegistrationLookup() { this.validateWrite(); - return new HolderGetter() - { - public Optional> get(ResourceKey p_259097_) - { - return Optional.of(this.getOrThrow(p_259097_)); + return new HolderGetter() { + public Optional> get(ResourceKey key) { + return Optional.of(this.getOrThrow(key)); } - public Holder.Reference getOrThrow(ResourceKey p_259750_) - { - return NamespacedWrapper.this.getOrCreateHolderOrThrow(p_259750_); + public Holder.Reference getOrThrow(ResourceKey key) { + return NamespacedWrapper.this.getOrCreateHolderOrThrow(key); } - public Optional> get(TagKey p_259486_) - { - return Optional.of(this.getOrThrow(p_259486_)); + public Optional> get(TagKey key) { + return Optional.of(this.getOrThrow(key)); } - public HolderSet.Named getOrThrow(TagKey p_260298_) - { - return NamespacedWrapper.this.getOrCreateTag(p_260298_); + public HolderSet.Named getOrThrow(TagKey key) { + return NamespacedWrapper.this.getOrCreateTag(key); } }; } - void validateWrite() - { + void validateWrite() { if (this.frozen) throw new IllegalStateException("Registry is already frozen"); } - void validateWrite(ResourceKey key) - { + void validateWrite(ResourceKey key) { if (this.frozen) throw new IllegalStateException("Registry is already frozen (trying to add key " + key + ")"); } - Holder.Reference getOrCreateHolderOrThrow(ResourceKey key) - { + protected Holder.Reference getOrCreateHolderOrThrow(ResourceKey key) { return this.holdersByName.computeIfAbsent(key.location(), k -> { - if (this.intrusiveHolderCallback != null) - { + if (this.isIntrusive()) { throw new IllegalStateException("This registry can't create new holders without value"); - } - else - { + } else { this.validateWrite(key); return Holder.Reference.createStandAlone(this.holderOwner(), key); } @@ -293,29 +250,24 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } @Override - public Optional> getRandom(RandomSource rand) - { + public Optional> getRandom(RandomSource rand) { return Util.getRandomSafe(this.getSortedHolders(), rand); } @Override - public Stream> holders() - { + public Stream> holders() { return this.getSortedHolders().stream(); } @Override - public Stream, HolderSet.Named>> getTags() - { + public Stream, HolderSet.Named>> getTags() { return this.tags.entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue())); } @Override - public HolderSet.Named getOrCreateTag(TagKey name) - { + public HolderSet.Named getOrCreateTag(TagKey name) { HolderSet.Named named = this.tags.get(name); - if (named == null) - { + if (named == null) { named = createTag(name); // They use volatile and set it this way to not have the performance penalties of synced read access. But this makes a lot of new maps.. We need to look into performance alternatives. Map, HolderSet.Named> map = new IdentityHashMap<>(this.tags); @@ -326,21 +278,18 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr return named; } - void addOptionalTag(TagKey name, @NotNull Set> defaults) - { + void addOptionalTag(TagKey name, @NotNull Set> defaults) { this.optionalTags.putAll(name, defaults); } @Override - public Stream> getTagNames() - { + public Stream> getTagNames() { return this.tags.keySet().stream(); } //TODO: Move this to ValidateCallback? @Override - public Registry freeze() - { + public Registry freeze() { this.frozen = true; List unregistered = this.holdersByName.entrySet().stream() .filter(e -> !e.getValue().isBound()) @@ -357,9 +306,8 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } @Override - public Holder.Reference createIntrusiveHolder(T value) - { - if (this.intrusiveHolderCallback == null) + public Holder.Reference createIntrusiveHolder(T value) { + if (!this.isIntrusive()) throw new IllegalStateException("This registry can't create intrusive holders"); this.validateWrite(); @@ -368,14 +316,12 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } @Override - public Optional> getTag(TagKey name) - { + public Optional> getTag(TagKey name) { return Optional.ofNullable(this.tags.get(name)); } @Override - public void bindTags(Map, List>> newTags) - { + public void bindTags(Map, List>> newTags) { Map, List>> holderToTag = new IdentityHashMap<>(); this.holdersByName.values().forEach(v -> holderToTag.put(v, new ArrayList<>())); newTags.forEach((name, values) -> values.forEach(holder -> addTagToHolder(holderToTag, name, holder))); @@ -406,8 +352,7 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr this.delegate.onBindTags(this.tags, defaultedTags); } - private void addTagToHolder(Map, List>> holderToTag, TagKey name, Holder holder) - { + private void addTagToHolder(Map, List>> holderToTag, TagKey name, Holder holder) { if (!holder.canSerializeIn(this.holderOwner())) throw new IllegalStateException("Can't create named set " + name + " containing value " + holder + " from outside registry " + this); @@ -418,34 +363,26 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } @Override - public void resetTags() - { + public void resetTags() { this.tags.values().forEach(t -> t.bind(List.of())); this.holders.values().forEach(v -> v.bindTags(Set.of())); } @Override - public void unfreeze() - { + public void unfreeze() { this.frozen = false; } - boolean isFrozen() - { + boolean isFrozen() { return this.frozen; } - boolean isIntrusive() - { - return this.intrusiveHolderCallback != null; + boolean isIntrusive() { + return this.intrusiveHolderCallback != null && this.stage == RegistryManager.ACTIVE; } @Nullable - Holder.Reference onAdded(RegistryManager stage, int id, ResourceKey key, T newValue, T oldValue) - { - if (stage != RegistryManager.ACTIVE && (this.intrusiveHolderCallback == null || !stage.isStaging())) // Intrusive handlers need updating in staging. - return null; // Only do holder shit on the active registries, not pending or snapshots. - + Holder.Reference onAdded(RegistryManager stage, int id, ResourceKey key, T newValue, T oldValue) { //Holder.Reference oldHolder = oldValue == null ? null : getHolder(key, oldValue); // Do we need to do anything with the old holder? We cant update its pointer unless its non-intrusive... // And if thats the case, then we *should* get its reference in newHolder @@ -456,8 +393,7 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr this.holdersById.set(id, newHolder); this.holdersByName.put(key.location(), newHolder); this.holders.put(newValue, newHolder); - if (this.unregisteredIntrusiveHolders != null) - { + if (this.unregisteredIntrusiveHolders != null) { this.unregisteredIntrusiveHolders.remove(newValue); newHolder.bindKey(key); } @@ -467,44 +403,21 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr return newHolder; } - @SuppressWarnings("deprecation") - private HolderSet.Named createTag(TagKey name) - { - return HolderSet.emptyNamed(this.holderOwner(), name); + private HolderSet.Named createTag(TagKey name) { + return new HolderSet.Named<>(this.holderOwner(), name); } - private Holder.Reference getHolder(ResourceKey key, T value) - { - if (this.intrusiveHolderCallback != null) + private Holder.Reference getHolder(ResourceKey key, T value) { + if (this.isIntrusive()) return this.intrusiveHolderCallback.apply(value); return this.holdersByName.computeIfAbsent(key.location(), k -> Holder.Reference.createStandAlone(this.holderOwner(), key)); } - private List> getSortedHolders() - { + private List> getSortedHolders() { if (this.holdersSorted == null) this.holdersSorted = this.holdersById.stream().filter(Objects::nonNull).toList(); return this.holdersSorted; } - - public static class Factory implements IForgeRegistry.CreateCallback, IForgeRegistry.AddCallback - { - public static final ResourceLocation ID = new ResourceLocation("forge", "registry_defaulted_wrapper"); - - @Override - public void onCreate(IForgeRegistryInternal owner, RegistryManager stage) - { - ForgeRegistry fowner = (ForgeRegistry) owner; - owner.setSlaveMap(ID, new NamespacedWrapper(fowner, fowner.getBuilder().getIntrusiveHolderCallback(), stage)); - } - - @Override - @SuppressWarnings("unchecked") - public void onAdd(IForgeRegistryInternal owner, RegistryManager stage, int id, ResourceKey key, V value, V oldValue) - { - owner.getSlaveMap(ID, NamespacedWrapper.class).onAdded(stage, id, key, value, oldValue); - } - } } diff --git a/src/main/java/net/minecraftforge/registries/RegistryBuilder.java b/src/main/java/net/minecraftforge/registries/RegistryBuilder.java index 323114892f..1c8290bd1e 100644 --- a/src/main/java/net/minecraftforge/registries/RegistryBuilder.java +++ b/src/main/java/net/minecraftforge/registries/RegistryBuilder.java @@ -20,8 +20,7 @@ import java.util.List; import java.util.Set; import java.util.function.Function; -public class RegistryBuilder -{ +public class RegistryBuilder { public static RegistryBuilder of() { return new RegistryBuilder(); } @@ -55,33 +54,28 @@ public class RegistryBuilder @Nullable private Function> intrusiveHolderCallback = null; - public RegistryBuilder setName(ResourceLocation name) - { + public RegistryBuilder setName(ResourceLocation name) { this.registryName = name; return this; } - public RegistryBuilder setIDRange(int min, int max) - { + public RegistryBuilder setIDRange(int min, int max) { this.minId = Math.max(min, 0); this.maxId = Math.min(max, MAX_ID); return this; } - public RegistryBuilder setMaxID(int max) - { + public RegistryBuilder setMaxID(int max) { return this.setIDRange(0, max); } - public RegistryBuilder setDefaultKey(ResourceLocation key) - { + public RegistryBuilder setDefaultKey(ResourceLocation key) { this.optionalDefaultKey = key; return this; } @SuppressWarnings("unchecked") - public RegistryBuilder addCallback(Object inst) - { + public RegistryBuilder addCallback(Object inst) { if (inst instanceof AddCallback) this.add((AddCallback)inst); if (inst instanceof ClearCallback) @@ -97,120 +91,98 @@ public class RegistryBuilder return this; } - public RegistryBuilder add(AddCallback add) - { + public RegistryBuilder add(AddCallback add) { this.addCallback.add(add); return this; } - public RegistryBuilder onAdd(AddCallback add) - { + public RegistryBuilder onAdd(AddCallback add) { return this.add(add); } - public RegistryBuilder add(ClearCallback clear) - { + public RegistryBuilder add(ClearCallback clear) { this.clearCallback.add(clear); return this; } - public RegistryBuilder onClear(ClearCallback clear) - { + public RegistryBuilder onClear(ClearCallback clear) { return this.add(clear); } - public RegistryBuilder add(CreateCallback create) - { + public RegistryBuilder add(CreateCallback create) { this.createCallback.add(create); return this; } - public RegistryBuilder onCreate(CreateCallback create) - { + public RegistryBuilder onCreate(CreateCallback create) { return this.add(create); } - public RegistryBuilder add(ValidateCallback validate) - { + public RegistryBuilder add(ValidateCallback validate) { this.validateCallback.add(validate); return this; } - public RegistryBuilder onValidate(ValidateCallback validate) - { + public RegistryBuilder onValidate(ValidateCallback validate) { return this.add(validate); } - public RegistryBuilder add(BakeCallback bake) - { + public RegistryBuilder add(BakeCallback bake) { this.bakeCallback.add(bake); return this; } - public RegistryBuilder onBake(BakeCallback bake) - { + public RegistryBuilder onBake(BakeCallback bake) { return this.add(bake); } - public RegistryBuilder set(MissingFactory missing) - { + public RegistryBuilder set(MissingFactory missing) { this.missingFactory = missing; return this; } - public RegistryBuilder missing(MissingFactory missing) - { + public RegistryBuilder missing(MissingFactory missing) { return this.set(missing); } - public RegistryBuilder disableSaving() - { + public RegistryBuilder disableSaving() { this.saveToDisc = false; return this; } /** * Prevents the registry from being synced to clients. - * - * @return this */ - public RegistryBuilder disableSync() - { + public RegistryBuilder disableSync() { this.sync = false; return this; } - public RegistryBuilder disableOverrides() - { + public RegistryBuilder disableOverrides() { this.allowOverrides = false; return this; } - public RegistryBuilder allowModification() - { + public RegistryBuilder allowModification() { this.allowModifications = true; return this; } - RegistryBuilder hasWrapper() - { + RegistryBuilder hasWrapper() { this.hasWrapper = true; return this; } - public RegistryBuilder legacyName(String name) - { + public RegistryBuilder legacyName(String name) { return legacyName(new ResourceLocation(name)); } - public RegistryBuilder legacyName(ResourceLocation name) - { + public RegistryBuilder legacyName(ResourceLocation name) { this.legacyNames.add(name); return this; } - RegistryBuilder intrusiveHolderCallback(Function> intrusiveHolderCallback) - { + RegistryBuilder intrusiveHolderCallback(Function> intrusiveHolderCallback) { this.intrusiveHolderCallback = intrusiveHolderCallback; return this; } @@ -222,8 +194,7 @@ public class RegistryBuilder * @return this builder * @see RegistryBuilder#hasWrapper() */ - public RegistryBuilder hasTags() - { + public RegistryBuilder hasTags() { // Tag system heavily relies on Registry objects, so we need a wrapper for this registry to take advantage this.hasWrapper(); return this; @@ -232,147 +203,128 @@ public class RegistryBuilder /** * Modders: Use {@link NewRegistryEvent#create(RegistryBuilder)} instead */ - IForgeRegistry create() - { - if (hasWrapper) - { - if (getDefault() == null) - addCallback(new NamespacedWrapper.Factory()); - else - addCallback(new NamespacedDefaultedWrapper.Factory()); + IForgeRegistry create() { + if (hasWrapper) { + GameData.WrapperFactory wrapper = GameData.createWrapperFactory(getDefault() != null); + this.addCallback.add(0, wrapper); + this.createCallback.add(0, wrapper); } return RegistryManager.ACTIVE.createRegistry(registryName, this); } @Nullable - public AddCallback getAdd() - { + public AddCallback getAdd() { if (addCallback.isEmpty()) return null; if (addCallback.size() == 1) return addCallback.get(0); - return (owner, stage, id, key, obj, old) -> - { - for (AddCallback cb : this.addCallback) + var tmp = this.addCallback; + return (owner, stage, id, key, obj, old) -> { + for (var cb : tmp) cb.onAdd(owner, stage, id, key, obj, old); }; } @Nullable - public ClearCallback getClear() - { + public ClearCallback getClear() { if (clearCallback.isEmpty()) return null; if (clearCallback.size() == 1) return clearCallback.get(0); - return (owner, stage) -> - { - for (ClearCallback cb : this.clearCallback) + var tmp = this.clearCallback; + return (owner, stage) -> { + for (var cb : tmp) cb.onClear(owner, stage); }; } @Nullable - public CreateCallback getCreate() - { + public CreateCallback getCreate() { if (createCallback.isEmpty()) return null; if (createCallback.size() == 1) return createCallback.get(0); - return (owner, stage) -> - { - for (CreateCallback cb : this.createCallback) + var tmp = this.createCallback; + return (owner, stage) -> { + for (var cb : tmp) cb.onCreate(owner, stage); }; } @Nullable - public ValidateCallback getValidate() - { + public ValidateCallback getValidate() { if (validateCallback.isEmpty()) return null; if (validateCallback.size() == 1) return validateCallback.get(0); - return (owner, stage, id, key, obj) -> - { - for (ValidateCallback cb : this.validateCallback) + var tmp = this.validateCallback; + return (owner, stage, id, key, obj) -> { + for (var cb : tmp) cb.onValidate(owner, stage, id, key, obj); }; } @Nullable - public BakeCallback getBake() - { + public BakeCallback getBake() { if (bakeCallback.isEmpty()) return null; if (bakeCallback.size() == 1) return bakeCallback.get(0); - return (owner, stage) -> - { - for (BakeCallback cb : this.bakeCallback) + var tmp = this.bakeCallback; + return (owner, stage) -> { + for (var cb : tmp) cb.onBake(owner, stage); }; } @Nullable - public ResourceLocation getDefault() - { + public ResourceLocation getDefault() { return this.optionalDefaultKey; } - public int getMinId() - { + public int getMinId() { return minId; } - public int getMaxId() - { + public int getMaxId() { return maxId; } - public boolean getAllowOverrides() - { + public boolean getAllowOverrides() { return allowOverrides; } - public boolean getAllowModifications() - { + public boolean getAllowModifications() { return allowModifications; } @Nullable - public MissingFactory getMissingFactory() - { + public MissingFactory getMissingFactory() { return missingFactory; } - public boolean getSaveToDisc() - { + public boolean getSaveToDisc() { return saveToDisc; } - public boolean getSync() - { + public boolean getSync() { return sync; } - public Set getLegacyNames() - { + public Set getLegacyNames() { return legacyNames; } - Function> getIntrusiveHolderCallback() - { + Function> getIntrusiveHolderCallback() { return this.intrusiveHolderCallback; } - boolean getHasWrapper() - { + boolean getHasWrapper() { return this.hasWrapper; } } diff --git a/src/main/java/net/minecraftforge/registries/RegistryManager.java b/src/main/java/net/minecraftforge/registries/RegistryManager.java index fa8163bc32..150b910e5f 100644 --- a/src/main/java/net/minecraftforge/registries/RegistryManager.java +++ b/src/main/java/net/minecraftforge/registries/RegistryManager.java @@ -15,6 +15,7 @@ import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; import com.mojang.serialization.Lifecycle; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.WritableRegistry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; @@ -127,7 +128,7 @@ public class RegistryManager { WritableRegistry> registry = (WritableRegistry>) rootRegistry; Registry wrapper = forgeReg.getWrapper(); if (wrapper != null) - registry.register(forgeReg.getRegistryKey(), wrapper, Lifecycle.experimental()); + registry.register(forgeReg.getRegistryKey(), wrapper, RegistrationInfo.BUILT_IN); } public static void postNewRegistryEvent() { diff --git a/src/main/java/net/minecraftforge/registries/RegistryObject.java b/src/main/java/net/minecraftforge/registries/RegistryObject.java index c82013e9c9..6d5a82ffcc 100644 --- a/src/main/java/net/minecraftforge/registries/RegistryObject.java +++ b/src/main/java/net/minecraftforge/registries/RegistryObject.java @@ -175,6 +175,7 @@ public final class RegistryObject implements Supplier if (!registryExists(registryName)) { invalidRegistry = true; + registryExists(registryName); throw new IllegalStateException("Unable to find registry with key " + registryName + " for mod \"" + modid + "\". Check the 'caused by' to see further stack.", callerStack); } registryExists = true; diff --git a/src/main/java/net/minecraftforge/registries/holdersets/AndHolderSet.java b/src/main/java/net/minecraftforge/registries/holdersets/AndHolderSet.java index ea22e477a2..382d6213a5 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/AndHolderSet.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/AndHolderSet.java @@ -10,6 +10,7 @@ import java.util.Set; import java.util.stream.Collectors; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; @@ -30,38 +31,31 @@ import net.minecraftforge.common.ForgeMod; * } * */ -public class AndHolderSet extends CompositeHolderSet -{ - public static Codec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) - { +public class AndHolderSet extends CompositeHolderSet { + public static MapCodec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) { return HolderSetCodec.create(registryKey, holderCodec, forceList) .listOf() .xmap(AndHolderSet::new, CompositeHolderSet::homogenize) - .fieldOf("values") - .codec(); + .fieldOf("values"); } - - public AndHolderSet(List> values) - { + + public AndHolderSet(List> values) { super(values); } @Override - public HolderSetType type() - { + public HolderSetType type() { return ForgeMod.AND_HOLDER_SET.get(); } @Override - protected Set> createSet() - { + protected Set> createSet() { List> components = this.getComponents(); - if (components.size() < 1) - { + if (components.size() < 1) { return Set.of(); } - if (components.size() == 1) - { + + if (components.size() == 1) { return components.get(0).stream().collect(Collectors.toSet()); } @@ -73,8 +67,7 @@ public class AndHolderSet extends CompositeHolderSet } @Override - public String toString() - { + public String toString() { return "AndSet[" + this.getComponents() + "]"; } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/registries/holdersets/AnyHolderSet.java b/src/main/java/net/minecraftforge/registries/holdersets/AnyHolderSet.java index 1689264d7e..168b6e93a3 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/AnyHolderSet.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/AnyHolderSet.java @@ -14,6 +14,7 @@ import java.util.stream.Stream; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import net.minecraft.Util; import net.minecraft.core.Holder; @@ -34,54 +35,44 @@ import net.minecraftforge.common.ForgeMod; * } * */ -public record AnyHolderSet(HolderLookup.RegistryLookup registryLookup) implements ICustomHolderSet -{ - public static Codec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) - { +public record AnyHolderSet(HolderLookup.RegistryLookup registryLookup) implements ICustomHolderSet { + public static MapCodec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) { return RegistryOps.retrieveRegistryLookup(registryKey) - .xmap(AnyHolderSet::new, AnyHolderSet::registryLookup) - .codec(); + .xmap(AnyHolderSet::new, AnyHolderSet::registryLookup); } @Override - public HolderSetType type() - { + public HolderSetType type() { return ForgeMod.ANY_HOLDER_SET.get(); } @Override - public Iterator> iterator() - { + public Iterator> iterator() { return this.stream().iterator(); } @Override - public Stream> stream() - { + public Stream> stream() { return this.registryLookup.listElements().map(Function.identity()); } @Override - public int size() - { - return (int) this.stream().count(); + public int size() { + return (int)this.stream().count(); } @Override - public Either, List>> unwrap() - { + public Either, List>> unwrap() { return Either.right(this.stream().toList()); } @Override - public Optional> getRandomElement(RandomSource random) - { + public Optional> getRandomElement(RandomSource random) { return Util.getRandomSafe(this.stream().toList(), random); } @Override - public Holder get(int i) - { + public Holder get(int i) { List> holders = this.stream().toList(); Holder holder = i >= holders.size() ? null : holders.get(i); if (holder == null) @@ -91,26 +82,22 @@ public record AnyHolderSet(HolderLookup.RegistryLookup registryLookup) imp } @Override - public boolean contains(Holder holder) - { + public boolean contains(Holder holder) { return holder.unwrapKey().map(key -> this.registryLookup.listElementIds().anyMatch(key::equals)).orElse(false); } @Override - public boolean canSerializeIn(HolderOwner holderOwner) - { + public boolean canSerializeIn(HolderOwner holderOwner) { return this.registryLookup.canSerializeIn(holderOwner); } @Override - public Optional> unwrapKey() - { + public Optional> unwrapKey() { return Optional.empty(); } @Override - public String toString() - { + public String toString() { return "AnySet(" + this.registryLookup.key() + ")"; } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/registries/holdersets/HolderSetType.java b/src/main/java/net/minecraftforge/registries/holdersets/HolderSetType.java index 80df39e494..1fe684daff 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/HolderSetType.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/HolderSetType.java @@ -6,6 +6,7 @@ package net.minecraftforge.registries.holdersets; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -13,5 +14,5 @@ import net.minecraft.resources.ResourceKey; @FunctionalInterface public interface HolderSetType { - Codec> makeCodec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList); + MapCodec> makeCodec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList); } diff --git a/src/main/java/net/minecraftforge/registries/holdersets/ICustomHolderSet.java b/src/main/java/net/minecraftforge/registries/holdersets/ICustomHolderSet.java index 9f33348a65..f19b28d389 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/ICustomHolderSet.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/ICustomHolderSet.java @@ -10,16 +10,14 @@ import net.minecraft.core.HolderSet; /** * Interface for mods' custom holderset types */ -public interface ICustomHolderSet extends HolderSet -{ +public interface ICustomHolderSet extends HolderSet { /** * {@return HolderSetType registered to {@link ForgeRegistries.HOLDER_SET_TYPES}} */ HolderSetType type(); @Override - default SerializationType serializationType() - { + default SerializationType serializationType() { return SerializationType.OBJECT; } } diff --git a/src/main/java/net/minecraftforge/registries/holdersets/NotHolderSet.java b/src/main/java/net/minecraftforge/registries/holdersets/NotHolderSet.java index fe810a1e2a..ba727ebb1d 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/NotHolderSet.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/NotHolderSet.java @@ -11,13 +11,13 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; -import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderOwner; import org.jetbrains.annotations.Nullable; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.Holder; @@ -42,11 +42,9 @@ import net.minecraftforge.common.ForgeMod; * */ // this doesn't extend CompositeHolderSet because it doesn't need to cache a set -public class NotHolderSet implements ICustomHolderSet -{ - public static Codec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) - { - return RecordCodecBuilder.>create(builder -> builder.group( +public class NotHolderSet implements ICustomHolderSet { + public static MapCodec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) { + return RecordCodecBuilder.>mapCodec(builder -> builder.group( RegistryOps.retrieveRegistryLookup(registryKey).forGetter(NotHolderSet::registryLookup), HolderSetCodec.create(registryKey, holderCodec, forceList).fieldOf("value").forGetter(NotHolderSet::value) ).apply(builder, NotHolderSet::new)); @@ -58,55 +56,52 @@ public class NotHolderSet implements ICustomHolderSet @Nullable private List> list = null; - public HolderLookup.RegistryLookup registryLookup() { return this.registryLookup; } - public HolderSet value() { return this.value; } - - public NotHolderSet(HolderLookup.RegistryLookup registryLookup, HolderSet value) - { + public NotHolderSet(HolderLookup.RegistryLookup registryLookup, HolderSet value) { this.registryLookup = registryLookup; this.value = value; this.value.addInvalidationListener(this::invalidate); } + public HolderLookup.RegistryLookup registryLookup() { + return this.registryLookup; + } + + public HolderSet value() { + return this.value; + } + @Override - public HolderSetType type() - { + public HolderSetType type() { return ForgeMod.NOT_HOLDER_SET.get(); } @Override - public void addInvalidationListener(Runnable runnable) - { + public void addInvalidationListener(Runnable runnable) { this.owners.add(runnable); } @Override - public Iterator> iterator() - { + public Iterator> iterator() { return this.getList().iterator(); } @Override - public Stream> stream() - { + public Stream> stream() { return this.getList().stream(); } @Override - public int size() - { + public int size() { return this.getList().size(); } @Override - public Either, List>> unwrap() - { + public Either, List>> unwrap() { return Either.right(this.getList()); } @Override - public Optional> getRandomElement(RandomSource random) - { + public Optional> getRandomElement(RandomSource random) { List> list = this.getList(); int size = list.size(); return size > 0 @@ -115,58 +110,47 @@ public class NotHolderSet implements ICustomHolderSet } @Override - public Holder get(int i) - { + public Holder get(int i) { return this.getList().get(i); } @Override - public boolean contains(Holder holder) - { + public boolean contains(Holder holder) { return !this.value.contains(holder); } @Override - public boolean canSerializeIn(HolderOwner holderOwner) - { + public boolean canSerializeIn(HolderOwner holderOwner) { return this.registryLookup.canSerializeIn(holderOwner); } @Override - public Optional> unwrapKey() - { + public Optional> unwrapKey() { return Optional.empty(); } @Override - public String toString() - { + public String toString() { return "NotSet(" + this.value + ")"; } - private List> getList() - { + private List> getList() { List> thisList = this.list; - if (thisList == null) - { + if (thisList == null) { List> list = this.registryLookup.listElements() .filter(holder -> !this.value.contains(holder)) .map(holder -> (Holder)holder) .toList(); this.list = list; return list; - } - else - { + } else { return thisList; } } - private void invalidate() - { + private void invalidate() { this.list = null; - for (Runnable runnable : this.owners) - { + for (Runnable runnable : this.owners) { runnable.run(); } } diff --git a/src/main/java/net/minecraftforge/registries/holdersets/OrHolderSet.java b/src/main/java/net/minecraftforge/registries/holdersets/OrHolderSet.java index 3d87005ce1..3ffd6762ac 100644 --- a/src/main/java/net/minecraftforge/registries/holdersets/OrHolderSet.java +++ b/src/main/java/net/minecraftforge/registries/holdersets/OrHolderSet.java @@ -10,9 +10,9 @@ import java.util.Set; import java.util.stream.Collectors; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import net.minecraft.core.Holder; -import net.minecraft.core.HolderOwner; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.resources.HolderSetCodec; @@ -31,37 +31,30 @@ import net.minecraftforge.common.ForgeMod; * } * */ -public class OrHolderSet extends CompositeHolderSet -{ - public static Codec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) - { +public class OrHolderSet extends CompositeHolderSet { + public static MapCodec> codec(ResourceKey> registryKey, Codec> holderCodec, boolean forceList) { return HolderSetCodec.create(registryKey, holderCodec, forceList) .listOf() .xmap(OrHolderSet::new, CompositeHolderSet::homogenize) - .fieldOf("values") - .codec(); + .fieldOf("values"); } - public OrHolderSet(List> values) - { + public OrHolderSet(List> values) { super(values); } @Override - public HolderSetType type() - { + public HolderSetType type() { return ForgeMod.OR_HOLDER_SET.get(); } @Override - protected Set> createSet() - { + protected Set> createSet() { return this.getComponents().stream().flatMap(HolderSet::stream).collect(Collectors.toSet()); } @Override - public String toString() - { + public String toString() { return "OrSet[" + this.getComponents() + "]"; } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java b/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java index 3500b6dd9e..e2ab43633f 100644 --- a/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java +++ b/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java @@ -18,12 +18,13 @@ import java.util.Map; import java.util.Set; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.AbstractPackResources; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.metadata.MetadataSectionSerializer; import net.minecraft.server.packs.metadata.pack.PackMetadataSection; import net.minecraft.server.packs.repository.Pack; -import net.minecraft.server.packs.repository.Pack.Info; +import net.minecraft.server.packs.repository.Pack.Metadata; import net.minecraft.server.packs.resources.IoSupplier; import org.jetbrains.annotations.ApiStatus; @@ -36,8 +37,8 @@ public class DelegatingPackResources extends AbstractPackResources { private final Map> namespacesAssets; private final Map> namespacesData; - public DelegatingPackResources(String packId, boolean isBuiltin, PackMetadataSection packMeta, List packs) { - super(packId, isBuiltin); + public DelegatingPackResources(PackLocationInfo info, PackMetadataSection packMeta, List packs) { + super(info); this.packMeta = packMeta; this.delegates = ImmutableList.copyOf(packs); this.namespacesAssets = this.buildNamespaceMap(PackType.CLIENT_RESOURCES, delegates); @@ -114,12 +115,12 @@ public class DelegatingPackResources extends AbstractPackResources { private class Supplier implements Pack.ResourcesSupplier { @Override - public PackResources openPrimary(String path) { + public PackResources openPrimary(PackLocationInfo p_332103_) { return DelegatingPackResources.this; } @Override - public PackResources openFull(String path, Info info) { + public PackResources openFull(PackLocationInfo p_330351_, Metadata p_333429_) { return DelegatingPackResources.this; } } diff --git a/src/main/java/net/minecraftforge/resource/PathPackResources.java b/src/main/java/net/minecraftforge/resource/PathPackResources.java deleted file mode 100644 index 4d6c92658d..0000000000 --- a/src/main/java/net/minecraftforge/resource/PathPackResources.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.resource; - -import com.mojang.logging.LogUtils; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import net.minecraft.FileUtil; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.AbstractPackResources; -import net.minecraft.server.packs.PackType; -import net.minecraft.server.packs.resources.IoSupplier; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; - -/** - * Defines a resource pack from an arbitrary Path. - *

- * This is primarily intended to support including optional resource packs inside a mod, - * such as to have alternative textures to use along with Programmer Art, or optional - * alternative recipes for compatibility to to replace vanilla recipes. - */ -public class PathPackResources extends AbstractPackResources { - private static final Logger LOGGER = LogUtils.getLogger(); - private final Path source; - - /** - * Constructs a java.nio.Path-based resource pack. - * - * @param packId the identifier of the pack. - * This identifier should be unique within the pack finder, preferably the name of the file or folder containing the resources. - * @param isBuiltin whether this pack resources should be considered builtin - * @param source the root path of the pack. This needs to point to the folder that contains "assets" and/or "data", not the asset folder itself! - */ - public PathPackResources(String packId, boolean isBuiltin, final Path source) { - super(packId, isBuiltin); - this.source = source; - } - - /** - * Returns the source path containing the resource pack. - * This is used for error display. - * - * @return the root path of the resources. - */ - public Path getSource() { - return this.source; - } - - /** - * Implement to return a file or folder path for the given set of path components. - * - * @param paths One or more path strings to resolve. Can include slash-separated paths. - * @return the resulting path, which may not exist. - */ - protected Path resolve(String... paths) { - Path path = getSource(); - for (String name : paths) - path = path.resolve(name); - return path; - } - - @Nullable - @Override - public IoSupplier getRootResource(String... paths) { - final Path path = resolve(paths); - if (!Files.exists(path)) - return null; - - return IoSupplier.create(path); - } - - @Override - public void listResources(PackType type, String namespace, String path, ResourceOutput resourceOutput) { - FileUtil.decomposePath(path).get() - .ifLeft(parts -> net.minecraft.server.packs.PathPackResources.listPath(namespace, resolve(type.getDirectory(), namespace).toAbsolutePath(), parts, resourceOutput)) - .ifRight(dataResult -> LOGGER.error("Invalid path {}: {}", path, dataResult.message())); - } - - @Override - public Set getNamespaces(PackType type) { - return getNamespacesFromDisk(type); - } - - @NotNull - private Set getNamespacesFromDisk(final PackType type) { - try { - Path root = resolve(type.getDirectory()); - try (Stream walker = Files.walk(root, 1)) { - return walker - .filter(Files::isDirectory) - .map(root::relativize) - .filter(p -> p.getNameCount() > 0) // Skip the root entry - .map(p -> p.toString().replaceAll("/$", "")) // Remove the trailing slash, if present - .filter(s -> !s.isEmpty()) // Filter empty strings, otherwise empty strings default to minecraft namespace in ResourceLocations - .collect(Collectors.toSet()); - } - } catch (IOException e) { - if (type == PackType.SERVER_DATA) // We still have to add the resource namespace if client resources exist, as we load langs (which are in assets) on server - return this.getNamespaces(PackType.CLIENT_RESOURCES); - else - return Collections.emptySet(); - } - } - - @Override - public IoSupplier getResource(PackType type, ResourceLocation location) { - return this.getRootResource(getPathFromLocation(location.getPath().startsWith("lang/") ? PackType.CLIENT_RESOURCES : type, location)); - } - - private static String[] getPathFromLocation(PackType type, ResourceLocation location) { - String[] parts = location.getPath().split("/"); - String[] result = new String[parts.length + 2]; - result[0] = type.getDirectory(); - result[1] = location.getNamespace(); - System.arraycopy(parts, 0, result, 2, parts.length); - return result; - } - - @Override - public void close() { } - - @Override - public String toString() { - return String.format(Locale.ROOT, "%s: %s (%s)", getClass().getName(), this.packId(), getSource()); - } -} diff --git a/src/main/java/net/minecraftforge/resource/ResourcePackLoader.java b/src/main/java/net/minecraftforge/resource/ResourcePackLoader.java index c97822701a..f5b717642f 100644 --- a/src/main/java/net/minecraftforge/resource/ResourcePackLoader.java +++ b/src/main/java/net/minecraftforge/resource/ResourcePackLoader.java @@ -16,12 +16,16 @@ import java.util.stream.Collectors; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.minecraft.server.packs.repository.Pack.Info; +import net.minecraft.server.packs.repository.Pack.Metadata; +import net.minecraft.server.packs.repository.Pack.Position; import net.minecraft.SharedConstants; import net.minecraft.network.chat.Component; import net.minecraft.server.packs.CompositePackResources; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackResources; +import net.minecraft.server.packs.PackSelectionConfig; import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.PathPackResources; import net.minecraft.server.packs.metadata.pack.PackMetadataSection; import net.minecraft.server.packs.repository.Pack; import net.minecraft.server.packs.repository.PackRepository; @@ -47,60 +51,6 @@ public class ResourcePackLoader { resourcePacks.addPackFinder(repo -> findPacks(repo, client)); } - @NotNull - public static PathPackResources createPackForMod(IModFileInfo mf) { - return new ModPathPackResources(mf.getFile()); - } - - private static class ModPathPackResources extends PathPackResources { - private final IModFile mod; - private final String[] prefix; - - private ModPathPackResources(IModFile mod, String... prefix) { - super(mod.getFileName(), true, mod.getFilePath()); - this.mod = mod; - this.prefix = prefix; - } - - @NotNull - @Override - protected Path resolve(@NotNull String... paths) { - if (prefix != null && prefix.length > 0) { - var tmp = new String[prefix.length + paths.length]; - System.arraycopy(prefix, 0, tmp, 0, prefix.length); - System.arraycopy(paths, 0, tmp, prefix.length, paths.length); - return this.mod.findResource(tmp); - } - return this.mod.findResource(paths); - } - - private static class Supplier implements Pack.ResourcesSupplier { - private final IModFile mod; - - private Supplier(IModFile mod) { - this.mod = mod; - } - - @Override - public PackResources openPrimary(String packId) { - return new ModPathPackResources(mod); - } - - @Override - public PackResources openFull(String packId, Info info) { - var primary = openPrimary(packId); - if (info.overlays().isEmpty()) - return primary; - - var lst = new ArrayList(info.overlays().size()); - for (var overlay : info.overlays()) - lst.add(new ModPathPackResources(mod, overlay)); - - return new CompositePackResources(primary, lst); - } - } - } - public static List getPackNames() { return ModList.get().applyForEachModFile(mf->"mod:"+mf.getModInfos().get(0).getModId()).filter(n->!n.equals("mod:minecraft")).collect(Collectors.toList()); } @@ -145,14 +95,16 @@ public class ResourcePackLoader { var file = mod.getFile(); - var supplier = new ModPathPackResources.Supplier(file); + var root = file.findResource(""); + var supplier = new PathPackResources.PathResourcesSupplier(root); var modinfo = file.getModInfos().get(0); var name = "mod:" + modinfo.getModId(); - var meta = Pack.readPackInfo(name, supplier, version); + var info = new PackLocationInfo(name, Component.literal(file.getFileName()), PackSource.DEFAULT, Optional.empty()); + var meta = Pack.readPackMetadata(info, supplier, version); Pack pack = null; if (meta != null) - pack = Pack.create(name, Component.literal(file.getFileName()), false, supplier, meta, Pack.Position.BOTTOM, false, PackSource.DEFAULT); + pack = new Pack(info, supplier, meta, new PackSelectionConfig(false, Position.BOTTOM, false)); if (pack == null) { // Vanilla only logs an error, instead of propagating, so handle null and warn that something went wrong @@ -168,8 +120,9 @@ public class ResourcePackLoader { } if (!hiddenPacks.isEmpty()) { + var info = new PackLocationInfo("mod_resources", Component.translatable("fml.resources.modresources", hiddenPacks.size()), PackSource.DEFAULT, Optional.empty()); @SuppressWarnings("resource") - var delegating = new DelegatingPackResources("mod_resources", false, + var delegating = new DelegatingPackResources(info, new PackMetadataSection( Component.translatable("fml.resources.modresources", hiddenPacks.size()), version, @@ -181,7 +134,9 @@ public class ResourcePackLoader { var supplier = delegating.supplier(); // Create a resource pack merging all mod resources that should be hidden - var modResourcesPack = Pack.readMetaAndCreate("mod_resources", Component.literal("Mod Resources"), true, supplier, type, Pack.Position.BOTTOM, PackSource.DEFAULT); + var wrapper = new PackLocationInfo("mod_resources", Component.literal("Mod Resources"), PackSource.DEFAULT, Optional.empty()); + var wrapperCfg = new PackSelectionConfig(true, Position.BOTTOM, false); + var modResourcesPack = Pack.readMetaAndCreate(wrapper, supplier, type, wrapperCfg); packAcceptor.accept(modResourcesPack); } } diff --git a/src/main/java/net/minecraftforge/server/LanguageHook.java b/src/main/java/net/minecraftforge/server/LanguageHook.java index 03d4da956d..b7aa3e5867 100644 --- a/src/main/java/net/minecraftforge/server/LanguageHook.java +++ b/src/main/java/net/minecraftforge/server/LanguageHook.java @@ -8,7 +8,6 @@ package net.minecraftforge.server; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.minecraft.locale.Language; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.MinecraftServer; @@ -19,7 +18,6 @@ import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -32,16 +30,16 @@ public class LanguageHook private static final Logger LOGGER = LogManager.getLogger(); private static final Gson GSON = new Gson(); private static final Pattern PATTERN = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); - private static List> capturedTables = new ArrayList<>(2); + private static final List> CAPTURED_TABLES = new ArrayList<>(); private static Map modTable; /** * Loads lang files on the server */ public static void captureLanguageMap(Map table) { - capturedTables.add(table); + CAPTURED_TABLES.add(table); if (modTable != null) { - capturedTables.forEach(t->t.putAll(modTable)); + CAPTURED_TABLES.forEach(t->t.putAll(modTable)); } } @@ -91,7 +89,7 @@ public class LanguageHook final InputStream forge = Thread.currentThread().getContextClassLoader().getResourceAsStream("assets/forge/lang/en_us.json"); loadLocaleData(mc); loadLocaleData(forge); - capturedTables.forEach(t->t.putAll(modTable)); + CAPTURED_TABLES.forEach(t->t.putAll(modTable)); ForgeI18n.loadLanguageData(modTable); } @@ -101,7 +99,7 @@ public class LanguageHook for (String lang : Arrays.asList("en_us")) { loadLanguage(lang, server); } - capturedTables.forEach(t->t.putAll(modTable)); + CAPTURED_TABLES.forEach(t->t.putAll(modTable)); ForgeI18n.loadLanguageData(modTable); } } diff --git a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java index 174f858c99..06525a1560 100644 --- a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java +++ b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java @@ -162,7 +162,7 @@ public class ServerLifecycleHooks { if (!allowLogins.get()) return rejectConnection(connection, ctx.getType(), "Server is still starting! Please wait before reconnecting."); - if (packet.nextProtocol() != ConnectionProtocol.LOGIN) + if (packet.intention() != ClientIntent.LOGIN) return true; if (ctx.getType() == ConnectionType.MODDED && ctx.getNetVersion() != NetworkContext.NET_VERSION) @@ -176,7 +176,7 @@ public class ServerLifecycleHooks { } private static boolean rejectConnection(final Connection connection, ConnectionType type, String message) { - connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN); + //connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN); LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", connection.getLoggableAddress(true), type, message); // TODO: Respect logIP setting var text = Component.literal(message); connection.send(new ClientboundLoginDisconnectPacket(text)); diff --git a/src/main/java/net/minecraftforge/server/command/ChunkGenWorker.java b/src/main/java/net/minecraftforge/server/command/ChunkGenWorker.java index b0c2a350b7..778c7c8d74 100644 --- a/src/main/java/net/minecraftforge/server/command/ChunkGenWorker.java +++ b/src/main/java/net/minecraftforge/server/command/ChunkGenWorker.java @@ -13,8 +13,8 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraftforge.common.WorldWorkerManager.IWorker; public class ChunkGenWorker implements IWorker diff --git a/src/main/java/net/minecraftforge/server/command/CommandHelper.java b/src/main/java/net/minecraftforge/server/command/CommandHelper.java index 77e010bcea..c94d1f33d2 100644 --- a/src/main/java/net/minecraftforge/server/command/CommandHelper.java +++ b/src/main/java/net/minecraftforge/server/command/CommandHelper.java @@ -25,11 +25,8 @@ import java.util.function.Function; * * @hidden */ -public final class CommandHelper -{ - private CommandHelper() - { - } +public final class CommandHelper { + private CommandHelper() { } /** * Deep copies the children of a command node and stores a link between the source and the copy @@ -42,13 +39,10 @@ public final class CommandHelper * @param sourceToResultSuggestion a function to convert from the {@link SuggestionProvider} with the original source stack to the {@link SuggestionProvider} with the result source stack */ public static void mergeCommandNode(CommandNode sourceNode, CommandNode resultNode, Map, CommandNode> sourceToResult, - S canUse, Command execute, Function, SuggestionProvider> sourceToResultSuggestion) - { + S canUse, Command execute, Function, SuggestionProvider> sourceToResultSuggestion) { sourceToResult.put(sourceNode, resultNode); - for (CommandNode sourceChild : sourceNode.getChildren()) - { - if (sourceChild.canUse(canUse)) - { + for (CommandNode sourceChild : sourceNode.getChildren()) { + if (sourceChild.canUse(canUse)) { resultNode.addChild(toResult(sourceChild, sourceToResult, canUse, execute, sourceToResultSuggestion)); } } @@ -65,42 +59,33 @@ public final class CommandHelper * @return the deep copied command node with the new source stack */ private static CommandNode toResult(CommandNode sourceNode, Map, CommandNode> sourceToResult, S canUse, Command execute, - Function, SuggestionProvider> sourceToResultSuggestion) - { - if (sourceToResult.containsKey(sourceNode)) + Function, SuggestionProvider> sourceToResultSuggestion) { + if (sourceToResult.containsKey(sourceNode)) { return sourceToResult.get(sourceNode); + } ArgumentBuilder resultBuilder; - if (sourceNode instanceof ArgumentCommandNode) - { - ArgumentCommandNode sourceArgument = (ArgumentCommandNode) sourceNode; + if (sourceNode instanceof ArgumentCommandNode sourceArgument) { RequiredArgumentBuilder resultArgumentBuilder = RequiredArgumentBuilder.argument(sourceArgument.getName(), sourceArgument.getType()); - if (sourceArgument.getCustomSuggestions() != null) - { + if (sourceArgument.getCustomSuggestions() != null) { resultArgumentBuilder.suggests(sourceToResultSuggestion.apply(sourceArgument.getCustomSuggestions())); } resultBuilder = resultArgumentBuilder; - } else if (sourceNode instanceof LiteralCommandNode) - { - LiteralCommandNode sourceLiteral = (LiteralCommandNode) sourceNode; + } else if (sourceNode instanceof LiteralCommandNode sourceLiteral) { resultBuilder = LiteralArgumentBuilder.literal(sourceLiteral.getLiteral()); - } else if (sourceNode instanceof RootCommandNode) - { + } else if (sourceNode instanceof RootCommandNode) { CommandNode resultNode = new RootCommandNode<>(); mergeCommandNode(sourceNode, resultNode, sourceToResult, canUse, execute, sourceToResultSuggestion); return resultNode; - } else - { + } else { throw new IllegalStateException("Node type " + sourceNode + " is not a standard node type"); } - if (sourceNode.getCommand() != null) - { + if (sourceNode.getCommand() != null) { resultBuilder.executes(execute); } - if (sourceNode.getRedirect() != null) - { + if (sourceNode.getRedirect() != null) { resultBuilder.redirect(toResult(sourceNode.getRedirect(), sourceToResult, canUse, execute, sourceToResultSuggestion)); } diff --git a/src/main/java/net/minecraftforge/server/command/TPSCommand.java b/src/main/java/net/minecraftforge/server/command/TPSCommand.java index ed6cc372ec..f7b593621c 100644 --- a/src/main/java/net/minecraftforge/server/command/TPSCommand.java +++ b/src/main/java/net/minecraftforge/server/command/TPSCommand.java @@ -53,7 +53,7 @@ class TPSCommand final Registry reg = cs.registryAccess().registryOrThrow(Registries.DIMENSION_TYPE); double worldTickTime = mean(times) * 1.0E-6D; double worldTPS = Math.min(1000.0 / worldTickTime, 20); - cs.sendSuccess(() -> Component.translatable("commands.forge.tps.summary.named", dim.dimension().location().toString(), reg.getKey(dim.dimensionType()), TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)), false); + cs.sendSuccess(() -> Component.translatable("commands.forge.tps.summary.named", dim.dimension().location().toString(), reg.getKey(dim.dimensionType()).toString(), TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)), false); return 1; } diff --git a/src/main/java/net/minecraftforge/server/command/TagsCommand.java b/src/main/java/net/minecraftforge/server/command/TagsCommand.java index 63f6c096c5..f565459874 100644 --- a/src/main/java/net/minecraftforge/server/command/TagsCommand.java +++ b/src/main/java/net/minecraftforge/server/command/TagsCommand.java @@ -158,7 +158,7 @@ class TagsCommand return tag.size(); } - private static int queryElementTags(final CommandContext ctx, final int page) throws CommandSyntaxException + private static int queryElementTags(final CommandContext ctx, final int page) throws CommandSyntaxException { final ResourceKey> registryKey = getResourceKey(ctx, "registry", ROOT_REGISTRY_KEY) .orElseThrow(); // Expect to be always retrieve a resource key for the root registry (registry key) @@ -168,7 +168,7 @@ class TagsCommand final ResourceLocation elementLocation = ResourceLocationArgument.getId(ctx, "element"); final ResourceKey elementKey = ResourceKey.create(cast(registryKey), elementLocation); - final Holder elementHolder = registry.getHolder(cast(elementKey)) + final Holder elementHolder = ((Registry)registry).getHolder((ResourceKey)elementKey) .orElseThrow(() -> UNKNOWN_ELEMENT.create(elementLocation, registryKey.location())); final long containingTagsCount = elementHolder.tags().count(); diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 9da0a063df..38a39df7e7 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -4,96 +4,6 @@ public net.minecraft.client.Minecraft f_90987_ # textureManager public net.minecraft.client.Minecraft m_91271_()V # createSearchTrees public-f net.minecraft.client.Options f_92059_ # keyMappings public net.minecraft.client.Options$FieldAccess -#group protected net.minecraft.client.gui.Gui * -protected net.minecraft.client.gui.Gui f_168664_ # scopeScale -protected net.minecraft.client.gui.Gui f_168665_ # SPYGLASS_SCOPE_LOCATION -protected net.minecraft.client.gui.Gui f_168666_ # POWDER_SNOW_OUTLINE_LOCATION -protected net.minecraft.client.gui.Gui f_168667_ # COLOR_WHITE -protected net.minecraft.client.gui.Gui f_168668_ # MIN_CROSSHAIR_ATTACK_SPEED -protected net.minecraft.client.gui.Gui f_168669_ # NUM_HEARTS_PER_ROW -protected net.minecraft.client.gui.Gui f_168670_ # LINE_HEIGHT -protected net.minecraft.client.gui.Gui f_168671_ # SPACER -protected net.minecraft.client.gui.Gui f_168672_ # PORTAL_OVERLAY_ALPHA_MIN -protected net.minecraft.client.gui.Gui f_168673_ # HEART_SIZE -protected net.minecraft.client.gui.Gui f_168674_ # HEART_SEPARATION -protected net.minecraft.client.gui.Gui f_193828_ # autosaveIndicatorValue -protected net.minecraft.client.gui.Gui f_193829_ # lastAutosaveIndicatorValue -protected net.minecraft.client.gui.Gui f_193830_ # SAVING_TEXT -protected net.minecraft.client.gui.Gui f_193831_ # AUTOSAVE_FADE_SPEED_FACTOR -protected net.minecraft.client.gui.Gui f_238167_ # chatDisabledByPlayerShown -protected net.minecraft.client.gui.Gui f_290334_ # HEART_VEHICLE_HALF_SPRITE -protected net.minecraft.client.gui.Gui f_290366_ # FOOD_FULL_HUNGER_SPRITE -protected net.minecraft.client.gui.Gui f_290368_ # HOTBAR_SELECTION_SPRITE -protected net.minecraft.client.gui.Gui f_290436_ # ARMOR_FULL_SPRITE -protected net.minecraft.client.gui.Gui f_290513_ # EFFECT_BACKGROUND_SPRITE -protected net.minecraft.client.gui.Gui f_290694_ # FOOD_EMPTY_SPRITE -protected net.minecraft.client.gui.Gui f_290711_ # CROSSHAIR_ATTACK_INDICATOR_PROGRESS_SPRITE -protected net.minecraft.client.gui.Gui f_290833_ # HOTBAR_ATTACK_INDICATOR_BACKGROUND_SPRITE -protected net.minecraft.client.gui.Gui f_290939_ # HEART_VEHICLE_CONTAINER_SPRITE -protected net.minecraft.client.gui.Gui f_291002_ # FOOD_HALF_SPRITE -protected net.minecraft.client.gui.Gui f_291104_ # JUMP_BAR_COOLDOWN_SPRITE -protected net.minecraft.client.gui.Gui f_291149_ # HOTBAR_SPRITE -protected net.minecraft.client.gui.Gui f_291256_ # HEART_VEHICLE_FULL_SPRITE -protected net.minecraft.client.gui.Gui f_291301_ # HOTBAR_ATTACK_INDICATOR_PROGRESS_SPRITE -protected net.minecraft.client.gui.Gui f_291320_ # debugOverlay -protected net.minecraft.client.gui.Gui f_291322_ # HOTBAR_OFFHAND_LEFT_SPRITE -protected net.minecraft.client.gui.Gui f_291360_ # CROSSHAIR_ATTACK_INDICATOR_BACKGROUND_SPRITE -protected net.minecraft.client.gui.Gui f_291363_ # CROSSHAIR_ATTACK_INDICATOR_FULL_SPRITE -protected net.minecraft.client.gui.Gui f_291473_ # EFFECT_BACKGROUND_AMBIENT_SPRITE -protected net.minecraft.client.gui.Gui f_291483_ # JUMP_BAR_BACKGROUND_SPRITE -protected net.minecraft.client.gui.Gui f_291486_ # FOOD_EMPTY_HUNGER_SPRITE -protected net.minecraft.client.gui.Gui f_291491_ # EXPERIENCE_BAR_PROGRESS_SPRITE -protected net.minecraft.client.gui.Gui f_291577_ # FOOD_HALF_HUNGER_SPRITE -protected net.minecraft.client.gui.Gui f_291609_ # AIR_BURSTING_SPRITE -protected net.minecraft.client.gui.Gui f_291650_ # FOOD_FULL_SPRITE -protected net.minecraft.client.gui.Gui f_291741_ # EXPERIENCE_BAR_BACKGROUND_SPRITE -protected net.minecraft.client.gui.Gui f_291785_ # ARMOR_HALF_SPRITE -protected net.minecraft.client.gui.Gui f_291820_ # JUMP_BAR_PROGRESS_SPRITE -protected net.minecraft.client.gui.Gui f_291829_ # CROSSHAIR_SPRITE -protected net.minecraft.client.gui.Gui f_291833_ # AIR_SPRITE -protected net.minecraft.client.gui.Gui f_291864_ # HOTBAR_OFFHAND_RIGHT_SPRITE -protected net.minecraft.client.gui.Gui f_291879_ # ARMOR_EMPTY_SPRITE -protected net.minecraft.client.gui.Gui f_302813_ # SCORE_DISPLAY_ORDER -protected net.minecraft.client.gui.Gui f_92970_ # titleFadeInTime -protected net.minecraft.client.gui.Gui f_92971_ # titleStayTime -protected net.minecraft.client.gui.Gui f_92972_ # titleFadeOutTime -protected net.minecraft.client.gui.Gui f_92973_ # lastHealth -protected net.minecraft.client.gui.Gui f_92974_ # displayHealth -protected net.minecraft.client.gui.Gui f_92975_ # lastHealthTime -protected net.minecraft.client.gui.Gui f_92976_ # healthBlinkTime -protected net.minecraft.client.gui.Gui f_92977_ # screenWidth -protected net.minecraft.client.gui.Gui f_92978_ # screenHeight -protected net.minecraft.client.gui.Gui f_92981_ # VIGNETTE_LOCATION -protected net.minecraft.client.gui.Gui f_92983_ # PUMPKIN_BLUR_LOCATION -protected net.minecraft.client.gui.Gui f_92984_ # DEMO_EXPIRED_TEXT -protected net.minecraft.client.gui.Gui f_92985_ # random -protected net.minecraft.client.gui.Gui f_92986_ # minecraft -protected net.minecraft.client.gui.Gui f_92987_ # itemRenderer -protected net.minecraft.client.gui.Gui f_92988_ # chat -protected net.minecraft.client.gui.Gui f_92989_ # tickCount -protected net.minecraft.client.gui.Gui f_92990_ # overlayMessageString -protected net.minecraft.client.gui.Gui f_92991_ # overlayMessageTime -protected net.minecraft.client.gui.Gui f_92992_ # animateOverlayMessageColor -protected net.minecraft.client.gui.Gui f_92993_ # toolHighlightTimer -protected net.minecraft.client.gui.Gui f_92994_ # lastToolHighlight -protected net.minecraft.client.gui.Gui f_92996_ # subtitleOverlay -protected net.minecraft.client.gui.Gui f_92997_ # spectatorGui -protected net.minecraft.client.gui.Gui f_92998_ # tabList -protected net.minecraft.client.gui.Gui f_92999_ # bossOverlay -protected net.minecraft.client.gui.Gui f_93000_ # titleTime -protected net.minecraft.client.gui.Gui f_93001_ # title -protected net.minecraft.client.gui.Gui f_93002_ # subtitle -#endgroup -protected net.minecraft.client.gui.Gui m_168688_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/entity/player/Player;IIIIFIIIZ)V # renderHearts -public net.minecraft.client.gui.Gui m_280030_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/scores/Objective;)V # displayScoreboardSidebar -public net.minecraft.client.gui.Gui m_280130_(Lnet/minecraft/client/gui/GuiGraphics;)V # renderCrosshair -public net.minecraft.client.gui.Gui m_280154_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/entity/Entity;)V # renderVignette -protected net.minecraft.client.gui.Gui m_280155_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/resources/ResourceLocation;F)V # renderTextureOverlay -public net.minecraft.client.gui.Gui m_280278_(Lnet/minecraft/client/gui/GuiGraphics;F)V # renderSpyglassOverlay -protected net.minecraft.client.gui.Gui m_280379_(Lnet/minecraft/client/gui/GuiGraphics;F)V # renderPortalOverlay -public net.minecraft.client.gui.Gui m_280518_(FLnet/minecraft/client/gui/GuiGraphics;)V # renderHotbar -public net.minecraft.client.gui.Gui m_280523_(Lnet/minecraft/client/gui/GuiGraphics;)V # renderEffects -protected net.minecraft.client.gui.Gui m_93039_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/client/gui/Font;III)V # drawBackdrop protected net.minecraft.client.gui.components.AbstractButton f_290895_ # SPRITES protected net.minecraft.client.gui.components.AbstractSelectionList$Entry f_93521_ # list protected net.minecraft.client.gui.components.AbstractSliderButton m_293290_()Lnet/minecraft/resources/ResourceLocation; # getHandleSprite @@ -107,10 +17,6 @@ public net.minecraft.client.gui.screens.Screen f_169369_ # renderables public net.minecraft.client.model.geom.LayerDefinitions f_171106_ # OUTER_ARMOR_DEFORMATION public net.minecraft.client.model.geom.LayerDefinitions f_171107_ # INNER_ARMOR_DEFORMATION public net.minecraft.client.multiplayer.ClientPacketListener f_104899_ # commands -public net.minecraft.client.particle.FireworkParticles$Starter m_106767_(DDDDDD[I[IZZ)V # createParticle -public net.minecraft.client.particle.FireworkParticles$Starter m_106778_(DI[I[IZZ)V # createParticleBall -public net.minecraft.client.particle.FireworkParticles$Starter m_106785_(D[[D[I[IZZZ)V # createParticleShape -public net.minecraft.client.particle.FireworkParticles$Starter m_106793_([I[IZZ)V # createParticleBurst public net.minecraft.client.particle.ParticleEngine m_107378_(Lnet/minecraft/core/particles/ParticleType;Lnet/minecraft/client/particle/ParticleEngine$SpriteParticleRegistration;)V # register public net.minecraft.client.particle.ParticleEngine m_107381_(Lnet/minecraft/core/particles/ParticleType;Lnet/minecraft/client/particle/ParticleProvider;)V # register public net.minecraft.client.particle.ParticleEngine m_272137_(Lnet/minecraft/core/particles/ParticleType;Lnet/minecraft/client/particle/ParticleProvider$Sprite;)V # register @@ -167,7 +73,6 @@ private-f net.minecraft.client.renderer.blockentity.PistonHeadRenderer f_112441_ public net.minecraft.client.renderer.blockentity.SkullBlockRenderer f_112519_ # SKIN_BY_TYPE public net.minecraft.client.renderer.entity.EntityRenderDispatcher f_114362_ # renderers public net.minecraft.client.renderer.entity.EntityRenderers m_174036_(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/client/renderer/entity/EntityRendererProvider;)V # register -protected net.minecraft.client.renderer.entity.ItemEntityRenderer m_115042_(Lnet/minecraft/world/item/ItemStack;)I # getRenderAmount public net.minecraft.client.renderer.entity.ItemRenderer m_115162_(Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;Ljava/util/List;Lnet/minecraft/world/item/ItemStack;II)V # renderQuadList public net.minecraft.client.renderer.entity.ItemRenderer m_115189_(Lnet/minecraft/client/resources/model/BakedModel;Lnet/minecraft/world/item/ItemStack;IILcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;)V # renderModelLists public net.minecraft.client.renderer.entity.LivingEntityRenderer m_115326_(Lnet/minecraft/client/renderer/entity/layers/RenderLayer;)Z # addLayer @@ -187,14 +92,14 @@ public net.minecraft.core.Holder$Reference m_205769_(Ljava/util/Collection;)V # public net.minecraft.core.Holder$Reference m_246870_(Lnet/minecraft/resources/ResourceKey;)V # bindKey public net.minecraft.core.Holder$Reference m_247654_(Ljava/lang/Object;)V # bindValue public net.minecraft.core.Holder$Reference$Type +public net.minecraft.core.HolderSet$Named (Lnet/minecraft/core/HolderOwner;Lnet/minecraft/tags/TagKey;)V # constructor public net.minecraft.core.HolderSet$Named m_205835_(Ljava/util/List;)V # bind protected net.minecraft.core.IdMapper f_122653_ # nextId protected net.minecraft.core.IdMapper f_122654_ # tToId - internal map protected net.minecraft.core.IdMapper f_122655_ # idToT - internal index list protected net.minecraft.core.MappedRegistry f_244282_ # unregisteredIntrusiveHolders +protected net.minecraft.core.MappedRegistry m_245420_(Lnet/minecraft/resources/ResourceKey;)Lnet/minecraft/core/Holder$Reference; # getOrCreateHolderOrThrow public net.minecraft.core.RegistrySetBuilder$LazyHolder m_247654_(Ljava/lang/Object;)V # bindValue -public net.minecraft.core.RegistrySynchronization$NetworkedRegistryData -public net.minecraft.core.particles.ParticleType (ZLnet/minecraft/core/particles/ParticleOptions$Deserializer;)V # constructor public net.minecraft.core.particles.SimpleParticleType (Z)V # constructor protected net.minecraft.data.loot.BlockLootSubProvider m_245335_(Lnet/minecraft/world/level/ItemLike;)Lnet/minecraft/world/level/storage/loot/LootTable$Builder; # createSilkTouchOnlyTable protected net.minecraft.data.loot.BlockLootSubProvider m_245602_(Lnet/minecraft/world/level/ItemLike;)Lnet/minecraft/world/level/storage/loot/LootTable$Builder; # createPotFlowerItemTable @@ -239,9 +144,10 @@ public net.minecraft.server.level.ServerPlayer f_8940_ # containerCounter public net.minecraft.server.level.ServerPlayer m_143399_(Lnet/minecraft/world/inventory/AbstractContainerMenu;)V # initMenu public net.minecraft.server.level.ServerPlayer m_9217_()V # nextContainerCounter public net.minecraft.server.network.ServerConfigurationPacketListenerImpl m_293514_(Lnet/minecraft/server/network/ConfigurationTask$Type;)V # finishCurrentTask +public net.minecraft.server.packs.repository.FolderRepositorySource$FolderPackDetector +public net.minecraft.server.packs.repository.FolderRepositorySource$FolderPackDetector (Lnet/minecraft/world/level/validation/DirectoryValidator;)V # constructor public net.minecraft.server.packs.repository.ServerPacksSource m_246173_()Lnet/minecraft/server/packs/VanillaPackResources; # createVanillaPackSource public net.minecraft.server.packs.resources.FallbackResourceManager f_10599_ # fallbacks -public net.minecraft.util.ExtraCodecs$EitherCodec public net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix$Conversion public net.minecraft.util.thread.BlockableEventLoop m_18689_(Ljava/lang/Runnable;)Ljava/util/concurrent/CompletableFuture; # submitAsync #group public net.minecraft.world.damagesource.DamageSource *() #All methods public, most are already @@ -252,7 +158,6 @@ public net.minecraft.world.entity.Entity m_20078_()Ljava/lang/String; # getEncod public net.minecraft.world.entity.ExperienceOrb f_20770_ # value public net.minecraft.world.entity.Mob f_21345_ # goalSelector public net.minecraft.world.entity.Mob f_21346_ # targetSelector -public net.minecraft.world.entity.SpawnPlacements m_21754_(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/entity/SpawnPlacements$Type;Lnet/minecraft/world/level/levelgen/Heightmap$Types;Lnet/minecraft/world/entity/SpawnPlacements$SpawnPredicate;)V # register public net.minecraft.world.entity.ai.memory.MemoryModuleType (Ljava/util/Optional;)V # constructor public net.minecraft.world.entity.ai.sensing.SensorType (Ljava/util/function/Supplier;)V # constructor protected net.minecraft.world.entity.item.PrimedTnt m_32103_()V # explode - make it easier to extend TNTEntity with custom explosion logic @@ -261,12 +166,25 @@ protected net.minecraft.world.entity.monster.Skeleton m_7878_()Lnet/minecraft/so protected net.minecraft.world.entity.monster.Stray m_7878_()Lnet/minecraft/sounds/SoundEvent; # getStepSound - make AbstractSkeletonEntity implementable protected net.minecraft.world.entity.monster.WitherSkeleton m_7878_()Lnet/minecraft/sounds/SoundEvent; # getStepSound - make AbstractSkeletonEntity implementable protected net.minecraft.world.entity.monster.Zombie f_34266_ # conversionTime +public net.minecraft.world.entity.npc.VillagerTrades$DyedArmorForEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$EmeraldForItems +public net.minecraft.world.entity.npc.VillagerTrades$EmeraldsForVillagerTypeItem +public net.minecraft.world.entity.npc.VillagerTrades$EnchantBookForEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$EnchantedItemForEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$FailureItemListing +public net.minecraft.world.entity.npc.VillagerTrades$ItemsAndEmeraldsToItems +public net.minecraft.world.entity.npc.VillagerTrades$ItemsForEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$SuspiciousStewForEmerald +public net.minecraft.world.entity.npc.VillagerTrades$TippedArrowForItemsAndEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$TreasureMapForEmeralds +public net.minecraft.world.entity.npc.VillagerTrades$TypeSpecificTrade public net.minecraft.world.entity.npc.VillagerType (Ljava/lang/String;)V # constructor public net.minecraft.world.entity.player.Player m_6915_()V # closeContainer protected net.minecraft.world.entity.projectile.Projectile (Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V # constructor private-f net.minecraft.world.entity.raid.Raid$RaiderType f_37813_ # VALUES public net.minecraft.world.entity.schedule.Activity (Ljava/lang/String;)V # constructor public net.minecraft.world.inventory.AnvilMenu f_39000_ # repairItemCountCost +public net.minecraft.world.inventory.BrewingStandMenu$PotionSlot public net.minecraft.world.inventory.MenuType (Lnet/minecraft/world/inventory/MenuType$MenuSupplier;Lnet/minecraft/world/flag/FeatureFlagSet;)V # constructor public net.minecraft.world.inventory.MenuType$MenuSupplier public net.minecraft.world.item.CreativeModeTab$Output @@ -286,10 +204,7 @@ public net.minecraft.world.item.CreativeModeTabs f_256968_ # INGREDIENTS public net.minecraft.world.item.CreativeModeTabs f_257028_ # REDSTONE_BLOCKS public net.minecraft.world.item.CreativeModeTabs f_257039_ # INVENTORY #group public net.minecraft.world.item.Item -public net.minecraft.world.item.AxeItem (Lnet/minecraft/world/item/Tier;FFLnet/minecraft/world/item/Item$Properties;)V # constructor -public net.minecraft.world.item.DiggerItem (FFLnet/minecraft/world/item/Tier;Lnet/minecraft/tags/TagKey;Lnet/minecraft/world/item/Item$Properties;)V # constructor -public net.minecraft.world.item.HoeItem (Lnet/minecraft/world/item/Tier;IFLnet/minecraft/world/item/Item$Properties;)V # constructor -public net.minecraft.world.item.PickaxeItem (Lnet/minecraft/world/item/Tier;IFLnet/minecraft/world/item/Item$Properties;)V # constructor +public net.minecraft.world.item.DiggerItem (Lnet/minecraft/world/item/Tier;Lnet/minecraft/tags/TagKey;Lnet/minecraft/world/item/Item$Properties;)V # constructor public net.minecraft.world.item.RecordItem (ILnet/minecraft/sounds/SoundEvent;Lnet/minecraft/world/item/Item$Properties;I)V # constructor #endgroup private-f net.minecraft.world.item.ItemDisplayContext f_268735_ # id @@ -300,7 +215,6 @@ public net.minecraft.world.item.context.BlockPlaceContext (Lnet/minecraft/ public net.minecraft.world.item.context.UseOnContext (Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/phys/BlockHitResult;)V # constructor public-f net.minecraft.world.item.crafting.Ingredient protected net.minecraft.world.item.crafting.Ingredient (Ljava/util/stream/Stream;)V # constructor -public+f net.minecraft.world.item.crafting.Ingredient m_43923_(Lnet/minecraft/network/FriendlyByteBuf;)V # toNetwork public net.minecraft.world.item.crafting.Ingredient m_43938_(Ljava/util/stream/Stream;)Lnet/minecraft/world/item/crafting/Ingredient; # fromValues public net.minecraft.world.item.crafting.Ingredient$ItemValue public net.minecraft.world.item.crafting.Ingredient$ItemValue (Lnet/minecraft/world/item/ItemStack;)V # constructor @@ -366,7 +280,7 @@ public net.minecraft.world.level.block.DecoratedPotBlock (Lnet/minecraft/w public net.minecraft.world.level.block.DirtPathBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor public net.minecraft.world.level.block.DispenserBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor public net.minecraft.world.level.block.DoorBlock (Lnet/minecraft/world/level/block/state/properties/BlockSetType;Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor -public net.minecraft.world.level.block.EnchantmentTableBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor +public net.minecraft.world.level.block.EnchantingTableBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor public net.minecraft.world.level.block.EndGatewayBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor public net.minecraft.world.level.block.EndPortalBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor public net.minecraft.world.level.block.EndRodBlock (Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V # constructor @@ -444,7 +358,7 @@ public net.minecraft.world.level.block.entity.HopperBlockEntity m_59395_(I)V # s public net.minecraft.world.level.block.entity.HopperBlockEntity m_59409_()Z # isOnCustomCooldown public net.minecraft.world.level.block.state.properties.BlockSetType m_272115_(Lnet/minecraft/world/level/block/state/properties/BlockSetType;)Lnet/minecraft/world/level/block/state/properties/BlockSetType; # register public net.minecraft.world.level.block.state.properties.WoodType m_61844_(Lnet/minecraft/world/level/block/state/properties/WoodType;)Lnet/minecraft/world/level/block/state/properties/WoodType; # register -public net.minecraft.world.level.chunk.ChunkStatus (Lnet/minecraft/world/level/chunk/ChunkStatus;IZLjava/util/EnumSet;Lnet/minecraft/world/level/chunk/ChunkStatus$ChunkType;Lnet/minecraft/world/level/chunk/ChunkStatus$GenerationTask;Lnet/minecraft/world/level/chunk/ChunkStatus$LoadingTask;)V # constructor +public net.minecraft.world.level.chunk.status.ChunkStatus (Lnet/minecraft/world/level/chunk/status/ChunkStatus;IZLjava/util/EnumSet;Lnet/minecraft/world/level/chunk/status/ChunkType;Lnet/minecraft/world/level/chunk/status/ChunkStatus$GenerationTask;Lnet/minecraft/world/level/chunk/status/ChunkStatus$LoadingTask;)V # constructor protected net.minecraft.world.level.levelgen.Aquifer$NoiseBasedAquifer f_157994_ # barrierNoise protected net.minecraft.world.level.levelgen.Aquifer$NoiseBasedAquifer f_157996_ # lavaNoise protected net.minecraft.world.level.levelgen.Aquifer$NoiseBasedAquifer f_157998_ # aquiferCache @@ -462,7 +376,6 @@ protected net.minecraft.world.level.levelgen.Aquifer$NoiseBasedAquifer m_158045_ protected net.minecraft.world.level.levelgen.Aquifer$NoiseBasedAquifer m_158047_(I)I # gridZ protected net.minecraft.world.level.levelgen.Beardifier f_158065_ # pieceIterator protected net.minecraft.world.level.levelgen.Beardifier f_158066_ # junctionIterator -protected net.minecraft.world.level.levelgen.Beardifier m_158083_(III)D # getBuryContribution protected net.minecraft.world.level.levelgen.Beardifier m_223925_(IIII)D # getBeardContribution private-f net.minecraft.world.level.levelgen.DebugLevelSource f_64114_ # ALL_BLOCKS private-f net.minecraft.world.level.levelgen.DebugLevelSource f_64115_ # GRID_WIDTH @@ -470,19 +383,19 @@ private-f net.minecraft.world.level.levelgen.DebugLevelSource f_64116_ # GRID_HE public-f net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator protected net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator m_224239_(Lnet/minecraft/world/level/LevelHeightAccessor;Lnet/minecraft/world/level/levelgen/RandomState;IILorg/apache/commons/lang3/mutable/MutableObject;Ljava/util/function/Predicate;)Ljava/util/OptionalInt; # iterateNoiseColumn #group public net.minecraft.world.level.levelgen.NoiseGeneratorSettings *() -public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255038_(Lnet/minecraft/data/worldgen/BootstapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # caves -public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255186_(Lnet/minecraft/data/worldgen/BootstapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # end -public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255226_(Lnet/minecraft/data/worldgen/BootstapContext;ZZ)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # overworld -public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255230_(Lnet/minecraft/data/worldgen/BootstapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # floatingIslands -public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255410_(Lnet/minecraft/data/worldgen/BootstapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # nether +public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255038_(Lnet/minecraft/data/worldgen/BootstrapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # caves +public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255186_(Lnet/minecraft/data/worldgen/BootstrapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # end +public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255226_(Lnet/minecraft/data/worldgen/BootstrapContext;ZZ)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # overworld +public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255230_(Lnet/minecraft/data/worldgen/BootstrapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # floatingIslands +public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_255410_(Lnet/minecraft/data/worldgen/BootstrapContext;)Lnet/minecraft/world/level/levelgen/NoiseGeneratorSettings; # nether public net.minecraft.world.level.levelgen.NoiseGeneratorSettings m_64474_(Lcom/mojang/serialization/codecs/RecordCodecBuilder$Instance;)Lcom/mojang/datafixers/kinds/App; # lambda$static$0 #endgroup -public net.minecraft.world.level.levelgen.feature.featuresize.FeatureSizeType (Lcom/mojang/serialization/Codec;)V # constructor -public net.minecraft.world.level.levelgen.feature.foliageplacers.FoliagePlacerType (Lcom/mojang/serialization/Codec;)V # constructor -public net.minecraft.world.level.levelgen.feature.rootplacers.RootPlacerType (Lcom/mojang/serialization/Codec;)V # constructor -public net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProviderType (Lcom/mojang/serialization/Codec;)V # constructor -public net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecoratorType (Lcom/mojang/serialization/Codec;)V # constructor -public net.minecraft.world.level.levelgen.feature.trunkplacers.TrunkPlacerType (Lcom/mojang/serialization/Codec;)V # constructor +public net.minecraft.world.level.levelgen.feature.featuresize.FeatureSizeType (Lcom/mojang/serialization/MapCodec;)V # constructor +public net.minecraft.world.level.levelgen.feature.foliageplacers.FoliagePlacerType (Lcom/mojang/serialization/MapCodec;)V # constructor +public net.minecraft.world.level.levelgen.feature.rootplacers.RootPlacerType (Lcom/mojang/serialization/MapCodec;)V # constructor +public net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProviderType (Lcom/mojang/serialization/MapCodec;)V # constructor +public net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecoratorType (Lcom/mojang/serialization/MapCodec;)V # constructor +public net.minecraft.world.level.levelgen.feature.trunkplacers.TrunkPlacerType (Lcom/mojang/serialization/MapCodec;)V # constructor protected net.minecraft.world.level.portal.PortalForcer f_77648_ # level public net.minecraft.world.level.storage.LevelResource (Ljava/lang/String;)V # constructor private-f net.minecraft.world.level.storage.loot.LootPool f_79028_ # rolls diff --git a/src/main/resources/META-INF/coremods.json b/src/main/resources/META-INF/coremods.json index 98eab2a142..d6ef083372 100644 --- a/src/main/resources/META-INF/coremods.json +++ b/src/main/resources/META-INF/coremods.json @@ -1,6 +1,4 @@ { "field_to_method": "coremods/field_to_method.js", - "field_to_instanceof": "coremods/field_to_instanceof.js", - "add_bouncer_method": "coremods/add_bouncer_method.js", "method_redirector": "coremods/method_redirector.js" } diff --git a/src/main/resources/coremods/add_bouncer_method.js b/src/main/resources/coremods/add_bouncer_method.js deleted file mode 100644 index 6ecdd4c272..0000000000 --- a/src/main/resources/coremods/add_bouncer_method.js +++ /dev/null @@ -1,46 +0,0 @@ -var ASMAPI = Java.type('net.minecraftforge.coremod.api.ASMAPI') -var Opcodes = Java.type('org.objectweb.asm.Opcodes') -var MethodNode = Java.type('org.objectweb.asm.tree.MethodNode') -var VarInsnNode = Java.type('org.objectweb.asm.tree.VarInsnNode') -var MethodInsnNode = Java.type('org.objectweb.asm.tree.MethodInsnNode') -var InsnNode = Java.type('org.objectweb.asm.tree.InsnNode') - -function initializeCoreMod() { - return { - //TODO: Remove in 1.20.5+ - "getPosition_bouncer": addBouncer("net.minecraft.world.level.Explosion", "m_307721_", "getPosition", "()Lnet/minecraft/world/phys/Vec3;"), - "getExploder_bouncer": addBouncer("net.minecraft.world.level.Explosion", "m_253049_", "getExploder", "()Lnet/minecraft/world/entity/Entity;"), - } -} - -function addBouncer(className, conflictedName, expectedName, descriptor, signature) { - if (signature == null) - signature = descriptor; - return { - 'target': { - 'type': 'CLASS', - 'name': className - }, - 'transformer': function(node) { - var mappedName = ASMAPI.mapMethod(conflictedName); - if (mappedName == expectedName) - return node; // No work to do! - - var method = new MethodNode( - /* access = */ Opcodes.ACC_PUBLIC, - /* name = */ expectedName, - /* descriptor = */ descriptor, - /* signature = */ signature, - /* exceptions = */ null - ); - - method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); /*this*/ - method.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, className.replaceAll("\\.","/"), mappedName, descriptor)); - method.instructions.add(new InsnNode(Opcodes.ARETURN)); - - node.methods.add(method); - - return node; - } - } -} \ No newline at end of file diff --git a/src/main/resources/coremods/field_to_instanceof.js b/src/main/resources/coremods/field_to_instanceof.js deleted file mode 100644 index e15fc50873..0000000000 --- a/src/main/resources/coremods/field_to_instanceof.js +++ /dev/null @@ -1,58 +0,0 @@ -var ASMAPI = Java.type('net.minecraftforge.coremod.api.ASMAPI') -var Opcodes = Java.type('org.objectweb.asm.Opcodes') - -function initializeCoreMod() { - var data = ASMAPI.loadData('coremods/field_to_instanceof.json') - //ASMAPI.log('DEBUG', JSON.stringify(data, null, 2)) - - var ret = {} - for (name in data) { - addTargets(ret, name, data[name]) - } - return ret -} - -function addTargets(ret, name, data) { - var owner = data.cls - var field = ASMAPI.mapField(data.name) - var replacement = data.replacement - for (x = 0; x < data.targets.length; x++) { - var key = name + '.' + x - var entry = data.targets[x] - - //ASMAPI.log('DEBUG', 'Entry ' + key + ' ' + JSON.stringify(entry)) - - ret[key] = { - 'target': { - 'type': 'METHOD', - 'class': entry.owner, - 'methodName': entry.name, - 'methodDesc': entry.desc - }, - 'transformer': function(entry) { return function(node) { - return transform(node, entry.owner, owner, field, replacement) - }}(entry) // We have to do this annoying double function imediate call, so that JS will capture the entry value - } - } -} - -function transform(node, parent, owner, field, replacement) { - var count = 0 - var last = null - for (x = 0; x < node.instructions.size(); x++) { - var current = node.instructions.get(x) - if (current.getOpcode() == Opcodes.IF_ACMPEQ || current.getOpcode() == Opcodes.IF_ACMPNE) { - if (last != null && (last.getOpcode() == Opcodes.GETSTATIC || last.getOpcode() == Opcodes.GETFIELD)) { - if (last.owner.equals(owner) && last.name.equals(field)) { - node.instructions.set(last, new org.objectweb.asm.tree.TypeInsnNode(Opcodes.INSTANCEOF, replacement)) - node.instructions.set(current, new org.objectweb.asm.tree.JumpInsnNode(current.getOpcode() == Opcodes.IF_ACMPEQ ? Opcodes.IFNE: Opcodes.IFEQ, current.label)) - count++ - } - } - } - last = current - } - //ASMAPI.log('DEBUG', 'Transforming: ' + parent + '.' + node.name + node.desc) - //ASMAPI.log('DEBUG', 'field_to_instance: Replaced {} checks', count) - return node -} diff --git a/src/main/resources/coremods/field_to_instanceof.json b/src/main/resources/coremods/field_to_instanceof.json deleted file mode 100644 index 544b7b4ddd..0000000000 --- a/src/main/resources/coremods/field_to_instanceof.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - -} \ No newline at end of file diff --git a/src/main/resources/coremods/field_to_method.js b/src/main/resources/coremods/field_to_method.js index 6d01086a60..1bcdbcc67b 100644 --- a/src/main/resources/coremods/field_to_method.js +++ b/src/main/resources/coremods/field_to_method.js @@ -8,18 +8,8 @@ function initializeCoreMod() { 'name': 'net.minecraft.world.level.biome.Biome' }, 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_47437_'), 'getModifiedClimateSettings') - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_47443_'), 'getModifiedSpecialEffects') - return classNode; - } - }, - 'structure': { - 'target': { - 'type': 'CLASS', - 'name': 'net.minecraft.world.level.levelgen.structure.Structure' - }, - 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_226555_'), 'getModifiedStructureSettings') + ASMAPI.redirectFieldToMethod(classNode, 'climateSettings', 'getModifiedClimateSettings') + ASMAPI.redirectFieldToMethod(classNode, 'specialEffects', 'getModifiedSpecialEffects') return classNode; } }, @@ -29,7 +19,7 @@ function initializeCoreMod() { 'name': 'net.minecraft.world.effect.MobEffectInstance' }, 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_19502_'), ASMAPI.mapMethod('m_19544_')) // potion + ASMAPI.redirectFieldToMethod(classNode, 'effect', 'getEffect') return classNode; } }, @@ -39,7 +29,7 @@ function initializeCoreMod() { 'name': 'net.minecraft.world.level.block.LiquidBlock' }, 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_54689_'), 'getFluid') + ASMAPI.redirectFieldToMethod(classNode, 'fluid', 'getFluid') return classNode; } }, @@ -49,7 +39,7 @@ function initializeCoreMod() { 'name': 'net.minecraft.world.item.BucketItem' }, 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_40687_'), 'getFluid') + ASMAPI.redirectFieldToMethod(classNode, 'content', 'getFluid') return classNode; } }, @@ -59,17 +49,7 @@ function initializeCoreMod() { 'name': 'net.minecraft.world.level.block.FlowerPotBlock' }, 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_302266_'), ASMAPI.mapMethod('m_304918_')) // potted - return classNode; - } - }, - 'itemstack': { - 'target': { - 'type': 'CLASS', - 'name': 'net.minecraft.world.item.ItemStack' - }, - 'transformer': function(classNode) { - ASMAPI.redirectFieldToMethod(classNode, ASMAPI.mapField('f_41589_'), ASMAPI.mapMethod('m_41720_')) // item + ASMAPI.redirectFieldToMethod(classNode, 'potted', 'getPotted') return classNode; } } diff --git a/src/main/resources/coremods/finalize_spawn_targets.json b/src/main/resources/coremods/finalize_spawn_targets.json index 494cd63bc2..0ea1d9e95b 100644 --- a/src/main/resources/coremods/finalize_spawn_targets.json +++ b/src/main/resources/coremods/finalize_spawn_targets.json @@ -14,6 +14,7 @@ "net/minecraft/world/entity/npc/Villager", "net/minecraft/world/entity/raid/Raid", "net/minecraft/world/level/NaturalSpawner", + "net/minecraft/world/level/block/entity/trialspawner/TrialSpawner", "net/minecraft/world/level/levelgen/PatrolSpawner", "net/minecraft/world/level/levelgen/PhantomSpawner", "net/minecraft/world/level/levelgen/structure/structures/OceanMonumentPieces$OceanMonumentPiece", diff --git a/src/main/resources/coremods/method_redirector.js b/src/main/resources/coremods/method_redirector.js index b70912ab85..042ff05b94 100644 --- a/src/main/resources/coremods/method_redirector.js +++ b/src/main/resources/coremods/method_redirector.js @@ -5,10 +5,10 @@ var MethodInsnNode = Java.type('org.objectweb.asm.tree.MethodInsnNode'); function finalizeSpawnNode(node){ return new MethodInsnNode( - Opcodes.INVOKESTATIC, - "net/minecraftforge/event/ForgeEventFactory", - "onFinalizeSpawn", - "(Lnet/minecraft/world/entity/Mob;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;", + Opcodes.INVOKESTATIC, + "net/minecraftforge/event/ForgeEventFactory", + "onFinalizeSpawn", + "(Lnet/minecraft/world/entity/Mob;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;", false); } @@ -33,7 +33,7 @@ var replacements = [ { 'opcode': Opcodes.INVOKEVIRTUAL, 'name': ASMAPI.mapMethod('m_6518_'), - 'desc': '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;', + 'desc': '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;', 'targets': 'coremods/finalize_spawn_targets.json', 'factory': finalizeSpawnNode } diff --git a/src/main/resources/forge.exc b/src/main/resources/forge.exc index d94ef84817..cb9e290a36 100644 --- a/src/main/resources/forge.exc +++ b/src/main/resources/forge.exc @@ -2,7 +2,6 @@ com/mojang/blaze3d/vertex/VertexConsumer.putBulkData(Lcom/mojang/blaze3d/vertex/ net/minecraft/client/Options.processOptionsForge(Lnet/minecraft/client/Options$FieldAccess;)V=|p_168428_ net/minecraft/client/gui/Gui.renderSelectedItemName(Lnet/minecraft/client/gui/GuiGraphics;I)V=|p_283501_,yShift net/minecraft/client/gui/screens/MenuScreens.getScreenFactory(Lnet/minecraft/world/inventory/MenuType;Lnet/minecraft/client/Minecraft;ILnet/minecraft/network/chat/Component;)Ljava/util/Optional;=|p_96202_,p_96203_,p_96204_,p_96205_ -net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.renderRectangle(Lnet/minecraft/client/gui/GuiGraphics;IIIIIII)V=|p_281392_,p_282294_,p_283353_,p_282640_,p_281964_,p_283211_,p_282349_,colorTo net/minecraft/client/gui/screens/inventory/tooltip/TooltipRenderUtil.renderTooltipBackground(Lnet/minecraft/client/gui/GuiGraphics;IIIIIIIII)V=|p_282666_,p_281901_,p_281846_,p_281559_,p_283336_,p_283422_,backgroundTop,backgroundBottom,borderTop,borderBottom net/minecraft/client/renderer/ScreenEffectRenderer.getOverlayBlock(Lnet/minecraft/world/entity/player/Player;)Lorg/apache/commons/lang3/tuple/Pair;=|p_110717_ net/minecraft/client/renderer/ScreenEffectRenderer.renderFluid(Lnet/minecraft/client/Minecraft;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/resources/ResourceLocation;)V=|p_110726_,p_110727_,texture @@ -18,14 +17,9 @@ net/minecraft/client/renderer/block/ModelBlockRenderer.tesselateWithoutAO(Lnet/m net/minecraft/client/renderer/block/model/BakedQuad.([IILnet/minecraft/core/Direction;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;ZZ)V=|p_111298_,p_111299_,p_111300_,p_111301_,p_111302_,hasAmbientOcclusion net/minecraft/client/renderer/block/model/BlockElement.(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Ljava/util/Map;Lnet/minecraft/client/renderer/block/model/BlockElementRotation;ZLnet/minecraftforge/client/model/ForgeFaceData;)V=|p_253626_,p_254426_,p_254454_,p_254229_,p_253661_,faceData net/minecraft/client/renderer/block/model/BlockElementFace.(Lnet/minecraft/core/Direction;ILjava/lang/String;Lnet/minecraft/client/renderer/block/model/BlockFaceUV;Lnet/minecraftforge/client/model/ForgeFaceData;)V=|p_111359_,p_111360_,p_111361_,p_111362_,faceData -net/minecraft/client/renderer/block/model/BlockModel.bakeVanilla(Lnet/minecraft/client/resources/model/ModelBaker;Lnet/minecraft/client/renderer/block/model/BlockModel;Ljava/util/function/Function;Lnet/minecraft/client/resources/model/ModelState;Lnet/minecraft/resources/ResourceLocation;ZLnet/minecraftforge/client/RenderTypeGroup;)Lnet/minecraft/client/resources/model/BakedModel;=|p_249720_,p_111451_,p_111452_,p_111453_,p_111454_,p_111455_,renderTypes net/minecraft/client/renderer/block/model/ItemTransform.(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)V=|p_254427_,p_254496_,p_254022_,rightRotation net/minecraft/client/renderer/block/model/ItemTransforms.(Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lnet/minecraft/client/renderer/block/model/ItemTransform;Lcom/google/common/collect/ImmutableMap;)V=|p_111798_,p_111799_,p_111800_,p_111801_,p_111802_,p_111803_,p_111804_,p_111805_,moddedTransforms -net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.renderGlint(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/model/Model;)V=|p_289673_,p_289654_,p_289649_,p_289659_ -net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.renderModel(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/item/ArmorItem;Lnet/minecraft/client/model/Model;ZFFFLnet/minecraft/resources/ResourceLocation;)V=|p_289664_,p_289689_,p_289681_,p_289650_,p_289658_,p_289668_,p_289678_,p_289674_,p_289693_,armorResource -net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.renderTrim(Lnet/minecraft/world/item/ArmorMaterial;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/item/armortrim/ArmorTrim;Lnet/minecraft/client/model/Model;Z)V=|p_289690_,p_289687_,p_289643_,p_289683_,p_289692_,p_289663_,p_289651_ net/minecraft/client/resources/model/MultiPartBakedModel.getQuads(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/Direction;Lnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;)Ljava/util/List;=|p_235050_,p_235051_,p_235052_,modelData,renderType -net/minecraft/client/resources/model/SimpleBakedModel$Builder.build(Lnet/minecraftforge/client/RenderTypeGroup;)Lnet/minecraft/client/resources/model/BakedModel;=|renderTypes net/minecraft/client/resources/model/SimpleBakedModel.(Ljava/util/List;Ljava/util/Map;ZZZLnet/minecraft/client/renderer/texture/TextureAtlasSprite;Lnet/minecraft/client/renderer/block/model/ItemTransforms;Lnet/minecraft/client/renderer/block/model/ItemOverrides;Lnet/minecraftforge/client/RenderTypeGroup;)V=|p_119489_,p_119490_,p_119491_,p_119492_,p_119493_,p_119494_,p_119495_,p_119496_,renderTypes net/minecraft/client/resources/model/WeightedBakedModel.getQuads(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/Direction;Lnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;)Ljava/util/List;=|p_235058_,p_235059_,p_235060_,modelData,renderType net/minecraft/data/registries/RegistriesDatapackGenerator.(Lnet/minecraft/data/PackOutput;Ljava/util/concurrent/CompletableFuture;Ljava/util/Set;)V=|p_256643_,p_255780_,modIds @@ -51,8 +45,6 @@ net/minecraft/data/tags/TagsProvider.(Lnet/minecraft/data/PackOutput;Lnet/ net/minecraft/data/tags/TagsProvider.(Lnet/minecraft/data/PackOutput;Lnet/minecraft/resources/ResourceKey;Ljava/util/concurrent/CompletableFuture;Ljava/util/concurrent/CompletableFuture;Ljava/lang/String;Lnet/minecraftforge/common/data/ExistingFileHelper;)V=|p_275432_,p_275476_,p_275222_,p_275565_,modId,existingFileHelper net/minecraft/data/tags/WorldPresetTagsProvider.(Lnet/minecraft/data/PackOutput;Ljava/util/concurrent/CompletableFuture;Ljava/lang/String;Lnet/minecraftforge/common/data/ExistingFileHelper;)V=|p_255701_,p_255974_,modId,existingFileHelper net/minecraft/gametest/framework/GameTestRegistry.register(Ljava/lang/reflect/Method;Ljava/util/Set;)V=|p_177504_,allowedNamespaces -net/minecraft/network/FriendlyByteBuf.writeItemStack(Lnet/minecraft/world/item/ItemStack;Z)Lnet/minecraft/network/FriendlyByteBuf;=|p_130056_,limitedTag -net/minecraft/server/ServerAdvancementManager.(Lnet/minecraft/world/level/storage/loot/LootDataManager;Lnet/minecraftforge/common/crafting/conditions/ICondition$IContext;)V=|p_279237_,context net/minecraft/server/level/DistanceManager.addRegionTicket(Lnet/minecraft/server/level/TicketType;Lnet/minecraft/world/level/ChunkPos;ILjava/lang/Object;Z)V=|p_140841_,p_140842_,p_140843_,p_140844_,forceTicks net/minecraft/server/level/DistanceManager.removeRegionTicket(Lnet/minecraft/server/level/TicketType;Lnet/minecraft/world/level/ChunkPos;ILjava/lang/Object;Z)V=|p_140850_,p_140851_,p_140852_,p_140853_,forceTicks net/minecraft/server/level/ServerChunkCache.addRegionTicket(Lnet/minecraft/server/level/TicketType;Lnet/minecraft/world/level/ChunkPos;ILjava/lang/Object;Z)V=|p_8388_,p_8389_,p_8390_,p_8391_,forceTicks @@ -62,34 +54,22 @@ net/minecraft/server/level/ServerPlayerGameMode.removeBlock(Lnet/minecraft/core/ net/minecraft/server/level/Ticket.(Lnet/minecraft/server/level/TicketType;ILjava/lang/Object;Z)V=|p_9425_,p_9426_,p_9427_,forceTicks net/minecraft/world/entity/Entity.changeDimension(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraftforge/common/util/ITeleporter;)Lnet/minecraft/world/entity/Entity;=|p_20118_,teleporter net/minecraft/world/entity/Entity.playCombinationStepSounds(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;)V=|p_277472_,p_277630_,primaryPos,secondaryPos -net/minecraft/world/entity/EntityType.(Lnet/minecraft/world/entity/EntityType$EntityFactory;Lnet/minecraft/world/entity/MobCategory;ZZZZLcom/google/common/collect/ImmutableSet;Lnet/minecraft/world/entity/EntityDimensions;IILnet/minecraft/world/flag/FeatureFlagSet;Ljava/util/function/Predicate;Ljava/util/function/ToIntFunction;Ljava/util/function/ToIntFunction;Ljava/util/function/BiFunction;)V=|p_251402_,p_251431_,p_251439_,p_251973_,p_252007_,p_250908_,p_250201_,p_251742_,p_250479_,p_249249_,p_250427_,velocityUpdateSupplier,trackingRangeSupplier,updateIntervalSupplier,customClientFactory net/minecraft/world/entity/item/ItemEntity.changeDimension(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraftforge/common/util/ITeleporter;)Lnet/minecraft/world/entity/Entity;=|p_32042_,teleporter net/minecraft/world/entity/npc/AbstractVillager.changeDimension(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraftforge/common/util/ITeleporter;)Lnet/minecraft/world/entity/Entity;=|p_35295_,teleporter -net/minecraft/world/entity/player/Player.getDigSpeed(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;)F=|p_36282_,pos net/minecraft/world/entity/projectile/ThrownEnderpearl.changeDimension(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraftforge/common/util/ITeleporter;)Lnet/minecraft/world/entity/Entity;=|p_37506_,teleporter -net/minecraft/world/food/FoodData.eat(Lnet/minecraft/world/item/Item;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/entity/LivingEntity;)V=|p_38713_,p_38714_,entity net/minecraft/world/item/BoneMealItem.applyBonemeal(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/player/Player;)Z=|p_40628_,p_40629_,p_40630_,player net/minecraft/world/item/BucketItem.emptyContents(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/BlockHitResult;Lnet/minecraft/world/item/ItemStack;)Z=|p_150716_,p_150717_,p_150718_,p_150719_,container -net/minecraft/world/item/DyeableHorseArmorItem.(ILnet/minecraft/resources/ResourceLocation;Lnet/minecraft/world/item/Item$Properties;)V=|p_41110_,p_41111_,p_41112_ -net/minecraft/world/item/HorseArmorItem.(ILnet/minecraft/resources/ResourceLocation;Lnet/minecraft/world/item/Item$Properties;)V=|p_41364_,p_41365_,p_41366_ -net/minecraft/world/item/ItemStack.(Lnet/minecraft/world/level/ItemLike;ILnet/minecraft/nbt/CompoundTag;)V=|p_41604_,p_41605_,p_41606_ net/minecraft/world/item/ItemStack.onItemUse(Lnet/minecraft/world/item/context/UseOnContext;Ljava/util/function/Function;)Lnet/minecraft/world/InteractionResult;=|p_41662_,callback net/minecraft/world/item/ItemStack.onItemUseFirst(Lnet/minecraft/world/item/context/UseOnContext;)Lnet/minecraft/world/InteractionResult;=|p_41662_ -net/minecraft/world/item/MapItem.getCustomMapData(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/level/Level;)Lnet/minecraft/world/level/saveddata/maps/MapItemSavedData;=|p_42910_,p_42911_ -net/minecraft/world/item/alchemy/PotionBrewing$Mix.(Lnet/minecraftforge/registries/IForgeRegistry;Ljava/lang/Object;Lnet/minecraft/world/item/crafting/Ingredient;Ljava/lang/Object;)V=|registry,p_43536_,p_43537_,p_43538_ -net/minecraft/world/item/crafting/RecipeManager.(Lnet/minecraftforge/common/crafting/conditions/ICondition$IContext;)V=|context -net/minecraft/world/item/enchantment/EnchantmentHelper.getTagEnchantmentLevel(Lnet/minecraft/world/item/enchantment/Enchantment;Lnet/minecraft/world/item/ItemStack;)I=|p_44844_,p_44845_ net/minecraft/world/level/Level.markAndNotifyBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/chunk/LevelChunk;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;II)V=|p_46605_,levelchunk,blockstate,p_46606_,p_46607_,p_46608_ net/minecraft/world/level/LevelSettings.(Ljava/lang/String;Lnet/minecraft/world/level/GameType;ZLnet/minecraft/world/Difficulty;ZLnet/minecraft/world/level/GameRules;Lnet/minecraft/world/level/WorldDataConfiguration;Lcom/mojang/serialization/Lifecycle;)V=|p_250485_,p_250207_,p_251631_,p_252122_,p_248961_,p_248536_,p_249797_,lifecycle net/minecraft/world/level/block/Block.dropResources(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/entity/BlockEntity;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/item/ItemStack;Z)V=|p_49882_,p_49883_,p_49884_,p_49885_,p_49886_,p_49887_,dropXp net/minecraft/world/level/block/ConcretePowderBlock.shouldSolidify(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/material/FluidState;)Z=|p_52081_,p_52082_,p_52083_,fluidState net/minecraft/world/level/block/ConcretePowderBlock.touchesLiquid(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)Z=|p_52065_,p_52066_,state -net/minecraft/world/level/block/FireBlock.tryCatchFire(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;ILnet/minecraft/util/RandomSource;ILnet/minecraft/core/Direction;)V=|p_53432_,p_53433_,p_53434_,p_53435_,p_53436_,face net/minecraft/world/level/block/FlowerPotBlock.(Ljava/util/function/Supplier;Ljava/util/function/Supplier;Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V=|emptyPot,p_53528_,properties net/minecraft/world/level/block/LiquidBlock.(Ljava/util/function/Supplier;Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;)V=|p_54694_,p_54695_ net/minecraft/world/level/block/PoweredRailBlock.(Lnet/minecraft/world/level/block/state/BlockBehaviour$Properties;Z)V=|p_55218_,isPoweredRail net/minecraft/world/level/chunk/ChunkAccess.findBlocks(Ljava/util/function/BiPredicate;Ljava/util/function/BiConsumer;)V=|p_285343_,p_285030_ net/minecraft/world/level/chunk/ImposterProtoChunk.findBlocks(Ljava/util/function/BiPredicate;Ljava/util/function/BiConsumer;)V=|p_285343_,p_285030_ net/minecraft/world/level/entity/PersistentEntitySectionManager.addEntityWithoutEvent(Lnet/minecraft/world/level/entity/EntityAccess;Z)Z=|p_157539_,p_157540_ -net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.processEntityInfos(Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;Ljava/util/List;)Ljava/util/List;=|template,p_215387_0_,p_215387_1_,p_215387_2_,p_215387_3_ -net/minecraft/world/level/storage/loot/LootContext.(Lnet/minecraft/world/level/storage/loot/LootParams;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/storage/loot/LootDataResolver;Lnet/minecraft/resources/ResourceLocation;)V=|p_287722_,p_287702_,p_287619_,queriedLootTableId \ No newline at end of file +net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.processEntityInfos(Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/levelgen/structure/templatesystem/StructurePlaceSettings;Ljava/util/List;)Ljava/util/List;=|template,p_215387_0_,p_215387_1_,p_215387_2_,p_215387_3_ \ No newline at end of file diff --git a/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_tables/blocks/test.json b/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_tables/blocks/test.json index 713bd46f9a..b94b56867e 100644 --- a/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_tables/blocks/test.json +++ b/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_tables/blocks/test.json @@ -10,8 +10,7 @@ } ], "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "rolls": 1.0 }, @@ -24,8 +23,7 @@ } ], "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "rolls": 1.0 } diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_doesnt_load_empty.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_doesnt_load_empty.json index 71df22f646..be95984161 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_doesnt_load_empty.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_doesnt_load_empty.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_recipe_choice.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_recipe_choice.json index 51ed7f4104..d9cd081033 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_recipe_choice.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/conditional_recipe_choice.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ @@ -45,9 +42,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:oak_log" - ] + "items": "minecraft:oak_log" } ] }, @@ -61,8 +56,7 @@ } }, "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_false_conditions.json index 71df22f646..be95984161 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_false_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_true_conditions.json index 3ac4f67736..415abef1c2 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/cooking_true_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:bee_nest" - ] + "items": "minecraft:bee_nest" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_false_conditions.json index 71df22f646..be95984161 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_false_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_true_conditions.json index 6f0c041227..132aae35c9 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shaped_true_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:oak_log" - ] + "items": "minecraft:oak_log" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_false_conditions.json index 3054fb16df..64cb91c38b 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_false_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:redstone_ore" - ] + "items": "minecraft:redstone_ore" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_true_conditions.json index e93ae3dbb2..131fba1ffc 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/shapeless_true_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:redstone_ore" - ] + "items": "minecraft:redstone_ore" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/singe_item_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/singe_item_true_conditions.json index e93ae3dbb2..131fba1ffc 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/singe_item_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/singe_item_true_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:redstone_ore" - ] + "items": "minecraft:redstone_ore" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/single_item_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/single_item_false_conditions.json index 71df22f646..be95984161 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/single_item_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/single_item_false_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -23,8 +21,7 @@ } }, "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "requirements": [ [ diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/test_encode_all_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/test_encode_all_conditions.json index d7e4486e38..b5db751247 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/test_encode_all_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/advancements/recipes/test_encode_all_conditions.json @@ -7,9 +7,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, @@ -40,8 +38,7 @@ "item": "minecraft:dirt" }, { - "type": "forge:true", - "value": {} + "type": "forge:true" }, { "type": "forge:tag_empty", @@ -50,8 +47,7 @@ ] }, { - "type": "forge:false", - "value": {} + "type": "forge:false" } ] }, diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_doesnt_load_empty.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_doesnt_load_empty.json index 4bbe29ba27..75a570a747 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_doesnt_load_empty.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_doesnt_load_empty.json @@ -1,21 +1,22 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "recipes": [ { - "type": "minecraft:crafting_shapeless", - "category": "misc", - "ingredients": [ - { - "item": "minecraft:dirt" + "recipe": { + "type": "minecraft:crafting_shapeless", + "category": "misc", + "ingredients": [ + { + "item": "minecraft:dirt" + } + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_recipe_choice.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_recipe_choice.json index 23a2e5fbf5..cbdd1f4b6e 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_recipe_choice.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/conditional_recipe_choice.json @@ -2,45 +2,47 @@ "type": "forge:conditional", "recipes": [ { - "type": "minecraft:crafting_shaped", - "category": "misc", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, - "key": { - "X": { - "item": "minecraft:dirt" + "recipe": { + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "X": { + "item": "minecraft:dirt" + } + }, + "pattern": [ + "XXX", + "XX " + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - }, - "pattern": [ - "XXX", - "XX " - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } }, { - "type": "minecraft:crafting_shaped", - "category": "misc", "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, - "key": { - "X": { - "item": "minecraft:oak_log" + "recipe": { + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "X": { + "item": "minecraft:oak_log" + } + }, + "pattern": [ + "XXX", + "XX " + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - }, - "pattern": [ - "XXX", - "XX " - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_false_conditions.json index dbb8c2221d..c95b42a6cc 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_false_conditions.json @@ -1,19 +1,22 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "recipes": [ { - "type": "minecraft:smelting", - "category": "blocks", - "cookingtime": 200, - "experience": 0.1, - "ingredient": { - "item": "minecraft:dirt" - }, - "result": "minecraft:diamond_block" + "recipe": { + "type": "minecraft:smelting", + "category": "blocks", + "cookingtime": 200, + "experience": 0.1, + "ingredient": { + "item": "minecraft:dirt" + }, + "result": { + "id": "minecraft:diamond_block" + } + } } ] } \ No newline at end of file diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_true_conditions.json index e85d511a1e..2d92519498 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/cooking_true_conditions.json @@ -1,19 +1,22 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "recipes": [ { - "type": "minecraft:smelting", - "category": "blocks", - "cookingtime": 200, - "experience": 0.1, - "ingredient": { - "item": "minecraft:bee_nest" - }, - "result": "minecraft:diamond_block" + "recipe": { + "type": "minecraft:smelting", + "category": "blocks", + "cookingtime": 200, + "experience": 0.1, + "ingredient": { + "item": "minecraft:bee_nest" + }, + "result": { + "id": "minecraft:diamond_block" + } + } } ] } \ No newline at end of file diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_false_conditions.json index 8c957588a3..5fda9c0602 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_false_conditions.json @@ -1,26 +1,27 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "recipes": [ { - "type": "minecraft:crafting_shaped", - "category": "misc", - "key": { - "X": { - "item": "minecraft:dirt" + "recipe": { + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "X": { + "item": "minecraft:dirt" + } + }, + "pattern": [ + "XXX", + "XXX", + "XXX" + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - }, - "pattern": [ - "XXX", - "XXX", - "XXX" - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_true_conditions.json index 3273547fd5..e268db673f 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shaped_true_conditions.json @@ -1,26 +1,27 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "recipes": [ { - "type": "minecraft:crafting_shaped", - "category": "misc", - "key": { - "X": { - "item": "minecraft:oak_log" + "recipe": { + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "X": { + "item": "minecraft:oak_log" + } + }, + "pattern": [ + "XXX", + "XXX", + "XXX" + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - }, - "pattern": [ - "XXX", - "XXX", - "XXX" - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_false_conditions.json index a10a3bf3c6..3a381deb8e 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_false_conditions.json @@ -1,26 +1,28 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "recipes": [ { - "type": "minecraft:crafting_shapeless", - "category": "misc", - "ingredients": [ - { - "item": "minecraft:redstone_ore" - }, - { - "item": "minecraft:redstone_ore" - }, - { - "item": "minecraft:redstone_ore" + "recipe": { + "type": "minecraft:crafting_shapeless", + "category": "misc", + "ingredients": [ + { + "item": "minecraft:redstone_ore" + }, + { + "item": "minecraft:redstone_ore" + }, + { + "item": "minecraft:redstone_ore" + } + ], + "result": { + "count": 1, + "id": "minecraft:diamond_block" } - ], - "result": { - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_true_conditions.json index d65d5141a8..694f9eeae4 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/shapeless_true_conditions.json @@ -1,29 +1,31 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "recipes": [ { - "type": "minecraft:crafting_shapeless", - "category": "misc", - "ingredients": [ - { - "item": "minecraft:redstone_ore" - }, - { - "item": "minecraft:redstone_ore" - }, - { - "item": "minecraft:redstone_ore" - }, - { - "item": "minecraft:redstone_ore" + "recipe": { + "type": "minecraft:crafting_shapeless", + "category": "misc", + "ingredients": [ + { + "item": "minecraft:redstone_ore" + }, + { + "item": "minecraft:redstone_ore" + }, + { + "item": "minecraft:redstone_ore" + }, + { + "item": "minecraft:redstone_ore" + } + ], + "result": { + "count": 1, + "id": "minecraft:diamond_block" } - ], - "result": { - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/singe_item_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/singe_item_true_conditions.json index b0fdb017c0..f55f2f98c7 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/singe_item_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/singe_item_true_conditions.json @@ -1,17 +1,20 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:true", - "value": {} + "type": "forge:true" }, "recipes": [ { - "type": "minecraft:stonecutting", - "count": 1, - "ingredient": { - "item": "minecraft:redstone_ore" - }, - "result": "minecraft:diamond_block" + "recipe": { + "type": "minecraft:stonecutting", + "ingredient": { + "item": "minecraft:redstone_ore" + }, + "result": { + "count": 1, + "id": "minecraft:diamond_block" + } + } } ] } \ No newline at end of file diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/single_item_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/single_item_false_conditions.json index 1f6fbda07c..d381579d12 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/single_item_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/single_item_false_conditions.json @@ -1,17 +1,20 @@ { "type": "forge:conditional", "forge:condition": { - "type": "forge:false", - "value": {} + "type": "forge:false" }, "recipes": [ { - "type": "minecraft:stonecutting", - "count": 1, - "ingredient": { - "item": "minecraft:dirt" - }, - "result": "minecraft:diamond_block" + "recipe": { + "type": "minecraft:stonecutting", + "ingredient": { + "item": "minecraft:dirt" + }, + "result": { + "count": 1, + "id": "minecraft:diamond_block" + } + } } ] } \ No newline at end of file diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/test_encode_all_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/test_encode_all_conditions.json index 3a5bb29e37..b9ff8baf67 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/test_encode_all_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipes/test_encode_all_conditions.json @@ -18,8 +18,7 @@ "item": "minecraft:dirt" }, { - "type": "forge:true", - "value": {} + "type": "forge:true" }, { "type": "forge:tag_empty", @@ -28,28 +27,29 @@ ] }, { - "type": "forge:false", - "value": {} + "type": "forge:false" } ] }, "recipes": [ { - "type": "minecraft:crafting_shaped", - "category": "misc", - "key": { - "X": { - "item": "minecraft:dirt" + "recipe": { + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "X": { + "item": "minecraft:dirt" + } + }, + "pattern": [ + "XXX", + "XXX", + "XXX" + ], + "result": { + "count": 64, + "id": "minecraft:diamond_block" } - }, - "pattern": [ - "XXX", - "XXX", - "XXX" - ], - "result": { - "count": 64, - "item": "minecraft:diamond_block" } } ] diff --git a/src/test/generated/criterion_test/data/criterion_test/advancements/break_glass_with_fish.json b/src/test/generated/criterion_test/data/criterion_test/advancements/break_glass_with_fish.json index db2ef780fc..86cc37ed83 100644 --- a/src/test/generated/criterion_test/data/criterion_test/advancements/break_glass_with_fish.json +++ b/src/test/generated/criterion_test/data/criterion_test/advancements/break_glass_with_fish.json @@ -5,10 +5,10 @@ "conditions": { "allowOffhand": true, "breakingBlock": { - "tag": "forge:glass" + "blocks": "#forge:glass" }, "holdingItem": { - "tag": "criterion_test:fish" + "items": "#criterion_test:fish" } }, "trigger": "criterion_test:criterion" @@ -17,7 +17,8 @@ "display": { "description": "Fish wins!", "icon": { - "item": "minecraft:cod" + "count": 1, + "id": "minecraft:cod" }, "title": "Fish vs Glass" }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/compound_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/compound_ingredient.json index 0bf0f6ef8d..e790a36545 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/compound_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/compound_ingredient.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/difference_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/difference_ingredient.json index 28a43bd0f7..76023b312f 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/difference_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/difference_ingredient.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/intersection_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/intersection_ingredient.json index 64b2f7224c..7007749f42 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/intersection_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/intersection_ingredient.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_damage_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_damage_only.json index 843ddb3e64..a386e76d1e 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_damage_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_damage_only.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_name_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_name_only.json index 93da29cc80..91a2e6698e 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_name_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/partial_nbt_name_only.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/strict_nbt_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/strict_nbt_ingredient.json index 9aa9e8128d..b385e37c70 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/strict_nbt_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/advancements/recipes/misc/strict_nbt_ingredient.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:dirt" - ] + "items": "minecraft:dirt" } ] }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/compound_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/compound_ingredient.json index e5bfed2410..524d6ec129 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/compound_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/compound_ingredient.json @@ -8,21 +8,25 @@ { "type": "forge:nbt", "stack": { - "Count": 1, - "id": "minecraft:dirt", - "tag": { - "Name": "{\"text\":\"Test Item\"}" - } + "components": { + "minecraft:custom_data": { + "display_name": "{\"text\":\"Test Item\"}" + } + }, + "count": 1, + "id": "minecraft:dirt" } }, { "type": "forge:nbt", "stack": { - "Count": 1, - "id": "minecraft:oak_log", - "tag": { - "Name": "{\"text\":\"Test Item\"}" - } + "components": { + "minecraft:custom_data": { + "display_name": "{\"text\":\"Test Item\"}" + } + }, + "count": 1, + "id": "minecraft:oak_log" } } ] @@ -33,6 +37,7 @@ " X " ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/difference_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/difference_ingredient.json index 78a627d515..0a8b17be8d 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/difference_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/difference_ingredient.json @@ -18,6 +18,7 @@ " X " ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/intersection_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/intersection_ingredient.json index c4de8d30f6..75ba21f254 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/intersection_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/intersection_ingredient.json @@ -20,6 +20,7 @@ " X " ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_damage_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_damage_only.json index a23f6c2865..509f47aec6 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_damage_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_damage_only.json @@ -9,7 +9,7 @@ "minecraft:stone_pickaxe", "minecraft:iron_pickaxe" ], - "nbt": "{Damage:3}" + "nbt": "{damage:3}" } }, "pattern": [ @@ -17,6 +17,7 @@ "XXX" ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_name_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_name_only.json index 1d68d79888..0953c62977 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_name_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/partial_nbt_name_only.json @@ -9,13 +9,14 @@ "minecraft:stone_pickaxe", "minecraft:iron_pickaxe" ], - "nbt": "{Name:'{\"text\":\"Test Item\"}'}" + "nbt": "{display_name:'{\"text\":\"Test Item\"}'}" } }, "pattern": [ "XXX" ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/strict_nbt_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/strict_nbt_ingredient.json index cfc104444b..70a54060f7 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/strict_nbt_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipes/strict_nbt_ingredient.json @@ -5,11 +5,13 @@ "X": { "type": "forge:nbt", "stack": { - "Count": 1, - "id": "minecraft:iron_pickaxe", - "tag": { - "Damage": 3 - } + "components": { + "minecraft:custom_data": { + "display_name": "{\"text\":\"Test Item\"}" + } + }, + "count": 1, + "id": "minecraft:diamond_pickaxe" } } }, @@ -17,6 +19,7 @@ "XXX" ], "result": { - "item": "minecraft:dirt" + "count": 1, + "id": "minecraft:dirt" } } \ No newline at end of file diff --git a/src/test/generated/datapack_builtin_entries_provider_test/data/datapack_builtin_entries_provider_test/biome_modifier/mossy_stone_modifier.json b/src/test/generated/datapack_builtin_entries_provider_test/data/datapack_builtin_entries_provider_test/forge/biome_modifier/mossy_stone_modifier.json similarity index 100% rename from src/test/generated/datapack_builtin_entries_provider_test/data/datapack_builtin_entries_provider_test/biome_modifier/mossy_stone_modifier.json rename to src/test/generated/datapack_builtin_entries_provider_test/data/datapack_builtin_entries_provider_test/forge/biome_modifier/mossy_stone_modifier.json diff --git a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/bamboo_silk.json b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/bamboo_silk.json index 09924fa32e..67e50d49e9 100644 --- a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/bamboo_silk.json +++ b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/bamboo_silk.json @@ -4,9 +4,7 @@ { "condition": "minecraft:match_tool", "predicate": { - "items": [ - "minecraft:bamboo" - ] + "items": "minecraft:bamboo" } } ] diff --git a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/smelting.json b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/smelting.json index 09b17fd901..2a9b58fa01 100644 --- a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/smelting.json +++ b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/smelting.json @@ -4,14 +4,16 @@ { "condition": "minecraft:match_tool", "predicate": { - "enchantments": [ - { - "enchantment": "global_loot_test:smelt", - "levels": { - "min": 1 + "predicates": { + "minecraft:enchantments": [ + { + "enchantment": "global_loot_test:smelt", + "levels": { + "min": 1 + } } - } - ] + ] + } } } ] diff --git a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/wheat_harvest.json b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/wheat_harvest.json index e2cdba2d4d..90e8896d15 100644 --- a/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/wheat_harvest.json +++ b/src/test/generated/global_loot_test/data/global_loot_test/loot_modifiers/wheat_harvest.json @@ -4,9 +4,7 @@ { "condition": "minecraft:match_tool", "predicate": { - "items": [ - "minecraft:shears" - ] + "items": "minecraft:shears" } }, { diff --git a/src/test/generated/mdk_datagen/pack.mcmeta b/src/test/generated/mdk_datagen/pack.mcmeta index e1651af8da..0b98554228 100644 --- a/src/test/generated/mdk_datagen/pack.mcmeta +++ b/src/test/generated/mdk_datagen/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { "description": "${mod_id} resources", - "pack_format": 22 + "pack_format": 32 } } \ No newline at end of file diff --git a/src/test/generated/test_helper_mod/pack.mcmeta b/src/test/generated/test_helper_mod/pack.mcmeta index f4cd0728f8..a0d2e1c873 100644 --- a/src/test/generated/test_helper_mod/pack.mcmeta +++ b/src/test/generated/test_helper_mod/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { "description": "Forge tests resource pack", - "pack_format": 22 + "pack_format": 32 } } \ No newline at end of file diff --git a/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java b/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java index 6e23af6e76..e9d3f59194 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java @@ -5,6 +5,9 @@ package net.minecraftforge.debug.gameplay.crafting; +import java.util.concurrent.CompletableFuture; + +import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.RecipeCategory; import net.minecraft.data.recipes.RecipeOutput; @@ -39,7 +42,7 @@ public class ConditionalRecipeTest extends BaseTestMod { @SubscribeEvent public void gatherData(GatherDataEvent event) { var gen = event.getGenerator(); - gen.addProvider(event.includeServer(), new Recipes(gen.getPackOutput())); + gen.addProvider(event.includeServer(), new Recipes(gen.getPackOutput(), event.getLookupProvider())); } private static ResourceLocation rl(String path) { @@ -156,8 +159,8 @@ public class ConditionalRecipeTest extends BaseTestMod { } public static class Recipes extends RecipeProvider implements IConditionBuilder { - public Recipes(PackOutput gen) { - super(gen); + public Recipes(PackOutput gen, CompletableFuture lookup) { + super(gen, lookup); } @Override diff --git a/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java b/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java index e08bef7037..ef5a749cbd 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java @@ -11,6 +11,7 @@ import java.util.function.Function; import org.jetbrains.annotations.Nullable; import net.minecraft.core.HolderLookup; +import net.minecraft.core.component.DataComponents; import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.RecipeCategory; import net.minecraft.data.recipes.RecipeOutput; @@ -28,6 +29,7 @@ import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.ItemLike; @@ -47,7 +49,9 @@ import net.minecraftforge.test.BaseTestMod; @Mod(CustomIngredientsTest.MODID) public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { static final String MODID = "custom_ingredients"; + private static final String TAG_DAMAGE = "damage"; private static final int TEST_DAMAGE = 3; + private static final String TAG_DISPLAY_NAME = "display_name"; private static final String TEST_DISPLAY_NAME = "{\"text\":\"Test Item\"}"; private static final TagKey LEFT = tag("left"); private static final TagKey RIGHT = tag("right"); @@ -62,7 +66,7 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { var blockTags = new BlockTagsGen(out, look, exist); gen.addProvider(event.includeServer(), blockTags); gen.addProvider(event.includeServer(), new ItemTagsGen(out, look, blockTags, exist)); - gen.addProvider(event.includeServer(), new Recipes(out)); + gen.addProvider(event.includeServer(), new Recipes(out, event.getLookupProvider())); } private static ResourceLocation rl(String path) { @@ -90,13 +94,13 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { private static CompoundTag named() { return CompoundTag.builder() - .put(ItemStack.TAG_DISPLAY_NAME, TEST_DISPLAY_NAME) + .put(TAG_DISPLAY_NAME, TEST_DISPLAY_NAME) .build(); } private static CompoundTag damaged() { return CompoundTag.builder() - .putInt(ItemStack.TAG_DAMAGE, TEST_DAMAGE) + .putInt(TAG_DAMAGE, TEST_DAMAGE) .build(); } @@ -114,7 +118,7 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { private static ItemStack tagged(ItemLike item, CompoundTag tag) { var ret = stack(item); - ret.setTag(tag.copy()); + ret.set(DataComponents.CUSTOM_DATA, CustomData.of(tag)); return ret; } @@ -185,9 +189,9 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { .define('X', stack) .build(); - assertRecipeMiss(helper, RecipeType.CRAFTING, container.apply(stack(Items.IRON_PICKAXE))); - assertRecipeMatch(helper, RecipeType.CRAFTING, container.apply(damaged(Items.IRON_PICKAXE)), "strict_nbt_ingredient"); - assertRecipeMiss(helper, RecipeType.CRAFTING, container.apply(damaged(Items.STONE_PICKAXE))); + assertRecipeMiss(helper, RecipeType.CRAFTING, container.apply(stack(Items.DIAMOND_PICKAXE))); + assertRecipeMatch(helper, RecipeType.CRAFTING, container.apply(named(Items.DIAMOND_PICKAXE)), "strict_nbt_ingredient"); + assertRecipeMiss(helper, RecipeType.CRAFTING, container.apply(named(Items.NETHERITE_PICKAXE))); } @GameTest(template = "forge:empty3x3x3") @@ -242,8 +246,8 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { } private static class Recipes extends RecipeProvider implements IConditionBuilder, IIngredientBuilder, INBTBuilder{ - public Recipes(PackOutput gen) { - super(gen); + public Recipes(PackOutput gen, CompletableFuture lookup) { + super(gen, lookup); } private static ShapedRecipeBuilder shaped() { @@ -294,7 +298,7 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { // strict NBT match - should match an unnamed pickaxe that lost 3 durability shaped() .pattern("XXX") - .define('X', strictNbt(damaged(Items.IRON_PICKAXE))) + .define('X', strictNbt(named(Items.DIAMOND_PICKAXE))) .unlockedBy(hasName, has) .save(out, rl("strict_nbt_ingredient")); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java b/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java index 6f2f2f8b75..7cc7820db2 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java @@ -44,8 +44,8 @@ public final class BreakWithItemCriterion extends SimpleCriterionTrigger it.breakingBlock.matches((ServerLevel) player.level(), block) && ( - it.holdingItem.matches(player.getItemInHand(InteractionHand.MAIN_HAND)) || - it.allowOffHand && it.holdingItem.matches(player.getItemInHand(InteractionHand.OFF_HAND)) + it.holdingItem.test(player.getItemInHand(InteractionHand.MAIN_HAND)) || + it.allowOffHand && it.holdingItem.test(player.getItemInHand(InteractionHand.OFF_HAND)) )); } diff --git a/src/test/java/net/minecraftforge/debug/gameplay/data/DatapackBuiltinEntriesProviderTest.java b/src/test/java/net/minecraftforge/debug/gameplay/data/DatapackBuiltinEntriesProviderTest.java index 758b24f5f2..374bbcae96 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/data/DatapackBuiltinEntriesProviderTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/data/DatapackBuiltinEntriesProviderTest.java @@ -5,19 +5,14 @@ package net.minecraftforge.debug.gameplay.data; -import net.minecraft.DetectedVersion; -import net.minecraft.core.*; +import net.minecraft.core.HolderSet; +import net.minecraft.core.RegistrySetBuilder; import net.minecraft.core.registries.Registries; -import net.minecraft.data.metadata.PackMetadataGenerator; -import net.minecraft.data.worldgen.BootstapContext; -import net.minecraft.network.chat.Component; +import net.minecraft.data.worldgen.BootstrapContext; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.PackType; -import net.minecraft.server.packs.metadata.pack.PackMetadataSection; import net.minecraft.tags.BiomeTags; import net.minecraft.tags.BlockTags; -import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.VerticalAnchor; @@ -77,7 +72,7 @@ public class DatapackBuiltinEntriesProviderTest extends BaseTestMod { } // Registers the mossy stone feature - private void createFeature(BootstapContext> context) { + private void createFeature(BootstrapContext> context) { context.register(MOSSY_STONE_FEATURE, new ConfiguredFeature<>( Feature.ORE, new OreConfiguration(MOSSY_STONE_TARGETS.get(), 5) @@ -85,8 +80,8 @@ public class DatapackBuiltinEntriesProviderTest extends BaseTestMod { } // Registers the mossy stone placement - private void createPlacement(BootstapContext context) { - HolderGetter> featureRegistry = context.lookup(Registries.CONFIGURED_FEATURE); + private void createPlacement(BootstrapContext context) { + var featureRegistry = context.lookup(Registries.CONFIGURED_FEATURE); context.register(MOSSY_STONE_PLACEMENT, new PlacedFeature( featureRegistry.getOrThrow(MOSSY_STONE_FEATURE), List.of(CountPlacement.of(8), InSquarePlacement.spread(), HeightRangePlacement.uniform(VerticalAnchor.absolute(-64), VerticalAnchor.absolute(64)), BiomeFilter.biome()) @@ -94,9 +89,9 @@ public class DatapackBuiltinEntriesProviderTest extends BaseTestMod { } // Registers the mossy stone biome modifier - private void createModifier(BootstapContext context) { - HolderGetter biomeRegistry = context.lookup(Registries.BIOME); - HolderGetter placementRegistry = context.lookup(Registries.PLACED_FEATURE); + private void createModifier(BootstrapContext context) { + var biomeRegistry = context.lookup(Registries.BIOME); + var placementRegistry = context.lookup(Registries.PLACED_FEATURE); context.register(MOSSY_STONE_MODIFIER, new ForgeBiomeModifiers.AddFeaturesBiomeModifier( biomeRegistry.getOrThrow(BiomeTags.IS_OVERWORLD), HolderSet.direct(placementRegistry.getOrThrow(MOSSY_STONE_PLACEMENT)), diff --git a/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java b/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java index 4d2e18ab8c..7c2feb8b07 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java @@ -6,6 +6,7 @@ package net.minecraftforge.debug.gameplay.loot; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.data.loot.LootTableProvider; @@ -32,6 +33,7 @@ import net.minecraftforge.registries.RegistryObject; import java.util.List; import java.util.Set; +import java.util.concurrent.CompletableFuture; @Mod(ConditionalLootPools.MODID) @GameTestHolder("forge." + ConditionalLootPools.MODID) @@ -43,7 +45,7 @@ public class ConditionalLootPools extends BaseTestMod { @SubscribeEvent public void runData(GatherDataEvent event) { - event.getGenerator().addProvider(event.includeServer(), new LootProvider(event.getGenerator().getPackOutput())); + event.getGenerator().addProvider(event.includeServer(), new LootProvider(event.getGenerator().getPackOutput(), event.getLookupProvider())); } @GameTest(template = "forge:empty3x3x3") @@ -61,10 +63,10 @@ public class ConditionalLootPools extends BaseTestMod { } private static class LootProvider extends LootTableProvider { - public LootProvider(PackOutput out) { + public LootProvider(PackOutput out, CompletableFuture lookup) { super(out, Set.of(), List.of( new LootTableProvider.SubProviderEntry(BlockLoot::new, LootContextParamSets.BLOCK) - )); + ), lookup); } } diff --git a/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java b/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java index 1b4c1d23a8..4ebceeb348 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java @@ -7,12 +7,17 @@ package net.minecraftforge.debug.gameplay.loot; import com.google.common.base.Suppliers; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.advancements.critereon.EnchantmentPredicate; +import net.minecraft.advancements.critereon.ItemEnchantmentsPredicate; import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.advancements.critereon.ItemSubPredicates; import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.component.DataComponents; import net.minecraft.util.ExtraCodecs; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -22,11 +27,11 @@ import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.data.loot.LootTableProvider; import net.minecraft.gametest.framework.GameTest; import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.tags.ItemTags; import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.Enchantment.Rarity; -import net.minecraft.world.item.enchantment.EnchantmentCategory; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.item.enchantment.ItemEnchantments; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.SimpleContainer; @@ -59,8 +64,8 @@ import net.minecraftforge.registries.ForgeRegistries; import org.jetbrains.annotations.NotNull; import java.util.List; -import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -69,7 +74,7 @@ import java.util.stream.Collectors; public class GlobalLootModifiersTest extends BaseTestMod { public static final String MODID = "global_loot_test"; - private static final DeferredRegister> GLM = DeferredRegister.create(ForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, MODID); + private static final DeferredRegister> GLM = DeferredRegister.create(ForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, MODID); static { GLM.register("multiply_loot", MultiplyDropsModifier.CODEC); GLM.register("smelting", SmeltingEnchantmentModifier.CODEC); @@ -78,7 +83,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { } private static final DeferredRegister ENCHANTS = DeferredRegister.create(ForgeRegistries.ENCHANTMENTS, MODID); - private static final RegistryObject SMELT = ENCHANTS.register("smelt", () -> new SmelterEnchantment(Rarity.UNCOMMON, EnchantmentCategory.DIGGER, EquipmentSlot.MAINHAND)); + private static final RegistryObject SMELT = ENCHANTS.register("smelt", () -> new Enchantment(Enchantment.definition(ItemTags.MINING_LOOT_ENCHANTABLE, 1, 1, Enchantment.constantCost(15), Enchantment.constantCost(15), 5, EquipmentSlot.MAINHAND))); private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); private static final RegistryObject TEST_BLOCK = BLOCKS.register("test", () -> new Block(BlockBehaviour.Properties.of())); @@ -86,17 +91,21 @@ public class GlobalLootModifiersTest extends BaseTestMod { private static final RegistryObject TEST_ITEM = ITEMS.register("test", () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties())); public GlobalLootModifiersTest() { - testItem(() -> { - var smelt = new ItemStack(Items.IRON_AXE); - EnchantmentHelper.setEnchantments(Map.of(SMELT.get(), 1), smelt); - return smelt; - }); + testItem(() -> getTestItem()); + } + + private static ItemStack getTestItem() { + var smelt = new ItemStack(Items.IRON_AXE); + var enchants = new ItemEnchantments.Mutable(EnchantmentHelper.getEnchantmentsForCrafting(smelt)); + enchants.set(SMELT.get(), 1); + smelt.set(DataComponents.ENCHANTMENTS, enchants.toImmutable()); + return smelt; } @SubscribeEvent public void runData(GatherDataEvent event) { - event.getGenerator().addProvider(event.includeServer(), new DataProvider(event.getGenerator().getPackOutput(), MODID)); - event.getGenerator().addProvider(event.includeServer(), new LootProvider(event.getGenerator().getPackOutput())); + event.getGenerator().addProvider(event.includeServer(), new DataProvider(event.getGenerator().getPackOutput(), MODID, event.getLookupProvider())); + event.getGenerator().addProvider(event.includeServer(), new LootProvider(event.getGenerator().getPackOutput(), event.getLookupProvider())); } @GameTest(template = "forge:empty3x3x3") @@ -104,8 +113,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { var center = new BlockPos(1, 1, 1); helper.setBlock(center, Blocks.OAK_LOG); - var smelt = new ItemStack(Items.IRON_AXE); - EnchantmentHelper.setEnchantments(Map.of(SMELT.get(), 1), smelt); + var smelt = getTestItem(); var player = helper.makeMockServerPlayer(); player.setItemSlot(EquipmentSlot.MAINHAND, smelt); @@ -135,8 +143,8 @@ public class GlobalLootModifiersTest extends BaseTestMod { } private static class DataProvider extends GlobalLootModifierProvider { - public DataProvider(PackOutput output, String modid) { - super(output, modid); + public DataProvider(PackOutput output, String modid, CompletableFuture registries) { + super(output, modid, registries); } @Override @@ -144,9 +152,13 @@ public class GlobalLootModifiersTest extends BaseTestMod { add("smelting", new SmeltingEnchantmentModifier( new LootItemCondition[]{ MatchTool.toolMatches( - ItemPredicate.Builder.item().hasEnchantment( - new EnchantmentPredicate(SMELT.get(), MinMaxBounds.Ints.atLeast(1)) - ) + ItemPredicate.Builder.item() + .withSubPredicate( + ItemSubPredicates.ENCHANTMENTS, + ItemEnchantmentsPredicate.enchantments(List.of( + new EnchantmentPredicate(SMELT.getHolder(), MinMaxBounds.Ints.atLeast(1)) + )) + ) ).build() }) ); @@ -161,7 +173,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { add("multiply_loot", new MultiplyDropsModifier( new LootItemCondition[] { - LootTableIdCondition.builder(TEST_BLOCK.get().getLootTable()).build() + LootTableIdCondition.builder(TEST_BLOCK.get().getLootTable().location()).build() }, 2) ); @@ -175,10 +187,10 @@ public class GlobalLootModifiersTest extends BaseTestMod { } private static class LootProvider extends LootTableProvider { - public LootProvider(PackOutput out) { + public LootProvider(PackOutput out, CompletableFuture lookup) { super(out, Set.of(), List.of( new LootTableProvider.SubProviderEntry(BlockLoot::new, LootContextParamSets.BLOCK) - )); + ), lookup); } private static class BlockLoot extends BlockLootSubProvider implements IConditionBuilder { @@ -198,18 +210,12 @@ public class GlobalLootModifiersTest extends BaseTestMod { } } - private static class SmelterEnchantment extends Enchantment { - protected SmelterEnchantment(Rarity rarityIn, EnchantmentCategory typeIn, EquipmentSlot... slots) { - super(rarityIn, typeIn, slots); - } - } - /** * The smelting enchantment causes this modifier to be invoked, via the smelting loot_modifier json */ private static class SmeltingEnchantmentModifier extends LootModifier { - public static final Supplier> CODEC = Suppliers.memoize(() -> - RecordCodecBuilder.create(inst -> + public static final Supplier> CODEC = Suppliers.memoize(() -> + RecordCodecBuilder.mapCodec(inst -> codecStart(inst) .apply(inst, SmeltingEnchantmentModifier::new) ) @@ -240,7 +246,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } } @@ -250,8 +256,8 @@ public class GlobalLootModifiersTest extends BaseTestMod { * */ private static class SilkTouchTestModifier extends LootModifier { - public static final Supplier> CODEC = Suppliers.memoize(() -> - RecordCodecBuilder.create(inst -> + public static final Supplier> CODEC = Suppliers.memoize(() -> + RecordCodecBuilder.mapCodec(inst -> codecStart(inst) .apply(inst, SilkTouchTestModifier::new) ) @@ -266,20 +272,20 @@ public class GlobalLootModifiersTest extends BaseTestMod { public ObjectArrayList doApply(ObjectArrayList generatedLoot, LootContext context) { var ctxTool = context.getParamOrNull(LootContextParams.TOOL); //return early if silk-touch is already applied (otherwise we'll get stuck in an infinite loop). - if (ctxTool == null || ctxTool.getEnchantmentLevel(Enchantments.SILK_TOUCH) > 0) return generatedLoot; + if (ctxTool == null || ctxTool.isEmpty() || ctxTool.getEnchantmentLevel(Enchantments.SILK_TOUCH) > 0) return generatedLoot; var fakeTool = ctxTool.copy(); fakeTool.enchant(Enchantments.SILK_TOUCH, 1); var params = new LootParams.Builder(context.getLevel()) .withParameter(LootContextParams.TOOL, fakeTool) .create(LootContextParamSets.EMPTY); - return context.getLevel().getServer().getLootData() + return context.getLevel().getServer().reloadableRegistries() .getLootTable(context.getParamOrNull(LootContextParams.BLOCK_STATE).getBlock().getLootTable()) .getRandomItems(params); } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } } @@ -290,7 +296,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { * */ private static class WheatSeedsConverterModifier extends LootModifier { - public static final Supplier> CODEC = Suppliers.memoize(() -> RecordCodecBuilder.create(inst -> codecStart(inst).and( + public static final Supplier> CODEC = Suppliers.memoize(() -> RecordCodecBuilder.mapCodec(inst -> codecStart(inst).and( inst.group( Codec.INT.fieldOf("numSeeds").forGetter(m -> m.numSeedsToConvert), ForgeRegistries.ITEMS.getCodec().fieldOf("seedItem").forGetter(m -> m.itemToCheck), @@ -331,13 +337,13 @@ public class GlobalLootModifiersTest extends BaseTestMod { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } } private static class MultiplyDropsModifier extends LootModifier { - public static final Supplier> CODEC = Suppliers.memoize(() -> RecordCodecBuilder.create(inst -> codecStart(inst) + public static final Supplier> CODEC = Suppliers.memoize(() -> RecordCodecBuilder.mapCodec(inst -> codecStart(inst) .and(ExtraCodecs.POSITIVE_INT.optionalFieldOf("multiplication_factor", 2).forGetter(m -> m.multiplicationFactor)) .apply(inst, MultiplyDropsModifier::new) )); @@ -358,7 +364,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } }