diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ea7d5307b8..f8af9a776f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -2,7 +2,7 @@ name: Publish on: push: - branches: [ '26.2' ] + branches: [ '26.1' ] permissions: contents: read diff --git a/.gitignore b/.gitignore index c134175e62..4dcbfe411a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,3 @@ -#forgedev dev if the folder exists in here -forgedev - #eclipse **/bin **/.settings @@ -25,12 +22,10 @@ forgedev /*/build /*/.gradle -# Minecraft -/run -/*.launch - # Projects repo, either ignore it, or ignore patches. -src/minecraft +/projects/mcp/ +/projects/clean/ +/projects/forge/ #occupational hazards /projects/**/build/ @@ -38,7 +33,6 @@ src/minecraft /projects/**/run/ /projects/**/*.launch /repo/ -/rejects-*/ src/*/generated/**/.cache/ # Generated by gradle every import @@ -53,8 +47,3 @@ src/*/generated/**/.cache/ /*/.factorypath /*/.apt_generated/ /fmlcore/logs/ -/lib/ -/_actual/ -/runs/ -/forge.ipr -/forge.iws diff --git a/LICENSE.txt b/LICENSE.txt index 51c22dd7db..249debe26b 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -3,7 +3,7 @@ parts herein are licensed under the terms of the LGPL 2.1 found here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and copied below. -Homepage: https://minecraftforge.net/ +Homepage: http://minecraftforge.net/ https://github.com/MinecraftForge/MinecraftForge diff --git a/build.gradle b/build.gradle index 76f7de0ad6..34c55fa107 100644 --- a/build.gradle +++ b/build.gradle @@ -1,795 +1,57 @@ -import org.apache.tools.ant.filters.ReplaceTokens +import net.minecraftforge.forge.tasks.* +import net.minecraftforge.gradleutils.PomUtils plugins { - id 'java-library' - id 'idea' + id 'net.minecraftforge.licenser' version '1.0.1' + id 'com.github.ben-manes.versions' version '0.46.0' + id 'net.minecraftforge.gradleutils' version '[2.6.4,2.7)' id 'eclipse' - id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.versions - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - alias libs.plugins.jarsigner - id 'net.minecraftforge.forgedev' - id 'net.minecraftforge.forge.build.convention' + id 'de.undercouch.download' version '5.4.0' + id 'net.minecraftforge.gradle.patcher' version '[6.0.51,6.2)' apply false + id 'net.minecraftforge.gradle.mcp' version '[6.0.51,6.2)' apply false + id 'net.minecraftforge.gradlejarsigner' version '1.0.4' + id 'org.barfuin.gradle.taskinfo' version '3.0.1' } -gradleutils.displayName = 'Forge' -group = 'net.minecraftforge' -description = 'Modifications to Minecraft to enable mod developers.' +Util.init() //Init all our extension methods! -// NOTE: See settings.gradle for all the referenceable version variables. -// All subprojects (that apply 'net.minecraftforge.forge.build.convention') will have these available. -println "Version: $version" - -java.toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) - -jarSigner.autoDetect('forge') - -// We have to tell ForgeDev to use the exact versions of tools we ship in the installer -fdtools { - configure('binpatcher') { - version = buildLibs.binarypatcher.get().version - } - configure('installertools') { - version = buildLibs.installertools.get().version - } - configure('jarcompatibilitychecker') { - javaLauncher = javaToolchains.launcherFor(java.toolchain) - } -} - -/* This is used for debugging, comparing all published artifacts against actual production -forgedev.validatePublish { - task { - baseBranch = 'upstream/26.1.2' - versionPrefix = minecraftVersion - } -} -*/ - -final minecraftFiles = forgedev.minecraftFiles(minecraftVersion) - -final mcpBase = forgedev.mcpBase { - mcpVersion = "${minecraftVersion}-${project.ext.mcpVersion}" - accessTransformers.from file('src/main/resources/META-INF/accesstransformer.cfg') - sideAnnotationStrippers.from file('src/main/resources/forge.sas') -} - -forgedev.patches { - base = mcpBase - patches = file('patches/minecraft') - patched = file('src/minecraft/java') - sourceSets.main.java.srcDir patched -} - -tasks.register('setup') { - dependsOn forgedev.patches.apply -} - -sourceSets { - named('main') { - resources.srcDir 'src/main/generated' - } - named('test') { - resources.srcDir 'src/test/generated' - } -} - -license { - header = file('LICENSE-header.txt') - - include 'net/minecraftforge/' - exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java' - - tasks.tap { - register('main') { - files.from files('src/main/java') - } - - register('test') { - files.from files('src/test/java') - } - } +ext { + VERSION = gitversion.getMCTagOffsetBranch(MC_VERSION) + FORGE_VERSION = VERSION.substring(MC_VERSION.length() + 1) } changelog { - from changelogBase - publishAll = false + from '47.999' } -// TODO [ForgeDev] Support compileOnlyApi, runtimeOnly, and a consumable annotation processor configuration -configurations { - // Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it. - register('bootstrap') { - transitive = false - canBeDeclared = true - canBeResolved = true - } - - register('installer') { - transitive = false - canBeDeclared = true - canBeResolved = true - extendsFrom(bootstrap) - } - - named('api') { - extendsFrom(installer) - } - - named('implementation') { - // Inherit vanilla Minecraft's dependencies - extendsFrom(mcpBase.dependencyConfiguration) - } +tasks.register('setup') { + dependsOn ':forge:extractMapped' + if (findProject(':clean')) + dependsOn ':clean:extractMapped' } -dependencies { - // These need to actually be on the classpath at the start. This is only used for the server shim jar. - // And this is only needed because custom file systems are REQUIRED to be on the boot classloader. - // This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project. - bootstrap libs.jarjar.fs // JarInJar file system - bootstrap libs.roimfs // JarInJar File System - FileSystems need to be on boot loader. - bootstrap libs.bundles.jimfs // In memory file system used for ForgeDev launches - bootstrap libs.securemodules // Has Union file system in it - bootstrap libs.unsafe // Needed by securemodules - bootstrap libs.bundles.asm // Needed by securemodules - - implementation libs.jopt.simple - - installer libs.bootstrap - installer libs.bootstrap.api // Needed by securemodules - installer libs.accesstransformers - installer libs.eventbus - installer libs.jspecify // Dep of EventBus - installer libs.forgespi - installer libs.coremods.api - installer libs.modlauncher - installer libs.mergetool.api - installer libs.bundles.night.config - installer libs.maven.artifact - installer libs.bundles.terminalconsoleappender - installer libs.mixin - installer libs.mixinextras.forge - installer libs.bundles.jarjar - installer libs.roimfs - - installer projects.fmlcore - installer projects.fmlloader - installer projects.fmlearlydisplay - installer projects.javafmllanguage - installer projects.lowcodelanguage - installer projects.mclanguage - installer projects.forgeTransformers - - runtimeOnly files(mcpBase.extra) - - runtimeOnly libs.bootstrap - runtimeOnly libs.bootstrap.dev - - annotationProcessor libs.eventbus.validator +tasks.register('doChecks') { + dependsOn ':forge:checkJarCompatibility' + dependsOn ':forge:publish' } -final EXTRA_TXTS = [ - file('LICENSE.txt'), - changelog.task.flatMap(task -> task.outputFile) -] -forgedev.runs { - configureEach { - options { - workingDir = layout.projectDirectory.dir("runs/$name") - - mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap' - args '--gameDir', '.' - jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' - - systemProperty 'bsl.debug', 'true' - systemProperty 'terminal.jline', 'true' - with(sourceSets.test) { - systemProperty 'forge.enableGameTest', 'true' - systemProperty 'forgedev.enableTestMods', 'true' - } - } +project(':mcp') { + apply plugin: 'net.minecraftforge.gradle.mcp' + mcp { + config MC_VERSION + '-' + MCP_VERSION + pipeline = 'joined' } - - create('client') { - options { - systemProperty 'eventbus.api.strictRuntimeChecks', 'true' - systemProperty 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll' - - args '--launchTarget', 'forge_dev_client', - '--username', 'Dev', - '--version', project.name, - '--accessToken', '0', - '--userType', 'mojang', - '--versionType', 'release', - '--assetsDir', '{assets_root}', - '--assetIndex', '{asset_index}' - } - } - - create('server') { - options { - args '--launchTarget', 'forge_dev_server' - } - } - - create('gameTestServer') { - options { - args '--launchTarget', 'forge_dev_server_gametest' - args '--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs - } - } - - create('data') { - options { - args '--launchTarget', 'forge_dev_data', - '--all', - '--existing', sourceSets.main.resources.srcDirs[0], - '--assetsDir', '{assets_root}', - '--assetIndex', '{asset_index}' - - with(sourceSets.main) { - args '--mod', 'forge', - '--output', rootProject.file('src/main/generated/') - } - - with(sourceSets.test) { - args '--mod', '.+', - '--existing', sourceSets.test.resources.srcDirs[0], - '--output', rootProject.file('src/test/generated/') - } - } - } - - create('clientData') { - options { - args '--all', - '--existing', sourceSets.main.resources.srcDirs[0], - '--assetsDir', '{assets_root}', - '--assetIndex', '{asset_index}' - - with(sourceSets.main) { - args '--launchTarget', 'forge_dev_client_data', - '--mod', 'forge', - '--output', rootProject.file('src/main/generated/'), - '--mod', 'forge' - } - - with(sourceSets.test) { - args '--launchTarget', 'forge_dev', - '--launchEntry', 'minecraft/net.minecraft.client.data.Main', - '--launchData', - '--mod', '.+', - '--existing', sourceSets.test.resources.srcDirs[0], - '--output', rootProject.file('src/test/generated/') - } - } - } -} -tasks.register('genAllData') { - dependsOn forgedev.runs.data.run, forgedev.runs.data.runTest, forgedev.runs.clientData.run, forgedev.runs.clientData.runTest -} - -final serverShim = forgedev.shim { - config { - mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap' - args = ['--launchTarget', 'forge_server'] - } - classpath { - libraries configurations.installer - library tasks.named('universalJar', Jar) - library forgedev.binaryPatches('server').apply, 'server' - serverBundle.fileProvider(minecraftFiles.server) - } - bootstrapClasspath(configurations.bootstrap) - jar { - jarSigner.sign(it) - } -} - -final finalizeSpawn = forgedev.methodCallFinder('findFinalizeSpawnTargets') { - jar.fileProvider(mcpBase.classes) - output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json') - blacklist 'net/minecraft/world/level/BaseSpawner' // Ignore this class as we special case it. - invokeVirtual('finalizeSpawn', '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;') -} - -forgedev.validateDeprecations(tasks.named('jar', Jar)) { - mcVersion = minecraftVersion -} - -forgedev.checks() { - base = mcpBase - ats {} - sas {} - execs {} - - patches { - dependsOn forgedev.patches.make - patchDir = forgedev.patches.patches - patchesWithS2SArtifact = [ - 'minecraft/net/minecraft/client/renderer/ViewArea.java.patch', - 'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch', - ] - } - - fix { - dependsOn finalizeSpawn - } - - forgedev.patches.make.configure { - finalizedBy forgedev.checks.patches.fix - } -} - -final crowdin = forgedev.crowdin // Create the crowdin tasks -tasks.named('jar', Jar) { - from(EXTRA_TXTS) - duplicatesStrategy = DuplicatesStrategy.EXCLUDE - exclude '.cache' - - from(zipTree(crowdin.flatMap { it.output } )) { - include 'assets/forge/lang/*.json' - } - - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.forge' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : gradleutils.vendor.get(), - 'Specification-Version' : gitversion.info.tag, - 'Implementation-Title' : project.group, - 'Implementation-Vendor' : gradleutils.vendor.get(), - 'Implementation-Version': forgeVersion - ], 'net/minecraftforge/versions/forge/') - attributes([ - 'Specification-Title' : 'Minecraft', - 'Specification-Vendor' : gradleutils.vendor.get(), - 'Specification-Version' : minecraftVersion, - 'Implementation-Title' : 'MCP', - 'Implementation-Vendor' : gradleutils.vendor.get(), - 'Implementation-Version': mcpVersion - ], 'net/minecraftforge/versions/mcp/') - } - jarSigner.sign(it) -} - -final universalJar = tasks.register('universalJar', Jar) { - from (zipTree(tasks.named('jar', Jar).flatMap { it.archiveFile } )) { - exclude(forgedev.filterVanilla(mcpBase.classes)) - } - manifest = tasks.named('jar', Jar).get().manifest - archiveClassifier = 'universal' - jarSigner.sign(it) -} - -final sourcesJarAll = tasks.register('sourcesJarAll', Jar) { - archiveClassifier = 'sources-all' - from(sourceSets.main.allJava.srcDirs) -} - -// Our sources, plus the patches we do to Vanilla Minecraft -final sourcesJar = tasks.register('sourcesJar', Jar) { - archiveClassifier = 'sources' - from(sourceSets.main.allJava.srcDirs - forgedev.patches.patched.asFile.get()) - mustRunAfter(forgedev.patches.make) - from(forgedev.patches.patches) { - into 'patches/' - } -} - -forgedev.userDev { - base(mcpBase) - - config { - universal universalJar - sources sourcesJar - addLibraries(configurations.installer) - // TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config - // so we don't gotta keep making exceptions for MixinExtras - addCompileDependency(libs.mixinextras.common) - addAnnotationProcessorDependency(libs.mixinextras.common) - - // TODO [ForgeDev] Consolidate Patcher + UserDev Config runs in a sane way - runs { - configureEach { - parents = [] - main = 'net.minecraftforge.bootstrap.ForgeBootstrap' - args '--gameDir', '.' - jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' - client = it.name.containsIgnoreCase('client') - environment 'MCP_MAPPINGS', '{mcp_mappings}' - } - - register('clientData') { - args '--launchTarget', "forge_userdev_client_data" - args '--assetIndex', '{asset_index}' - args '--assetsDir', '{assets_root}' - } - - register('client') { - property 'forge.enableGameTest', 'true' - args '--launchTarget', "forge_userdev_client" - args '--version', 'MOD_DEV' - args '--assetIndex', '{asset_index}' - args '--assetsDir', '{assets_root}' - } - - register('server') { - property 'forge.enableGameTest', 'true' - args '--launchTarget', "forge_userdev_server" - } - - register('gameTestServer') { - args '--launchTarget', "forge_userdev_server_gametest" - } - - register('data') { - args '--launchTarget', "forge_userdev_data" - args '--assetIndex', '{asset_index}' - args '--assetsDir', '{assets_root}' - } - } - } - patches { - modified.setFrom(sourcesJarAll.flatMap { it.archiveFile }) - } - binaryPatches { - mustRunAfter(forgedev.patches.make) - patches.setFrom(forgedev.patches.patches) - dirty.setFrom(tasks.named('jar', Jar).flatMap { it.archiveFile }) - } -} - -forgedev.userdevCompatibility(minecraftVersion) { - clean = mcpBase.classes - dirty = tasks.named('jar', Jar) -} - -// region Installer tasks, Not needed when we simplify the installer/remove obf -final clientBinPatches = forgedev.binaryPatches('client') { - clean = minecraftFiles.client - // Workaround for 3rd party launcher issues, marker needed to locate MC, store needed to fix zlib-ng issues - apply { - store = true - marker = '.forge_patched_minecraft' - } -} -final serverBinPatches = forgedev.binaryPatches('server') { - clean = minecraftFiles.serverExtracted - apply { store = true } -} -// endregion - -forgedev.installer { - dev = !forgedev.ci - offline = false - baseVersion = buildLibs.installer.get().version.toString() - - // Add extra libraries - pack serverShim.jar // The Server executable jar IS needed to be packed, as the installer would need a spec bump in order to download it - pack universalJar // I don't think this is strictly needed to be packed anymore, will need to double check later - - launcherLibrary universalJar - // We configure the launcher here to keep the order for easier diff, after publishing, move this to the LauncherJson configuration below - launcherJson { - // We create this during install, so it's not downloadable - generated(clientBinPatches.apply, 'client') - } - - launcherLibraries configurations.installer - - final launcherId = "${minecraftVersion}-${project.name}-${forgeVersion}" - final installertools = tool(buildLibs.installertools) - final binarypatcher = tool(buildLibs.binarypatcher) - - jar { - from(EXTRA_TXTS) - from(rootProject.file('/forge_installer_logo.png')) { - rename { 'big_logo.png' } - } - from(clientBinPatches.create.flatMap { t -> t.output }) { - rename { 'data/client.lzma' } - } - from(serverBinPatches.create.flatMap { t -> t.output }) { - rename { 'data/server.lzma' } - } - - final argsFile = rootProject.file('server_files/args.txt') - final tokens = [tokens: [ - SHIM_JAR_FILE: serverShim.jar.get().archiveFileName.get(), - MAVEN_PATH: forgedev.mavenArtifact.directory - ]] - from(argsFile) { - filter(tokens, ReplaceTokens) - into 'data' - rename { 'unix_args.txt' } - } - from(argsFile) { - filter(tokens, ReplaceTokens) - into 'data' - rename { 'win_args.txt' } - } - - from(rootProject.file('server_files')) { - filter(tokens, ReplaceTokens) - into 'data' - exclude 'args.txt' - } - - jarSigner.sign(it) - } - json { - icon = rootProject.file('icon.ico') - executable serverShim.jar - minecraft = minecraftVersion - profileVersion = launcherId - - final projectArtifact = "${project.group}:${project.name}:${project.version}" - - data 'MC_UNPACKED', "[net.minecraft:client:${minecraftVersion}]", "[net.minecraft:server:${minecraftVersion}:unpacked]" - data 'MC_UNPACKED_SHA', minecraftFiles.client, minecraftFiles.serverExtracted - - data 'BINPATCH', '/data/client.lzma', '/data/server.lzma' - data 'PATCHED', "[$projectArtifact:client]", "[$projectArtifact:server]" - data 'PATCHED_SHA', clientBinPatches.apply.flatMap { it.output }, serverBinPatches.apply.flatMap { it.output } - - steps = [ - extract(installertools) { - side = 'server' - archive '{INSTALLER}' - extract 'data/README.txt', '{ROOT}/README.txt' - extract 'data/run.sh', '{ROOT}/run.sh' - executable '{ROOT}/run.sh' - extract 'data/run.bat', '{ROOT}/run.bat' - optional 'data/user_jvm_args.txt', '{ROOT}/user_jvm_args.txt' - extract 'data/unix_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/unix_args.txt" - extract 'data/win_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/win_args.txt" - }, - extractBundle(installertools) { - side = 'server' - libraries() - }, - extractBundle(installertools) { - side = 'server' - jar '{MINECRAFT_JAR}', '{MC_UNPACKED}' - cache '{MC_UNPACKED}', '{MC_UNPACKED_SHA}' - }, - step(binarypatcher) { - side = 'server' - args = [ - '--clean', '{MC_UNPACKED}', - '--output', '{PATCHED}', - '--apply', '{BINPATCH}', - '--data', '--unpatched', - '--store' - ] - cache '{PATCHED}', '{PATCHED_SHA}' - }, - step(binarypatcher) { - side = 'client' - args = [ - '--clean', '{MINECRAFT_JAR}', - '--output', '{PATCHED}', - '--apply', '{BINPATCH}', - '--data', '--unpatched', - '--store', - '--marker', '.forge_patched_minecraft' - ] - cache '{PATCHED}', '{PATCHED_SHA}' - } - ] - } - - launcherJson { - // These are flags to preserve glitchy old behavior to make diffing easier, removing when migrating to production is recommended - sortLibraries = false // Don't sort, makes things non-deterministic, but easier to diff old versions - duplicateLibraries = true // Our 'bootstrap' layer go added twice - librariesLast = false // Makes libraries be added before args - - id = launcherId - inheritsFrom = minecraftVersion - mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap' - gameArgs = [ '--launchTarget', 'forge_client' ] - jvmArgs = [ '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' ] - } -} - -final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) { - gradleVersion = '9.5.0' - scriptFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradlew") - jarFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradle/wrapper/gradle-wrapper.jar") -} - -final mdkZip = tasks.register('mdkZip', Zip) { - dependsOn mdkGradleWrapper - - archiveBaseName = project.name - archiveClassifier = 'mdk' - archiveVersion = project.version - destinationDirectory = file('build/libs') - from(EXTRA_TXTS) - - from mdkGradleWrapper.map(Wrapper.&getScriptFile) - from mdkGradleWrapper.map(Wrapper.&getBatchScript) - into('gradle/wrapper/') { - from mdkGradleWrapper.map(Wrapper.&getJarFile) - from mdkGradleWrapper.map(Wrapper.&getPropertiesFile) - } - from(rootProject.file('mdk/')){ - rootProject.file('mdk/gitignore.txt').eachLine { - if (!it.trim().isEmpty() && !it.trim().startsWith('#')) - exclude it - } - filter(ReplaceTokens, tokens: [ - FORGE_VERSION: forgeVersion, - FORGE_GROUP: project.group, - FORGE_NAME: project.name, - MC_VERSION: minecraftVersion, - FORGE_SPEC_VERSION: gitversion.info.tag.split("\\.")[0], - MC_NEXT_VERSION: minecraftNextVersion, - EVENTBUS_VERSION: libs.versions.eventbus.get() - ]) - rename 'gitignore\\.txt', '.gitignore' - rename 'gitattributes\\.txt', '.gitattributes' - } - from(rootProject.file('src/test/java/com/example/examplemod/')) { - into('src/main/java/com/example/examplemod/') - } - from(rootProject.file('src/test/generated/mdk_datagen/')) { - into('src/main/resources/') - exclude '**/.cache/' - } -} - -/* -tasks.named('javadoc', Javadoc) { - description = 'Generates the combined javadocs for the FML projects and the main Forge project' - var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage', ':forge-transformers' ] - source includedProjects.collect { project(it).sourceSets.main.allJava } - classpath = classpath + files(includedProjects.collect { project(it).sourceSets.main.compileClasspath }) - - var docsDir = rootProject.file('src/docs/') - inputs.dir(docsDir) - .withPropertyName('docs resources directory') - .withPathSensitivity(PathSensitivity.RELATIVE) - .optional() - - failOnError = false - - // Exclude the Minecraft classes if not enabled - if (!project.hasProperty('generateAllDocumentation')) { - exclude 'net/minecraft/**' - exclude 'com/mojang/**' - } - exclude 'mcp/**' - - options { - stylesheetFile = new File(docsDir, 'stylesheet.css') - - tags = [ - 'apiNote:a:API Note:', - 'implSpec:a:Implementation Requirements:', - 'implNote:a:Implementation Note:' - ] - - groups = [ - 'Forge Mod Loader': [ - 'net.minecraftforge.fml.common.asm*', - 'net.minecraftforge.fml.loading*', - 'net.minecraftforge.fml.server*' - ], - 'FML Core': [ - 'net.minecraftforge.fml', - 'net.minecraftforge.fml.config*', - 'net.minecraftforge.fml.event*', - 'net.minecraftforge.fml.util*' - ], - 'FML Common': [ - 'net.minecraftforge.fml.core', - 'net.minecraftforge.fml.event.config', - 'net.minecraftforge.fml.event.lifecycle' - ], - 'FML Java/MC Language Providers': [ - 'net.minecraftforge.fml.common', - 'net.minecraftforge.fml.javafmlmod', - 'net.minecraftforge.fml.mclanguageprovider' - ], - 'Minecraft Forge API': [ - 'net.minecraftforge*' - ] - ] - - author = false - noSince = true - noHelp = true - - bottom = "Minecraft Forge is an open source modding API for Minecraft: Java Edition, licensed under the Lesser GNU General Public License, version 2.1." - windowTitle = "Minecraft Forge API ${version}" - docTitle = "Minecraft Forge API - ${forgeVersion} for Minecraft ${minecraftVersion}" - header = "
${forgeVersion} for Minecraft ${minecraftVersion}
" - } - - doLast { - project.copy { - from docsDir - exclude '/stylesheet.css' - into destinationDir - } - } -} -*/ - -publishing { repositories { - maven gradleutils.publishingForgeMaven + mavenLocal() } +} - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - artifact universalJar - artifact forgedev.installer.jar - artifact mdkZip - artifact forgedev.userDev.jar - artifact sourcesJar - artifact serverShim.jar - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } +if (System.env.TEAMCITY_VERSION) { + //Only setup the CI environment if and only if the environment variables are set. + tasks.named('configureTeamCity').configure { + doLast { + println "##teamcity[buildNumber '${project(':forge').version}']" + println "##teamcity[setParameter name='env.PUBLISHED_JAVA_ARTIFACT_VERSION' value='${project(':forge').version}']" } } } - - -/* -// These are debugging tasks that are only used when developing ForgeDevPlugin, to bulk test task's config/caching -// region ForgeDev Tests -def all = tasks.register('all') {} -afterEvaluate { - if (gradle.startParameter.taskNames.contains('all')) { - tasks.forEach { task -> // This forces everything to be realized, which is why we have the startParameter check - if (!gradle.startParameter.isTaskGraph() && task.name.startsWith('run')) return - if (task.name in [all.name, 'dependencyInsight', 'dependencies', 'dependencyUpdates', 'init', 'buildEnvironment', 'idea', - 'eclipse', 'javaToolchains', 'outgoingVariants', 'projects', 'properties', 'resolvableConfigurations', 'tasks', 'updateDaemonJvm', - 'generateActionsWorkflow' - ]) return - if (task.name.startsWith('clean')) return - if (task.name == 'checkJarCompatibility') return // This doesn't work in FG6 dev, I think it's cuz we check vs srg names. Will need to look at later - all.configure { dependsOn(task) } - } - } -} -*/ -// endregion -// We dont have any unit tests, so disable this error -tasks.withType(AbstractTestTask).configureEach { - failOnNoDiscoveredTests = false -} -// This shouldn't be needed according to the Gradle devs, as we never run these commands together. -// But in another case of Gradle being gradle, here we are -[ 'makePatches', 'compileJava', 'checkLicenseMain', 'updateLicenseMain', 'sourcesJar', 'sourcesJarAll' ] - .each{ tasks.named(it).configure{ mustRunAfter forgedev.patches.apply }} -forgedev.runs.configureEach { - run.configure { dependsOn finalizeSpawn} - runTest.configure { dependsOn finalizeSpawn} -} -// run gradlew dependencyUpdates --no-parallel -//noinspection UnnecessaryQualifiedReference -tasks.named('dependencyUpdates', com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask) { - resolutionStrategy { - mcpBase.dependencies.get().forEach {dep -> force(dep) } // Force all vanilla dependencies to their correct versions - force(earlyDisplayLibs.slf4j.jdk14) // Force slf4j implementation, its tied to the api from the manifest - } -} \ No newline at end of file diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore new file mode 100644 index 0000000000..2979d33310 --- /dev/null +++ b/buildSrc/.gitignore @@ -0,0 +1,3 @@ +/.gradle/ +/build/ +/out/ diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000000..c3e2c4e2b5 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,14 @@ +repositories { + maven { url = 'https://maven.minecraftforge.net/' } + mavenCentral() +} + +dependencies { + implementation 'org.ow2.asm:asm:9.9.1' + implementation 'org.ow2.asm:asm-tree:9.9.1' + implementation 'net.minecraftforge:srgutils:0.6.2' + implementation 'net.minecraftforge:JarJarMetadata:0.3.27' + 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.7.0.202309050840-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 new file mode 100644 index 0000000000..ad9bed5f55 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy @@ -0,0 +1,67 @@ +package net.minecraftforge.forge.tasks + +import org.gradle.api.tasks.* +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.bundling.AbstractArchiveTask + +import java.util.zip.ZipFile + +abstract class BundleList extends DefaultTask { + @InputFiles abstract ConfigurableFileCollection getConfig() + @InputFile abstract RegularFileProperty getServerBundle() + @OutputFile abstract RegularFileProperty getOutput() + + BundleList() { + config.setFrom(project.configurations.installer) + output.convention(project.layout.buildDirectory.file("$name/output.list")) + configure { + dependsOn(project.tasks.universalJar) + inputs.file(project.tasks.universalJar.archiveFile) + dependsOn(project.tasks.applyServerBinPatches) + inputs.file(project.tasks.applyServerBinPatches.output) + } + } + + @TaskAction + void run() { + def entries = [:] as TreeMap + def resolved = project.configurations.installer.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 + entries.put("$info.art.group:$info.art.name:$info.art.classifier", "$file.sha256\t$info.name\t$info.path") + + var classifier = 'server' + var genned = project.tasks.applyServerBinPatches + info = Util.getMavenInfoFromTask(genned, classifier) + file = genned.output.get().asFile + entries.put("$info.art.group:$info.art.name:$info.art.classifier", "$file.sha256\t$info.name\t$info.path") + + try (def zip = new ZipFile(serverBundle.get().asFile)) { + def entry = zip.getEntry('META-INF/libraries.list') + def data = zip.getInputStream(entry).text.split('\n') + for (def line : data) { + def (sha, artifact, path) = line.split('\t') + def (group, name, other) = artifact.split(':', 3) + //println("Group: $group Name: $name") + def key = "$group:$name" + if (other.indexOf(':') != -1){ + key += ':' + other.split(':', 2)[1] + //println("\tKey: $key") + } + if (!entries.containsKey(key)) + entries.put(key, line) + } + } + + output.get().asFile.text = entries.values().join('\n') + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodeFinder.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodeFinder.groovy new file mode 100644 index 0000000000..8f8271f490 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodeFinder.groovy @@ -0,0 +1,52 @@ +package net.minecraftforge.forge.tasks + +import groovy.json.JsonBuilder +import groovy.transform.CompileStatic +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.TaskAction +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.FieldNode +import org.objectweb.asm.tree.MethodNode + +@CompileStatic +abstract class BytecodeFinder extends DefaultTask { + @InputFile abstract RegularFileProperty getJar() + // It should be fine to mark the output as internal as we want to control when we run it anyways. + // This also shuts Gradle 8 up about implicit task dependencies. + @Internal abstract RegularFileProperty getOutput() + + BytecodeFinder() { + output.convention(project.layout.buildDirectory.dir(name).map { it.file("output.json") }) + } + + @TaskAction + protected void exec() { + Util.init() + + var outputFile = output.get().asFile + if (outputFile.exists()) + outputFile.delete() + + pre() + + Util.processClassNodes(jar.get().asFile, this.&process) + + post() + outputFile.text = new JsonBuilder(getData()).toPrettyString() + } + + + protected process(ClassNode node) { + if (node.fields !== null) node.fields.each { process(node, it) } + if (node.methods !== null) node.methods.each { process(node, it) } + } + + protected pre() {} + protected process(ClassNode parent, FieldNode node) {} + protected process(ClassNode parent, MethodNode node) {} + protected post() {} + protected abstract Object getData() +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodePredicateFinder.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodePredicateFinder.groovy new file mode 100644 index 0000000000..b0efa482cc --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BytecodePredicateFinder.groovy @@ -0,0 +1,48 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.CompileStatic +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Internal +import org.objectweb.asm.Opcodes +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.MethodNode + +@CompileStatic +abstract class BytecodePredicateFinder extends BytecodeFinder { + + @Internal + abstract Property> getPredicate() + + private final Map> matches = new TreeMap<>(Comparator.naturalOrder()) + + @Override + protected process(ClassNode parent, MethodNode node) { + for (final current : node.instructions) { + if (predicate.get().call(parent, node, current)) { + var methods = matches.compute(parent.name, { k, v -> v ?: new ArrayList<>() }) + + // only add non-synthetic methods + if ((node.access & Opcodes.ACC_SYNTHETIC) == 0) { + methods.add(node.name + node.desc) + } + + return + } + } + } + + @Internal + @Override + protected Object getData() { + var array = new ArrayList() + matches.forEach { c, m -> + { + array.add( + 'class': c, + 'methods': m + ) + } + } + return array ?: { throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.') }() + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/CleanProperties.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/CleanProperties.groovy new file mode 100644 index 0000000000..676ac30300 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/CleanProperties.groovy @@ -0,0 +1,97 @@ +package net.minecraftforge.forge.tasks; + +import groovy.transform.CompileDynamic; +import groovy.transform.CompileStatic; + +import java.util.Properties; +import java.util.Enumeration; +import java.util.Map; +import java.util.TreeSet; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.Reader; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Set; + +/** + * Eclipse config files are literally just java properties, with the header cleaned up. + * https://github.com/eclipse/buildship/blob/5b2c7fca7fa86cd74d71b3c099c7b1559eba038e/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/configuration/PreferenceStore.java#L238 + * + * This does the same thing, as well as sorting alphabetically. + * It also ignores all comments. We can add them latter if someone cares. + */ +@CompileStatic +public class CleanProperties extends Properties { + private static final long serialVersionUID = 1L; + private static final String LINE_SEP = System.getProperty("line.separator"); + private static final String UNIX_LINE_SEP = "\n"; + private static final Charset ENCODING = StandardCharsets.UTF_8; + + public CleanProperties load(File input) throws IOException { + if (input.exists()) { + try (Reader is = new InputStreamReader(new FileInputStream(input), ENCODING)) { + super.load(is); + } + } + return this; + } + + public void store(File out) throws IOException { + if (!out.getParentFile().exists()) + out.getParentFile().mkdirs(); + + try (OutputStream os = new FileOutputStream(out)) { + store(os, null); + } + } + + @Override + public synchronized Enumeration keys() { + Set ret = new TreeSet<>(); + for (Enumeration e = super.keys(); e.hasMoreElements();) + ret.add(e.nextElement()); + return Collections.enumeration(ret); + } + + @CompileDynamic + @Override + public Set> entrySet() { + Set> ret = new TreeSet<>((l, r) -> ((String)l.getKey()).compareTo((String)r.getKey())); + ret.addAll(super.entrySet()); + return ret; + } + + @Override + public void store(OutputStream out, String comments) throws IOException { + out.write(clean().getBytes(ENCODING)); + out.flush(); + } + + @Override + public void store(Writer out, String comments) throws IOException { + out.write(clean()); + out.flush(); + } + + private String clean() throws IOException { + ByteArrayOutputStream tmp = new ByteArrayOutputStream(); + try { + super.store(tmp, null); + } finally { + tmp.close(); + } + + String ret = tmp.toString(ENCODING).replace(LINE_SEP, UNIX_LINE_SEP); + ret = ret.substring(ret.indexOf(UNIX_LINE_SEP) + 1); + return ret; + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ClosureHelper.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ClosureHelper.groovy new file mode 100644 index 0000000000..348ca2cfe2 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ClosureHelper.groovy @@ -0,0 +1,33 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.stc.FirstParam + +import java.util.function.BiConsumer + +public class ClosureHelper { + BiConsumer callback + + public ClosureHelper(Closure cl, BiConsumer callback) { + this.callback = callback + apply(this, cl) + } + + + def methodMissing(String name, Object args) { + if (!args.class.isArray()) return + Object[] aargs = (Object[])args + + if (aargs.length == 1 && aargs[0] instanceof Closure) { + this.callback.accept(name, (Closure)aargs[0]) + } else { + throw new IllegalArgumentException('Unknown method: "' + name + '" with arguments ' + args + ' for ' + this) + } + } + + static T apply(T obj, @DelegatesTo(value = FirstParam, strategy = Closure.DELEGATE_FIRST) Closure cl) { + cl.delegate = obj + cl.resolveStrategy = Closure.DELEGATE_FIRST + cl() + return obj + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DownloadLibraries.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DownloadLibraries.groovy new file mode 100644 index 0000000000..c3f98258ff --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DownloadLibraries.groovy @@ -0,0 +1,54 @@ +package net.minecraftforge.forge.tasks + +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.OutputFiles +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.OutputDirectory + +import java.nio.file.Files + +abstract class DownloadLibraries extends DefaultTask { + @InputFile abstract RegularFileProperty getInput() + @OutputDirectory abstract DirectoryProperty getOutput() + @OutputFile abstract RegularFileProperty getLibrariesOutput() + + DownloadLibraries() { + output.convention(project.layout.buildDirectory.dir(name)) + librariesOutput.convention(project.layout.buildDirectory.dir(name).map(d -> d.file('libraries.txt'))) + } + + @TaskAction + def run() { + Util.init() + File outputDir = output.get().asFile + var libraries = new ArrayList() + + def json = input.get().asFile.json().libraries.each { lib -> + //TODO: Thread? + def artifacts = [lib.downloads.artifact] + lib.downloads.get('classifiers', [:]).values() + artifacts.each{ art -> + def target = new File(outputDir, art.path) + libraries.add(target.absolutePath) + if (!target.exists() || art.sha1 != target.sha1()) { + project.logger.lifecycle("Downloading ${art.url}") + if (!target.parentFile.exists()) { + target.parentFile.mkdirs() + } + new URL(art.url).withInputStream { i -> + target.withOutputStream { it << i } + } + if (art.sha1 != target.sha1()) { + throw new IllegalStateException("Failed to download ${art.url} to ${target.canonicalPath} SHA Mismatch") + } + } + } + } + Files.write(librariesOutput.get().asFile.toPath(), libraries) + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy new file mode 100644 index 0000000000..727c3258e0 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy @@ -0,0 +1,28 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.CompileStatic +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.* + +import java.util.zip.ZipFile + +@CompileStatic +abstract class ExtractFile extends DefaultTask { + @InputFile abstract RegularFileProperty getInput() + @Input abstract Property getTarget() + @OutputFile abstract RegularFileProperty getOutput() + + @TaskAction + protected void exec() { + var zip = new ZipFile(input.get().asFile); + var entry = zip.getEntry(target.get()) + if (entry == null) + throw new IllegalStateException(input.get().asFile.absolutePath + " does not contain " + target.get()) + var stream = zip.getInputStream(entry) + output.get().asFile.withOutputStream { out -> + stream.transferTo(out) + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/FieldCompareFinder.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/FieldCompareFinder.groovy new file mode 100644 index 0000000000..ec0deac865 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/FieldCompareFinder.groovy @@ -0,0 +1,101 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.CompileStatic +import groovy.transform.EqualsAndHashCode + +import org.gradle.api.tasks.* +import org.objectweb.asm.tree.AbstractInsnNode +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.MethodNode + +import static org.objectweb.asm.Opcodes.* + +abstract class FieldCompareFinder extends BytecodeFinder { + @Nested + Map fields = [:] as HashMap + @Internal + Map fieldsReverse = [:] as HashMap + @Internal + Map> targets = [:] as TreeMap + + @Override + protected pre() { + //fields.each{ k,v -> logger.lifecycle("Fields: " + k + ' ' + v) } + } + + @Override + protected process(ClassNode parent, MethodNode node) { + AbstractInsnNode last = null + def parentInstance = new ObjectTarget(owner: parent.name, name: '', desc: '') + for (int x = 0; x < node.instructions.size(); x++) { + def current = node.instructions.get(x) + if (current.opcode === IF_ACMPEQ || current.opcode === IF_ACMPNE) { + if (last !== null && (last.opcode === GETSTATIC || last.opcode === GETFIELD)) { + def target = new Search(cls: last.owner, name: last.name) + def wanted = fieldsReverse.get(target) + def original = fields.get(wanted) + def instance = new ObjectTarget(owner: parent.name, name: node.name, desc: node.desc) + if (wanted !== null && (original.blacklist === null || (!original.blacklist.contains(instance) && !original.blacklist.contains(parentInstance)))) { + targets.computeIfAbsent(wanted, { k -> new TreeSet() }).add(instance) + } + } + } + last = current + } + } + + @Internal + @Override + protected Object getData() { + def ret = [:] as HashMap + targets.forEach{ k, v -> + def e = fields.get(k) + ret[k] = [ + cls: e.cls, + name: e.name, + replacement: e.replacement, + targets: v + ] + } + return ret + } + + @CompileStatic + @EqualsAndHashCode(excludes = ['replacement', 'blacklist']) + static class Search { + @Input + String cls + + @Input + String name + + @Input + String replacement + + @Nested + @Optional + Set blacklist + + @Override + String toString() { + return cls + '.' + name + } + + def blacklist(String owner, String name, String desc) { + if (blacklist === null) + blacklist = new HashSet<>() + blacklist.add(new ObjectTarget(owner: owner, name: name, desc: desc)) + } + def blacklist(String owner) { + blacklist(owner, '', '') + } + } + + void fields(Closure cl) { + new ClosureHelper(cl, {name, ccl -> + def search = ClosureHelper.apply(new Search(), ccl) + this.fields.put(name, search) + this.fieldsReverse.put(search, name) + }) + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InheritanceData.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InheritanceData.groovy new file mode 100644 index 0000000000..546aec2018 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InheritanceData.groovy @@ -0,0 +1,49 @@ +package net.minecraftforge.forge.tasks + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import groovy.transform.CompileStatic +import groovy.transform.TupleConstructor + +@CompileStatic +@TupleConstructor +final class InheritanceData implements Annotatable { + String name + int access + String superName + List interfaces = [] + Map methods = [:] + Map fields = [:] + List annotations = [] + + @TupleConstructor + static final class Method implements Annotatable { + int access + String override + List annotations = [] + } + + @TupleConstructor + static final class Field implements Annotatable { + int access + String desc + List annotations = [] + } + + @TupleConstructor + static final class Annotation { + String desc + } + + private static final Gson GSON = new Gson() + static Map parse(File file) { + try (final reader = file.newReader()) { + return GSON.fromJson(reader, new TypeToken>() {}) + } + } +} + +@CompileStatic +interface Annotatable { + List getAnnotations() +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy new file mode 100644 index 0000000000..f0918baace --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy @@ -0,0 +1,158 @@ +package net.minecraftforge.forge.tasks + +import org.gradle.api.file.DuplicatesStrategy +import org.gradle.api.tasks.bundling.AbstractArchiveTask +import org.gradle.api.tasks.bundling.Zip +import org.gradle.api.tasks.* +import org.gradle.api.DefaultTask +import org.gradle.api.provider.Property +import groovy.json.JsonSlurper + +abstract class InstallerJar extends Zip { + @Input @Optional abstract Property getFat() + @Input @Optional abstract Property getOffline() + + InstallerJar() { + archiveClassifier.set('installer') + archiveExtension.set('jar') // Needs to be Zip task to not override Manifest, so set extension + destinationDirectory.set(project.layout.buildDirectory.dir('libs')) + fat.convention(false) + offline.convention(false) + + def installerJson = project.tasks.installerJson + def launcherJson = project.tasks.launcherJson + def downloadInstaller = project.tasks.downloadInstaller + + dependsOn(installerJson, launcherJson, downloadInstaller, project.configurations.installer) + from(installerJson, launcherJson) + + from(project.rootProject.file('/src/main/resources/url.png')) + project.afterEvaluate { + from(project.zipTree(downloadInstaller.output)) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } + + if (fat.get() || offline.get()) { + def cfg = project.tasks.register(name + "Config", Configure) + cfg.get().configure { + parent = this + dependsOn(project.tasks.installerJson, project.tasks.launcherJson) + } + dependsOn(cfg) + } else { + // Things we ALWAYS bundle, this just the server shim jar, because the installer spec only says to extract the file. + // I should make it allow downloads but thats a spec break, and this is just a ~14KB jar + [ + project.tasks.serverShimJar // Server bootstrap executable jar + ].forEach { AbstractArchiveTask packed -> + def path = Util.getMavenInfoFromTask(packed).path + from(packed) { + rename { "maven/$path" } + } + } + } + } + } + + static abstract class Configure extends DefaultTask { + public Zip parent + private int count = 0; + + @TaskAction + protected void exec() { + def deps = [:] as java.util.TreeMap + + // Gather all things that need downloading + [ + project.tasks.installerJson, + project.tasks.launcherJson + ].each { task -> + def json = task.output.get().asFile.json + json.libraries.each { lib -> + if (lib.downloads?.artifact?.url !== null && !lib.downloads.artifact.url.isEmpty()) + deps.put(lib.name, lib.downloads.artifact) + } + } + + // First find things we build in this project. + [ + project.tasks.universalJar, // Forge runtime code + project.tasks.serverShimJar // Shim jar for dedicated server + ].forEach { AbstractArchiveTask packed -> + def name = Util.getMavenInfoFromTask(packed).name + def info = deps.remove(name) + if (info !== null) { + println("Adding: $packed.path $name") + parent.from(packed) { + rename { "maven/$info.path" } + } + } + } + + // Find any artifacts from the 'installer' config + // This config specifies the runtime files we intend for the interaller to have. + // And are typically what we would be developing and testing alongside Forge. + // So we may have local modified versions + def cfg = project.configurations.installer + while (cfg != null) { + //println('') + def resolved = cfg.resolvedConfiguration.resolvedArtifacts + int found = 0 + for (def dep : resolved) { + def name = Util.getMavenInfoFromDep(dep).name + def info = deps.remove(name) + if (info == null) { + //println("Skipping: $name") + continue + } + //println("-$name") + found++ + addFile(dep.file, info) + } + + if (deps.isEmpty()) { + cfg = null + continue + } + + // Prevent infinite loops if something fucky happens + if (found == 0) + throw new IllegalStateException("Failed to find any installer dependencies") + + def seen = [] as Set + cfg = project.configurations.detachedConfiguration() + cfg.transitive = false + for (def key : deps.keySet()) { + def (group, artifact, other) = key.split(':', 3) + // Only resolve unique group:artifact so we don't get version overrides + if (seen.add(group + ':' + artifact)) { + //println("+$key") + cfg.dependencies.add(project.dependencies.create(key)) + } + } + } + } + + void addFile(file, info) { + boolean pack = parent.offline.get() || info.url.isEmpty() + + // If it's a offline jar just always pack + if (!pack) { + try { + var remote = new URL("${info.url}.sha1").getText('UTF-8') + pack = info.sha1 != remote + } catch (FileNotFoundException e) { + pack = !info.url.startsWith('https://libraries.minecraft.net/') + // Oh noes its not there! + } + } + + if (pack) { + println("Adding: $file.absolutePath") + parent.from(file) { + rename { "maven/$info.path" } + } + } + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy new file mode 100644 index 0000000000..1076b7552b --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy @@ -0,0 +1,73 @@ +package net.minecraftforge.forge.tasks + +import groovy.json.JsonBuilder +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.provider.SetProperty +import org.gradle.api.tasks.* +import org.gradle.api.tasks.bundling.AbstractArchiveTask + +import java.nio.file.Files + +abstract class InstallerJson extends DefaultTask { + @OutputFile abstract RegularFileProperty getOutput() + @InputFiles abstract ConfigurableFileCollection getInput() + @Input @Optional final Map libraries = new LinkedHashMap<>() + @Input Map json = new LinkedHashMap<>() + @InputFile abstract RegularFileProperty getIcon() + @Input abstract Property getLauncherJsonName() + @Input abstract Property getLogo() + @Input abstract Property getMirrors() + @Input abstract Property getWelcome() + + InstallerJson() { + launcherJsonName.convention('/version.json') + logo.convention('/big_logo.png') + mirrors.convention('https://files.minecraftforge.net/mirrors-2.0.json') + welcome.convention("Welcome to the ${project.name.capitalize()} installer.") + output.convention(project.layout.buildDirectory.file('libs/install_profile.json')) + + project.afterEvaluate { + [ + project.tasks.universalJar, + project.tasks.serverShimJar + ].forEach { packed -> + dependsOn(packed) + input.from packed.archiveFile + } + } + } + + @TaskAction + protected void exec() { + def libs = libraries + [ + project.tasks.universalJar, + project.tasks.serverShimJar + ].forEach { AbstractArchiveTask packed -> + def info = Util.getMavenInfoFromTask(packed) + libs.put(info.name, [ + name: info.name, + downloads: [ + artifact: [ + path: info.path, + url: "https://maven.minecraftforge.net/$info.path", + sha1: packed.archiveFile.get().asFile.sha1(), + size: packed.archiveFile.get().asFile.length() + ] + ] + ]) + } + json.libraries = libs.values().sort{a,b -> a.name.compareTo(b.name)} + json.icon = "data:image/png;base64," + new String(Base64.getEncoder().encode(Files.readAllBytes(icon.get().asFile.toPath()))) + json.json = launcherJsonName.get() + json.logo = logo.get() + if (!mirrors.get().isEmpty()) + json.mirrorList = mirrors.get() + json.welcome = welcome.get() + + Files.writeString(output.get().getAsFile().toPath(), new JsonBuilder(json).toPrettyString()) + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/JarJarMetadataOptions.java b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/JarJarMetadataOptions.java new file mode 100644 index 0000000000..8837a29032 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/JarJarMetadataOptions.java @@ -0,0 +1,415 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.forge.tasks; + +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier; +import net.minecraftforge.jarjar.metadata.ContainedJarMetadata; +import net.minecraftforge.jarjar.metadata.ContainedVersion; +import net.minecraftforge.jarjar.metadata.Metadata; +import net.minecraftforge.jarjar.metadata.MetadataIOHandler; +import net.minecraftforge.jarjar.metadata.json.ArtifactVersionSerializer; +import net.minecraftforge.jarjar.metadata.json.ContainedJarIdentifierSerializer; +import net.minecraftforge.jarjar.metadata.json.ContainedJarMetadataSerializer; +import net.minecraftforge.jarjar.metadata.json.ContainedVersionSerializer; +import net.minecraftforge.jarjar.metadata.json.MetadataSerializer; +import net.minecraftforge.jarjar.metadata.json.VersionRangeSerializer; +import org.apache.maven.artifact.versioning.ArtifactVersion; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.VersionRange; +import org.codehaus.groovy.runtime.InvokerHelper; +import org.gradle.api.Action; +import org.gradle.api.DefaultTask; +import org.gradle.api.artifacts.ConfigurationContainer; +import org.gradle.api.artifacts.Dependency; +import org.gradle.api.artifacts.ExternalModuleDependency; +import org.gradle.api.artifacts.FileCollectionDependency; +import org.gradle.api.artifacts.MinimalExternalModuleDependency; +import org.gradle.api.artifacts.ModuleDependency; +import org.gradle.api.artifacts.ModuleIdentifier; +import org.gradle.api.artifacts.ModuleVersionIdentifier; +import org.gradle.api.artifacts.ResolvedArtifact; +import org.gradle.api.file.ProjectLayout; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.Provider; +import org.gradle.api.provider.SetProperty; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.TaskAction; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.io.Serial; +import java.io.Serializable; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.zip.ZipFile; + +// TODO SUPER SUPER SUPER UGLY, CLEAN UP IN FORGEDEV 7 +@Deprecated(forRemoval = true) // Will be moved to JarJar plugin in ForgeDev 7 +public abstract class JarJarMetadataOptions extends DefaultTask { + private static final Gson GSON = new GsonBuilder() + .registerTypeAdapter(VersionRange.class, new VersionRangeSerializer()) + .registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionSerializer()) + .registerTypeAdapter(DefaultArtifactVersion.class, new ArtifactVersionSerializer()) + .registerTypeAdapter(ContainedJarIdentifier.class, new ContainedJarIdentifierSerializer()) + .registerTypeAdapter(ContainedJarMetadata.class, new ContainedJarMetadataSerializer()) + .registerTypeAdapter(ContainedVersion.class, new ContainedVersionSerializer()) + .registerTypeAdapter(Metadata.class, new MetadataSerializer()) + .setPrettyPrinting() + .create(); + + protected abstract @Input SetProperty getResolvedDependencies(); + + protected abstract @OutputFile RegularFileProperty getMetadataFile(); + + protected abstract @Inject ProjectLayout getLayout(); + + // NOTE: I'm not adding a non-provider version. please just use the version catalog entries for now. + public void add(Provider dependency, Action action) { + this.getResolvedDependencies().add(dependency.map(d -> { + var ret = ResolvedDependencyInfoImpl.from(this.getProject().getConfigurations(), d); + action.execute(ret); + return ret; + })); + } + + @Inject + public JarJarMetadataOptions() { + this.getMetadataFile().convention(this.getLayout().getBuildDirectory().file(this.getName() + "/options.json")); + } + + @TaskAction + protected void exec() { + record ForgeLocaterOptions(String resource, String layer, String id, List deps, ContainedJarMetadata meta, boolean nested) { } + + var resolved = this.getResolvedDependencies().get(); + var jars = new ArrayList(resolved.size()); + for (var dependency : resolved) { + var deps = new ArrayList(); + try (var zip = new ZipFile(dependency.artifact)) { + var entry = zip.getEntry("META-INF/jarjar/metadata.json"); + if (entry != null) { + try (var stream = zip.getInputStream(entry)) { + var meta = MetadataIOHandler.fromStream(stream).orElse(null); + if (meta == null) + throw new IllegalStateException("Corrupt metadata.json in " + dependency.artifact.getAbsolutePath()); + for (var dep : meta.jars()) + deps.add(new ContainedJarMetadata(dep.identifier(), dep.version(), "", dep.isObfuscated())); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + jars.add(new ForgeLocaterOptions( + dependency.resource, + dependency.layer, + dependency.identifier, + deps, + new ContainedJarMetadata( + new ContainedJarIdentifier(validateGroup(dependency), dependency.module.getName()), + new ContainedVersion(null, parseVersion(dependency)), + Objects.requireNonNull(dependency.path, "Dependency path is unspecified: " + dependency.asString), + false + ), + dependency.nested + )); + } + + try { + record Meta(List options){} + + Files.writeString( + this.getMetadataFile().getAsFile().get().toPath(), + GSON.toJson(new Meta(jars), Meta.class) + ); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private String validateGroup(ResolvedDependencyInfoImpl dependency) { + try { + return Objects.requireNonNull(dependency.module.getGroup()); + } catch (NullPointerException e) { + throw new IllegalArgumentException("Module dependency has no group: " + dependency.asString, e); + } + } + + private ArtifactVersion parseVersion(ResolvedDependencyInfoImpl resolved) { + try { + return VersionRange.createFromVersionSpec(Objects.requireNonNull(resolved.version)).getRecommendedVersion(); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException("Version is invalid for: " + resolved.asString, e); + } catch (NullPointerException e) { + throw new IllegalArgumentException("Version is unspecified for: " + resolved.asString, e); + } + } + + private VersionRange parseVersionRange(ResolvedDependencyInfoImpl dependency) { + if (dependency.hasManuallySpecifiedRange) { + try { + return VersionRange.createFromVersionSpec(dependency.versionRange); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException("Version is invalid for: " + dependency.asString, e); + } + } else { + try { + return VersionRange.createFromVersionSpec("[%s,)".formatted(Objects.requireNonNull(dependency.versionRange))); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException("Version range is invalid for: " + dependency.asString, e); + } catch (NullPointerException e) { + throw new IllegalArgumentException("Version is unspecified for: " + dependency.asString, e); + } + } + } + + public interface ResolvedDependencyInfo { + void containedJarMetadata(Action action); + + void setResource(String resource); + + void setLayer(String layer); + + void setId(String identifier); + + void setNested(boolean nested); + + interface ContainedJarMetadataInfo { + void setGroup(String group); + + void setName(String name); + + void setPath(String version); + } + } + + static final class ResolvedDependencyInfoImpl implements ResolvedDependencyInfo, ResolvedDependencyInfo.ContainedJarMetadataInfo, Serializable { + private static final @Serial long serialVersionUID = -7577318115877822993L; + + final MinimalModuleVersionIdentifier module; + final String version; + String versionRange; + boolean hasManuallySpecifiedRange; + boolean nested; + final File artifact; + String path; + String resource; + String layer; + String identifier; + final String asString; + + public ResolvedDependencyInfoImpl(MinimalModuleVersionIdentifier module, String version, File artifact, String asString) { + this.module = module; + this.version = version; + this.artifact = artifact; + this.asString = asString; + } + + @Override + public void containedJarMetadata(Action action) { + action.execute(this); + } + + @Override + public void setGroup(String group) { + this.module.group = group; + } + + @Override + public void setName(String name) { + this.module.name = name; + } + + @Override + public void setPath(String path) { + this.path = path; + } + + @Override + public void setResource(String resource) { + this.resource = resource; + } + + @Override + public void setLayer(String layer) { + this.layer = layer; + } + + @Override + public void setId(String identifier) { + this.identifier = identifier; + } + + @Override + public void setNested(boolean nested) { + this.nested = nested; + } + + static Set getFiles(Set resolvedDependencies) { + var ret = new HashSet(resolvedDependencies.size()); + for (var dependency : resolvedDependencies) { + ret.add(dependency.artifact); + } + return ret; + } + + static ResolvedDependencyInfoImpl from(ConfigurationContainer configurations, Dependency dependency) { + var group = dependency.getGroup(); + var name = dependency.getName(); + var version = dependency.getVersion(); + + if (dependency instanceof FileCollectionDependency filesDependency) { + File artifact; + try { + artifact = filesDependency.getFiles().getSingleFile(); + } catch (IllegalStateException e) { + // TODO fileCollectionDependencyIsNotSingleFile + throw e; + } + + return new ResolvedDependencyInfoImpl( + new MinimalModuleVersionIdentifier(group, name, version), + version, + artifact, + filesDependency.toString() + ); + } else if (dependency instanceof ModuleDependency moduleDependency) { + moduleDependency = moduleDependency.copy(); + if (moduleDependency instanceof ExternalModuleDependency externalModuleDependency) { + externalModuleDependency.version(v -> v.strictly(version.toString())); + } + + var detachedConfiguration = configurations.detachedConfiguration(moduleDependency); + detachedConfiguration.setTransitive(false); + + ResolvedDependencyInfoImpl ret = null; + for (var artifact : detachedConfiguration.getResolvedConfiguration().getFirstLevelModuleDependencies().iterator().next().getModuleArtifacts()) { + var fileName = getFileName(artifact); + if (!fileName.endsWith(".jar")) + continue; + + if (ret != null) + throw new IllegalArgumentException("Module dependency has too many Jar artifacts: " + moduleDependency); + + ret = new ResolvedDependencyInfoImpl( + new MinimalModuleVersionIdentifier(group, name, artifact.getModuleVersion().getId().getVersion()), + version, + artifact.getFile(), + moduleDependency.toString() + ); + } + if (ret == null) + throw new IllegalArgumentException("Module dependency has no Jar artifacts: " + moduleDependency); + + return ret; + } else { + throw new IllegalArgumentException("Unsupported dependency type: " + dependency.getClass().getName() + " -- " + dependency); + } + } + + private static String getFileName(ResolvedArtifact artifact) { + try { + return InvokerHelper.getProperty(artifact.getId(), "fileName").toString(); + } catch (Throwable e) { + // NOTE: Why not just use this to begin with? + // ComponentArtifactIdentifier can have a getFileName() method, which doesn't necessarily resolve the file itself. + // This allows us to get the name of the file to be used without asking Gradle to download the file. + // So, if a file is not a JAR file, we can check the name without actually downloading it. + return artifact.getFile().getName(); + } + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (ResolvedDependencyInfoImpl) obj; + return Objects.equals(this.module, that.module) && + Objects.equals(this.version, that.version) && + Objects.equals(this.versionRange, that.versionRange) && + Objects.equals(this.artifact, that.artifact); + } + + @Override + public int hashCode() { + return Objects.hash(module, version, versionRange, artifact); + } + + @Override + public String toString() { + return "ResolvedDependencyInfo[" + + "module=" + module + ", " + + "fixedVersion=" + version + ", " + + "versionRange=" + versionRange + ", " + + "artifact=" + artifact + ']'; + } + + static final class MinimalModuleVersionIdentifier implements ModuleIdentifier, ModuleVersionIdentifier { + private static final @Serial long serialVersionUID = -955346236759069739L; + + private String group; + private String name; + private final String version; + + @Inject + public MinimalModuleVersionIdentifier(String group, String name, String version) { + this.group = group; + this.name = name; + this.version = version; + } + + @Override + public ModuleIdentifier getModule() { + return this; + } + + @Override + public String getGroup() { + return this.group; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String getVersion() { + return this.version; + } + + @Override + public boolean equals(Object obj) { + return this == obj || obj instanceof MinimalModuleVersionIdentifier o + && Objects.equals(this.group, o.group) + && Objects.equals(this.name, o.name) + && Objects.equals(this.version, o.version); + } + + @Override + public int hashCode() { + return Objects.hash(group, name, version); + } + + @Override + public String toString() { + return "MinimalModuleVersionIdentifier[" + + "group=" + group + ", " + + "name=" + name + ", " + + "version=" + version + ']'; + } + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy new file mode 100644 index 0000000000..e9cf3a18d2 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy @@ -0,0 +1,94 @@ +package net.minecraftforge.forge.tasks + +import groovy.json.JsonBuilder +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.SetProperty +import org.gradle.api.tasks.* +import org.gradle.api.tasks.bundling.AbstractArchiveTask + +import java.nio.file.Files + +import static net.minecraftforge.forge.tasks.Util.getArtifacts +import static net.minecraftforge.forge.tasks.Util.iso8601Now + +abstract class LauncherJson extends DefaultTask { + @OutputFile abstract RegularFileProperty getOutput() + @InputFiles abstract ConfigurableFileCollection getInput() + @Input Map json = new LinkedHashMap<>() + + LauncherJson() { + output.convention(project.layout.buildDirectory.file('libs/version.json')) + + dependsOn(project.tasks.universalJar) + input.from(project.tasks.universalJar.archiveFile) + input.from(project.configurations.installer) + configure { + def mc = project.rootProject.ext.MC_VERSION + def forge = project.rootProject.ext.FORGE_VERSION + def timestamp = iso8601Now() + json.putAll([ + _comment: [ + "Please do not automate the download and installation of Forge.", + "Our efforts are supported by ads from the download page.", + "If you MUST automate this, please consider supporting the project through https://www.patreon.com/LexManos/" + ], + id: "$mc-$project.name-$forge", + time: timestamp, + releaseTime: timestamp, + inheritsFrom: mc, + type: 'release', + logging: [:], + mainClass: '', + libraries: [] + ] as LinkedHashMap) + + [ + project.tasks.universalJar + ].forEach { packed -> + dependsOn(packed) + input.from packed.archiveFile + } + + def patched = project.tasks.applyClientBinPatches + dependsOn(patched) + input.from patched.output + } + } + + @TaskAction + protected void exec() { + var packed = (AbstractArchiveTask) project.tasks.universalJar + def info = Util.getMavenInfoFromTask(packed) + json.libraries.add([ + name: info.name, + downloads: [ + artifact: [ + path: info.path, + url: "https://maven.minecraftforge.net/$info.path", + sha1: packed.archiveFile.get().asFile.sha1(), + size: packed.archiveFile.get().asFile.length() + ] + ] + ]) + + var classifier = 'client' + var genned = project.tasks.applyClientBinPatches + info = Util.getMavenInfoFromTask(genned, classifier) + json.libraries.add([ + name: info.name, + downloads: [ + artifact: [ + path: info.path, + url: "", + sha1: genned.output.get().asFile.sha1(), + size: genned.output.get().asFile.length() + ] + ] + ]) + + json.libraries.addAll(getArtifacts(project.configurations.installer).values()) + Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString()) + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/MergeJars.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/MergeJars.groovy new file mode 100644 index 0000000000..0f95d42f36 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/MergeJars.groovy @@ -0,0 +1,46 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.CompileStatic +import org.apache.commons.io.IOUtils +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction + +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + +@CompileStatic +abstract class MergeJars extends DefaultTask { + MergeJars() { + output.convention(project.layout.buildDirectory.dir(name).map { it.file('output.jar') }) + } + + @TaskAction + void run() { + def jars = inputJars.files + + try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(output.get().asFile))) { + for (def jar : jars) { + try (ZipInputStream zin = new ZipInputStream(new FileInputStream(jar))) { + ZipEntry entry + while ((entry = zin.getNextEntry()) !== null) { + ZipEntry _new = new ZipEntry(entry.getName()) + _new.setTime(0) //SHOULD be the same time as the main entry, but NOOOO _new.setTime(entry.getTime()) throws DateTimeException, so you get 0, screw you! + zout.putNextEntry(_new) + IOUtils.copy(zin, zout) + } + } + } + } + } + + @InputFiles + abstract ConfigurableFileCollection getInputJars() + + @OutputFile + abstract RegularFileProperty getOutput() +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ObjectTarget.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ObjectTarget.groovy new file mode 100644 index 0000000000..00f64e18fa --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ObjectTarget.groovy @@ -0,0 +1,32 @@ +package net.minecraftforge.forge.tasks + +import groovy.transform.EqualsAndHashCode + +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Nested +import org.gradle.api.tasks.Optional + +@EqualsAndHashCode +public class ObjectTarget implements Comparable { + @Input + String owner + + @Input + String name + + @Input + @Optional + String desc + + @Override + String toString() { + if (desc == null) + return owner + '.' + name + return owner + '.' + name + desc + } + + @Override + int compareTo(ObjectTarget o) { + return toString() <=> o.toString() + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy new file mode 100644 index 0000000000..a583d6b5e6 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy @@ -0,0 +1,47 @@ +package net.minecraftforge.forge.tasks + +import org.gradle.api.DefaultTask +import org.gradle.api.artifacts.Dependency +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Optional +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction + +import java.nio.file.Files +import java.nio.file.StandardCopyOption + +abstract class SetupCheckJarCompatibility extends DefaultTask { + SetupCheckJarCompatibility() { + group = 'jar compatibility' + onlyIf { + inputVersion.getOrNull() !== null + } + outputs.upToDateWhen { false } // Never up to date, because this setup task should always run + + baseBinPatchesOutput.convention(project.layout.buildDirectory.dir(name).map { it.file('joined.lzma') }) + } + + @TaskAction + void run() { + def inputVersion = inputVersion.get() + + def baseForgeUserdev = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-userdev.jar") }.get().asFile + project.rootProject.extensions.download.run { + src "https://maven.minecraftforge.net/net/minecraftforge/forge/${inputVersion}/forge-${inputVersion}-userdev.jar" + dest baseForgeUserdev + } + + def joinedLzma = project.zipTree(baseForgeUserdev).matching { it.include('joined.lzma') }.singleFile + + Files.copy(joinedLzma.toPath(), baseBinPatchesOutput.get().asFile.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + + @Input + @Optional + abstract Property getInputVersion() + + @OutputFile + abstract RegularFileProperty getBaseBinPatchesOutput() +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/TeamcityRequests.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/TeamcityRequests.groovy new file mode 100644 index 0000000000..bccebbaffa --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/TeamcityRequests.groovy @@ -0,0 +1,74 @@ +package net.minecraftforge.forge.tasks + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import groovy.transform.CompileStatic +import org.eclipse.jgit.api.Git + +import javax.annotation.Nullable +import java.util.stream.Collectors + +@CompileStatic +class TeamcityRequests { + public static final Gson GSON = new Gson() + + @Nullable + static T jsonRequest(TypeToken clazz, String url) throws Exception { + final HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection() + conn.setRequestProperty('Accept', 'application/json') + conn.setReadTimeout(5 * 1000) + conn.setConnectTimeout(5 * 1000) + conn.connect() + + if (conn.responseCode !== 200) { + return null + } + + try (final InputStream is = conn.getInputStream()) { + GSON.fromJson(new InputStreamReader(is), clazz.getType()) + } + } + + @Nullable + static Map buildsByCommit() throws IOException { + final Map builds = [:] + jsonRequest(new TypeToken() {}, 'https://teamcity.minecraftforge.net/guestAuth/app/rest/builds?fields=build:(revisions,number)&locator=buildType:(id:MinecraftForge_MinecraftForge_MinecraftForge_MinecraftForge__Build),defaultFilter:false,count:300,status:SUCCESS') + ?.build?.forEach { + it.revisions.revision.each { rev -> builds[rev.version] = it } + } + return builds + } + + @Nullable + static String attemptFindBase(File gitPath) { + try (final git = Git.open(gitPath)) { + final Map buildByCommit = buildsByCommit() + for (final commit in git.log().setMaxCount(100).call()) { + // Find the first commit which was built on CI + final build = buildByCommit[commit.id.name] + if (build) { + return build.number + } + } + } catch (Exception ignored) {} + return null + } + + static final class Builds { + public List build + } + + static final class Build { + public String number + public Revisions revisions + } + + static final class Revisions { + public int count + public List revision + } + + static final class Revision { + public String version + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy new file mode 100644 index 0000000000..c15e595952 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy @@ -0,0 +1,230 @@ +package net.minecraftforge.forge.tasks + +import groovy.json.JsonBuilder +import groovy.json.JsonSlurper +import groovy.transform.CompileStatic +import groovy.transform.stc.ClosureParams +import groovy.transform.stc.SimpleType +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.ResolvedArtifact +import org.gradle.api.tasks.bundling.AbstractArchiveTask +import org.objectweb.asm.ClassReader +import org.objectweb.asm.Opcodes +import org.objectweb.asm.tree.ClassNode + +import java.net.http.HttpClient +import java.net.http.HttpRequest +import java.net.http.HttpResponse +import java.security.MessageDigest +import java.text.SimpleDateFormat +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Semaphore +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream + +final class Util { + public static final int ASM_LEVEL = Opcodes.ASM9 + private static final HttpClient HTTP = HttpClient.newBuilder().build() + + static void init() { + File.metaClass.sha1 = { -> + MessageDigest md = MessageDigest.getInstance('SHA-1') + delegate.eachByte(4096) { byte[] bytes, int size -> + md.update(bytes, 0, size) + } + return md.digest().collect(this.&toHex).join('') + } + File.metaClass.getSha1 = { !delegate.exists() ? null : delegate.sha1() } + File.metaClass.sha256 = { -> + MessageDigest md = MessageDigest.getInstance('SHA-256') + delegate.eachByte(4096) { byte[] bytes, int size -> + md.update(bytes, 0, size) + } + return md.digest().collect(this.&toHex).join('') + } + File.metaClass.getSha256 = { !delegate.exists() ? null : delegate.sha256() } + + File.metaClass.json = { -> new JsonSlurper().parseText(delegate.text) } + File.metaClass.getJson = { return delegate.exists() ? new JsonSlurper().parse(delegate) : [:] } + File.metaClass.setJson = { json -> delegate.text = new JsonBuilder(json).toPrettyString() } + + Date.metaClass.iso8601 = { -> + var format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") + var result = format.format(delegate) + return result[0..21] + ':' + result[22..-1] + } + + String.metaClass.rsplit = { String del, int limit = -1 -> + var lst = new ArrayList() + int x = 0 + int idx + String tmp = delegate + while ((idx = tmp.lastIndexOf(del)) != -1 && (limit === -1 || x++ < limit)) { + lst.add(0, tmp.substring(idx + del.length(), tmp.length())) + tmp = tmp.substring(0, idx) + } + lst.add(0, tmp) + return lst + } + } + + static String[] getClasspath(Project project, Map libs, String artifact) { + def ret = [] + artifactTree(project, artifact).each { key, lib -> + libs[lib.name] = lib + if (lib.name != artifact) + ret.add(lib.name) + } + return ret + } + + @CompileStatic + static Map getArtifacts(Configuration config) { + var ret = [:] + var semaphore = new Semaphore(1, true) + config.resolvedConfiguration.resolvedArtifacts.parallelStream().forEachOrdered(dep -> { + var info = getMavenInfoFromDep(dep) + var domain = 'libraries.minecraft.net' + var url = "https://$domain/$info.path" + if (!checkExists(url)) + url.values[0] = 'maven.minecraftforge.net' + + var sha1 = sha1(dep.file) + + semaphore.acquire() + ret[info.key] = [ + name: info.name, + downloads: [ + artifact: [ + path: info.path, + url: url.toString(), + sha1: sha1, + size: dep.file.length() + ] + ] + ] + semaphore.release() + }) + return ret + } + + @CompileStatic + static Map getMavenInfoFromDep(ResolvedArtifact dep) { + return getMavenInfoFromMap([ + group: dep.moduleVersion.id.group, + name: dep.moduleVersion.id.name, + version: dep.moduleVersion.id.version, + classifier: dep.classifier, + extension: dep.extension + ]) + } + + @CompileStatic + static Map getMavenInfoFromTask(AbstractArchiveTask task) { + return getMavenInfoFromMap([ + group: task.project.group.toString(), + name: task.project.name, + version: task.project.version.toString(), + classifier: task.archiveClassifier.get(), + extension: task.archiveExtension.get() + ]) + } + + @CompileStatic + static Map getMavenInfoFromTask(Task task, String classifier) { + return getMavenInfoFromMap([ + group: task.project.group.toString(), + name: task.project.name, + version: task.project.version.toString(), + classifier: classifier, + extension: 'jar' + ]) + } + + @CompileStatic + private static Map getMavenInfoFromMap(Map art) { + var key = "$art.group:$art.name" + var name = "$art.group:$art.name:$art.version" + var path = "${art.group.replace('.', '/')}/$art.name/$art.version/$art.name-$art.version" + if (art.classifier !== null) { + name += ":$art.classifier" + path += "-$art.classifier" + } + if ('jar' != art.extension) { + name += "@$art.extension" + path += ".$art.extension" + } else { + path += ".jar" + } + return [ + key: key.toString(), + name: name.toString(), + path: path.toString(), + art: art + ] + } + + static String iso8601Now() { new Date().iso8601() } + + @CompileStatic + static String sha1(File file) { + MessageDigest md = MessageDigest.getInstance('SHA-1') + file.eachByte(4096) { byte[] bytes, int size -> + md.update(bytes, 0, size) + } + return md.digest().collect(this.&toHex).join('') + } + + @CompileStatic + private static String toHex(byte bite) { + return String.format('%02x', bite) + } + + private static Map artifactTree(Project project, String artifact, boolean transitive = true) { + if (!project.ext.has('tree_resolver')) + project.ext.tree_resolver = 1 + def cfg = project.configurations.create('tree_resolver_' + project.ext.tree_resolver++) + cfg.transitive = transitive + def dep = project.dependencies.create(artifact) + cfg.dependencies.add(dep) + def files = cfg.resolve() + return getArtifacts(cfg) + } + + @CompileStatic + static boolean checkExists(String url) { + try { + return HTTP.send(HttpRequest.newBuilder(new URI(url)) + .method('HEAD', HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding() + ).statusCode() === 200 + } catch (Exception e) { + if (e.toString().contains('unable to find valid certification path to requested target')) + throw new RuntimeException("Failed to connect to $url: Missing certificate root authority, try updating Java") + throw e + } + } + + static String getLatestForgeVersion(String mcVersion) { + final json = new JsonSlurper().parseText(new URL('https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json').getText('UTF-8')) + final ver = json.promos["$mcVersion-latest"] + ver === null ? null : (mcVersion + '-' + ver) + } + + @CompileStatic + static void processClassNodes(File file, @ClosureParams(value = SimpleType, options = 'org.objectweb.asm.tree.ClassNode') Closure process) { + file.withInputStream { i -> + new ZipInputStream(i).withCloseable { zin -> + ZipEntry zein + while ((zein = zin.nextEntry) !== null) { + if (zein.name.endsWith('.class')) { + var node = new ClassNode(ASM_LEVEL) + new ClassReader(zin).accept(node, 0) + process(node) + } + } + } + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ValidateDeprecations.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ValidateDeprecations.groovy new file mode 100644 index 0000000000..14018ddd8a --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ValidateDeprecations.groovy @@ -0,0 +1,94 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.forge.tasks + +import groovy.transform.CompileStatic +import net.minecraftforge.srgutils.MinecraftVersion +import org.gradle.api.DefaultTask +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.TaskAction +import org.objectweb.asm.tree.AnnotationNode +import org.objectweb.asm.tree.ClassNode + +abstract class ValidateDeprecations extends DefaultTask { + @InputFile + abstract RegularFileProperty getInput() + + @Input + abstract Property getMcVersion() + + ValidateDeprecations() { + this.onlyIf { !System.env.TEAMCITY_VERSION } + } + + @TaskAction + protected void exec() { + var mcVer = MinecraftVersion.from(mcVersion.get()) + List errors = [] + + Util.processClassNodes(input.get().asFile) { + processNode(mcVer, errors, it) + } + + if (!errors.isEmpty()) { + errors.forEach { + this.logger.error("Deprecated ${it[0]} is marked for removal in ${it[1]} but is not yet removed") + } + throw new IllegalStateException("Found deprecated members marked for removal but not yet removed in ${mcVer}; see log for details") + } + } + + protected processNode(MinecraftVersion mcVer, List errors, ClassNode node) { + node.visibleAnnotations?.each { annotation -> + ValidateDeprecations.processAnnotations(annotation, mcVer, errors) { + "class ${node.name}" + } + } + node.fields?.each { field -> + field.visibleAnnotations?.each { annotation -> + ValidateDeprecations.processAnnotations(annotation, mcVer, errors) { + "field ${node.name}#${field.name}" + } + } + } + node.methods?.each { method -> + method.visibleAnnotations?.each { annotation -> + ValidateDeprecations.processAnnotations(annotation, mcVer, errors) { + "method ${node.name}#${method.name}${method.desc}" + } + } + } + } + + private static void processAnnotations(AnnotationNode annotation, MinecraftVersion mcVer, List errors, Closure context) { + def values = annotation.values + if (values === null) + return + int forRemoval = values.indexOf('forRemoval') + int since = values.indexOf('since') + if (annotation.desc == 'Ljava/lang/Deprecated;' && forRemoval !== -1 && since !== -1 && values.size() >= 4 && values[forRemoval + 1] === true) { + def oldVersion = MinecraftVersion.from(values[since + 1]) + int[] split = ValidateDeprecations.splitDots(oldVersion.toString()) + if (split.length < 2) + return + def removeVersion = MinecraftVersion.from("${split[0]}.${split[1] + 1}") + if (removeVersion <= mcVer) + errors.add([context(), removeVersion]) + } + } + + @CompileStatic + private static int[] splitDots(String version) { + String[] pts = version.split('\\.') + int[] values = new int[pts.length] + for (int x = 0; x < pts.length; x++) + values[x] = Integer.parseInt(pts[x]) + return values + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckATs.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckATs.groovy new file mode 100644 index 0000000000..7e7bf20da2 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckATs.groovy @@ -0,0 +1,282 @@ +package net.minecraftforge.forge.tasks.checks + +import groovy.transform.CompileStatic +import groovy.transform.TupleConstructor +import net.minecraftforge.forge.tasks.InheritanceData +import net.minecraftforge.srgutils.IMappingFile +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFile +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Optional +import org.objectweb.asm.Opcodes + +@CompileStatic +abstract class CheckATs extends CheckTask { + + @InputFile abstract RegularFileProperty getInheritance() + @InputFiles abstract ConfigurableFileCollection getAts() + + @Override + void check(Reporter reporter, boolean fix) { + final inheritance = InheritanceData.parse(this.inheritance.get().asFile) + + ats.each { + final lines = process(it, reporter, inheritance) + if (fix) { + it.text = joinBack(lines, inheritance).join('\n') + } + } + } + + private static TreeMap process(File file, Reporter reporter, Map inheritance) { + final TreeMap lines = ATParser.parse(file.readLines(), reporter) + final Map constructorGroups = [:] + + final itr = lines.entrySet().iterator() + final toRemove = [] + while (itr.hasNext()) { + final next = itr.next() + String key = next.key + final entry = next.value + if (entry === null) continue + + final binaryName = entry.cls.replaceAll('\\.', '/') + + // Process Groups, this will remove any entries outside the group that is covered by the group + if (entry.group) { + final jcls = inheritance[binaryName] + if (jcls === null) { + itr.remove() + reporter.report("Invalid group: $key") + } else if ('*' == entry.desc) { + if (!jcls.fields) { + itr.remove() + reporter.report("Invalid group, class has no fields: $key") + } else { + jcls.fields.each { field, value -> + final fkey = entry.cls + ' ' + field + if (accessLevel(value.access) < accessStr(entry.modifier)) { + if (lines.containsKey(fkey)) { + toRemove.add(fkey) + } else if (!entry.existing.contains(fkey)) { + reporter.report("Missing group entry: $fkey") + } + entry.children.add(fkey) + } else if (lines.containsKey(fkey)) { + toRemove.add(fkey) + reporter.report("Found invalid group entry: $fkey") + } + } + entry.existing.findAll { it !in entry.children }.each { println('Removed: ' + it) } + } + } else if ('*()' == entry.desc) { + if (!jcls.methods) { + itr.remove() + reporter.report("Invalid group, class has no methods: $key") + } else { + jcls.methods.each { mtd, value -> + if (mtd.startsWith('') || mtd.startsWith('lambda$')) return + key = entry.cls + ' ' + mtd.replace(' ', '') + if (accessLevel(value.access) < accessStr(entry.modifier)) { + if (lines.containsKey(key)) { + toRemove.add(key) + } else if (!entry.existing.contains(key)) { + reporter.report("Missing group entry: $key") + } + entry.children.add(key) + } else if (lines.containsKey(key)) { + toRemove.add(key) + reporter.report("Found invalid group entry: $key") + } + } + entry.existing.findAll { it !in entry.children }.each { println('Removed: ' + it) } + } + } else if ('' == entry.desc) { //Make all public non-abstract subclasses + constructorGroups.put(binaryName, entry) + } + } + + // Process normal lines, remove invalid and remove narrowing + else { + def jcls = inheritance.get(binaryName) + if (jcls === null) { + itr.remove() + reporter.report("Invalid: $key") + } else if (entry.desc == '') { + if (accessLevel(jcls.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) { + itr.remove() + reporter.report("Invalid Narrowing: $key") + } + } else if (!entry.desc.contains('(')) { + if (!jcls.fields || !jcls.fields.containsKey(entry.desc)) { + itr.remove() + reporter.report("Invalid: $key") + } else { + final value = jcls.fields[entry.desc] + if (accessLevel(value.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) { + itr.remove() + reporter.report("Invalid Narrowing: $key - ${entry.comment}") + } + } + } else { + final jdesc = entry.desc.replace('(', ' (') + if (!jcls.methods || !jcls.methods.containsKey(jdesc)) { + itr.remove() + reporter.report("Invalid: $key") + } else { + final value = jcls.methods[jdesc] + if (accessLevel(value.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) { + itr.remove() + reporter.report("Invalid Narrowing: $key") + } + } + } + } + } + + inheritance.each { tcls, value -> + if (!value.methods || ((value.access & Opcodes.ACC_ABSTRACT) !== 0)) return + String parent = tcls + while (parent !== null) { + constructorGroups[parent]?.tap { entry -> + value.methods.each { mtd, v -> + if (mtd.startsWith('')) { + final child = tcls.replaceAll('/', '\\.') + ' ' + mtd.replace(' ', '') + if (accessLevel(v.access) < 3) { + if (lines.containsKey(child)) { + toRemove.add(child) + } else if (child !in entry.existing) { + reporter.report("Missing group entry: $child") + } + entry.children.add(child) + } else if (lines.containsKey(child)) { + toRemove.add(child) + reporter.report("Found invalid group entry: $child") + } + } + } + } + parent = inheritance[parent]?.superName + } + } + constructorGroups.values().each { entry -> entry.existing.findAll { it !in entry.children }.each{ reporter.report("Found invalid group entry: $it") } } + + toRemove.each(lines.&remove) + + return lines + } + + private static List joinBack(TreeMap lines, Map inheritance) { + final data = [] as List + lines.each { key, value -> + if (!value.group) { + def comment = null //value.comment + data.add(value.modifier + ' ' + key + (comment ? ' ' + comment : '')) + } else { + data.add(('#group ' + value.modifier + ' ' + key + ' ' + (value.comment ?: '')).trim()) + value.children.each { + final line = value.modifier + ' ' + it + final entry = ATParser.parseEntry(line) + final comment = null //entry.comment + data.add(line + (comment ? ' ' + comment : '')) + } + data.add('#endgroup') + } + } + return data + } + + static int accessStr(String access) { + if (access.endsWith('-f') || access.endsWith('+f')) return 4 + switch (access.toLowerCase()) { + case 'public': return 3 + case 'protected': return 2 + case 'default': return 1 + case 'private': return 0 + default: return -1 + } + } + + static int accessLevel(int access) { + if ((access & Opcodes.ACC_PUBLIC) !== 0) return 3 + if ((access & Opcodes.ACC_PROTECTED) !== 0) return 2 + if ((access & Opcodes.ACC_PRIVATE) !== 0) return 0 + return 1 + } +} + +@CompileStatic +class ATParser { + static TreeMap parse(List lines, CheckTask.Reporter reporter) { + TreeMap outLines = new TreeMap<>() + Entry group = null + for (final line : lines) { + if (line.isEmpty()) continue + if (line.startsWith('#group ')) { + final entry = parseEntry(line.substring(7)) + + if (entry.desc != '*' && entry.desc != '*()' && entry.desc != '') { + reporter.report("Invalid group: $line", false) + } + + entry.group = true + entry.children = [] + entry.existing = [] + + group = entry + + if (outLines.containsKey(entry.key)) { + reporter.report("Duplicate group: $line", false) + } + + outLines[entry.key] = group + } else if (group !== null) { + if (line.startsWith('#endgroup')) { + group = null + } else { + final key = parseEntry(line).key + group.existing.add(key) + } + } else if (line.startsWith('#endgroup')) { + reporter.report("Invalid group ending: $line", false) + } else if (line.startsWith('#')) { + //Nom + } else { + final entry = parseEntry(line) + if (outLines.containsKey(entry.key)) { + reporter.report("Found duplicate: $line") + continue + } + outLines[entry.key] = entry + } + } + return outLines + } + + static Entry parseEntry(String line) { + final idx = line.indexOf('#') + final String comment = idx === -1 ? null : line.substring(idx) + if (idx !== -1) line = line.substring(0, idx - 1) + final data = (line.trim() + ' ').split(' ', -1) + data[1] = data[1].replaceAll('/', '.') // Convert to Source names, internal names are fine by spec, but not supported by old AST based AT implementations. + new Entry(data[0], data[1], data[2], comment) + } + + @TupleConstructor + static final class Entry { + String modifier, cls, desc, comment + + Set existing + TreeSet children + boolean group = false + + @Lazy + String key = {cls + (desc.isEmpty() ? '' : ' ' + desc)}() + + Object getAt(String key) { + return getProperty(key) + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckExcs.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckExcs.groovy new file mode 100644 index 0000000000..8925657539 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckExcs.groovy @@ -0,0 +1,95 @@ +package net.minecraftforge.forge.tasks.checks + +import net.minecraftforge.forge.tasks.Util +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassVisitor +import org.objectweb.asm.MethodVisitor +import org.objectweb.asm.Type + +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream + +abstract class CheckExcs extends CheckTask { + + @InputFile abstract RegularFileProperty getBinary() + @InputFiles abstract ConfigurableFileCollection getExcs() + + @Override + void check(Reporter reporter, boolean fix) { + final Set known = [] + collectKnown(known) + + excs.each { f -> + final lines = [] + f.eachLine { line -> + int idx = line.indexOf('#') + if (idx === 0 || line.isEmpty()) { + return + } + + if (idx !== -1) line = line.substring(0, idx - 1) + + if (!line.contains('=')) { + reporter.report("Invalid: $line") + return + } + + def (String key, String value) = line.split('=', 2) + if (!known.contains(key)) { + reporter.report("Unknown: $line") + return + } + + String desc = key.split('\\.', 2)[1] + if (!desc.contains('(')) { + reporter.report("Invalid: $line") + return + } + desc = '(' + desc.split('\\(', 2)[1] + + def (exceptions, String args) = value.contains('|') ? value.split('|', 2) : [value, ''] + + if (args.split(',').length !== Type.getArgumentTypes(desc).length) { + reporter.report("Invalid: $line") + return + } + lines.add(line) + + return + } + + if (fix) f.text = lines.sort().join('\n') + } + } + + private void collectKnown(Collection known) { + binary.get().asFile.withInputStream { i -> + new ZipInputStream(i).withCloseable { zin -> + final visitor = new ClassVisitor(Util.ASM_LEVEL) { + private String cls + @Override + void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + this.cls = name + } + + @Override + MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { + known.add(this.cls + '.' + name + descriptor) + super.visitMethod(access, name, descriptor, signature, exceptions) + } + } + ZipEntry zein + while ((zein = zin.nextEntry) !== null) { + if (zein.name.endsWith('.class')) { + ClassReader reader = new ClassReader(zin) + reader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES) + } + } + } + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckMode.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckMode.groovy new file mode 100644 index 0000000000..8580aa64e4 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckMode.groovy @@ -0,0 +1,11 @@ +package net.minecraftforge.forge.tasks.checks + +import groovy.transform.CompileStatic + +@CompileStatic +enum CheckMode { + CHECK, + FIX + + CheckMode() {} +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckPatches.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckPatches.groovy new file mode 100644 index 0000000000..89192dff55 --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckPatches.groovy @@ -0,0 +1,182 @@ +package net.minecraftforge.forge.tasks.checks + +import groovy.transform.CompileStatic +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputDirectory +import org.gradle.api.tasks.Optional + +import java.nio.file.Files +import java.nio.file.Path +import java.util.regex.Pattern + +@CompileStatic +abstract class CheckPatches extends CheckTask { + + private static final Pattern HUNK_START_PATTERN = Pattern.compile('^@@ -[0-9,]* \\+[0-9,_]* @@$') + private static final Pattern WHITESPACE_PATTERN = Pattern.compile('^[+\\-]\\s*$') + private static final Pattern IMPORT_PATTERN = Pattern.compile('^[+\\-]\\s*import.*') + private static final Pattern FIELD_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final)?([^=;]*)(=.*)?;\\s*$') + private static final Pattern METHOD_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final)?([^(]*)[(]([^)]*)?[)]\\s*[{]\\s*$') + private static final Pattern CLASS_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final[\\s]*)?(class|interface)([^{]*)[{]\\s*$') + private static final Map ACCESS_MAP = [private: 0, protected: 2, public: 3].tap { it.put(null, 1) } + + @InputDirectory abstract DirectoryProperty getPatchDir() + @Input @Optional abstract ListProperty getPatchesWithS2SArtifact() + + @Override + void check(Reporter reporter, boolean fix) { + final patchDir = getPatchDir().get().asFile.toPath() + Files.walk(patchDir).withCloseable { + it.filter(Files.&isRegularFile).forEach { path -> + final String relativeName = patchDir.relativize(path).toString() + verifyPatch(path, reporter, fix, relativeName, patchesWithS2SArtifact.get().contains(relativeName.replace('\\', '/'))) + } + } + } + + static boolean accessChange(String previous, String current) { + //return ACCESS_MAP[previous] < ACCESS_MAP[current] + return previous != current + } + + void verifyPatch(Path patch, Reporter reporter, boolean fix, String patchPath, boolean hasS2SArtifact) { + int oldFixedErrors = reporter.fixed.size() + + final lines = Files.readAllLines(patch) + + int hunksStart = 0 + boolean onlyWhiteSpace = false + + final List newLines = [] + + // First two lines are file name ++/-- and we do not care + newLines.add(lines[0] + '\n') + newLines.add(lines[1] + '\n') + + int i + for (i = 2; i < lines.size(); ++i) { + def line = lines[i] + newLines.add(line + '\n') + + if (HUNK_START_PATTERN.matcher(line).find()) { + if (onlyWhiteSpace) { + if (!hasS2SArtifact) + reporter.report("Patch contains only white space hunk starting at line ${hunksStart + 1}, file: $patchPath") + int toRemove = i - hunksStart + while (toRemove-- > 0) + newLines.remove(newLines.size() - 1) + } + hunksStart = i + onlyWhiteSpace = true + continue + } + + if (line.startsWithAny('+','-')) { + def prefixChange = false + def prevLine = lines[i - 1] + + if (line.charAt(0) == (char)'+' && prevLine.charAt(0) == (char)'-') { + def prevTrim = prevLine.substring(1).replaceAll("\\s", "") + def currTrim = line.substring(1).replaceAll("\\s", "") + + if (prevTrim == currTrim) { + prefixChange = true + } + + def pMatcher = FIELD_PATTERN.matcher(prevLine) + def cMatcher = FIELD_PATTERN.matcher(line) + + if (pMatcher.find() && cMatcher.find() && + pMatcher.group(6) == cMatcher.group(6) && // = ... + pMatcher.group(5) == cMatcher.group(5) && // field name + pMatcher.group(3) == cMatcher.group(3) && // static + (accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) { + reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false) + } + + pMatcher = METHOD_PATTERN.matcher(prevLine) + cMatcher = METHOD_PATTERN.matcher(line) + + if (pMatcher.find() && cMatcher.find() && + pMatcher.group(6) == cMatcher.group(6) && // params + pMatcher.group(5) == cMatcher.group(5) && // void name + pMatcher.group(3) == cMatcher.group(3) && // static + (accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) { + reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false) + } + + pMatcher = CLASS_PATTERN.matcher(prevLine) + cMatcher = CLASS_PATTERN.matcher(line) + + if (pMatcher.find() && cMatcher.find() && + pMatcher.group(6) == cMatcher.group(6) && // ClassName<> extends ... + pMatcher.group(5) == cMatcher.group(5) && // class | interface + pMatcher.group(3) == cMatcher.group(3) && // static + (accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) { + reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false) + } + } + + if (line.charAt(0) == (char)'-' && i + 1 < lines.size()) { + final nextLine = lines[i + 1] + if (nextLine.charAt(0) == (char)'+') { + final nextTrim = nextLine.substring(1).replaceAll("\\s", "") + final currTrim = line.substring(1).replaceAll("\\s", "") + + if (nextTrim == currTrim) { + prefixChange = true + } + } + } + + final isWhiteSpaceChange = WHITESPACE_PATTERN.matcher(line).find() + + if (!prefixChange && !isWhiteSpaceChange) { + onlyWhiteSpace = hasS2SArtifact && IMPORT_PATTERN.matcher(line).find() + } else if (isWhiteSpaceChange) { + final prevLineChange = prevLine.startsWithAny('+','-') + final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-') + + if (!prevLineChange && !nextLineChange) { + reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath \n$prevLine\n$line\n${lines[i+1]}", false) + } + } + + if (line.contains('\t')) { + reporter.report("Patch contains tabs on line ${i + 1}, file: $patchPath") + line = line.replaceAll('\t', ' ') + newLines.remove(newLines.size() - 1) + newLines.add(line + '\n') + } + + if (IMPORT_PATTERN.matcher(line).find() && !hasS2SArtifact) { + reporter.report("Patch contains import change on line ${i + 1}, file: $patchPath", false) + } + } + } + + if (onlyWhiteSpace) { + if (!hasS2SArtifact) + reporter.report("Patch contains only white space hunk starting at line ${hunksStart + 1}, file: $patchPath") + def toRemove = i - hunksStart; + while (toRemove-- > 0) + newLines.remove(newLines.size() - 1) + } + + if ((reporter.fixed.size() > oldFixedErrors && fix) || hasS2SArtifact) { + if (newLines.size() <= 2) { + logger.lifecycle("Patch is now empty removing, file: {}", patchPath) + Files.delete(patch) + } + else { + if (!hasS2SArtifact) + logger.lifecycle("*** Updating patch file. Please run setup then genPatches again. ***") + Files.newBufferedWriter(patch).withCloseable { + newLines.each { l -> it.write(l) } + } + } + } + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckSAS.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckSAS.groovy new file mode 100644 index 0000000000..bc93cf05ba --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckSAS.groovy @@ -0,0 +1,110 @@ +package net.minecraftforge.forge.tasks.checks + +import groovy.transform.CompileStatic +import net.minecraftforge.forge.tasks.Annotatable +import net.minecraftforge.forge.tasks.InheritanceData +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles + +@CompileStatic +abstract class CheckSAS extends CheckTask { + + @InputFile abstract RegularFileProperty getInheritance() + @InputFiles abstract ConfigurableFileCollection getSass() + + @Override + void check(Reporter reporter, boolean fix) { + final inheritance = InheritanceData.parse(this.inheritance.get().asFile) + + sass.each { f -> + final lines = [] + f.eachLine { line -> + if (line[0] == '\t') return // Skip any tabbed lines, those are ones we add + final idx = line.indexOf('#') + if (idx == 0 || line.isEmpty()) { + lines.add(line) + return + } + def comment = idx == -1 ? null : line.substring(idx) + if (idx != -1) line = line.substring(0, idx - 1) + final spl = (line.trim().replace('(', ' (') + ' ').split(' ', -1) + def (String cls, String name, String desc) = [spl[0], spl[1], spl[2]] + cls = cls.replaceAll('\\.', '/') + + if (inheritance[cls] === null) { + reporter.report("Invalid: $line") + } else if (name.isEmpty()) { //Class SAS + final toAdd = [] + final clsSided = isSided(inheritance[cls]) + boolean sided = clsSided + + /* TODO: MergeTool doesn't do fields + if (json[cls]['fields'] != null) { + for (entry in json[cls]['fields']) { + if (isSided(entry.value)) { + sided = true + toAdd.add('\t' + cls + ' ' + entry.key) + } + } + } */ + + final clsInh = inheritance[cls] + if (clsInh.methods) { + for (entry in clsInh.methods) { + if (isSided(entry.value)) { + sided = true + toAdd.add('\t' + cls + ' ' + entry.key.replaceAll(' ', '')) + findChildMethods(inheritance, cls, entry.key).each { lines.add('\t' + it) } + findChildMethods(inheritance, cls, entry.key).each { println(line + ' -- ' + it) } + } else if (clsSided) { + findChildMethods(inheritance, cls, entry.key).each { lines.add('\t' + it) } + findChildMethods(inheritance, cls, entry.key).each { println(line + ' -- ' + it) } + } + } + } + + if (sided) { + lines.add(cls + (comment == null ? '' : ' ' + comment)) + lines.addAll(toAdd.sort()) + } else { + reporter.report("Invalid: $line") + } + + } else if (desc.isEmpty()) { // Fields + /* TODO: MergeTool doesn't do fields + if (json[cls]['fields'] != null && isSided(json[cls]['fields'][name])) + lines.add(cls + ' ' + name + (comment == null ? '' : ' ' + comment)) + else */ + reporter.report("Invalid: $line") + } else { // Methods + final clsInh = inheritance[cls] + if (clsInh.methods === null || !isSided(clsInh.methods[name + ' ' + desc])) + reporter.report("Invalid: $line") + else { + lines.add(cls + ' ' + name + desc + (comment == null ? '' : ' ' + comment)) + findChildMethods(inheritance, cls, name + ' ' + desc).each { println(line + ' -- ' + it) } + findChildMethods(inheritance, cls, name + ' ' + desc).each { lines.add('\t' + it) } + } + } + } + + if (fix) f.text = lines.join('\n') + } + } + + protected static boolean isSided(Annotatable annotatable) { + if (annotatable === null) return false + for (ann in annotatable.annotations) { + if ('Lnet/minecraftforge/api/distmarker/OnlyIn;' == ann.desc) + return true + } + return false + } + + protected static findChildMethods(Map json, String cls, String desc) { + return json.values().findAll{ it.methods !== null && it.methods[desc] !== null && it.methods[desc].override == cls && isSided(it.methods[desc]) } + .collect { it.name + ' ' + desc.replace(' ', '') } as TreeSet + } +} diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckTask.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckTask.groovy new file mode 100644 index 0000000000..62b50abdbf --- /dev/null +++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/checks/CheckTask.groovy @@ -0,0 +1,114 @@ +package net.minecraftforge.forge.tasks.checks + +import groovy.transform.CompileStatic +import groovy.transform.stc.ClosureParams +import groovy.transform.stc.ThirdParam +import net.minecraftforge.forge.tasks.Util +import org.gradle.api.Action +import org.gradle.api.DefaultTask +import org.gradle.api.logging.LogLevel +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.VerificationTask + +@CompileStatic +abstract class CheckTask extends DefaultTask implements VerificationTask { + @Input + abstract Property getMode() + + private boolean ignoreFailures = false + + @Input + @Override + boolean getIgnoreFailures() { + return ignoreFailures + } + + @Override + void setIgnoreFailures(boolean ignoreFailures) { + this.ignoreFailures = ignoreFailures + } + + @TaskAction + void run() { + Util.init() + + boolean doFix = getMode().get() === CheckMode.FIX + final Reporter reporter = new Reporter(doFix) + check(reporter, doFix) + + if (reporter.messages) { + if (getMode().get() === CheckMode.CHECK) { + logger.error("Check task '{}' found errors:\n{}", name, reporter.messages.join('\n')) + if (!ignoreFailures) { + throw new IllegalArgumentException("${reporter.messages.size()} errors were found!") + } + } else { + if (logger.isEnabled(LogLevel.DEBUG)) { + logger.warn("Check task '{}' found {} errors and fixed {}:\n{}", name, reporter.messages.size(), reporter.fixed.size(), reporter.fixed.join('\n')) + } else { + logger.warn("Check task '{}' found {} errors and fixed {}.", name, reporter.messages.size(), reporter.fixed.size()) + } + + if (reporter.notFixed) { + logger.error('{} errors could not be fixed:\n{}', reporter.notFixed.size(), reporter.notFixed.join('\n')) + if (!ignoreFailures) { + throw new IllegalArgumentException("${reporter.notFixed.size()} errors which cannot be fixed were found!") + } + } + } + } + } + + abstract void check(Reporter reporter, boolean fix) + + @CompileStatic + static final class Reporter { + final boolean trackFixed + Reporter(boolean trackFixed) { + this.trackFixed = trackFixed + } + + public final List messages = [] + + public final List fixed = [] + public final List notFixed = [] + + void report(String message, boolean canBeFixed = true) { + messages.add(message) + + if (trackFixed) { + if (canBeFixed) { + fixed.add(message) + } else { + notFixed.add(message) + } + } + } + } + + static void registerTask(TaskContainer tasks, String taskName, @DelegatesTo.Target('type') Class clazz, + @DelegatesTo(genericTypeIndex = 0, target = 'type') + @ClosureParams(ThirdParam.FirstGenericType) Closure configuration) { + taskName = taskName.capitalize() + tasks.register("check$taskName", clazz) { CheckTask task -> + def castedTask = task as T + configuration.setDelegate(castedTask) + configuration.call(castedTask) + castedTask.mode.set(CheckMode.CHECK) + castedTask.group = 'checks' + } + tasks.named('checkAll').configure { it.dependsOn("check$taskName") } + + tasks.register("checkAndFix$taskName", clazz) { CheckTask task -> + def castedTask = task as T + configuration.setDelegate(castedTask) + configuration.call(castedTask) + castedTask.mode.set(CheckMode.FIX) + castedTask.group = 'checks' + } + tasks.named('checkAllAndFix').configure { it.dependsOn("checkAndFix$taskName") } + } +} diff --git a/build_clean.gradle b/build_clean.gradle new file mode 100644 index 0000000000..21471fcc6c --- /dev/null +++ b/build_clean.gradle @@ -0,0 +1,73 @@ +plugins { + id 'java-library' + id 'net.minecraftforge.gradle.patcher' +} + +evaluationDependsOn(':mcp') + +repositories { + mavenCentral() + maven gradleutils.forgeMaven + maven gradleutils.minecraftLibsMaven +} + +java.toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) + +dependencies { + implementation(libs.forgespi) +} + +patcher { + parent = project(':mcp') + mcVersion = MC_VERSION + patchedSrc = file('src/main/java') + + mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION + + runs { + clean_client { + client true + taskName 'clean_client' + ideaModule "${rootProject.name}.${project.name}.main" + + main 'net.minecraft.client.main.Main' + workingDirectory project.file('run/client') + + args '--gameDir', '.' + args '--version', MC_VERSION + args '--assetsDir', downloadAssets.output + args '--assetIndex', '{asset_index}' + args '--accessToken', '0' + } + + clean_server { + client false + taskName 'clean_server' + ideaModule "${rootProject.name}.${project.name}.main" + + main 'net.minecraft.server.Main' + workingDirectory project.file('run/server') + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation + options.warnings = false // Shutup deprecated for removal warnings +} + +eclipse.classpath.file.whenMerged { + // Disable optional warnings on the minecraft decompiled source code. It just muddies the warning window and hides warnings in our own codebase + 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 new file mode 100644 index 0000000000..3df89c798d --- /dev/null +++ b/build_forge.gradle @@ -0,0 +1,1021 @@ +import de.undercouch.gradle.tasks.download.Download +import net.minecraftforge.forge.tasks.checks.CheckATs +import net.minecraftforge.forge.tasks.checks.CheckExcs +import net.minecraftforge.forge.tasks.checks.CheckPatches +import net.minecraftforge.forge.tasks.checks.CheckSAS +import net.minecraftforge.forge.tasks.checks.CheckTask + +import java.nio.file.Files +import net.minecraftforge.forge.tasks.* +import static net.minecraftforge.forge.tasks.Util.* +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 org.apache.tools.ant.filters.ReplaceTokens +import org.objectweb.asm.Opcodes + +plugins { + id 'idea' + id 'eclipse' + id 'java-library' + id 'maven-publish' + id 'net.minecraftforge.licenser' + id 'de.undercouch.download' + id 'net.minecraftforge.gradleutils' + id 'net.minecraftforge.gradle.patcher' + id 'net.minecraftforge.gradlejarsigner' +} + +Util.init() //Init all our extension methods! + +// We depend on all other projects so that we can know their versions for userdev config +rootProject.subprojects.each { sib -> if (sib != project) evaluationDependsOn(sib.path) } + +apply from: rootProject.file('build_shared.gradle') + +java { + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) + withSourcesJar() +} + +jarSigner.autoDetect('forge') + +applyPatches { + level 'WARNING' + failOnError = UPDATING != 'true' + rejects = rootProject.layout.projectDirectory.dir('rejects').asFile +} + +sourceSets { + main { + java { + srcDir "$rootDir/src/main/java" + } + resources { + srcDir "$rootDir/src/main/resources" + srcDir "$rootDir/src/main/generated" + } + } + test { + java { + srcDir "$rootDir/src/test/java" + } + resources { + srcDir "$rootDir/src/test/resources" + srcDir "$rootDir/src/test/generated" + } + } +} + +final String SPEC_VERSION = gitversion.info.tag + +// The new versioning sceme is -.. +// ForgeMC is a unique identifier for every MC version we have supported. +// Essentially, the same as the old, except dropping the first number, and the builds are no longer unique. +final def MCP_ARTIFACT = project(':mcp').mcp.config.get() + +final List EXTRA_TXTS = [ + rootProject.file('LICENSE.txt'), + rootProject.tasks.createChangelog.outputFile +] + +ext { + MAVEN_PATH = "${group.toString().replace('.', '/')}/${project.name}/${VERSION}".toString() +} +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.5' +final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6' +final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.2.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 } + installer { + extendsFrom(bootstrap) + transitive = false + } + api.extendsFrom(installer) +} + +dependencies { + // These need to actually be on the classpath at the start. This is only used for the server shim jar. + // And this is only needed because custom file systems are REQUIRED to be on the boot classloader. + // This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project. + bootstrap(libs.jarjar.fs) // JarInJar file system + bootstrap(libs.roimfs) // JarInJar File System - FileSystems need to be on boot loader. + bootstrap(libs.bundles.jimfs) // In memory file system used for ForgeDev launches + bootstrap(libs.securemodules) // Has Union file system in it + bootstrap(libs.unsafe) // Needed by securemodules + bootstrap(libs.bundles.asm) // Needed by securemodules + + implementation(libs.jopt.simple) + + installer(libs.bootstrap) + installer(libs.bootstrap.api) // Needed by securemodules + installer(libs.accesstransformers) + installer(libs.eventbus) + installer(libs.jspecify) // Dep of EventBus + installer(libs.forgespi) + installer(libs.coremods.api) + installer(libs.modlauncher) + installer(libs.mergetool.api) + installer(libs.bundles.night.config) + installer(libs.maven.artifact) + installer(libs.bundles.terminalconsoleappender) + installer(libs.mixin) + installer(libs.mixinextras.forge) + installer(libs.bundles.jarjar) + installer(libs.roimfs) + + installer(project(':fmlcore')) + installer(project(':fmlloader')) + installer(project(':fmlearlydisplay')) + installer(project(':javafmllanguage')) + installer(project(':lowcodelanguage')) + installer(project(':mclanguage')) + installer(project(':forge-transformers')) + + runtimeOnly(libs.bootstrap) + runtimeOnly(libs.bootstrap.dev) + + annotationProcessor(libs.eventbus.validator) +} + +tasks.named('extractRangeMap').configure { + tool = S2S_TOOL +} +tasks.named('applyRangeMap').configure { + tool = S2S_TOOL +} +tasks.named('applyRangeMapBase').configure { + tool = S2S_TOOL +} + +// Disable all tests, we have GameTests not JUnit tests +test { + exclude '**/*' +} + +patcher { + excs.from file("$rootDir/src/main/resources/forge.exc") + parent = project(':mcp') + mcVersion = MC_VERSION + mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION + patches = file("$rootDir/patches/minecraft") + patchedSrc = file('src/main/java') + srgPatches = false + accessTransformers.from file("$rootDir/src/main/resources/META-INF/accesstransformer.cfg") + sideAnnotationStrippers.from file("$rootDir/src/main/resources/forge.sas") + + runs { + forge_client { + property 'eventbus.api.strictRuntimeChecks', 'true' + property 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll' + + args '--launchTarget', 'forge_dev_client', + '--username', 'Dev', + '--version', project.name, + '--accessToken', '0', + '--userType', 'mojang', + '--versionType', 'release', + '--assetsDir', downloadAssets.output, + '--assetIndex', "{asset_index}" + } + + forge_client_test { + parent runs.forge_client + source sourceSets.test + } + + forge_server { + args '--launchTarget', 'forge_dev_server' + } + + forge_server_test { + parent runs.forge_server + source sourceSets.test + } + + forge_server_gametest { + args '--launchTarget', 'forge_dev_server_gametest' + args '--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs + } + + forge_server_gametest_test { + parent runs.forge_server_gametest + source sourceSets.test + } + + forge_data { + args '--launchTarget', 'forge_dev_data', + '--mod', 'forge', + '--all', + '--output', rootProject.file('src/main/generated/'), + '--existing', sourceSets.main.resources.srcDirs[0], + '--assetsDir', downloadAssets.output, + '--assetIndex', "{asset_index}" + } + + forge_data_test { + source sourceSets.test + args '--launchTarget', 'forge_dev_data', + '--mod', '.+', + '--all', + '--output', rootProject.file('src/test/generated/'), + '--existing', sourceSets.main.resources.srcDirs[0], + '--existing', sourceSets.test.resources.srcDirs[0], + '--assetsDir', downloadAssets.output, + '--assetIndex', "{asset_index}" + } + + forge_client_data { + args '--launchTarget', 'forge_dev_client_data', + '--mod', 'forge', + '--all', + '--output', rootProject.file('src/main/generated/'), + '--existing', sourceSets.main.resources.srcDirs[0], + '--assetsDir', downloadAssets.output, + '--assetIndex', "{asset_index}" + } + + forge_client_data_test { + source sourceSets.test + args '--launchTarget', 'forge_dev', + '--launchEntry', 'minecraft/net.minecraft.client.data.Main', + '--launchData', + '--mod', '.+', + '--all', + '--output', rootProject.file('src/test/generated/'), + '--existing', sourceSets.main.resources.srcDirs[0], + '--existing', sourceSets.test.resources.srcDirs[0], + '--assetsDir', downloadAssets.output, + '--assetIndex', "{asset_index}" + } + } +} + +afterEvaluate { + if (!patcher.srgPatches) { + srg2mcpClean { + dependsOn = [] + input = project(':mcp').setupMCP.output + } + userdevJar { + onlyIf = { t -> true } + } + } +} + +tasks.register('downloadCrowdin', Download) { + src 'https://files.minecraftforge.net/crowdin.zip' + dest file('build/crowdin.zip') + useETag 'all' + onlyIfModified true + quiet true +} + +tasks.userdevConfig.configure { + configurations.installer.allDependencies.forEach { + def dep = it.toString() + if (it instanceof ProjectDependency) + dep = "net.minecraftforge:$it.dependencyProject.name:$it.dependencyProject.version" + libraries.add(dep) + } + + // TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config + // so we don't gotta keep making exceptions for MixinExtras + addCompileDependency(libs.mixinextras.common) + addAnnotationProcessorDependency(libs.mixinextras.common) + + inject = '' // We don't have a userdev sourceset anymore. Empty as a gradle workaround... + runs { + client { + environment 'MCP_MAPPINGS', '{mcp_mappings}' + property 'forge.enableGameTest', 'true' + args '--launchTarget', "forge_userdev_client" + args '--version', 'MOD_DEV' + args '--assetIndex', '{asset_index}' + args '--assetsDir', '{assets_root}' + } + + clientData { + environment 'MCP_MAPPINGS', '{mcp_mappings}' + args '--launchTarget', "forge_userdev_client_data" + args '--assetIndex', '{asset_index}' + args '--assetsDir', '{assets_root}' + } + + server { + environment 'MCP_MAPPINGS', '{mcp_mappings}' + property 'forge.enableGameTest', 'true' + args '--launchTarget', "forge_userdev_server" + } + + gameTestServer { + environment 'MCP_MAPPINGS', '{mcp_mappings}' + args '--launchTarget', "forge_userdev_server_gametest" + } + + data { + environment 'MCP_MAPPINGS', '{mcp_mappings}' + args '--launchTarget', "forge_userdev_data" + args '--assetIndex', '{asset_index}' + args '--assetsDir', '{assets_root}' + } + } +} + +for (def run in patcher.runs + tasks.userdevConfig.runs) { + if (run.parents) continue // We already added this to the parent run config + //run.property 'bsl.debug', 'true' + run.args '--gameDir', '.' + run.jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' + run.client run.name.contains('client') + run.main 'net.minecraftforge.bootstrap.ForgeBootstrap' +} + +for (def run : patcher.runs) { + def isTest = run.name.endsWith('_test') + run.taskName = run.name + run.workingDirectory file('run/' + run.name) + run.ideaModule rootProject.name + '.' + project.name + '.' + (isTest ? 'test' : 'main') + run.property 'bsl.debug', 'true' + run.property 'terminal.jline', 'true' + if (isTest) { + run.property 'forge.enableGameTest', 'true' + run.property 'forgedev.enableTestMods', 'true' + } +} + +tasks.register('downloadVersionManifest', Download) { + src 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json' + dest file('build/versions/version_manifest.json') + useETag 'all' + onlyIfModified true + quiet true +} +tasks.register('downloadJson', Download) { + dependsOn downloadVersionManifest + inputs.file downloadVersionManifest.dest + src { downloadVersionManifest.dest.json.versions.find { it.id == MC_VERSION }.url } + dest file("build/versions/$MC_VERSION/version.json") + useETag 'all' + onlyIfModified true + quiet true +} +tasks.register('downloadClientRaw', Download) { + dependsOn downloadJson + inputs.file downloadJson.dest + src { downloadJson.dest.json.downloads.client.url } + dest file("build/versions/$MC_VERSION/client.jar") + useETag 'all' + onlyIfModified true + quiet true +} +tasks.register('downloadServerRaw', Download) { + dependsOn downloadJson + inputs.file downloadJson.dest + src { downloadJson.dest.json.downloads.server.url } + dest file("build/versions/$MC_VERSION/server-bundled.jar") + useETag 'all' + onlyIfModified true + quiet true +} +tasks.register('extractServer', ExtractFile) { + dependsOn downloadServerRaw + input = downloadServerRaw.dest + target = "META-INF/versions/$MC_VERSION/server-${MC_VERSION}.jar" + output = file("build/versions/$MC_VERSION/server.jar") +} +tasks.register('downloadLibraries', DownloadLibraries) { + dependsOn downloadJson + input = downloadJson.dest + output = rootProject.file('build/libraries/') +} +tasks.register('extractInheritance', ExtractInheritance) { + dependsOn downloadLibraries + tool = INSTALLER_TOOLS + ':fatjar' + args.add '--annotations' + input = genJoinedBinPatches.cleanJar + libraries.addAll downloadLibraries.librariesOutput.map { rf -> + Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).toList() + } +} +tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) { + dependsOn downloadClientRaw + jar = downloadClientRaw.dest + output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json') + predicate = { + parent, node, insn -> + return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it. + && insn.getOpcode().equals(Opcodes.INVOKEVIRTUAL) + && insn.name == 'finalizeSpawn' + && insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;'; + } +} +tasks.register('validateDeprecations', ValidateDeprecations) { + input = tasks.jar.archiveFile + mcVersion = MC_VERSION +} +tasks.named('jar', Jar).configure { + finalizedBy 'validateDeprecations' +} +tasks.register("downloadInstaller", DownloadMavenArtifact) { + artifact = "net.minecraftforge:installer:2.2.+:fatjar" + changing = true +} +tasks.register("downloadServerShim", DownloadMavenArtifact) { + artifact = libs.bootstrap.shim.get().toString() + changing = true +} +tasks.register("createJoinedSRG", DownloadMavenArtifact) { + artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}" +} +tasks.named('genClientBinPatches').configure { + dependsOn(downloadClientRaw) + tool = BINPATCH_TOOL + cleanJar = downloadClientRaw.dest + dirtyJar = jar.archiveFile +} +tasks.named('genServerBinPatches').configure { + dependsOn(extractServer) + tool = BINPATCH_TOOL + cleanJar = extractServer.output + dirtyJar = jar.archiveFile +} +tasks.named('genJoinedBinPatches').configure { + tool = BINPATCH_TOOL + cleanJar = createJoinedSRG.output + dirtyJar = jar.archiveFile +} +tasks.register('applyClientBinPatches', ApplyBinPatches) { + dependsOn downloadClientRaw + tool = BINPATCH_TOOL + clean = downloadClientRaw.dest + patch = genClientBinPatches.output + args.addAll(['--data', '--unpatched']) +} +tasks.register('applyServerBinPatches', ApplyBinPatches) { + dependsOn extractServer + tool = BINPATCH_TOOL + clean = extractServer.output + patch = genServerBinPatches.output + args.addAll(['--data', '--unpatched']) +} +tasks.register('applyJoinedBinPatches', ApplyBinPatches) { + tool = BINPATCH_TOOL + clean = genJoinedBinPatches.cleanJar + patch = genJoinedBinPatches.output +} +tasks.register('createServerShimClasspath', BundleList) { + dependsOn(downloadServerRaw) + serverBundle = downloadServerRaw.dest +} +tasks.register('createServerShimConfig') { + ext.output = file('build/libs/bootstrap-shim.properties') + doLast { + var cfg = new CleanProperties() + cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap' + cfg['Java-Version'] = '25' + cfg['Arguments'] = '--launchTarget forge_server' + cfg.store(output) + } +} +tasks.register('serverShimJar', Jar) { + dependsOn(createServerShimConfig) + from (createServerShimConfig.output) + from (createServerShimClasspath.output) { + rename { 'bootstrap-shim.list' } + } + from (zipTree(downloadServerShim.output)) + manifest { + from { + zipTree(downloadServerShim.output).find { it.name == 'MANIFEST.MF' } + } + + attributes('Class-Path': configurations.bootstrap.resolvedConfiguration.resolvedArtifacts.collect { "libraries/${Util.getMavenInfoFromDep(it).path}" }.join(' ')) + } + archiveClassifier = 'shim' + jarSigner.sign(it) +} +tasks.register('checkAll') { + dependsOn 'checkLicenses' + group = 'checks' +} +tasks.register('checkAllAndFix') { + dependsOn 'findFinalizeSpawnTargets', 'checkLicenses' + group = 'checks' +} + +CheckTask.registerTask(tasks, 'ATs', CheckATs) { + dependsOn extractInheritance + ats.from patcher.accessTransformers + inheritance = extractInheritance.output +} + +CheckTask.registerTask(tasks, 'SAS', CheckSAS) { + dependsOn extractInheritance + sass.from patcher.sideAnnotationStrippers + inheritance = extractInheritance.output +} + +CheckTask.registerTask(tasks, 'Excs', CheckExcs) { + dependsOn jar + binary = jar.archiveFile.get().asFile + excs.from patcher.excs +} + +CheckTask.registerTask(tasks, 'Patches', CheckPatches) { + dependsOn 'genPatches' + patchDir = file("$rootDir/patches") + patchesWithS2SArtifact = [ + 'minecraft/net/minecraft/client/renderer/ViewArea.java.patch', + 'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch', + ] +} + +tasks.named('genPatches', GeneratePatches).configure { + finalizedBy checkAndFixPatches + autoHeader true + lineEnding = '\n' +} + +def baseForgeVersionProperty = project.objects.property(String) +baseForgeVersionProperty.set(project.provider { TeamcityRequests.attemptFindBase(rootDir) ?: getLatestForgeVersion(MC_VERSION) }) +baseForgeVersionProperty.finalizeValueOnRead() +final jarCompatibilityTaskSetup = { Task task -> + task.group = 'jar compatibility' + task.onlyIf { + baseForgeVersionProperty.getOrNull() !== null + } +} + +tasks.register('setupCheckJarCompatibility', SetupCheckJarCompatibility) { + inputVersion = baseForgeVersionProperty +} + +tasks.register('applyBaseCompatibilityJarBinPatches', ApplyBinPatches) { + jarCompatibilityTaskSetup(it) + + clean = project.tasks.createJoinedSRG.output + patch = project.tasks.named('setupCheckJarCompatibility').flatMap { it.baseBinPatchesOutput } + output = project.layout.buildDirectory.dir(name).map { it.file('output.jar') } +} + +tasks.register('mergeBaseForgeJar', MergeJars) { + jarCompatibilityTaskSetup(it) + + inputJars.from(project.tasks.named('applyBaseCompatibilityJarBinPatches').flatMap { it.output }) + inputJars.from(baseForgeVersionProperty.map { inputVersion -> + def output = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-universal.jar") }.get().asFile + project.rootProject.extensions.download.run { + src "https://maven.minecraftforge.net/net/minecraftforge/forge/${inputVersion}/forge-${inputVersion}-universal.jar" + dest output + } + return output + }) +} + +tasks.register('checkJarCompatibility', CheckJarCompatibility) { + jarCompatibilityTaskSetup(it) + dependsOn 'setupCheckJarCompatibility' + + baseJar = project.tasks.named('mergeBaseForgeJar').flatMap { it.output } + baseLibraries.from(project.tasks.named('createJoinedSRG').flatMap { it.output }) + + inputJar = project.tasks.named('reobfJar').flatMap { it.output } + + commonLibraries.from(project.configurations.minecraftImplementation) + commonLibraries.from(project.configurations.installer) +} + +tasks.register('launcherJson', LauncherJson).configure { + json.putAll([ + mainClass: 'net.minecraftforge.bootstrap.ForgeBootstrap', + arguments: [ + game: [ + '--launchTarget', 'forge_client' + ], + jvm: [ + '-Djava.net.preferIPv6Addresses=system', + '-XX:+UseCompactObjectHeaders' + ] + ] + ] as LinkedHashMap) +} + +tasks.register('installerJson', InstallerJson) { + icon = rootProject.file('icon.ico') + + // Json to install into the client's launcher + dependsOn(launcherJson) + input.from(launcherJson.output) + + // Get 'base' MC jar, Client is straight download, server is extracted from the bundle + dependsOn(downloadClientRaw, extractServer) + input.from(downloadClientRaw.dest, extractServer.output) + // Apply Binary patches to vanilla jar + dependsOn(applyClientBinPatches, applyServerBinPatches) + input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar) + + doFirst { + var libs = libraries + String[] INSTALLER_TOOLS_CLASSPATH = getClasspath(project, libs, INSTALLER_TOOLS) + json.putAll([ + _comment: launcherJson.json._comment, + hideExtract: true, + spec: 1, + profile: project.name, + version: launcherJson.json.id, + path: Util.getMavenInfoFromTask(tasks.serverShimJar).name, + minecraft: MC_VERSION, + serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar', + data: [ + MC_UNPACKED: [ + client: "[net.minecraft:client:${MC_VERSION}]", + server: "[net.minecraft:server:${MC_VERSION}:unpacked]" + ], + MC_UNPACKED_SHA: [ + client: "'${downloadClientRaw.dest.sha1}'", + server: "'${extractServer.output.get().asFile.sha1}'" + ], + BINPATCH: [ + client: '/data/client.lzma', + server: '/data/server.lzma' + ], + PATCHED: [ + client: "[${project.group}:${project.name}:${project.version}:client]", + server: "[${project.group}:${project.name}:${project.version}:server]" + ], + PATCHED_SHA: [ + client: "'${applyClientBinPatches.output.get().asFile.sha1}'", + server: "'${applyServerBinPatches.output.get().asFile.sha1}'" + ] + ], + processors: [ + [ + sides: ['server'], + jar: INSTALLER_TOOLS, + classpath: INSTALLER_TOOLS_CLASSPATH, + args: [ + '--task', 'EXTRACT_FILES', + '--archive', '{INSTALLER}', + + '--from', 'data/README.txt', + '--to', '{ROOT}/README.txt', + + '--from', 'data/run.sh', + '--to', '{ROOT}/run.sh', + '--exec', '{ROOT}/run.sh', + + '--from', 'data/run.bat', + '--to', '{ROOT}/run.bat', + + '--from', 'data/user_jvm_args.txt', + '--to', '{ROOT}/user_jvm_args.txt', + '--optional', '{ROOT}/user_jvm_args.txt', + + '--from', 'data/unix_args.txt', + '--to', "{ROOT}/libraries/${MAVEN_PATH}/unix_args.txt", + + '--from', 'data/win_args.txt', + '--to', "{ROOT}/libraries/${MAVEN_PATH}/win_args.txt" + ] + ], [ + sides: ['server'], + jar: INSTALLER_TOOLS, + classpath: INSTALLER_TOOLS_CLASSPATH, + args: [ + '--task', 'BUNDLER_EXTRACT', + '--input', '{MINECRAFT_JAR}', + '--output', '{ROOT}/libraries/', + '--libraries' + ] + ], [ + sides: ['server'], + jar: INSTALLER_TOOLS, + classpath: INSTALLER_TOOLS_CLASSPATH, + args: [ + '--task', 'BUNDLER_EXTRACT', + '--input', '{MINECRAFT_JAR}', + '--output', '{MC_UNPACKED}', + '--jar-only' + ], + outputs: [ + '{MC_UNPACKED}': '{MC_UNPACKED_SHA}' + ] + ], [ + sides: ['server'], + jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar + classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]), + args: [ + '--clean', '{MC_UNPACKED}', + '--output', '{PATCHED}', + '--apply', '{BINPATCH}', + '--data', '--unpatched' + ], + outputs: [ + '{PATCHED}': '{PATCHED_SHA}' + ] + ], [ + sides: ['client'], + jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar + classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]), + args: [ + '--clean', '{MINECRAFT_JAR}', + '--output', '{PATCHED}', + '--apply', '{BINPATCH}', + '--data', '--unpatched' + ], + outputs: [ + '{PATCHED}': '{PATCHED_SHA}' + ] + ] + ] + ] as LinkedHashMap) + getClasspath(project, libs, MCP_ARTIFACT.descriptor) //Tell it to download mcp_config + } +} + +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 + filterInners = true +} + +tasks.named('universalJar').configure { + dependsOn downloadCrowdin + from zipTree(downloadCrowdin.dest).matching { + include 'assets/forge/lang/*.json' + } + + from(EXTRA_TXTS) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + exclude '.cache' + + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.forge' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'Forge', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': SPEC_VERSION, + 'Implementation-Title': project.group, + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': FORGE_VERSION + ] as LinkedHashMap, 'net/minecraftforge/versions/forge/') + attributes([ + 'Specification-Title': 'Minecraft', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': MC_VERSION, + 'Implementation-Title': 'MCP', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': MCP_VERSION + ] as LinkedHashMap, 'net/minecraftforge/versions/mcp/') + } + jarSigner.sign(it) +} + +tasks.named('userdevConfig').configure { + universal = "$project.group:$project.name:$project.version:universal@jar" +} + +tasks.register('installerJar', InstallerJar) { + fat = !System.env.TEAMCITY_VERSION + //offline = true + from(EXTRA_TXTS) + from(rootProject.file('/forge_installer_logo.png')) { + rename { 'big_logo.png' } + } + from(genClientBinPatches.output) { + rename { 'data/client.lzma' } + } + from(genServerBinPatches.output) { + rename { 'data/server.lzma' } + } + + final var argsFile = rootProject.file('server_files/args.txt') + final Map> tokens = [tokens: [ + SHIM_JAR_FILE: serverShimJar.archiveFileName.get(), + MAVEN_PATH: MAVEN_PATH + ]] + from(argsFile) { + filter(tokens, ReplaceTokens) + into 'data' + rename { 'unix_args.txt' } + } + from(argsFile) { + filter(tokens, ReplaceTokens) + into 'data' + rename { 'win_args.txt' } + } + + from(rootProject.file('server_files')) { + filter(tokens, ReplaceTokens) + into 'data' + exclude 'args.txt' + } + + jarSigner.sign(it) +} + +final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) { + gradleVersion = '9.3.1' +} + +tasks.register('mdkZip', Zip) { + dependsOn mdkGradleWrapper + + archiveBaseName = project.name + archiveClassifier = 'mdk' + archiveVersion = project.version + destinationDirectory = file('build/libs') + + from mdkGradleWrapper.map(Wrapper.&getScriptFile) + from mdkGradleWrapper.map(Wrapper.&getBatchScript) + from(EXTRA_TXTS) + into('gradle/wrapper/') { + from mdkGradleWrapper.map(Wrapper.&getJarFile) + from mdkGradleWrapper.map(Wrapper.&getPropertiesFile) + } + from(rootProject.file('mdk/')){ + rootProject.file('mdk/gitignore.txt').eachLine { + if (!it.trim().isEmpty() && !it.trim().startsWith('#')) + exclude it + } + + filter(ReplaceTokens, tokens: [ + FORGE_VERSION: FORGE_VERSION, + FORGE_GROUP: project.group, + FORGE_NAME: project.name, + MC_VERSION: MC_VERSION, + MAPPING_CHANNEL: MAPPING_CHANNEL, + MAPPING_VERSION: MAPPING_VERSION, + FORGE_SPEC_VERSION: SPEC_VERSION.split("\\.")[0], + MC_NEXT_VERSION: MC_NEXT_VERSION, + EVENTBUS_VERSION: libs.versions.eventbus.get() + ]) + rename 'gitignore\\.txt', '.gitignore' + rename 'gitattributes\\.txt', '.gitattributes' + } + from(rootProject.file('src/test/java/com/example/examplemod/')) { + into('src/main/java/com/example/examplemod/') + } + from(rootProject.file('src/test/generated/mdk_datagen/')) { + into('src/main/resources/') + exclude '**/.cache/' + } +} + +license { + header = file("$rootDir/LICENSE-header.txt") + + include 'net/minecraftforge/' + exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java' + + tasks { + main { + files.from files("$rootDir/src/main/java") + } + test { + files.from files("$rootDir/src/test/java") + } + } +} + +tasks.register('genAllData') { + dependsOn 'forge_data', 'forge_data_test', 'forge_client_data_test' +} + +if (project.hasProperty('UPDATE_MAPPINGS')) { + extractRangeMap { + sources.from sourceSets.test.java.srcDirs + addDependencies compileTestJava.classpath + } + applyRangeMap { + sources.from sourceSets.test.java.srcDirs + } + sourceSets.test.java.srcDirs.each { extractMappedNew.addTarget it } +} + +tasks.named('javadoc', Javadoc).configure { + description 'Generates the combined javadocs for the FML projects and the main Forge project' + var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage', ':forge-transformers' ] + source includedProjects.collect { project(it).sourceSets.main.allJava } + classpath = classpath + files(includedProjects.collect { project(it).sourceSets.main.compileClasspath }) + + var docsDir = rootProject.file('src/docs/') + inputs.dir(docsDir) + .withPropertyName('docs resources directory') + .withPathSensitivity(PathSensitivity.RELATIVE) + .optional() + + failOnError = false + + // Exclude the Minecraft classes if not enabled + if (!project.hasProperty('generateAllDocumentation')) { + exclude 'net/minecraft/**' + exclude 'com/mojang/**' + } + exclude 'mcp/**' + + options.addStringOption('Xdoclint:all,-missing', '-public') + options { + stylesheetFile = new File(docsDir, 'stylesheet.css') + + tags = [ + 'apiNote:a:API Note:', + 'implSpec:a:Implementation Requirements:', + 'implNote:a:Implementation Note:' + ] + + groups = [ + 'Forge Mod Loader': [ + 'net.minecraftforge.fml.common.asm*', + 'net.minecraftforge.fml.loading*', + 'net.minecraftforge.fml.server*' + ], + 'FML Core': [ + 'net.minecraftforge.fml', + 'net.minecraftforge.fml.config*', + 'net.minecraftforge.fml.event*', + 'net.minecraftforge.fml.util*' + ], + 'FML Common': [ + 'net.minecraftforge.fml.core', + 'net.minecraftforge.fml.event.config', + 'net.minecraftforge.fml.event.lifecycle' + ], + 'FML Java/MC Language Providers': [ + 'net.minecraftforge.fml.common', + 'net.minecraftforge.fml.javafmlmod', + 'net.minecraftforge.fml.mclanguageprovider' + ], + 'Minecraft Forge API': [ + 'net.minecraftforge*' + ] + ] + + author = false + noSince = true + noHelp = true + + bottom = "Minecraft Forge is an open source modding API for Minecraft: Java Edition, licensed under the Lesser GNU General Public License, version 2.1." + windowTitle = "Minecraft Forge API ${VERSION}" + docTitle = "Minecraft Forge API - ${FORGE_VERSION} for Minecraft ${MC_VERSION}" + header = "
${FORGE_VERSION} for Minecraft ${MC_VERSION}
" + } + + doLast { + project.copy { + from docsDir + exclude '/stylesheet.css' + into destinationDir + } + } +} + +publishing { + publications.register('mavenJava', MavenPublication).configure { + artifact universalJar + artifact installerJar + artifact mdkZip + artifact userdevJar + artifact sourcesJar + artifact serverShimJar + + artifactId = project.name + pom { + name = project.name + description = 'Modifactions to Minecraft to enable mod developers.' + url = 'https://github.com/MinecraftForge/MinecraftForge' + gradleutils.pom.setGitHubDetails(pom, 'MinecraftForge') + license gradleutils.pom.Licenses.LGPLv2_1 + } + } + + repositories { + maven gradleutils.publishingForgeMaven + } +} + +// Make sure we run bin compat checking during local testing. +if ((!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) && CHECK_COMPATIBILITY == "true") + tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') } diff --git a/build_shared.gradle b/build_shared.gradle new file mode 100644 index 0000000000..b988510649 --- /dev/null +++ b/build_shared.gradle @@ -0,0 +1,89 @@ +import net.minecraftforge.forge.tasks.CleanProperties + +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'net.minecraftforge.gradleutils' + +group = 'net.minecraftforge' +version = VERSION +println("Version: $version") + +repositories { + mavenCentral() + maven gradleutils.forgeMaven + maven gradleutils.minecraftLibsMaven + //mavenLocal() +} + +tasks.withType(Javadoc).configureEach { + options.tags = [ + 'apiNote:a:API Note:', + 'implSpec:a:Implementation Requirements:', + 'implNote:a:Implementation Note:' + ] + options.addStringOption('Xdoclint:all,-missing', '-public') +} + +// We need to write the manifest to the binary file so we have properly versioned packaged at dev time. +tasks.register('writeManifest') { + doLast { + if (plugins.findPlugin('net.minecraftforge.gradle.patcher')) // Forge project + universalJar.manifest.writeTo(rootProject.file('src/main/resources/META-INF/MANIFEST.MF')) + else + jar.manifest.writeTo(project.file('src/main/resources/META-INF/MANIFEST.MF')) + } +} + +tasks.register('generateResources') { + dependsOn('writeManifest') +} + +tasks.named('processResources') { + dependsOn(generateResources) +} + +// Make sure out manifests get written before compiling the code, IDEA calls this task if you tell it to use the gradle build. +tasks.withType(JavaCompile).configureEach { + dependsOn 'generateResources' + dependsOn 'processResources' // Needed because we merge the output of this with the output of the compile task. And gradle detects downstream tasks using the output without a hard dep + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation + options.warnings = false // Shutup deprecated for removal warnings + options.forkOptions.jvmArgs += '-Xmx6G' // Needed to make compiling faster, and not run out of heap space in some cases. +} + +// Merge the resources and classes into the same directory. We'll need to split them at runtime because +// Minecraft and Forge are in the same sourceSet as they are inter dependent.. for now.. +sourceSets.each { + def dir = layout.buildDirectory.dir("classes/java/$it.name") + it.output.resourcesDir = dir + it.java.destinationDirectory = dir +} + +tasks.register('copyEclipseSettings') { + doLast { + rootProject.fileTree('ide/eclipse/template/.settings/').matching { include '**/*.prefs' }.each { file -> + def target = project.file('.settings/' + file.name) + def temp = new CleanProperties().load(file) + def exst = new CleanProperties().load(target) + exst.put('eclipse.preferences.version', '1') + exst.putAll(temp) + exst.store(target) + } + } +} + +// TODO: [Gradle][IntelliJ] Auto trigger these tasks on import. +eclipse { + // Run everytime eclipse builds the code + //autoBuildTasks writeManifest + // Run when importing the project + synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject +} + +idea { + module { + // IntelliJ IDEA does not do this by itself anymore... + downloadJavadoc = true + downloadSources = true + } +} diff --git a/docs/README.md b/docs/README.md index e4082e7eac..aa5726b41b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,8 +2,8 @@ MinecraftForge ============= -[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=26.2-&query=$.promos["26.2-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download] -[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=26.2-&query=$.promos["26.2-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo= +[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.21.11-&query=$.promos["1.21.11-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download] +[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=26.1-&query=$.promos["26.1-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo= )][Download] [![Discord](https://img.shields.io/discord/313125603924639766.svg?color=%237289da&label=Discord&logo=discord&logoColor=%237289da)][Discord] [![Support](https://img.shields.io/badge/Patreon-Support-orange.svg?logo=Patreon)][Patreon] Forge is a free, open-source modding API all of your favourite mods use! diff --git a/fmlcore/build.gradle b/fmlcore/build.gradle index d6adcbbea8..2c1153c9c9 100644 --- a/fmlcore/build.gradle +++ b/fmlcore/build.gradle @@ -1,78 +1,68 @@ +import net.minecraftforge.gradleutils.PomUtils + plugins { id 'java-library' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' } -gradleutils.displayName = 'FML' -final vendor = 'Forge Development LLC' -description = 'Modifications to Minecraft to enable mod developers.' +apply from: rootProject.file('build_shared.gradle') dependencies { - compileOnly libs.jetbrains.annotations + compileOnly(libs.jetbrains.annotations) - api libs.eventbus + api(libs.eventbus) + annotationProcessor(libs.eventbus.validator) - implementation projects.fmlloader - implementation libs.commons.io + implementation(project(':fmlloader')) + implementation(libs.commons.io) } java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} -changelog { - from changelogBase +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.fmlcore', + 'FMLModType': 'LIBRARY' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'FML', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'FML', + 'Implementation-Version': '1.0', + 'Implementation-Vendor': 'Forge Development LLC' + ] as LinkedHashMap, 'net/minecraftforge/fml/') + } } tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:-unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.fmlcore', - 'FMLModType' : 'LIBRARY' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Version': '1.0', - 'Implementation-Vendor' : vendor - ], 'net/minecraftforge/fml/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'fmlcore' + pom { + 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 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } } diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/CrashReportCallables.java b/fmlcore/src/main/java/net/minecraftforge/fml/CrashReportCallables.java index d17eaedb7b..18bc69f54f 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/CrashReportCallables.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/CrashReportCallables.java @@ -14,14 +14,16 @@ import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Supplier; -public class CrashReportCallables { +public class CrashReportCallables +{ private static final Logger LOGGER = LogUtils.getLogger(); private static final List crashCallables = Collections.synchronizedList(new ArrayList<>()); /** * Register a custom {@link ISystemReportExtender} */ - public static void registerCrashCallable(ISystemReportExtender callable) { + public static void registerCrashCallable(ISystemReportExtender callable) + { crashCallables.add(callable); } @@ -31,15 +33,19 @@ public class CrashReportCallables { * @param headerName The name of the system report entry * @param reportGenerator The report generator to be called when a crash report is built */ - public static void registerCrashCallable(String headerName, Supplier reportGenerator) { - registerCrashCallable(new ISystemReportExtender() { + public static void registerCrashCallable(String headerName, Supplier reportGenerator) + { + registerCrashCallable(new ISystemReportExtender() + { @Override - public String getLabel() { + public String getLabel() + { return headerName; } @Override - public String get() { + public String get() + { return reportGenerator.get(); } }); @@ -52,23 +58,31 @@ public class CrashReportCallables { * @param reportGenerator The report generator to be called when a crash report is built * @param active The supplier of the flag to be checked when a crash report is built */ - public static void registerCrashCallable(String headerName, Supplier reportGenerator, BooleanSupplier active) { - registerCrashCallable(new ISystemReportExtender() { + public static void registerCrashCallable(String headerName, Supplier reportGenerator, BooleanSupplier active) + { + registerCrashCallable(new ISystemReportExtender() + { @Override - public String getLabel() { + public String getLabel() + { return headerName; } @Override - public String get() { + public String get() + { return reportGenerator.get(); } @Override - public boolean isActive() { - try { + public boolean isActive() + { + try + { return active.getAsBoolean(); - } catch (Throwable t) { + } + catch (Throwable t) + { LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t); return false; } @@ -76,7 +90,8 @@ public class CrashReportCallables { }); } - public static List allCrashCallables() { + public static List allCrashCallables() + { return List.copyOf(crashCallables); } } diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ISystemReportExtender.java b/fmlcore/src/main/java/net/minecraftforge/fml/ISystemReportExtender.java index e39d9d069e..e533be752b 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ISystemReportExtender.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ISystemReportExtender.java @@ -7,10 +7,12 @@ package net.minecraftforge.fml; import java.util.function.Supplier; -public interface ISystemReportExtender extends Supplier { +public interface ISystemReportExtender extends Supplier +{ String getLabel(); - default boolean isActive() { + default boolean isActive() + { return true; } } diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ModContainer.java b/fmlcore/src/main/java/net/minecraftforge/fml/ModContainer.java index 8c453fda1c..b4a1ea8c69 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ModContainer.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ModContainer.java @@ -53,7 +53,7 @@ public abstract class ModContainer { Supplier displayTestSupplier = switch (displayTestString) { case "MATCH_VERSION" -> // default displaytest checks for version string match () -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(), - (incoming, _) -> Objects.equals(incoming, this.modInfo.getVersion().toString())); + (incoming, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString())); case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION; case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ModLoader.java b/fmlcore/src/main/java/net/minecraftforge/fml/ModLoader.java index f6be23d2d1..e8629be1bb 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ModLoader.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ModLoader.java @@ -379,8 +379,8 @@ public final class ModLoader { @SuppressWarnings("removal") public static void postEventWrapContainerInModOrder(T event) { postEventWithWrapInModOrder(event, - (mc, _) -> ModLoadingContext.get().setActiveContainer(mc), - (_, _) -> ModLoadingContext.get().setActiveContainer(null) + (mc, e) -> ModLoadingContext.get().setActiveContainer(mc), + (mc, e) -> ModLoadingContext.get().setActiveContainer(null) ); } diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ModLoadingState.java b/fmlcore/src/main/java/net/minecraftforge/fml/ModLoadingState.java index bba28748b7..ed7347c61e 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ModLoadingState.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ModLoadingState.java @@ -9,6 +9,7 @@ import net.minecraftforge.fml.loading.progress.ProgressMeter; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; +import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.function.Function; diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ModStateTransitionHelper.java b/fmlcore/src/main/java/net/minecraftforge/fml/ModStateTransitionHelper.java index 683b5d92ba..704a707113 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ModStateTransitionHelper.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ModStateTransitionHelper.java @@ -99,7 +99,7 @@ final class ModStateTransitionHelper { results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception))); } - return CompletableFuture.allOf(results).handle((_, _)->null).thenApply(_ -> list); + return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list); } private static CompletableFuture addCompletableFutureTaskForModDispatch( @@ -135,7 +135,7 @@ final class ModStateTransitionHelper { handler.run(); mod.acceptEvent(eventGenerator.apply(mod)); }, executor) - .whenComplete((_, exception) -> { + .whenComplete((mc, exception) -> { mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception); progressBar.increment(); ModLoadingContext.get().setActiveContainer(null); diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/ThreadSelector.java b/fmlcore/src/main/java/net/minecraftforge/fml/ThreadSelector.java index 8a3c9a7347..fe03dcc582 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/ThreadSelector.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/ThreadSelector.java @@ -9,8 +9,8 @@ import java.util.concurrent.Executor; import java.util.function.BinaryOperator; public enum ThreadSelector implements BinaryOperator { - SYNC((sync, _) -> sync), - PARALLEL((_, parallel) -> parallel); + SYNC((sync, parallel) -> sync), + PARALLEL((sync, parallel) -> parallel); private final BinaryOperator selector; diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/config/ModConfig.java b/fmlcore/src/main/java/net/minecraftforge/fml/config/ModConfig.java index bb2f2f5670..dcce18700b 100644 --- a/fmlcore/src/main/java/net/minecraftforge/fml/config/ModConfig.java +++ b/fmlcore/src/main/java/net/minecraftforge/fml/config/ModConfig.java @@ -13,6 +13,8 @@ import net.minecraftforge.fml.loading.StringUtils; import java.io.ByteArrayInputStream; import java.nio.file.Path; +import java.util.Locale; +import java.util.concurrent.Callable; public class ModConfig { diff --git a/fmlearlydisplay/build.gradle b/fmlearlydisplay/build.gradle index b3316d0262..78e8905e8f 100644 --- a/fmlearlydisplay/build.gradle +++ b/fmlearlydisplay/build.gradle @@ -1,74 +1,67 @@ -import org.gradle.api.plugins.jvm.JvmTestSuite -import org.gradle.internal.os.OperatingSystem +import net.minecraftforge.gradleutils.PomUtils plugins { id 'java-library' - id 'jvm-test-suite' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' } +apply from: rootProject.file('build_shared.gradle') + +import org.gradle.internal.os.OperatingSystem switch (OperatingSystem.current()) { - case OperatingSystem.LINUX: - project.ext.lwjglNatives = "natives-linux" - break - case OperatingSystem.MAC_OS: - project.ext.lwjglNatives = "natives-macos" - break - case OperatingSystem.WINDOWS: - project.ext.lwjglNatives = "natives-windows" - break + case OperatingSystem.LINUX: + project.ext.lwjglNatives = "natives-linux" + break + case OperatingSystem.MAC_OS: + project.ext.lwjglNatives = "natives-macos" + break + case OperatingSystem.WINDOWS: + project.ext.lwjglNatives = "natives-windows" + break } -gradleutils.displayName = 'FML Early Display' -final vendor = 'Forge Development LLC' -description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.' - java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} - -changelog { - from changelogBase -} - dependencies { - compileOnly libs.jetbrains.annotations - - implementation projects.fmlloader - implementation projects.fmlcore - implementation libs.bundles.lwjgl - implementation earlyDisplayLibs.slf4j.api - implementation libs.jopt.simple + compileOnly(libs.jetbrains.annotations) + implementation(project(':fmlloader')) + implementation(project(':fmlcore')) + implementation(libs.bundles.lwjgl) + implementation('org.slf4j:slf4j-api:1.8.0-beta4') + implementation(libs.jopt.simple) + testImplementation('org.junit.jupiter:junit-jupiter-api:5.8.2') + testImplementation('org.powermock:powermock-core:2.0.9') + testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.8.2') + testRuntimeOnly('org.slf4j:slf4j-jdk14:1.8.0-beta4') + testRuntimeOnly("org.lwjgl:lwjgl::$lwjglNatives") + testRuntimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives") + testRuntimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives") + testRuntimeOnly("org.lwjgl:lwjgl-stb::$lwjglNatives") } -// See gradle/gradle#35070 (https://github.com/gradle/gradle/issues/35070) -// We are making the list of providers first BEFORE mapping them to a provider of the resolved objects so that they can be finalized after configuration. -var lwjglTestLibs = [ - dependencies.variantOf(earlyDisplayTestLibs.lwjgl) { classifier lwjglNatives }, - dependencies.variantOf(earlyDisplayTestLibs.lwjgl.glfw) { classifier lwjglNatives }, - dependencies.variantOf(earlyDisplayTestLibs.lwjgl.opengl) { classifier lwjglNatives }, - dependencies.variantOf(earlyDisplayTestLibs.lwjgl.stb) { classifier lwjglNatives } -].with { list -> - provider { list.collect { it.get() } } +tasks.named('test', Test).configure { + useJUnitPlatform() } -testing.suites.named('test', JvmTestSuite) { - useJUnitJupiter('5.8.2') - - dependencies { - implementation earlyDisplayTestLibs.powermock.core - runtimeOnly earlyDisplayLibs.slf4j.jdk14 - runtimeOnly.bundle lwjglTestLibs +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.earlydisplay', + 'Forge-Module-Layer': 'boot' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'FML Early Display', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'FML Early Display', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': '1.0' + ] as LinkedHashMap, 'net/minecraftforge/fml/earlydisplay/') } } @@ -76,42 +69,24 @@ tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.earlydisplay', - 'Forge-Module-Layer' : 'boot' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Vendor' : vendor, - 'Implementation-Version': '1.0' - ], 'net/minecraftforge/fml/earlydisplay/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'fmlearlydisplay' + pom { + name = project.name + description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.' + url = 'https://github.com/MinecraftForge/MinecraftForge' + PomUtils.setGitHubDetails(pom, 'MinecraftForge') + license PomUtils.Licenses.LGPLv2_1 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } -} \ No newline at end of file +} diff --git a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java index df45aadd56..5c6c8dc6c7 100644 --- a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java +++ b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java @@ -113,14 +113,6 @@ public class DisplayWindow implements ImmediateWindowProvider { return "fmlearlywindow"; } - @Override - public ImmediateWindowProvider selectBackend(String backend) { - // We only support opengl - if ("default".equals(backend) || "opengl".equals(backend)) - return this; - return ImmediateWindowProvider.getFallbackHandler(); - } - @Override public Runnable initialize(String[] arguments) { String mcVersion = FMLLoader.versionInfo().mcVersion(); @@ -145,7 +137,7 @@ public class DisplayWindow implements ImmediateWindowProvider { this.colourScheme = ColourScheme.BLACK; } else { try { - // check the options file for the color scheme + // check the options file for the colour scheme var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt"))); var keyName = "darkMojangStudiosBackground:"; for (String line : optionLines) { @@ -467,9 +459,7 @@ public class DisplayWindow implements ImmediateWindowProvider { this.winWidth = x[0]; this.winHeight = y[0]; - // Setting the window position isn't supported on wayland, so check the error here glfwSetWindowPos(window, (vidmode.width() - this.winWidth) / 2 + monitorX, (vidmode.height() - this.winHeight) / 2 + monitorY); - handleLastGLFWError(); // Attempt setting the icon // int[] channels = new int[1]; @@ -492,10 +482,7 @@ public class DisplayWindow implements ImmediateWindowProvider { // Show the window glfwShowWindow(window); - // Getting the window position isn't supported on wayland, so check the error here glfwGetWindowPos(window, x, y); - handleLastGLFWError(); - this.winX = x[0]; this.winY = y[0]; glfwGetFramebufferSize(window, x, y); @@ -504,18 +491,6 @@ public class DisplayWindow implements ImmediateWindowProvider { glfwPollEvents(); } - private static void handleLastGLFWError() { - handleLastGLFWError((error, description) -> { - if (error == GLFW_FEATURE_UNAVAILABLE) { - // suppress window pos errors for unsupported platforms (wayland) - LOGGER.debug(String.format("Suppressing GLFW error: [0x%X]%s", error, description)); - return; - } - - throw new IllegalStateException(String.format("GLFW error: [0x%X]%s", error, description)); - }); - } - private void winResize(long window, int width, int height) { if (window == this.window && width != 0 && height != 0) { this.winWidth = width; @@ -673,4 +648,4 @@ public class DisplayWindow implements ImmediateWindowProvider { this.context.elementShader().close(); SimpleBufferBuilder.destroy(); } -} +} \ No newline at end of file diff --git a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/RenderElement.java b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/RenderElement.java index e0cd43e72c..68895f3298 100644 --- a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/RenderElement.java +++ b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/RenderElement.java @@ -116,7 +116,7 @@ public class RenderElement { } public static RenderElement forgeVersionOverlay(SimpleFont font, String version) { - return new RenderElement(RenderElement.initializeText(font, (bb, _, ctx)-> + return new RenderElement(RenderElement.initializeText(font, (bb, fnt, ctx)-> font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10, ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb, new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha))))); @@ -178,11 +178,11 @@ public class RenderElement { var colour = (alpha << 24) | 0xFFFFFF; Renderer bar; if (pm.steps() == 0) { - bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _->colour, frame -> indeterminateBar(frame, cnt == 0)); + bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f->colour, frame -> indeterminateBar(frame, cnt == 0)); } else { - bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pm.progress()}); + bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pm.progress()}); } - Renderer label = (bb, ctx, _) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx); + Renderer label = (bb, ctx, frame) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx); return bar.then(label); } private static float[] indeterminateBar(int frame, boolean isActive) { @@ -198,9 +198,9 @@ public class RenderElement { var y = 10 * context.scale(); PerformanceInfo pi = context.performance(); final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f); - var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pi.memory()}); + var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pi.memory()}); var width = font.stringWidth(pi.text()); - Renderer label = (bb, ctx, _) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx); + Renderer label = (bb, ctx, frame) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx); bar.then(label).accept(buffer, context, frameNumber); } @@ -250,7 +250,7 @@ public class RenderElement { } private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) { - return (bb, context, _) -> renderText(font, textGenerator, bb, context); + return (bb, context, frame) -> renderText(font, textGenerator, bb, context); } private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) { @@ -262,7 +262,7 @@ public class RenderElement { } private static TextGenerator text(int x, int y, String text, int colour) { - return (bb, font, _) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour)); + return (bb, font, context) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour)); } private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) { diff --git a/fmlloader/build.gradle b/fmlloader/build.gradle index 21a9112b80..1ee709ae2a 100644 --- a/fmlloader/build.gradle +++ b/fmlloader/build.gradle @@ -1,75 +1,69 @@ -import groovy.transform.CompileDynamic -import groovy.transform.CompileStatic -import groovy.transform.PackageScope -import net.minecraftforge.forgedev.legacy.tasks.JarJarMetadataOptions -import org.gradle.api.plugins.jvm.JvmTestSuite - -import javax.inject.Inject +import net.minecraftforge.gradleutils.PomUtils plugins { id 'java-library' - id 'jvm-test-suite' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - alias libs.plugins.apt - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' + alias(libs.plugins.apt) } -gradleutils.displayName = 'FMLLoader' -final vendor = 'Forge Development LLC' -description = 'Modifications to Minecraft to enable mod developers.' +apply from: rootProject.file('build_shared.gradle') + +configurations.forEach{ it.transitive = false } + +dependencies { + compileOnly(libs.jetbrains.annotations) + + api(libs.bundles.asm) // Needed by all the black magic + api(libs.forgespi) + api(libs.mergetool.api) + api(libs.log4j.api) + api(libs.slf4j.api) + api(libs.guava) + api(libs.gson) + api(libs.maven.artifact) + api(libs.apache.commons) + api(libs.bundles.night.config) + api(libs.modlauncher) + api(libs.mojang.logging) + api(libs.jarjar.selector) + api(libs.jarjar.meta) + + implementation(libs.jopt.simple) + implementation(libs.securemodules) + implementation(libs.accesstransformers) + implementation(libs.terminalconsoleappender) + implementation(libs.jimfs) + implementation(libs.roimfs) + + // Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated + implementation(libs.log4j.core) + annotationProcessor(libs.bundles.log4j) + + testCompileOnly(libs.jetbrains.annotations) + testRuntimeOnly(libs.bootstrap) +} java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} - -changelog { - from changelogBase -} - -dependencies { - compileOnly libs.jetbrains.annotations - - // TODO [FMLLoader] Figure out a better way to lock transitive dependencies to the explicit versions shipped by the isntaller - api(libs.bundles.asm ){ transitive = false } // Needed by all the black magic - api(libs.forgespi ){ transitive = false } - api(libs.mergetool.api ){ transitive = false } - api(libs.log4j.api ){ transitive = false } - api(libs.slf4j.api ){ transitive = false } - api(libs.guava ){ transitive = false } - api(libs.gson ){ transitive = false } - api(libs.maven.artifact ){ transitive = false } - api(libs.apache.commons ){ transitive = false } - api(libs.bundles.night.config){ transitive = false } - api(libs.modlauncher ){ transitive = false } - api(libs.mojang.logging ){ transitive = false } - api(libs.jarjar.selector ){ transitive = false } - api(libs.jarjar.meta ){ transitive = false } - - implementation(libs.jopt.simple ){ transitive = false } - implementation(libs.securemodules ){ transitive = false } - implementation(libs.accesstransformers ){ transitive = false } - implementation(libs.terminalconsoleappender){ transitive = false } - implementation(libs.jimfs ){ transitive = false } - implementation(libs.roimfs ){ transitive = false } - - // Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated - implementation(libs.log4j.core ){ transitive = false } - annotationProcessor(libs.bundles.log4j){ transitive = false } -} - -testing.suites.named('test', JvmTestSuite) { - dependencies { - compileOnly libs.jetbrains.annotations - runtimeOnly libs.bootstrap +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.fmlloader', + 'Forge-Module-Layer': 'boot' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'FMLLoader', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'FMLLoader', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': FORGE_VERSION + ] as LinkedHashMap, 'net/minecraftforge/fml/loading/') } } @@ -77,81 +71,39 @@ tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.fmlloader', - 'Forge-Module-Layer' : 'boot' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Vendor' : vendor, - 'Implementation-Version': forgeVersion - ], 'net/minecraftforge/fml/loading/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'fmlloader' + pom { + 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 + } + } + repositories { maven gradleutils.publishingForgeMaven } +} - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } +tasks.register('writeForgeVersionJson') { + doLast { + file('src/main/resources/forge_version.json').json = [ + forge: FORGE_VERSION, + mc: MC_VERSION, + mcp: MCP_VERSION + ] } } -// A simple task to write JSON to a file. Using Task#doLast to output files is no longer supported. -// This code may seem verbose, but it's better this way. If more projects need this, we can move it to buildSrc. -@CompileStatic -@PackageScope abstract class WriteForgeVersionJson extends DefaultTask { - abstract @Input Property getForgeVersion() - abstract @Input Property getMinecraftVersion() - abstract @Input Property getMcpVersion() - - abstract @OutputFile RegularFileProperty getOutputFile() - - @Inject - WriteForgeVersionJson() {} - - @TaskAction - @CompileDynamic - void exec() { - var json = new groovy.json.JsonBuilder() - json { - forge this.forgeVersion.get() - mc this.minecraftVersion.get() - mcp this.mcpVersion.get() - } - this.outputFile.asFile.get().text = json.toPrettyString() - } -} - -tasks.register('writeForgeVersionJson', WriteForgeVersionJson) { - forgeVersion = project.forgeVersion - minecraftVersion = project.minecraftVersion - mcpVersion = project.mcpVersion - - outputFile = file('src/main/resources/forge_version.json') -} - -tasks.register('jarJarOptionsJson', JarJarMetadataOptions) { +tasks.register('jarJarOptionsJson', net.minecraftforge.forge.tasks.JarJarMetadataOptions) { metadataFile = project.file('src/main/resources/jarjar_options.json') // This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually... //add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class') @@ -166,25 +118,29 @@ tasks.register('jarJarOptionsJson', JarJarMetadataOptions) { } } -tasks.named('generateResources') { - dependsOn( - tasks.named('eclipseJdt'), - tasks.named('eclipseJdtApt'), - tasks.named('eclipseFactorypath'), - tasks.named('writeForgeVersionJson', WriteForgeVersionJson), - tasks.named('jarJarOptionsJson') - ) +tasks.named('generateResources').configure { + dependsOn('eclipseJdt') + dependsOn('eclipseJdtApt') + dependsOn('eclipseFactorypath') + dependsOn('writeForgeVersionJson') + dependsOn('jarJarOptionsJson') } -eclipse.classpath { - // We need to set the default output directory for the log4j annotation processor - // Ideally we'd just set the value, but the eclipse plugin deduplicates the output directories - // So we have to do a hacky whenMerged - //defaultOutputDir = file('bin/main') - file.whenMerged { - entries.each { entry -> - if (entry.kind == 'output' && entry.hasProperty('path')) - entry.path = 'bin/main' - } +tasks.named('sourcesJar') { + dependsOn('jarJarOptionsJson') +} + +eclipse { + classpath { + // We need to set the default output directory for the log4j annotation processor + // Ideally we'd just set the value, but the eclipse plugin deduplicates the output directories + // So we have to do a hacky whenMerged + //defaultOutputDir = file('bin/main') + file.whenMerged { + entries.each { entry -> + if (entry.kind == 'output' && entry.hasProperty('path')) + entry.path = 'bin/main' + } + } } } diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLConfig.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLConfig.java index 414dee68e3..1530f6b575 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLConfig.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLConfig.java @@ -109,7 +109,7 @@ public class FMLConfig } if (!configSpec.isCorrect(configData)) { LOGGER.warn(CORE, "Configuration file {} is not correct. Correcting", configFile); - configSpec.correct(configData, (_, path, incorrectValue, correctedValue) -> + configSpec.correct(configData, (action, path, incorrectValue, correctedValue) -> LOGGER.info(CORE, "Incorrect key {} was corrected from {} to {}", path, incorrectValue, correctedValue)); } configData.putAllComments(configComments); diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java index 327279e890..4f72460375 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java @@ -20,8 +20,8 @@ public class FMLEnvironment public static final boolean secureJarsEnabled = FMLLoader.isSecureJarEnabled(); static void setupInteropEnvironment(IEnvironment environment) { - environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), _->naming); - environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), _->dist); + environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), v->naming); + environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), v->dist); } public static class Keys { diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLServiceProvider.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLServiceProvider.java index fd74cf0698..f5b2258d1f 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLServiceProvider.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLServiceProvider.java @@ -12,6 +12,7 @@ import net.minecraftforge.forgespi.Environment; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -41,7 +42,7 @@ public class FMLServiceProvider implements ITransformationService { LOGGER.debug(CORE, "Loading configuration"); FMLConfig.load(); LOGGER.debug(CORE, "Preparing ModFile"); - environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), _->ModFile::new); + environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), k->ModFile::new); LOGGER.debug(CORE, "Preparing launch handler"); FMLLoader.setupLaunchHandler(environment, arguments); FMLEnvironment.setupInteropEnvironment(environment); diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowHandler.java index c704a3fd7d..d6a8bff4e1 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowHandler.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowHandler.java @@ -10,13 +10,8 @@ import net.minecraftforge.fml.loading.progress.StartupNotificationManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import joptsimple.OptionParser; - -import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.*; import java.util.function.*; import java.util.stream.Collectors; @@ -46,62 +41,16 @@ public class ImmediateWindowHandler { if (provider == null) { LOGGER.info("Failed to find ImmediateWindowProvider {}, disabling", providername); provider = new DummyProvider(); - } else { - var backend = findBackend(arguments); - var newProvider = provider.selectBackend(backend); - if (provider != newProvider) { - if (newProvider == null) - newProvider = new DummyProvider(); - - LOGGER.info("ImmediateWindowProvider {} does not support {}, switching to {}", provider.name(), backend, newProvider.name()); - provider = newProvider; - } } } - // Only update config if the provider isn't the dummy provider if (!Objects.equals(provider.name(), "dummyprovider")) FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER, provider.name()); - FMLLoader.progressWindowTick = provider.initialize(arguments); earlyProgress = StartupNotificationManager.addProgressBar("EARLY", 0); earlyProgress.label("Bootstrapping Minecraft"); } - private static String findBackend(String[] arguments) { - // Try and parse from the command line arguments - var parser = new OptionParser(); - var backendOption = parser.accepts("graphicsBackend").withRequiredArg(); - parser.allowsUnrecognizedOptions(); - var parsed = parser.parse(arguments); - - if (parsed.has(backendOption)) - return parsed.valueOf(backendOption).toLowerCase(Locale.ENGLISH); - - - // Read the options.txt if it exists. - var optionsFile = FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt")); - if (!Files.exists(optionsFile)) // Default is OpenGL first - return "default"; - - List lines = null; - try { - lines = Files.readAllLines(optionsFile); - } catch (IOException e) { - return "default"; // We failed to read for some reason, assume we're using the default. - } - - final String key = "preferredGraphicsBackend:"; - for (var line : lines) { - if (line.startsWith(key)) { - var backend = line.substring(key.length() + 1, line.length() - 1); - return backend.toLowerCase(Locale.ENGLISH); - } - } - - return "default"; - } - public static long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier backend) { return provider.setupMinecraftWindow(width, height, title, monitor, backend); } @@ -134,7 +83,7 @@ public class ImmediateWindowHandler { earlyProgress.label(message); } - record DummyProvider() implements ImmediateWindowProvider { + private record DummyProvider() implements ImmediateWindowProvider { private static Method NV_HANDOFF; private static Method NV_POSITION; private static Method NV_OVERLAY; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowProvider.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowProvider.java index d15c3629da..59a9c744e9 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowProvider.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/ImmediateWindowProvider.java @@ -24,36 +24,11 @@ import java.util.function.Supplier; * No doubt many more things can be said here. */ public interface ImmediateWindowProvider { - /** - * Returns a new instance of ImmediateWindowProvider which just bounces to the vanilla code. - * This can be useful when you want to disable your provider and defer to vanilla behavior for some reason. - */ - public static ImmediateWindowProvider getFallbackHandler() { - return new ImmediateWindowHandler.DummyProvider(); - } - /** * @return The name of this window provider. Do NOT use fmlearlywindow. */ String name(); - /** - * This is called before initialize, but after reading the preferred graphics backend config value from the user's - * options.txt or command line. - * - * If you do not support the requested backend, you can return a new ImmediateWindowProvider that does. - * {@link #getFallbackHandler()} can be used to get an instance that falls back to Vanilla's code effectively - * disabling the early loading screen. - * - * @param backend - The backend the user has selected, known values: "default", "opengl", and "vulkan". However this - * is read from the config file, or command line arguments so could be anything. - * Default and OpenGL are treated the same, attempting to load OpenGL first, then Vulkan. - * Vulkan attempts to load Vulkan first then OpenGL - */ - default ImmediateWindowProvider selectBackend(String backend) { - return this; - } - /** * This is called very early on to initialize ourselves. Use this to initialize the window and other GL core resources. * 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 201aca6de4..ca908d0470 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/MCPNamingService.java @@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading; import com.mojang.logging.LogUtils; import cpw.mods.modlauncher.api.INameMappingService; +import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import java.io.BufferedReader; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/MavenCoordinateResolver.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/MavenCoordinateResolver.java index d0d90d22cb..fe3e595b06 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/MavenCoordinateResolver.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/MavenCoordinateResolver.java @@ -6,6 +6,7 @@ package net.minecraftforge.fml.loading; import java.nio.file.Path; +import java.nio.file.Paths; /** * Convert a maven coordinate into a Path. diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/StringUtils.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/StringUtils.java index bf40fc6492..195719ee5b 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/StringUtils.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/StringUtils.java @@ -26,7 +26,6 @@ public class StringUtils { return java.util.stream.Stream.of(endings).anyMatch(lowerSearch::endsWith); } - @SuppressWarnings("deprecation") public static URL toURL(final String string) { if (string == null || string.trim().isEmpty() || string.contains("myurl.me") || string.contains("example.invalid")) return null; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/VersionSupportMatrix.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/VersionSupportMatrix.java index da25929206..3435993791 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/VersionSupportMatrix.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/VersionSupportMatrix.java @@ -13,6 +13,7 @@ import org.jetbrains.annotations.ApiStatus; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.function.BiPredicate; @ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version public class VersionSupportMatrix { diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/BackgroundScanHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/BackgroundScanHandler.java index faed16a26c..b795a82033 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/BackgroundScanHandler.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/BackgroundScanHandler.java @@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading.moddiscovery; import com.mojang.logging.LogUtils; import net.minecraftforge.fml.loading.ImmediateWindowHandler; +import net.minecraftforge.fml.loading.LoadingModList; import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.forgespi.language.ModFileScanData; import org.slf4j.Logger; @@ -55,7 +56,7 @@ public final class BackgroundScanHandler { ImmediateWindowHandler.updateProgress("Scanning mod candidates"); CompletableFuture future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner) .whenComplete(file::setScanResult); - if (DEBUG) future = future.whenComplete((_, t) -> addCompletedFile(file, t)); + if (DEBUG) future = future.whenComplete((r, t) -> addCompletedFile(file, t)); file.setFutureScanResult(future); } diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/InvalidModIdentifier.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/InvalidModIdentifier.java index 7e84195398..8d6cd490da 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/InvalidModIdentifier.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/InvalidModIdentifier.java @@ -24,7 +24,7 @@ public enum InvalidModIdentifier { LITELOADER(filePresent("litemod.json")), OPTIFINE(filePresent("optifine/Installer.class")), BUKKIT(filePresent("plugin.yml")), - INVALIDZIP((_,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed + INVALIDZIP((f,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed private final BiPredicate> ident; @@ -51,7 +51,7 @@ public enum InvalidModIdentifier { private static BiPredicate> filePresent(String filename) { - return (_, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false); + return (f, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false); } private static Optional optionalFromException(Supplier_WithExceptions supp) diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/JarInJarDependencyLocator.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/JarInJarDependencyLocator.java index 38e5b0c083..c2e497621e 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/JarInJarDependencyLocator.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/JarInJarDependencyLocator.java @@ -145,7 +145,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID var ids = new TreeMap>(); for (var entry : selector.entries.values()) { if (entry != FAILED && entry.coord != null) - ids.computeIfAbsent(entry.coord, _ -> new ArrayList<>()).add(entry); + ids.computeIfAbsent(entry.coord, id -> new ArrayList<>()).add(entry); } for (var entry : ids.entrySet()) { diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/MinecraftLocator.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/MinecraftLocator.java index b2ffbfd22c..5a3aeccbdd 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/MinecraftLocator.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/MinecraftLocator.java @@ -27,7 +27,7 @@ public final class MinecraftLocator extends AbstractModProvider implements IModL // Minecraft itself. var meta = new ModJarMetadata(); - var mcjar = SecureJar.from(_ -> meta, paths); + var mcjar = SecureJar.from(jar -> meta, paths); var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML); meta.setModFile(mc); diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java index 5008e0d80b..e9a8cfc597 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java @@ -8,6 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery; import com.google.common.collect.ImmutableMap; import com.mojang.logging.LogUtils; import cpw.mods.jarhandling.SecureJar; +import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.LanguageLoadingProvider; import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.forgespi.language.IModFileInfo; @@ -25,6 +26,7 @@ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFileParser.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFileParser.java index 4074429850..9c25c42985 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFileParser.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFileParser.java @@ -6,13 +6,11 @@ package net.minecraftforge.fml.loading.moddiscovery; import com.electronwill.nightconfig.core.file.FileConfig; -import com.electronwill.nightconfig.core.io.ParsingException; import com.mojang.logging.LogUtils; import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.ModFileFactory; -import net.minecraftforge.forgespi.locating.ModFileLoadingException; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -26,7 +24,6 @@ public class ModFileParser { return parser.build(modFile); } - // Note: Although @Nullable, several other places in FML assume ModFileInfo is not null. Keep this in mind public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) { ModFile modFile = (ModFile) imodFile; LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath()); @@ -35,19 +32,11 @@ public class ModFileParser { LOGGER.warn(LogMarkers.LOADING, "Mod file {} is missing mods.toml file", modFile.getFilePath()); return null; } - try { - final FileConfig fileConfig = FileConfig.builder(modsjson).build(); - fileConfig.load(); - fileConfig.close(); - final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig); - return new ModFileInfo(modFile, configWrapper, configWrapper::setFile); - } catch (ParsingException e) { // Handle landmine toml errors, e.g. incorrectly ported mods. - LOGGER.error("Mod candidate {} contains a corrupt or misconfigured toml.", modFile.getFileName()); - throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains a corrupt or misconfigured toml."); - } catch (Exception other) { // Otherwise this is just someone who (probably) forgot a comma or something. - LOGGER.error("Mod candidate {}'s toml .", modFile.getFileName()); - throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains broken toml, likely due to a typo."); - } + final FileConfig fileConfig = FileConfig.builder(modsjson).build(); + fileConfig.load(); + fileConfig.close(); + final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig); + return new ModFileInfo(modFile, configWrapper, configWrapper::setFile); } } diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/progress/StartupNotificationManager.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/progress/StartupNotificationManager.java index 6bd30c47db..2e714d5ed1 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/progress/StartupNotificationManager.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/progress/StartupNotificationManager.java @@ -56,7 +56,7 @@ public class StartupNotificationManager { private synchronized static void addMessage(Message.MessageType type, String message, int maxSize) { EnumMap> newMessages = new EnumMap<>(messages); - newMessages.compute(type, (_, existingList) -> { + newMessages.compute(type, (key, existingList) -> { List newList = new ArrayList<>(); if (existingList != null) { diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/CommonDevLaunchHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/CommonDevLaunchHandler.java index b9dc6ef946..570b6a680f 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/CommonDevLaunchHandler.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/CommonDevLaunchHandler.java @@ -141,7 +141,7 @@ abstract class CommonDevLaunchHandler extends CommonLaunchHandler { protected static Path getForgeOnly(Path forge) { var packages = getPackages(); // Pulled out so it is passed to the lambda as value // We need to separate out our resources/code so that we can show up as a different data pack. - var modJar = SecureJar.from((path, _) -> { + var modJar = SecureJar.from((path, base) -> { if (!path.endsWith(".class")) return true; for (var pkg : packages) if (path.startsWith(pkg)) return true; diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeDevLocator.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeDevLocator.java index 7b9d067940..1ab63857e5 100644 --- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeDevLocator.java +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeDevLocator.java @@ -112,7 +112,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo // We want just the class files from the root of the input paths. So make a new union with a filter. var classes = UnionHelper.newFileSystem( - (name, _) -> { + (name, base) -> { if (name.endsWith("/")) { if (name.startsWith("/")) name = name.substring(1); @@ -164,7 +164,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo if ("value".equals(key)) { int idx = clsName.lastIndexOf('/'); var pkg = clsName.substring(0, idx); - mods.computeIfAbsent(pkg, _ -> new HashSet<>()).add((String)value); + mods.computeIfAbsent(pkg, k -> new HashSet<>()).add((String)value); idx = pkg.lastIndexOf('/'); while (idx != -1) { 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 ee622db88a..1488be3a7a 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 @@ -25,9 +25,7 @@ sealed abstract class ForgeProdLaunchHandler extends CommonLaunchHandler { @Override public List getMinecraftPaths() { - // We use a marker because 3rd party launcher don't build their class paths correctly - // https://github.com/MinecraftForge/MinecraftForge/issues/10797 - return List.of(getPathFromResource(".forge_patched_minecraft")); + return List.of(getPathFromResource("net/minecraft/client/Minecraft.class")); } } diff --git a/fmlloader/src/main/resources/jarjar_options.json b/fmlloader/src/main/resources/jarjar_options.json index 79a05c8ff7..40fe849a55 100644 --- a/fmlloader/src/main/resources/jarjar_options.json +++ b/fmlloader/src/main/resources/jarjar_options.json @@ -11,8 +11,8 @@ "artifact": "MixinExtras" }, "version": { - "range": "[0.5.4,)", - "artifactVersion": "0.5.4" + "range": "[0.5.3,)", + "artifactVersion": "0.5.3" }, "path": "", "isObfuscated": false @@ -24,7 +24,7 @@ "artifact": "mixinextras-forge" }, "version": { - "artifactVersion": "0.5.4" + "artifactVersion": "0.5.3" }, "path": "", "isObfuscated": false diff --git a/forge-transformers/build.gradle b/forge-transformers/build.gradle index 145d9ed3e9..105a289c88 100644 --- a/forge-transformers/build.gradle +++ b/forge-transformers/build.gradle @@ -1,78 +1,73 @@ +import net.minecraftforge.gradleutils.PomUtils + plugins { id 'java-library' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' + alias(libs.plugins.apt) } -gradleutils.displayName = 'Forge Transformers' -final vendor = 'Forge Development LLC' -description = 'Forge-specific transformers unrelated to the FML project.' +apply from: rootProject.file('build_shared.gradle') + +configurations.forEach{ it.transitive = false } + +dependencies { + compileOnly(libs.jetbrains.annotations) + + implementation(libs.bundles.asm) // Needed by all the black magic + implementation(libs.log4j.api) + implementation(libs.gson) + implementation(libs.modlauncher) + implementation(libs.coremods.api) + + testCompileOnly(libs.jetbrains.annotations) +} java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } +tasks.named('jar', Jar) { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.forge.transformers', + 'Forge-Module-Layer': 'boot' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'Forge Transformers', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'Forge Transformers', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': FORGE_VERSION + ] as LinkedHashMap, 'net/minecraftforge/forge/transformers/') + } +} + +tasks.withType(JavaCompile).configureEach { + options.compilerArgs << '-Xlint:unchecked' +} + license { header = rootProject.file('LICENSE-header.txt') } -changelog { - from changelogBase -} - -dependencies { - compileOnly(libs.jetbrains.annotations) - - implementation(libs.bundles.asm ){ transitive = false } // Needed by all the black magic - implementation(libs.log4j.api ){ transitive = false } - implementation(libs.gson ){ transitive = false } - implementation(libs.modlauncher ){ transitive = false } - implementation(libs.coremods.api){ transitive = false } - - testCompileOnly(libs.jetbrains.annotations) -} - -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.forge.transformers', - 'Forge-Module-Layer' : 'boot' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Vendor' : vendor, - 'Implementation-Version': forgeVersion - ], 'net/minecraftforge/forge/transformers/') - } -} - publishing { + publications.register('mavenJava', MavenPublication) { + from components.java + artifactId = 'forge-transformers' + pom { + name = project.name + description = 'Forge-specific transformers unrelated to the FML project.' + url = 'https://github.com/MinecraftForge/MinecraftForge' + PomUtils.setGitHubDetails(pom, 'MinecraftForge') + license PomUtils.Licenses.LGPLv2_1 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { pom -> - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } } diff --git a/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/FieldToMethodTransformer.java b/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/FieldToMethodTransformer.java index 113dac1e5c..5f5df8e829 100644 --- a/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/FieldToMethodTransformer.java +++ b/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/FieldToMethodTransformer.java @@ -126,7 +126,7 @@ record FieldToMethodTransformer(String className, Map fields) im throw new IllegalStateException("No field with name " + fieldName + " found"); if (!Modifier.isPrivate(foundField.access) || Modifier.isStatic(foundField.access)) - throw new IllegalStateException("Field " + classNode.name + '.' + fieldName + " is not private and an instance field"); + throw new IllegalStateException("Field " + fieldName + " is not private and an instance field"); var methodSignature = "()" + foundField.desc; var foundMethod = findMethod(classNode, methodName, methodSignature); diff --git a/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/MethodRedirector.java b/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/MethodRedirector.java index c87b3f9dbb..dfa92c5f46 100644 --- a/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/MethodRedirector.java +++ b/forge-transformers/src/main/java/net/minecraftforge/forge/transformers/MethodRedirector.java @@ -41,7 +41,7 @@ record MethodRedirector() implements ITransformer { "finalizeSpawn", "(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;", GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class), - _ -> new MethodInsnNode( + insn -> new MethodInsnNode( Opcodes.INVOKESTATIC, "net/minecraftforge/event/ForgeEventFactory", "onFinalizeSpawn", diff --git a/forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json b/forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json index 555238cf0c..8355662f9a 100644 --- a/forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json +++ b/forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json @@ -1,8 +1,8 @@ [ { - "class": "net/minecraft/gametest/framework/GameTestEntityBuilder", + "class": "net/minecraft/gametest/framework/GameTestHelper", "methods": [ - "spawn()Lnet/minecraft/world/entity/Entity;" + "spawn(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/entity/EntitySpawnReason;)Lnet/minecraft/world/entity/Entity;" ] }, { @@ -20,7 +20,7 @@ { "class": "net/minecraft/world/entity/EntityType", "methods": [ - "create(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/PostSpawnProcessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;" + "create(Lnet/minecraft/server/level/ServerLevel;Ljava/util/function/Consumer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;" ] }, { @@ -42,6 +42,12 @@ "finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;" ] }, + { + "class": "net/minecraft/world/entity/animal/frog/Tadpole", + "methods": [ + + ] + }, { "class": "net/minecraft/world/entity/monster/Strider", "methods": [ @@ -79,12 +85,24 @@ "finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;" ] }, + { + "class": "net/minecraft/world/entity/monster/zombie/ZombieVillager", + "methods": [ + + ] + }, { "class": "net/minecraft/world/entity/npc/CatSpawner", "methods": [ "spawnCat(Lnet/minecraft/core/BlockPos;Lnet/minecraft/server/level/ServerLevel;Z)V" ] }, + { + "class": "net/minecraft/world/entity/npc/villager/Villager", + "methods": [ + + ] + }, { "class": "net/minecraft/world/entity/raid/Raid", "methods": [ @@ -140,5 +158,11 @@ "methods": [ "handleDataMarker(Ljava/lang/String;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/structure/BoundingBox;)V" ] + }, + { + "class": "net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate", + "methods": [ + + ] } ] \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 636e21bfab..7ef188b37a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,29 +1,17 @@ -# TODO Re-evaluate # Sets default memory used for gradle commands. Can be overridden by user or command line properties. # This is required to provide enough memory for the Minecraft decompilation process. org.gradle.jvmargs=-Xmx6G - -org.gradle.warning.mode=all -org.gradle.caching=true +org.gradle.daemon=false org.gradle.parallel=true -org.gradle.configureondemand=true -# TODO [ForgeDev] Enable this once ForgeDev 7 tasks are fully migrated -org.gradle.configuration-cache=false -org.gradle.configuration-cache.parallel=false -#org.gradle.configuration-cache.problems=warn -#org.gradle.configuration-cache.integrity-check=true +JAVA_VERSION=25 +MC_VERSION=26.1 +MC_NEXT_VERSION=26.2 +MCP_VERSION=20260324.123823 +MAPPING_CHANNEL=official +MAPPING_VERSION=26.1 -net.minecraftforge.gradleutils.ide.automatic.sources=true -net.minecraftforge.gradleutils.compilation.defaults=true - -net.minecraftforge.gradle.merge-source-sets=true - -# Controls if the compatibility checks are auto-added to the 'check' task. -# The check tasks are still created and can be run, they just are not grouped with the normal 'check' task. -# Set to false for the first builds of a new Minecraft version. -net.minecraftforge.forge.build.check.compatibility=false -# Set to true to allow for fuzzy patching. Useful during updating. -net.minecraftforge.forge.build.updating=false -# Set to true to enable the 'validatePublish' task which is currently a work in progress -net.minecraftforge.forgedev.validate.publish=false +# 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 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 61285a659d..e6441136f3 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1a704683a0..e18bc253b8 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-9.5.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index adff685a03..1aa94a4269 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015 the original authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,8 +15,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # -# SPDX-License-Identifier: Apache-2.0 -# ############################################################################## # @@ -57,7 +55,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -86,7 +84,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,6 +112,7 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -171,6 +170,7 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -203,14 +203,15 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index c4bdd3ab8e..25da30dbde 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,6 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -70,10 +68,11 @@ goto fail :execute @rem Setup the command line +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/javafmllanguage/build.gradle b/javafmllanguage/build.gradle index 8f0b9b76c9..e81fd2b59f 100644 --- a/javafmllanguage/build.gradle +++ b/javafmllanguage/build.gradle @@ -1,79 +1,66 @@ +import net.minecraftforge.gradleutils.PomUtils + plugins { id 'java-library' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' } -gradleutils.displayName = 'JavaFMLMod' -final vendor = 'Forge Development LLC' -description = 'Language provider for Minecraft Forge that provides basic Java mod functionality.' +apply from: rootProject.file('build_shared.gradle') + +dependencies { + compileOnly(libs.jetbrains.annotations) + implementation(project(':fmlloader')) + implementation(project(':fmlcore')) + implementation(libs.unsafe) + implementation(libs.securemodules) +} java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} - -changelog { - from changelogBase -} - -dependencies { - compileOnly libs.jetbrains.annotations - - implementation projects.fmlloader - implementation projects.fmlcore - implementation libs.unsafe - implementation libs.securemodules +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.javafmlmod', + 'FMLModType': 'LANGPROVIDER' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'JavaFMLMod', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'JavaFMLMod', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': FORGE_VERSION + ] as LinkedHashMap, 'net/minecraftforge/fml/javafmlmod/') + } } tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.javafmlmod', - 'FMLModType' : 'LANGPROVIDER' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Vendor' : vendor, - 'Implementation-Version': forgeVersion - ], 'net/minecraftforge/fml/javafmlmod/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'javafmllanguage' + pom { + name = project.name + description = 'Language provider for Minecraft Forge that provides basic java mod functionality' + url = 'https://github.com/MinecraftForge/MinecraftForge' + PomUtils.setGitHubDetails(pom, 'MinecraftForge') + license PomUtils.Licenses.LGPLv2_1 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } -} \ No newline at end of file +} diff --git a/javafmllanguage/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java b/javafmllanguage/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java index 6bc2b2e139..49bbeb9d46 100644 --- a/javafmllanguage/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java +++ b/javafmllanguage/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java @@ -81,7 +81,7 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider .filter(ad -> ad.annotationType().equals(MODANNOTATION)) .peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.clazz().getClassName(), ad.annotationData().get("value"))) .map(ad -> new FMLModTarget(ad.clazz().getClassName(), (String)ad.annotationData().get("value"))) - .collect(Collectors.toMap(FMLModTarget::modId, Function.identity(), (a, _) -> a)); + .collect(Collectors.toMap(FMLModTarget::modId, Function.identity(), (a,b)->a)); scanResult.addLanguageLoader(modTargetMap); }; } diff --git a/lowcodelanguage/build.gradle b/lowcodelanguage/build.gradle index 5681135f79..f4e92d6233 100644 --- a/lowcodelanguage/build.gradle +++ b/lowcodelanguage/build.gradle @@ -1,77 +1,65 @@ +import net.minecraftforge.gradleutils.PomUtils + plugins { id 'java-library' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' } -gradleutils.displayName = 'LowCodeMod' -final vendor = 'Forge Development LLC' -description = 'Language provider for Minecraft Forge that loads mods without a Java entrypoint.' +apply from: rootProject.file('build_shared.gradle') java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} - -changelog { - from changelogBase -} - dependencies { - compileOnly libs.jetbrains.annotations + compileOnly(libs.jetbrains.annotations) - implementation projects.fmlloader - implementation projects.fmlcore + implementation(project(':fmlloader')) + implementation(project(':fmlcore')) +} + +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.lowcodemod', + 'FMLModType': 'LANGPROVIDER' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'LowCodeMod', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1.0', + 'Implementation-Title': project.name, + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': FORGE_VERSION.split('\\.')[0] + ] as java.util.LinkedHashMap, 'net/minecraftforge/fml/lowcodemod/') + } } tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.lowcodemod', - 'FMLModType' : 'LANGPROVIDER' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1.0', - 'Implementation-Title' : project.name, - 'Implementation-Vendor' : vendor, - 'Implementation-Version': forgeVersion.split('\\.')[0] - ], 'net/minecraftforge/fml/lowcodemod/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'lowcodelanguage' + pom { + name = project.name + description = 'Language provider for Minecraft Forge that loads resource packs as mods' + url = 'https://github.com/MinecraftForge/MinecraftForge' + PomUtils.setGitHubDetails(pom, 'MinecraftForge') + license PomUtils.Licenses.LGPLv2_1 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } } diff --git a/lowcodelanguage/src/main/java/net/minecraftforge/fml/lowcodemod/LowCodeModLanguageProvider.java b/lowcodelanguage/src/main/java/net/minecraftforge/fml/lowcodemod/LowCodeModLanguageProvider.java index f39666fd40..0f5dcb950f 100644 --- a/lowcodelanguage/src/main/java/net/minecraftforge/fml/lowcodemod/LowCodeModLanguageProvider.java +++ b/lowcodelanguage/src/main/java/net/minecraftforge/fml/lowcodemod/LowCodeModLanguageProvider.java @@ -74,7 +74,7 @@ public class LowCodeModLanguageProvider implements IModLanguageProvider .flatMap(fi->fi.getMods().stream()) .map(IModInfo::getModId) .map(LowCodeModTarget::new) - .collect(Collectors.toMap(LowCodeModTarget::modId, Function.identity(), (a, _)->a)); + .collect(Collectors.toMap(LowCodeModTarget::modId, Function.identity(), (a, b)->a)); scanResult.addLanguageLoader(modTargetMap); }; } diff --git a/mclanguage/build.gradle b/mclanguage/build.gradle index 7e4ed70a54..abf4e79ed2 100644 --- a/mclanguage/build.gradle +++ b/mclanguage/build.gradle @@ -1,77 +1,64 @@ +import net.minecraftforge.gradleutils.PomUtils + plugins { id 'java-library' id 'maven-publish' - alias libs.plugins.licenser - alias libs.plugins.gradleutils - alias libs.plugins.gitversion - alias libs.plugins.changelog - id 'net.minecraftforge.forge.build.convention' + id 'net.minecraftforge.licenser' + id 'net.minecraftforge.gradleutils' } -gradleutils.displayName = 'MCLanguage' -final vendor = 'Forge Development LLC' -description = 'Language provider for Minecraft Forge that provides Minecraft Itself.' +apply from: rootProject.file('build_shared.gradle') + +dependencies { + compileOnly(libs.jetbrains.annotations) + implementation(project(':fmlloader')) + implementation(project(':fmlcore')) +} java { - toolchain.languageVersion = JavaLanguageVersion.of(javaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION) withSourcesJar() } -license { - header = rootProject.file('LICENSE-header.txt') -} - -changelog { - from changelogBase -} - -dependencies { - compileOnly libs.jetbrains.annotations - - implementation projects.fmlloader - implementation projects.fmlcore +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Automatic-Module-Name': 'net.minecraftforge.mclanguageprovider', + 'FMLModType': 'LANGPROVIDER' + ] as LinkedHashMap) + attributes([ + 'Specification-Title': 'MCLanguage', + 'Specification-Vendor': 'Forge Development LLC', + 'Specification-Version': '1', + 'Implementation-Title': 'MCLanguage', + 'Implementation-Vendor': 'Forge Development LLC', + 'Implementation-Version': '1.0' + ] as LinkedHashMap, 'net/minecraftforge/fml/mclanguageprovider/') + } } tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xlint:unchecked' } -tasks.named('jar', Jar) { - manifest { - attributes([ - 'Automatic-Module-Name': 'net.minecraftforge.mclanguageprovider', - 'FMLModType' : 'LANGPROVIDER' - ]) - attributes([ - 'Specification-Title' : gradleutils.displayName.get(), - 'Specification-Vendor' : vendor, - 'Specification-Version' : '1', - 'Implementation-Title' : gradleutils.displayName.get(), - 'Implementation-Vendor' : vendor, - 'Implementation-Version': '1.0' - ], 'net/minecraftforge/fml/mclanguageprovider/') - } +license { + header = rootProject.file('LICENSE-header.txt') } publishing { + publications.register('mavenJava', MavenPublication).configure { + from components.java + artifactId = 'mclanguage' + pom { + name = project.name + description = 'Language provider for Minecraft Forge that provides Minecraft Itself' + url = 'https://github.com/MinecraftForge/MinecraftForge' + PomUtils.setGitHubDetails(pom, 'MinecraftForge') + license PomUtils.Licenses.LGPLv2_1 + } + } + repositories { maven gradleutils.publishingForgeMaven } - - publications.register('mavenJava', MavenPublication) { - changelog.publish(it) - gradleutils.promote(it) - - from components.java - - pom { - description = project.description - - gradleutils.pom.addRemoteDetails(pom) - - licenses { - license gradleutils.pom.licenses.LGPLv2_1 - } - } - } } diff --git a/mdk/build.gradle b/mdk/build.gradle index c13dfe3355..6864f526bc 100644 --- a/mdk/build.gradle +++ b/mdk/build.gradle @@ -6,7 +6,7 @@ plugins { id 'java' id 'idea' id 'eclipse' - id 'net.minecraftforge.gradle' version '[7.0.17,8)' + id 'net.minecraftforge.gradle' version '[7.0.3,8)' } version = '1.0.0' @@ -19,6 +19,8 @@ java.toolchain.languageVersion = JavaLanguageVersion.of(25) sourceSets.main.resources { srcDir 'src/generated/resources' } minecraft { + mappings channel: 'official', version: '@MC_VERSION@' + runs { configureEach { workingDir = layout.projectDirectory.dir('run') diff --git a/minecraft.versions.toml b/minecraft.versions.toml deleted file mode 100644 index a2a4d47b43..0000000000 --- a/minecraft.versions.toml +++ /dev/null @@ -1,6 +0,0 @@ -[versions] -java = "25" -minecraft = "26.2" -minecraft-next = "26.3" -mcp = "20260616.103818" -changelog-base = "65.0" diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlCommandEncoder.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlCommandEncoder.java.patch index 8ef6350531..2c728bacba 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlCommandEncoder.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlCommandEncoder.java.patch @@ -1,6 +1,6 @@ --- a/com/mojang/blaze3d/opengl/GlCommandEncoder.java +++ b/com/mojang/blaze3d/opengl/GlCommandEncoder.java -@@ -201,6 +_,9 @@ +@@ -111,6 +_,9 @@ GlStateManager._colorMask(15); GlStateManager._clear(16384); GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, 0, 0); diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlConst.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlConst.java.patch index 19c0803e0c..e025fc1df7 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlConst.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlConst.java.patch @@ -1,35 +1,35 @@ --- a/com/mojang/blaze3d/opengl/GlConst.java +++ b/com/mojang/blaze3d/opengl/GlConst.java -@@ -239,6 +_,10 @@ +@@ -249,6 +_,10 @@ } - public static int toGlInternalId(final GpuFormat gpuFormat) { -+ return toGlInternalId(gpuFormat, false); + public static int toGlInternalId(final TextureFormat textureFormat) { ++ return toGlInternalId(textureFormat, false); + } -+ public static int toGlInternalId(final GpuFormat gpuFormat, final boolean stencil) { -+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8; - return switch (gpuFormat) { - case R8_UNORM -> 33321; - case R8_SNORM -> 36756; -@@ -291,6 +_,10 @@ ++ public static int toGlInternalId(final TextureFormat textureFormat, final boolean stencil) { ++ if (stencil && textureFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8; + return switch (textureFormat) { + case RGBA8 -> 32856; + case RED8 -> 33321; +@@ -258,6 +_,10 @@ } - public static int toGlExternalId(final GpuFormat gpuFormat) { -+ return toGlExternalId(gpuFormat, false); + public static int toGlExternalId(final TextureFormat textureFormat) { ++ return toGlExternalId(textureFormat, false); + } -+ public static int toGlExternalId(final GpuFormat gpuFormat, final boolean stencil) { -+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL; - return switch (gpuFormat) { - case R8_UNORM, R8_SNORM, R16_UNORM, R16_SNORM, R16_FLOAT, R32_FLOAT -> 6403; - case RG8_UNORM, RG8_SNORM, RG16_UNORM, RG16_SNORM, RG16_FLOAT, RG32_FLOAT -> 33319; -@@ -308,6 +_,10 @@ ++ public static int toGlExternalId(final TextureFormat textureFormat, final boolean stencil) { ++ if (stencil && textureFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL; + return switch (textureFormat) { + case RGBA8 -> 6408; + case RED8 -> 6403; +@@ -267,6 +_,10 @@ } - public static int toGlType(final GpuFormat gpuFormat) { -+ return toGlType(gpuFormat, false); + public static int toGlType(final TextureFormat textureFormat) { ++ return toGlType(textureFormat, false); + } -+ public static int toGlType(final GpuFormat gpuFormat, boolean stencil) { -+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV; - return switch (gpuFormat) { - case R8_UNORM, RG8_UNORM, RGB8_UNORM, RGBA8_UNORM, R8_UINT, RG8_UINT, RGBA8_UINT, S8_UINT, RGB8_UINT -> 5121; - case R8_SNORM, RG8_SNORM, RGB8_SNORM, RGBA8_SNORM, R8_SINT, RG8_SINT, RGBA8_SINT, RGB8_SINT -> 5120; ++ public static int toGlType(final TextureFormat textureFormat, boolean stencil) { ++ if (stencil && textureFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV; + return switch (textureFormat) { + case RGBA8 -> 5121; + case RED8 -> 5121; diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch index 5f5f2a7781..a284b9ecd6 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch @@ -15,30 +15,30 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final int CIRCULAR_LOG_SIZE = 10; private final Queue MESSAGE_BUFFER = EvictingQueue.create(10); -@@ -83,6 +_,8 @@ +@@ -103,6 +_,8 @@ } - LOGGER.info("OpenGL debug message: {}", entry); + LOGGER.info("OpenGL debug message: {}", gldebug$logentry); + // TODO: [VEN] Trim the stack trace + if (PRINT_STACKTRACE_ON_ERROR) LOGGER.info("Trace: ", new Throwable("GlDebug")); } public List getLastOpenGlDebugMessages() { -@@ -107,7 +_,7 @@ - GlDebug debug = new GlDebug(); - enabledExtensions.add("GL_KHR_debug"); - GL33C.glEnable(37600); -- if (debugSynchronousGlLogs) { -+ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) { - GL33C.glEnable(33346); - } +@@ -126,7 +_,7 @@ + GlDebug gldebug1 = new GlDebug(); + enabledExtensions.add("GL_KHR_debug"); + GL11.glEnable(37600); +- if (debugSynchronousGlLogs) { ++ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) { + GL11.glEnable(33346); + } -@@ -121,7 +_,7 @@ - } else if (caps.GL_ARB_debug_output && GlDevice.USE_GL_ARB_debug_output) { - GlDebug debug = new GlDebug(); - enabledExtensions.add("GL_ARB_debug_output"); -- if (debugSynchronousGlLogs) { -+ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) { - GL33C.glEnable(33346); - } +@@ -140,7 +_,7 @@ + } else if (glcapabilities.GL_ARB_debug_output && GlDevice.USE_GL_ARB_debug_output) { + GlDebug gldebug = new GlDebug(); + enabledExtensions.add("GL_ARB_debug_output"); +- if (debugSynchronousGlLogs) { ++ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) { + GL11.glEnable(33346); + } diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch index 6700394d6b..9882980d67 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch @@ -1,6 +1,6 @@ --- a/com/mojang/blaze3d/opengl/GlDevice.java +++ b/com/mojang/blaze3d/opengl/GlDevice.java -@@ -150,7 +_,12 @@ +@@ -129,7 +_,12 @@ final int depthOrLayers, final int mipLevels ) { @@ -9,12 +9,12 @@ + } + + @Override -+ public GpuTexture createTexture(final @Nullable Supplier label, @GpuTexture.Usage final int usage, final GpuFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, final boolean stencil) { ++ public GpuTexture createTexture(final @Nullable Supplier label, @GpuTexture.Usage final int usage, final TextureFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, final boolean stencil ) { + return this.createTexture(this.debugLabels.exists() && label != null ? label.get() : null, usage, format, width, height, depthOrLayers, mipLevels, stencil); } @Override -@@ -163,6 +_,11 @@ +@@ -142,6 +_,11 @@ final int depthOrLayers, final int mipLevels ) { @@ -22,29 +22,33 @@ + } + + @Override -+ public GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, final GpuFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, boolean stencil) { ++ public GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, final TextureFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, boolean stencil) { GlStateManager.clearGlErrors(); - int id = GlStateManager._genTexture(); + int i = GlStateManager._genTexture(); if (label == null) { -@@ -186,9 +_,9 @@ - GlStateManager._texParameter(target, 34892, 0); - } - -- int glInternalID = GlConst.toGlInternalId(format); -- int glExternalID = GlConst.toGlExternalId(format); -- int glType = GlConst.toGlType(format); -+ int glInternalID = GlConst.toGlInternalId(format, stencil); -+ int glExternalID = GlConst.toGlExternalId(format, stencil); -+ int glType = GlConst.toGlType(format, stencil); - if (glInternalID != 0 && glExternalID != 0 && glType != 0) { - if (isCubemap) { - for (int cubeTarget : GlConst.CUBEMAP_TARGETS) { -@@ -211,7 +_,7 @@ - throw new IllegalStateException("OpenGL error " + error); +@@ -169,14 +_,14 @@ + for (int k : GlConst.CUBEMAP_TARGETS) { + for (int l = 0; l < mipLevels; l++) { + GlStateManager._texImage2D( +- k, l, GlConst.toGlInternalId(format), width >> l, height >> l, 0, GlConst.toGlExternalId(format), GlConst.toGlType(format), null ++ k, l, GlConst.toGlInternalId(format, stencil), width >> l, height >> l, 0, GlConst.toGlExternalId(format, stencil), GlConst.toGlType(format, stencil), null + ); + } } - -- GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, this.frameBufferCache); -+ GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, this.frameBufferCache, stencil); - this.debugLabels.applyLabel(texture); - return texture; } else { + for (int i1 = 0; i1 < mipLevels; i1++) { + GlStateManager._texImage2D( +- j, i1, GlConst.toGlInternalId(format), width >> i1, height >> i1, 0, GlConst.toGlExternalId(format), GlConst.toGlType(format), null ++ j, i1, GlConst.toGlInternalId(format, stencil), width >> i1, height >> i1, 0, GlConst.toGlExternalId(format, stencil), GlConst.toGlType(format, stencil), null + ); + } + } +@@ -187,7 +_,7 @@ + } else if (j1 != 0) { + throw new IllegalStateException("OpenGL error " + j1); + } else { +- GlTexture gltexture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, i); ++ GlTexture gltexture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, i, stencil); + this.debugLabels.applyLabel(gltexture); + return gltexture; + } diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlStateManager.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlStateManager.java.patch index 11e9b24586..4605f091f5 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlStateManager.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlStateManager.java.patch @@ -1,18 +1,18 @@ --- a/com/mojang/blaze3d/opengl/GlStateManager.java +++ b/com/mojang/blaze3d/opengl/GlStateManager.java -@@ -80,6 +_,11 @@ +@@ -86,6 +_,11 @@ } } -+ public static boolean _isBlendEnabled(int index) { ++ public static boolean _isBlendEnabled() { + RenderSystem.assertOnRenderThread(); -+ return BLEND[index].mode.enabled; ++ return BLEND.mode.enabled; + } + - public static void _disableBlend(int index) { + public static void _disableBlend() { RenderSystem.assertOnRenderThread(); - BLEND[index].mode.disable(); -@@ -390,9 +_,17 @@ + BLEND.mode.disable(); +@@ -380,9 +_,17 @@ } } @@ -22,8 +22,8 @@ + public static void _texParameter(final int target, final int name, final int value) { RenderSystem.assertOnRenderThread(); - GL33C.glTexParameteri(target, name, value); -+ if (target == GL33C.GL_TEXTURE1) { + GL11.glTexParameteri(target, name, value); ++ if (target == GL13.GL_TEXTURE1) { + lastBrightnessX = name; + lastBrightnessY = value; + } diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlTexture.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlTexture.java.patch index a46d2a3d47..0c0efb4678 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlTexture.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlTexture.java.patch @@ -1,21 +1,20 @@ --- a/com/mojang/blaze3d/opengl/GlTexture.java +++ b/com/mojang/blaze3d/opengl/GlTexture.java -@@ -27,9 +_,14 @@ - final int id, - final FrameBufferCache frameBufferCache +@@ -28,8 +_,13 @@ + final int mipLevels, + final int id ) { -+ this(usage, label, format, width, height, depthOrLayers, mipLevels, id, frameBufferCache, false); ++ this(usage, label, format, width, height, depthOrLayers, mipLevels, id, false); + } + -+ protected GlTexture(@GpuTexture.Usage int usage, String label, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels, int id, FrameBufferCache frameBufferCache, boolean stencil) { ++ protected GlTexture(int usage, String label, TextureFormat format, int width, int height, int depthOrLayers, int mipLevels, int id, boolean stencil) { super(usage, label, format, width, height, depthOrLayers, mipLevels); this.id = id; - this.frameBufferCache = frameBufferCache; + this.stencilEnabled = stencil; } @Override -@@ -84,5 +_,12 @@ +@@ -96,5 +_,12 @@ if (this.closed && this.views == 0) { this.destroyImmediately(); } diff --git a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch index 0c3e099fc8..09e7a71e25 100644 --- a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch @@ -1,15 +1,15 @@ --- a/com/mojang/blaze3d/pipeline/RenderTarget.java +++ b/com/mojang/blaze3d/pipeline/RenderTarget.java -@@ -83,7 +_,7 @@ +@@ -80,7 +_,7 @@ this.width = width; this.height = height; if (this.useDepth) { -- this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, GpuFormat.D32_FLOAT, width, height, 1, 1); -+ this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, GpuFormat.D32_FLOAT, width, height, 1, 1, this.stencilEnabled); - this.depthTextureView = device.createTextureView(this.depthTexture); +- this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1); ++ this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1, this.stencilEnabled); + this.depthTextureView = gpudevice.createTextureView(this.depthTexture); } -@@ -121,5 +_,26 @@ +@@ -124,5 +_,26 @@ public @Nullable GpuTextureView getDepthTextureView() { return this.depthTextureView; diff --git a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch index e7a00bd35a..3625ee9afb 100644 --- a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch @@ -1,28 +1,28 @@ --- a/com/mojang/blaze3d/platform/Window.java +++ b/com/mojang/blaze3d/platform/Window.java -@@ -101,8 +_,9 @@ - Monitor initialMonitor = monitorManager.getMonitor(GLFW.glfwGetPrimaryMonitor()); +@@ -97,8 +_,9 @@ + Monitor monitor = this.screenManager.getMonitor(GLFW.glfwGetPrimaryMonitor()); this.windowedWidth = this.width = allowedWindowMinSize(displayData.width()); this.windowedHeight = this.height = allowedWindowMinSize(displayData.height()); -- this.handle = this.createWindow(backend, this.width, this.height, title, this.fullscreen && initialMonitor != null ? initialMonitor.monitor() : 0L); -+ this.handle = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(this.width, this.height, title, this.fullscreen && initialMonitor != null ? initialMonitor.monitor() : 0L, () -> backend); +- this.handle = this.createWindow(backend, this.width, this.height, title, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L); ++ this.handle = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(this.width, this.height, title, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, () -> backend); this.backend = backend; -+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(initialMonitor), 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 (initialMonitor != null) { - VideoMode mode = initialMonitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); - this.windowedX = this.x = initialMonitor.x() + mode.getWidth() / 2 - this.width / 2; -@@ -114,6 +_,7 @@ - this.windowedX = this.x = actualX[0]; - this.windowedY = this.y = actualY[0]; ++ 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; +@@ -110,6 +_,7 @@ + this.windowedX = this.x = aint1[0]; + this.windowedY = this.y = aint[0]; } + } this.setMode(); this.refreshFramebufferSize(); -@@ -306,6 +_,9 @@ - outHeight[0] = this.isSoftScreen() ? outHeight[0] - 1 : outHeight[0]; - this.framebufferWidth = outWidth[0] > 0 ? outWidth[0] : 1; - this.framebufferHeight = outHeight[0] > 0 ? outHeight[0] : 1; +@@ -300,6 +_,9 @@ + GLFW.glfwGetFramebufferSize(this.handle, 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); + } diff --git a/patches/minecraft/com/mojang/blaze3d/systems/GpuDevice.java.patch b/patches/minecraft/com/mojang/blaze3d/systems/GpuDevice.java.patch index 056d0582eb..4ef186d362 100644 --- a/patches/minecraft/com/mojang/blaze3d/systems/GpuDevice.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/systems/GpuDevice.java.patch @@ -1,14 +1,14 @@ --- a/com/mojang/blaze3d/systems/GpuDevice.java +++ b/com/mojang/blaze3d/systems/GpuDevice.java -@@ -73,6 +_,21 @@ +@@ -61,6 +_,21 @@ return this.backend.createTexture(label, usage, format, width, height, depthOrLayers, mipLevels); } -+ /** Forge: same as {@link #createTexture(Supplier, int, GpuFormat, int, int, int)} but with stencil support */ ++ /** Forge: same as {@link #createTexture(Supplier, int, TextureFormat, int, int, int)} but with stencil support */ + public GpuTexture createTexture( + final @Nullable Supplier label, + @GpuTexture.Usage final int usage, -+ final GpuFormat format, ++ final TextureFormat format, + final int width, + final int height, + final int depthOrLayers, @@ -21,18 +21,18 @@ + public GpuTexture createTexture( final @Nullable String label, - final @GpuTexture.Usage int usage, -@@ -84,6 +_,21 @@ + @GpuTexture.Usage final int usage, +@@ -72,6 +_,21 @@ ) { this.verifyTextureCreationArgs(usage, width, height, depthOrLayers, mipLevels); return this.backend.createTexture(label, usage, format, width, height, depthOrLayers, mipLevels); + } + -+ /** Forge: same as {@link #createTexture(Supplier, int, GpuFormat, int, int, int)} but with stencil support */ ++ /** Forge: same as {@link #createTexture(Supplier, int, TextureFormat, int, int, int)} but with stencil support */ + public GpuTexture createTexture( + final @Nullable String label, + @GpuTexture.Usage final int usage, -+ final GpuFormat format, ++ final TextureFormat format, + final int width, + final int height, + final int depthOrLayers, @@ -43,4 +43,4 @@ + return this.backend.createTexture(label, usage, format, width, height, depthOrLayers, mipLevels, stencil); } - private void verifyTextureCreationArgs(final @GpuTexture.Usage int usage, final int width, final int height, final int depthOrLayers, final int mipLevels) { + private void verifyTextureCreationArgs(@GpuTexture.Usage final int usage, final int width, final int height, final int depthOrLayers, final int mipLevels) { diff --git a/patches/minecraft/com/mojang/blaze3d/systems/GpuDeviceBackend.java.patch b/patches/minecraft/com/mojang/blaze3d/systems/GpuDeviceBackend.java.patch index d39e0b3864..457ba3d3a0 100644 --- a/patches/minecraft/com/mojang/blaze3d/systems/GpuDeviceBackend.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/systems/GpuDeviceBackend.java.patch @@ -1,18 +1,20 @@ --- a/com/mojang/blaze3d/systems/GpuDeviceBackend.java +++ b/com/mojang/blaze3d/systems/GpuDeviceBackend.java -@@ -32,7 +_,17 @@ - @Nullable Supplier label, @GpuTexture.Usage int usage, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels +@@ -30,9 +_,19 @@ + @Nullable Supplier label, @GpuTexture.Usage final int usage, TextureFormat format, int width, int height, int depthOrLayers, int mipLevels ); -+ /** Forge: same as {@link #createTexture(Supplier, int, GpuFormat, int, int, int)} but with stencil support */ -+ default GpuTexture createTexture(@Nullable Supplier label, @GpuTexture.Usage final int usage, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels, boolean stencil) { ++ /** Forge: same as {@link #createTexture(Supplier, int, TextureFormat, int, int, int)} but with stencil support */ ++ default GpuTexture createTexture(@Nullable Supplier label, @GpuTexture.Usage final int usage, TextureFormat format, int width, int height, int depthOrLayers, int mipLevels, boolean stencil) { + return createTexture(label, usage, format, width, height, depthOrLayers, mipLevels); + } + - GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage int usage, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels); + GpuTexture createTexture( + @Nullable String label, @GpuTexture.Usage final int usage, TextureFormat format, int width, int height, int depthOrLayers, int mipLevels + ); + -+ /** Forge: same as {@link #createTexture(String, int, GpuFormat, int, int, int)} but with stencil support */ -+ default GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels, boolean stencil) { ++ /** Forge: same as {@link #createTexture(String, int, TextureFormat, int, int, int)} but with stencil support */ ++ default GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, TextureFormat format, int width, int height, int depthOrLayers, int mipLevels, boolean stencil) { + return createTexture(label, usage, format, width, height, depthOrLayers, mipLevels); + } diff --git a/patches/minecraft/com/mojang/blaze3d/textures/GpuTexture.java.patch b/patches/minecraft/com/mojang/blaze3d/textures/GpuTexture.java.patch index e1acf98c71..77b6b38a95 100644 --- a/patches/minecraft/com/mojang/blaze3d/textures/GpuTexture.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/textures/GpuTexture.java.patch @@ -1,6 +1,6 @@ --- a/com/mojang/blaze3d/textures/GpuTexture.java +++ b/com/mojang/blaze3d/textures/GpuTexture.java -@@ -9,7 +_,7 @@ +@@ -8,7 +_,7 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch index d181b3f0bb..6b8eaa1d7c 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch @@ -1,31 +1,32 @@ --- a/com/mojang/blaze3d/vertex/VertexFormat.java +++ b/com/mojang/blaze3d/vertex/VertexFormat.java -@@ -19,6 +_,7 @@ - private final int vertexSize; - private final int stepRate; - private final List elementValues; +@@ -29,6 +_,7 @@ + private final int[] offsetsByElement = new int[32]; + private @Nullable GpuBuffer immediateDrawVertexBuffer; + private @Nullable GpuBuffer immediateDrawIndexBuffer; + private final com.google.common.collect.ImmutableMap elementMapping; - private VertexFormat(final List elements, final int vertexSize, final int stepRate) { - this.vertexSize = vertexSize; -@@ -29,6 +_,11 @@ + private VertexFormat(final List elements, final List names, final IntList offsets, final int vertexSize) { + this.elements = elements; +@@ -41,6 +_,11 @@ + int j = vertexformatelement != null ? elements.indexOf(vertexformatelement) : -1; + this.offsetsByElement[i] = j != -1 ? offsets.getInt(j) : -1; } - - this.elementValues = elements; + -+ var elementMapping = com.google.common.collect.ImmutableMap.builder(); -+ for (var element : elements) -+ elementMapping.put(element.name(), element); ++ ImmutableMap.Builder elementMapping = ImmutableMap.builder(); ++ for (int i = 0; i < elements.size(); i++) ++ elementMapping.put(names.get(i), elements.get(i)); + this.elementMapping = elementMapping.buildOrThrow(); } - public static VertexFormat.Builder builder(final int stepRate) { -@@ -69,6 +_,8 @@ - public int hashCode() { - return this.elementValues.hashCode(); + public static VertexFormat.Builder builder() { +@@ -139,6 +_,9 @@ + this.immediateDrawIndexBuffer = uploadToBuffer(this.immediateDrawIndexBuffer, buffer, 72, () -> "Immediate index buffer for " + this); + return this.immediateDrawIndexBuffer; } + -+ public com.google.common.collect.ImmutableMap getElementMapping() { return elementMapping; } ++ public ImmutableMap getElementMapping() { return elementMapping; } ++ public int getOffset(int index) { return offsetsByElement[index]; } @OnlyIn(Dist.CLIENT) public static class Builder { diff --git a/patches/minecraft/com/mojang/math/Transformation.java.patch b/patches/minecraft/com/mojang/math/Transformation.java.patch index a08cc0d2b5..537bbf1349 100644 --- a/patches/minecraft/com/mojang/math/Transformation.java.patch +++ b/patches/minecraft/com/mojang/math/Transformation.java.patch @@ -1,6 +1,6 @@ --- a/com/mojang/math/Transformation.java +++ b/com/mojang/math/Transformation.java -@@ -14,7 +_,7 @@ +@@ -17,7 +_,7 @@ import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; @@ -15,15 +15,15 @@ ); + } + -+ private org.joml.Matrix3f normalTransform = null; -+ public org.joml.Matrix3f getNormalMatrix() { ++ private Matrix3f normalTransform = null; ++ public Matrix3f getNormalMatrix() { + checkNormalTransform(); + return normalTransform; + } + + private void checkNormalTransform() { + if (normalTransform == null) { -+ normalTransform = new org.joml.Matrix3f(matrix); ++ normalTransform = new Matrix3f(matrix); + normalTransform.invert(); + normalTransform.transpose(); + } 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 f7cb1fe45c..8956112e2d 100644 --- a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch +++ b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java.patch @@ -6,7 +6,7 @@ @Override + public boolean keyPressed(net.minecraft.client.input.KeyEvent event) { + if (event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) { -+ minecraft.gui.setScreen(this.nextScreen); ++ minecraft.setScreen(this.nextScreen); + return true; + } + return super.keyPressed(event); diff --git a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch index fc1e5576c9..fea9804e7c 100644 --- a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch +++ b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch @@ -1,11 +1,11 @@ --- a/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java +++ b/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java -@@ -300,7 +_,7 @@ - int y = this.getY(); - graphics.blit(RenderPipelines.GUI_TEXTURED, this.image, x + 2, y + 2, 0.0F, 0.0F, 56, 56, 56, 56, 56, 56, color); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_FRAME_SPRITE, x, y, 60, 60, color); -- int textColor = hoveredOrFocused ? -6250336 : -1; -+ int textColor = getFGColor(); - graphics.centeredText(RealmsResetWorldScreen.this.font, this.getMessage(), x + 28, y - 14, textColor); +@@ -303,7 +_,7 @@ + int k = this.getY(); + graphics.blit(RenderPipelines.GUI_TEXTURED, this.image, j + 2, k + 2, 0.0F, 0.0F, 56, 56, 56, 56, 56, 56, i); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_FRAME_SPRITE, j, k, 60, 60, i); +- int l = flag ? -6250336 : -1; ++ int l = getFGColor(); + graphics.centeredText(RealmsResetWorldScreen.this.font, this.getMessage(), j + 28, k - 14, l); } } diff --git a/patches/minecraft/net/minecraft/CrashReport.java.patch b/patches/minecraft/net/minecraft/CrashReport.java.patch index cbf30e33e5..1bc62134c6 100644 --- a/patches/minecraft/net/minecraft/CrashReport.java.patch +++ b/patches/minecraft/net/minecraft/CrashReport.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/CrashReport.java +++ b/net/minecraft/CrashReport.java @@ -58,14 +_,9 @@ - if (this.uncategorizedStackTrace.length > 0) { + if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) { builder.append("-- Head --\n"); builder.append("Thread: ").append(Thread.currentThread().getName()).append("\n"); - builder.append("Stacktrace:\n"); - -- for (StackTraceElement element : this.uncategorizedStackTrace) { -- builder.append("\t").append("at ").append(element); +- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) { +- builder.append("\t").append("at ").append(stacktraceelement); - builder.append("\n"); - } - @@ -17,7 +17,7 @@ + builder.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace)); } - for (CrashReportCategory entry : this.details) { + for (CrashReportCategory crashreportcategory : this.details) { @@ -73,6 +_,7 @@ builder.append("\n\n"); } @@ -26,20 +26,23 @@ this.systemReport.appendToCrashReportString(builder); } -@@ -84,15 +_,7 @@ - exception = replaceMessage(exception, this.title); +@@ -92,18 +_,7 @@ + throwable.setStackTrace(this.exception.getStackTrace()); } +- String s; - try { -- writer = new StringWriter(); -- printWriter = new PrintWriter(writer); -- exception.printStackTrace(printWriter); -- return writer.toString(); +- stringwriter = new StringWriter(); +- printwriter = new PrintWriter(stringwriter); +- throwable.printStackTrace(printwriter); +- s = stringwriter.toString(); - } finally { -- IOUtils.closeQuietly(writer); -- IOUtils.closeQuietly(printWriter); +- IOUtils.closeQuietly((Writer)stringwriter); +- IOUtils.closeQuietly((Writer)printwriter); - } -+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(exception); +- +- return s; ++ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable); } - private static Throwable copyProperties(final Throwable original, final Throwable copy) { + public String getFriendlyReport(final ReportType reportType, final List extraComments) { diff --git a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch index c6cf02d013..1ce817c8dc 100644 --- a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch +++ b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch @@ -1,26 +1,26 @@ --- a/net/minecraft/CrashReportCategory.java +++ b/net/minecraft/CrashReportCategory.java -@@ -138,8 +_,10 @@ +@@ -114,8 +_,10 @@ + if (astacktraceelement.length <= 0) { return 0; + } else { +- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - nestedOffset]; +- System.arraycopy(astacktraceelement, 3 + nestedOffset, this.stackTrace, 0, this.stackTrace.length); ++ int len = astacktraceelement.length - 3 - nestedOffset; ++ 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; } - -- this.stackTrace = new StackTraceElement[full.length - 3 - nestedOffset]; -- System.arraycopy(full, 3 + nestedOffset, this.stackTrace, 0, this.stackTrace.length); -+ int len = full.length - 3 - nestedOffset; -+ if (len <= 0) len = full.length; -+ this.stackTrace = new StackTraceElement[len]; -+ System.arraycopy(full, full.length - len, this.stackTrace, 0, this.stackTrace.length); - return this.stackTrace.length; } +@@ -162,16 +_,16 @@ -@@ -181,16 +_,16 @@ - - if (this.stackTrace.length > 0) { + if (this.stackTrace != null && this.stackTrace.length > 0) { builder.append("\nStacktrace:"); - -- for (StackTraceElement element : this.stackTrace) { +- for (StackTraceElement stacktraceelement : this.stackTrace) { - builder.append("\n\tat "); -- builder.append(element); +- builder.append(stacktraceelement); - } + builder.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace)); } diff --git a/patches/minecraft/net/minecraft/SharedConstants.java.patch b/patches/minecraft/net/minecraft/SharedConstants.java.patch index 661c3eada0..a22540af53 100644 --- a/patches/minecraft/net/minecraft/SharedConstants.java.patch +++ b/patches/minecraft/net/minecraft/SharedConstants.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/SharedConstants.java +++ b/net/minecraft/SharedConstants.java -@@ -218,6 +_,7 @@ +@@ -216,6 +_,7 @@ } static { diff --git a/patches/minecraft/net/minecraft/advancements/Advancement.java.patch b/patches/minecraft/net/minecraft/advancements/Advancement.java.patch index ededdcc34c..6d5670fd12 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 -@@ -220,7 +_,11 @@ +@@ -227,7 +_,11 @@ } public AdvancementHolder save(final Consumer output, final String name) { -- AdvancementHolder advancement = this.build(Identifier.parse(name)); +- AdvancementHolder advancementholder = this.build(Identifier.parse(name)); + return save(output, Identifier.parse(name)); + } + + public AdvancementHolder save(Consumer output, Identifier id) { -+ AdvancementHolder advancement = this.build(id); - output.accept(advancement); - return advancement; ++ AdvancementHolder advancementholder = this.build(id); + output.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 24a7b0abf3..f626d79953 100644 --- a/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch +++ b/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/advancements/AdvancementRewards.java +++ b/net/minecraft/advancements/AdvancementRewards.java -@@ -43,6 +_,7 @@ - LootParams params = new LootParams.Builder(level) +@@ -44,6 +_,7 @@ + LootParams lootparams = new LootParams.Builder(serverlevel) .withParameter(LootContextParams.THIS_ENTITY, player) .withParameter(LootContextParams.ORIGIN, player.position()) + .withLuck(player.getLuck()) .create(LootContextParamSets.ADVANCEMENT_REWARD); - boolean changes = false; + boolean flag = false; diff --git a/patches/minecraft/net/minecraft/client/Camera.java.patch b/patches/minecraft/net/minecraft/client/Camera.java.patch index 2b21b2469f..b32b0b843c 100644 --- a/patches/minecraft/net/minecraft/client/Camera.java.patch +++ b/patches/minecraft/net/minecraft/client/Camera.java.patch @@ -1,12 +1,13 @@ --- a/net/minecraft/client/Camera.java +++ b/net/minecraft/client/Camera.java -@@ -224,11 +_,13 @@ +@@ -217,12 +_,14 @@ + return 90.0F; + } else { + float f = this.minecraft.options.fov().get().intValue() * Mth.lerp(partialTicks, this.oldFovModifier, this.fovModifier); +- return this.modifyFovBasedOnDeathOrFluid(partialTicks, f); ++ var ret = this.modifyFovBasedOnDeathOrFluid(partialTicks, f); ++ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeFov(this.minecraft.gameRenderer, this, partialTicks, ret, true).getFOV(); } - - float fov = this.minecraft.options.fov().get().intValue() * Mth.lerp(partialTicks, this.oldFovModifier, this.fovModifier); -- return this.modifyFovBasedOnDeathOrFluid(partialTicks, fov); -+ var ret = this.modifyFovBasedOnDeathOrFluid(partialTicks, fov); -+ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeFov(this.minecraft.gameRenderer, this, partialTicks, ret, true).getFOV(); } private float calculateHudFov(final float partialTicks) { @@ -16,7 +17,7 @@ } private float modifyFovBasedOnDeathOrFluid(final float partialTicks, float fov) { -@@ -337,9 +_,13 @@ +@@ -331,9 +_,13 @@ } protected void setRotation(final float yRot, final float xRot) { @@ -31,7 +32,7 @@ FORWARDS.rotate(this.rotation, this.forwards); UP.rotate(this.rotation, this.up); LEFT.rotate(this.rotation, this.left); -@@ -370,6 +_,13 @@ +@@ -364,6 +_,13 @@ public float yRot() { return this.yRot; diff --git a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch index ef8d086d33..9a4b06e8b9 100644 --- a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch @@ -16,11 +16,11 @@ } private static void forAllKeyMappings(final InputConstants.Key key, final Consumer operation) { -- List keyMappings = MAP.get(key); -+ List keyMappings = MAP.getAll(key); - if (keyMappings != null && !keyMappings.isEmpty()) { - for (KeyMapping keyMapping : keyMappings) { - operation.accept(keyMapping); +- List list = MAP.get(key); ++ List list = MAP.getAll(key); + if (list != null && !list.isEmpty()) { + for (KeyMapping keymapping : list) { + operation.accept(keymapping); @@ -106,7 +_,7 @@ } @@ -70,7 +70,7 @@ return this.key.equals(that.key); } -@@ -179,11 +_,13 @@ +@@ -175,11 +_,13 @@ } public Component getTranslatedKeyMessage() { @@ -85,7 +85,7 @@ } public String saveString() { -@@ -195,11 +_,94 @@ +@@ -191,11 +_,94 @@ } private void registerMapping(final InputConstants.Key key) { diff --git a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch index 121ab8fa48..71c954bdb0 100644 --- a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/client/KeyboardHandler.java +++ b/net/minecraft/client/KeyboardHandler.java -@@ -478,7 +_,7 @@ - if (screen != null) { - try { - if (action != 1 && action != 2) { -- if (action == 0 && screen.keyReleased(event)) { -+ if (action == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, event)) { - if (options.keyDebugModifier.matches(event)) { - this.usedDebugKeyAsModifier = false; - } -@@ -487,7 +_,7 @@ +@@ -516,7 +_,7 @@ + if (screen != null) { + try { + if (action != 1 && action != 2) { +- if (action == 0 && screen.keyReleased(event)) { ++ if (action == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, event)) { + if (options.keyDebugModifier.matches(event)) { + this.usedDebugKeyAsModifier = false; } - } else { - screen.afterKeyboardAction(); -- if (screen.keyPressed(event)) { -+ if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, event)) { - if (this.minecraft.gui.screen() == null) { - InputConstants.Key key = InputConstants.getKey(event); - KeyMapping.set(key, false); -@@ -562,6 +_,7 @@ +@@ -525,7 +_,7 @@ + } + } else { + screen.afterKeyboardAction(); +- if (screen.keyPressed(event)) { ++ if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, event)) { + if (this.minecraft.screen == null) { + InputConstants.Key inputconstants$key = InputConstants.getKey(event); + KeyMapping.set(inputconstants$key, false); +@@ -597,6 +_,7 @@ } } } @@ -26,12 +26,12 @@ } } -@@ -570,7 +_,7 @@ - Screen screen = this.minecraft.gui.screen(); - if (screen != null && this.minecraft.gui.overlay() == null) { +@@ -605,7 +_,7 @@ + Screen screen = this.minecraft.screen; + if (screen != null && this.minecraft.getOverlay() == null) { try { - screen.charTyped(event); + net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, event); - } catch (Throwable t) { - CrashReport report = CrashReport.forThrowable(t, "charTyped event handler"); - screen.fillCrashDetails(report); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "charTyped event handler"); + screen.fillCrashDetails(crashreport); diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch index 1986a3b198..2901bd6cee 100644 --- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch +++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/Minecraft.java +++ b/net/minecraft/client/Minecraft.java -@@ -258,7 +_,7 @@ +@@ -272,7 +_,7 @@ import org.slf4j.Logger; @OnlyIn(Dist.CLIENT) @@ -9,7 +9,7 @@ private static Minecraft instance; private static final Logger LOGGER = LogUtils.getLogger(); private static final int MAX_TICKS_PER_UPDATE = 10; -@@ -410,7 +_,6 @@ +@@ -436,7 +_,6 @@ } }, Util.nonCriticalIoPool()); LOGGER.info("Setting user: {}", this.user.getName()); @@ -17,126 +17,158 @@ this.demo = gameConfig.game.demo; this.allowsMultiplayer = !gameConfig.game.disableMultiplayer; this.allowsChat = !gameConfig.game.disableChat; -@@ -547,12 +_,12 @@ - LOGGER.error("Couldn't set icon", e); - } - -+ // FORGE: Move mouse and keyboard handler setup further below - this.mouseHandler = new MouseHandler(this); -- this.mouseHandler.setup(this.window); - this.keyboardHandler = new KeyboardHandler(this); -- this.keyboardHandler.setup(this.window); - this.options.applyGraphicsPreset(this.options.graphicsPreset().get()); - 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, var1 -> { -@@ -630,6 +_,7 @@ - ParticleResources particleResources = new ParticleResources(); - this.resourceManager.registerReloadListener(particleResources); - this.particleEngine = new ParticleEngine(this.level, particleResources); -+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(particleResources); - particleResources.onReload(this.particleEngine::clearParticles); - this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.modelManager); - WindowRenderState windowRenderState = this.gameRenderer.gameRenderState().windowRenderState; -@@ -647,6 +_,7 @@ - this.window.getHeight() - ); - this.levelExtractor = new LevelExtractor(this, this.gameRenderer.gameRenderState().levelRenderState, this.levelRenderer); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onInitLevelRenderer(); - this.resourceManager.registerReloadListener(this.levelExtractor); - this.resourceManager.registerReloadListener(this.levelRenderer.cloudRenderer()); - this.gpuWarnlistManager = new GpuWarnlistManager(); -@@ -654,6 +_,9 @@ - this.resourceManager.registerReloadListener(this.regionalCompliancies); - this.gui = new Gui(this, new Hud(this), this.gameRenderer.gameRenderState().guiRenderState); - this.gui.registerReloadListeners(this.resourceManager); -+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them. -+ this.mouseHandler.setup(this.window); -+ this.keyboardHandler.setup(this.window); - RealmsClient realmsClient = RealmsClient.getOrCreate(this); - this.realmsDataFetcher = new RealmsDataFetcher(realmsClient); - RenderSystem.setErrorCallback(this::onFullscreenError); -@@ -686,6 +_,7 @@ - } - } - -+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager); - this.window.updateRawMouseInput(this.options.rawMouseInput().get()); - this.window.setAllowCursorChanges(this.options.allowCursorChanges().get()); - this.window.setDefaultErrorCallback(); -@@ -710,14 +_,15 @@ - .createReload(Util.backgroundExecutor().forName("resourceLoad"), this, RESOURCE_RELOAD_INITIAL_TASK, packs); - GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); - GameLoadCookie loadCookie = new GameLoadCookie(realmsClient, gameConfig.quickPlay); -- this.gui.setOverlay(new LoadingOverlay(this, reloadInstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, loadCookie), () -> { -+ this.gui.setOverlay(net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay(() -> this, () ->reloadInstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, loadCookie), () -> { - if (SharedConstants.IS_RUNNING_IN_IDE) { - this.selfTest(); +@@ -522,14 +_,14 @@ + LOGGER.error("Couldn't set icon", (Throwable)ioexception); } - this.reloadStateTracker.finishReload(); - this.onResourceLoadFinished(loadCookie); -- }), false)); -+ net.minecraftforge.client.loading.ClientModLoader.completeModLoading(); -+ }), false).get()); - this.quickPlayLog = QuickPlayLog.of(gameConfig.quickPlay.logPath()); - this.framerateLimitTracker = new FramerateLimitTracker(this.options, this); - this.fpsPieProfiler = new ContinuousProfiler(Util.timeSource(), () -> this.fpsPieRenderTicks, this.framerateLimitTracker::isHeavilyThrottled); -@@ -801,6 +_,7 @@ - StringBuilder builder = new StringBuilder("Minecraft"); ++ // FORGE: Move mouse and keyboard handler setup further below + this.mouseHandler = new MouseHandler(this); +- this.mouseHandler.setup(this.window); + this.keyboardHandler = new KeyboardHandler(this); +- this.keyboardHandler.setup(this.window); + this.options.applyGraphicsPreset(this.options.graphicsPreset().get()); + LOGGER.info("Using optional rendering extensions: {}", String.join(", ", RenderSystem.getDevice().getEnabledExtensions())); + this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight()); + 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, languageData -> { +@@ -617,6 +_,7 @@ + this.particleResources = new ParticleResources(); + this.resourceManager.registerReloadListener(this.particleResources); + this.particleEngine = new ParticleEngine(this.level, this.particleResources); ++ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleResources); + this.particleResources.onReload(this.particleEngine::clearParticles); + this.waypointStyles = new WaypointStyleManager(); + this.resourceManager.registerReloadListener(this.waypointStyles); +@@ -638,6 +_,9 @@ + 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); ++ this.keyboardHandler.setup(this.window); + RealmsClient realmsclient = RealmsClient.getOrCreate(this); + this.realmsDataFetcher = new RealmsDataFetcher(realmsclient); + RenderSystem.setErrorCallback(this::onFullscreenError); +@@ -669,6 +_,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.setAllowCursorChanges(this.options.allowCursorChanges().get()); +@@ -695,14 +_,16 @@ + GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); + Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, gameConfig.quickPlay); + this.setOverlay( +- new LoadingOverlay(this, reloadinstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, minecraft$gameloadcookie), () -> { ++ net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay( ++ () -> this, () -> reloadinstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, minecraft$gameloadcookie), () -> { + if (SharedConstants.IS_RUNNING_IN_IDE) { + this.selfTest(); + } + + this.reloadStateTracker.finishReload(); + this.onResourceLoadFinished(minecraft$gameloadcookie); +- }), false) ++ net.minecraftforge.client.loading.ClientModLoader.completeModLoading(); ++ }), false).get() + ); + this.quickPlayLog = QuickPlayLog.of(gameConfig.quickPlay.logPath()); + this.framerateLimitTracker = new FramerateLimitTracker(this.options, this); +@@ -822,6 +_,7 @@ + StringBuilder stringbuilder = new StringBuilder("Minecraft"); if (checkModStatus().shouldReportAsModified()) { - builder.append("*"); -+ builder.append(" Forge"); + stringbuilder.append("*"); ++ stringbuilder.append(" Forge"); } - builder.append(" "); -@@ -824,6 +_,8 @@ + stringbuilder.append(" "); +@@ -845,6 +_,8 @@ } - private static UserApiService createUserApiService(final YggdrasilAuthenticationService authService, final GameConfig config) { + private UserApiService createUserApiService(final YggdrasilAuthenticationService authService, final GameConfig config) { + if ("0".equals(config.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam. + return UserApiService.OFFLINE; return config.game.offlineDeveloperMode ? UserApiService.OFFLINE : authService.createUserApiService(config.user.user.getAccessToken()); } -@@ -840,7 +_,7 @@ +@@ -857,7 +_,7 @@ } - private void rollbackResourcePacks(final Throwable t, final @Nullable GameLoadCookie loadCookie) { + private void rollbackResourcePacks(final Throwable t, final Minecraft.@Nullable GameLoadCookie loadCookie) { - 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(t, null, loadCookie); } else { Util.throwAsRuntime(t); -@@ -1141,6 +_,7 @@ - Util.shutdownExecutors(); - this.windowSurface.close(); - RenderSystem.shutdownRenderer(); -+ net.minecraftforge.fml.config.ConfigTracker.forceUnload(); - } catch (Throwable t) { - LOGGER.error("Shutdown failure!", t); - throw t; -@@ -1301,7 +_,9 @@ - profiler.popPush("gpuAsync"); - RenderSystem.executePendingTasks(); - profiler.pop(); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker); - this.gameRenderer.render(this.deltaTracker, advanceGameTime); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker); - } +@@ -1134,12 +_,6 @@ + LOGGER.error("setScreen called from non-game thread"); + } - profiler.push("present"); -@@ -1425,6 +_,7 @@ - this.window.setGuiScale(guiScale); - if (this.gui.screen() != null) { - this.gui.screen().resize(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); -+ this.gui.resizeLayers(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); +- if (this.screen != null) { +- this.screen.removed(); +- } else { +- this.setLastInputType(InputType.NONE); +- } +- + if (screen == null) { + if (this.clientLevelTeardownInProgress) { + throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); +@@ -1158,6 +_,23 @@ + } + } + ++ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this); ++ Screen old = this.screen; ++ if (screen != null) { ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, screen); ++ if (event == null) return; ++ screen = event; ++ } ++ ++ if (screen != old) { ++ if (old != null) { ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old); ++ old.removed(); ++ } else { ++ this.setLastInputType(InputType.NONE); ++ } ++ } ++ + this.screen = screen; + if (this.screen != null) { + this.screen.added(); +@@ -1241,6 +_,7 @@ + Util.shutdownExecutors(); + RenderSystem.getSamplerCache().close(); + RenderSystem.getDevice().close(); ++ net.minecraftforge.fml.config.ConfigTracker.forceUnload(); + } catch (Throwable throwable) { + LOGGER.error("Shutdown failure!", throwable); + throw throwable; +@@ -1352,7 +_,9 @@ + profilerfiller.popPush("gpuAsync"); + RenderSystem.executePendingTasks(); + profilerfiller.pop(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker); + this.gameRenderer.render(this.deltaTracker, advanceGameTime); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker); + profilerfiller.push("present"); + if (!this.gameRenderer.getGameRenderState().windowRenderState.isMinimized) { + this.mainRenderTarget.blitToScreen(); +@@ -1456,6 +_,7 @@ + this.window.setGuiScale(i); + if (this.screen != null) { + this.screen.resize(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); ++ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); } this.mouseHandler.setIgnoreFirstMove(); -@@ -1576,6 +_,7 @@ +@@ -1600,6 +_,7 @@ } public void stop() { @@ -144,132 +176,132 @@ this.running = false; } -@@ -1599,10 +_,18 @@ +@@ -1629,10 +_,18 @@ if (down && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) { - BlockHitResult blockHit = (BlockHitResult)this.hitResult; - BlockPos pos = blockHit.getBlockPos(); -- if (!this.level.getBlockState(pos).isAir()) { -+ if (!this.level.isEmptyBlock(pos)) { + BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; + BlockPos blockpos = blockhitresult.getBlockPos(); +- if (!this.level.getBlockState(blockpos).isAir()) { ++ if (!this.level.isEmptyBlock(blockpos)) { + var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND); + if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) { + if (inputEvent.shouldSwingHand()) { -+ this.level.addBreakingBlockEffect(pos, blockHit); ++ this.level.addBreakingBlockEffect(blockpos, blockhitresult); + this.player.swing(InteractionHand.MAIN_HAND); + } + return; + } - Direction direction = blockHit.getDirection(); -- if (this.gameMode.continueDestroyBlock(pos, direction)) { -- this.level.addBreakingBlockEffect(pos, direction); -+ if (this.gameMode.continueDestroyBlock(pos, direction) && inputEvent.shouldSwingHand()) { -+ this.level.addBreakingBlockEffect(pos, blockHit); + Direction direction = blockhitresult.getDirection(); +- if (this.gameMode.continueDestroyBlock(blockpos, direction)) { +- this.level.addBreakingBlockEffect(blockpos, direction); ++ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) { ++ this.level.addBreakingBlockEffect(blockpos, blockhitresult); this.player.swing(InteractionHand.MAIN_HAND); } } -@@ -1656,6 +_,8 @@ +@@ -1675,6 +_,8 @@ + this.player.swing(InteractionHand.MAIN_HAND); return true; + } else { ++ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND); ++ if (!net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) + switch (this.hitResult.getType()) { + case ENTITY: + AttackRange attackrange = itemstack.get(DataComponents.ATTACK_RANGE); +@@ -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; + } +@@ -1716,6 +_,12 @@ } -+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND); -+ if (!net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) - switch (this.hitResult.getType()) { - case ENTITY: - AttackRange customItemRange = heldItem.get(DataComponents.ATTACK_RANGE); -@@ -1666,7 +_,7 @@ - case BLOCK: - BlockHitResult blockHit = (BlockHitResult)this.hitResult; - BlockPos pos = blockHit.getBlockPos(); -- if (!this.level.getBlockState(pos).isAir()) { -+ if (!this.level.isEmptyBlock(pos)) { - this.gameMode.startDestroyBlock(pos, blockHit.getDirection()); - if (this.level.getBlockState(pos).isAir()) { - endAttack = true; -@@ -1679,8 +_,10 @@ - } - - this.player.resetAttackStrengthTicker(); -+ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player); - } - -+ if (inputEvent.shouldSwingHand()) - this.player.swing(InteractionHand.MAIN_HAND); - return endAttack; - } -@@ -1696,6 +_,12 @@ - } - - for (InteractionHand hand : InteractionHand.values()) { -+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(1, this.options.keyUse, hand); + for (InteractionHand interactionhand : InteractionHand.values()) { ++ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(1, this.options.keyUse, interactionhand); + if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) { -+ if (inputEvent.shouldSwingHand()) this.player.swing(hand); ++ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand); + return; + } + - ItemStack heldItem = this.player.getItemInHand(hand); - if (!heldItem.isItemEnabled(this.level.enabledFeatures())) { + ItemStack itemstack = this.player.getItemInHand(interactionhand); + if (!itemstack.isItemEnabled(this.level.enabledFeatures())) { return; -@@ -1712,7 +_,7 @@ - - if (this.player.isWithinEntityInteractionRange(entity, 0.0) - && this.gameMode.interact(this.player, entity, entityHit, hand) instanceof InteractionResult.Success success) { -- if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { -+ if (success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { - this.player.swing(hand); +@@ -1734,7 +_,7 @@ + && this.gameMode.interact(this.player, entity, entityhitresult, interactionhand) instanceof InteractionResult.Success interactionresult$success2 + ) + { +- if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT) { ++ if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { + this.player.swing(interactionhand); } -@@ -1724,7 +_,7 @@ - int oldCount = heldItem.getCount(); - InteractionResult useResult = this.gameMode.useItemOn(this.player, hand, blockHit); - if (useResult instanceof InteractionResult.Success success) { -- if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { -+ if (success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { - this.player.swing(hand); - if (!heldItem.isEmpty() && (heldItem.getCount() != oldCount || this.player.hasInfiniteMaterials())) { - this.gameRenderer.itemInHandRenderer.itemUsed(hand); -@@ -1740,6 +_,9 @@ +@@ -1746,7 +_,7 @@ + int i = itemstack.getCount(); + InteractionResult interactionresult = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult); + if (interactionresult instanceof InteractionResult.Success interactionresult$success) { +- if (interactionresult$success.swingSource() == InteractionResult.SwingSource.CLIENT) { ++ if (interactionresult$success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { + this.player.swing(interactionhand); + if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.player.hasInfiniteMaterials())) { + this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand); +@@ -1762,6 +_,9 @@ } } -+ if (heldItem.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) -+ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, hand); ++ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) ++ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, interactionhand); + - if (!heldItem.isEmpty() && this.gameMode.useItem(this.player, hand) instanceof InteractionResult.Success success) { - if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { - this.player.swing(hand); -@@ -1768,6 +_,8 @@ + if (!itemstack.isEmpty() + && this.gameMode.useItem(this.player, interactionhand) instanceof InteractionResult.Success interactionresult$success1) { + if (interactionresult$success1.swingSource() == InteractionResult.SwingSource.CLIENT) { +@@ -1791,6 +_,8 @@ } - ProfilerFiller profiler = Profiler.get(); + ProfilerFiller profilerfiller = Profiler.get(); + net.minecraftforge.event.ForgeEventFactory.onPreClientTick(); + - profiler.push("gameMode"); - if (!this.pause && this.level != null) { - this.gameMode.tick(); -@@ -1817,6 +_,7 @@ + profilerfiller.push("gui"); + this.textInputManager.tick(); + this.chatListener.tick(); +@@ -1873,6 +_,7 @@ this.tutorial.tick(); + net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true); try { this.level.tick(() -> true); - } catch (Throwable t) { -@@ -1830,6 +_,7 @@ + } catch (Throwable throwable1) { +@@ -1886,6 +_,7 @@ - throw new ReportedException(report); + throw new ReportedException(crashreport1); } + net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true); } - profiler.popPush("animateTick"); -@@ -1854,6 +_,7 @@ - profiler.popPush("keyboard"); + profilerfiller.popPush("animateTick"); +@@ -1910,6 +_,7 @@ + profilerfiller.popPush("keyboard"); this.keyboardHandler.tick(); - profiler.pop(); + profilerfiller.pop(); + net.minecraftforge.event.ForgeEventFactory.onPostClientTick(); } private boolean isLevelRunningNormally() { -@@ -2059,6 +_,7 @@ +@@ -2140,6 +_,7 @@ } public void setLevel(final ClientLevel level) { @@ -277,35 +309,35 @@ this.level = level; this.updateLevelInEngines(level); } -@@ -2120,6 +_,7 @@ - IntegratedServer server = this.singleplayerServer; +@@ -2201,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.gui.setClientLevelTeardownInProgress(true); -@@ -2127,6 +_,7 @@ + this.clientLevelTeardownInProgress = true; +@@ -2208,6 +_,7 @@ try { if (this.level != null) { - this.gui.hud.onDisconnected(); + this.gui.onDisconnected(); + net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); } this.level = null; -@@ -2141,6 +_,7 @@ +@@ -2222,6 +_,7 @@ } - profiler.pop(); + profilerfiller.pop(); + net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level); } this.setScreenAndShow(screen); -@@ -2354,6 +_,7 @@ +@@ -2374,6 +_,7 @@ private void pickBlockOrEntity() { if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) { + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInputPickBlock(this.options.keyPickItem)) return; - boolean includeData = this.hasControlDown(); + boolean flag = this.hasControlDown(); switch (this.hitResult) { - case BlockHitResult blockHitResult: + case BlockHitResult blockhitresult: diff --git a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch index 7be4daacb7..d684bf2620 100644 --- a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch @@ -1,68 +1,68 @@ --- a/net/minecraft/client/MouseHandler.java +++ b/net/minecraft/client/MouseHandler.java -@@ -77,6 +_,7 @@ +@@ -87,6 +_,7 @@ this.activeButton = null; } -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(buttonInfo, action)) return; - if (this.minecraft.gui.overlay() == null) { - if (pressed - && this.minecraft.handleGlobalKeyPress(InputConstants.Type.MOUSE.getOrCreate(buttonInfo.button()), buttonInfo.hasControlDownWithQuirk())) { -@@ -101,7 +_,7 @@ - && currentTime - this.lastClick.time() < 250L ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo, action)) return; + if (this.minecraft.getOverlay() == null) { + if (this.minecraft.screen == null) { + if (!this.mouseGrabbed && flag) { +@@ -106,7 +_,7 @@ + && i - this.lastClick.time() < 250L && this.lastClick.screen() == screen - && this.lastClickButton == event.button(); -- if (screen.mouseClicked(event, doubleClick)) { -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, xm, ym, event, doubleClick)) { - this.lastClick = new MouseHandler.LastClick(currentTime, screen); - this.lastClickButton = buttonInfo.button(); + && this.lastClickButton == mousebuttonevent.button(); +- if (screen.mouseClicked(mousebuttonevent, flag1)) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, mousebuttonevent, flag1)) { + this.lastClick = new MouseHandler.LastClick(i, screen); + this.lastClickButton = mousebuttoninfo.button(); return; -@@ -116,7 +_,7 @@ +@@ -121,7 +_,7 @@ } } else { try { -- if (screen.mouseReleased(event)) { -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, xm, ym, event)) { +- if (screen.mouseReleased(mousebuttonevent)) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, mousebuttonevent)) { return; } - } catch (Throwable t) { -@@ -146,6 +_,7 @@ - KeyMapping.click(mouseKey); + } catch (Throwable throwable) { +@@ -151,6 +_,7 @@ + KeyMapping.click(inputconstants$key); } } -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(buttonInfo, action); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo, action); } } -@@ -197,7 +_,9 @@ - if (this.minecraft.gui.screen() != null) { - double xm = this.getScaledXPos(this.minecraft.getWindow()); - double ym = this.getScaledYPos(this.minecraft.getWindow()); -- this.minecraft.gui.screen().mouseScrolled(xm, ym, scaledXOffset, scaledYOffset); -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.gui.screen(), xm, ym, scaledXOffset, scaledYOffset)) return; -+ if (this.minecraft.gui.screen().mouseScrolled(xm, ym, scaledXOffset, scaledYOffset)) return; -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.gui.screen(), xm, ym, scaledXOffset, scaledYOffset); - this.minecraft.gui.screen().afterMouseAction(); +@@ -202,7 +_,9 @@ + if (this.minecraft.screen != null) { + double d3 = this.getScaledXPos(this.minecraft.getWindow()); + double d4 = this.getScaledYPos(this.minecraft.getWindow()); +- 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) { - Vector2i wheelXY = this.scrollWheelHandler.onMouseScroll(scaledXOffset, scaledYOffset); -@@ -206,6 +_,7 @@ + Vector2i vector2i = this.scrollWheelHandler.onMouseScroll(d1, d2); +@@ -211,6 +_,7 @@ } - int wheel = wheelXY.y == 0 ? -wheelXY.x : wheelXY.y; -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, scaledXOffset, scaledYOffset)) return; + int i = vector2i.y == 0 ? -vector2i.x : vector2i.y; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return; if (this.minecraft.player.isSpectator()) { - if (this.minecraft.gui.hud.getSpectatorGui().isMenuActive()) { - this.minecraft.gui.hud.getSpectatorGui().onMouseScrolled(-wheel); -@@ -312,7 +_,7 @@ - double dy = getScaledYPos(window, this.accumulatedDY); + if (this.minecraft.gui.getSpectatorGui().isMenuActive()) { + this.minecraft.gui.getSpectatorGui().onMouseScrolled(-i); +@@ -315,7 +_,7 @@ + double d5 = getScaledYPos(window, this.accumulatedDY); try { -- screen.mouseDragged(new MouseButtonEvent(xm, ym, this.activeButton), dx, dy); -+ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(xm, ym, this.activeButton), dx, dy); - } catch (Throwable t) { - CrashReport report = CrashReport.forThrowable(t, "mouseDragged event handler"); - screen.fillCrashDetails(report); -@@ -397,6 +_,14 @@ +- screen.mouseDragged(new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); ++ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); + } catch (Throwable throwable) { + CrashReport crashreport1 = CrashReport.forThrowable(throwable, "mouseDragged event handler"); + screen.fillCrashDetails(crashreport1); +@@ -400,6 +_,14 @@ public double ypos() { return this.ypos; diff --git a/patches/minecraft/net/minecraft/client/Options.java.patch b/patches/minecraft/net/minecraft/client/Options.java.patch index 165bac1558..69156039ac 100644 --- a/patches/minecraft/net/minecraft/client/Options.java.patch +++ b/patches/minecraft/net/minecraft/client/Options.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/Options.java +++ b/net/minecraft/client/Options.java -@@ -986,6 +_,7 @@ +@@ -921,6 +_,7 @@ ); public boolean syncWrites; public boolean startedCleanly = true; @@ -8,15 +8,15 @@ public static boolean isSoundDeviceDefault(final String deviceName) { return deviceName.equals(""); -@@ -1474,6 +_,7 @@ +@@ -1396,6 +_,7 @@ } public Options(final Minecraft minecraft, final File workingDirectory) { + setForgeKeybindProperties(); this.minecraft = minecraft; this.optionsFile = new File(workingDirectory, "options.txt"); - boolean largeDistances = Runtime.getRuntime().maxMemory() >= 1000000000L; -@@ -1624,15 +_,28 @@ + boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L; +@@ -1548,15 +_,28 @@ this.startedCleanly = access.process("startedCleanly", this.startedCleanly); access.process("musicToast", this.musicToast); access.process("musicFrequency", this.musicFrequency); @@ -26,27 +26,27 @@ + // FORGE: split off to allow reloading keys after mod loading is done + private void processOptionsKeysOnly(Options.FieldAccess access) { - for (KeyMapping keyMapping : this.keyMappings) { -- String currentValue = keyMapping.saveString(); -+ String currentValue = keyMapping.saveString() + (keyMapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keyMapping.getKeyModifier() : ""); - String newValue = access.process("key_" + keyMapping.getName(), currentValue); - if (!currentValue.equals(newValue)) { - keyMapping.setKey(InputConstants.getKey(newValue)); -+ if (newValue.indexOf(':') != -1) { -+ String[] pts = newValue.split(":"); -+ keyMapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0])); + 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 = access.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(newValue)); ++ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1)); + } } } + } + private void processOptionsEnd(Options.FieldAccess access) { - for (SoundSource source : SoundSource.values()) { - access.process("soundCategory_" + source.getName(), this.soundSourceVolumes.get(source)); + for (SoundSource soundsource : SoundSource.values()) { + access.process("soundCategory_" + soundsource.getName(), this.soundSourceVolumes.get(soundsource)); } -@@ -1647,6 +_,10 @@ +@@ -1571,6 +_,10 @@ } public void load() { @@ -57,60 +57,64 @@ try { if (!this.optionsFile.exists()) { return; -@@ -1666,7 +_,8 @@ +@@ -1590,7 +_,8 @@ } - final CompoundTag options = this.dataFix(rawOptions); + final CompoundTag compoundtag1 = this.dataFix(compoundtag); - this.processOptions( + java.util.function.Consumer processor = limited ? this::processOptionsKeysOnly : this::processOptions; + processor.accept( new Options.FieldAccess() { - private @Nullable String getValue(final String name) { - Tag tag = options.get(name); -@@ -1748,6 +_,17 @@ + { + Objects.requireNonNull(Options.this); +@@ -1672,6 +_,17 @@ ); - options.getString("fullscreenResolution").ifPresent(fullscreenResolution -> this.fullscreenVideoModeString = fullscreenResolution); + compoundtag1.getString("fullscreenResolution").ifPresent(fullscreenResolution -> this.fullscreenVideoModeString = fullscreenResolution); KeyMapping.resetMapping(); + + if (limited) { + this.unknownKeys.clear(); + } else { + var knownKeys = Arrays.stream(this.keyMappings).map(k -> "key_" + k.getName()).collect(Collectors.toSet()); -+ for (var entry : options.entrySet()) { ++ for (var entry : compoundtag1.entrySet()) { + if (entry.getKey().startsWith("key_") && entry.getValue().asString().isPresent() && !knownKeys.contains(entry.getKey())) + this.unknownKeys.put(entry.getKey(), entry.getValue().asString().get()); + } + } + - } catch (Exception e) { - LOGGER.error("Failed to load options", e); + } catch (Exception exception) { + LOGGER.error("Failed to load options", (Throwable)exception); } -@@ -1778,9 +_,11 @@ +@@ -1699,6 +_,7 @@ public void save() { - try (final PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) { - writer.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version()); + try (final PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) { + printwriter.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version()); + var seen = new java.util.HashSet(); this.processOptions( new Options.FieldAccess() { + { +@@ -1706,6 +_,7 @@ + } + public void writePrefix(final String name) { + seen.add(name); - writer.print(name); - writer.print(':'); + printwriter.print(name); + printwriter.print(':'); } -@@ -1836,6 +_,12 @@ - if (fullscreenVideoModeString != null) { - writer.println("fullscreenResolution:" + fullscreenVideoModeString); +@@ -1761,6 +_,12 @@ + if (s != null) { + printwriter.println("fullscreenResolution:" + s); } + // Forge add any unknown keys so that Mods can add keybindings between vanilla loading/saving its config. + for (var entry : this.unknownKeys.entrySet()) { + if (!seen.contains(entry.getKey())) -+ writer.println(entry.getKey() + ":" + entry.getValue()); ++ printwriter.println(entry.getKey() + ":" + entry.getValue()); + } + - } catch (Exception e) { - LOGGER.error("Failed to save options", e); + } catch (Exception exception) { + LOGGER.error("Failed to save options", (Throwable)exception); } -@@ -1873,6 +_,7 @@ +@@ -1798,6 +_,7 @@ } public void broadcastOptions() { @@ -118,7 +122,7 @@ if (this.minecraft.player != null) { this.minecraft.player.connection.broadcastClientInformation(this.buildPlayerInformation()); } -@@ -1986,6 +_,23 @@ +@@ -1915,6 +_,23 @@ public static Component genericValueLabel(final Component caption, final int value) { return genericValueLabel(caption, Component.literal(Integer.toString(value))); diff --git a/patches/minecraft/net/minecraft/client/Screenshot.java.patch b/patches/minecraft/net/minecraft/client/Screenshot.java.patch index b5df8b3e6a..4a51109d7f 100644 --- a/patches/minecraft/net/minecraft/client/Screenshot.java.patch +++ b/patches/minecraft/net/minecraft/client/Screenshot.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/Screenshot.java +++ b/net/minecraft/client/Screenshot.java -@@ -53,14 +_,24 @@ - file = new File(picDir, forceName); +@@ -45,6 +_,13 @@ + file2 = new File(file1, forceName); } -+ var event = new net.minecraftforge.client.event.ScreenshotEvent(image, file); ++ var event = new net.minecraftforge.client.event.ScreenshotEvent(image, file2); + if (net.minecraftforge.client.event.ScreenshotEvent.BUS.post(event)) { + callback.accept(event.getCancelMessage()); + return; @@ -14,17 +14,19 @@ Util.ioPool() .execute( () -> { - try (image) { -- image.writeToFile(file); -- Component component = Component.literal(file.getName()) -+ image.writeToFile(outputFile); -+ Component component = Component.literal(outputFile.getName()) - .withStyle(ChatFormatting.UNDERLINE) -- .withStyle(s -> s.withClickEvent(new ClickEvent.OpenFile(file.getAbsoluteFile()))); -+ .withStyle(s -> s.withClickEvent(new ClickEvent.OpenFile(outputFile.getAbsoluteFile()))); -+ if (event.getResultMessage() != null) -+ callback.accept(event.getResultMessage()); -+ else - callback.accept(Component.translatable("screenshot.success", component)); - } catch (Exception e) { - LOGGER.warn("Couldn't save screenshot", e); +@@ -52,10 +_,13 @@ + NativeImage nativeimage = image; + + try { +- image.writeToFile(file2); +- Component component = Component.literal(file2.getName()) ++ image.writeToFile(outputFile); ++ Component component = Component.literal(outputFile.getName()) + .withStyle(ChatFormatting.UNDERLINE) + .withStyle(s -> s.withClickEvent(new ClickEvent.OpenFile(file2.getAbsoluteFile()))); ++ if (event.getResultMessage() != null) ++ callback.accept(event.getResultMessage()); ++ else + callback.accept(Component.translatable("screenshot.success", component)); + } catch (Throwable throwable1) { + if (image != null) { 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 7f5ef9ee48..196aa01623 100644 --- a/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch +++ b/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/client/color/block/BlockColors.java +++ b/net/minecraft/client/color/block/BlockColors.java @@ -45,6 +_,7 @@ - colors.register(List.of(BlockTintSources.constant(-2046180)), Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM); - colors.register(List.of(BlockTintSources.stem()), Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); - colors.register(List.of(BlockTintSources.constant(-9321636, -14647248)), Blocks.LILY_PAD); -+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(colors); - return colors; + blockcolors.register(List.of(BlockTintSources.constant(-2046180)), Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM); + blockcolors.register(List.of(BlockTintSources.stem()), Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); + blockcolors.register(List.of(BlockTintSources.constant(-9321636, -14647248)), Blocks.LILY_PAD); ++ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors); + return blockcolors; } @@ -57,6 +_,8 @@ - return layer >= layers.size() ? null : layers.get(layer); + return layer >= list.size() ? null : list.get(layer); } + /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */ diff --git a/patches/minecraft/net/minecraft/client/data/Main.java.patch b/patches/minecraft/net/minecraft/client/data/Main.java.patch index e270fa81b4..78a59e26e1 100644 --- a/patches/minecraft/net/minecraft/client/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/client/data/Main.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/client/data/Main.java +++ b/net/minecraft/client/data/Main.java @@ -28,13 +_,18 @@ - OptionSpec clientOption = parser.accepts("client", "Include client generators"); - OptionSpec allOption = parser.accepts("all", "Include all generators"); - OptionSpec outputOption = parser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); -+ OptionSpec inputSpec = parser.accepts("input", "Input folder").withRequiredArg(); -+ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(parser, true); - OptionSet optionSet = parser.parse(args); -- if (!optionSet.has(helpOption) && optionSet.hasOptions()) { -+ if (!optionSet.has(helpOption) && optionSet.hasOptions() && loader.hasArgs(optionSet)) { -+ var input = optionSet.valuesOf(inputSpec).stream().map(Paths::get).toList(); - Path output = Paths.get(outputOption.value(optionSet)); - boolean allOptions = optionSet.has(allOption); - boolean client = allOptions || optionSet.has(clientOption); + OptionSpec optionspec1 = optionparser.accepts("client", "Include client generators"); + OptionSpec optionspec2 = optionparser.accepts("all", "Include all generators"); + OptionSpec optionspec3 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); ++ OptionSpec inputSpec = optionparser.accepts("input", "Input folder").withRequiredArg(); ++ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(optionparser, true); + OptionSet optionset = optionparser.parse(args); +- if (!optionset.has(optionspec) && optionset.hasOptions()) { ++ if (!optionset.has(optionspec) && optionset.hasOptions() && loader.hasArgs(optionset)) { ++ var input = optionset.valuesOf(inputSpec).stream().map(Paths::get).toList(); + Path path = Paths.get(optionspec3.value(optionset)); + boolean flag = optionset.has(optionspec2); + boolean flag1 = flag || optionset.has(optionspec1); Bootstrap.bootStrap(); ClientBootstrap.bootstrap(); -+ if (!loader.run(optionSet, output, input, allOptions, client, allOptions, allOptions)) ++ if (!loader.run(optionset, path, input, flag, flag1, flag, flag)) + return; - DataGenerator generator = new DataGenerator.Cached(output, SharedConstants.getCurrentVersion(), true); - addClientProviders(generator, client); - generator.run(); + DataGenerator datagenerator = new DataGenerator.Cached(path, SharedConstants.getCurrentVersion(), true); + addClientProviders(datagenerator, flag1); + datagenerator.run(); diff --git a/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch b/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch index bc85a58c04..a69c0a5c8c 100644 --- a/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch +++ b/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/data/models/ItemModelGenerators.java +++ b/net/minecraft/client/data/models/ItemModelGenerators.java -@@ -868,6 +_,9 @@ +@@ -922,6 +_,9 @@ this.declareCustomModelItem(Items.COD); this.declareCustomModelItem(Items.FEATHER); this.declareCustomModelItem(Items.LEAD); diff --git a/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch b/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch index ddd4b0600a..381d3e129f 100644 --- a/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch +++ b/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/client/data/models/ModelProvider.java +++ b/net/minecraft/client/data/models/ModelProvider.java -@@ -43,11 +_,11 @@ +@@ -44,11 +_,11 @@ @Override public CompletableFuture run(final CachedOutput cache) { -- ModelProvider.ItemInfoCollector itemModels = new ModelProvider.ItemInfoCollector(); -- ModelProvider.BlockStateGeneratorCollector blockStateGenerators = new ModelProvider.BlockStateGeneratorCollector(); -+ ModelProvider.ItemInfoCollector itemModels = new ModelProvider.ItemInfoCollector(this::getKnownItems); -+ ModelProvider.BlockStateGeneratorCollector blockStateGenerators = new ModelProvider.BlockStateGeneratorCollector(this::getKnownBlocks); - ModelProvider.SimpleModelCollector simpleModels = new ModelProvider.SimpleModelCollector(); -- new BlockModelGenerators(blockStateGenerators, itemModels, simpleModels).run(); -- new ItemModelGenerators(itemModels, simpleModels).run(); -+ getBlockModelGenerators(blockStateGenerators, itemModels, simpleModels).run(); -+ getItemModelGenerators(itemModels, simpleModels).run(); - blockStateGenerators.validate(); - itemModels.finalizeAndValidate(); +- ModelProvider.ItemInfoCollector modelprovider$iteminfocollector = new ModelProvider.ItemInfoCollector(); +- ModelProvider.BlockStateGeneratorCollector modelprovider$blockstategeneratorcollector = new ModelProvider.BlockStateGeneratorCollector(); ++ ModelProvider.ItemInfoCollector modelprovider$iteminfocollector = new ModelProvider.ItemInfoCollector(this::getKnownItems); ++ ModelProvider.BlockStateGeneratorCollector modelprovider$blockstategeneratorcollector = new ModelProvider.BlockStateGeneratorCollector(this::getKnownBlocks); + ModelProvider.SimpleModelCollector modelprovider$simplemodelcollector = new ModelProvider.SimpleModelCollector(); +- new BlockModelGenerators(modelprovider$blockstategeneratorcollector, modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); +- new ItemModelGenerators(modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); ++ getBlockModelGenerators(modelprovider$blockstategeneratorcollector, modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); ++ getItemModelGenerators(modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); + modelprovider$blockstategeneratorcollector.validate(); + modelprovider$iteminfocollector.finalizeAndValidate(); return CompletableFuture.allOf( -@@ -57,6 +_,22 @@ +@@ -58,6 +_,22 @@ ); } @@ -39,7 +39,7 @@ @Override public final String getName() { return "Model Definitions"; -@@ -65,6 +_,15 @@ +@@ -66,6 +_,15 @@ @OnlyIn(Dist.CLIENT) public static class BlockStateGeneratorCollector implements Consumer { private final Map generators = new HashMap<>(); @@ -55,17 +55,17 @@ public void accept(final BlockModelDefinitionGenerator generator) { Block block = generator.block(); -@@ -75,8 +_,7 @@ +@@ -76,8 +_,7 @@ } public void validate() { -- List missingDefinitions = BuiltInRegistries.BLOCK +- List list = BuiltInRegistries.BLOCK - .listElements() -+ List missingDefinitions = known.get().map(Block::builtInRegistryHolder) ++ List list = known.get().map(Block::builtInRegistryHolder) .filter(e -> !this.generators.containsKey(e.value())) .map(e -> e.key().identifier()) .toList(); -@@ -96,6 +_,15 @@ +@@ -97,6 +_,15 @@ public static class ItemInfoCollector implements ItemModelOutput { private final Map itemInfos = new HashMap<>(); private final Map copies = new HashMap<>(); @@ -81,7 +81,7 @@ @Override public void accept(final Item item, final ItemModel.Unbaked model, final ClientItem.Properties properties) { -@@ -114,7 +_,7 @@ +@@ -115,7 +_,7 @@ this.copies.put(acceptor, donor); } @@ -89,23 +89,23 @@ + public void generateDefaultBlockModels() { BuiltInRegistries.ITEM.forEach(item -> { if (!this.copies.containsKey(item)) { - if (item instanceof BlockItem blockItem && !this.itemInfos.containsKey(blockItem)) { -@@ -123,6 +_,8 @@ + if (item instanceof BlockItem blockitem && !this.itemInfos.containsKey(blockitem)) { +@@ -124,6 +_,8 @@ } } }); + } + public void finalizeAndValidate() { this.copies.forEach((acceptor, donor) -> { - ClientItem donorInfo = this.itemInfos.get(donor); - if (donorInfo == null) { -@@ -131,8 +_,8 @@ - - this.register(acceptor, donorInfo); + ClientItem clientitem = this.itemInfos.get(donor); + if (clientitem == null) { +@@ -132,8 +_,8 @@ + this.register(acceptor, clientitem); + } }); -- List missingDefinitions = BuiltInRegistries.ITEM +- List list = BuiltInRegistries.ITEM - .listElements() -+ List missingDefinitions = known.get() ++ List list = known.get() + .map(item -> item.builtInRegistryHolder()) .filter(e -> !this.itemInfos.containsKey(e.value())) .map(e -> e.key().identifier()) diff --git a/patches/minecraft/net/minecraft/client/gui/Font.java.patch b/patches/minecraft/net/minecraft/client/gui/Font.java.patch index 1749a11c05..55ffbfcb53 100644 --- a/patches/minecraft/net/minecraft/client/gui/Font.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/Font.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/Font.java +++ b/net/minecraft/client/gui/Font.java -@@ -28,7 +_,7 @@ +@@ -33,7 +_,7 @@ import org.jspecify.annotations.Nullable; @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch index 8aeebcebc3..0515b1e903 100644 --- a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch @@ -1,75 +1,103 @@ --- a/net/minecraft/client/gui/Gui.java +++ b/net/minecraft/client/gui/Gui.java -@@ -64,7 +_,7 @@ - import org.slf4j.Logger; +@@ -150,7 +_,7 @@ + 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; +@@ -192,6 +_,7 @@ + () -> new JumpableVehicleBarRenderer(minecraft) + ); + this.resetTitleTimes(); ++ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.init(this, minecraft); + } - @OnlyIn(Dist.CLIENT) --public class Gui { -+public class Gui extends net.minecraftforge.client.gui.overlay.ForgeLayerInstance { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final Component SOCIAL_INTERACTIONS_NOT_AVAILABLE = Component.translatable("multiplayer.socialInteractions.not_available"); - public static final Component SAVING_LEVEL = Component.translatable("menu.savingLevel"); -@@ -80,6 +_,7 @@ - private @Nullable TutorialToast socialInteractionsToast; + public void resetTitleTimes() { +@@ -202,6 +_,10 @@ - public Gui(final Minecraft minecraft, final Hud hud, final GuiRenderState guiRenderState) { -+ super(minecraft); - this.minecraft = minecraft; - this.hud = hud; - this.splashManager = new SplashManager(minecraft.getUser()); -@@ -175,7 +_,7 @@ - profiler.push("screen"); - - try { -- this.screen.extractRenderStateWithTooltipAndSubtitles(graphics, xMouse, yMouse, deltaTracker.getGameTimeDeltaTicks()); -+ drawScreen(graphics, xMouse, yMouse, deltaTracker.getRealtimeDeltaTicks()); - } catch (Throwable t) { - CrashReport report = CrashReport.forThrowable(t, "Rendering screen"); - CrashReportCategory category = report.addCategory("Screen render details"); -@@ -224,12 +_,6 @@ - LOGGER.error("setScreen called from non-game thread"); - } - -- if (this.screen != null) { -- this.screen.removed(); -- } else { -- this.minecraft.setLastInputType(InputType.NONE); -- } -- - if (screen == null) { - if (this.clientLevelTeardownInProgress) { - throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); -@@ -248,6 +_,22 @@ - } - } - -+ clearLayers(); -+ Screen old = this.screen; -+ if (screen != null) { -+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, screen); -+ if (event == null) return; -+ screen = event; -+ } -+ -+ if (screen != old) { -+ if (old != null) { -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old); -+ old.removed(); -+ } else { -+ this.minecraft.setLastInputType(InputType.NONE); + public void extractRenderState(final GuiGraphicsExtractor graphics, final DeltaTracker deltaTracker) { + if (!(this.minecraft.screen instanceof LevelLoadingScreen)) { ++ if (Boolean.valueOf(true)) { ++ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.extractRenderState(graphics, deltaTracker); ++ return; + } -+ } - this.screen = screen; - if (this.screen != null) { - this.screen.added(); -@@ -465,5 +_,10 @@ + if (!this.minecraft.options.hideGui) { + this.extractCameraOverlays(graphics, deltaTracker); + this.extractCrosshair(graphics, deltaTracker); +@@ -385,7 +_,7 @@ + int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window)); + int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window)); + graphics.nextStratum(); +- this.chat.extractRenderState(graphics, this.getFont(), this.tickCount, i, j, ChatComponent.DisplayMode.BACKGROUND, false); ++ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(graphics, this.chat, window, i, j, this.tickCount, this.getFont()); + } + } + +@@ -475,6 +_,8 @@ + + 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 k = graphics.guiWidth(); + int l = 1; +@@ -505,6 +_,7 @@ } - ) - ); + } + ++ if (renderer.extractGuiIcon(mobeffectinstance, this, graphics, k, l, 0, f)) continue; + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(holder), k + 3, l + 3, 18, 18, ARGB.white(f)); + } + } +@@ -605,6 +_,10 @@ + } + + public void extractSelectedItemName(final GuiGraphicsExtractor graphics) { ++ renderSelectedItemName(graphics, 0); + } + -+ @Override -+ protected void setScreenInternal(Screen value) { -+ this.screen = value; ++ public void renderSelectedItemName(final GuiGraphicsExtractor graphics, int yShift) { + if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { + MutableComponent mutablecomponent = Component.empty() + .append(this.lastToolHighlight.getHoverName()) +@@ -613,9 +_,13 @@ + mutablecomponent.withStyle(ChatFormatting.ITALIC); + } + +- int i = this.getFont().width(mutablecomponent); ++ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent); ++ 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) ++ font = this.getFont(); ++ int i = font.width(highlightTip); + int j = (graphics.guiWidth() - i) / 2; +- int k = graphics.guiHeight() - 59; ++ int k = graphics.guiHeight() - Math.max(yShift, 59); + if (!this.minecraft.gameMode.canHurtPlayer()) { + k += 14; + } +@@ -626,7 +_,7 @@ + } + + if (l > 0) { +- graphics.textWithBackdrop(this.getFont(), mutablecomponent, j, k, i, ARGB.white(l)); ++ graphics.textWithBackdrop(font, highlightTip, j, k, i, ARGB.white(l)); + } + } } - } +@@ -1165,7 +_,9 @@ + this.toolHighlightTimer = 0; + } else if (this.lastToolHighlight.isEmpty() + || !itemstack.is(this.lastToolHighlight.getItem()) +- || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) { ++ || !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/GuiGraphicsExtractor.java.patch b/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch index 3f0f48e0ba..3022b44b22 100644 --- a/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/GuiGraphicsExtractor.java +++ b/net/minecraft/client/gui/GuiGraphicsExtractor.java -@@ -85,7 +_,7 @@ +@@ -88,7 +_,7 @@ import org.jspecify.annotations.Nullable; @OnlyIn(Dist.CLIENT) @@ -9,15 +9,15 @@ private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2; private final Minecraft minecraft; private final Matrix3x2fStack pose; -@@ -912,6 +_,7 @@ - CrashReport report = CrashReport.forThrowable(t, "Rendering item"); - CrashReportCategory category = report.addCategory("Item being rendered"); - category.setDetail("Item Type", () -> String.valueOf(itemStack.getItem())); -+ category.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); - category.setDetail("Item Components", () -> String.valueOf(itemStack.getComponents())); - category.setDetail("Item Foil", () -> String.valueOf(itemStack.hasFoil())); - throw new ReportedException(report); -@@ -938,6 +_,7 @@ +@@ -867,6 +_,7 @@ + CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); + crashreportcategory.setDetail("Item Type", () -> String.valueOf(itemStack.getItem())); ++ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); + crashreportcategory.setDetail("Item Components", () -> String.valueOf(itemStack.getComponents())); + crashreportcategory.setDetail("Item Foil", () -> String.valueOf(itemStack.hasFoil())); + throw new ReportedException(crashreport); +@@ -893,6 +_,7 @@ this.itemCooldown(itemStack, x, y); this.itemCount(font, itemStack, x, y, countText); this.pose.popMatrix(); @@ -25,7 +25,7 @@ } } -@@ -1106,16 +_,25 @@ +@@ -1069,16 +_,25 @@ this.setTooltipForNextFrame(this.minecraft.font, formattedCharSequences, DefaultTooltipPositioner.INSTANCE, x, y, false); } @@ -51,20 +51,17 @@ public void setTooltipForNextFrame( final Font font, final List texts, -@@ -1124,11 +_,7 @@ +@@ -1087,8 +_,7 @@ final int yo, final @Nullable Identifier style ) { -- List components = texts.stream() -- .map(Component::getVisualOrderText) -- .map(ClientTooltipComponent::create) -- .collect(Util.toMutableList()); -- optionalImage.ifPresent(image -> components.add(components.isEmpty() ? 0 : 1, ClientTooltipComponent.create(image))); -+ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, texts, optionalImage, xo, guiWidth(), guiHeight(), font); - this.setTooltipForNextFrameInternal(font, components, xo, yo, DefaultTooltipPositioner.INSTANCE, style, false); +- List list = texts.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList()); +- optionalImage.ifPresent(image -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(image))); ++ List list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, texts, optionalImage, xo, guiWidth(), guiHeight(), font); + this.setTooltipForNextFrameInternal(font, list, xo, yo, DefaultTooltipPositioner.INSTANCE, style, false); } -@@ -1156,7 +_,22 @@ +@@ -1116,7 +_,22 @@ } public void setComponentTooltipForNextFrame(final Font font, final List lines, final int xo, final int yo) { @@ -88,7 +85,7 @@ } public void setComponentTooltipForNextFrame(final Font font, final List lines, final int xo, final int yo, final @Nullable Identifier style) { -@@ -1207,10 +_,16 @@ +@@ -1167,10 +_,16 @@ ) { if (!lines.isEmpty()) { if (this.deferredTooltip == null || replaceExisting) { @@ -106,7 +103,7 @@ public void tooltip( final Font font, -@@ -1218,13 +_,16 @@ +@@ -1178,13 +_,16 @@ final int xo, final int yo, final ClientTooltipPositioner positioner, @@ -116,48 +113,48 @@ ) { + var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(itemstack, this, xo, yo, guiWidth(), guiHeight(), lines, font, positioner, style); + if (preEvent == null) return; - int textWidth = 0; - int tempHeight = lines.size() == 1 ? -2 : 0; + int i = 0; + int j = lines.size() == 1 ? -2 : 0; - for (ClientTooltipComponent line : lines) { -- int lineWidth = line.getWidth(font); -+ int lineWidth = line.getWidth(preEvent.getFont()); - if (lineWidth > textWidth) { - textWidth = lineWidth; + for (ClientTooltipComponent clienttooltipcomponent : lines) { +- int k = clienttooltipcomponent.getWidth(font); ++ int k = clienttooltipcomponent.getWidth(preEvent.getFont()); + if (k > i) { + i = k; } -@@ -1234,25 +_,25 @@ +@@ -1194,25 +_,25 @@ - int w = textWidth; - int h = tempHeight; -- Vector2ic positionedTooltip = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), xo, yo, w, h); -+ Vector2ic positionedTooltip = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), w, h); - int x = positionedTooltip.x(); - int y = positionedTooltip.y(); + int l1 = i; + int i2 = j; +- Vector2ic vector2ic = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), xo, yo, i, j); ++ Vector2ic vector2ic = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i, j); + int l = vector2ic.x(); + int i1 = vector2ic.y(); this.pose.pushMatrix(); -- TooltipRenderUtil.extractTooltipBackground(this, x, y, w, h, style); -+ TooltipRenderUtil.extractTooltipBackground(this, x, y, w, h, preEvent.getBackground()); - int localY = y; +- TooltipRenderUtil.extractTooltipBackground(this, l, i1, i, j, style); ++ TooltipRenderUtil.extractTooltipBackground(this, l, i1, i, j, preEvent.getBackground()); + int j1 = i1; - for (int i = 0; i < lines.size(); i++) { - ClientTooltipComponent line = lines.get(i); -- line.extractText(this, font, x, localY); -- localY += line.getHeight(font) + (i == 0 ? 2 : 0); -+ line.extractText(this, preEvent.getFont(), x, localY); -+ localY += line.getHeight(preEvent.getFont()) + (i == 0 ? 2 : 0); + for (int k1 = 0; k1 < lines.size(); k1++) { + ClientTooltipComponent clienttooltipcomponent1 = lines.get(k1); +- clienttooltipcomponent1.extractText(this, font, l, j1); +- j1 += clienttooltipcomponent1.getHeight(font) + (k1 == 0 ? 2 : 0); ++ clienttooltipcomponent1.extractText(this, preEvent.getFont(), l, j1); ++ j1 += clienttooltipcomponent1.getHeight(preEvent.getFont()) + (k1 == 0 ? 2 : 0); } - localY = y; + j1 = i1; - for (int i = 0; i < lines.size(); i++) { - ClientTooltipComponent line = lines.get(i); -- line.extractImage(font, x, localY, w, h, this); -- localY += line.getHeight(font) + (i == 0 ? 2 : 0); -+ line.extractImage(preEvent.getFont(), x, localY, w, h, this); -+ localY += line.getHeight(preEvent.getFont()) + (i == 0 ? 2 : 0); + for (int j2 = 0; j2 < lines.size(); j2++) { + ClientTooltipComponent clienttooltipcomponent2 = lines.get(j2); +- clienttooltipcomponent2.extractImage(font, l, j1, l1, i2, this); +- j1 += clienttooltipcomponent2.getHeight(font) + (j2 == 0 ? 2 : 0); ++ clienttooltipcomponent2.extractImage(preEvent.getFont(), l, j1, l1, i2, this); ++ j1 += clienttooltipcomponent2.getHeight(preEvent.getFont()) + (j2 == 0 ? 2 : 0); } this.pose.popMatrix(); -@@ -1326,6 +_,14 @@ +@@ -1287,6 +_,14 @@ private ActiveTextCollector.Parameters createDefaultTextParameters(final float opacity) { return new ActiveTextCollector.Parameters(new Matrix3x2f(this.pose), opacity, this.scissorStack.peek()); diff --git a/patches/minecraft/net/minecraft/client/gui/Hud.java.patch b/patches/minecraft/net/minecraft/client/gui/Hud.java.patch deleted file mode 100644 index 52f4edb8f3..0000000000 --- a/patches/minecraft/net/minecraft/client/gui/Hud.java.patch +++ /dev/null @@ -1,116 +0,0 @@ ---- a/net/minecraft/client/gui/Hud.java -+++ b/net/minecraft/client/gui/Hud.java -@@ -156,7 +_,7 @@ - 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; -@@ -198,6 +_,7 @@ - () -> new JumpableVehicleBar(minecraft) - ); - this.resetTitleTimes(); -+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.init(this, minecraft); - } - - public void registerReloadListeners(final ReloadableResourceManager resourceManager) { -@@ -221,6 +_,10 @@ - public void extractRenderState(final GuiGraphicsExtractor graphics, final DeltaTracker deltaTracker) { - this.minecraft.gameRenderer.gameRenderState().guiRenderState.isHudHidden = this.isHidden; - if (!(this.minecraft.gui.screen() instanceof LevelLoadingScreen)) { -+ if (Boolean.valueOf(true)) { -+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.extractRenderState(graphics, deltaTracker); -+ return; -+ } - if (!this.isHidden) { - this.extractCameraOverlays(graphics, deltaTracker); - this.extractCrosshair(graphics, deltaTracker); -@@ -404,7 +_,7 @@ - int mouseX = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window)); - int mouseY = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window)); - graphics.nextStratum(); -- this.chat.extractRenderState(graphics, this.getFont(), this.tickCount, mouseX, mouseY, ChatComponent.DisplayMode.BACKGROUND, false); -+ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(graphics, this.chat, window, mouseX, mouseY, this.tickCount, this.getFont()); - } - } - -@@ -497,6 +_,8 @@ - - for (MobEffectInstance instance : Ordering.natural().reverse().sortedCopy(activeEffects)) { - Holder effect = instance.getEffect(); -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(instance); -+ if (!renderer.isVisibleInGui(instance)) continue; - if (instance.showIcon()) { - int x = graphics.guiWidth(); - int y = 1; -@@ -527,6 +_,7 @@ - } - } - -+ if (renderer.extractGuiIcon(instance, this, graphics, x, y, 0, alpha)) continue; - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(effect), x + 3, y + 3, 18, 18, ARGB.white(alpha)); - } - } -@@ -629,15 +_,37 @@ - } - - public void extractSelectedItemName(final GuiGraphicsExtractor graphics) { -+ renderSelectedItemName(graphics, 0); -+ } -+ -+ // Forge: Maintain vanilla parity during FLD#BACKGROUND -+ public final void updateContextualInfo(final GuiGraphicsExtractor graphics, DeltaTracker deltaTracker) { -+ var nextContextualInfo = this.nextContextualInfoState(); -+ if (nextContextualInfo != this.contextualInfoBar.getFirst()) { -+ this.contextualInfoBar = Pair.of(nextContextualInfo, this.contextualInfoBars.get(nextContextualInfo).get()); -+ } -+ -+ this.contextualInfoBar.getSecond().extractBackground(graphics, deltaTracker); -+ } -+ // Forge: Same as above but for FLD#CONTEXTUAL_INFO -+ public final void extractContextualInfoState(final GuiGraphicsExtractor graphics, DeltaTracker deltaTracker) { -+ this.contextualInfoBar.getSecond().extractRenderState(graphics, deltaTracker); -+ } -+ -+ public void renderSelectedItemName(final GuiGraphicsExtractor graphics, int yShift) { - if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { - MutableComponent str = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color()); - if (this.lastToolHighlight.has(DataComponents.CUSTOM_NAME)) { - str.withStyle(ChatFormatting.ITALIC); - } - -- int strWidth = this.getFont().width(str); -+ Component highlightTip = this.lastToolHighlight.getHighlightTip(str); -+ 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) -+ font = this.getFont(); -+ int strWidth = font.width(highlightTip); - int x = (graphics.guiWidth() - strWidth) / 2; -- int y = graphics.guiHeight() - 59; -+ int y = graphics.guiHeight() - Math.max(yShift, 59); - if (!this.minecraft.gameMode.canHurtPlayer()) { - y += 14; - } -@@ -648,7 +_,7 @@ - } - - if (alpha > 0) { -- graphics.textWithBackdrop(this.getFont(), str, x, y, strWidth, ARGB.white(alpha)); -+ graphics.textWithBackdrop(font, highlightTip, x, y, strWidth, ARGB.white(alpha)); - } - } - } -@@ -1216,7 +_,9 @@ - this.toolHighlightTimer = 0; - } else if (this.lastToolHighlight.isEmpty() - || !selected.is(this.lastToolHighlight.getItem()) -- || !selected.getHoverName().equals(this.lastToolHighlight.getHoverName())) { -+ || !selected.getHoverName().equals(this.lastToolHighlight.getHoverName()) -+ || !selected.getHighlightTip(selected.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/components/AbstractWidget.java.patch b/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch index a836cbc212..7fa0c6a30d 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/AbstractWidget.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/components/AbstractWidget.java +++ b/net/minecraft/client/gui/components/AbstractWidget.java -@@ -225,6 +_,23 @@ +@@ -221,6 +_,23 @@ this.focused = focused; } 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 99351df883..bdd5333e13 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 @@ -68,13 +_,16 @@ - for (LerpingBossEvent event : this.events.values()) { - int xLeft = screenWidth / 2 - 91; - int yo = yOffset; -+ var progressEvent = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(graphics, this.minecraft.getWindow(), event, xLeft, yOffset, 10 + this.minecraft.font.lineHeight); -+ if (progressEvent != null) { - this.extractBar(graphics, xLeft, yo, event); - Component msg = event.getName(); - int width = this.minecraft.font.width(msg); - int x = screenWidth / 2 - width / 2; - int y = yo - 9; - graphics.text(this.minecraft.font, msg, x, y, -1); -- yOffset += 10 + 9; + + for (LerpingBossEvent lerpingbossevent : this.events.values()) { + int k = i / 2 - 91; ++ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(graphics, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight); ++ if (event != null) { + this.extractBar(graphics, k, j, lerpingbossevent); + Component component = lerpingbossevent.getName(); + int l = this.minecraft.font.width(component); + int i1 = i / 2 - l / 2; + int j1 = j - 9; + graphics.text(this.minecraft.font, component, i1, j1, -1); +- j += 10 + 9; + } -+ yOffset += progressEvent.getIncrement(); - if (yOffset >= graphics.guiHeight() / 3) { ++ j += event.getIncrement(); + if (j >= graphics.guiHeight() / 3) { break; } diff --git a/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch b/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch index f4e973747c..4021699366 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch @@ -2,9 +2,9 @@ +++ b/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java @@ -29,6 +_,7 @@ if (entity != null) { - result.add(ChatFormatting.UNDERLINE + "Targeted Entity"); - result.add(entity.typeHolder().getRegisteredName()); -+ entity.getType().builtInRegistryHolder().tags().forEach(t -> result.add("#" + t.location())); + list.add(ChatFormatting.UNDERLINE + "Targeted Entity"); + list.add(entity.typeHolder().getRegisteredName()); ++ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location())); } - displayer.addToGroup(GROUP, result); + displayer.addToGroup(GROUP, list); diff --git a/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastManager.java.patch b/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastManager.java.patch index c24fc060da..6b3471dc2e 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastManager.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/toasts/ToastManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/components/toasts/ToastManager.java +++ b/net/minecraft/client/gui/components/toasts/ToastManager.java -@@ -142,6 +_,7 @@ +@@ -143,6 +_,7 @@ } public void addToast(final Toast toast) { diff --git a/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch b/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch index 3a38a98fa3..9437099d7e 100644 --- a/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/render/GuiRenderer.java +++ b/net/minecraft/client/gui/render/GuiRenderer.java -@@ -110,6 +_,7 @@ - builder.put((Class)pictureInPictureRenderer.getRenderStateClass(), pictureInPictureRenderer); +@@ -131,6 +_,7 @@ + builder.put((Class)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer); } -+ net.minecraftforge.client.ForgeHooksClient.onRegisterPictureInPictureRenderers(pictureInPictureRenderers, builder); ++ net.minecraftforge.client.ForgeHooksClient.onRegisterPictureInPictureRenderers(pictureInPictureRenderers, bufferSource, builder); this.pictureInPictureRenderers = builder.buildOrThrow(); } 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 44572e9d4b..2458106002 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/ChatScreen.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/screens/ChatScreen.java +++ b/net/minecraft/client/gui/screens/ChatScreen.java -@@ -141,6 +_,7 @@ - this.handleChatInput(this.input.getValue(), true); - if (this.closeOnSubmit) { - this.exitReason = ChatScreen.ExitReason.DONE; -+ if (this.minecraft.gui.screen() == this) // FORGE: Prevent closing the screen if another screen has been opened. - this.minecraft.gui.setScreen(null); - } else { - this.input.setValue(""); +@@ -139,6 +_,7 @@ + this.handleChatInput(this.input.getValue(), true); + if (this.closeOnSubmit) { + this.exitReason = ChatScreen.ExitReason.DONE; ++ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened. + this.minecraft.setScreen(null); + } else { + this.input.setValue(""); 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 cc71b72a4e..3e3207b92d 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 -@@ -109,6 +_,8 @@ +@@ -114,6 +_,8 @@ } - if (resolvedAddress.isEmpty()) { + if (optional.isEmpty()) { + ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", hostAndPort.getHost()); + net.minecraftforge.network.DualStackUtils.logInitialPreferences(); minecraft.execute( - () -> minecraft.gui - .setScreen( + () -> minecraft.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 a63c4a7bd0..e8ad174ffb 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch @@ -8,24 +8,24 @@ + @Override public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) { - int width = graphics.guiWidth(); + int i = graphics.guiWidth(); @@ -103,6 +_,7 @@ - logoAlpha = 1.0F; + f2 = 1.0F; } -+ if (extractContentRenderState(graphics, logoAlpha)) { - int contentX = (int)(graphics.guiWidth() * 0.5); - int logoY = (int)(graphics.guiHeight() * 0.5); - double logoHeight = Math.min(graphics.guiWidth() * 0.75, graphics.guiHeight()) * 0.25; -@@ -148,6 +_,7 @@ - graphics, width / 2 - logoWidthHalf, barY - 5, width / 2 + logoWidthHalf, barY + 5, 1.0F - Mth.clamp(fadeOutAnim, 0.0F, 1.0F) - ); ++ if (extractContentRenderState(graphics, f2)) { + int k2 = (int)(graphics.guiWidth() * 0.5); + int i1 = (int)(graphics.guiHeight() * 0.5); + double d0 = Math.min(graphics.guiWidth() * 0.75, (double)graphics.guiHeight()) * 0.25; +@@ -118,6 +_,7 @@ + if (f < 1.0F) { + this.extractProgressBar(graphics, i / 2 - k1, i2 - 5, i / 2 + k1, i2 + 5, 1.0F - Mth.clamp(f, 0.0F, 1.0F)); } + } - if (fadeOutAnim >= 2.0F) { - this.minecraft.gui.setOverlay(null); -@@ -157,6 +_,7 @@ + if (f >= 2.0F) { + this.minecraft.setOverlay(null); +@@ -127,6 +_,7 @@ @Override public void tick() { if (this.fadeOutStart == -1L && this.reload.isDone() && this.isReadyToFadeOut()) { @@ -33,11 +33,11 @@ try { this.reload.checkExceptions(); this.onFinish.accept(Optional.empty()); -@@ -164,7 +_,6 @@ - this.onFinish.accept(Optional.of(t)); +@@ -134,7 +_,6 @@ + this.onFinish.accept(Optional.of(throwable)); } - this.fadeOutStart = Util.getMillis(); - if (this.minecraft.gui.screen() != null) { + if (this.minecraft.screen != null) { Window window = this.minecraft.getWindow(); - this.minecraft.gui.screen().init(window.getGuiScaledWidth(), window.getGuiScaledHeight()); + this.minecraft.screen.init(window.getGuiScaledWidth(), window.getGuiScaledHeight()); 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 b68e34708a..0c0ff84c91 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch @@ -8,13 +8,13 @@ + } + + public static java.util.Optional> getScreenFactory(@Nullable MenuType type, Minecraft minecraft, int containerId, Component title) { - MenuScreens.ScreenConstructor constructor = getConstructor(type); - if (constructor == null) { + MenuScreens.ScreenConstructor screenconstructor = getConstructor(type); + if (screenconstructor == null) { LOGGER.warn("Failed to create screen for menu type: {}", BuiltInRegistries.MENU.getKey(type)); + return java.util.Optional.empty(); } else { -- constructor.fromPacket(title, type, minecraft, containerId); -+ return java.util.Optional.of(constructor); +- screenconstructor.fromPacket(title, type, minecraft, containerId); ++ return java.util.Optional.of(screenconstructor); } } 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 7e40bbe1dc..358831c2fc 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 -@@ -165,6 +_,7 @@ - Button.builder(OPTIONS, var1x -> this.minecraft.gui.setScreen(new OptionsScreen(this, this.minecraft.options, true))).width(204).build(), 2 - ); +@@ -104,6 +_,7 @@ + } else { + gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this))); } -+ helper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.gui.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2); ++ 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); - this.disconnectButton = helper.addChild( + this.disconnectButton = gridlayout$rowhelper.addChild( Button.builder( 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 9ec2c33b30..acf649d56d 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/Screen.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/client/gui/screens/Screen.java +++ b/net/minecraft/client/gui/screens/Screen.java -@@ -196,7 +_,7 @@ +@@ -194,7 +_,7 @@ } public void onClose() { -- this.minecraft.gui.setScreen(null); -+ this.minecraft.gui.popLayer(); +- this.minecraft.setScreen(null); ++ this.minecraft.popGuiLayer(); } protected T addRenderableWidget(final T widget) { -@@ -327,8 +_,10 @@ +@@ -326,8 +_,10 @@ this.width = width; this.height = height; if (!this.initialized) { @@ -20,7 +20,7 @@ } else { this.repositionElements(); } -@@ -345,8 +_,10 @@ +@@ -344,8 +_,10 @@ protected void rebuildWidgets() { this.clearWidgets(); this.clearFocus(); @@ -31,16 +31,16 @@ } protected void fadeWidgets(final float widgetFade) { -@@ -386,6 +_,8 @@ +@@ -385,6 +_,8 @@ this.extractMenuBackground(graphics); } + net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, graphics); + - this.minecraft.gui.hud.extractDeferredSubtitles(); + this.minecraft.gui.extractDeferredSubtitles(); } -@@ -471,6 +_,19 @@ +@@ -474,6 +_,19 @@ } public void onFilesDrop(final List files) { 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 e4a863df35..d6a50d3fc9 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/TitleScreen.java +++ b/net/minecraft/client/gui/screens/TitleScreen.java -@@ -57,6 +_,7 @@ +@@ -53,6 +_,7 @@ private boolean fading; private long fadeInStart; private final LogoRenderer logoRenderer; @@ -8,48 +8,48 @@ public TitleScreen() { this(false); -@@ -114,11 +_,15 @@ - int copyrightX = this.width - copyrightWidth - 2; - int spacing = 24; - int topPos = this.height / 4 + 48; +@@ -105,11 +_,15 @@ + int j = this.width - i - 2; + int k = 24; + int l = this.height / 4 + 48; + Button modButton = null; if (this.minecraft.isDemo()) { - topPos = this.createDemoMenuOptions(topPos, 24); + l = this.createDemoMenuOptions(l, 24); } else { - topPos = this.createNormalMenuOptions(topPos, 24); -+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.gui.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))) -+ .pos(this.width / 2 - 100, topPos).size(98, 20).build()); + l = 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).size(98, 20).build()); } + modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton); - int numberOfButtons = 3; - int currentButton = 0; -@@ -199,7 +_,7 @@ - }).bounds(this.width / 2 - 100, var7 = topPos + spacing, 200, 20).tooltip(tooltip).build()).active = multiplayerAllowed; + l = this.createTestWorldButton(l, 24); + SpriteIconButton spriteiconbutton = this.addRenderableWidget( +@@ -176,7 +_,7 @@ + }).bounds(this.width / 2 - 100, i = topPos + spacing, 200, 20).tooltip(tooltip).build()).active = flag; this.addRenderableWidget( - Button.builder(Component.translatable("menu.online"), var1 -> this.minecraft.gui.setScreen(new RealmsMainScreen(this))) -- .bounds(this.width / 2 - 100, topPos = var7 + spacing, 200, 20) -+ .bounds(this.width / 2 + 2, topPos = var7 + spacing, 98, 20) + Button.builder(Component.translatable("menu.online"), button -> this.minecraft.setScreen(new RealmsMainScreen(this))) +- .bounds(this.width / 2 - 100, topPos = i + spacing, 200, 20) ++ .bounds(this.width / 2 + 2, topPos = i + spacing, 98, 20) .tooltip(tooltip) .build() ) -@@ -323,9 +_,18 @@ - versionString = versionString + I18n.get("menu.modded"); +@@ -304,9 +_,18 @@ + s = s + I18n.get("menu.modded"); } -- graphics.text(this.font, versionString, 2, this.height - 10, ARGB.white(widgetFade)); -+ final float widgetFade_f = widgetFade; +- graphics.text(this.font, s, 2, this.height - 10, ARGB.white(f)); ++ final float f_f = f; + net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brd, brdline) -> -+ graphics.text(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(widgetFade_f, -1)) ++ graphics.text(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(f_f, -1)) + ); + + net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brd, brdline) -> -+ graphics.text(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), ARGB.color(widgetFade_f, -1)) ++ graphics.text(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), ARGB.color(f_f, -1)) + ); + - if (this.realmsNotificationsEnabled() && widgetFade >= 1.0F) { + if (this.realmsNotificationsEnabled() && f >= 1.0F) { this.realmsNotificationsScreen.extractRenderState(graphics, mouseX, mouseY, a); -+ if (widgetFade >= 1.0f) this.modUpdateNotification.extractRenderState(graphics, mouseX, mouseY, a); ++ if (f >= 1.0f) this.modUpdateNotification.extractRenderState(graphics, mouseX, mouseY, a); } } 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 a76516fffd..63f7d1273d 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,14 +1,14 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java -@@ -41,6 +_,7 @@ +@@ -40,6 +_,7 @@ + private int maxY = Integer.MIN_VALUE; private float fade; private boolean centered; - private @Nullable AdvancementWidget hovered; + private int page; public AdvancementTab( final Minecraft minecraft, -@@ -62,6 +_,15 @@ +@@ -61,6 +_,15 @@ this.addWidget(this.root, rootNode.holder()); } @@ -24,14 +24,14 @@ public AdvancementTabType getType() { return this.type; } -@@ -169,8 +_,8 @@ - } +@@ -155,8 +_,8 @@ + return null; + } else { + for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) { +- if (index < advancementtabtype.getMax()) { +- return new AdvancementTab(minecraft, screen, advancementtabtype, index, root, optional.get()); ++ if ((index % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) { ++ return new AdvancementTab(minecraft, screen, advancementtabtype, index % AdvancementTabType.MAX_TABS, index / AdvancementTabType.MAX_TABS, root, optional.get()); + } - for (AdvancementTabType type : AdvancementTabType.values()) { -- if (index < type.getMax()) { -- return new AdvancementTab(minecraft, screen, type, index, root, display.get()); -+ if ((index % AdvancementTabType.MAX_TABS) < type.getMax()) { -+ return new AdvancementTab(minecraft, screen, type, index % AdvancementTabType.MAX_TABS, index / AdvancementTabType.MAX_TABS, root, display.get()); - } - - index -= type.getMax(); + index -= advancementtabtype.getMax(); 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 a1e863e50a..43a5f3f861 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,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java -@@ -52,6 +_,7 @@ +@@ -51,6 +_,7 @@ private final Map tabs = Maps.newLinkedHashMap(); private @Nullable AdvancementTab selectedTab; private boolean isScrolling; @@ -8,7 +8,7 @@ public AdvancementsScreen(final ClientAdvancements advancements) { this(advancements, null); -@@ -65,6 +_,19 @@ +@@ -64,6 +_,19 @@ @Override protected void init() { @@ -28,33 +28,33 @@ this.layout.addTitleHeader(TITLE, this.font); this.tabs.clear(); this.selectedTab = null; -@@ -119,7 +_,7 @@ - int yo = (this.height - 140) / 2; +@@ -106,7 +_,7 @@ + int j = (this.height - 140) / 2; - for (AdvancementTab tab : this.tabs.values()) { -- if (tab.isMouseOver(xo, yo, event.x(), event.y())) { -+ if (tab.getPage() == tabPage && tab.isMouseOver(xo, yo, event.x(), event.y())) { - this.advancements.setSelectedTab(tab.getRootNode().holder(), true); + for (AdvancementTab advancementtab : this.tabs.values()) { +- if (advancementtab.isMouseOver(i, j, event.x(), event.y())) { ++ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, event.x(), event.y())) { + this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true); break; } -@@ -208,10 +_,12 @@ - graphics.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, this.leftPos, this.topPos, 0.0F, 0.0F, 252, 140, 256, 256); +@@ -197,10 +_,12 @@ + graphics.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, xo, yo, 0.0F, 0.0F, 252, 140, 256, 256); if (this.tabs.size() > 1) { - for (AdvancementTab tab : this.tabs.values()) { -+ if (tab.getPage() == tabPage) - tab.extractTab(graphics, this.leftPos, this.topPos, mouseX, mouseY, tab == this.selectedTab); + for (AdvancementTab advancementtab : this.tabs.values()) { ++ if (advancementtab.getPage() == tabPage) + advancementtab.extractTab(graphics, xo, yo, mouseX, mouseY, advancementtab == this.selectedTab); } - for (AdvancementTab tab : this.tabs.values()) { -+ if (tab.getPage() == tabPage) - tab.extractIcon(graphics, this.leftPos, this.topPos); + for (AdvancementTab advancementtab1 : this.tabs.values()) { ++ if (advancementtab1.getPage() == tabPage) + advancementtab1.extractIcon(graphics, xo, yo); } } -@@ -230,6 +_,7 @@ +@@ -219,6 +_,7 @@ if (this.tabs.size() > 1) { - for (AdvancementTab tab : this.tabs.values()) { -+ if (tab.getPage() == tabPage) - if (tab.isMouseOver(this.leftPos, this.topPos, mouseX, mouseY)) { - graphics.setTooltipForNextFrame(this.font, tab.getTitle(), mouseX, mouseY); + for (AdvancementTab advancementtab : this.tabs.values()) { ++ if (advancementtab.getPage() == tabPage) + if (advancementtab.isMouseOver(xo, yo, mouseX, mouseY)) { + graphics.setTooltipForNextFrame(this.font, advancementtab.getTitle(), mouseX, mouseY); } 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 54657e5031..6e2473bea1 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,118 +1,121 @@ --- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java +++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java -@@ -98,6 +_,7 @@ - int xo = this.leftPos; - int yo = this.topPos; +@@ -111,6 +_,7 @@ + int i = this.leftPos; + int j = this.topPos; super.extractRenderState(graphics, mouseX, mouseY, a); + net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderBackground(this, graphics, mouseX, mouseY); graphics.pose().pushMatrix(); - graphics.pose().translate(xo, yo); + graphics.pose().translate(i, j); this.extractLabels(graphics, mouseX, mouseY); -@@ -109,6 +_,7 @@ - if (previouslyHoveredSlot != null && previouslyHoveredSlot != this.hoveredSlot) { - this.onStopHovering(previouslyHoveredSlot); +@@ -122,6 +_,7 @@ + if (slot != null && slot != this.hoveredSlot) { + this.onStopHovering(slot); } + net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderForeground(this, graphics, mouseX, mouseY); graphics.pose().popMatrix(); } -@@ -170,7 +_,7 @@ - ItemStack item = this.hoveredSlot.getItem(); - if (this.menu.getCarried().isEmpty() || this.showTooltipWithItemInHand(item)) { - graphics.setTooltipForNextFrame( -- this.font, this.getTooltipFromContainerItem(item), item.getTooltipImage(), mouseX, mouseY, item.get(DataComponents.TOOLTIP_STYLE) -+ this.font, this.getTooltipFromContainerItem(item), item.getTooltipImage(), item, mouseX, mouseY +@@ -203,9 +_,9 @@ + this.font, + this.getTooltipFromContainerItem(itemstack), + itemstack.getTooltipImage(), ++ itemstack, + mouseX, +- mouseY, +- itemstack.get(DataComponents.TOOLTIP_STYLE) ++ mouseY ); } } -@@ -186,7 +_,8 @@ +@@ -221,7 +_,8 @@ private void extractFloatingItem(final GuiGraphicsExtractor graphics, final ItemStack carried, final int x, final int y, final @Nullable String itemCount) { graphics.item(carried, x, y); -- graphics.itemDecorations(this.font, carried, x, y, itemCount); +- graphics.itemDecorations(this.font, carried, x, y - (this.draggingItem.isEmpty() ? 0 : 8), itemCount); + var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(carried).getFont(carried, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT); -+ graphics.itemDecorations(font == null ? this.font : font, carried, x, y, itemCount); ++ graphics.itemDecorations(font == null ? this.font : font, carried, x, y - (this.draggingItem.isEmpty() ? 0 : 8), itemCount); } protected void extractLabels(final GuiGraphicsExtractor graphics, final int xm, final int ym) { -@@ -285,7 +_,8 @@ +@@ -319,7 +_,8 @@ + if (super.mouseClicked(event, doubleClick)) { return true; - } - -- boolean cloning = this.minecraft.options.keyPickItem.matchesMouse(event) && this.minecraft.player.hasInfiniteMaterials(); -+ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(event.button()); -+ boolean cloning = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials(); - Slot slot = this.getHoveredSlot(event.x(), event.y()); - this.doubleclick = this.lastClickSlot == slot && doubleClick; - this.skipNextRelease = false; -@@ -295,6 +_,7 @@ - int xo = this.leftPos; - int yo = this.topPos; - boolean clickedOutside = this.hasClickedOutside(event.x(), event.y(), xo, yo); -+ if (slot != null) clickedOutside = false; // Forge, prevent dropping of items through slots outside of GUI boundaries - int slotId = -1; - if (slot != null) { - slotId = slot.index; -@@ -306,7 +_,7 @@ - - if (slotId != -1 && !this.isQuickCrafting) { - if (this.menu.getCarried().isEmpty()) { -- if (cloning) { -+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, slotId, event.button(), ContainerInput.CLONE); - } else { - boolean quickKey = slotId != -999 && event.hasShiftDown(); -@@ -330,7 +_,7 @@ - this.quickCraftingType = 0; - } else if (event.button() == 1) { - this.quickCraftingType = 1; -- } else if (cloning) { -+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.quickCraftingType = 2; - } - } -@@ -374,10 +_,13 @@ + } else { +- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(event) && this.minecraft.player.hasInfiniteMaterials(); ++ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(event.button()); ++ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials(); + Slot slot = this.getHoveredSlot(event.x(), event.y()); + this.doubleclick = this.lastClickSlot == slot && doubleClick; + this.skipNextRelease = false; +@@ -329,6 +_,7 @@ + int i = this.leftPos; + int j = this.topPos; + boolean flag1 = this.hasClickedOutside(event.x(), event.y(), i, j); ++ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + int k = -1; + if (slot != null) { + k = slot.index; +@@ -354,7 +_,7 @@ + } + } else if (!this.isQuickCrafting) { + if (this.menu.getCarried().isEmpty()) { +- if (flag) { ++ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + this.slotClicked(slot, k, event.button(), ContainerInput.CLONE); + } else { + boolean flag2 = k != -999 && event.hasShiftDown(); +@@ -378,7 +_,7 @@ + this.quickCraftingType = 0; + } else if (event.button() == 1) { + this.quickCraftingType = 1; +- } else if (flag) { ++ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + this.quickCraftingType = 2; + } + } +@@ -448,10 +_,13 @@ @Override public boolean mouseReleased(final MouseButtonEvent event) { + super.mouseReleased(event); //Forge, Call parent to release buttons Slot slot = this.getHoveredSlot(event.x(), event.y()); - int xo = this.leftPos; - int yo = this.topPos; - boolean clickedOutside = this.hasClickedOutside(event.x(), event.y(), xo, yo); -+ if (slot != null) clickedOutside = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + int i = this.leftPos; + int j = this.topPos; + boolean flag = this.hasClickedOutside(event.x(), event.y(), i, j); ++ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(event.button()); - int slotId = -1; + int k = -1; if (slot != null) { - slotId = slot.index; -@@ -394,7 +_,7 @@ - if (target != null - && target.mayPickup(this.minecraft.player) - && target.hasItem() -- && target.container == slot.container -+ && target.isSameInventory(slot) - && AbstractContainerMenu.canItemQuickReplace(target, this.lastQuickMoved, true)) { - this.slotClicked(target, target.index, event.button(), ContainerInput.QUICK_MOVE); + k = slot.index; +@@ -468,7 +_,7 @@ + if (slot1 != null + && slot1.mayPickup(this.minecraft.player) + && slot1.hasItem() +- && slot1.container == slot.container ++ && slot1.isSameInventory(slot) + && AbstractContainerMenu.canItemQuickReplace(slot1, this.lastQuickMoved, true)) { + this.slotClicked(slot1, slot1.index, event.button(), ContainerInput.QUICK_MOVE); } -@@ -421,7 +_,7 @@ - if (this.isQuickCrafting && !this.quickCraftSlots.isEmpty()) { +@@ -527,7 +_,7 @@ + } else if (this.isQuickCrafting && !this.quickCraftSlots.isEmpty()) { this.quickCraftToSlots(); } else if (!this.menu.getCarried().isEmpty()) { - if (this.minecraft.options.keyPickItem.matchesMouse(event)) { + if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, slotId, event.button(), ContainerInput.CLONE); + this.slotClicked(slot, k, event.button(), ContainerInput.CLONE); } else { - boolean quickKey = slotId != -999 && event.hasShiftDown(); -@@ -489,7 +_,7 @@ + boolean flag1 = k != -999 && event.hasShiftDown(); +@@ -598,7 +_,7 @@ + public boolean keyPressed(final KeyEvent event) { + if (super.keyPressed(event)) { return true; - } - -- if (this.minecraft.options.keyInventory.matches(event)) { -+ if (this.minecraft.options.keyInventory.isActiveAndMatches(com.mojang.blaze3d.platform.InputConstants.getKey(event))) { +- } else if (this.minecraft.options.keyInventory.matches(event)) { ++ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(com.mojang.blaze3d.platform.InputConstants.getKey(event))) { this.onClose(); return true; - } -@@ -587,4 +_,11 @@ + } else { +@@ -696,6 +_,13 @@ super.onClose(); } @@ -123,4 +126,6 @@ + public int getGuiTop() { return topPos; } + public int getXSize() { return imageWidth; } + public int getYSize() { return imageHeight; } - } + + @OnlyIn(Dist.CLIENT) + private record SnapbackData(ItemStack item, Vector2i start, Vector2i end, long time) { 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 89c9860fb0..dd485d7950 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 @@ -11,7 +11,7 @@ super(new CreativeModeInventoryScreen.ItemPickerMenu(player), player.getInventory(), CommonComponents.EMPTY, 195, 136); @@ -164,7 +_,7 @@ private void refreshCurrentTabContents(final Collection displayList) { - int oldRowIndex = this.menu.getRowIndexForScroll(this.scrollOffs); + int i = this.menu.getRowIndexForScroll(this.scrollOffs); this.menu.items.clear(); - if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { + if (selectedTab.hasSearchBar()) { @@ -55,16 +55,16 @@ 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); -@@ -379,7 +_,7 @@ +@@ -377,7 +_,7 @@ + public boolean charTyped(final CharacterEvent event) { + if (this.ignoreTextInput) { return false; - } - -- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { -+ if (!selectedTab.hasSearchBar()) { +- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) { ++ } else if (!selectedTab.hasSearchBar()) { return false; - } - -@@ -407,7 +_,7 @@ + } else { + String s = this.searchBox.getValue(); +@@ -405,7 +_,7 @@ @Override public boolean keyPressed(final KeyEvent event) { this.ignoreTextInput = false; @@ -73,28 +73,28 @@ if (this.minecraft.options.keyChat.matches(event)) { this.ignoreTextInput = true; this.selectTab(CreativeModeTabs.searchTab()); -@@ -443,6 +_,7 @@ +@@ -441,6 +_,7 @@ } private void refreshSearchResults() { + if (!selectedTab.hasSearchBar()) return; this.menu.items.clear(); this.visibleTags.clear(); - String searchTerm = this.searchBox.getValue(); -@@ -455,10 +_,10 @@ - SearchTree tree; - if (searchTerm.startsWith("#")) { - searchTerm = searchTerm.substring(1); -- tree = searchTrees.creativeTagSearch(); -+ tree = searchTrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); - this.updateVisibleTags(searchTerm); + String s = this.searchBox.getValue(); +@@ -453,10 +_,10 @@ + SearchTree searchtree; + if (s.startsWith("#")) { + s = s.substring(1); +- searchtree = sessionsearchtrees.creativeTagSearch(); ++ searchtree = sessionsearchtrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); + this.updateVisibleTags(s); } else { -- tree = searchTrees.creativeNameSearch(); -+ tree = searchTrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); +- searchtree = sessionsearchtrees.creativeNameSearch(); ++ searchtree = sessionsearchtrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); } - this.menu.items.addAll(tree.search(searchTerm.toLowerCase(Locale.ROOT))); -@@ -486,7 +_,7 @@ + this.menu.items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT))); +@@ -484,7 +_,7 @@ @Override protected void extractLabels(final GuiGraphicsExtractor graphics, final int xm, final int ym) { if (selectedTab.showTitle()) { @@ -103,25 +103,25 @@ } } -@@ -496,7 +_,7 @@ - double xm = event.x() - this.leftPos; - double ym = event.y() - this.topPos; +@@ -494,7 +_,7 @@ + double d0 = event.x() - this.leftPos; + double d1 = event.y() - this.topPos; -- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(tab, xm, ym)) { +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(creativemodetab, d0, d1)) { return true; } -@@ -518,7 +_,7 @@ - double ym = event.y() - this.topPos; +@@ -516,7 +_,7 @@ + double d1 = event.y() - this.topPos; this.scrolling = false; -- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(tab, xm, ym)) { - this.selectTab(tab); +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(creativemodetab, d0, d1)) { + this.selectTab(creativemodetab); return true; -@@ -611,13 +_,15 @@ +@@ -610,13 +_,15 @@ this.originalSlots = null; } @@ -130,7 +130,7 @@ this.searchBox.setVisible(true); this.searchBox.setCanLoseFocus(false); this.searchBox.setFocused(true); - if (oldTab != tab) { + if (creativemodetab != tab) { this.searchBox.setValue(""); } + this.searchBox.setWidth(selectedTab.getSearchBarWidth()); @@ -138,11 +138,11 @@ this.refreshSearchResults(); } else { -@@ -682,7 +_,14 @@ +@@ -679,7 +_,14 @@ this.effects.extractRenderState(graphics, mouseX, mouseY); super.extractRenderState(graphics, mouseX, mouseY, a); -- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { + if (this.pages.size() != 1) { + Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size())); + graphics.pose().pushMatrix(); @@ -150,75 +150,83 @@ + graphics.pose().popMatrix(); + } + -+ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { - if (this.checkTabHovering(graphics, tab, mouseX, mouseY)) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (this.checkTabHovering(graphics, creativemodetab, mouseX, mouseY)) { break; } -@@ -704,7 +_,7 @@ +@@ -701,7 +_,7 @@ public List getTooltipFromContainerItem(final ItemStack itemStack) { - boolean isCreativeSlot = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot; - boolean isSingleCategoryTab = selectedTab.getType() == CreativeModeTab.Type.CATEGORY; -- boolean isSearchTab = selectedTab.getType() == CreativeModeTab.Type.SEARCH; -+ boolean isSearchTab = selectedTab.hasSearchBar(); - TooltipFlag.Default originalTooltipStyle = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL; - TooltipFlag tooltipStyle = isCreativeSlot ? originalTooltipStyle.asCreative() : originalTooltipStyle; - List originalLines = itemStack.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipStyle); -@@ -728,7 +_,7 @@ - int i = 1; + 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 = itemStack.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipflag); +@@ -722,7 +_,7 @@ + int i = 1; - for (CreativeModeTab tab : CreativeModeTabs.tabs()) { -- if (tab.getType() != CreativeModeTab.Type.SEARCH && tab.contains(itemStack)) { -+ if (!tab.hasSearchBar() && tab.contains(itemStack)) { - linesToDisplay.add(i++, tab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); + for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { +- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(itemStack)) { ++ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(itemStack)) { + list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); + } } - } -@@ -740,7 +_,7 @@ +@@ -735,7 +_,7 @@ public void extractBackground(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) { super.extractBackground(graphics, mouseX, mouseY, a); -- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { - if (tab != selectedTab) { - this.extractTabButton(graphics, mouseX, mouseY, tab); +- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { + if (creativemodetab != selectedTab) { + this.extractTabButton(graphics, mouseX, mouseY, creativemodetab); } -@@ -775,6 +_,7 @@ - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, sprite, xscr, yscr + (int)((yscr2 - yscr - 17) * this.scrollOffs), 12, 15); +@@ -770,6 +_,7 @@ + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, identifier, j, k + (int)((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.extractTabButton(graphics, mouseX, mouseY, selectedTab); if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) { InventoryScreen.extractEntityInInventoryFollowsMouse( -@@ -784,7 +_,7 @@ +@@ -779,7 +_,7 @@ } private int getTabX(final CreativeModeTab tab) { -- int pos = tab.column(); -+ int pos = currentPage.getColumn(tab); - int spacing = 27; - int x = 27 * pos; +- int i = tab.column(); ++ int i = currentPage.getColumn(tab); + int j = 27; + int k = 27 * i; if (tab.isAlignedRight()) { -@@ -796,7 +_,7 @@ +@@ -791,7 +_,7 @@ private int getTabY(final CreativeModeTab tab) { - int y = 0; + int i = 0; - if (tab.row() == CreativeModeTab.Row.TOP) { + if (currentPage.isTop(tab)) { - y -= 32; + i -= 32; } else { - y += this.imageHeight; -@@ -824,8 +_,8 @@ + i += this.imageHeight; +@@ -819,8 +_,8 @@ protected void extractTabButton(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final CreativeModeTab tab) { - boolean selected = tab == selectedTab; -- boolean isTop = tab.row() == CreativeModeTab.Row.TOP; -- int pos = tab.column(); -+ boolean isTop = currentPage.isTop(tab); -+ int pos = currentPage.getColumn(tab); - int x = this.leftPos + this.getTabX(tab); - int y = this.topPos - (isTop ? 28 : -(this.imageHeight - 4)); - Identifier[] sprites; -@@ -875,6 +_,14 @@ + boolean flag = tab == selectedTab; +- boolean flag1 = tab.row() == CreativeModeTab.Row.TOP; +- int i = tab.column(); ++ boolean flag1 = currentPage.isTop(tab); ++ int i = currentPage.getColumn(tab); + int j = this.leftPos + this.getTabX(tab); + int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4)); + Identifier[] aidentifier; +@@ -834,6 +_,7 @@ + graphics.requestCursor(CursorTypes.POINTING_HAND); + } + ++ com.mojang.blaze3d.opengl.GlStateManager._enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border. + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, aidentifier[Mth.clamp(i, 0, aidentifier.length)], j, k, 26, 32); + int l = j + 13 - 8; + int i1 = k + 16 - 8 + (flag1 ? 1 : -1); +@@ -870,6 +_,14 @@ } } @@ -233,7 +241,7 @@ @OnlyIn(Dist.CLIENT) private static class CustomCreativeSlot extends Slot { public CustomCreativeSlot(final Container container, final int slot, final int x, final int y) { -@@ -1055,6 +_,22 @@ +@@ -1050,6 +_,22 @@ @Override public boolean mayPickup(final Player player) { return this.target.mayPickup(player); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch index 38a927f73f..515c9a4b75 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch @@ -1,39 +1,39 @@ --- a/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java +++ b/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java @@ -47,12 +_,16 @@ - int availableWidth = this.screen.width - xo; - Collection activeEffects = this.minecraft.player.getActiveEffects(); - if (!activeEffects.isEmpty() && availableWidth >= 32) { -- int maxWidth = availableWidth >= 120 ? availableWidth - 7 : 32; -+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenEffectSize(this.screen, availableWidth, availableWidth < 120, xo); + int j = this.screen.width - i; + Collection collection = this.minecraft.player.getActiveEffects(); + if (!collection.isEmpty() && j >= 32) { +- int k = j >= 120 ? j - 7 : 32; ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenEffectSize(this.screen, j, j < 120, i); + if (event == null) return; -+ int maxWidth = !event.isCompact() ? availableWidth - 7 : 32; -+ xo = event.getHorizontalOffset(); - int yStep = 33; - if (activeEffects.size() > 5) { - yStep = 132 / (activeEffects.size() - 1); ++ int k = !event.isCompact() ? j - 7 : 32; ++ i = event.getHorizontalOffset(); + int l = 33; + if (collection.size() > 5) { + l = 132 / (collection.size() - 1); } -+ Iterable iterable = activeEffects.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList(); - this.extractEffects(graphics, activeEffects, xo, yStep, mouseX, mouseY, maxWidth); ++ Iterable iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList(); + this.extractEffects(graphics, collection, i, l, mouseX, mouseY, k); } } @@ -72,6 +_,11 @@ - for (MobEffectInstance effect : sortedEffects) { - boolean isAmbient = effect.isAmbient(); -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(effect); -+ if (renderer.extractInventory(effect, this, graphics, x0, y0, 0)) { -+ y0 += yStep; + for (MobEffectInstance mobeffectinstance : iterable) { + boolean flag = mobeffectinstance.isAmbient(); ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); ++ if (renderer.extractInventory(mobeffectinstance, this, graphics, x0, i, 0)) { ++ i += yStep; + continue; + } - Component effectText = this.getEffectName(effect); - Component duration = MobEffectUtil.formatDuration(effect, 1.0F, this.minecraft.level.tickRateManager().tickrate()); - int textureWidth = this.extractBackground(graphics, font, effectText, duration, x0, y0, isAmbient, maxWidth); + Component component = this.getEffectName(mobeffectinstance); + Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate()); + int j = this.extractBackground(graphics, font, component, component1, x0, i, flag, maxWidth); @@ -136,5 +_,9 @@ } - return name; + return mutablecomponent; + } + + public AbstractContainerScreen getScreen() { 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 d32f83cb84..f58ce6e108 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,33 +1,32 @@ --- a/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java +++ b/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java @@ -111,7 +_,7 @@ - int textWidth = 86 - this.font.width(costText); - FormattedText message = EnchantmentNames.getInstance().getRandomName(this.font, textWidth); - int col = -9937334; -- if ((goldCount < i + 1 || this.minecraft.player.experienceLevel < cost) && !this.minecraft.player.hasInfiniteMaterials()) { -+ if (((goldCount < i + 1 || this.minecraft.player.experienceLevel < cost) && !this.minecraft.player.hasInfiniteMaterials()) || this.menu.enchantClue[i] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{ - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, ENCHANTMENT_SLOT_DISABLED_SPRITE, leftPos, yo + 14 + 19 * i, 108, 19); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, DISABLED_LEVEL_SPRITES[i], leftPos + 1, yo + 15 + 19 * i, 16, 16); - graphics.textWithWordWrap(this.font, message, leftPosText, yo + 16 + 19 * i, textWidth, ARGB.opaque((col & 16711422) >> 1), false); -@@ -162,14 +_,18 @@ + int l1 = 86 - this.font.width(s); + FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1); + int i2 = -9937334; +- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.hasInfiniteMaterials()) { ++ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.hasInfiniteMaterials()) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{ + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16); + graphics.textWithWordWrap(this.font, formattedtext, j1, j + 16 + 19 * l, l1, ARGB.opaque((i2 & 16711422) >> 1), false); +@@ -162,13 +_,16 @@ .registryAccess() .lookupOrThrow(Registries.ENCHANTMENT) - .get(this.menu.enchantClue[i]); -- if (!enchant.isEmpty()) { + .get(this.menu.enchantClue[j]); +- if (!optional.isEmpty()) { + { - int enchantLevel = this.menu.levelClue[i]; - int cost = i + 1; -- if (this.isHovering(60, 14 + 19 * i, 108, 17, mouseX, mouseY) && minLevel > 0 && enchantLevel >= 0) { -+ if (this.isHovering(60, 14 + 19 * i, 108, 17, (double)mouseX, (double)mouseY) && enchantLevel >= 0) { - List texts = Lists.newArrayList(); - texts.add( -- Component.translatable("container.enchant.clue", Enchantment.getFullname(enchant.get(), enchantLevel)).withStyle(ChatFormatting.WHITE) -+ Component.translatable("container.enchant.clue", enchant.isEmpty() ? "" : Enchantment.getFullname(enchant.get(), enchantLevel)).withStyle(ChatFormatting.WHITE) - ); -+ if (enchant.isEmpty()) { -+ texts.add(Component.literal("")); -+ texts.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED)); -+ } else - if (!infiniteMaterials) { - texts.add(CommonComponents.EMPTY); - if (this.minecraft.player.experienceLevel < minLevel) { + int l = this.menu.levelClue[j]; + int i1 = j + 1; +- if (this.isHovering(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l >= 0) { ++ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)mouseX, (double)mouseY) && l >= 0) { + List list = Lists.newArrayList(); +- list.add(Component.translatable("container.enchant.clue", Enchantment.getFullname(optional.get(), l)).withStyle(ChatFormatting.WHITE)); +- if (!flag) { ++ list.add(Component.translatable("container.enchant.clue", optional.isEmpty() ? "" : Enchantment.getFullname(optional.get(), l)).withStyle(ChatFormatting.WHITE)); ++ if (optional.isEmpty()) { ++ 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 617ada3af3..39298d9625 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,7 +1,7 @@ --- a/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java +++ b/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java -@@ -16,7 +_,7 @@ - private static final Vector3fc TEXT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F); +@@ -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 Identifier texture = Identifier.withDefaultNamespace("textures/gui/hanging_signs/" + this.woodType.name() + ".png"); 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 1c74ad59e2..246c28c0af 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 -@@ -18,7 +_,7 @@ - return switch (component) { - case BundleTooltip bundleTooltip -> new ClientBundleTooltip(bundleTooltip.contents()); - case ClientActivePlayersTooltip.ActivePlayersTooltip activePlayersTooltip -> new ClientActivePlayersTooltip(activePlayersTooltip); +@@ -20,7 +_,7 @@ + case ClientActivePlayersTooltip.ActivePlayersTooltip clientactiveplayerstooltip$activeplayerstooltip -> new ClientActivePlayersTooltip( + clientactiveplayerstooltip$activeplayerstooltip + ); - default -> throw new IllegalArgumentException("Unknown TooltipComponent"); + default -> net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(component); - }; + }); } 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 770354dba6..f7efecb938 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 -@@ -369,6 +_,8 @@ +@@ -371,6 +_,8 @@ graphics.setTooltipForNextFrame(Lists.transform(this.onlinePlayersTooltip, Component::getVisualOrderText), mouseX, mouseY); } + net.minecraftforge.client.ForgeHooksClient.drawForgePingInfo(this.screen, serverData, graphics, this.getContentX(), this.getContentY(), this.getContentWidth(), mouseX - this.getContentX(), mouseY - this.getContentY()); + - if (hovered) { + if (this.minecraft.options.touchscreen().get() || hovered) { graphics.fill(this.getContentX(), this.getContentY(), this.getContentX() + 32, this.getContentY() + 32, -1601138544); - int relX = mouseX - this.getContentX(); + int i1 = mouseX - this.getContentX(); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch index c377afcffa..774ce5641d 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java +++ b/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java -@@ -116,9 +_,10 @@ +@@ -123,9 +_,10 @@ this.name = name; this.changeButton = Button.builder(name, button -> { KeyBindsList.this.keyBindsScreen.selectedKey = key; @@ -12,7 +12,7 @@ .createNarration( defaultNarrationSupplier -> key.isUnbound() ? Component.translatable("narrator.controls.unbound", name) -@@ -126,7 +_,7 @@ +@@ -133,7 +_,7 @@ ) .build(); this.resetButton = Button.builder(RESET_BUTTON_TITLE, button -> { @@ -21,13 +21,13 @@ KeyBindsList.this.resetMappingAndUpdateButtons(); }).bounds(0, 0, 50, 20).createNarration(defaultNarrationSupplier -> Component.translatable("narrator.controls.reset", name)).build(); this.refreshEntry(); -@@ -167,7 +_,8 @@ - MutableComponent tooltip = Component.empty(); +@@ -174,7 +_,8 @@ + MutableComponent mutablecomponent = Component.empty(); if (!this.key.isUnbound()) { - for (KeyMapping otherKey : KeyBindsList.this.minecraft.options.keyMappings) { -- if (otherKey != this.key && this.key.same(otherKey) && (!otherKey.isDefault() || !this.key.isDefault())) { -+ var vanillConflict = otherKey != this.key && this.key.same(otherKey) && (!otherKey.isDefault() || !this.key.isDefault()); -+ if (vanillConflict || otherKey.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G + for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) { +- if (keymapping != this.key && this.key.same(keymapping) && (!keymapping.isDefault() || !this.key.isDefault())) { ++ var vanillConflict = keymapping != this.key && this.key.same(keymapping) && (!keymapping.isDefault() || !this.key.isDefault()); ++ if (vanillConflict || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G if (this.hasCollision) { - tooltip.append(", "); + mutablecomponent.append(", "); } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch index 8558529b3e..5a179d9cc6 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch @@ -3,9 +3,9 @@ @@ -42,7 +_,7 @@ protected void addFooter() { this.resetButton = Button.builder(Component.translatable("controls.resetAll"), button -> { - for (KeyMapping key : this.options.keyMappings) { -- key.setKey(key.getDefaultKey()); -+ key.setToDefault(); + for (KeyMapping keymapping : this.options.keyMappings) { +- keymapping.setKey(keymapping.getDefaultKey()); ++ keymapping.setToDefault(); } this.keyBindsList.resetMappingAndUpdateButtons(); @@ -27,7 +27,7 @@ @@ -101,5 +_,18 @@ } - this.resetButton.active = canReset; + this.resetButton.active = flag; + } + + @Override 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 10e954a55a..32cbf8ce37 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,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/packs/PackSelectionModel.java +++ b/net/minecraft/client/gui/screens/packs/PackSelectionModel.java -@@ -111,6 +_,10 @@ +@@ -112,6 +_,10 @@ boolean canMoveUp(); boolean canMoveDown(); @@ -11,7 +11,7 @@ } @OnlyIn(Dist.CLIENT) -@@ -210,6 +_,11 @@ +@@ -213,6 +_,11 @@ @Override public void moveDown() { this.move(1); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch index 53617793d5..70dc308202 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java +++ b/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java -@@ -65,7 +_,7 @@ - Component header = Component.empty().append(this.title).withStyle(ChatFormatting.UNDERLINE, ChatFormatting.BOLD); - this.addEntry(new TransferableSelectionList.HeaderEntry(this.minecraft.font, header), (int)(9.0F * 1.5F)); +@@ -66,7 +_,7 @@ + Component component = Component.empty().append(this.title).withStyle(ChatFormatting.UNDERLINE, ChatFormatting.BOLD); + this.addEntry(new TransferableSelectionList.HeaderEntry(this.minecraft.font, component), (int)(9.0F * 1.5F)); this.setSelected(null); - entries.forEach(e -> { + entries.filter(PackSelectionModel.Entry::notHidden).forEach(e -> { - TransferableSelectionList.PackEntry entry = new TransferableSelectionList.PackEntry(this.minecraft, this, e); - this.addEntry(entry); + TransferableSelectionList.PackEntry transferableselectionlist$packentry = new TransferableSelectionList.PackEntry(this.minecraft, this, e); + this.addEntry(transferableselectionlist$packentry); if (transferredEntry != null && transferredEntry.getId().equals(e.getId())) { 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 6e72414996..950bf2b1b9 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,14 +1,14 @@ --- a/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java +++ b/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java -@@ -172,6 +_,7 @@ - WorldDataConfiguration dataConfig = SharedConstants.IS_RUNNING_IN_IDE +@@ -177,6 +_,7 @@ + WorldDataConfiguration worlddataconfiguration = SharedConstants.IS_RUNNING_IN_IDE ? new WorldDataConfiguration(new DataPackConfig(List.of("vanilla", "tests"), List.of()), FeatureFlags.DEFAULT_FLAGS) : WorldDataConfiguration.DEFAULT; -+ net.minecraftforge.event.ForgeEventFactory.addPackFindersServer(vanillaOnlyPackRepository::addPackFinder); - WorldLoader.InitConfig loadConfig = createDefaultLoadConfig(vanillaOnlyPackRepository, dataConfig); - CompletableFuture loadResult = WorldLoader.load( - loadConfig, -@@ -512,7 +_,7 @@ ++ net.minecraftforge.event.ForgeEventFactory.addPackFindersServer(packrepository::addPackFinder); + WorldLoader.InitConfig worldloader$initconfig = createDefaultLoadConfig(packrepository, worlddataconfiguration); + CompletableFuture completablefuture = WorldLoader.load( + worldloader$initconfig, +@@ -520,7 +_,7 @@ if (retry) { onAbort.accept(this.uiState.getSettings().dataConfiguration()); } else { @@ -17,10 +17,10 @@ } }, Component.translatable("dataPack.validation.failed"), -@@ -621,6 +_,7 @@ - if (dataPackDir != null) { +@@ -634,6 +_,7 @@ + if (path != null) { if (this.tempDataPackRepository == null) { - this.tempDataPackRepository = ServerPacksSource.createPackRepository(dataPackDir, this.packValidator); + 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 2deeb0af17..aa503f068e 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,6 +1,6 @@ --- 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 { 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 628bc0c979..4d2bbafbde 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 -@@ -239,7 +_,7 @@ +@@ -234,7 +_,7 @@ public @Nullable PresetEditor getPresetEditor() { - Holder preset = this.getWorldType().preset(); -- return preset != null ? PresetEditor.EDITORS.get(preset.unwrapKey()) : null; -+ return preset != null ? preset.unwrapKey().map(net.minecraftforge.client.PresetEditorManager::get).orElse(null) : null; // FORGE: redirect lookup to expanded map + 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() { 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 f34ed9e0f1..212b5cbe84 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,29 +1,11 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java -@@ -495,6 +_,8 @@ +@@ -507,6 +_,8 @@ this.minecraft.setScreenAndShow(new GenericMessageScreen(Component.translatable("selectWorld.resource_load"))); - PackRepository packRepository = ServerPacksSource.createPackRepository(worldAccess); + PackRepository packrepository = ServerPacksSource.createPackRepository(worldAccess); + net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(worldAccess, worldAccess.getLevelDirectory()); + - WorldStem worldStem; + WorldStem worldstem; try { - worldStem = this.loadWorldStem(worldAccess, levelDataTag, safeMode, packRepository); -@@ -537,6 +_,8 @@ - WorldData data = worldDataAndGenSettings.data(); - boolean oldCustomized = worldDataAndGenSettings.genSettings().options().isOldCustomizedWorld(); - boolean unstable = data.worldGenSettingsLifecycle() != Lifecycle.stable(); -+ if (unstable && data instanceof PrimaryLevelData primaryData) -+ unstable = !primaryData.hasConfirmedExperimentalWarning(); - if (!oldCustomized && !unstable) { - this.openWorldLoadBundledResourcePack(worldAccess, worldStem, packRepository, onCancel); - } else { -@@ -553,6 +_,8 @@ - private void openWorldLoadBundledResourcePack( - final LevelStorageSource.LevelStorageAccess worldAccess, final WorldStem worldStem, final PackRepository packRepository, final Runnable onCancel - ) { -+ if (worldStem.worldDataAndGenSettings().data() instanceof PrimaryLevelData primaryLevelData) -+ primaryLevelData.withConfirmedWarning(worldStem.worldDataAndGenSettings().data().worldGenSettingsLifecycle() != Lifecycle.stable()); - DownloadedPackSource packSource = this.minecraft.getDownloadedPackSource(); - this.loadBundledResourcePack(packSource, worldAccess).thenApply(unused -> true).exceptionallyComposeAsync(t -> { - LOGGER.warn("Failed to load pack: ", t); + worldstem = this.loadWorldStem(worldAccess, levelDataTag, safeMode, 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 4612184de5..0a0325f977 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,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java -@@ -83,6 +_,7 @@ +@@ -84,6 +_,7 @@ private static final Identifier JOIN_HIGHLIGHTED_SPRITE = Identifier.withDefaultNamespace("world_list/join_highlighted"); private static final Identifier JOIN_SPRITE = Identifier.withDefaultNamespace("world_list/join"); private static final Logger LOGGER = LogUtils.getLogger(); @@ -8,7 +8,7 @@ private static final Component FROM_NEWER_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.fromNewerVersion1").withStyle(ChatFormatting.RED); private static final Component FROM_NEWER_TOOLTIP_2 = Component.translatable("selectWorld.tooltip.fromNewerVersion2").withStyle(ChatFormatting.RED); private static final Component SNAPSHOT_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.snapshot1").withStyle(ChatFormatting.GOLD); -@@ -483,6 +_,19 @@ +@@ -493,6 +_,19 @@ } } @@ -27,12 +27,12 @@ + @Override public Component getNarration() { - Component entryNarration = Component.translatable( -@@ -512,6 +_,7 @@ - this.infoText.setPosition(textX, this.getContentY() + 9 + 9 + 3); + Component component = Component.translatable( +@@ -522,6 +_,7 @@ + this.infoText.setPosition(i, this.getContentY() + 9 + 9 + 3); this.infoText.extractRenderState(graphics, mouseX, mouseY, a); graphics.blit(RenderPipelines.GUI_TEXTURED, this.icon.textureLocation(), this.getContentX(), this.getContentY(), 0.0F, 0.0F, 32, 32, 32, 32); + renderExperimentalWarning(graphics, mouseX, mouseY, this.getContentY(), this.getContentX()); - if (this.list.entryType == WorldSelectionList.EntryType.SINGLEPLAYER && hovered) { + if (this.list.entryType == WorldSelectionList.EntryType.SINGLEPLAYER && (this.minecraft.options.touchscreen().get() || hovered)) { graphics.fill(this.getContentX(), this.getContentY(), this.getContentX() + 32, this.getContentY() + 32, -1601138544); - int relX = mouseX - this.getContentX(); + int j = mouseX - this.getContentX(); diff --git a/patches/minecraft/net/minecraft/client/main/Main.java.patch b/patches/minecraft/net/minecraft/client/main/Main.java.patch index 30246c1da7..476c04ce08 100644 --- a/patches/minecraft/net/minecraft/client/main/Main.java.patch +++ b/patches/minecraft/net/minecraft/client/main/Main.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/main/Main.java +++ b/net/minecraft/client/main/Main.java -@@ -159,8 +_,8 @@ +@@ -114,8 +_,8 @@ CrashReport.preload(); logger = LogUtils.getLogger(); - stage = "Bootstrap"; + s1 = "Bootstrap"; - Bootstrap.bootStrap(); - ClientBootstrap.bootstrap(); + net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(Bootstrap::bootStrap, net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); + net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(ClientBootstrap::bootstrap, net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); GameLoadTimesEvent.INSTANCE.setBootstrapTime(Bootstrap.bootstrapDuration.get()); Bootstrap.validate(); - stage = "Argument parsing"; + s1 = "Argument parsing"; diff --git a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch index 8309858145..805bd4cdf4 100644 --- a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch +++ b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/model/HumanoidModel.java +++ b/net/minecraft/client/model/HumanoidModel.java -@@ -391,6 +_,8 @@ +@@ -387,6 +_,8 @@ break; case SPEAR: SpearAnimations.thirdPersonHandUse(this.rightArm, this.head, true, state.getUseItemStackForArm(HumanoidArm.RIGHT), state); @@ -9,7 +9,7 @@ } } -@@ -436,6 +_,8 @@ +@@ -432,6 +_,8 @@ break; case SPEAR: SpearAnimations.thirdPersonHandUse(this.leftArm, this.head, false, state.getUseItemStackForArm(HumanoidArm.LEFT), state); @@ -18,17 +18,17 @@ } } -@@ -497,7 +_,7 @@ +@@ -493,7 +_,7 @@ } @OnlyIn(Dist.CLIENT) -- public enum ArmPose { -+ public enum ArmPose implements net.minecraftforge.common.IExtensibleEnum { +- public static enum ArmPose { ++ public static enum ArmPose implements net.minecraftforge.common.IExtensibleEnum { EMPTY(false, false), ITEM(false, false), BLOCK(false, false), -@@ -523,10 +_,29 @@ - ArmPose(final boolean twoHanded, final boolean affectsOffhandPose) { +@@ -519,10 +_,29 @@ + private ArmPose(final boolean twoHanded, final boolean affectsOffhandPose) { this.twoHanded = twoHanded; this.affectsOffhandPose = affectsOffhandPose; + this.forgeArmPose = null; 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 2c26bba477..35e82948e2 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 -@@ -557,6 +_,7 @@ - result.put(ModelLayers.PALE_OAK_CHEST_BOAT, chestBoatModel); - result.put(ModelLayers.MANGROVE_BOAT, boatModel); - result.put(ModelLayers.MANGROVE_CHEST_BOAT, chestBoatModel); -+ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(result); - ImmutableMap definitions = result.build(); - List missingDefinitions = ModelLayers.getKnownLocations().filter(l -> !definitions.containsKey(l)).toList(); - if (!missingDefinitions.isEmpty()) { +@@ -572,6 +_,7 @@ + builder.put(ModelLayers.createHangingSignModelName(woodType, hangingsignblock$attachment), layerdefinition70); + } + }); ++ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(builder); + ImmutableMap immutablemap = builder.build(); + List list = ModelLayers.getKnownLocations().filter(l -> !immutablemap.containsKey(l)).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 new file mode 100644 index 0000000000..7407aaa41c --- /dev/null +++ b/patches/minecraft/net/minecraft/client/model/geom/ModelLayers.java.patch @@ -0,0 +1,24 @@ +--- a/net/minecraft/client/model/geom/ModelLayers.java ++++ b/net/minecraft/client/model/geom/ModelLayers.java +@@ -324,15 +_,18 @@ + } + + public static ModelLayerLocation createStandingSignModelName(final WoodType type) { +- return createLocation("sign/standing/" + type.name(), "main"); ++ Identifier location = Identifier.parse(type.name()); ++ return new ModelLayerLocation(Identifier.fromNamespaceAndPath(location.getNamespace(), "sign/standing/" + location.getPath()), "main"); + } + + public static ModelLayerLocation createWallSignModelName(final WoodType type) { +- return createLocation("sign/wall/" + type.name(), "main"); ++ Identifier location = Identifier.parse(type.name()); ++ return new ModelLayerLocation(Identifier.fromNamespaceAndPath(location.getNamespace(), "sign/wall/" + location.getPath()), "main"); + } + + public static ModelLayerLocation createHangingSignModelName(final WoodType type, final HangingSignBlock.Attachment attachmentType) { +- return createLocation("hanging_sign/" + type.name() + "/" + attachmentType.getSerializedName(), "main"); ++ Identifier location = Identifier.parse(type.name()); ++ return new ModelLayerLocation(Identifier.fromNamespaceAndPath(location.getNamespace(), "hanging_sign/" + location.getPath() + "/" + attachmentType.getSerializedName()), "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 18309f6ec9..a21d92e760 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(fetchedKeyPair); - return Optional.ofNullable(fetchedKeyPair); - } catch (IOException | CryptException | MinecraftClientException e) { +@@ -76,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", e); + LOGGER.error("Failed to retrieve profile key pair", (Throwable)ioexception); this.writeProfileKeyPair(null); return cachedKeyPair; diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch index e20e0e1797..a4fce51e58 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 -@@ -64,6 +_,7 @@ - int index = this.storage.getIndex(pos.x(), pos.z()); - LevelChunk currentChunk = this.storage.getChunk(index); - if (isValidChunk(currentChunk, pos.x(), pos.z())) { -+ net.minecraftforge.event.level.ChunkEvent.Unload.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(currentChunk)); - this.storage.drop(index, currentChunk); +@@ -65,6 +_,7 @@ + int i = this.storage.getIndex(pos.x(), pos.z()); + LevelChunk levelchunk = this.storage.getChunk(i); + if (isValidChunk(levelchunk, pos.x(), pos.z())) { ++ net.minecraftforge.event.level.ChunkEvent.Unload.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(levelchunk)); + this.storage.drop(i, levelchunk); } } @@ -124,6 +_,7 @@ + } + + this.level.onChunkLoaded(chunkpos); ++ net.minecraftforge.event.level.ChunkEvent.Load.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(levelchunk, false)); + return levelchunk; } - - this.level.onChunkLoaded(pos); -+ net.minecraftforge.event.level.ChunkEvent.Load.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(chunk, false)); - return chunk; } - diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch index 7502d7fa93..1038902575 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch @@ -5,6 +5,6 @@ @Override public void handleCustomPayload(final ClientboundCustomPayloadPacket packet) { + if (net.minecraftforge.common.ForgeHooks.onCustomPayload(packet.payload(), this.connection)) return; - CustomPacketPayload payload = packet.payload(); - if (!(payload instanceof DiscardedPayload)) { + CustomPacketPayload custompacketpayload = packet.payload(); + if (!(custompacketpayload instanceof DiscardedPayload)) { PacketUtils.ensureRunningOnSameThread(packet, this, this.minecraft.packetProcessor()); diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch index 5276b053c2..d12bfa070b 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java -@@ -144,6 +_,7 @@ - } - })); +@@ -148,6 +_,7 @@ + })); + } } + net.minecraftforge.common.ForgeHooks.handleClientConfigurationComplete(this.connection); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch index e35f76eaec..137f604874 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java -@@ -211,6 +_,7 @@ - Component title = this.wasTransferredTo ? CommonComponents.TRANSFER_CONNECT_FAILED : CommonComponents.CONNECT_FAILED; +@@ -209,6 +_,7 @@ + Component component = this.wasTransferredTo ? CommonComponents.TRANSFER_CONNECT_FAILED : CommonComponents.CONNECT_FAILED; if (this.serverData != null && this.serverData.isRealm()) { - this.minecraft.gui.setScreen(new DisconnectedScreen(this.parent, title, details.reason(), CommonComponents.GUI_BACK)); + this.minecraft.setScreen(new DisconnectedScreen(this.parent, component, details.reason(), CommonComponents.GUI_BACK)); + } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.connection, this.minecraft, this.parent, details.reason())) { } else { - this.minecraft.gui.setScreen(new DisconnectedScreen(this.parent, title, details)); + this.minecraft.setScreen(new DisconnectedScreen(this.parent, component, details)); } -@@ -235,6 +_,7 @@ +@@ -233,6 +_,7 @@ @Override public void handleCustomQuery(final ClientboundCustomQueryPacket packet) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch index e4aedd7cfb..d7f671294c 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/multiplayer/ClientLevel.java +++ b/net/minecraft/client/multiplayer/ClientLevel.java -@@ -165,6 +_,7 @@ +@@ -150,6 +_,7 @@ cache.put(BiomeColors.FOLIAGE_COLOR_RESOLVER, new BlockTintCache(pos -> this.calculateBlockTint(pos, BiomeColors.FOLIAGE_COLOR_RESOLVER))); cache.put(BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER, new BlockTintCache(pos -> this.calculateBlockTint(pos, BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER))); cache.put(BiomeColors.WATER_COLOR_RESOLVER, new BlockTintCache(pos -> this.calculateBlockTint(pos, BiomeColors.WATER_COLOR_RESOLVER))); @@ -8,8 +8,8 @@ }); private final ClientChunkCache chunkSource; private final Deque lightUpdateQueue = Queues.newArrayDeque(); -@@ -178,6 +_,8 @@ - private final Long2ObjectMap> destructionProgress = new Long2ObjectOpenHashMap<>(); +@@ -161,6 +_,8 @@ + private final EnvironmentAttributeSystem environmentAttributes; private final int seaLevel; 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<>(); @@ -17,16 +17,16 @@ public void handleBlockChangedAck(final int sequence) { if (SharedConstants.DEBUG_BLOCK_BREAK) { -@@ -260,6 +_,8 @@ - this.serverSimulationDistance = serverSimulationDistance; - this.environmentAttributes = this.addEnvironmentAttributeLayers(EnvironmentAttributeSystem.builder()).build(); - this.updateSkyBrightness(); +@@ -273,6 +_,8 @@ + + runnable.run(); + } + this.gatherCapabilities(); + net.minecraftforge.event.ForgeEventFactory.onLevelLoad(this); } - private EnvironmentAttributeSystem.Builder addEnvironmentAttributeLayers(final EnvironmentAttributeSystem.Builder environmentAttributes) { -@@ -471,6 +_,7 @@ + public @Nullable EndFlashState endFlashState() { +@@ -352,6 +_,7 @@ entity.setOldPosAndRot(); entity.tickCount++; Profiler.get().push(entity.typeHolder()::getRegisteredName); @@ -34,7 +34,7 @@ entity.tick(); Profiler.get().pop(); -@@ -527,8 +_,10 @@ +@@ -412,8 +_,10 @@ } public void addEntity(final Entity entity) { @@ -45,7 +45,7 @@ } public void removeEntity(final int id, final Entity.RemovalReason reason) { -@@ -692,8 +_,10 @@ +@@ -579,8 +_,10 @@ final float pitch, final long seed ) { @@ -57,7 +57,7 @@ } } -@@ -707,8 +_,10 @@ +@@ -594,8 +_,10 @@ final float pitch, final long seed ) { @@ -69,24 +69,24 @@ } } -@@ -1081,7 +_,7 @@ +@@ -951,7 +_,7 @@ @Override public void addDestroyBlockEffect(final BlockPos pos, final BlockState blockState) { - if (!blockState.isAir() && blockState.shouldSpawnTerrainParticles()) { + if (!blockState.isAir() && !net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).addDestroyEffects(blockState, this, pos, this.minecraft.particleEngine)) { - VoxelShape shape = blockState.getShape(this, pos); - double density = 0.25; - shape.forAllBoxes( -@@ -1108,6 +_,7 @@ + VoxelShape voxelshape = blockState.getShape(this, pos); + double d0 = 0.25; + voxelshape.forAllBoxes( +@@ -978,6 +_,7 @@ new TerrainParticle( - this, pos.getX() + x, pos.getY() + y, pos.getZ() + z, relX - 0.5, relY - 0.5, relZ - 0.5, blockState, pos + this, pos.getX() + d7, pos.getY() + d8, pos.getZ() + d9, d4 - 0.5, d5 - 0.5, d6 - 0.5, blockState, pos ) + .updateSprite(blockState, pos) ); } } -@@ -1117,6 +_,13 @@ +@@ -987,6 +_,13 @@ } } @@ -98,18 +98,18 @@ + + /** @deprecated Forge - Use crack(BlockPos, BlockHitResult) as it has more context and gives more control to modders */ public void addBreakingBlockEffect(final BlockPos pos, final Direction direction) { - BlockState blockState = this.getBlockState(pos); - if (blockState.getRenderShape() != RenderShape.INVISIBLE && blockState.shouldSpawnTerrainParticles()) { -@@ -1152,7 +_,7 @@ - xp = x + shape.maxX + 0.1F; + BlockState blockstate = this.getBlockState(pos); + if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.shouldSpawnTerrainParticles()) { +@@ -1022,7 +_,7 @@ + d0 = i + aabb.maxX + 0.1F; } -- this.minecraft.particleEngine.add(new TerrainParticle(this, xp, yp, zp, 0.0, 0.0, 0.0, blockState, pos).setPower(0.2F).scale(0.6F)); -+ this.minecraft.particleEngine.add(new TerrainParticle(this, xp, yp, zp, 0.0, 0.0, 0.0, blockState, pos).updateSprite(blockState, pos).setPower(0.2F).scale(0.6F)); +- this.minecraft.particleEngine.add(new TerrainParticle(this, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, pos).setPower(0.2F).scale(0.6F)); ++ this.minecraft.particleEngine.add(new TerrainParticle(this, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, pos).updateSprite(blockstate, pos).setPower(0.2F).scale(0.6F)); } } -@@ -1218,6 +_,16 @@ +@@ -1088,6 +_,16 @@ this.explosionTracker.track(center, radius, blockCount, blockParticles); } @@ -126,7 +126,7 @@ @OnlyIn(Dist.CLIENT) public static class ClientLevelData implements WritableLevelData { private final boolean hardcore; -@@ -1273,6 +_,7 @@ +@@ -1143,6 +_,7 @@ } public void setDifficulty(final Difficulty difficulty) { @@ -134,7 +134,7 @@ this.difficulty = difficulty; } -@@ -1315,6 +_,12 @@ +@@ -1190,6 +_,12 @@ break; default: } @@ -147,8 +147,8 @@ } public void onTrackingEnd(final Entity entity) { -@@ -1327,6 +_,15 @@ - ClientLevel.this.dragonParts.removeAll(Arrays.asList(dragon.getSubEntities())); +@@ -1202,6 +_,15 @@ + ClientLevel.this.dragonParts.removeAll(Arrays.asList(enderdragon.getSubEntities())); break; default: + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch index 93ba01ef1f..475f0c06fe 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/client/multiplayer/ClientPacketListener.java +++ b/net/minecraft/client/multiplayer/ClientPacketListener.java -@@ -531,6 +_,7 @@ +@@ -536,6 +_,7 @@ this.debugSubscriber.clear(); - this.minecraft.levelExtractor.debugRenderer.refreshRendererList(); + this.minecraft.levelRenderer.debugRenderer.refreshRendererList(); this.minecraft.player.resetPos(); + net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogin(this.minecraft.gameMode, this.minecraft.player, this.minecraft.getConnection().connection); this.minecraft.player.setId(packet.playerId()); this.level.addEntity(this.minecraft.player); this.minecraft.player.input = new KeyboardInput(this.minecraft.options); -@@ -1323,6 +_,8 @@ - newPlayer.getAttributes().assignBaseValues(oldPlayer.getAttributes()); +@@ -1345,6 +_,8 @@ + localplayer1.getAttributes().assignBaseValues(localplayer.getAttributes()); } -+ newPlayer.updateSyncFields(oldPlayer); // Forge: fix MC-10657 -+ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerRespawn(this.minecraft.gameMode, oldPlayer, newPlayer, newPlayer.connection.connection); - this.level.addEntity(newPlayer); - newPlayer.input = new KeyboardInput(this.minecraft.options); - this.minecraft.gameMode.adjustPlayer(newPlayer); -@@ -1478,7 +_,7 @@ - ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(blockEntity.problemPath(), LOGGER); ++ localplayer1.updateSyncFields(localplayer); // Forge: fix MC-10657 ++ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerRespawn(this.minecraft.gameMode, localplayer, localplayer1, localplayer1.connection.connection); + this.level.addEntity(localplayer1); + localplayer1.input = new KeyboardInput(this.minecraft.options); + this.minecraft.gameMode.adjustPlayer(localplayer1); +@@ -1504,7 +_,7 @@ + ProblemReporter.ScopedCollector problemreporter$scopedcollector = new ProblemReporter.ScopedCollector(blockEntity.problemPath(), LOGGER); try { -- blockEntity.loadWithComponents(TagValueInput.create(reporter, this.registryAccess, packet.getTag())); -+ blockEntity.onDataPacket(connection, TagValueInput.create(reporter, this.registryAccess, packet.getTag()), this.registryAccess); - } catch (Throwable t$) { +- blockEntity.loadWithComponents(TagValueInput.create(problemreporter$scopedcollector, this.registryAccess, packet.getTag())); ++ blockEntity.onDataPacket(connection, TagValueInput.create(problemreporter$scopedcollector, this.registryAccess, packet.getTag()), this.registryAccess); + } catch (Throwable throwable1) { try { - reporter.close(); -@@ -1686,7 +_,9 @@ + problemreporter$scopedcollector.close(); +@@ -1727,7 +_,9 @@ @Override public void handleCommands(final ClientboundCommandsPacket packet) { PacketUtils.ensureRunningOnSameThread(packet, this, this.minecraft.packetProcessor()); @@ -37,24 +37,24 @@ } @Override -@@ -1787,6 +_,7 @@ - if (this.minecraft.gui.screen() instanceof RecipeUpdateListener updateListener) { - updateListener.recipesUpdated(); +@@ -1828,6 +_,7 @@ + if (this.minecraft.screen instanceof RecipeUpdateListener recipeupdatelistener) { + recipeupdatelistener.recipesUpdated(); } + net.minecraftforge.client.event.ForgeEventFactoryClient.onRecipesUpdated(recipeBook); } @Override -@@ -1830,6 +_,8 @@ +@@ -1872,6 +_,8 @@ this.fuelValues = FuelValues.vanillaBurnTimes(this.registryAccess, this.enabledFeatures); - List searchItems = List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); - this.searchTrees.updateCreativeTags(searchItems); + List list1 = List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); + this.searchTrees.updateCreativeTags(list1); + + net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.registryAccess, true, this.connection.isMemoryConnection()); } @Override -@@ -2652,7 +_,9 @@ +@@ -2688,7 +_,9 @@ } } @@ -62,18 +62,18 @@ + public void sendChat(String content) { + content = net.minecraftforge.client.ForgeHooksClient.onClientSendMessage(content); + if (content.isEmpty()) return; - Instant timeStamp = Instant.now(); - long salt = Crypt.SaltSupplier.getLong(); - LastSeenMessagesTracker.Update lastSeenUpdate = this.lastSeenMessages.generateAndApplyUpdate(); -@@ -2661,6 +_,7 @@ + Instant instant = Instant.now(); + long i = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update lastseenmessagestracker$update = this.lastSeenMessages.generateAndApplyUpdate(); +@@ -2698,6 +_,7 @@ } public void sendCommand(final String command) { + if (net.minecraftforge.client.ClientCommandHandler.runCommand(command)) return; - SignableCommand signableCommand = SignableCommand.of(this.commands.parse(command, this.suggestionsProvider)); - if (signableCommand.arguments().isEmpty()) { + SignableCommand signablecommand = SignableCommand.of(this.commands.parse(command, this.suggestionsProvider)); + if (signablecommand.arguments().isEmpty()) { this.send(new ServerboundChatCommandPacket(command)); -@@ -2677,6 +_,7 @@ +@@ -2714,6 +_,7 @@ } public void sendUnattendedCommand(final String command, final @Nullable Screen screenAfterCommand) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch index 3f564487bf..5b6a49eda1 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch @@ -1,173 +1,163 @@ --- a/net/minecraft/client/multiplayer/MultiPlayerGameMode.java +++ b/net/minecraft/client/multiplayer/MultiPlayerGameMode.java -@@ -115,6 +_,7 @@ +@@ -114,6 +_,7 @@ } public boolean destroyBlock(final BlockPos pos) { + if (minecraft.player.getMainHandItem().onBlockStartBreak(pos, minecraft.player)) return false; if (this.minecraft.player.blockActionRestricted(this.minecraft.level, pos, this.localPlayerMode)) { return false; - } -@@ -134,9 +_,8 @@ - return false; - } - -- oldBlock.playerWillDestroy(level, pos, oldState, this.minecraft.player); - FluidState fluidState = level.getFluidState(pos); -- boolean changed = level.setBlock(pos, fluidState.createLegacyBlock(), 11); -+ boolean changed = oldState.onDestroyedByPlayer(level, pos, minecraft.player, false, fluidState); - if (changed) { - oldBlock.destroy(level, pos, oldState); - } -@@ -165,6 +_,7 @@ - } - - this.startPrediction(this.minecraft.level, sequence -> { -+ if (!net.minecraftforge.event.ForgeEventFactory.isLeftClickBlockCancelled(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK)) - this.destroyBlock(pos); - return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction, sequence); - }); -@@ -178,6 +_,7 @@ - this.connection - .send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, this.destroyBlockPos, direction)); - } -+ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); - - BlockState state = this.minecraft.level.getBlockState(pos); - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, state, 0.0F); -@@ -188,9 +_,11 @@ - this.startPrediction(this.minecraft.level, sequence -> { - boolean notAir = !state.isAir(); - if (notAir && this.destroyProgress == 0.0F) { -+ if (event != null && !event.getUseBlock().isDenied()) - state.attack(this.minecraft.level, pos, this.minecraft.player); - } - -+ if (event != null && !event.getUseItem().isDenied()) { - if (notAir && state.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos) >= 1.0F) { - this.destroyBlock(pos); + } else { +@@ -128,9 +_,8 @@ + } else if (blockstate.isAir()) { + return false; } else { -@@ -201,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, pos, direction, sequence); - }); -@@ -242,6 +_,7 @@ - } - - this.startPrediction(this.minecraft.level, sequence -> { -+ if (!net.minecraftforge.event.ForgeEventFactory.isLeftClickBlockCancelled(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK)) - this.destroyBlock(pos); - return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction, sequence); - }); -@@ -255,7 +_,7 @@ - - this.destroyProgress = this.destroyProgress + state.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos); - if (this.destroyTicks % 4.0F == 0.0F) { -- SoundType soundType = state.getSoundType(); -+ SoundType soundType = state.getSoundType(this.minecraft.level, pos, this.minecraft.player); - this.minecraft - .getSoundManager() - .play( -@@ -272,6 +_,7 @@ - - this.destroyTicks++; - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, state, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); -+ if (net.minecraftforge.event.ForgeEventFactory.onLeftClickBlockHold(this.minecraft.player, pos, direction).getUseItem().isDenied()) return true; - if (this.destroyProgress >= 1.0F) { - this.isDestroying = false; - if (SharedConstants.DEBUG_BLOCK_BREAK) { -@@ -279,6 +_,7 @@ +- block.playerWillDestroy(level, pos, blockstate, this.minecraft.player); + FluidState fluidstate = level.getFluidState(pos); +- boolean flag = level.setBlock(pos, fluidstate.createLegacyBlock(), 11); ++ boolean flag = blockstate.onDestroyedByPlayer(level, pos, minecraft.player, false, fluidstate); + if (flag) { + block.destroy(level, pos, blockstate); + } +@@ -159,6 +_,7 @@ } this.startPrediction(this.minecraft.level, sequence -> { + if (!net.minecraftforge.event.ForgeEventFactory.isLeftClickBlockCancelled(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK)) this.destroyBlock(pos); - return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, pos, direction, sequence); + return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction, sequence); }); -@@ -313,7 +_,7 @@ +@@ -172,6 +_,7 @@ + this.connection + .send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, this.destroyBlockPos, direction)); + } ++ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); + + BlockState blockstate1 = this.minecraft.level.getBlockState(pos); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, blockstate1, 0.0F); +@@ -182,9 +_,11 @@ + this.startPrediction(this.minecraft.level, sequence -> { + boolean flag = !blockstate1.isAir(); + if (flag && this.destroyProgress == 0.0F) { ++ if (event != null && !event.getUseBlock().isDenied()) + blockstate1.attack(this.minecraft.level, pos, this.minecraft.player); + } + ++ if (event != null && !event.getUseItem().isDenied()) { + if (flag && blockstate1.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos) >= 1.0F) { + this.destroyBlock(pos); + } else { +@@ -195,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, pos, direction, sequence); + }); +@@ -235,6 +_,7 @@ + } + + this.startPrediction(this.minecraft.level, sequence -> { ++ if (!net.minecraftforge.event.ForgeEventFactory.isLeftClickBlockCancelled(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK)) + this.destroyBlock(pos); + return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction, sequence); + }); +@@ -247,7 +_,7 @@ + } else { + this.destroyProgress = this.destroyProgress + blockstate.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos); + if (this.destroyTicks % 4.0F == 0.0F) { +- SoundType soundtype = blockstate.getSoundType(); ++ SoundType soundtype = blockstate.getSoundType(this.minecraft.level, pos, this.minecraft.player); + this.minecraft + .getSoundManager() + .play( +@@ -264,6 +_,7 @@ + + this.destroyTicks++; + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, blockstate, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); ++ if (net.minecraftforge.event.ForgeEventFactory.onLeftClickBlockHold(this.minecraft.player, pos, direction).getUseItem().isDenied()) return true; + if (this.destroyProgress >= 1.0F) { + this.isDestroying = false; + if (SharedConstants.DEBUG_BLOCK_BREAK) { +@@ -306,7 +_,7 @@ private boolean sameDestroyTarget(final BlockPos pos) { - ItemStack selected = this.minecraft.player.getMainHandItem(); -- return pos.equals(this.destroyBlockPos) && ItemStack.isSameItemSameComponents(selected, this.destroyingItem); -+ return pos.equals(this.destroyBlockPos) && !destroyingItem.shouldCauseBlockBreakReset(selected); + ItemStack itemstack = this.minecraft.player.getMainHandItem(); +- return pos.equals(this.destroyBlockPos) && ItemStack.isSameItemSameComponents(itemstack, this.destroyingItem); ++ return pos.equals(this.destroyBlockPos) && !destroyingItem.shouldCauseBlockBreakReset(itemstack); } private void ensureHasSentCarriedItem() { -@@ -341,13 +_,24 @@ +@@ -334,12 +_,23 @@ private InteractionResult performUseItemOn(final LocalPlayer player, final InteractionHand hand, final BlockHitResult blockHit) { - BlockPos pos = blockHit.getBlockPos(); - ItemStack itemStack = player.getItemInHand(hand); -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, pos, blockHit); + BlockPos blockpos = blockHit.getBlockPos(); + ItemStack itemstack = player.getItemInHand(hand); ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, blockpos, blockHit); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock.BUS.post(event)) { + return event.getCancellationResult(); + } if (this.localPlayerMode == GameType.SPECTATOR) { return InteractionResult.CONSUME; - } - -- boolean haveSomethingInOurHands = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); -+ UseOnContext context = new UseOnContext(player, hand, blockHit); -+ if (!event.getUseItem().isDenied()) { -+ InteractionResult result = itemStack.onItemUseFirst(context); -+ if (result != InteractionResult.PASS) { -+ return result; -+ } -+ } -+ boolean haveSomethingInOurHands = !player.getMainHandItem().doesSneakBypassUse(player.level(), pos, player) || !player.getOffhandItem().doesSneakBypassUse(player.level(), pos, player); - boolean suppressUsingBlock = player.isSecondaryUseActive() && haveSomethingInOurHands; -- if (!suppressUsingBlock) { -+ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !suppressUsingBlock)) { - BlockState blockState = this.minecraft.level.getBlockState(pos); - if (!this.connection.isFeatureEnabled(blockState.getBlock().requiredFeatures())) { - return InteractionResult.FAIL; -@@ -366,8 +_,10 @@ - } - } - -- if (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack)) { -- UseOnContext context = new UseOnContext(player, hand, blockHit); -+ if (event.getUseItem().isDenied()) { -+ return InteractionResult.PASS; -+ } -+ if (event.getUseItem().isAllowed() || (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack))) { - InteractionResult success; - if (player.hasInfiniteMaterials()) { - int count = itemStack.getCount(); -@@ -398,6 +_,12 @@ - return packet; - } - -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem(player, hand); -+ if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem.BUS.post(event)) { -+ interactionResult.setValue(event.getCancellationResult()); -+ return packet; + } else { +- boolean flag = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); ++ UseOnContext useoncontext = new UseOnContext(player, hand, blockHit); ++ if (!event.getUseItem().isDenied()) { ++ InteractionResult result = itemstack.onItemUseFirst(useoncontext); ++ if (result != InteractionResult.PASS) { ++ return result; ++ } + } -+ - InteractionResult resultHolder = itemStack.use(this.minecraft.level, player, hand); - ItemStack result; - if (resultHolder instanceof InteractionResult.Success success) { -@@ -408,6 +_,9 @@ - - if (result != itemStack) { - player.setItemInHand(hand, result); -+ if (result.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, itemStack, hand); -+ } ++ boolean flag = !player.getMainHandItem().doesSneakBypassUse(player.level(), blockpos, player) || !player.getOffhandItem().doesSneakBypassUse(player.level(), blockpos, player); + boolean flag1 = player.isSecondaryUseActive() && flag; +- if (!flag1) { ++ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !flag1)) { + BlockState blockstate = this.minecraft.level.getBlockState(blockpos); + if (!this.connection.isFeatureEnabled(blockstate.getBlock().requiredFeatures())) { + return InteractionResult.FAIL; +@@ -358,8 +_,10 @@ + } } - interactionResult.setValue(resultHolder); -@@ -445,6 +_,10 @@ +- if (!itemstack.isEmpty() && !player.getCooldowns().isOnCooldown(itemstack)) { +- UseOnContext useoncontext = new UseOnContext(player, hand, blockHit); ++ if (event.getUseItem().isDenied()) { ++ return InteractionResult.PASS; ++ } ++ if (event.getUseItem().isAllowed() || (!itemstack.isEmpty() && !player.getCooldowns().isOnCooldown(itemstack))) { + InteractionResult interactionresult2; + if (player.hasInfiniteMaterials()) { + int i = itemstack.getCount(); +@@ -389,6 +_,11 @@ + mutableobject.setValue(InteractionResult.PASS); + return serverbounduseitempacket; + } else { ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem(player, hand); ++ if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem.BUS.post(event)) { ++ mutableobject.setValue(event.getCancellationResult()); ++ return serverbounduseitempacket; ++ } + InteractionResult interactionresult = itemstack.use(this.minecraft.level, player, hand); + ItemStack itemstack1; + if (interactionresult instanceof InteractionResult.Success interactionresult$success) { +@@ -399,6 +_,9 @@ + + if (itemstack1 != itemstack) { + player.setItemInHand(hand, itemstack1); ++ if (itemstack1.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, itemstack, hand); ++ } + } + + mutableobject.setValue(interactionresult); +@@ -434,6 +_,10 @@ this.ensureHasSentCarriedItem(); - Vec3 location = hitResult.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); - this.connection.send(new ServerboundInteractPacket(entity.getId(), hand, location, player.isShiftKeyDown())); + Vec3 vec3 = hitResult.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); + this.connection.send(new ServerboundInteractPacket(entity.getId(), hand, vec3, player.isShiftKeyDown())); + if (this.localPlayerMode != GameType.SPECTATOR) { -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, location); ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific.BUS.post(event)) return event.getCancellationResult(); + } - return this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : player.interactOn(entity, hand, location); + return (InteractionResult)(this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : player.interactOn(entity, hand, vec3)); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch index b30ddd96a7..b0e87ba8f2 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/client/multiplayer/ServerStatusPinger.java +++ b/net/minecraft/client/multiplayer/ServerStatusPinger.java -@@ -118,6 +_,7 @@ +@@ -124,6 +_,7 @@ onPersistentDataChange.run(); } }); -+ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(status, data); ++ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(serverstatus, data); this.pingStart = Util.getMillis(); connection.send(new ServerboundPingRequestPacket(this.pingStart)); this.success = true; -@@ -174,7 +_,7 @@ +@@ -180,7 +_,7 @@ private void pingLegacyServer( final InetSocketAddress resolvedAddress, final ServerAddress rawAddress, final ServerData data, final EventLoopGroupHolder eventLoopGroupHolder ) { - new Bootstrap().group(eventLoopGroupHolder.eventLoopGroup()).handler(new ChannelInitializer() { + new Bootstrap().group(eventLoopGroupHolder.eventLoopGroup(true)).handler(new ChannelInitializer() { - @Override - protected void initChannel(final Channel channel) { - try { + { + Objects.requireNonNull(ServerStatusPinger.this); + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch index fd72487550..5cd36219b3 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/multiplayer/SessionSearchTrees.java +++ b/net/minecraft/client/multiplayer/SessionSearchTrees.java -@@ -33,8 +_,8 @@ +@@ -34,8 +_,8 @@ private static final SessionSearchTrees.Key RECIPE_COLLECTIONS = new SessionSearchTrees.Key(); public static final SessionSearchTrees.Key CREATIVE_NAMES = new SessionSearchTrees.Key(); public static final SessionSearchTrees.Key CREATIVE_TAGS = new SessionSearchTrees.Key(); @@ -11,7 +11,7 @@ private CompletableFuture> recipeSearch = CompletableFuture.completedFuture(SearchTree.empty()); private final Map reloaders = new IdentityHashMap<>(); -@@ -89,44 +_,52 @@ +@@ -90,44 +_,52 @@ } public void updateCreativeTags(final List items) { @@ -20,16 +20,16 @@ - CREATIVE_TAGS, + entry.getValue(), () -> { -- CompletableFuture previous = this.creativeByTagSearch; +- CompletableFuture completablefuture = this.creativeByTagSearch; - this.creativeByTagSearch = CompletableFuture.supplyAsync( - () -> new IdSearchTree<>(itemStack -> itemStack.tags().map(TagKey::location), items), Util.backgroundExecutor() - ); + var tabItems = entry.getKey() == net.minecraft.world.item.CreativeModeTabs.searchTab() ? items : List.copyOf(entry.getKey().getDisplayItems()); -+ CompletableFuture previous = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); ++ CompletableFuture completablefuture = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); + this.creativeSearch.put(entry.getValue(), CompletableFuture.supplyAsync( + () -> new IdSearchTree<>(itemStack -> itemStack.tags().map(TagKey::location), tabItems), Util.backgroundExecutor() + )); - previous.cancel(true); + completablefuture.cancel(true); } ); } @@ -46,14 +46,14 @@ + entry.getValue(), () -> { + var items = entry.getKey() == net.minecraft.world.item.CreativeModeTabs.searchTab() ? itemStacks : List.copyOf(entry.getKey().getDisplayItems()); - Item.TooltipContext tooltipContext = Item.TooltipContext.of(registries); - TooltipFlag tooltipFlag = TooltipFlag.Default.NORMAL.asCreative(); -- CompletableFuture previous = this.creativeByNameSearch; + Item.TooltipContext item$tooltipcontext = Item.TooltipContext.of(registries); + TooltipFlag tooltipflag = TooltipFlag.Default.NORMAL.asCreative(); +- CompletableFuture completablefuture = this.creativeByNameSearch; - this.creativeByNameSearch = CompletableFuture.supplyAsync( -+ CompletableFuture previous = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); ++ CompletableFuture completablefuture = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); + this.creativeSearch.put(entry.getValue(), CompletableFuture.supplyAsync( () -> new FullTextSearchTree<>( - itemStack -> getTooltipLines(Stream.of(itemStack), tooltipContext, tooltipFlag), + itemStack -> getTooltipLines(Stream.of(itemStack), item$tooltipcontext, tooltipflag), itemStack -> itemStack.typeHolder().unwrapKey().map(ResourceKey::identifier).stream(), - itemStacks + items @@ -61,7 +61,7 @@ Util.backgroundExecutor() - ); + )); - previous.cancel(true); + completablefuture.cancel(true); } ); } 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 a44448243a..85168444ee 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch @@ -1,46 +1,44 @@ --- a/net/minecraft/client/multiplayer/chat/ChatListener.java +++ b/net/minecraft/client/multiplayer/chat/ChatListener.java -@@ -142,6 +_,8 @@ - LocalPlayer receiver = this.minecraft.player; - if (receiver != null && receiver.chatAbilities().canReceivePlayerMessages()) { - Component decoratedMessage = boundChatType.decorate(message); -+ decoratedMessage = net.minecraftforge.client.ForgeHooksClient.onClientChat(boundChatType, decoratedMessage, Util.NIL_UUID); -+ if (decoratedMessage == null) return false; - this.minecraft.gui.hud.getChat().addPlayerMessage(decoratedMessage, null, GuiMessageTag.system()); +@@ -140,6 +_,8 @@ + LocalPlayer localplayer = this.minecraft.player; + if (localplayer != null && localplayer.chatAbilities().canReceivePlayerMessages()) { + Component component = boundChatType.decorate(message); ++ component = net.minecraftforge.client.ForgeHooksClient.onClientChat(boundChatType, component, Util.NIL_UUID); ++ if (component == null) return false; + this.minecraft.gui.getChat().addPlayerMessage(component, null, GuiMessageTag.system()); this.narrateChatMessage(boundChatType, message); - this.logSystemMessage(decoratedMessage, received); -@@ -177,12 +_,16 @@ - MessageSignature signature = message.signature(); - FilterMask filterMask = message.filterMask(); - if (filterMask.isEmpty()) { -- this.minecraft.gui.hud.getChat().addPlayerMessage(decoratedMessage, signature, tag); + this.logSystemMessage(component, instant); +@@ -169,12 +_,16 @@ + MessageSignature messagesignature = message.signature(); + FilterMask filtermask = message.filterMask(); + if (filtermask.isEmpty()) { +- this.minecraft.gui.getChat().addPlayerMessage(decoratedMessage, messagesignature, guimessagetag); + Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, decoratedMessage, message, message.sender()); + if (forgeComponent == null) return false; -+ this.minecraft.gui.hud.getChat().addPlayerMessage(forgeComponent, signature, tag); ++ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, messagesignature, guimessagetag); this.narrateChatMessage(boundChatType, message.decoratedContent()); } else { - Component filteredContent = filterMask.applyWithFormatting(message.signedContent()); - if (filteredContent != null) { -- this.minecraft.gui.hud.getChat().addPlayerMessage(boundChatType.decorate(filteredContent), signature, tag); -+ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, boundChatType.decorate(filteredContent), message, message.sender()); + Component component = filtermask.applyWithFormatting(message.signedContent()); + if (component != null) { +- this.minecraft.gui.getChat().addPlayerMessage(boundChatType.decorate(component), messagesignature, guimessagetag); ++ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, boundChatType.decorate(component), message, message.sender()); + if (forgeComponent == null) return false; -+ this.minecraft.gui.hud.getChat().addPlayerMessage(forgeComponent, signature, tag); - this.narrateChatMessage(boundChatType, filteredContent); ++ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, messagesignature, guimessagetag); + this.narrateChatMessage(boundChatType, component); } } -@@ -216,12 +_,14 @@ - chatLog.push(LoggedChatMessage.system(message, timeStamp)); +@@ -208,10 +_,12 @@ + chatlog.push(LoggedChatMessage.system(message, timeStamp)); } - public void handleSystemMessage(final Component message, final boolean remote) { + public void handleSystemMessage(Component message, final boolean remote) { - UUID guessedUUID = this.guessChatUUID(message); - if (!this.minecraft.options.hideMatchedNames().get() || !this.minecraft.isBlocked(guessedUUID)) { - if (guessedUUID == Util.NIL_UUID || !this.minecraft.isFriendOnlyRestricted(guessedUUID)) { - LocalPlayer receiver = this.minecraft.player; - if (receiver != null && receiver.chatAbilities().canReceiveSystemMessages()) { -+ message = net.minecraftforge.client.ForgeHooksClient.onClientSystemMessage(message, remote); -+ if (message == null) return; - if (remote) { - this.minecraft.gui.hud.getChat().addServerSystemMessage(message); - this.logSystemMessage(message, Instant.now()); + if (!this.minecraft.options.hideMatchedNames().get() || !this.minecraft.isBlocked(this.guessChatUUID(message))) { + LocalPlayer localplayer = this.minecraft.player; + if (localplayer != null && localplayer.chatAbilities().canReceiveSystemMessages()) { ++ message = net.minecraftforge.client.ForgeHooksClient.onClientSystemMessage(message, remote); ++ if (message == null) return; + if (remote) { + this.minecraft.gui.getChat().addServerSystemMessage(message); + this.logSystemMessage(message, Instant.now()); 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 c7a72f7f4e..8c79125e4f 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch @@ -4,8 +4,8 @@ boolean isAllowed(ServerAddress address); static AddressCheck createFromService() { -- final ImmutableList> blockLists = Streams.stream(ServiceLoader.load(BlockListSupplier.class)) -+ final ImmutableList> blockLists = Streams.stream(ServiceLoader.load(BlockListSupplier.class, net.minecraftforge.fml.loading.FMLLoader.class.getClassLoader())) +- 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/FireworkParticles.java.patch b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch index e010a4a758..2b192da3fc 100644 --- a/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/particle/FireworkParticles.java +++ b/net/minecraft/client/particle/FireworkParticles.java @@ -256,6 +_,10 @@ - colors = IntList.of(DyeColor.BLACK.getFireworkColor()); + intlist = IntList.of(DyeColor.BLACK.getFireworkColor()); } -+ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(explosion.shape()); ++ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(fireworkexplosion1.shape()); + if (factory != null) -+ factory.build(this, trail, twinkle, colors.toIntArray(), colors.toIntArray()); ++ factory.build(this, flag3, flag4, intlist.toIntArray(), intlist1.toIntArray()); + else - switch (explosion.shape()) { + switch (fireworkexplosion1.shape()) { case SMALL_BALL: - this.createParticleBall(0.25, 2, colors, fadeColors, trail, twinkle); + 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 index b8cbb0e086..1ce295bf48 100644 --- a/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/FlyTowardsPositionParticle.java +++ b/net/minecraft/client/particle/FlyTowardsPositionParticle.java @@ -107,6 +_,7 @@ - this.x = this.xStart + this.xd * pos; - this.y = this.yStart + this.yd * pos - pp * 1.2F; - this.z = this.zStart + this.zd * pos; + this.x = this.xStart + this.xd * f; + this.y = this.yStart + this.yd * f - f1 * 1.2F; + this.z = this.zStart + this.zd * 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 a35194545d..0c38eaf21f 100644 --- a/patches/minecraft/net/minecraft/client/particle/Particle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/Particle.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/particle/Particle.java +++ b/net/minecraft/client/particle/Particle.java -@@ -208,6 +_,10 @@ +@@ -205,6 +_,10 @@ return Optional.empty(); } diff --git a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch index e2d8d3f95a..8300437bbb 100644 --- a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch @@ -1,24 +1,25 @@ --- a/net/minecraft/client/particle/ParticleEngine.java +++ b/net/minecraft/client/particle/ParticleEngine.java -@@ -64,7 +_,7 @@ - private @Nullable Particle makeParticle( +@@ -64,8 +_,7 @@ final T options, final double x, final double y, final double z, final double xa, final double ya, final double za ) { -- ParticleProvider provider = (ParticleProvider)this.resourceManager.getProviders().get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType())); -+ ParticleProvider provider = (ParticleProvider)this.resourceManager.getProvider(options.getType()); - return provider == null ? null : provider.createParticle(options, this.level, x, y, z, xa, ya, za, this.random); + ParticleProvider particleprovider = (ParticleProvider)this.resourceManager +- .getProviders() +- .get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType())); ++ .getProvider(options.getType()); + return particleprovider == null ? null : particleprovider.createParticle(options, this.level, x, y, z, xa, ya, za, this.random); } -@@ -114,6 +_,8 @@ +@@ -113,6 +_,8 @@ return new ItemPickupParticleGroup(this); } else if (type == ParticleRenderType.ELDER_GUARDIANS) { return new ElderGuardianParticleGroup(this); + } else if (factories.containsKey(type)) { + return factories.get(type).apply(this); } else { - return type == ParticleRenderType.NO_RENDER ? new NoRenderParticleGroup(this) : new QuadParticleGroup(this, type); + return (ParticleGroup)(type == ParticleRenderType.NO_RENDER ? new NoRenderParticleGroup(this) : new QuadParticleGroup(this, type)); } -@@ -123,8 +_,20 @@ +@@ -122,8 +_,20 @@ this.trackedParticleCounts.addTo(limit, change); } @@ -35,8 +36,8 @@ + } + public void extract(final ParticlesRenderState particlesRenderState, final Frustum frustum, final Camera camera, final float partialTickTime) { -- for (ParticleRenderType particleType : RENDER_ORDER) { -+ for (ParticleRenderType particleType : particleRenderOrder) { // Forge: allow custom ParticleRenderType's - ParticleGroup particles = this.particles.get(particleType); - if (particles != null && !particles.isEmpty()) { - particlesRenderState.add(particles.extractRenderState(frustum, camera, partialTickTime)); +- for (ParticleRenderType particlerendertype : RENDER_ORDER) { ++ for (ParticleRenderType particlerendertype : particleRenderOrder) { // Forge: allow custom ParticleRenderType's + ParticleGroup particlegroup = this.particles.get(particlerendertype); + if (particlegroup != null && !particlegroup.isEmpty()) { + particlesRenderState.add(particlegroup.extractRenderState(frustum, camera, partialTickTime)); diff --git a/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch b/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch index 405fb678b4..01848d5f0a 100644 --- a/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch @@ -8,8 +8,8 @@ private @Nullable Runnable onReload; public ParticleResources() { -@@ -183,14 +_,17 @@ - this.register(ParticleTypes.SULFUR_CUBE_GOO, BreakingItemParticle.SulfurCubeProvider::new); +@@ -175,14 +_,17 @@ + this.register(ParticleTypes.FIREFLY, FireflyParticle.FireflyProvider::new); } + /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ @@ -20,14 +20,14 @@ + /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ public void register(final ParticleType type, final ParticleResources.SpriteParticleRegistration provider) { - ParticleResources.MutableSpriteSet spriteSet = new ParticleResources.MutableSpriteSet(); - this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(type), spriteSet); -- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(type), provider.create(spriteSet)); -+ register(type, provider.create(spriteSet)); + ParticleResources.MutableSpriteSet particleresources$mutablespriteset = new ParticleResources.MutableSpriteSet(); + this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(type), particleresources$mutablespriteset); +- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(type), provider.create(particleresources$mutablespriteset)); ++ register(type, provider.create(particleresources$mutablespriteset)); } @Override -@@ -281,8 +_,13 @@ +@@ -278,8 +_,13 @@ } } diff --git a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch index 755c17877b..6e013dc2fe 100644 --- a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/PortalParticle.java +++ b/net/minecraft/client/particle/PortalParticle.java -@@ -85,6 +_,7 @@ - this.x = this.xStart + this.xd * pos; - this.y = this.yStart + this.yd * pos + (1.0F - a); - this.z = this.zStart + this.zd * pos; +@@ -84,6 +_,7 @@ + this.x = this.xStart + this.xd * f2; + this.y = this.yStart + this.yd * f2 + (1.0F - f); + this.z = this.zStart + this.zd * 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 9e4ae118c2..bd115b3485 100644 --- a/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/ReversePortalParticle.java +++ b/net/minecraft/client/particle/ReversePortalParticle.java @@ -42,6 +_,7 @@ - this.x = this.x + this.xd * speedMultiplier; - this.y = this.y + this.yd * speedMultiplier; - this.z = this.z + this.zd * speedMultiplier; + this.x = this.x + this.xd * f; + this.y = this.y + this.yd * f; + this.z = this.z + this.zd * 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 b72b1f8e6a..b3314754fe 100644 --- a/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch @@ -3,18 +3,18 @@ @@ -43,7 +_,7 @@ this.gCol = 0.6F; this.bCol = 0.6F; - BlockTintSource tintSource = Minecraft.getInstance().getBlockColors().getTintSource(blockState, 0); -- if (tintSource != null) { -+ if (tintSource != null && net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).areBreakingParticlesTinted(blockState, level, pos)) { - int col = tintSource.colorAsTerrainParticle(blockState, level, pos); - this.rCol *= (col >> 16 & 0xFF) / 255.0F; - this.gCol *= (col >> 8 & 0xFF) / 255.0F; + BlockTintSource blocktintsource = Minecraft.getInstance().getBlockColors().getTintSource(blockState, 0); +- if (blocktintsource != null) { ++ if (blocktintsource != null && net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).areBreakingParticlesTinted(blockState, level, pos)) { + int i = blocktintsource.colorAsTerrainParticle(blockState, level, pos); + this.rCol *= (i >> 16 & 0xFF) / 255.0F; + this.gCol *= (i >> 8 & 0xFF) / 255.0F; @@ -93,8 +_,14 @@ ) { - BlockState state = options.getState(); - return !state.isAir() && !state.is(Blocks.MOVING_PISTON) && state.shouldSpawnTerrainParticles() -- ? new TerrainParticle(level, x, y, z, xAux, yAux, zAux, state) -+ ? (TerrainParticle)new TerrainParticle(level, x, y, z, xAux, yAux, zAux, state).updateSprite(state, options.getPos()) + BlockState blockstate = options.getState(); + return !blockstate.isAir() && !blockstate.is(Blocks.MOVING_PISTON) && blockstate.shouldSpawnTerrainParticles() +- ? new TerrainParticle(level, x, y, z, xAux, yAux, zAux, blockstate) ++ ? (TerrainParticle)new TerrainParticle(level, x, y, z, xAux, yAux, zAux, blockstate).updateSprite(blockstate, options.getPos()) : null; + } + diff --git a/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch index 1233dedf45..61cfafc590 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 @@ -87,6 +_,7 @@ - this.x = Mth.lerp(alpha, this.x, destination.x()); - this.y = Mth.lerp(alpha, this.y, destination.y()); - this.z = Mth.lerp(alpha, this.z, destination.z()); + 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 dx = this.x - destination.x(); - double dy = this.y - destination.y(); - double dz = this.z - destination.z(); + 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 c0cd60352a..c4db09489e 100644 --- a/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch @@ -4,8 +4,8 @@ } } -- return Mth.lerp(effectScale, 1.0F, modifier); -+ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireFovModifierEvent(this, modifier, effectScale).getNewFovModifier(); +- return Mth.lerp(effectScale, 1.0F, f); ++ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireFovModifierEvent(this, f, effectScale).getNewFovModifier(); } @Override diff --git a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch index 6ccb204b23..500c4d65e5 100644 --- a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/player/LocalPlayer.java +++ b/net/minecraft/client/player/LocalPlayer.java -@@ -318,6 +_,7 @@ - ServerboundPlayerActionPacket.Action action = all +@@ -324,6 +_,7 @@ + ServerboundPlayerActionPacket.Action serverboundplayeractionpacket$action = all ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS : ServerboundPlayerActionPacket.Action.DROP_ITEM; + if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (all || getUseItem().getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the clientside - ItemStack prediction = this.getInventory().removeFromSelected(all); - this.connection.send(new ServerboundPlayerActionPacket(action, BlockPos.ZERO, Direction.DOWN)); - return !prediction.isEmpty(); -@@ -545,7 +_,10 @@ + ItemStack itemstack = this.getInventory().removeFromSelected(all); + this.connection.send(new ServerboundPlayerActionPacket(serverboundplayeractionpacket$action, BlockPos.ZERO, Direction.DOWN)); + return !itemstack.isEmpty(); +@@ -551,7 +_,10 @@ @Override public void playSound(final SoundEvent sound, final float volume, final float pitch) { @@ -20,15 +20,15 @@ } @Override -@@ -787,6 +_,7 @@ +@@ -793,6 +_,7 @@ && this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.CROUCHING) && (this.isShiftKeyDown() || !this.isSleeping() && !this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.STANDING)); this.input.tick(); + net.minecraftforge.client.ForgeHooksClient.onMovementInputUpdate(this, this.input); this.minecraft.getTutorial().onInput(this.input); - boolean wasAutoJump = false; + boolean flag3 = false; if (this.autoJumpTime > 0) { -@@ -859,8 +_,9 @@ +@@ -865,8 +_,9 @@ } this.wasFallFlying = this.isFallFlying(); @@ -40,7 +40,7 @@ } if (this.isEyeInFluid(FluidTags.WATER)) { -@@ -928,7 +_,7 @@ +@@ -934,7 +_,7 @@ } private boolean shouldStopSwimSprinting() { @@ -49,16 +49,16 @@ } public Portal.Transition getActivePortalLocalTransition() { -@@ -973,6 +_,8 @@ +@@ -979,6 +_,8 @@ @Override public void rideTick() { super.rideTick(); + if (this.wantsToStopRiding() && this.isPassenger()) + this.input.keyPresses = this.input.keyPresses.jump(false); this.handsBusy = false; - if (this.getControlledVehicle() instanceof AbstractBoat boat) { - boat.setInput(this.input.keyPresses.left(), this.input.keyPresses.right(), this.input.keyPresses.forward(), this.input.keyPresses.backward()); -@@ -1147,7 +_,7 @@ + if (this.getControlledVehicle() instanceof AbstractBoat abstractboat) { + abstractboat.setInput( +@@ -1154,7 +_,7 @@ && this.isSprintingPossible(this.getAbilities().flying) && !this.isSlowDueToUsingItem() && (!this.isFallFlying() || this.isUnderWater()) @@ -67,7 +67,7 @@ } private boolean vehicleCanSprint(final Entity vehicle) { -@@ -1222,6 +_,17 @@ +@@ -1230,6 +_,17 @@ @Override public float getVisualRotationYInDegrees() { return this.getYRot(); diff --git a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch index 6c126a4949..d0058d90b1 100644 --- a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/GameRenderer.java +++ b/net/minecraft/client/renderer/GameRenderer.java -@@ -220,6 +_,9 @@ +@@ -235,6 +_,9 @@ case null: default: this.clearPostEffect(); @@ -10,24 +10,47 @@ } } -@@ -515,6 +_,10 @@ - Registry blockRegistry = this.minecraft.level.registryAccess().lookupOrThrow(Registries.BLOCK); - renderOutline = !itemStack.isEmpty() - && (itemStack.canBreakBlockInAdventureMode(blockInWorld) || itemStack.canPlaceOnBlockInAdventureMode(blockInWorld)); -+ if (!renderOutline && blockState.hasBlockEntity()) { -+ var blockEntity = this.minecraft.level.getBlockEntity(pos); -+ renderOutline = blockEntity != null && blockEntity.hasCustomOutlineRendering(); -+ } +@@ -246,7 +_,13 @@ + public void processBlurEffect() { + PostChain postchain = this.minecraft.getShaderManager().getPostChain(BLUR_POST_CHAIN_ID, LevelTargetBundle.MAIN_TARGETS); + if (postchain != null) { ++ // TODO: [Forge][Rendering] Check if this blend management is needed anymnore with the new render pipeline changes ++ boolean wasBlendEnabled = com.mojang.blaze3d.opengl.GlStateManager._isBlendEnabled(); ++ if (wasBlendEnabled) ++ com.mojang.blaze3d.opengl.GlStateManager._disableBlend(); + postchain.process(this.minecraft.getMainRenderTarget(), this.resourcePool); ++ if (wasBlendEnabled) ++ com.mojang.blaze3d.opengl.GlStateManager._enableBlend(); + } + } + +@@ -507,7 +_,7 @@ + profilerfiller.push("screen"); + + try { +- this.minecraft.screen.extractRenderStateWithTooltipAndSubtitles(guigraphicsextractor, i, j, deltaTracker.getGameTimeDeltaTicks()); ++ net.minecraftforge.client.ForgeHooksClient.drawScreen(this.minecraft.screen, guigraphicsextractor, i, j, deltaTracker.getRealtimeDeltaTicks()); + } catch (Throwable throwable) { + CrashReport crashreport1 = CrashReport.forThrowable(throwable, "Rendering screen"); + CrashReportCategory crashreportcategory1 = crashreport1.addCategory("Screen render details"); +@@ -672,6 +_,10 @@ + Registry registry = this.minecraft.level.registryAccess().lookupOrThrow(Registries.BLOCK); + flag = !itemstack.isEmpty() + && (itemstack.canBreakBlockInAdventureMode(blockinworld) || itemstack.canPlaceOnBlockInAdventureMode(blockinworld)); ++ if (!flag && blockstate.hasBlockEntity()) { ++ var blockEntity = this.minecraft.level.getBlockEntity(blockpos); ++ flag = blockEntity != null && blockEntity.hasCustomOutlineRendering(); ++ } + } } } - } -@@ -538,6 +_,9 @@ - if (optionsState.bobView) { - this.bobView(cameraState, bobStack); +@@ -696,6 +_,9 @@ + if (optionsrenderstate.bobView) { + this.bobView(camerarenderstate, posestack); } + -+ var cameraSetup = net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeCameraAngles(this, this.mainCamera, worldPartialTicks); ++ var cameraSetup = net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeCameraAngles(this, this.mainCamera, f); + this.mainCamera.setRotation(cameraSetup.getYaw(), cameraSetup.getPitch(), cameraSetup.getRoll()); - projectionMatrix.mul(bobStack.last().pose()); - float screenEffectScale = optionsState.screenEffectScale; + matrix4f.mul(posestack.last().pose()); + float f2 = optionsrenderstate.screenEffectScale; diff --git a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch index 4406fd83bb..7253bbc9cf 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch @@ -1,57 +1,55 @@ --- a/net/minecraft/client/renderer/ItemInHandRenderer.java +++ b/net/minecraft/client/renderer/ItemInHandRenderer.java -@@ -362,6 +_,7 @@ - float mainHandAttack = attackHand == InteractionHand.MAIN_HAND ? attackValue : 0.0F; - float mainhandInverseArmHeight = this.itemModelResolver.swapAnimationScale(this.mainHandItem) - * (1.0F - Mth.lerp(frameInterp, this.oMainHandHeight, this.mainHandHeight)); -+ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, xRot, mainHandAttack, mainhandInverseArmHeight, this.mainHandItem)) - this.submitArmWithItem( - player, - frameInterp, -@@ -380,6 +_,8 @@ - float offHandAttack = attackHand == InteractionHand.OFF_HAND ? attackValue : 0.0F; - float offhandInverseArmHeight = this.itemModelResolver.swapAnimationScale(this.offHandItem) - * (1.0F - Mth.lerp(frameInterp, this.oOffHandHeight, this.offHandHeight)); -+ -+ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, xRot, offHandAttack, offhandInverseArmHeight, this.offHandItem)) - this.submitArmWithItem( - player, - frameInterp, -@@ -454,7 +_,7 @@ +@@ -366,12 +_,14 @@ + if (iteminhandrenderer$handrenderselection.renderMainHand) { + float f4 = interactionhand == InteractionHand.MAIN_HAND ? f : 0.0F; + float f5 = this.itemModelResolver.swapAnimationScale(this.mainHandItem) * (1.0F - Mth.lerp(frameInterp, this.oMainHandHeight, this.mainHandHeight)); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, f1, f4, f5, this.mainHandItem)) + this.renderArmWithItem(player, frameInterp, f1, InteractionHand.MAIN_HAND, f4, this.mainHandItem, f5, poseStack, submitNodeCollector, lightCoords); + } + + if (iteminhandrenderer$handrenderselection.renderOffHand) { + float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F; + float f7 = this.itemModelResolver.swapAnimationScale(this.offHandItem) * (1.0F - Mth.lerp(frameInterp, this.oOffHandHeight, this.offHandHeight)); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, f1, f6, f7, this.offHandItem)) + this.renderArmWithItem(player, frameInterp, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, poseStack, submitNodeCollector, lightCoords); + } + +@@ -438,7 +_,7 @@ } else { - this.renderOneHandedMap(poseStack, submitNodeCollector, lightCoords, inverseArmHeight, arm, attack, itemStack); + this.renderOneHandedMap(poseStack, submitNodeCollector, lightCoords, inverseArmHeight, humanoidarm, attack, itemStack); } - } else if (itemStack.is(Items.CROSSBOW)) { + } else if (itemStack.getItem() instanceof CrossbowItem) { - this.applyItemArmTransform(poseStack, arm, inverseArmHeight); - boolean charged = CrossbowItem.isCharged(itemStack); - boolean isRightArm = arm == HumanoidArm.RIGHT; -@@ -499,6 +_,7 @@ + this.applyItemArmTransform(poseStack, humanoidarm, inverseArmHeight); + boolean flag1 = CrossbowItem.isCharged(itemStack); + boolean flag2 = humanoidarm == HumanoidArm.RIGHT; +@@ -483,6 +_,7 @@ } else { - boolean isRightArm = arm == HumanoidArm.RIGHT; - int invert = isRightArm ? 1 : -1; -+ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemStack).applyForgeHandTransform(poseStack, minecraft.player, arm, itemStack, frameInterp, inverseArmHeight, attack)) // FORGE: Allow items to define custom arm animation + boolean flag3 = humanoidarm == HumanoidArm.RIGHT; + int j = flag3 ? 1 : -1; ++ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemStack).applyForgeHandTransform(poseStack, minecraft.player, humanoidarm, itemStack, frameInterp, inverseArmHeight, attack)) // FORGE: Allow items to define custom arm animation if (player.isUsingItem() && player.getUseItemRemainingTicks() > 0 && player.getUsedItemHand() == hand) { - ItemUseAnimation useAnimation = itemStack.getUseAnimation(); - if (!useAnimation.hasCustomArmTransform()) { -@@ -647,8 +_,18 @@ + ItemUseAnimation itemuseanimation = itemStack.getUseAnimation(); + if (!itemuseanimation.hasCustomArmTransform()) { +@@ -628,8 +_,18 @@ this.offHandHeight = Mth.clamp(this.offHandHeight - 0.4F, 0.0F, 1.0F); } else { - float attackAnim = player.getItemSwapScale(1.0F); -- float mainHandTargetHeight = this.mainHandItem != nextMainHand ? 0.0F : attackAnim * attackAnim * attackAnim; -- float offHandTargetHeight = this.offHandItem != nextOffHand ? 0.0F : 1.0F; + float f = localplayer.getItemSwapScale(1.0F); +- float f1 = this.mainHandItem != itemstack ? 0.0F : f * f * f; +- float f2 = this.offHandItem != itemstack1 ? 0.0F : 1.0F; + -+ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, nextMainHand, player.getInventory().getSelectedSlot()); -+ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, nextOffHand, -1); ++ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, itemstack, localplayer.getInventory().getSelectedSlot()); ++ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, itemstack1, -1); + -+ if (!requipM && this.mainHandItem != nextMainHand) -+ this.mainHandItem = nextMainHand; -+ if (!requipO && this.offHandItem != nextOffHand) -+ this.offHandItem = nextOffHand; ++ if (!requipM && this.mainHandItem != itemstack) ++ this.mainHandItem = itemstack; ++ if (!requipO && this.offHandItem != itemstack1) ++ this.offHandItem = itemstack1; + -+ float mainHandTargetHeight = requipM ? 0.0F : attackAnim * attackAnim * attackAnim; -+ float offHandTargetHeight = requipO ? 0.0F : 1.0F; ++ float f1 = requipM ? 0.0F : f * f * f; ++ float f2 = requipO ? 0.0F : 1.0F; + - this.mainHandHeight = this.mainHandHeight + Mth.clamp(mainHandTargetHeight - this.mainHandHeight, -0.4F, 0.4F); - this.offHandHeight = this.offHandHeight + Mth.clamp(offHandTargetHeight - this.offHandHeight, -0.4F, 0.4F); + this.mainHandHeight = this.mainHandHeight + Mth.clamp(f1 - this.mainHandHeight, -0.4F, 0.4F); + this.offHandHeight = this.offHandHeight + Mth.clamp(f2 - this.offHandHeight, -0.4F, 0.4F); } diff --git a/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch b/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch index 72a8555d01..786f314f5d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/LevelEventHandler.java +++ b/net/minecraft/client/renderer/LevelEventHandler.java -@@ -305,7 +_,7 @@ +@@ -384,7 +_,7 @@ case 2001: - BlockState blockState = Block.stateById(data); - if (!blockState.isAir()) { -- SoundType soundType = blockState.getSoundType(); -+ SoundType soundType = blockState.getSoundType(this.level, pos, null); + BlockState blockstate1 = Block.stateById(data); + if (!blockstate1.isAir()) { +- SoundType soundtype = blockstate1.getSoundType(); ++ SoundType soundtype = blockstate1.getSoundType(this.level, pos, null); this.level .playLocalSound( - pos, soundType.getBreakSound(), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false + pos, soundtype.getBreakSound(), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, false diff --git a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch index 905e188bac..ac4e502fcf 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch @@ -1,38 +1,116 @@ --- a/net/minecraft/client/renderer/LevelRenderer.java +++ b/net/minecraft/client/renderer/LevelRenderer.java -@@ -235,6 +_,7 @@ +@@ -189,6 +_,7 @@ + this.optionsRenderState = gameRenderState.optionsRenderState; + this.levelRenderState = gameRenderState.levelRenderState; + this.featureRenderDispatcher = featureRenderDispatcher; ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onInitLevelRenderer(); + } + + @Override +@@ -515,8 +_,9 @@ + this.addSkyPass(framegraphbuilder, cameraState, terrainFog); } - this.addAlwaysOnTopPass(frame, featureFrame, terrainFog); -+ net.minecraftforge.client.FramePassManager.insertForgePasses(frame, targets, this.levelRenderState, deltaTracker); // Forge: Modded passes are inserted here. - profiler.popPush("executeFrameGraph"); - frame.execute(resourceAllocator, new FrameGraphBuilder.Inspector() { - @Override -@@ -285,7 +_,8 @@ - this.submitBlockDestroyAnimation(poseStack, submitNodeCollector, levelRenderState); - levelRenderState.blockBreakingRenderStates.clear(); - levelRenderState.particlesRenderState.submit(submitNodeCollector, levelRenderState.cameraRenderState); -- if (renderOutline) { + var hasCustomOutline = this.levelRenderState.blockOutlineRenderState != null && this.levelRenderState.blockOutlineRenderState.customRenderer() != null; -+ if (renderOutline || hasCustomOutline) { - this.submitBlockOutline(poseStack, this.submitNodeStorage, levelRenderState); + this.addMainPass( +- framegraphbuilder, frustum, modelViewMatrix, terrainFog, renderOutline, this.levelRenderState, deltaTracker, profilerfiller, chunkSectionsToRender ++ framegraphbuilder, frustum, modelViewMatrix, terrainFog, renderOutline | hasCustomOutline, this.levelRenderState, deltaTracker, profilerfiller, chunkSectionsToRender + ); + PostChain postchain1 = this.minecraft.getShaderManager().getPostChain(ENTITY_OUTLINE_POST_CHAIN_ID, LevelTargetBundle.OUTLINE_TARGETS); + if (this.levelRenderState.haveGlowingEntities && postchain1 != null) { +@@ -543,6 +_,7 @@ } -@@ -705,6 +_,10 @@ - private void submitBlockOutline(final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector, final LevelRenderState levelRenderState) { - BlockOutlineRenderState state = levelRenderState.blockOutlineRenderState; - if (state != null) { -+ if (state.customRenderer() != null) { -+ state.customRenderer().render(submitNodeCollector, poseStack, levelRenderState); + this.addLateDebugPass(framegraphbuilder, this.levelRenderState.cameraRenderState, terrainFog, modelViewMatrix); ++ net.minecraftforge.client.FramePassManager.insertForgePasses(framegraphbuilder, targets, this.levelRenderState); // Forge: Modded passes are inserted here. + profilerfiller.popPush("executeFrameGraph"); + framegraphbuilder.execute(resourceAllocator, new FrameGraphBuilder.Inspector() { + { +@@ -580,7 +_,7 @@ + profilerfiller.popPush("entities"); + this.extractVisibleEntities(camera, frustum, deltaTracker, this.levelRenderState); + profilerfiller.popPush("blockEntities"); +- this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState); ++ this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState, frustum); + profilerfiller.popPush("blockOutline"); + this.extractBlockOutline(camera, this.levelRenderState); + profilerfiller.popPush("blockBreaking"); +@@ -863,7 +_,7 @@ + } + } + +- private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState) { ++ private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState, final Frustum frustum) { + Vec3 vec3 = camera.position(); + double d0 = vec3.x(); + double d1 = vec3.y(); +@@ -874,6 +_,7 @@ + List list = sectionrenderdispatcher$rendersection.getSectionMesh().getRenderableBlockEntities(); + if (!list.isEmpty() && !(sectionrenderdispatcher$rendersection.getVisibility(Util.getMillis()) < 0.3F)) { + for (BlockEntity blockentity : list) { ++ if (!frustum.isVisible(blockentity.getRenderBoundingBox())) continue; + BlockPos blockpos = blockentity.getBlockPos(); + SortedSet sortedset = this.destructionProgress.get(blockpos.asLong()); + ModelFeatureRenderer.CrumblingOverlay modelfeaturerenderer$crumblingoverlay; +@@ -902,6 +_,7 @@ + if (blockentity1.isRemoved()) { + iterator.remove(); + } else { ++ if (!frustum.isVisible(blockentity1.getRenderBoundingBox())) continue; + BlockEntityRenderState blockentityrenderstate1 = this.blockEntityRenderDispatcher.tryExtractRenderState(blockentity1, deltaPartialTick, null); + if (blockentityrenderstate1 != null) { + levelRenderState.blockEntityRenderStates.add(blockentityrenderstate1); +@@ -938,7 +_,7 @@ + SortedSet sortedset = entry.getValue(); + if (sortedset != null && !sortedset.isEmpty()) { + int i = sortedset.last().getProgress(); +- levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(blockpos, this.level.getBlockState(blockpos), i)); ++ levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(blockpos, this.level.getBlockState(blockpos), i, this.level.getModelDataManager().getAtOrEmpty(blockpos))); + } + } + } +@@ -966,6 +_,12 @@ + + private void extractBlockOutline(final Camera camera, final LevelRenderState levelRenderState) { + levelRenderState.blockOutlineRenderState = null; ++ var custom = net.minecraftforge.client.ForgeHooksClient.onExtractBlockOutline(this, camera, levelRenderState, this.minecraft.hitResult); ++ if (custom != null) { ++ levelRenderState.blockOutlineRenderState = new BlockOutlineRenderState(BlockPos.ZERO, false, false, net.minecraft.world.phys.shapes.Shapes.empty(), null, null, null, custom); ++ return; ++ } ++ + if (this.minecraft.hitResult instanceof BlockHitResult blockhitresult) { + if (blockhitresult.getType() != HitResult.Type.MISS) { + BlockPos blockpos = blockhitresult.getBlockPos(); +@@ -999,6 +_,10 @@ + ) { + BlockOutlineRenderState blockoutlinerenderstate = levelRenderState.blockOutlineRenderState; + if (blockoutlinerenderstate != null) { ++ if (blockoutlinerenderstate.customRenderer() != null) { ++ blockoutlinerenderstate.customRenderer().render(bufferSource, poseStack, onlyTranslucentBlocks, levelRenderState); + return; + } - Vec3 cameraPos = levelRenderState.cameraRenderState.pos; - BlockPos pos = state.pos(); - poseStack.pushPose(); -@@ -979,6 +_,14 @@ + if (blockoutlinerenderstate.isTranslucent() == onlyTranslucentBlocks) { + Vec3 vec3 = levelRenderState.cameraRenderState.pos; + if (blockoutlinerenderstate.highContrast()) { +@@ -1491,7 +_,7 @@ + } else { + int i = brightnessGetter.packedBrightness(level, pos); + int j = LightCoordsUtil.block(i); +- int k = state.getLightEmission(); ++ int k = state.getLightEmission(level, pos); + return j < k ? LightCoordsUtil.withBlock(i, k) : i; + } + } +@@ -1539,6 +_,18 @@ - public SectionOcclusionGraph sectionOcclusionGraph() { - return this.sectionOcclusionGraph; + public CloudRenderer getCloudRenderer() { + return this.cloudRenderer; ++ } ++ ++ public int getTicks() { ++ return this.ticks; + } + + public WeatherEffectRenderer getWeatherEffects() { @@ -43,4 +121,4 @@ + this.weatherEffectRenderer = value; } - public Gizmos.TemporaryCollection collectPerFrameRenderThreadGizmos() { + public Gizmos.TemporaryCollection collectPerFrameGizmos() { diff --git a/patches/minecraft/net/minecraft/client/renderer/OrderedSubmitNodeCollector.java.patch b/patches/minecraft/net/minecraft/client/renderer/OrderedSubmitNodeCollector.java.patch new file mode 100644 index 0000000000..ec1d208644 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/renderer/OrderedSubmitNodeCollector.java.patch @@ -0,0 +1,13 @@ +--- a/net/minecraft/client/renderer/OrderedSubmitNodeCollector.java ++++ b/net/minecraft/client/renderer/OrderedSubmitNodeCollector.java +@@ -183,6 +_,10 @@ + + void submitBreakingBlockModel(PoseStack poseStack, BlockStateModel model, long seed, int progress); + ++ default void submitBreakingBlockModel(PoseStack poseStack, BlockStateModel model, long seed, int progress, net.minecraftforge.client.model.data.ModelData data) { ++ submitBreakingBlockModel(poseStack, model, seed, progress); ++ } ++ + void submitItem( + PoseStack poseStack, + ItemDisplayContext displayContext, diff --git a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch index 7250254598..1ce73125ff 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch @@ -1,70 +1,70 @@ --- a/net/minecraft/client/renderer/ScreenEffectRenderer.java +++ b/net/minecraft/client/renderer/ScreenEffectRenderer.java -@@ -61,8 +_,9 @@ - PoseStack poseStack = new PoseStack(); +@@ -62,19 +_,25 @@ Player player = this.minecraft.player; if (isFirstPerson && !isSleeping) { -- BlockState blockState = getViewBlockingState(player); -- if (blockState != null) { -+ var overlay = getOverlayBlock(player); -+ BlockState blockState = overlay == null ? null : overlay.getLeft(); -+ if (blockState != null && net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, poseStack, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) { - BlockStateModelSet blockStateModelSet = this.minecraft.getModelManager().getBlockStateModelSet(); - TextureAtlasSprite sprite = blockStateModelSet.getParticleMaterial(blockState).sprite(); - submitBlockSprite(sprite, poseStack, submitNodeCollector, -15132391); -@@ -70,11 +_,15 @@ + if (!player.noPhysics) { +- BlockState blockstate = getViewBlockingState(player); ++ var overlay = getOverlayBlock(player); ++ BlockState blockstate = overlay == null ? null : overlay.getLeft(); + if (blockstate != null) { ++ if (!net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, posestack, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) + renderTex(this.minecraft.getModelManager().getBlockStateModelSet().getParticleMaterial(blockstate).sprite(), posestack, this.bufferSource); + } + } if (!this.minecraft.player.isSpectator()) { if (this.minecraft.player.isEyeInFluid(FluidTags.WATER)) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, poseStack)) - submitWater(this.minecraft, poseStack, submitNodeCollector); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, posestack)) + renderWater(this.minecraft, posestack, this.bufferSource); + } else if (!player.getEyeInFluidType().isAir()) { -+ net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(this.minecraft, poseStack, submitNodeCollector); ++ net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(this.minecraft, posestack, this.bufferSource); } if (this.minecraft.player.isOnFire()) { - TextureAtlasSprite fireSprite = this.sprites.get(ModelBakery.FIRE_1); -+ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, poseStack)) - submitFire(poseStack, submitNodeCollector, fireSprite); + TextureAtlasSprite textureatlassprite = this.sprites.get(ModelBakery.FIRE_1); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, posestack)) + renderFire(posestack, this.bufferSource, textureatlassprite); } } -@@ -128,6 +_,11 @@ - return null; - } +@@ -126,6 +_,11 @@ + } + private static @Nullable BlockState getViewBlockingState(final Player player) { + var ret = getOverlayBlock(player); + return ret == null ? null : ret.getLeft(); + } + + private static org.apache.commons.lang3.tuple.@Nullable Pair getOverlayBlock(Player player) { - BlockPos.MutableBlockPos testPos = new BlockPos.MutableBlockPos(); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); for (int i = 0; i < 8; i++) { -@@ -138,7 +_,7 @@ - ); - BlockState blockState = player.level().getBlockState(testPos); - if (blockState.getRenderShape() != RenderShape.INVISIBLE && blockState.isViewBlocking(player.level(), testPos)) { -- return blockState; -+ return org.apache.commons.lang3.tuple.Pair.of(blockState, testPos.immutable()); +@@ -135,7 +_,7 @@ + blockpos$mutableblockpos.set(d0, d1, d2); + BlockState blockstate = player.level().getBlockState(blockpos$mutableblockpos); + if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.isViewBlocking(player.level(), blockpos$mutableblockpos)) { +- return blockstate; ++ return org.apache.commons.lang3.tuple.Pair.of(blockstate, blockpos$mutableblockpos.immutable()); } } -@@ -156,13 +_,17 @@ +@@ -163,6 +_,10 @@ } - private static void submitWater(final Minecraft minecraft, final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector) { -+ renderFluid(minecraft, poseStack, submitNodeCollector, UNDERWATER_LOCATION); + private static void renderWater(final Minecraft minecraft, final PoseStack poseStack, final MultiBufferSource bufferSource) { ++ renderFluid(minecraft, poseStack, bufferSource, UNDERWATER_LOCATION); + } + -+ public static void renderFluid(Minecraft minecraft, PoseStack poseStack, SubmitNodeCollector submitNodeCollector, Identifier texture) { - LocalPlayer player = minecraft.player; - BlockPos pos = BlockPos.containing(player.getEyePosition()); - float brightness = Lightmap.getBrightness(player.level().dimensionType(), player.level().getMaxLocalRawBrightness(pos)); - int color = ARGB.colorFromFloat(0.1F, brightness, brightness, brightness); - float u0 = -player.getYRot() / 64.0F; - float v0 = player.getXRot() / 64.0F; -- submitNodeCollector.submitCustomGeometry(poseStack, RenderTypes.blockScreenEffect(UNDERWATER_LOCATION), (pose, builder) -> { -+ submitNodeCollector.submitCustomGeometry(poseStack, RenderTypes.blockScreenEffect(texture), (pose, builder) -> { - float uvSize = 4.0F; - buildQuad(builder, pose.pose(), -1.0F, -1.0F, 1.0F, 1.0F, -0.5F, u0 + 4.0F, v0 + 4.0F, u0, v0, color); - }); ++ public static void renderFluid(Minecraft minecraft, PoseStack poseStack, MultiBufferSource bufferSource, Identifier texture) { + BlockPos blockpos = BlockPos.containing(minecraft.player.getX(), minecraft.player.getEyeY(), minecraft.player.getZ()); + float f = Lightmap.getBrightness(minecraft.player.level().dimensionType(), minecraft.player.level().getMaxLocalRawBrightness(blockpos)); + int i = ARGB.colorFromFloat(0.1F, f, f, f); +@@ -175,7 +_,7 @@ + float f7 = -minecraft.player.getYRot() / 64.0F; + float f8 = minecraft.player.getXRot() / 64.0F; + Matrix4f matrix4f = poseStack.last().pose(); +- VertexConsumer vertexconsumer = bufferSource.getBuffer(RenderTypes.blockScreenEffect(UNDERWATER_LOCATION)); ++ VertexConsumer vertexconsumer = bufferSource.getBuffer(RenderTypes.blockScreenEffect(texture)); + vertexconsumer.addVertex(matrix4f, -1.0F, -1.0F, -0.5F).setUv(4.0F + f7, 4.0F + f8).setColor(i); + vertexconsumer.addVertex(matrix4f, 1.0F, -1.0F, -0.5F).setUv(0.0F + f7, 4.0F + f8).setColor(i); + vertexconsumer.addVertex(matrix4f, 1.0F, 1.0F, -0.5F).setUv(0.0F + f7, 0.0F + f8).setColor(i); diff --git a/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch b/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch index 3486c46905..71ea5a8683 100644 --- a/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/Sheets.java.patch @@ -1,9 +1,32 @@ --- a/net/minecraft/client/renderer/Sheets.java +++ b/net/minecraft/client/renderer/Sheets.java -@@ -120,4 +_,13 @@ - case COPPER_OXIDIZED -> (SpriteId)CHEST_COPPER.oxidized().select(type); - }; +@@ -146,11 +_,11 @@ } + + private static SpriteId createSignSprite(final WoodType type) { +- return SIGN_MAPPER.defaultNamespaceApply(type.name()); ++ return SIGN_MAPPER.apply(Identifier.parse(type.name())); + } + + private static SpriteId createHangingSignSprite(final WoodType type) { +- return HANGING_SIGN_MAPPER.defaultNamespaceApply(type.name()); ++ return HANGING_SIGN_MAPPER.apply(Identifier.parse(type.name())); + } + + public static SpriteId getSignSprite(final WoodType type) { +@@ -184,5 +_,22 @@ + case COPPER_WEATHERED -> (SpriteId)CHEST_COPPER_WEATHERED.select(type); + case COPPER_OXIDIZED -> (SpriteId)CHEST_COPPER_OXIDIZED.select(type); + }; ++ } ++ ++ /** ++ * Not thread-safe. Enqueue it in client setup. ++ */ ++ public static void addWoodType(WoodType woodType) { ++ SIGN_SPRITES.put(woodType, createSignSprite(woodType)); ++ HANGING_SIGN_SPRITES.put(woodType, createHangingSignSprite(woodType)); ++ } + + static { + if (net.minecraftforge.fml.ModLoader.isLoadingStateValid() && !net.minecraftforge.fml.ModLoader.hasCompletedState(net.minecraftforge.common.ForgeStatesProvider.LOAD_REGISTRIES)) { @@ -12,5 +35,5 @@ + new IllegalStateException("net.minecraft.client.renderer.Sheets loaded too early") + ); + } -+ } + } } diff --git a/patches/minecraft/net/minecraft/client/renderer/SubmitNodeCollection.java.patch b/patches/minecraft/net/minecraft/client/renderer/SubmitNodeCollection.java.patch new file mode 100644 index 0000000000..8fa5f0d8c5 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/renderer/SubmitNodeCollection.java.patch @@ -0,0 +1,15 @@ +--- a/net/minecraft/client/renderer/SubmitNodeCollection.java ++++ b/net/minecraft/client/renderer/SubmitNodeCollection.java +@@ -179,6 +_,12 @@ + } + + @Override ++ public void submitBreakingBlockModel(final PoseStack poseStack, final BlockStateModel model, final long seed, final int progress, final net.minecraftforge.client.model.data.ModelData data) { ++ this.wasUsed = true; ++ this.breakingBlockModelSubmits.add(new SubmitNodeStorage.BreakingBlockModelSubmit(poseStack.last().copy(), model, seed, progress, data)); ++ } ++ ++ @Override + public void submitItem( + final PoseStack poseStack, + final ItemDisplayContext displayContext, diff --git a/patches/minecraft/net/minecraft/client/renderer/SubmitNodeStorage.java.patch b/patches/minecraft/net/minecraft/client/renderer/SubmitNodeStorage.java.patch new file mode 100644 index 0000000000..0b2d317ec6 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/renderer/SubmitNodeStorage.java.patch @@ -0,0 +1,26 @@ +--- a/net/minecraft/client/renderer/SubmitNodeStorage.java ++++ b/net/minecraft/client/renderer/SubmitNodeStorage.java +@@ -141,6 +_,11 @@ + } + + @Override ++ public void submitBreakingBlockModel(final PoseStack poseStack, final BlockStateModel model, final long seed, final int progress, final net.minecraftforge.client.model.data.ModelData data) { ++ this.order(0).submitBreakingBlockModel(poseStack, model, seed, progress, data); ++ } ++ ++ @Override + public void submitItem( + final PoseStack poseStack, + final ItemDisplayContext displayContext, +@@ -192,7 +_,10 @@ + } + + @OnlyIn(Dist.CLIENT) +- public record BreakingBlockModelSubmit(PoseStack.Pose pose, BlockStateModel model, long seed, int progress) { ++ public record BreakingBlockModelSubmit(PoseStack.Pose pose, BlockStateModel model, long seed, int progress, net.minecraftforge.client.model.data.ModelData data) { ++ public BreakingBlockModelSubmit(PoseStack.Pose pose, BlockStateModel model, long seed, int progress) { ++ this(pose, model, seed, progress, net.minecraftforge.client.model.data.ModelData.EMPTY); ++ } + } + + @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch index 5bdbaa158c..7923bbe67d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/client/renderer/block/FluidRenderer.java +++ b/net/minecraft/client/renderer/block/FluidRenderer.java -@@ -86,8 +_,10 @@ - boolean renderEast = shouldRenderFace(fluidState, blockState, Direction.EAST, fluidStateEast); - if (renderUp || renderDown || renderEast || renderWest || renderNorth || renderSouth) { - FluidModel model = this.fluidModels.get(fluidState); +@@ -87,8 +_,10 @@ + boolean flag5 = shouldRenderFace(fluidState, blockState, Direction.EAST, fluidstate5); + if (flag || flag1 || flag5 || flag4 || flag2 || flag3) { + FluidModel fluidmodel = this.fluidModels.get(fluidState); + var fluidExt = net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(fluidState); -+ model = fluidExt.getModel(fluidState, level, pos, model); - VertexConsumer builder = output.getBuilder(model.layer()); -- int tintColor = model.tintSource() != null ? model.tintSource().colorInWorld(blockState, level, pos) : -1; -+ int tintColor = model.tintSource() != null ? model.tintSource().colorInWorld(blockState, level, pos) : fluidExt.getTintColor(); - CardinalLighting cardinalLighting = level.cardinalLighting(); - Fluid type = fluidState.getType(); - float heightSelf = this.getHeight(level, type, pos, blockState, fluidState); -@@ -294,7 +_,7 @@ - boolean isOverlay = false; - if (model.overlayMaterial() != null) { - Block relativeBlock = faceState.getBlock(); -- if (relativeBlock instanceof HalfTransparentBlock || relativeBlock instanceof LeavesBlock) { -+ if (faceState.shouldDisplayFluidOverlay(level, pos.relative(faceDir), fluidState)) { - sprite = model.overlayMaterial().sprite(); - isOverlay = true; ++ fluidmodel = fluidExt.getModel(fluidState, level, pos, fluidmodel); + VertexConsumer vertexconsumer = output.getBuilder(fluidmodel.layer()); +- int i = fluidmodel.tintSource() != null ? fluidmodel.tintSource().colorInWorld(blockState, level, pos) : -1; ++ int i = fluidmodel.tintSource() != null ? fluidmodel.tintSource().colorInWorld(blockState, level, pos) : fluidExt.getTintColor(); + CardinalLighting cardinallighting = level.cardinalLighting(); + Fluid fluid = fluidState.getType(); + float f4 = this.getHeight(level, fluid, pos, blockState, fluidState); +@@ -284,7 +_,7 @@ + boolean flag7 = false; + if (fluidmodel.overlayMaterial() != null) { + Block block = blockstate6.getBlock(); +- if (block instanceof HalfTransparentBlock || block instanceof LeavesBlock) { ++ if (blockstate6.shouldDisplayFluidOverlay(level, pos.relative(direction), fluidState)) { + textureatlassprite3 = fluidmodel.overlayMaterial().sprite(); + flag7 = true; } 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 6607f98f7e..676b261c60 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch @@ -26,9 +26,9 @@ + model.collectParts(this.random, this.parts, modelData); if (!this.parts.isEmpty()) { try { - Vec3 offset = blockState.getOffset(pos); + Vec3 vec3 = blockState.getOffset(pos); - if (this.ambientOcclusion && blockState.getLightEmission() == 0 && this.parts.getFirst().useAmbientOcclusion()) { + if (this.ambientOcclusion && blockState.getLightEmission(level, pos) == 0 && this.parts.getFirst().useAmbientOcclusion()) { - this.tesselateAmbientOcclusion(output, x + (float)offset.x, y + (float)offset.y, z + (float)offset.z, this.parts, level, blockState, pos); + this.tesselateAmbientOcclusion(output, x + (float)vec3.x, y + (float)vec3.y, z + (float)vec3.z, this.parts, level, blockState, pos); } else { - this.tesselateFlat(output, x + (float)offset.x, y + (float)offset.y, z + (float)offset.z, this.parts, level, blockState, pos); + this.tesselateFlat(output, x + (float)vec3.x, y + (float)vec3.y, z + (float)vec3.z, this.parts, level, blockState, pos); diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch index 938f1d1453..35eb5a4d6e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java +++ b/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java -@@ -20,9 +_,11 @@ +@@ -22,9 +_,11 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) @@ -12,4 +12,4 @@ + /**@deprecated Forge: Use {@link net.minecraftforge.client.extensions.IForgeBlockStateModel#particleMaterial(net.minecraftforge.client.model.data.ModelData)}*/ Material.Baked particleMaterial(); - @BakedQuad.MaterialFlags int materialFlags(); + @BakedQuad.MaterialFlags diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch index 6d820387cf..0b9c85bb8d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java +++ b/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java -@@ -16,11 +_,13 @@ - private final WeightedList list; +@@ -17,11 +_,13 @@ private final Material.Baked particleMaterial; - private final @BakedQuad.MaterialFlags int materialFlags; + @BakedQuad.MaterialFlags + private final int materialFlags; + private final BlockStateModel first; public WeightedVariants(final WeightedList list) { this.list = list; - BlockStateModel firstModel = list.unwrap().getFirst().value(); - this.particleMaterial = firstModel.particleMaterial(); -+ this.first = firstModel; + BlockStateModel blockstatemodel = list.unwrap().getFirst().value(); + this.particleMaterial = blockstatemodel.particleMaterial(); ++ this.first = blockstatemodel; this.materialFlags = computeMaterialFlags(list); } -@@ -40,6 +_,11 @@ +@@ -41,6 +_,11 @@ + return this.particleMaterial; } - @Override ++ @Override + public Material.Baked particleMaterial(net.minecraftforge.client.model.data.ModelData data) { + return this.first.particleMaterial(data); + } + -+ @Override - public @BakedQuad.MaterialFlags int materialFlags() { - return this.materialFlags; - } -@@ -47,6 +_,11 @@ + @BakedQuad.MaterialFlags + @Override + public int materialFlags() { +@@ -50,6 +_,11 @@ @Override public void collectParts(final RandomSource random, final List output) { this.list.getRandomOrThrow(random).collectParts(random, output); diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch index 886541fbd5..d221d7c5b3 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch @@ -1,19 +1,20 @@ --- a/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java +++ b/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java -@@ -38,12 +_,24 @@ +@@ -38,6 +_,13 @@ + return this.shared.particleMaterial; } - @Override ++ @Override + public Material.Baked particleMaterial(net.minecraftforge.client.model.data.ModelData data) { + if (this.models == null) + this.models = this.shared.selectModels(this.blockState); + return this.models.getFirst().particleMaterial(data); + } + -+ @Override - public @BakedQuad.MaterialFlags int materialFlags() { - return this.shared.materialFlags; - } + @BakedQuad.MaterialFlags + @Override + public int materialFlags() { +@@ -46,6 +_,11 @@ @Override public void collectParts(final RandomSource random, final List output) { @@ -25,12 +26,12 @@ if (this.models == null) { this.models = this.shared.selectModels(this.blockState); } -@@ -52,7 +_,7 @@ +@@ -54,7 +_,7 @@ - for (BlockStateModel model : this.models) { - random.setSeed(seed); -- model.collectParts(random, output); -+ model.collectParts(random, output, data); + for (BlockStateModel blockstatemodel : this.models) { + random.setSeed(i); +- blockstatemodel.collectParts(random, output); ++ blockstatemodel.collectParts(random, output, data); } } 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 9c94cca359..b4d5cf9d3e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java +++ b/net/minecraft/client/renderer/blockentity/BlockEntityRenderers.java -@@ -14,7 +_,7 @@ +@@ -13,7 +_,7 @@ @OnlyIn(Dist.CLIENT) public class BlockEntityRenderers { 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 9248946751..499a66c7a0 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java +++ b/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java -@@ -43,6 +_,7 @@ +@@ -44,6 +_,7 @@ public static final WallAndGroundTransformations TRANSFORMATIONS = new WallAndGroundTransformations<>( SkullBlockRenderer::createWallTransformation, SkullBlockRenderer::createGroundTransformation, 16 ); @@ -8,9 +8,9 @@ private final Function modelByType; public static final Map SKIN_BY_TYPE = Util.make(Maps.newHashMap(), map -> { map.put(SkullBlock.Types.SKELETON, Identifier.withDefaultNamespace("textures/entity/skeleton/skeleton.png")); -@@ -67,7 +_,9 @@ +@@ -68,7 +_,9 @@ case PIGLIN -> new PiglinHeadModel(modelSet.bakeLayer(ModelLayers.PIGLIN_HEAD)); - }; + }); } else { - return null; + if (customModels == null) diff --git a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch index 57a9638c4e..48c6a97f1c 100644 --- a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch @@ -1,32 +1,20 @@ --- a/net/minecraft/client/renderer/chunk/SectionCompiler.java +++ b/net/minecraft/client/renderer/chunk/SectionCompiler.java -@@ -56,6 +_,7 @@ +@@ -63,6 +_,7 @@ public SectionCompiler.Results compile( final SectionPos sectionPos, final RenderSectionRegion region, final VertexSorting vertexSorting, final SectionBufferBuilderPack builders ) { + var modelDataMap = net.minecraft.client.Minecraft.getInstance().level.getModelDataManager().getAt(sectionPos); - SectionCompiler.Results results = new SectionCompiler.Results(); - BlockPos minPos = sectionPos.origin(); - BlockPos maxPos = minPos.offset(15, 15, 15); -@@ -95,6 +_,9 @@ - } - - if (blockState.getRenderShape() == RenderShape.MODEL) { -+ var model = this.blockModelSet.get(blockState); -+ var modelData = modelDataMap.getOrDefault(pos, net.minecraftforge.client.model.data.ModelData.EMPTY); -+ modelData = model.getModelData(region, pos, blockState, modelData); - blockRenderer.tesselateBlock( - ModelBlockRenderer.forceOpaque(this.cutoutLeaves, blockState) ? opaqueQuadOutput : quadOutput, - SectionPos.sectionRelative(pos.getX()), -@@ -103,8 +_,9 @@ - region, - pos, - blockState, -- this.blockModelSet.get(blockState), -- blockState.getSeed(pos) -+ model, -+ blockState.getSeed(pos), -+ modelData + SectionCompiler.Results sectioncompiler$results = new SectionCompiler.Results(); + BlockPos blockpos = sectionPos.origin(); + BlockPos blockpos1 = blockpos.offset(15, 15, 15); +@@ -111,7 +_,8 @@ + blockpos2, + blockstate, + this.blockModelSet.get(blockstate), +- blockstate.getSeed(blockpos2) ++ blockstate.getSeed(blockpos2), ++ modelDataMap.getOrDefault(blockpos2, net.minecraftforge.client.model.data.ModelData.EMPTY) ); } - } catch (Throwable t) { + } catch (Throwable throwable) { 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 f84ccf0f15..4112c208bd 100644 --- a/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch @@ -6,6 +6,6 @@ public boolean isVisible(final AABB bb) { + // Forge: exit early for infinite bounds, these would otherwise fail in the intersection test at certain camera angles (GH-9321) + if (bb.equals(net.minecraftforge.common.extensions.IForgeBlockEntity.INFINITE_EXTENT_AABB)) return true; - int intersectionResult = this.cubeInFrustum(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - return intersectionResult == -2 || intersectionResult == -1; + int i = this.cubeInFrustum(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + return i == -2 || i == -1; } diff --git a/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch index 7e02373768..84d27d0637 100644 --- a/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java +++ b/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java -@@ -99,8 +_,8 @@ +@@ -93,8 +_,8 @@ ); } -- if (entity instanceof EnderDragon dragon) { -- for (EnderDragonPart subEntity : dragon.getSubEntities()) { +- if (entity instanceof EnderDragon enderdragon) { +- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { + if (entity.isMultipartEntity()) { -+ for (var subEntity : entity.getParts()) { - Vec3 latestSubPosition = subEntity.position(); - Vec3 currentSubPosition = subEntity.getPosition(partialTicks); - Vec3 subOffset = currentSubPosition.subtract(latestSubPosition); ++ for (var enderdragonpart : entity.getParts()) { + Vec3 vec34 = enderdragonpart.position(); + Vec3 vec35 = enderdragonpart.getPosition(partialTicks); + Vec3 vec36 = vec35.subtract(vec34); 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 a04ce8151e..022b06d41b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java +++ b/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java -@@ -207,6 +_,14 @@ +@@ -209,6 +_,14 @@ return this.itemInHandRenderer; } @@ -14,11 +14,11 @@ + @Override public void onResourceManagerReload(final ResourceManager resourceManager) { - EntityRendererProvider.Context context = new EntityRendererProvider.Context( -@@ -224,5 +_,6 @@ - this.renderers = EntityRenderers.createEntityRenderers(context); - this.playerRenderers = EntityRenderers.createAvatarRenderers(context); - this.mannequinRenderers = EntityRenderers.createAvatarRenderers(context); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onGatherLayers(renderers, playerRenderers, mannequinRenderers, context); + EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context( +@@ -226,5 +_,6 @@ + this.renderers = EntityRenderers.createEntityRenderers(entityrendererprovider$context); + this.playerRenderers = EntityRenderers.createAvatarRenderers(entityrendererprovider$context); + this.mannequinRenderers = EntityRenderers.createAvatarRenderers(entityrendererprovider$context); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onGatherLayers(renderers, playerRenderers, mannequinRenderers, 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 0b8b6f89b8..444d0bfebb 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch @@ -1,30 +1,33 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderer.java +++ b/net/minecraft/client/renderer/entity/EntityRenderer.java -@@ -128,13 +_,14 @@ +@@ -126,16 +_,17 @@ final S state, final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector, final CameraRenderState camera, final int offset ) { poseStack.pushPose(); - if (state.scoreText != null) { -- submitNodeCollector.submitNameTag(poseStack, state.nameTagAttachment, offset, state.scoreText, !state.isDiscrete, state.lightCoords, camera); + var event = net.minecraftforge.client.event.ForgeEventFactoryClient.fireRenderNameTagEvent(state, this, poseStack, submitNodeCollector, camera); + if (event.getScoreContent() != null) { -+ submitNodeCollector.submitNameTag(poseStack, state.nameTagAttachment, offset, event.getScoreContent(), !state.isDiscrete, state.lightCoords, camera); + submitNodeCollector.submitNameTag( +- poseStack, state.nameTagAttachment, offset, state.scoreText, !state.isDiscrete, state.lightCoords, state.distanceToCameraSq, camera ++ poseStack, state.nameTagAttachment, offset, event.getScoreContent(), !state.isDiscrete, state.lightCoords, state.distanceToCameraSq, camera + ); poseStack.translate(0.0F, 9.0F * 1.15F * 0.025F, 0.0F); } - if (state.nameTag != null) { -- submitNodeCollector.submitNameTag(poseStack, state.nameTagAttachment, offset, state.nameTag, !state.isDiscrete, state.lightCoords, camera); + if (event.getContent() != null) { -+ submitNodeCollector.submitNameTag(poseStack, state.nameTagAttachment, offset, event.getContent(), !state.isDiscrete, state.lightCoords, camera); + submitNodeCollector.submitNameTag( +- poseStack, state.nameTagAttachment, offset, state.nameTag, !state.isDiscrete, state.lightCoords, state.distanceToCameraSq, camera ++ poseStack, state.nameTagAttachment, offset, event.getContent(), !state.isDiscrete, state.lightCoords, state.distanceToCameraSq, camera + ); } - poseStack.popPose(); -@@ -252,7 +_,7 @@ - protected final void extractNameTags(final T entity, final S state, final float partialTicks, final double nameTagDistance, final double belowNameDistance) { +@@ -187,7 +_,7 @@ + if (this.entityRenderDispatcher.camera != null) { state.distanceToCameraSq = this.entityRenderDispatcher.distanceToSqr(entity); -- boolean shouldShowName = state.distanceToCameraSq < Mth.square(nameTagDistance) && this.shouldShowName(entity, state.distanceToCameraSq); -+ boolean shouldShowName = net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(entity, state.distanceToCameraSq, nameTagDistance) && this.shouldShowName(entity, state.distanceToCameraSq); - if (shouldShowName) { +- boolean flag1 = state.distanceToCameraSq < 4096.0 && this.shouldShowName(entity, state.distanceToCameraSq); ++ boolean flag1 = net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(entity, state.distanceToCameraSq) && this.shouldShowName(entity, state.distanceToCameraSq); + if (flag1) { state.nameTag = this.getNameTag(entity); state.nameTagAttachment = entity.getAttachments().getNullable(EntityAttachment.NAME_TAG, 0, entity.getYRot(partialTicks)); 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 3cc42ac3d9..3e7cdc88f0 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch @@ -2,17 +2,17 @@ +++ b/net/minecraft/client/renderer/entity/ItemFrameRenderer.java @@ -82,6 +_,7 @@ if (state.mapId != null) { - int rotation = state.rotation % 4 * 2; - poseStack.mulPose(Axis.ZP.rotationDegrees(rotation * 360.0F / 8.0F)); + int i = state.rotation % 4 * 2; + poseStack.mulPose(Axis.ZP.rotationDegrees(i * 360.0F / 8.0F)); + if (!net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderItemInFrame(state, this, poseStack, submitNodeCollector, state.lightCoords)) { poseStack.mulPose(Axis.ZP.rotationDegrees(180.0F)); - float s = 0.0078125F; + float f2 = 0.0078125F; poseStack.scale(0.0078125F, 0.0078125F, 0.0078125F); @@ -89,6 +_,7 @@ poseStack.translate(0.0F, 0.0F, -1.0F); - int lightCoords = this.getLightCoords(state.isGlowFrame, 15728850, state.lightCoords); - this.mapRenderer.render(state.mapRenderState, poseStack, submitNodeCollector, true, lightCoords); + int j = this.getLightCoords(state.isGlowFrame, 15728850, state.lightCoords); + this.mapRenderer.render(state.mapRenderState, poseStack, submitNodeCollector, true, j); + } } else if (!state.item.isEmpty()) { poseStack.mulPose(Axis.ZP.rotationDegrees(state.rotation * 360.0F / 8.0F)); - int lightVal = this.getLightCoords(state.isGlowFrame, 15728880, state.lightCoords); + int k = this.getLightCoords(state.isGlowFrame, 15728880, state.lightCoords); 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 7ffa0ca238..357e2023ec 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/renderer/entity/LivingEntityRenderer.java +++ b/net/minecraft/client/renderer/entity/LivingEntityRenderer.java -@@ -73,6 +_,7 @@ +@@ -72,6 +_,7 @@ } public void submit(final S state, final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector, final CameraRenderState camera) { + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderLivingPre(state, this, poseStack, submitNodeCollector, camera)) return; poseStack.pushPose(); if (state.hasPose(Pose.SLEEPING)) { - Direction bedOrientation = state.bedOrientation; -@@ -110,6 +_,7 @@ + Direction direction = state.bedOrientation; +@@ -107,6 +_,7 @@ poseStack.popPose(); super.submit(state, poseStack, submitNodeCollector, camera); @@ -16,7 +16,7 @@ } protected boolean shouldRenderLayers(final S state) { -@@ -278,7 +_,7 @@ +@@ -283,7 +_,7 @@ state.isFullyFrozen = entity.isFullyFrozen(); state.isBaby = entity.isBaby(); 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 index f6f46b961d..db416febd6 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch @@ -1,21 +1,23 @@ --- a/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java +++ b/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java -@@ -66,12 +_,13 @@ +@@ -66,6 +_,7 @@ Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE); if (equippable != null && shouldRender(equippable, slot)) { - A model = this.getArmorModel(state, slot); -+ var newModel = this.getArmorModel(state, slot, itemStack, model); - EquipmentClientInfo.LayerType layerType = state.isBaby && state.entityType != EntityTypes.ARMOR_STAND + A a = this.getArmorModel(state, slot); ++ var model = this.getArmorModel(state, slot, itemStack, a); + EquipmentClientInfo.LayerType equipmentclientinfo$layertype = state.isBaby && state.entityType != EntityType.ARMOR_STAND ? EquipmentClientInfo.LayerType.HUMANOID_BABY : (this.usesInnerModel(slot) ? EquipmentClientInfo.LayerType.HUMANOID_LEGGINGS : EquipmentClientInfo.LayerType.HUMANOID); - this.equipmentRenderer +@@ -73,7 +_,7 @@ .renderLayers( -- layerType, equippable.assetId().orElseThrow(), model, state, itemStack, poseStack, submitNodeCollector, lightCoords, state.outlineColor -+ layerType, equippable.assetId().orElseThrow(), newModel, state, itemStack, poseStack, submitNodeCollector, lightCoords, state.outlineColor - ); - } - } -@@ -82,5 +_,12 @@ + equipmentclientinfo$layertype, + equippable.assetId().orElseThrow(), +- a, ++ model, + state, + itemStack, + poseStack, +@@ -90,5 +_,12 @@ private boolean usesInnerModel(final EquipmentSlot slot) { return slot == EquipmentSlot.LEGS; diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch index 67cdb05fa5..36e65971d9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch @@ -6,6 +6,6 @@ - protected static @Nullable Identifier getPlayerElytraTexture(final HumanoidRenderState state) { + protected @Nullable Identifier getPlayerElytraTexture(final HumanoidRenderState state) { - if (state instanceof AvatarRenderState playerState) { - PlayerSkin skin = playerState.skin; - if (skin.elytra() != null) { + if (state instanceof AvatarRenderState avatarrenderstate) { + PlayerSkin playerskin = avatarrenderstate.skin; + if (playerskin.elytra() != null) { diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch index 8dd36f4d24..7fb5516fd1 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch @@ -1,26 +1,26 @@ --- a/net/minecraft/client/renderer/entity/player/AvatarRenderer.java +++ b/net/minecraft/client/renderer/entity/player/AvatarRenderer.java -@@ -98,7 +_,7 @@ +@@ -96,7 +_,7 @@ + private static HumanoidModel.ArmPose getArmPose(final Avatar avatar, final ItemStack itemInHand, final InteractionHand hand) { + if (itemInHand.isEmpty()) { return HumanoidModel.ArmPose.EMPTY; - } - -- if (!avatar.swinging && itemInHand.is(Items.CROSSBOW) && CrossbowItem.isCharged(itemInHand)) { -+ if (!avatar.swinging && itemInHand.getItem() instanceof CrossbowItem && CrossbowItem.isCharged(itemInHand)) { +- } else if (!avatar.swinging && itemInHand.is(Items.CROSSBOW) && CrossbowItem.isCharged(itemInHand)) { ++ } else if (!avatar.swinging && itemInHand.getItem() instanceof CrossbowItem && CrossbowItem.isCharged(itemInHand)) { return HumanoidModel.ArmPose.CROSSBOW_HOLD; - } - -@@ -141,7 +_,9 @@ - if (attack != null && attack.type() == SwingAnimationType.STAB && avatar.swinging) { - return HumanoidModel.ArmPose.SPEAR; } else { -- return itemInHand.is(ItemTags.SPEARS) ? HumanoidModel.ArmPose.SPEAR : HumanoidModel.ArmPose.ITEM; -+ if (itemInHand.is(ItemTags.SPEARS)) return HumanoidModel.ArmPose.SPEAR; -+ var pose = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemInHand).getArmPose(avatar, hand, itemInHand); -+ return pose == null ? HumanoidModel.ArmPose.ITEM : pose; + if (avatar.getUsedItemHand() == hand && avatar.getUseItemRemainingTicks() > 0) { +@@ -138,7 +_,9 @@ + if (swinganimation != null && swinganimation.type() == SwingAnimationType.STAB && avatar.swinging) { + return HumanoidModel.ArmPose.SPEAR; + } else { +- return itemInHand.is(ItemTags.SPEARS) ? HumanoidModel.ArmPose.SPEAR : HumanoidModel.ArmPose.ITEM; ++ if (itemInHand.is(ItemTags.SPEARS)) return HumanoidModel.ArmPose.SPEAR; ++ var pose = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemInHand).getArmPose(avatar, hand, itemInHand); ++ return pose == null ? HumanoidModel.ArmPose.ITEM : pose; + } } } - -@@ -241,12 +_,14 @@ +@@ -239,12 +_,14 @@ public void renderRightHand( final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector, final int lightCoords, final Identifier skinTexture, final boolean hasSleeve ) { @@ -35,7 +35,7 @@ this.renderHand(poseStack, submitNodeCollector, lightCoords, skinTexture, this.model.leftArm, hasSleeve); } -@@ -304,5 +_,12 @@ +@@ -302,5 +_,12 @@ public static boolean isPlayerUpsideDown(final Player player) { return isUpsideDownName(player.getGameProfile().name()); diff --git a/patches/minecraft/net/minecraft/client/renderer/extract/LevelExtractor.java.patch b/patches/minecraft/net/minecraft/client/renderer/extract/LevelExtractor.java.patch deleted file mode 100644 index 1ed87d4486..0000000000 --- a/patches/minecraft/net/minecraft/client/renderer/extract/LevelExtractor.java.patch +++ /dev/null @@ -1,58 +0,0 @@ ---- a/net/minecraft/client/renderer/extract/LevelExtractor.java -+++ b/net/minecraft/client/renderer/extract/LevelExtractor.java -@@ -172,7 +_,7 @@ - profiler.popPush("entities"); - this.extractVisibleEntities(camera, cullFrustum, deltaTracker, this.levelRenderState); - profiler.popPush("blockEntities"); -- this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState); -+ this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState, cullFrustum); - profiler.popPush("blockOutline"); - this.extractBlockOutline(camera, this.levelRenderState); - profiler.popPush("blockBreaking"); -@@ -264,7 +_,7 @@ - return this.levelRenderer.entityRenderDispatcher().extractEntity(entity, partialTickTime); - } - -- private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState) { -+ private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState, final Frustum frustum) { - Vec3 cameraPos = camera.position(); - double camX = cameraPos.x(); - double camY = cameraPos.y(); -@@ -275,6 +_,7 @@ - List renderableBlockEntities = section.getSectionMesh().getRenderableBlockEntities(); - if (!renderableBlockEntities.isEmpty() && !(section.getVisibility(Util.getMillis()) < 0.3F)) { - for (BlockEntity blockEntity : renderableBlockEntities) { -+ if (!frustum.isVisible(blockEntity.getRenderBoundingBox())) continue; - BlockPos blockPos = blockEntity.getBlockPos(); - SortedSet progresses = this.level.destructionProgress().get(blockPos.asLong()); - ModelFeatureRenderer.CrumblingOverlay breakProgress; -@@ -304,6 +_,7 @@ - if (blockEntity.isRemoved()) { - iterator.remove(); - } else { -+ if (!frustum.isVisible(blockEntity.getRenderBoundingBox())) continue; - BlockEntityRenderState state = this.levelRenderer - .blockEntityRenderDispatcher() - .tryExtractRenderState(blockEntity, deltaPartialTick, null, true); -@@ -327,7 +_,7 @@ - SortedSet progresses = entry.getValue(); - if (progresses != null && !progresses.isEmpty()) { - int progress = progresses.last().getProgress(); -- levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(pos, this.level.getBlockState(pos), progress)); -+ levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(pos, this.level.getBlockState(pos), progress, this.level.getModelDataManager().getAtOrEmpty(pos))); - } - } - } -@@ -335,6 +_,12 @@ - - private void extractBlockOutline(final Camera camera, final LevelRenderState levelRenderState) { - levelRenderState.blockOutlineRenderState = null; -+ var custom = net.minecraftforge.client.ForgeHooksClient.onExtractBlockOutline(this, camera, levelRenderState, this.minecraft.hitResult); -+ if (custom != null) { -+ levelRenderState.blockOutlineRenderState = new BlockOutlineRenderState(BlockPos.ZERO, false, false, net.minecraft.world.phys.shapes.Shapes.empty(), null, null, null, custom); -+ return; -+ } -+ - if (this.minecraft.hitResult instanceof BlockHitResult blockHitResult) { - if (blockHitResult.getType() != HitResult.Type.MISS) { - BlockPos pos = blockHitResult.getBlockPos(); diff --git a/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch new file mode 100644 index 0000000000..9b2cc91f11 --- /dev/null +++ b/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java ++++ b/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java +@@ -164,7 +_,7 @@ + this.random.setSeed(submitnodestorage$breakingblockmodelsubmit.seed()); + + try { +- submitnodestorage$breakingblockmodelsubmit.model().collectParts(this.random, this.parts); ++ submitnodestorage$breakingblockmodelsubmit.model().collectParts(this.random, this.parts, submitnodestorage$breakingblockmodelsubmit.data()); + + for (BlockStateModelPart blockstatemodelpart : this.parts) { + putPartQuads(blockstatemodelpart, submitnodestorage$breakingblockmodelsubmit.pose(), this.quadInstance, NO_TINT, vertexconsumer, null); diff --git a/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch index 386f3cf404..688160ecff 100644 --- a/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/client/renderer/fog/FogRenderer.java +++ b/net/minecraft/client/renderer/fog/FogRenderer.java -@@ -159,6 +_,12 @@ - fogBlue = Mth.lerp(brightenFactor, fogBlue, fogBlue * scale); +@@ -153,6 +_,12 @@ + f2 = Mth.lerp(f6, f2, f2 * f7); + } + ++ var fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(camera, partialTicks, level, renderDistance, darkenWorldAmount, f5, f1, f2); ++ ++ f5 = fogColor.x(); ++ f1 = fogColor.y(); ++ f2 = fogColor.z(); ++ + dest.set(f5, f1, f2, 1.0F); } - -+ var fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(camera, partialTicks, level, renderDistance, darkenWorldAmount, fogRed, fogGreen, fogBlue); -+ -+ fogRed = fogColor.x(); -+ fogGreen = fogColor.y(); -+ fogBlue = fogColor.z(); -+ - dest.set(fogRed, fogGreen, fogBlue, 1.0F); - } - -@@ -186,6 +_,7 @@ - float renderDistanceFogSpan = Mth.clamp(renderDistanceInBlocks / 10.0F, 4.0F, 64.0F); - fog.renderDistanceStart = renderDistanceInBlocks - renderDistanceFogSpan; - fog.renderDistanceEnd = renderDistanceInBlocks; -+ fog.color = net.minecraftforge.client.ForgeHooksClient.setupFog(fogType, camera, deltaTracker, fog, fog.color); - return fog; + } +@@ -181,6 +_,7 @@ + float f2 = Mth.clamp(f1 / 10.0F, 4.0F, 64.0F); + fogdata.renderDistanceStart = f1 - f2; + fogdata.renderDistanceEnd = f1; ++ fogdata.color = net.minecraftforge.client.ForgeHooksClient.setupFog(fogtype, camera, deltaTracker, fogdata, fogdata.color); + return fogdata; } diff --git a/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch new file mode 100644 index 0000000000..b8a7a9c88e --- /dev/null +++ b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch @@ -0,0 +1,67 @@ +--- a/net/minecraft/client/renderer/rendertype/RenderSetup.java ++++ b/net/minecraft/client/renderer/rendertype/RenderSetup.java +@@ -32,6 +_,7 @@ + final boolean sortOnUpload; + final int bufferSize; + final LayeringTransform layeringTransform; ++ final Map texturesWithSamplers; + + private RenderSetup( + final RenderPipeline pipeline, +@@ -44,7 +_,8 @@ + final RenderSetup.OutlineProperty outlineProperty, + final boolean affectsCrumbling, + final boolean sortOnUpload, +- final int bufferSize ++ final int bufferSize, ++ Map texturesWithSamplers + ) { + this.pipeline = pipeline; + this.textures = textures; +@@ -57,6 +_,7 @@ + this.affectsCrumbling = affectsCrumbling; + this.sortOnUpload = sortOnUpload; + this.bufferSize = bufferSize; ++ this.texturesWithSamplers = texturesWithSamplers; + } + + @Override +@@ -115,6 +_,8 @@ + ); + } + ++ map.putAll(this.texturesWithSamplers); ++ + return map; + } + } +@@ -150,6 +_,7 @@ + private int bufferSize = 1536; + private RenderSetup.OutlineProperty outlineProperty = RenderSetup.OutlineProperty.NONE; + private final Map textures = new HashMap<>(); ++ private final Map texturesWithSamplers = new HashMap<>(); + + private RenderSetupBuilder(final RenderPipeline pipeline) { + this.pipeline = pipeline; +@@ -165,6 +_,11 @@ + return this; + } + ++ public RenderSetup.RenderSetupBuilder withTexture(String name, GpuTextureView textureView, GpuSampler sampler) { ++ this.texturesWithSamplers.put(name, new RenderSetup.TextureAndSampler(textureView, sampler)); ++ return this; ++ } ++ + public RenderSetup.RenderSetupBuilder useLightmap() { + this.useLightmap = true; + return this; +@@ -222,7 +_,8 @@ + this.outlineProperty, + this.affectsCrumbling, + this.sortOnUpload, +- this.bufferSize ++ this.bufferSize, ++ this.texturesWithSamplers + ); + } + } diff --git a/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderTypes.java.patch b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderTypes.java.patch index fcbfb34b31..6297ab501f 100644 --- a/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderTypes.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderTypes.java.patch @@ -12,9 +12,9 @@ @@ -582,19 +_,19 @@ } - public static RenderType textGrayscale(final Identifier texture) { -- return TEXT_GRAYSCALE.apply(texture); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextGrayscale(texture); + public static RenderType textIntensity(final Identifier texture) { +- return TEXT_INTENSITY.apply(texture); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensity(texture); } public static RenderType textPolygonOffset(final Identifier texture) { @@ -22,9 +22,9 @@ + return net.minecraftforge.client.ForgeRenderTypes.getTextPolygonOffset(texture); } - public static RenderType textGrayscalePolygonOffset(final Identifier texture) { -- return TEXT_GRAYSCALE_POLYGON_OFFSET.apply(texture); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextGrayscalePolygonOffset(texture); + public static RenderType textIntensityPolygonOffset(final Identifier texture) { +- return TEXT_INTENSITY_POLYGON_OFFSET.apply(texture); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensityPolygonOffset(texture); } public static RenderType textSeeThrough(final Identifier texture) { @@ -36,9 +36,9 @@ @@ -602,7 +_,7 @@ } - public static RenderType textGrayscaleSeeThrough(final Identifier texture) { -- return TEXT_GRAYSCALE_SEE_THROUGH.apply(texture); -+ return net.minecraftforge.client.ForgeRenderTypes.getTextGrayscaleSeeThrough(texture); + public static RenderType textIntensitySeeThrough(final Identifier texture) { +- return TEXT_INTENSITY_SEE_THROUGH.apply(texture); ++ return net.minecraftforge.client.ForgeRenderTypes.getTextIntensitySeeThrough(texture); } public static RenderType lightning() { 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 0a07048d44..3239ef2fb1 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/client/renderer/texture/MipmapGenerator.java +++ b/net/minecraft/client/renderer/texture/MipmapGenerator.java -@@ -123,12 +_,16 @@ - float cutoutRef = mipmapStrategy == MipmapStrategy.STRICT_CUTOUT ? 0.3F : 0.5F; - float originalCoverage = isCutoutMip ? alphaTestCoverage(currentMips[0], cutoutRef, 1.0F) : 0.0F; +@@ -122,12 +_,16 @@ + float f = mipmapStrategy == MipmapStrategy.STRICT_CUTOUT ? 0.3F : 0.5F; + float f1 = flag ? alphaTestCoverage(currentMips[0], f, 1.0F) : 0.0F; -+ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(result[0].getWidth(), result[0].getHeight()); - for (int level = 1; level <= newMipLevel; level++) { - if (level < currentMips.length) { - result[level] = currentMips[level]; - } else { - NativeImage lastData = result[level - 1]; -- NativeImage data = new NativeImage(lastData.getWidth() >> 1, lastData.getHeight() >> 1, false); -+ // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes -+ NativeImage data = new NativeImage(Math.max(1, lastData.getWidth() >> 1), Math.max(1, lastData.getHeight() >> 1), false); -+ if (level <= maxMipmapLevel) { ++ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(anativeimage[0].getWidth(), anativeimage[0].getHeight()); + for (int i = 1; i <= newMipLevel; i++) { + if (i < currentMips.length) { + anativeimage[i] = currentMips[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 width = data.getWidth(); - int height = data.getHeight(); + int j = nativeimage1.getWidth(); + int k = nativeimage1.getHeight(); -@@ -147,6 +_,7 @@ +@@ -146,6 +_,7 @@ - data.setPixel(x, y, color); + nativeimage1.setPixel(l, i1, j2); + } ++ } } -+ } - } - result[level] = data; + anativeimage[i] = nativeimage1; 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 0d4d9f1d02..c8a1dd5a2a 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/client/renderer/texture/SpriteLoader.java +++ b/net/minecraft/client/renderer/texture/SpriteLoader.java -@@ -71,7 +_,7 @@ - int minSize = Math.min(minTexelSize, lowestOneBit); - int minPowerOfTwo = Mth.log2(minSize); - int mipLevel; -- if (minPowerOfTwo < maxMipmapLevels) { -+ if (minPowerOfTwo < maxMipmapLevels && net.minecraftforge.common.ForgeConfig.CLIENT.allowMipmapLowering()) { // Forge: Do not lower the mipmap level - LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, maxMipmapLevels, minPowerOfTwo, minSize); - mipLevel = minPowerOfTwo; +@@ -72,7 +_,7 @@ + int j1 = Math.min(j, k); + int k1 = Mth.log2(j1); + int l1; +- if (k1 < maxMipmapLevels) { ++ if (k1 < maxMipmapLevels && net.minecraftforge.common.ForgeConfig.CLIENT.allowMipmapLowering()) { // Forge: Do not lower the mipmap level + LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, maxMipmapLevels, k1, j1); + l1 = k1; } else { -@@ -129,7 +_,8 @@ +@@ -130,7 +_,8 @@ final Executor taskExecutor, final Set> additionalMetadata ) { -- SpriteResourceLoader spriteResourceLoader = SpriteResourceLoader.create(additionalMetadata); +- SpriteResourceLoader spriteresourceloader = SpriteResourceLoader.create(additionalMetadata); + var sections = net.minecraftforge.client.ForgeHooksClient.getAtlastMetadataSections(atlasInfoLocation, additionalMetadata); -+ SpriteResourceLoader spriteResourceLoader = SpriteResourceLoader.create(sections); ++ SpriteResourceLoader spriteresourceloader = SpriteResourceLoader.create(sections); return CompletableFuture.>supplyAsync(() -> SpriteSourceList.load(manager, atlasInfoLocation).list(manager), taskExecutor) - .thenCompose(sprites -> runSpriteSuppliers(spriteResourceLoader, (List)sprites, taskExecutor)) + .thenCompose(sprites -> runSpriteSuppliers(spriteresourceloader, (List)sprites, taskExecutor)) .thenApply(resources -> this.stitch((List)resources, maxMipmapLevels, taskExecutor)); -@@ -138,7 +_,7 @@ +@@ -139,7 +_,7 @@ private Map getStitchedSprites(final Stitcher stitcher, final int atlasWidth, final int atlasHeight) { - Map result = new HashMap<>(); + Map map = new HashMap<>(); stitcher.gatherSprites( -- (contents, x, y, padding) -> result.put(contents.name(), new TextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) -+ (contents, x, y, padding) -> result.put(contents.name(), net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) +- (contents, x, y, padding) -> map.put(contents.name(), new TextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) ++ (contents, x, y, padding) -> map.put(contents.name(), net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) ); - return result; + 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 98165c19d2..bd353204e2 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch @@ -10,25 +10,25 @@ .thenComparing(h -> h.entry.name()); @@ -54,6 +_,14 @@ - for (Stitcher.Holder holder : holders) { + 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"); -+ holders.forEach(h -> sb.append("\t").append(h).append("\n")); ++ list.forEach(h -> sb.append("\t").append(h).append("\n")); + LOGGER.info(sb.toString()); + } - throw new StitcherException(holder.entry, holders.stream().map(h -> h.entry).collect(ImmutableList.toImmutableList())); + throw new StitcherException(holder.entry, list.stream().map(h -> h.entry).collect(ImmutableList.toImmutableList())); } } -@@ -94,7 +_,7 @@ - boolean yWillGrow = yCanGrow && yCurrentSize != yNewSize; - boolean growOnX; - if (xWillGrow ^ yWillGrow) { -- growOnX = xWillGrow; -+ growOnX = !xWillGrow && xCanGrow; // Forge: Fix stitcher not expanding entire height before growing width, and (potentially) growing larger then the max size. - } else { - growOnX = xCanGrow && xCurrentSize <= yCurrentSize; - } +@@ -93,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 6b9b413024..dc7f995bb9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/renderer/texture/TextureAtlas.java +++ b/net/minecraft/client/renderer/texture/TextureAtlas.java -@@ -135,6 +_,7 @@ - } +@@ -119,6 +_,7 @@ + this.sprites = list; + this.animatedTexturesStates = List.copyOf(list1); + this.uploadInitialContents(); ++ net.minecraftforge.client.ForgeHooksClient.onTextureStitchedPost(this); + if (SharedConstants.DEBUG_DUMP_TEXTURE_ATLAS) { + Path path = TextureUtil.getDebugTexturePath(); - this.uploadInitialContents(); -+ net.minecraftforge.client.ForgeHooksClient.onTextureStitchedPost(this); - if (SharedConstants.DEBUG_DUMP_TEXTURE_ATLAS) { - Path dumpDir = TextureUtil.getDebugTexturePath(); - -@@ -324,5 +_,10 @@ +@@ -304,5 +_,10 @@ int getHeight() { return this.height; 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 3fadacbcc9..dec5805bd8 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,12 @@ --- a/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java +++ b/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java @@ -68,6 +_,9 @@ - frameSize = new FrameSize(image.getWidth(), image.getHeight()); + framesize = new FrameSize(nativeimage.getWidth(), nativeimage.getHeight()); } -+ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(spriteLocation, resource, frameSize, image, additionalMetadata); ++ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(spriteLocation, resource, framesize, nativeimage, list); + if (contents != null) return contents; + - return new SpriteContents(spriteLocation, frameSize, image, animationInfo, additionalMetadata, textureInfo); + return new SpriteContents(spriteLocation, framesize, nativeimage, optional, list, optional1); }; } diff --git a/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch b/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch new file mode 100644 index 0000000000..1bf7bb8c3e --- /dev/null +++ b/patches/minecraft/net/minecraft/client/resources/language/I18n.java.patch @@ -0,0 +1,10 @@ +--- a/net/minecraft/client/resources/language/I18n.java ++++ b/net/minecraft/client/resources/language/I18n.java +@@ -15,6 +_,7 @@ + + static void setLanguage(final Language locale) { + language = locale; ++ net.minecraftforge.common.ForgeI18n.loadLanguageData(locale.getLanguageData()); + } + + public static String get(final String id, final Object... args) { 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 03ba4a31c1..e951131a98 100644 --- a/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch @@ -10,8 +10,8 @@ } private static Map extractLanguages(final Stream resourcePacks) { -@@ -67,8 +_,12 @@ - this.reloadCallback.accept(locale); +@@ -68,8 +_,12 @@ + this.reloadCallback.accept(clientlanguage); } + private java.util.Locale javaLocale; // Forge: add locale information for modders diff --git a/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch b/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch index e5da32b5be..c156208aa6 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/client/resources/model/BlockStateDefinitions.java @@ -33,6 +_,8 @@ - public static Function> definitionLocationToBlockStateMapper() { - Map> result = new HashMap<>(STATIC_DEFINITIONS); + static Function> definitionLocationToBlockStateMapper() { + Map> map = new HashMap<>(STATIC_DEFINITIONS); + var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onRegisterModeStateDefinitions(); -+ result.putAll(event.getStates()); ++ map.putAll(event.getStates()); for (Block block : BuiltInRegistries.BLOCK) { - result.put(block.builtInRegistryHolder().key().identifier(), block.getStateDefinition()); + map.put(block.builtInRegistryHolder().key().identifier(), block.getStateDefinition()); 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 1053df58f3..30c13e90c9 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelBaker.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/client/resources/model/ModelBaker.java +++ b/net/minecraft/client/resources/model/ModelBaker.java @@ -32,4 +_,16 @@ - interface SharedOperationKey { + public interface SharedOperationKey { T compute(ModelBaker modelBakery); } + diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch index 4ac9113c82..371b6f96db 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch @@ -15,20 +15,20 @@ @Override public String debugName() { return this.id.toString(); -@@ -229,14 +_,14 @@ - - private QuadCollection bakeDefaultState(final TextureSlots textureSlots, final ModelBaker baker, final ModelState state) { - QuadCollection result = this.getSlot(KEY_DEFAULT_GEOMETRY); -- return result != null ? result : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this)); -+ return result != null ? result : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this, getContext())); +@@ -233,14 +_,14 @@ + QuadCollection quadcollection = this.getSlot(KEY_DEFAULT_GEOMETRY); + return quadcollection != null + ? quadcollection +- : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this)); ++ : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this, getContext())); } @Override public QuadCollection bakeTopGeometry(final TextureSlots textureSlots, final ModelBaker baker, final ModelState state) { return state == BlockModelRotation.IDENTITY ? this.bakeDefaultState(textureSlots, baker, state) : this.modelBakeCache.computeIfAbsent(state, s -> { - UnbakedGeometry topGeometry = this.getTopGeometry(); -- return topGeometry.bake(textureSlots, baker, s, this); -+ return topGeometry.bake(textureSlots, baker, s, this, getContext()); + UnbakedGeometry unbakedgeometry = this.getTopGeometry(); +- return unbakedgeometry.bake(textureSlots, baker, s, this); ++ return unbakedgeometry.bake(textureSlots, baker, s, this, getContext()); }); } } 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 0b9ae29949..94851681bf 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/resources/model/ModelManager.java +++ b/net/minecraft/client/resources/model/ModelManager.java -@@ -61,6 +_,7 @@ +@@ -68,6 +_,7 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final FileToIdConverter MODEL_LISTER = FileToIdConverter.json("models"); private Map bakedItemStackModels = Map.of(); @@ -8,7 +8,7 @@ private Map itemProperties = Map.of(); private final AtlasManager atlasManager; private final PlayerSkinRenderCache playerSkinRenderCache; -@@ -71,6 +_,7 @@ +@@ -78,6 +_,7 @@ private @Nullable BlockModelSet blockModelSet; private @Nullable FluidStateModelSet fluidStateModelSet; private Object2IntMap modelGroups = Object2IntMaps.emptyMap(); @@ -16,7 +16,7 @@ public ModelManager(final BlockColors blockColors, final AtlasManager atlasManager, final PlayerSkinRenderCache playerSkinRenderCache) { this.blockColors = blockColors; -@@ -82,6 +_,18 @@ +@@ -89,6 +_,18 @@ return this.bakedItemStackModels.getOrDefault(id, this.missingModels.item()); } @@ -35,47 +35,49 @@ public ClientItem.Properties getItemProperties(final Identifier id) { return this.itemProperties.getOrDefault(id, ClientItem.Properties.DEFAULT); } -@@ -105,6 +_,7 @@ +@@ -112,6 +_,7 @@ final PreparableReloadListener.PreparationBarrier preparationBarrier, final Executor reloadExecutor ) { + net.minecraftforge.client.model.geometry.GeometryLoaderManager.init(); - ResourceManager manager = currentReload.resourceManager(); - CompletableFuture entityModelSet = CompletableFuture.supplyAsync(EntityModelSet::vanilla, taskExecutor); - CompletableFuture> modelCache = loadBlockModels(manager, taskExecutor); -@@ -224,12 +_,14 @@ + ResourceManager resourcemanager = currentReload.resourceManager(); + CompletableFuture completablefuture = CompletableFuture.supplyAsync(EntityModelSet::vanilla, taskExecutor); + CompletableFuture> completablefuture1 = loadBlockModels(resourcemanager, taskExecutor); +@@ -275,6 +_,8 @@ + completablefuture1, (bakingResult, bakedModels) -> { - blockItemMaterialBaker.logMissingTextures(); - Map fluidModels = FluidStateModelSet.bake(blockOnlyMaterialBaker); -+ fluidModels = net.minecraftforge.client.ForgeHooksClient.onFluidModelBake(bakery, blockOnlyMaterialBaker, fluidModels); + Map map = FluidStateModelSet.bake(materialbaker); ++ map = net.minecraftforge.client.ForgeHooksClient.onFluidModelBake(bakery, materialbaker, map); + net.minecraftforge.client.ForgeHooksClient.onModifyBakingResult(bakery, bakingResult); - blockOnlyMaterialBaker.logMissingTextures(); - Map modelByStateCache = createBlockStateToModelDispatch( - bakingResult.blockStateModels(), bakingResult.missingModels().block() - ); - return new ModelManager.ReloadState( -- bakingResult, modelGroups, modelByStateCache, (Map)bakedModels, fluidModels, entityModelSet -+ bakingResult, modelGroups, modelByStateCache, (Map)bakedModels, fluidModels, entityModelSet, bakery - ); + multimap.asMap() + .forEach( + (location, sprites) -> LOGGER.warn( +@@ -292,7 +_,7 @@ + ) + ); + Map map1 = createBlockStateToModelDispatch(bakingResult.blockStateModels(), bakingResult.missingModels().block()); +- return new ModelManager.ReloadState(bakingResult, modelGroups, map1, (Map)bakedModels, map, entityModelSet); ++ return new ModelManager.ReloadState(bakingResult, modelGroups, map1, (Map)bakedModels, map, entityModelSet, bakery); } ); -@@ -261,10 +_,15 @@ + } +@@ -329,10 +_,15 @@ private void apply(final ModelManager.ReloadState preparations) { - ModelBakery.BakingResult bakedModels = preparations.bakedModels; + ModelBakery.BakingResult modelbakery$bakingresult = preparations.bakedModels; + // TODO [BlockState Models] fix + //this.bakedBlockStateModelsView = java.util.Collections.unmodifiableMap(this.bakedBlockStateModels); - this.bakedItemStackModels = bakedModels.itemStackModels(); + this.bakedItemStackModels = modelbakery$bakingresult.itemStackModels(); + this.bakedItemStackModelsView = java.util.Collections.unmodifiableMap(this.bakedItemStackModels); - this.itemProperties = bakedModels.itemProperties(); + this.itemProperties = modelbakery$bakingresult.itemProperties(); this.modelGroups = preparations.modelGroups; - this.missingModels = bakedModels.missingModels(); + this.missingModels = modelbakery$bakingresult.missingModels(); + this.modelBakery = preparations.modelBakery(); + net.minecraftforge.client.ForgeHooksClient.onModelBake(this, this.modelBakery); this.blockStateModelSet = new BlockStateModelSet(preparations.blockStateModels, this.missingModels.block()); this.blockModelSet = new BlockModelSet(this.blockStateModelSet, preparations.blockModels, this.blockColors); this.fluidStateModelSet = new FluidStateModelSet(preparations.fluidModels, this.missingModels.fluid()); -@@ -333,7 +_,8 @@ +@@ -368,7 +_,8 @@ Map blockStateModels, Map blockModels, Map fluidModels, diff --git a/patches/minecraft/net/minecraft/client/resources/model/ResolvedModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ResolvedModel.java.patch index d60e332b5f..8a69840bf3 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ResolvedModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ResolvedModel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/resources/model/ResolvedModel.java +++ b/net/minecraft/client/resources/model/ResolvedModel.java -@@ -89,7 +_,7 @@ +@@ -88,7 +_,7 @@ } default QuadCollection bakeTopGeometry(final TextureSlots textureSlots, final ModelBaker baker, final ModelState state) { @@ -9,7 +9,7 @@ } static Material.Baked resolveParticleMaterial(final TextureSlots textureSlots, final ModelBaker baker, final ModelDebugName resolvedModel) { -@@ -133,5 +_,9 @@ +@@ -132,5 +_,9 @@ default ItemTransforms getTopTransforms() { return findTopTransforms(this); diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch index 0623fc6b7a..509bff2402 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch @@ -21,11 +21,11 @@ return uvs.getVertexU(rotation.rotateVertexIndex(vertex)) / 16.0F; } @@ -38,7 +_,7 @@ - String texture = getTexture(object); - CuboidFace.UVs uvs = getUVs(object); - Quadrant rotation = getRotation(object); -- return new CuboidFace(cullDirection, tintIndex, texture, uvs, rotation); -+ return new CuboidFace(cullDirection, tintIndex, texture, uvs, rotation, net.minecraftforge.client.model.ForgeFaceData.read(object.get("forge_data"), null)); + String s = getTexture(jsonobject); + CuboidFace.UVs cuboidface$uvs = getUVs(jsonobject); + Quadrant quadrant = getRotation(jsonobject); +- return new CuboidFace(direction, i, s, cuboidface$uvs, quadrant); ++ return new CuboidFace(direction, i, s, cuboidface$uvs, quadrant, net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), null)); } private static int getTintIndex(final JsonObject object) { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch index 8bd3875a95..9f52c81911 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch @@ -23,13 +23,13 @@ static final Gson GSON = new GsonBuilder() .registerTypeAdapter(CuboidModel.class, new CuboidModel.Deserializer()) @@ -62,8 +_,9 @@ - guiLight = UnbakedModel.GuiLight.getByName(GsonHelper.getAsString(object, "gui_light")); + unbakedmodel$guilight = UnbakedModel.GuiLight.getByName(GsonHelper.getAsString(jsonobject, "gui_light")); } -+ var forgeData = net.minecraftforge.client.ForgeHooksClient.deserializeBlockModel(object, context); - Identifier parentLocation = parentName.isEmpty() ? null : Identifier.parse(parentName); -- return new CuboidModel(elements, guiLight, hasAmbientOcclusion, transforms, textureMap, parentLocation); -+ return new CuboidModel(elements, guiLight, hasAmbientOcclusion, transforms, textureMap, parentLocation, forgeData); ++ var forgeData = net.minecraftforge.client.ForgeHooksClient.deserializeBlockModel(jsonobject, context); + Identifier identifier = s.isEmpty() ? null : Identifier.parse(s); +- return new CuboidModel(unbakedgeometry, unbakedmodel$guilight, obool, itemtransforms, textureslots$data, identifier); ++ return new CuboidModel(unbakedgeometry, unbakedmodel$guilight, obool, itemtransforms, textureslots$data, identifier, forgeData); } private TextureSlots.Data getTextureMap(final JsonObject object) { @@ -42,4 +42,4 @@ + return geo; if (!object.has("elements")) { return null; - } + } else { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch index 3757ee8724..f9d2f52a10 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch @@ -1,17 +1,19 @@ --- a/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java +++ b/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java -@@ -52,8 +_,8 @@ - QuadCollection singleResult = null; - QuadCollection.Builder builder = null; +@@ -52,8 +_,10 @@ + QuadCollection quadcollection = null; + QuadCollection.Builder quadcollection$builder = null; -- for (int layerIndex = 0; layerIndex < LAYERS.size(); layerIndex++) { -- String textureReference = LAYERS.get(layerIndex); -+ for (int layerIndex = 0; true; layerIndex++) { // Forge: Allow for more layers -+ String textureReference = String.format(java.util.Locale.ROOT, "layer%d", layerIndex); - Material material = textureSlots.getMaterial(textureReference); +- for (int i = 0; i < LAYERS.size(); i++) { +- String s = LAYERS.get(i); ++ // Forge: Allow for more layers ++ int i = 0; ++ while (true) { ++ String s = String.format(java.util.Locale.ROOT, "layer%d", i++); + Material material = textureSlots.getMaterial(s); if (material == null) { break; -@@ -83,17 +_,29 @@ +@@ -83,6 +_,12 @@ public static void bakeExtrudedSprite( final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo ) { @@ -21,10 +23,13 @@ + public static void bakeExtrudedSprite( + final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo, final BakedQuad.MaterialInfo template + ) { - Vector3f from = new Vector3f(0.0F, 0.0F, 7.5F); - Vector3f to = new Vector3f(16.0F, 16.0F, 8.5F); - builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, SOUTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.SOUTH, modelState, null)); - builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, NORTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.NORTH, modelState, null)); + Vector3f vector3f = new Vector3f(0.0F, 0.0F, 7.5F); + Vector3f vector3f1 = new Vector3f(16.0F, 16.0F, 8.5F); + builder.addUnculledFace( +@@ -91,13 +_,19 @@ + builder.addUnculledFace( + FaceBakery.bakeQuad(interner, vector3f, vector3f1, NORTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.NORTH, modelState, null) + ); - bakeSideFaces(builder, interner, modelState, materialInfo); + bakeSideFaces(builder, interner, modelState, materialInfo, template); } @@ -32,14 +37,14 @@ public static void bakeSideFaces( final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo ) { -- SpriteContents sprite = materialInfo.sprite().contents(); +- SpriteContents spritecontents = materialInfo.sprite().contents(); + bakeSideFaces(builder, interner, modelState, materialInfo, materialInfo); + } + + public static void bakeSideFaces( + final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo, final BakedQuad.MaterialInfo template + ) { -+ SpriteContents sprite = template.sprite().contents(); - float xScale = 16.0F / sprite.width(); - float yScale = 16.0F / sprite.height(); - Vector3f from = new Vector3f(); ++ SpriteContents spritecontents = template.sprite().contents(); + float f = 16.0F / spritecontents.width(); + float f1 = 16.0F / spritecontents.height(); + Vector3f vector3f = new Vector3f(); diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch index f053947293..f7a3af2860 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch @@ -12,12 +12,12 @@ public static final ItemTransform NO_TRANSFORM = new ItemTransform(new Vector3f(), new Vector3f(), new Vector3f(1.0F, 1.0F, 1.0F)); public void apply(final boolean applyLeftHandFix, final PoseStack.Pose pose) { -@@ -63,7 +_,7 @@ - translation.set(Mth.clamp(translation.x, -5.0F, 5.0F), Mth.clamp(translation.y, -5.0F, 5.0F), Mth.clamp(translation.z, -5.0F, 5.0F)); - Vector3f scale = getVector3f(object, "scale", DEFAULT_SCALE); - scale.set(Mth.clamp(scale.x, -4.0F, 4.0F), Mth.clamp(scale.y, -4.0F, 4.0F), Mth.clamp(scale.z, -4.0F, 4.0F)); -- return new ItemTransform(rotation, translation, scale); -+ return new ItemTransform(rotation, translation, scale, this.getVector3f(object, "right_rotation", DEFAULT_ROTATION)); +@@ -62,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)); } - private static Vector3f getVector3f(final JsonObject object, final String key, final Vector3fc def) { + private Vector3f getVector3f(final JsonObject object, final String key, final Vector3f def) { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch index 6a93fdb22f..c8cff8dd0b 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch @@ -26,22 +26,22 @@ } @@ -70,6 +_,19 @@ - ItemTransform ground = this.getTransform(context, object, ItemDisplayContext.GROUND); - ItemTransform fixed = this.getTransform(context, object, ItemDisplayContext.FIXED); - ItemTransform fixedFromBottom = this.getTransform(context, object, ItemDisplayContext.ON_SHELF); + ItemTransform itemtransform6 = this.getTransform(context, jsonobject, ItemDisplayContext.GROUND); + ItemTransform itemtransform7 = this.getTransform(context, jsonobject, ItemDisplayContext.FIXED); + ItemTransform itemtransform8 = this.getTransform(context, jsonobject, ItemDisplayContext.ON_SHELF); + var builder = com.google.common.collect.ImmutableMap.builder(); + for (ItemDisplayContext type : ItemDisplayContext.values()) { + if (type.isModded()) { -+ var transform = this.getTransform(context, object, type); ++ var transform = this.getTransform(context, jsonobject, type); + var fallbackType = type; + while (transform == ItemTransform.NO_TRANSFORM && fallbackType.fallback() != null) { + fallbackType = fallbackType.fallback(); -+ transform = this.getTransform(context, object, fallbackType); ++ transform = this.getTransform(context, jsonobject, fallbackType); + } + if (transform != ItemTransform.NO_TRANSFORM) + builder.put(type, transform); + } + } return new ItemTransforms( - thirdPersonLeftHand, thirdPersonRightHand, firstPersonLeftHand, firstPersonRightHand, head, gui, ground, fixed, fixedFromBottom + itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7, itemtransform8 ); diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch index 5377339e00..4cbca8b569 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch @@ -4,7 +4,7 @@ final ModelState modelState, final ModelDebugName name ) { -- QuadCollection.Builder builder = new QuadCollection.Builder(); +- QuadCollection.Builder quadcollection$builder = new QuadCollection.Builder(); + var builder = new QuadCollection.Builder(); + bake(builder, elements, textures, modelBaker, modelState, name, id -> modelBaker.materials().resolveSlot(textures, id, name)); + return builder.build(); @@ -19,23 +19,35 @@ + final ModelDebugName name, + final java.util.function.Function materialMapper //Forge: Allow overwriting textures + ) { - for (CuboidModelElement element : elements) { - boolean drawXFaces = true; - boolean drawYFaces = true; + for (CuboidModelElement cuboidmodelelement : elements) { + boolean flag = true; + boolean flag1 = true; @@ -63,7 +_,7 @@ - case Z -> drawZFaces; + case Z -> flag2; }; - if (shouldDrawFace) { -- Material.Baked material = modelBaker.materials().resolveSlot(textures, face.texture(), name); -+ Material.Baked material = materialMapper.apply(face.texture()); - BakedQuad quad = FaceBakery.bakeQuad( - modelBaker, from, to, face, material, facing, modelState, element.rotation(), element.shade(), element.lightEmission() + if (flag3) { +- Material.Baked material$baked = modelBaker.materials().resolveSlot(textures, cuboidface.texture(), name); ++ Material.Baked material$baked = materialMapper.apply(cuboidface.texture()); + BakedQuad bakedquad = FaceBakery.bakeQuad( + modelBaker, + vector3fc, +@@ -77,9 +_,9 @@ + cuboidmodelelement.lightEmission() ); -@@ -76,7 +_,5 @@ + if (cuboidface.cullForDirection() == null) { +- quadcollection$builder.addUnculledFace(bakedquad); ++ builder.addUnculledFace(bakedquad); + } else { +- quadcollection$builder.addCulledFace( ++ builder.addCulledFace( + Direction.rotate(modelState.transformation().getMatrix(), cuboidface.cullForDirection()), bakedquad + ); + } +@@ -87,7 +_,5 @@ } } } - -- return builder.build(); +- return quadcollection$builder.build(); } } diff --git a/patches/minecraft/net/minecraft/client/resources/model/geometry/QuadCollection.java.patch b/patches/minecraft/net/minecraft/client/resources/model/geometry/QuadCollection.java.patch index 94a691fada..166488eaa6 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/geometry/QuadCollection.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/geometry/QuadCollection.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/resources/model/geometry/QuadCollection.java +++ b/net/minecraft/client/resources/model/geometry/QuadCollection.java -@@ -70,6 +_,12 @@ +@@ -71,6 +_,12 @@ return this.all; } @@ -10,6 +10,6 @@ + transformer.process(this.west), transformer.process(this.up), transformer.process(this.down)); + } + - public @BakedQuad.MaterialFlags int materialFlags() { + @BakedQuad.MaterialFlags + public int materialFlags() { if (this.materialFlags == -1) { - this.materialFlags = computeMaterialFlags(this.all); diff --git a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch index 989eb4441f..4a4b1b2840 100644 --- a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch +++ b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/client/server/IntegratedServer.java +++ b/net/minecraft/client/server/IntegratedServer.java -@@ -103,12 +_,13 @@ +@@ -98,12 +_,13 @@ LOGGER.info("Starting integrated minecraft server version {}", SharedConstants.getCurrentVersion().name()); this.setUsesAuthentication(true); this.initializeKeyPair(); + if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; this.loadLevel(); - GameProfile host = this.getSingleplayerProfile(); - String levelName = this.getWorldData().getLevelName(); - this.setMotd(host != null ? host.name() + " - " + levelName : levelName); + GameProfile gameprofile = this.getSingleplayerProfile(); + String s = this.getWorldData().getLevelName(); + this.setMotd(gameprofile != null ? gameprofile.name() + " - " + s : s); this.saveEverything(false, true, true); - return true; + return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); } @Override -@@ -371,6 +_,7 @@ +@@ -259,6 +_,7 @@ @Override public void halt(final boolean wait) { + if (isRunning()) this.executeBlocking(() -> { - for (ServerPlayer player : Lists.newArrayList(this.getPlayerList().getPlayers())) { - if (!player.getUUID().equals(this.uuid)) { + 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 fdc3c5c619..195146481f 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch @@ -10,15 +10,15 @@ this.socket.joinGroup(this.pingGroup); } @@ -87,7 +_,11 @@ - String motd = LanServerPinger.parseMotd(pingData); - String address = LanServerPinger.parseAddress(pingData); - if (address != null) { -- address = socketAddress.getHostAddress() + ":" + address; + String s = LanServerPinger.parseMotd(pingData); + String s1 = LanServerPinger.parseAddress(pingData); + if (s1 != null) { +- s1 = socketAddress.getHostAddress() + ":" + s1; + if (net.minecraftforge.network.DualStackUtils.checkIPv6(socketAddress)) { -+ address = "[" + com.google.common.net.InetAddresses.toAddrString(socketAddress) + "]:" + address; ++ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(socketAddress) + "]:" + s1; + } else { -+ address = socketAddress.getHostAddress() + ":" + address; ++ s1 = socketAddress.getHostAddress() + ":" + s1; + } - boolean found = false; + boolean flag = false; - for (LanServer server : 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 20ca07e2b3..43f23fa2e3 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch @@ -13,8 +13,8 @@ while (!this.isInterrupted() && this.isRunning) { try { -- InetAddress group = InetAddress.getByName("224.0.2.60"); -+ InetAddress group = InetAddress.getByName(MULTICAST_GROUP); - DatagramPacket packet = new DatagramPacket(ping, ping.length, group, 4445); - this.socket.send(packet); - } catch (IOException e) { +- 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 0beb89e8a4..d7c50023ae 100644 --- a/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/sounds/SoundEngine.java +++ b/net/minecraft/client/sounds/SoundEngine.java -@@ -82,6 +_,7 @@ +@@ -84,6 +_,7 @@ this.options = options; this.soundBuffers = new SoundBufferLibrary(resourceProvider); this.lastSeenDevices = this.deviceTracker.currentDevices(); @@ -8,7 +8,7 @@ } public void reload() { -@@ -99,6 +_,7 @@ +@@ -101,6 +_,7 @@ this.destroy(); this.loadLibrary(); @@ -16,7 +16,7 @@ } private synchronized void loadLibrary() { -@@ -340,7 +_,7 @@ +@@ -342,12 +_,15 @@ } } @@ -24,33 +24,31 @@ + public SoundEngine.PlayResult play(SoundInstance instance) { if (!this.loaded) { return SoundEngine.PlayResult.NOT_STARTED; - } -@@ -349,6 +_,9 @@ + } else if (!instance.canPlaySound()) { return SoundEngine.PlayResult.NOT_STARTED; - } - -+ instance = net.minecraftforge.client.ForgeHooksClient.playSound(this, instance); -+ if (instance == null || !instance.canPlaySound()) -+ return SoundEngine.PlayResult.NOT_STARTED; - WeighedSoundEvents soundEvent = instance.resolve(this.soundManager); - Identifier eventLocation = instance.getIdentifier(); - if (soundEvent == null) { -@@ -430,15 +_,18 @@ - channel.setSelfPosition(position); - channel.setRelative(isRelative); - }); -+ SoundInstance soundinstance = instance; - if (!isStreaming) { - this.soundBuffers.getCompleteBuffer(sound.getPath()).thenAccept(soundBuffer -> handle.execute(channel -> { - channel.attachStaticBuffer(soundBuffer); - channel.play(); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlaySoundSource(this, soundinstance, channel); - })); - } else { - this.soundBuffers.getStream(sound.getPath(), isLooping).thenAccept(stream -> handle.execute(channel -> { - channel.attachBufferStream(stream); - channel.play(); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlayStreamingSource(this, soundinstance, channel); - })); - } + } else { ++ instance = net.minecraftforge.client.ForgeHooksClient.playSound(this, instance); ++ if (instance == null || !instance.canPlaySound()) ++ return SoundEngine.PlayResult.NOT_STARTED; + WeighedSoundEvents weighedsoundevents = instance.resolve(this.soundManager); + Identifier identifier = instance.getIdentifier(); + if (weighedsoundevents == null) { +@@ -427,15 +_,18 @@ + channel.setSelfPosition(vec3); + channel.setRelative(flag); + }); ++ SoundInstance soundinstance = instance; + if (!flag1) { + this.soundBuffers.getCompleteBuffer(sound.getPath()).thenAccept(soundBuffer -> channelaccess$channelhandle.execute(channel -> { + channel.attachStaticBuffer(soundBuffer); + channel.play(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlaySoundSource(this, soundinstance, channel); + })); + } else { + this.soundBuffers.getStream(sound.getPath(), flag3).thenAccept(stream -> channelaccess$channelhandle.execute(channel -> { + channel.attachBufferStream(stream); + channel.play(); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onPlayStreamingSource(this, soundinstance, channel); + })); + } diff --git a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch index 33b4390d27..d0471f04cd 100644 --- a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch +++ b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/CommandSourceStack.java +++ b/net/minecraft/commands/CommandSourceStack.java -@@ -48,7 +_,7 @@ +@@ -49,7 +_,7 @@ import net.minecraft.world.phys.Vec3; import org.jspecify.annotations.Nullable; diff --git a/patches/minecraft/net/minecraft/commands/Commands.java.patch b/patches/minecraft/net/minecraft/commands/Commands.java.patch index 58a2296f83..4abd7ee2b8 100644 --- a/patches/minecraft/net/minecraft/commands/Commands.java.patch +++ b/patches/minecraft/net/minecraft/commands/Commands.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/Commands.java +++ b/net/minecraft/commands/Commands.java -@@ -265,7 +_,7 @@ +@@ -267,7 +_,7 @@ ChaseCommand.register(this.dispatcher); } @@ -9,19 +9,19 @@ RaidCommand.register(this.dispatcher, context); DebugPathCommand.register(this.dispatcher); DebugMobSpawningCommand.register(this.dispatcher); -@@ -299,6 +_,7 @@ +@@ -300,6 +_,7 @@ + if (commandSelection.includeIntegrated) { PublishCommand.register(this.dispatcher); - UnpublishCommand.register(this.dispatcher); } + net.minecraftforge.event.ForgeEventFactory.onCommandRegister(this.dispatcher, commandSelection, context); this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer()); } -@@ -321,9 +_,18 @@ +@@ -322,9 +_,18 @@ public void performCommand(final ParseResults command, final String commandString) { - CommandSourceStack sender = command.getContext().getSource(); + CommandSourceStack commandsourcestack = command.getContext().getSource(); Profiler.get().push(() -> "/" + commandString); -- ContextChain commandChain = finishParsing(command, commandString, sender); +- ContextChain contextchain = finishParsing(command, commandString, commandsourcestack); try { + var event = new net.minecraftforge.event.CommandEvent(command); @@ -33,19 +33,19 @@ + } + return; + } -+ ContextChain commandChain = finishParsing(event.getParseResults(), commandString, sender); - if (commandChain != null) { ++ ContextChain contextchain = finishParsing(event.getParseResults(), commandString, commandsourcestack); + if (contextchain != null) { executeCommandInContext( - sender, -@@ -414,7 +_,10 @@ - Map, CommandNode> playerCommands = new HashMap<>(); - RootCommandNode root = new RootCommandNode<>(); - playerCommands.put(this.dispatcher.getRoot(), root); -- fillUsableCommands(this.dispatcher.getRoot(), root, player.createCommandSourceStack(), playerCommands); + commandsourcestack, +@@ -416,7 +_,10 @@ + Map, CommandNode> map = new HashMap<>(); + RootCommandNode rootcommandnode = new RootCommandNode<>(); + map.put(this.dispatcher.getRoot(), rootcommandnode); +- fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, player.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(), root, playerCommands, player.createCommandSourceStack(), ctx -> 0, suggest -> suggest); ++ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, player.createCommandSourceStack(), ctx -> 0, suggest -> suggest); + // FORGE: Clean any modded command content if the client is vanilla -+ root = net.minecraftforge.server.command.CommandHelper.filterCommandList(player.connection.getConnection(), root); - player.connection.send(new ClientboundCommandsPacket(root, COMMAND_NODE_INSPECTOR)); ++ rootcommandnode = net.minecraftforge.server.command.CommandHelper.filterCommandList(player.connection.getConnection(), rootcommandnode); + player.connection.send(new ClientboundCommandsPacket(rootcommandnode, COMMAND_NODE_INSPECTOR)); } diff --git a/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch index 8cbc4da9a8..8d6474fe18 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 -@@ -128,7 +_,7 @@ - if (contextBuilder.getSource() instanceof SharedSuggestionProvider source) { - StringReader reader = new StringReader(builder.getInput()); - reader.setCursor(builder.getStart()); -- EntitySelectorParser parser = new EntitySelectorParser(reader, source.permissions().hasPermission(Permissions.COMMANDS_ENTITY_SELECTORS)); -+ EntitySelectorParser parser = new EntitySelectorParser(reader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(source)); +@@ -130,7 +_,7 @@ + StringReader stringreader = new StringReader(builder.getInput()); + stringreader.setCursor(builder.getStart()); + EntitySelectorParser entityselectorparser = new EntitySelectorParser( +- stringreader, sharedsuggestionprovider.permissions().hasPermission(Permissions.COMMANDS_ENTITY_SELECTORS) ++ stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider) + ); try { - parser.parse(); diff --git a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch index 0f583f2c97..a9fcd71425 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch @@ -3,18 +3,18 @@ @@ -31,7 +_,7 @@ public static Objective getObjective(final CommandContext context, final String name) throws CommandSyntaxException { - String id = context.getArgument(name, String.class); + String s = context.getArgument(name, String.class); - Scoreboard scoreboard = context.getSource().getServer().getScoreboard(); + Scoreboard scoreboard = context.getSource().getScoreboard(); - Objective objective = scoreboard.getObjective(id); + Objective objective = scoreboard.getObjective(s); if (objective == null) { - throw ERROR_OBJECTIVE_NOT_FOUND.create(id); + throw ERROR_OBJECTIVE_NOT_FOUND.create(s); @@ -57,7 +_,7 @@ public CompletableFuture listSuggestions(final CommandContext context, final SuggestionsBuilder builder) { - S rawSource = context.getSource(); - if (rawSource instanceof CommandSourceStack source) { -- return SharedSuggestionProvider.suggest(source.getServer().getScoreboard().getObjectiveNames(), builder); -+ return SharedSuggestionProvider.suggest(source.getScoreboard().getObjectiveNames(), builder); + S s = context.getSource(); + if (s instanceof CommandSourceStack commandsourcestack) { +- return SharedSuggestionProvider.suggest(commandsourcestack.getServer().getScoreboard().getObjectiveNames(), builder); ++ return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), builder); } else { - return rawSource instanceof SharedSuggestionProvider source ? source.customSuggestion(context) : Suggestions.empty(); + return s instanceof SharedSuggestionProvider sharedsuggestionprovider ? sharedsuggestionprovider.customSuggestion(context) : Suggestions.empty(); } diff --git a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch index 257d518e49..40bf69e0c8 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch @@ -3,9 +3,9 @@ @@ -28,7 +_,7 @@ public static PlayerTeam getTeam(final CommandContext context, final String name) throws CommandSyntaxException { - String id = context.getArgument(name, String.class); + String s = context.getArgument(name, String.class); - Scoreboard scoreboard = context.getSource().getServer().getScoreboard(); + Scoreboard scoreboard = context.getSource().getScoreboard(); - PlayerTeam team = scoreboard.getPlayerTeam(id); - if (team == null) { - throw ERROR_TEAM_NOT_FOUND.create(id); + PlayerTeam playerteam = scoreboard.getPlayerTeam(s); + if (playerteam == null) { + throw ERROR_TEAM_NOT_FOUND.create(s); 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 51f2fe36c1..553740988c 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/arguments/selector/EntitySelectorParser.java +++ b/net/minecraft/commands/arguments/selector/EntitySelectorParser.java -@@ -465,6 +_,11 @@ +@@ -466,6 +_,11 @@ } this.reader.skip(); @@ -12,7 +12,7 @@ this.parseSelector(); } else { this.parseNameOrUUID(); -@@ -481,6 +_,7 @@ +@@ -482,6 +_,7 @@ builder.suggest("@s", Component.translatable("argument.entity.selector.self")); builder.suggest("@e", Component.translatable("argument.entity.selector.allEntities")); builder.suggest("@n", Component.translatable("argument.entity.selector.nearestEntity")); diff --git a/patches/minecraft/net/minecraft/core/BlockPos.java.patch b/patches/minecraft/net/minecraft/core/BlockPos.java.patch index 0755583bf8..3e33eccdeb 100644 --- a/patches/minecraft/net/minecraft/core/BlockPos.java.patch +++ b/patches/minecraft/net/minecraft/core/BlockPos.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/core/BlockPos.java +++ b/net/minecraft/core/BlockPos.java -@@ -29,7 +_,7 @@ - import org.apache.commons.lang3.Validate; +@@ -30,7 +_,7 @@ + import org.apache.commons.lang3.tuple.Pair; @Immutable -public class BlockPos extends Vec3i { diff --git a/patches/minecraft/net/minecraft/core/Holder.java.patch b/patches/minecraft/net/minecraft/core/Holder.java.patch index 7fbde66e6f..38c1dc1eb9 100644 --- a/patches/minecraft/net/minecraft/core/Holder.java.patch +++ b/patches/minecraft/net/minecraft/core/Holder.java.patch @@ -4,8 +4,8 @@ import net.minecraft.tags.TagKey; import org.jspecify.annotations.Nullable; --public sealed interface Holder permits Holder.Direct, Holder.Reference { -+public sealed interface Holder extends java.util.function.Supplier, net.minecraftforge.registries.tags.IReverseTag permits Holder.Direct, Holder.Reference { +-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); diff --git a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch index 66de6fc518..e12c2068f4 100644 --- a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch +++ b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch @@ -17,45 +17,47 @@ this.validateWrite(key); Objects.requireNonNull(key); Objects.requireNonNull(value); -@@ -107,6 +_,8 @@ - holder.bindKey(key); - } else { - holder = this.byKey.computeIfAbsent(key, k -> Holder.Reference.createStandAlone(this, (ResourceKey)k)); -+ // Forge: Bind the value immediately so it can be queried while the registry is not frozen -+ holder.bindValue(value); - } - - this.byKey.put(key, holder); -@@ -278,7 +_,6 @@ - } - - this.frozen = true; -- this.byValue.forEach((value, holder) -> holder.bindValue((T)value)); - List unboundEntries = this.byKey - .entrySet() - .stream() -@@ -295,7 +_,8 @@ - throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values()); +@@ -104,6 +_,8 @@ + reference.bindKey(key); + } else { + reference = this.byKey.computeIfAbsent(key, k -> Holder.Reference.createStandAlone(this, (ResourceKey)k)); ++ // Forge: Bind the value immediately so it can be queried while the registry is not frozen ++ reference.bindValue(value); } -- 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; - } + this.byKey.put(key, reference); +@@ -275,7 +_,6 @@ + return this; + } else { + this.frozen = true; +- this.byValue.forEach((value, holder) -> holder.bindValue((T)value)); + List list = this.byKey.entrySet().stream().filter(e -> !e.getValue().isBound()).map(e -> e.getKey().identifier()).sorted().toList(); + if (!list.isEmpty()) { + throw new IllegalStateException("Unbound values in registry " + this.key() + ": " + list); +@@ -285,7 +_,8 @@ + throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values()); + } - if (this.allTags.isBound()) { -@@ -310,7 +_,8 @@ - .sorted() - .toList(); - if (!unboundTags.isEmpty()) { -- throw new IllegalStateException("Unbound tags in registry " + this.key() + ": " + unboundTags); -+ LOGGER.debug(MARKER, "Unbound tags in registry " + this.key() + ": " + unboundTags); -+ bindAllUnboundTagsToEmpty(); - } +- 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; + } - this.componentLookup = new DataComponentLookup<>(this.byId); -@@ -319,6 +_,13 @@ - return this; + if (this.allTags.isBound()) { +@@ -299,8 +_,9 @@ + .sorted() + .toList(); + if (!list1.isEmpty()) { +- throw new IllegalStateException("Unbound tags in registry " + this.key() + ": " + list1); +- } else { ++ LOGGER.debug(MARKER, "Unbound tags in registry " + this.key() + ": " + list1); ++ bindAllUnboundTagsToEmpty(); ++ } /* else */ { + this.componentLookup = new DataComponentLookup<>(this.byId); + this.allTags = MappedRegistry.TagSet.fromMap(this.frozenTags); + this.refreshTagsInHolders(); +@@ -311,6 +_,13 @@ + } } + private void bindAllUnboundTagsToEmpty() { @@ -68,7 +70,7 @@ @Override public Holder.Reference createIntrusiveHolder(final T value) { if (this.unregisteredIntrusiveHolders == null) { -@@ -393,6 +_,31 @@ +@@ -389,6 +_,31 @@ }; } @@ -100,15 +102,15 @@ @Override public Registry.PendingTags prepareTagReload(final TagLoader.LoadResult tags) { if (!this.frozen) { -@@ -441,6 +_,11 @@ - @Override - public HolderLookup.RegistryLookup lookup() { - return patchedHolder; -+ } +@@ -444,6 +_,11 @@ + @Override + public HolderLookup.RegistryLookup lookup() { + return registrylookup; ++ } + -+ @Override -+ public List> getPending(TagKey key) { -+ return pendingContents.getOrDefault(key, List.of()); - } ++ @Override ++ public List> getPending(TagKey key) { ++ return map.getOrDefault(key, List.of()); + } - @Override + @Override diff --git a/patches/minecraft/net/minecraft/core/Registry.java.patch b/patches/minecraft/net/minecraft/core/Registry.java.patch index 374850a9da..acfad02147 100644 --- a/patches/minecraft/net/minecraft/core/Registry.java.patch +++ b/patches/minecraft/net/minecraft/core/Registry.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/core/Registry.java +++ b/net/minecraft/core/Registry.java -@@ -175,5 +_,7 @@ +@@ -178,5 +_,7 @@ void apply(); int size(); diff --git a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch index 27bba4809c..ec117b8d3b 100644 --- a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch +++ b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/core/RegistrySetBuilder.java +++ b/net/minecraft/core/RegistrySetBuilder.java -@@ -22,7 +_,8 @@ +@@ -23,7 +_,8 @@ import org.apache.commons.lang3.mutable.MutableObject; import org.jspecify.annotations.Nullable; @@ -10,7 +10,7 @@ private final List> entries = new ArrayList<>(); private static HolderGetter wrapContextLookup(final HolderLookup.RegistryLookup original) { -@@ -66,14 +_,43 @@ +@@ -67,14 +_,43 @@ public RegistrySetBuilder add( final ResourceKey> key, final Lifecycle lifecycle, final RegistrySetBuilder.RegistryBootstrap bootstrap ) { @@ -53,38 +53,38 @@ + } + private RegistrySetBuilder.BuildState createState(final RegistryAccess context) { - RegistrySetBuilder.BuildState state = RegistrySetBuilder.BuildState.create(context, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key)); - this.entries.forEach(e -> e.apply(state)); -@@ -181,14 +_,16 @@ - } - - Map, Holder.Reference> entries = new HashMap<>(); -- HolderLookup.RegistryLookup patchContents = patchProvider.lookupOrThrow(registryKey); -+ HolderLookup.RegistryLookup patchContents = patchProvider.lookup(registryKey).orElse(null); - patchContents.listElements().forEach(elementHolder -> { - ResourceKey elementKey = elementHolder.key(); - RegistrySetBuilder.LazyHolder holder = new RegistrySetBuilder.LazyHolder<>(owner, elementKey); - holder.supplier = () -> cloner.clone((T)elementHolder.value(), patchProvider, targetProvider.get()); - entries.put(elementKey, holder); - }); -- HolderLookup.RegistryLookup fallbackContents = fallbackProvider.lookupOrThrow(registryKey); -+ HolderLookup.RegistryLookup fallbackContents = fallbackProvider.lookup(registryKey).orElse(null); -+ Lifecycle lifecycle = patchContents.registryLifecycle(); -+ if (fallbackContents != null) { - fallbackContents.listElements().forEach(elementHolder -> { - ResourceKey elementKey = elementHolder.key(); - entries.computeIfAbsent(elementKey, key -> { -@@ -197,7 +_,8 @@ - return holder; + RegistrySetBuilder.BuildState registrysetbuilder$buildstate = RegistrySetBuilder.BuildState.create( + context, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key) +@@ -183,14 +_,16 @@ + throw new NullPointerException("No cloner for " + registryKey.identifier()); + } else { + Map, Holder.Reference> map = new HashMap<>(); +- HolderLookup.RegistryLookup registrylookup = patchProvider.lookupOrThrow(registryKey); ++ HolderLookup.RegistryLookup registrylookup = patchProvider.lookup(registryKey).orElse(null); + registrylookup.listElements().forEach(elementHolder -> { + ResourceKey resourcekey = elementHolder.key(); + RegistrySetBuilder.LazyHolder lazyholder = new RegistrySetBuilder.LazyHolder<>(owner, resourcekey); + lazyholder.supplier = () -> cloner.clone((T)elementHolder.value(), patchProvider, targetProvider.get()); + map.put(resourcekey, lazyholder); }); - }); -- Lifecycle lifecycle = patchContents.registryLifecycle().add(fallbackContents.registryLifecycle()); -+ lifecycle = patchContents.registryLifecycle().add(fallbackContents.registryLifecycle()); -+ } - return lookupFromMap(registryKey, lifecycle, owner, entries); +- HolderLookup.RegistryLookup registrylookup1 = fallbackProvider.lookupOrThrow(registryKey); ++ HolderLookup.RegistryLookup registrylookup1 = fallbackProvider.lookup(registryKey).orElse(null); ++ Lifecycle lifecycle = registrylookup.registryLifecycle(); ++ if (registrylookup1 != null) { + registrylookup1.listElements().forEach(elementHolder -> { + ResourceKey resourcekey = elementHolder.key(); + map.computeIfAbsent(resourcekey, key -> { +@@ -199,7 +_,8 @@ + return lazyholder; + }); + }); +- Lifecycle lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); ++ lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); ++ } + return lookupFromMap(registryKey, lifecycle, owner, map); + } } - -@@ -266,6 +_,11 @@ +@@ -275,6 +_,11 @@ @Override public HolderGetter lookup(final ResourceKey> key) { return (HolderGetter)BuildState.this.registries.getOrDefault(key.identifier(), BuildState.this.lookup); diff --git a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch index f756c58e99..5ee5127611 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java @@ -29,18 +_,22 @@ - double spawnY = center.y() + direction.getStepY() * 1.125F; - double spawnZ = center.z() + direction.getStepZ() * justOutsideDispenser; - BlockPos frontPos = source.pos().relative(direction); -+ AbstractBoat boat = this.type.create(level, EntitySpawnReason.DISPENSER); -+ if (boat == null) { + double d2 = vec3.y() + direction.getStepY() * 1.125F; + double d3 = vec3.z() + direction.getStepZ() * d0; + BlockPos blockpos = source.pos().relative(direction); ++ AbstractBoat abstractboat = this.type.create(serverlevel, EntitySpawnReason.DISPENSER); ++ if (abstractboat == null) { + return this.defaultDispenseItemBehavior.dispense(source, dispensed); + } -+ boat.setYRot(direction.toYRot()); - double yOffset; -- if (level.getFluidState(frontPos).is(FluidTags.WATER)) { -+ if (boat.canBoatInFluid(level.getFluidState(frontPos))) { - yOffset = 1.0; ++ abstractboat.setYRot(direction.toYRot()); + double d4; +- if (serverlevel.getFluidState(blockpos).is(FluidTags.WATER)) { ++ if (abstractboat.canBoatInFluid(serverlevel.getFluidState(blockpos))) { + d4 = 1.0; } else { -- if (!level.getBlockState(frontPos).isAir() || !level.getFluidState(frontPos.below()).is(FluidTags.WATER)) { -+ if (!level.getBlockState(frontPos).isAir() || !boat.canBoatInFluid(level.getFluidState(frontPos.below()))) { +- if (!serverlevel.getBlockState(blockpos).isAir() || !serverlevel.getFluidState(blockpos.below()).is(FluidTags.WATER)) { ++ if (!serverlevel.getBlockState(blockpos).isAir() || !abstractboat.canBoatInFluid(serverlevel.getFluidState(blockpos.below()))) { return this.defaultDispenseItemBehavior.dispense(source, dispensed); } - yOffset = 0.0; + d4 = 0.0; } -- AbstractBoat boat = this.type.create(level, EntitySpawnReason.DISPENSER); - if (boat != null) { - boat.setInitialPos(spawnX, spawnY + yOffset, spawnZ); - EntityType.createDefaultStackConfig(level, dispensed, null).apply(boat); +- AbstractBoat abstractboat = this.type.create(serverlevel, EntitySpawnReason.DISPENSER); + if (abstractboat != null) { + abstractboat.setInitialPos(d1, d2 + d4, d3); + EntityType.createDefaultStackConfig(serverlevel, dispensed, null).accept(abstractboat); diff --git a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch index 35d8910ab2..eac5f4ca9a 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch @@ -1,11 +1,23 @@ --- a/net/minecraft/core/dispenser/DispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/DispenseItemBehavior.java -@@ -141,7 +_,7 @@ - DispensibleContainerItem bucket = (DispensibleContainerItem)dispensed.getItem(); - BlockPos target = source.pos().relative(source.state().getValue(DispenserBlock.FACING)); +@@ -148,7 +_,7 @@ + DispensibleContainerItem dispensiblecontaineritem = (DispensibleContainerItem)dispensed.getItem(); + BlockPos blockpos = source.pos().relative(source.state().getValue(DispenserBlock.FACING)); Level level = source.level(); -- if (bucket.emptyContents(null, level, target, null)) { -+ if (bucket.emptyContents(null, level, target, null, dispensed)) { - bucket.checkExtraContent(null, level, dispensed, target); +- if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null)) { ++ if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null, dispensed)) { + dispensiblecontaineritem.checkExtraContent(null, level, dispensed, blockpos); return this.consumeWithRemainder(source, dispensed, new ItemStack(Items.BUCKET)); } else { +@@ -199,8 +_,9 @@ + } else if (CampfireBlock.canLight(blockstate) || CandleBlock.canLight(blockstate) || CandleCakeBlock.canLight(blockstate)) { + serverlevel.setBlockAndUpdate(blockpos, blockstate.setValue(BlockStateProperties.LIT, true)); + serverlevel.gameEvent(null, GameEvent.BLOCK_CHANGE, blockpos); +- } else if (blockstate.getBlock() instanceof TntBlock) { +- if (TntBlock.prime(serverlevel, blockpos)) { ++ } else if (blockstate.isFlammable(serverlevel, blockpos, source.state().getValue(DispenserBlock.FACING).getOpposite())) { ++ if (blockstate.onCaughtFire(serverlevel, blockpos, source.state().getValue(DispenserBlock.FACING).getOpposite(), null)) { ++ if (blockstate.getBlock() instanceof TntBlock) + serverlevel.removeBlock(blockpos, false); + } else { + this.setSuccess(false); diff --git a/patches/minecraft/net/minecraft/core/dispenser/FlintAndSteelDispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/FlintAndSteelDispenseItemBehavior.java.patch deleted file mode 100644 index 67d867e46e..0000000000 --- a/patches/minecraft/net/minecraft/core/dispenser/FlintAndSteelDispenseItemBehavior.java.patch +++ /dev/null @@ -1,14 +0,0 @@ ---- a/net/minecraft/core/dispenser/FlintAndSteelDispenseItemBehavior.java -+++ b/net/minecraft/core/dispenser/FlintAndSteelDispenseItemBehavior.java -@@ -32,8 +_,9 @@ - } else if (CampfireBlock.canLight(target) || CandleBlock.canLight(target) || CandleCakeBlock.canLight(target)) { - level.setBlockAndUpdate(targetPos, target.setValue(BlockStateProperties.LIT, true)); - level.gameEvent(null, GameEvent.BLOCK_CHANGE, targetPos); -- } else if (target.getBlock() instanceof TntBlock) { -- if (TntBlock.prime(level, targetPos)) { -+ } else if (target.isFlammable(level, targetPos, source.state().getValue(DispenserBlock.FACING).getOpposite())) { -+ if (target.onCaughtFire(level, targetPos, source.state().getValue(DispenserBlock.FACING).getOpposite(), null)) { -+ if (target.getBlock() instanceof TntBlock) - level.removeBlock(targetPos, false); - } else { - this.setSuccess(false); diff --git a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch index ebb3225c50..b763fd20a7 100644 --- a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch +++ b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/core/registries/BuiltInRegistries.java +++ b/net/minecraft/core/registries/BuiltInRegistries.java -@@ -389,11 +_,13 @@ +@@ -385,11 +_,13 @@ } private static > R internalRegister( @@ -8,20 +8,20 @@ + final ResourceKey> name, R registry, final BuiltInRegistries.RegistryBootstrap loader ) { Bootstrap.checkBootstrapCalled(() -> "registry " + name.identifier()); - Identifier key = name.identifier(); -- LOADERS.put(key, () -> loader.run(registry)); + Identifier identifier = name.identifier(); +- LOADERS.put(identifier, () -> loader.run(registry)); + var maybeWrapped = net.minecraftforge.registries.GameData.getWrapper(name, registry); + registry = maybeWrapped; -+ LOADERS.put(key, () -> loader.run(maybeWrapped)); ++ LOADERS.put(identifier, () -> loader.run(maybeWrapped)); WRITABLE_REGISTRY.register((ResourceKey)name, registry, RegistrationInfo.BUILT_IN); return registry; } -@@ -429,7 +_,7 @@ +@@ -425,7 +_,7 @@ if (r instanceof DefaultedRegistry) { - Identifier key = ((DefaultedRegistry)r).getDefaultKey(); -- Objects.requireNonNull(r.getValue(key), "Missing default of DefaultedMappedRegistry: " + key); -+ Objects.requireNonNull(r.getValue(key), "Missing default of DefaultedMappedRegistry: " + r.key() + " - " + key); + Identifier identifier = ((DefaultedRegistry)r).getDefaultKey(); +- Objects.requireNonNull(r.getValue(identifier), "Missing default of DefaultedMappedRegistry: " + identifier); ++ Objects.requireNonNull(r.getValue(identifier), "Missing default of DefaultedMappedRegistry: " + r.key() + " - " + identifier); } }); } diff --git a/patches/minecraft/net/minecraft/core/registries/Registries.java.patch b/patches/minecraft/net/minecraft/core/registries/Registries.java.patch index 6069af07bf..19ddbb8e35 100644 --- a/patches/minecraft/net/minecraft/core/registries/Registries.java.patch +++ b/patches/minecraft/net/minecraft/core/registries/Registries.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/core/registries/Registries.java +++ b/net/minecraft/core/registries/Registries.java -@@ -326,6 +_,8 @@ +@@ -323,6 +_,8 @@ } private static String registryDirPath(final ResourceKey> registryKey) { diff --git a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch index 3aa26cd8e4..8ef665c9d2 100644 --- a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/DataGenerator.java +++ b/net/minecraft/data/DataGenerator.java -@@ -18,6 +_,7 @@ +@@ -19,6 +_,7 @@ protected final PackOutput vanillaPackOutput; protected final Set allProviderIds = new HashSet<>(); protected final Map providersToRun = new LinkedHashMap<>(); @@ -8,9 +8,9 @@ public DataGenerator(final Path output) { this.vanillaPackOutput = new PackOutput(output); -@@ -33,6 +_,35 @@ - Path packOutputDir = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(packId); - return new DataGenerator.PackGenerator(toRun, packId, new PackOutput(packOutputDir)); +@@ -34,6 +_,35 @@ + Path path = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(packId); + return new DataGenerator.PackGenerator(toRun, packId, new PackOutput(path)); } + public Map getProvidersView() { + return this.providersView; @@ -44,19 +44,19 @@ static { Bootstrap.bootStrap(); -@@ -60,6 +_,7 @@ +@@ -61,6 +_,7 @@ DataGenerator.LOGGER.debug("Generator {} already run for version {}", providerId, this.version.name()); } else { DataGenerator.LOGGER.info("Starting provider: {}", providerId); + net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + providerId); - stopwatch.start(); - cache.applyUpdate(cache.generateUpdate(providerId, provider::run).join()); - stopwatch.stop(); -@@ -109,6 +_,7 @@ - Stopwatch stopwatch = Stopwatch.createUnstarted(); + stopwatch1.start(); + hashcache.applyUpdate(hashcache.generateUpdate(providerId, provider::run).join()); + stopwatch1.stop(); +@@ -112,6 +_,7 @@ + Stopwatch stopwatch1 = Stopwatch.createUnstarted(); this.providersToRun.forEach((providerId, provider) -> { DataGenerator.LOGGER.info("Starting uncached provider: {}", providerId); + net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + providerId); - stopwatch.start(); + stopwatch1.start(); provider.run(CachedOutput.NO_CACHE).join(); - stopwatch.stop(); + stopwatch1.stop(); diff --git a/patches/minecraft/net/minecraft/data/HashCache.java.patch b/patches/minecraft/net/minecraft/data/HashCache.java.patch index abe2871b98..5efdd9058e 100644 --- a/patches/minecraft/net/minecraft/data/HashCache.java.patch +++ b/patches/minecraft/net/minecraft/data/HashCache.java.patch @@ -11,31 +11,31 @@ @@ -65,6 +_,7 @@ } - this.caches = loadedCaches; + this.caches = map; + this.originalCaches = Map.copyOf(this.caches); - this.initialCount = initialCount; + this.initialCount = i; } @@ -106,6 +_,8 @@ this.caches.forEach((providerId, cache) -> { if (this.cachesToWrite.contains(providerId)) { - Path cachePath = this.getProviderCachePath(providerId); + Path path = this.getProviderCachePath(providerId); + // Forge: Only rewrite the cache file if it changed or is missing -+ if (!cache.equals(this.originalCaches.get(providerId)) || !Files.exists(cachePath)) - cache.save(this.rootDir, cachePath, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime.now()) + "\t" + providerId); ++ if (!cache.equals(this.originalCaches.get(providerId)) || !Files.exists(path)) + cache.save(this.rootDir, path, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime.now()) + "\t" + providerId); } -@@ -217,10 +_,11 @@ - output.write(extraHeaderInfo); - output.newLine(); +@@ -224,10 +_,11 @@ + bufferedwriter.write(extraHeaderInfo); + bufferedwriter.newLine(); -- for (Entry e : this.data.entrySet()) { +- for (Entry entry : this.data.entrySet()) { + // Forge: Standardize order of entries -+ for (Entry e : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { - output.write(e.getValue().toString()); - output.write(32); -- output.write(rootDir.relativize(e.getKey()).toString()); -+ output.write(rootDir.relativize(e.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. - output.newLine(); ++ for (Entry entry : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { + bufferedwriter.write(entry.getValue().toString()); + bufferedwriter.write(32); +- bufferedwriter.write(rootDir.relativize(entry.getKey()).toString()); ++ bufferedwriter.write(rootDir.relativize(entry.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. + bufferedwriter.newLine(); } - } catch (IOException e) { + } catch (IOException ioexception) { diff --git a/patches/minecraft/net/minecraft/data/Main.java.patch b/patches/minecraft/net/minecraft/data/Main.java.patch index 5bb968547a..2329f4aa1c 100644 --- a/patches/minecraft/net/minecraft/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/data/Main.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/data/Main.java +++ b/net/minecraft/data/Main.java @@ -78,14 +_,17 @@ - OptionSpec allOption = parser.accepts("all", "Include all generators"); - OptionSpec outputOption = parser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); - OptionSpec inputOption = parser.accepts("input", "Input folder").withRequiredArg(); -+ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(parser, false); - OptionSet optionSet = parser.parse(args); -- if (!optionSet.has(helpOption) && optionSet.hasOptions()) { -+ if (!optionSet.has(helpOption) && optionSet.hasOptions() && loader.hasArgs(optionSet)) { - Path output = Paths.get(outputOption.value(optionSet)); - boolean allOptions = optionSet.has(allOption); - boolean server = allOptions || optionSet.has(serverOption); - boolean dev = allOptions || optionSet.has(devOption); - boolean reports = allOptions || optionSet.has(reportsOption); - Collection input = optionSet.valuesOf(inputOption).stream().map(x$0 -> Paths.get(x$0)).toList(); -+ if (!loader.run(optionSet, output, input, server, allOptions, dev, reports)) + OptionSpec optionspec4 = optionparser.accepts("all", "Include all generators"); + OptionSpec optionspec5 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); + OptionSpec optionspec6 = optionparser.accepts("input", "Input folder").withRequiredArg(); ++ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(optionparser, false); + OptionSet optionset = optionparser.parse(args); +- if (!optionset.has(optionspec) && optionset.hasOptions()) { ++ if (!optionset.has(optionspec) && optionset.hasOptions() && loader.hasArgs(optionset)) { + Path path = Paths.get(optionspec5.value(optionset)); + boolean flag = optionset.has(optionspec4); + boolean flag1 = flag || optionset.has(optionspec1); + boolean flag2 = flag || optionset.has(optionspec2); + boolean flag3 = flag || optionset.has(optionspec3); + Collection collection = optionset.valuesOf(optionspec6).stream().map(x$0 -> Paths.get(x$0)).toList(); ++ if (!loader.run(optionset, path, collection, flag1, flag, flag2, flag3)) + return; - DataGenerator generator = new DataGenerator.Cached(output, SharedConstants.getCurrentVersion(), true); - addServerDefinitionProviders(generator, server, reports); - addServerConverters(generator, input, server, dev); + DataGenerator datagenerator = new DataGenerator.Cached(path, SharedConstants.getCurrentVersion(), true); + addServerDefinitionProviders(datagenerator, flag1, flag3); + addServerConverters(datagenerator, collection, flag1, flag2); diff --git a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch index a26aec6715..80f7c557df 100644 --- a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch @@ -11,7 +11,7 @@ @Override public void generate(final BiConsumer, LootTable.Builder> output) { this.generate(); - Set> seen = new HashSet<>(); + Set> set = new HashSet<>(); - for (Block block : BuiltInRegistries.BLOCK) { + for (Block block : getKnownBlocks()) { diff --git a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch index 2cedc75886..143b382b8e 100644 --- a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/loot/EntityLootSubProvider.java +++ b/net/minecraft/data/loot/EntityLootSubProvider.java -@@ -117,12 +_,16 @@ +@@ -119,12 +_,16 @@ public abstract void generate(); @@ -11,11 +11,11 @@ @Override public void generate(final BiConsumer, LootTable.Builder> output) { this.generate(); - Set> seen = new HashSet<>(); + Set> set = new HashSet<>(); - BuiltInRegistries.ENTITY_TYPE - .listElements() + this.getKnownEntityTypes() + .map(EntityType::builtInRegistryHolder) .forEach( holder -> { - EntityType type = holder.value(); + EntityType entitytype = holder.value(); diff --git a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch index ac401dd8aa..5debbdb428 100644 --- a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/data/loot/LootTableProvider.java +++ b/net/minecraft/data/loot/LootTableProvider.java -@@ -59,7 +_,7 @@ +@@ -60,7 +_,7 @@ private CompletableFuture run(final CachedOutput cache, final HolderLookup.Provider registries) { - WritableRegistry tables = new MappedRegistry<>(Registries.LOOT_TABLE, Lifecycle.experimental()); - Map randomSequenceSeeds = new Object2ObjectOpenHashMap<>(); + WritableRegistry writableregistry = new MappedRegistry<>(Registries.LOOT_TABLE, Lifecycle.experimental()); + Map map = new Object2ObjectOpenHashMap<>(); - this.subProviders.forEach(subProvider -> subProvider.provider().apply(registries).generate((id, lootTable) -> { + this.getTables().forEach(subProvider -> subProvider.provider().apply(registries).generate((id, lootTable) -> { - Identifier sequenceId = sequenceIdForLootTable(id); - Identifier previous = randomSequenceSeeds.put(RandomSequence.seedForKey(sequenceId), sequenceId); - if (previous != null) { -@@ -75,11 +_,8 @@ - HolderGetter.Provider validationProvider = new RegistryAccess.ImmutableRegistryAccess(List.of(tables)).freeze(); - ValidationContextSource validationContext = new ValidationContextSource(problems, validationProvider); + Identifier identifier = sequenceIdForLootTable(id); + Identifier identifier1 = map.put(RandomSequence.seedForKey(identifier), identifier); + if (identifier1 != null) { +@@ -76,11 +_,8 @@ + HolderGetter.Provider holdergetter$provider = new RegistryAccess.ImmutableRegistryAccess(List.of(writableregistry)).freeze(); + ValidationContextSource validationcontextsource = new ValidationContextSource(problemreporter$collector, holdergetter$provider); -- for (ResourceKey missingTable : Sets.difference(this.requiredTables, tables.registryKeySet())) { -- problems.report(new LootTableProvider.MissingTableProblem(missingTable)); +- for (ResourceKey resourcekey : Sets.difference(this.requiredTables, writableregistry.registryKeySet())) { +- problemreporter$collector.report(new LootTableProvider.MissingTableProblem(resourcekey)); - } -+ validate(tables, validationContext, problems); ++ validate(writableregistry, validationcontextsource, problemreporter$collector); -- LootDataType.TABLE.runValidation(validationContext, tables); - if (!problems.isEmpty()) { - problems.forEach((id, problem) -> LOGGER.warn("Found validation problem in {}: {}", id, problem.description())); +- LootDataType.TABLE.runValidation(validationcontextsource, writableregistry); + if (!problemreporter$collector.isEmpty()) { + problemreporter$collector.forEach((id, problem) -> LOGGER.warn("Found validation problem in {}: {}", id, problem.description())); throw new IllegalStateException("Failed to validate loot tables, see logs"); -@@ -100,6 +_,18 @@ +@@ -101,6 +_,18 @@ @Override public final String getName() { return "Loot Tables"; diff --git a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch index 0dbbdf45d1..9c93b96500 100644 --- a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch @@ -1,43 +1,42 @@ --- a/net/minecraft/data/recipes/RecipeProvider.java +++ b/net/minecraft/data/recipes/RecipeProvider.java -@@ -908,14 +_,14 @@ - final List> tasks = new ArrayList<>(); - RecipeOutput recipeOutput = new RecipeOutput() { +@@ -892,13 +_,13 @@ + } + @Override - public void accept(final ResourceKey> id, final Recipe recipe, final @Nullable AdvancementHolder advancementHolder) { + public void accept(final ResourceKey> id, final Recipe recipe, net.minecraft.resources.@Nullable Identifier advancementId, com.google.gson.@Nullable JsonElement advancement) { - if (!allRecipes.add(id)) { + if (!set.add(id)) { throw new IllegalStateException("Duplicate recipe " + id.identifier()); - } - - this.saveRecipe(id, recipe); -- if (advancementHolder != null) { -- this.saveAdvancement(advancementHolder); -+ if (advancement != null && advancementId != null) { -+ this.saveAdvancement(advancementId, advancement); + } else { + this.saveRecipe(id, recipe); +- if (advancementHolder != null) { +- this.saveAdvancement(advancementHolder); ++ if (advancement != null && advancementId != null) { ++ this.saveAdvancement(advancementId, advancement); + } } } - -@@ -929,19 +_,26 @@ - AdvancementHolder root = Advancement.Builder.recipeAdvancement() +@@ -913,19 +_,26 @@ + AdvancementHolder advancementholder = Advancement.Builder.recipeAdvancement() .addCriterion("impossible", CriteriaTriggers.IMPOSSIBLE.createCriterion(new ImpossibleTrigger.TriggerInstance())) .build(RecipeBuilder.ROOT_RECIPE_ADVANCEMENT); -- this.saveAdvancement(root); +- this.saveAdvancement(advancementholder); + var ops = registry().createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE); -+ var json = Advancement.CODEC.encodeStart(ops, root.value()).getOrThrow(IllegalStateException::new); -+ this.saveAdvancement(root.id(), json); ++ var json = Advancement.CODEC.encodeStart(ops, advancementholder.value()).getOrThrow(IllegalStateException::new); ++ this.saveAdvancement(advancementholder.id(), json); } private void saveRecipe(final ResourceKey> id, final Recipe recipe) { - tasks.add(DataProvider.saveStable(cache, registries, Recipe.CODEC, recipe, recipePathProvider.json(id.identifier()))); + list.add(DataProvider.saveStable(cache, registries, Recipe.CODEC, recipe, packoutput$pathprovider.json(id.identifier()))); } - private void saveAdvancement(final AdvancementHolder advancementHolder) { + private void saveAdvancement(net.minecraft.resources.Identifier id, com.google.gson.JsonElement advancement) { - tasks.add( + list.add( DataProvider.saveStable( -- cache, registries, Advancement.CODEC, advancementHolder.value(), advancementPathProvider.json(advancementHolder.id()) -+ cache, advancement, advancementPathProvider.json(id) +- cache, registries, Advancement.CODEC, advancementHolder.value(), packoutput$pathprovider1.json(advancementHolder.id()) ++ cache, advancement, packoutput$pathprovider1.json(id) ) ); + } @@ -47,4 +46,4 @@ + return registries; } }; - this.createRecipeProvider(registries, recipeOutput).buildRecipes(); + this.createRecipeProvider(registries, recipeoutput).buildRecipes(); diff --git a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch index a73e9cad16..ceec6566ec 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/registries/RegistriesDatapackGenerator.java +++ b/net/minecraft/data/registries/RegistriesDatapackGenerator.java -@@ -18,10 +_,21 @@ +@@ -20,10 +_,21 @@ public class RegistriesDatapackGenerator implements DataProvider { private final PackOutput output; private final CompletableFuture registries; @@ -22,22 +22,22 @@ } @Override -@@ -31,8 +_,7 @@ +@@ -33,8 +_,7 @@ access -> { - DynamicOps registryOps = access.createSerializationContext(JsonOps.INSTANCE); + DynamicOps dynamicops = access.createSerializationContext(JsonOps.INSTANCE); return CompletableFuture.allOf( - RegistryDataLoader.WORLDGEN_REGISTRIES - .stream() + RegistryDataLoader.getWorldGenAndDimensionStream() - .flatMap(v -> this.dumpRegistryCap(cache, access, registryOps, (RegistryDataLoader.RegistryData)v).stream()) + .flatMap(v -> this.dumpRegistryCap(cache, access, dynamicops, (RegistryDataLoader.RegistryData)v).stream()) .toArray(CompletableFuture[]::new) ); -@@ -50,11 +_,16 @@ - PackOutput.PathProvider pathProvider = this.output.createRegistryElementsPathProvider(registryKey); +@@ -52,11 +_,16 @@ + PackOutput.PathProvider packoutput$pathprovider = this.output.createRegistryElementsPathProvider(resourcekey); return CompletableFuture.allOf( registry.listElements() + .filter(holder -> shouldDump(holder.key())) - .>map(e -> dumpValue(pathProvider.json(e.key().identifier()), cache, writeOps, v.elementCodec(), e.value())) + .>map(e -> dumpValue(packoutput$pathprovider.json(e.key().identifier()), cache, writeOps, v.elementCodec(), e.value())) .toArray(CompletableFuture[]::new) ); } diff --git a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch index 091d98a9ab..9adc5a4240 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/data/registries/RegistryPatchGenerator.java @@ -21,7 +_,7 @@ parent -> { - RegistryAccess.Frozen staticRegistries = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); - Cloner.Factory cloner = new Cloner.Factory(); -- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach(registryData -> registryData.runWithArguments(cloner::addCodec)); -+ RegistryDataLoader.getWorldGenAndDimensionStream().forEach(registryData -> registryData.runWithArguments(cloner::addCodec)); - RegistrySetBuilder.PatchedRegistries newRegistries = packBuilder.buildPatch(staticRegistries, parent, cloner); - HolderLookup.Provider fullPatchedRegistry = newRegistries.full(); - Optional> biomes = fullPatchedRegistry.lookup(Registries.BIOME); + RegistryAccess.Frozen registryaccess$frozen = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); + Cloner.Factory cloner$factory = new Cloner.Factory(); +- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach(registryData -> registryData.runWithArguments(cloner$factory::addCodec)); ++ RegistryDataLoader.getWorldGenAndDimensionStream().forEach(registryData -> registryData.runWithArguments(cloner$factory::addCodec)); + RegistrySetBuilder.PatchedRegistries registrysetbuilder$patchedregistries = packBuilder.buildPatch( + registryaccess$frozen, parent, 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 adf14ed7fa..3aac66dc71 100644 --- a/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/registries/VanillaRegistries.java +++ b/net/minecraft/data/registries/VanillaRegistries.java -@@ -110,6 +_,7 @@ +@@ -108,6 +_,7 @@ .add(Registries.TIMELINE, Timelines::bootstrap) .add(Registries.VILLAGER_TRADE, VillagerTrades::bootstrap) .add(Registries.TRADE_SET, TradeSets::bootstrap); @@ -8,10 +8,10 @@ private static void validateThatAllBiomeFeaturesHaveBiomeFilter(final HolderLookup.Provider provider) { validateThatAllBiomeFeaturesHaveBiomeFilter(provider.lookupOrThrow(Registries.PLACED_FEATURE), provider.lookupOrThrow(Registries.BIOME)); -@@ -141,5 +_,9 @@ - HolderLookup.Provider newRegistries = BUILDER.build(staticRegistries); - validateThatAllBiomeFeaturesHaveBiomeFilter(newRegistries); - return newRegistries; +@@ -139,5 +_,9 @@ + HolderLookup.Provider holderlookup$provider = BUILDER.build(registryaccess$frozen); + validateThatAllBiomeFeaturesHaveBiomeFilter(holderlookup$provider); + return holderlookup$provider; + } + + public static RegistrySetBuilder builder() { diff --git a/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch index 7f57b981e8..6fc2e16a2b 100644 --- a/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/BannerPatternTagsProvider.java.patch @@ -3,7 +3,7 @@ @@ -9,8 +_,14 @@ import net.minecraft.world.level.block.entity.BannerPatterns; - public class BannerPatternTagsProvider extends TagsProvider { + public class BannerPatternTagsProvider extends KeyTagProvider { + /** @deprecated Forge: Use the {@linkplain #BannerPatternTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ + @Deprecated public BannerPatternTagsProvider(final PackOutput output, final CompletableFuture lookupProvider) { diff --git a/patches/minecraft/net/minecraft/data/tags/BlockItemTagAppender.java.patch b/patches/minecraft/net/minecraft/data/tags/BlockItemTagAppender.java.patch deleted file mode 100644 index 46728d91f1..0000000000 --- a/patches/minecraft/net/minecraft/data/tags/BlockItemTagAppender.java.patch +++ /dev/null @@ -1,31 +0,0 @@ ---- a/net/minecraft/data/tags/BlockItemTagAppender.java -+++ b/net/minecraft/data/tags/BlockItemTagAppender.java -@@ -56,4 +_,28 @@ - this.original.addOptionalTag(tag); - return this; - } -+ -+ @Override -+ public TagAppender addOptional(net.minecraft.resources.Identifier location) { -+ this.original.addOptional(location); -+ return this; -+ } -+ -+ @Override -+ public TagAppender replace(boolean value) { -+ this.original.replace(value); -+ return this; -+ } -+ -+ @Override -+ public TagAppender remove(final net.minecraft.resources.Identifier location) { -+ this.original.remove(location); -+ return this; -+ } -+ -+ @Override -+ public TagAppender remove(TagKey tag) { -+ this.original.remove(tag); -+ return this; -+ } - } diff --git a/patches/minecraft/net/minecraft/data/tags/BlockItemTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/BlockItemTagsProvider.java.patch deleted file mode 100644 index 3f4b6a64db..0000000000 --- a/patches/minecraft/net/minecraft/data/tags/BlockItemTagsProvider.java.patch +++ /dev/null @@ -1,15 +0,0 @@ ---- a/net/minecraft/data/tags/BlockItemTagsProvider.java -+++ b/net/minecraft/data/tags/BlockItemTagsProvider.java -@@ -64,6 +_,12 @@ - return this; - } - -+ default BlockItemTagsProvider.CombinedAppender add(final BlockItemTagId... ids) { -+ for (var id : ids) -+ addTag(id); -+ return this; -+ } -+ - default BlockItemTagsProvider.CombinedAppender addAll(final Collection ids) { - this.addAll(ids.stream()); - return this; diff --git a/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch index 5159b1e7c2..61dfb52c0e 100644 --- a/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/EntityTypeTagsProvider.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/data/tags/EntityTypeTagsProvider.java +++ b/net/minecraft/data/tags/EntityTypeTagsProvider.java -@@ -13,6 +_,10 @@ - super(output, Registries.ENTITY_TYPE, lookupProvider); +@@ -12,6 +_,10 @@ + super(output, Registries.ENTITY_TYPE, lookupProvider, e -> e.builtInRegistryHolder().key()); } + public EntityTypeTagsProvider(final PackOutput output, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(output, Registries.ENTITY_TYPE, lookupProvider, modId, existingFileHelper); ++ super(output, Registries.ENTITY_TYPE, lookupProvider, e -> e.builtInRegistryHolder().key(), modId, existingFileHelper); + } + @Override diff --git a/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch index 28fd0f8030..565f54b821 100644 --- a/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/FluidTagsProvider.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/data/tags/FluidTagsProvider.java +++ b/net/minecraft/data/tags/FluidTagsProvider.java @@ -13,6 +_,10 @@ - super(output, Registries.FLUID, lookupProvider); + super(output, Registries.FLUID, lookupProvider, e -> e.builtInRegistryHolder().key()); } + public FluidTagsProvider(final PackOutput output, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(output, Registries.FLUID, lookupProvider, modId, existingFileHelper); ++ super(output, Registries.FLUID, lookupProvider, e -> e.builtInRegistryHolder().key(), modId, existingFileHelper); + } + @Override protected void addTags(final HolderLookup.Provider registries) { - this.tag(FluidTags.WATER).add(FluidIds.WATER, FluidIds.FLOWING_WATER); + 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 dbd35d4100..9c4d02eee9 100644 --- a/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/GameEventTagsProvider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/tags/GameEventTagsProvider.java +++ b/net/minecraft/data/tags/GameEventTagsProvider.java -@@ -60,6 +_,10 @@ +@@ -59,6 +_,10 @@ super(output, Registries.GAME_EVENT, lookupProvider); } diff --git a/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch new file mode 100644 index 0000000000..a3082f668a --- /dev/null +++ b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch @@ -0,0 +1,44 @@ +--- a/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java ++++ b/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java +@@ -26,6 +_,18 @@ + final PackOutput output, + final ResourceKey> registryKey, + final CompletableFuture lookupProvider, ++ final Function> keyExtractor, ++ final String modid, ++ final @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper ++ ) { ++ super(output, registryKey, lookupProvider, modid, existingFileHelper); ++ this.keyExtractor = keyExtractor; ++ } ++ ++ public IntrinsicHolderTagsProvider( ++ final PackOutput output, ++ final ResourceKey> registryKey, ++ final CompletableFuture lookupProvider, + final CompletableFuture> parentProvider, + final Function> keyExtractor + ) { +@@ -33,8 +_,21 @@ + this.keyExtractor = keyExtractor; + } + ++ public IntrinsicHolderTagsProvider( ++ final PackOutput output, ++ final ResourceKey> registryKey, ++ final CompletableFuture lookupProvider, ++ final CompletableFuture> parentProvider, ++ final Function> keyExtractor, ++ final String modid, ++ final @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper ++ ) { ++ super(output, registryKey, lookupProvider, parentProvider, modid, existingFileHelper); ++ this.keyExtractor = keyExtractor; ++ } ++ + protected TagAppender tag(final TagKey tag) { + TagBuilder tagbuilder = this.getOrCreateRawBuilder(tag); +- return TagAppender.forBuilder(tagbuilder).map(this.keyExtractor); ++ return TagAppender.forBuilder(tagbuilder, this.modId).map(this.keyExtractor); + } + } diff --git a/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch new file mode 100644 index 0000000000..37dd14b965 --- /dev/null +++ b/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch @@ -0,0 +1,17 @@ +--- a/net/minecraft/data/tags/KeyTagProvider.java ++++ b/net/minecraft/data/tags/KeyTagProvider.java +@@ -20,9 +_,13 @@ + return TagAppender.forBuilder(tagbuilder); + } + ++ protected KeyTagProvider(final PackOutput output, final ResourceKey> registryKey, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { ++ super(output, registryKey, lookupProvider, modId, existingFileHelper); ++ } ++ + protected TagAppender, T> tag(final TagKey tag, final boolean replace) { + TagBuilder tagbuilder = this.getOrCreateRawBuilder(tag); + tagbuilder.setReplace(replace); +- return TagAppender.forBuilder(tagbuilder); ++ return TagAppender.forBuilder(tagbuilder, this.modId); + } + } diff --git a/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch index f7a73aa2b4..d1801fec15 100644 --- a/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/PaintingVariantTagsProvider.java.patch @@ -3,7 +3,7 @@ @@ -9,8 +_,13 @@ import net.minecraft.world.entity.decoration.painting.PaintingVariants; - public class PaintingVariantTagsProvider extends TagsProvider { + public class PaintingVariantTagsProvider extends KeyTagProvider { + /** @deprecated Forge: Use the {@linkplain #PaintingVariantTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ public PaintingVariantTagsProvider(final PackOutput output, final CompletableFuture lookupProvider) { super(output, Registries.PAINTING_VARIANT, lookupProvider); diff --git a/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch index 3549bd0cd1..e9fa6dd1be 100644 --- a/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/PoiTypeTagsProvider.java.patch @@ -3,7 +3,7 @@ @@ -9,8 +_,13 @@ import net.minecraft.world.entity.ai.village.poi.PoiTypes; - public class PoiTypeTagsProvider extends TagsProvider { + public class PoiTypeTagsProvider extends KeyTagProvider { + /** @deprecated Forge: Use the {@linkplain #PoiTypeTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ public PoiTypeTagsProvider(final PackOutput output, final CompletableFuture lookupProvider) { super(output, Registries.POINT_OF_INTEREST_TYPE, lookupProvider); diff --git a/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch index e2f5697e5e..60cfd57a4d 100644 --- a/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/StructureTagsProvider.java.patch @@ -3,7 +3,7 @@ @@ -9,8 +_,13 @@ import net.minecraft.world.level.levelgen.structure.Structure; - public class StructureTagsProvider extends TagsProvider { + public class StructureTagsProvider extends KeyTagProvider { + /** @deprecated Forge: Use the {@linkplain #StructureTagsProvider(PackOutput, CompletableFuture, String, net.minecraftforge.common.data.ExistingFileHelper) mod id variant} */ public StructureTagsProvider(final PackOutput output, final CompletableFuture lookupProvider) { super(output, Registries.STRUCTURE, lookupProvider); diff --git a/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch b/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch index f30cfc6529..d1714f2feb 100644 --- a/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch @@ -1,30 +1,29 @@ --- a/net/minecraft/data/tags/TagAppender.java +++ b/net/minecraft/data/tags/TagAppender.java -@@ -7,7 +_,7 @@ +@@ -9,7 +_,7 @@ import net.minecraft.tags.TagBuilder; import net.minecraft.tags.TagKey; --public interface TagAppender { -+public interface TagAppender extends net.minecraftforge.common.extensions.IForgeTagAppender { - TagAppender add(ResourceKey element); +-public interface TagAppender { ++public interface TagAppender extends net.minecraftforge.common.extensions.IForgeTagAppender { + TagAppender add(E element); - default TagAppender add(final ResourceKey... elements) { -@@ -31,6 +_,10 @@ - TagAppender addOptionalTag(TagKey tag); + default TagAppender add(final E... elements) { +@@ -33,6 +_,10 @@ + TagAppender addOptionalTag(TagKey tag); - static TagAppender forBuilder(final TagBuilder builder) { + static TagAppender, T> forBuilder(final TagBuilder builder) { + return forBuilder(builder, "unknown"); + } + -+ static TagAppender forBuilder(final TagBuilder builder, String source) { - return new TagAppender() { - @Override - public TagAppender add(final ResourceKey element) { -@@ -54,6 +_,16 @@ - public TagAppender addOptionalTag(final TagKey tag) { ++ static TagAppender, T> forBuilder(final TagBuilder builder, String source) { + return new TagAppender, T>() { + public TagAppender, T> add(final ResourceKey element) { + builder.addElement(element.identifier()); +@@ -55,6 +_,21 @@ builder.addOptionalTag(tag.location()); return this; -+ } + } + + @Override + public TagBuilder getInternalBuilder() { @@ -34,6 +33,35 @@ + @Override + public String getSourceName() { + return source; - } ++ } ++ ++ @Override ++ public TagAppender, T> remove(ResourceKey value) { ++ return this.remove(value.identifier()); ++ } }; } + +@@ -86,6 +_,22 @@ + @Override + public TagAppender addOptionalTag(final TagKey tag) { + tagappender.addOptionalTag(tag); ++ return this; ++ } ++ ++ @Override ++ public TagBuilder getInternalBuilder() { ++ return tagappender.getInternalBuilder(); ++ } ++ ++ @Override ++ public String getSourceName() { ++ return tagappender.getSourceName(); ++ } ++ ++ @Override ++ public TagAppender remove(U value) { ++ tagappender.remove(converter.apply(value)); + return this; + } + }; diff --git a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch index 61dd38debc..c98380cbd9 100644 --- a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/tags/TagsProvider.java +++ b/net/minecraft/data/tags/TagsProvider.java -@@ -31,28 +_,53 @@ +@@ -32,28 +_,53 @@ private final CompletableFuture> parentProvider; protected final ResourceKey> registryKey; protected final Map builders = Maps.newLinkedHashMap(); @@ -57,45 +57,45 @@ } protected abstract void addTags(HolderLookup.Provider registries); -@@ -70,7 +_,13 @@ +@@ -71,7 +_,13 @@ .thenCombineAsync(this.parentProvider, (x$0, x$1) -> new CombinedData<>(x$0, (TagsProvider.TagLookup)x$1), Util.backgroundExecutor()) .thenCompose( c -> { -- HolderLookup.RegistryLookup lookup = c.contents.lookupOrThrow(this.registryKey); -+ HolderLookup.RegistryLookup lookup = c.contents.lookup(this.registryKey).orElseThrow(() -> { +- HolderLookup.RegistryLookup registrylookup = c.contents.lookupOrThrow(this.registryKey); ++ HolderLookup.RegistryLookup registrylookup = c.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.identifier() + " does not have support for tags"); + } + return new IllegalStateException("Registry " + this.registryKey.identifier() + " not found"); + }); - Predicate elementCheck = id -> lookup.get(ResourceKey.create(this.registryKey, id)).isPresent(); - Predicate tagCheck = id -> this.builders.containsKey(id) || c.parent.contains(TagKey.create(this.registryKey, id)); + Predicate predicate = id -> registrylookup.get(ResourceKey.create(this.registryKey, id)).isPresent(); + Predicate predicate1 = id -> this.builders.containsKey(id) || c.parent.contains(TagKey.create(this.registryKey, id)); return CompletableFuture.allOf( -@@ -82,7 +_,7 @@ - Identifier id = entry.getKey(); - TagBuilder builder = entry.getValue(); - List entries = builder.build(); -- List unresolvedEntries = entries.stream().filter(e -> !e.verifyIfPresent(elementCheck, tagCheck)).toList(); -+ List unresolvedEntries = java.util.stream.Stream.concat(entries.stream(), builder.getRemoveEntries()).filter(e -> !e.verifyIfPresent(elementCheck, tagCheck)).filter(this::missing).toList(); - if (!unresolvedEntries.isEmpty()) { +@@ -83,7 +_,7 @@ + Identifier identifier = entry.getKey(); + TagBuilder tagbuilder = entry.getValue(); + List list = tagbuilder.build(); +- List list1 = list.stream().filter(e -> !e.verifyIfPresent(predicate, predicate1)).toList(); ++ List list1 = java.util.stream.Stream.concat(list.stream(), tagbuilder.getRemoveEntries()).filter(e -> !e.verifyIfPresent(predicate, predicate1)).filter(this::missing).toList(); + if (!list1.isEmpty()) { throw new IllegalArgumentException( String.format( @@ -94,8 +_,11 @@ + ) ); + } else { +- Path path = this.pathProvider.json(identifier); +- return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(list, tagbuilder.shouldReplace()), path); ++ Path path = this.getPath(identifier); ++ if (path == null) { ++ return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags. ++ } ++ return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(list, tagbuilder.shouldReplace(), tagbuilder.getRemoveEntries().toList()), path); } - -- Path path = this.pathProvider.json(id); -- return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(entries, builder.shouldReplace()), path); -+ Path path = this.getPath(id); -+ if (path == null) { -+ return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags. -+ } -+ return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(entries, builder.shouldReplace(), builder.getRemoveEntries().toList()), path); } ) - .toArray(CompletableFuture[]::new) -@@ -105,7 +_,12 @@ +@@ -106,7 +_,12 @@ } protected TagBuilder getOrCreateRawBuilder(final TagKey tag) { @@ -109,10 +109,12 @@ } public CompletableFuture> contentsGetter() { -@@ -120,15 +_,24 @@ +@@ -119,6 +_,15 @@ + this.addTags(registries); + return (HolderLookup.Provider)registries; }); - } - ++ } ++ + + private boolean missing(TagEntry reference) { + // Optional tags should not be validated @@ -120,19 +122,6 @@ + return existingFileHelper == null || !existingFileHelper.exists(reference.getId(), reference.isTag() ? resourceType : elementResourceType); + } + return false; -+ } -+ - protected TagAppender tag(final TagKey tag) { - TagBuilder builder = this.getOrCreateRawBuilder(tag); -- return TagAppender.forBuilder(builder); -+ return TagAppender.forBuilder(builder, this.modId); - } - - protected TagAppender tag(final TagKey tag, final boolean replace) { - TagBuilder builder = this.getOrCreateRawBuilder(tag); - builder.setReplace(replace); -- return TagAppender.forBuilder(builder); -+ return TagAppender.forBuilder(builder, this.modId); } @FunctionalInterface diff --git a/patches/minecraft/net/minecraft/data/tags/VanillaBlockTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/VanillaBlockTagsProvider.java.patch index 4e69799faf..b1f6fb2758 100644 --- a/patches/minecraft/net/minecraft/data/tags/VanillaBlockTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/VanillaBlockTagsProvider.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/data/tags/VanillaBlockTagsProvider.java +++ b/net/minecraft/data/tags/VanillaBlockTagsProvider.java -@@ -29,6 +_,10 @@ - }; +@@ -17,6 +_,10 @@ + super(output, Registries.BLOCK, lookupProvider, e -> e.builtInRegistryHolder().key()); } + public VanillaBlockTagsProvider(final PackOutput output, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(output, Registries.BLOCK, lookupProvider, modId, existingFileHelper); ++ super(output, Registries.BLOCK, lookupProvider, e -> e.builtInRegistryHolder().key(), modId, existingFileHelper); + } + @Override protected void addTags(final HolderLookup.Provider registries) { - new VanillaBlockItemTagsProvider(tagId -> BlockItemTagsProvider.wrapForBlocks(this.tag(tagId.block()))).run(); + (new BlockItemTagsProvider() { diff --git a/patches/minecraft/net/minecraft/data/tags/VanillaItemTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/VanillaItemTagsProvider.java.patch index cb163841a1..b85e778d9c 100644 --- a/patches/minecraft/net/minecraft/data/tags/VanillaItemTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/VanillaItemTagsProvider.java.patch @@ -1,13 +1,26 @@ --- a/net/minecraft/data/tags/VanillaItemTagsProvider.java +++ b/net/minecraft/data/tags/VanillaItemTagsProvider.java -@@ -28,6 +_,10 @@ - }; +@@ -16,6 +_,10 @@ + super(output, Registries.ITEM, lookupProvider, e -> e.builtInRegistryHolder().key()); } + public VanillaItemTagsProvider(final PackOutput output, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { -+ super(output, Registries.ITEM, lookupProvider, modId, existingFileHelper); ++ super(output, Registries.ITEM, lookupProvider, e -> e.builtInRegistryHolder().key(), modId, existingFileHelper); + } + @Override protected void addTags(final HolderLookup.Provider registries) { - new VanillaBlockItemTagsProvider(tagId -> BlockItemTagsProvider.wrapForItems(this.tag(tagId.item()))).run(); + (new BlockItemTagsProvider() { +@@ -578,6 +_,12 @@ + @Override + public TagAppender addOptionalTag(final TagKey tag) { + this.itemAppender.addOptionalTag(blockTagToItemTag(tag)); ++ return this; ++ } ++ ++ @Override ++ public TagAppender remove(final Block value) { ++ this.itemAppender.remove(Objects.requireNonNull(value.asItem())); + return this; + } + } diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch index a77a2f311d..ddb4454f87 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/gametest/framework/GameTestHelper.java +++ b/net/minecraft/gametest/framework/GameTestHelper.java -@@ -77,7 +_,7 @@ +@@ -76,7 +_,7 @@ import net.minecraft.world.phys.Vec3; import org.jspecify.annotations.Nullable; @@ -9,7 +9,7 @@ private final GameTestInfo testInfo; private boolean finalCheckAdded; -@@ -1109,6 +_,12 @@ +@@ -1076,6 +_,12 @@ return this.testInfo.getTick(); } @@ -22,8 +22,8 @@ public AABB getBounds() { return this.testInfo.getStructureBounds(); } -@@ -1153,6 +_,26 @@ - if (result.right().isPresent()) { +@@ -1122,6 +_,26 @@ + if (either.right().isPresent()) { throw this.assertionException("test.error.set_biome"); } + } diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch index e8a168dfc6..53c1b805be 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch @@ -5,6 +5,6 @@ Bootstrap.bootStrap(); Util.startTimerHackThread(); + net.minecraftforge.server.loading.ServerModLoader.load(); - String universePath = options.valueOf(universe); - createOrResetDir(universePath); - onUniverseCreated.accept(universePath); + String s = optionset.valueOf(universe); + createOrResetDir(s); + onUniverseCreated.accept(s); diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch index 76fcf278cc..d4f0561e18 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/gametest/framework/GameTestServer.java +++ b/net/minecraft/gametest/framework/GameTestServer.java -@@ -101,7 +_,7 @@ +@@ -102,7 +_,7 @@ final int repeatCount ) { packRepository.reload(); -- ArrayList enabledPacks = new ArrayList<>(packRepository.getAvailableIds()); -+ ArrayList enabledPacks = new ArrayList<>(packRepository.getSelectedIds()); // Forge: Use the selected datapacks as this takes sorting into account. - enabledPacks.remove("vanilla"); - enabledPacks.addFirst("vanilla"); - WorldDataConfiguration defaultTestConfig = new WorldDataConfiguration(new DataPackConfig(enabledPacks, List.of()), ENABLED_FEATURES); -@@ -174,6 +_,7 @@ +- ArrayList arraylist = new ArrayList<>(packRepository.getAvailableIds()); ++ ArrayList arraylist = new ArrayList<>(packRepository.getSelectedIds()); // Forge: Use the selected datapacks as this takes sorting into account. + arraylist.remove("vanilla"); + arraylist.addFirst("vanilla"); + WorldDataConfiguration worlddataconfiguration = new WorldDataConfiguration(new DataPackConfig(arraylist, List.of()), ENABLED_FEATURES); +@@ -178,6 +_,7 @@ @Override protected boolean initServer() { + if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; - this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {}); - Gizmos.withCollector(GizmoCollector.NOOP); - this.loadLevel(); + this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) { + { + Objects.requireNonNull(GameTestServer.this); diff --git a/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch b/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch index 5dae5ebe99..34211c42ae 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/gametest/framework/TestCommand.java +++ b/net/minecraft/gametest/framework/TestCommand.java -@@ -481,7 +_,12 @@ +@@ -477,7 +_,12 @@ return Optional.empty(); } else { - Holder.Reference test = maybeTest.get(); -- GameTestInfo testInfo = new GameTestInfo(test, blockEntity.getRotation(), level, retryOptions); + Holder.Reference reference = optional.get(); +- GameTestInfo gametestinfo = new GameTestInfo(reference, testinstanceblockentity.getRotation(), serverlevel, retryOptions); + // Forge: The rotation is stored in the structure block, and added in the GameTestInfo constructor. + // So reverse it to find the manually specified rotation so the test runs the same every time. -+ var rotation = blockEntity.test().flatMap(blockEntity.getLevel().registryAccess()::get).map(Holder::value).map(GameTestInstance::rotation).orElse(Rotation.NONE); -+ var steps = StructureUtils.getRotationStepsForRotation(blockEntity.getRotation()) - StructureUtils.getRotationStepsForRotation(rotation); ++ var rotation = testinstanceblockentity.test().flatMap(testinstanceblockentity.getLevel().registryAccess()::get).map(Holder::value).map(GameTestInstance::rotation).orElse(Rotation.NONE); ++ var steps = StructureUtils.getRotationStepsForRotation(testinstanceblockentity.getRotation()) - StructureUtils.getRotationStepsForRotation(rotation); + if (steps < 0) steps += 4; -+ GameTestInfo testInfo = new GameTestInfo(test, StructureUtils.getRotationForRotationSteps(steps), level, retryOptions); - testInfo.setTestBlockPos(testBlockPos); - return !verifyStructureExists(source, testInfo.getStructure()) ? Optional.empty() : Optional.of(testInfo); ++ GameTestInfo gametestinfo = new GameTestInfo(reference, StructureUtils.getRotationForRotationSteps(steps), serverlevel, retryOptions); + gametestinfo.setTestBlockPos(testBlockPos); + return !verifyStructureExists(source, gametestinfo.getStructure()) ? Optional.empty() : Optional.of(gametestinfo); } diff --git a/patches/minecraft/net/minecraft/locale/Language.java.patch b/patches/minecraft/net/minecraft/locale/Language.java.patch index ed7306a5e9..38f6e9c842 100644 --- a/patches/minecraft/net/minecraft/locale/Language.java.patch +++ b/patches/minecraft/net/minecraft/locale/Language.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/locale/Language.java +++ b/net/minecraft/locale/Language.java @@ -38,7 +_,8 @@ - BiConsumer output = loadedData::put; - parseTranslations(output, "/assets/minecraft/lang/en_us.json"); - deprecatedInfo.applyToMap(loadedData); -- final Map storage = Map.copyOf(loadedData); -+ net.minecraftforge.server.LanguageHook.captureLanguageMap(loadedData); -+ final Map storage = loadedData; + BiConsumer biconsumer = map::put; + parseTranslations(biconsumer, "/assets/minecraft/lang/en_us.json"); + deprecatedtranslationsinfo.applyToMap(map); +- final Map map1 = Map.copyOf(map); ++ net.minecraftforge.server.LanguageHook.captureLanguageMap(map); ++ final Map map1 = map; return new Language() { @Override public String getOrDefault(final String elementId, final String defaultValue) { @@ -17,16 +17,14 @@ + + @Override + public Map getLanguageData() { -+ return loadedData; ++ return map; + } }; } -@@ -89,7 +_,10 @@ - +@@ -90,6 +_,8 @@ public static void inject(final Language language) { instance = language; -+ net.minecraftforge.common.ForgeI18n.loadLanguageData(language.getLanguageData()); } + + public Map getLanguageData() { return Map.of(); } diff --git a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch index ee3ca5ffca..4dbbc31641 100644 --- a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch +++ b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch @@ -9,16 +9,16 @@ private final byte[] encodeBuf = new byte[8192]; private final Deflater deflater; private int threshold; -@@ -25,6 +_,12 @@ - VarInt.write(out, 0); - out.writeBytes(uncompressed); - } else { -+ if (!DISABLE_PACKET_DEBUG && uncompressedLength > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { -+ uncompressed.markReaderIndex(); -+ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", uncompressedLength, net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH, -+ net.minecraftforge.common.util.HexDumper.dump(uncompressed)); -+ uncompressed.resetReaderIndex(); -+ } - byte[] input = new byte[uncompressedLength]; - uncompressed.readBytes(input); - VarInt.write(out, input.length); +@@ -24,6 +_,12 @@ + VarInt.write(out, 0); + out.writeBytes(uncompressed); + } else { ++ if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { ++ uncompressed.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(uncompressed)); ++ uncompressed.resetReaderIndex(); ++ } + byte[] abyte = new byte[i]; + uncompressed.readBytes(abyte); + VarInt.write(out, abyte.length); diff --git a/patches/minecraft/net/minecraft/network/Connection.java.patch b/patches/minecraft/net/minecraft/network/Connection.java.patch index 2567ce0d12..e48de671dc 100644 --- a/patches/minecraft/net/minecraft/network/Connection.java.patch +++ b/patches/minecraft/net/minecraft/network/Connection.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/network/Connection.java +++ b/net/minecraft/network/Connection.java @@ -81,9 +_,17 @@ + private boolean handlingFault; private volatile @Nullable DisconnectionDetails delayedDisconnect; private @Nullable BandwidthDebugMonitor bandwidthDebugMonitor; - private @Nullable UUID intendedProfileId; + private java.util.function.Consumer activationHandler; + private final net.minecraftforge.common.util.PacketLogger packetLogger = new net.minecraftforge.common.util.PacketLogger(this); + private ProtocolInfo outboundProtocol = null; @@ -26,46 +26,46 @@ if (this.delayedDisconnect != null) { this.disconnect(this.delayedDisconnect); } -@@ -152,6 +_,7 @@ - - if (packetListener.shouldHandleMessage(packet)) { - try { -+ packetLogger.recv(packet); - genericsFtw(packet, packetListener); - } catch (RunningOnDifferentThreadException var5) { - } catch (RejectedExecutionException ignored) { -@@ -201,6 +_,7 @@ +@@ -151,6 +_,7 @@ + } else { + if (packetlistener.shouldHandleMessage(packet)) { + try { ++ packetLogger.recv(packet); + genericsFtw(packet, packetlistener); + } catch (RunningOnDifferentThreadException runningondifferentthreadexception) { + } catch (RejectedExecutionException rejectedexecutionexception) { +@@ -200,6 +_,7 @@ + if (protocol.flow() != this.getReceiving()) { throw new IllegalStateException("Invalid inbound protocol: " + protocol.id()); + } else { ++ this.inboundProtocol = protocol; + this.packetListener = packetListener; + this.disconnectListener = null; + UnconfiguredPipelineHandler.InboundConfigurationTask unconfiguredpipelinehandler$inboundconfigurationtask = UnconfiguredPipelineHandler.setupInboundProtocol( +@@ -223,6 +_,8 @@ + } else { + UnconfiguredPipelineHandler.OutboundConfigurationTask unconfiguredpipelinehandler$outboundconfigurationtask = UnconfiguredPipelineHandler.setupOutboundProtocol( + protocol ++ ).andThen( ++ f -> this.outboundProtocol = protocol + ); + BundlerInfo bundlerinfo = protocol.bundlerInfo(); + if (bundlerinfo != null) { +@@ -274,7 +_,8 @@ + this.disconnectListener = listener; + this.runOnceConnected(connection -> { + this.setupInboundProtocol(inbound, listener); +- connection.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().protocolVersion(), hostName, port, intent), null, true); ++ // TODO: Change this to be a immediately sent login custom payload packet? ++ connection.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().protocolVersion(), net.minecraftforge.network.NetworkContext.enhanceHostName(hostName), port, intent), null, true); + this.setupOutboundProtocol(outbound); + }); } - -+ this.inboundProtocol = protocol; - this.packetListener = packetListener; - this.disconnectListener = null; - UnconfiguredPipelineHandler.InboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupInboundProtocol(protocol); -@@ -218,7 +_,7 @@ - throw new IllegalStateException("Invalid outbound protocol: " + protocol.id()); - } - -- UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol); -+ UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol).andThen(_ -> this.outboundProtocol = protocol); - BundlerInfo bundlerInfo = protocol.bundlerInfo(); - if (bundlerInfo != null) { - PacketBundleUnpacker newUnbundler = new PacketBundleUnpacker(bundlerInfo); -@@ -265,7 +_,8 @@ - this.disconnectListener = listener; - this.runOnceConnected(connection -> { - this.setupInboundProtocol(inbound, listener); -- connection.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().protocolVersion(), hostName, port, intent), null, true); -+ // TODO: Change this to be a immediately sent login custom payload packet? -+ connection.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().protocolVersion(), net.minecraftforge.network.NetworkContext.enhanceHostName(hostName), port, intent), null, true); - this.setupOutboundProtocol(outbound); - }); - } -@@ -309,10 +_,13 @@ +@@ -319,10 +_,13 @@ if (listener != null) { - ChannelFuture future = flush ? this.channel.writeAndFlush(packet) : this.channel.write(packet); - future.addListener(listener); -+ future.addListener(f -> packetLogger.send(packet)); + ChannelFuture channelfuture = flush ? this.channel.writeAndFlush(packet) : this.channel.write(packet); + channelfuture.addListener(listener); ++ channelfuture.addListener(f -> packetLogger.send(packet)); } else if (flush) { this.channel.writeAndFlush(packet, this.channel.voidPromise()); + packetLogger.send(packet); @@ -75,7 +75,7 @@ } } -@@ -381,7 +_,7 @@ +@@ -391,7 +_,7 @@ if (this.address == null) { return "local"; } else { @@ -84,7 +84,7 @@ } } -@@ -426,7 +_,9 @@ +@@ -436,7 +_,9 @@ } public static ChannelFuture connect(final InetSocketAddress address, final EventLoopGroupHolder eventLoopGroupHolder, final Connection connection) { @@ -95,7 +95,7 @@ @Override protected void initChannel(final Channel channel) { try { -@@ -491,7 +_,8 @@ +@@ -503,7 +_,8 @@ public static Connection connectToLocalServer(final SocketAddress address) { final Connection connection = new Connection(PacketFlow.CLIENTBOUND); @@ -104,8 +104,8 @@ + new Bootstrap().group(EventLoopGroupHolder.local().eventLoopGroup(true)).handler(new ChannelInitializer() { @Override protected void initChannel(final Channel channel) { - ChannelPipeline pipeline = channel.pipeline(); -@@ -590,6 +_,22 @@ + ChannelPipeline channelpipeline = channel.pipeline(); +@@ -594,6 +_,22 @@ public float getAverageSentPackets() { return this.averageSentPackets; 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 8b24670454..d208f6ce37 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 -@@ -135,6 +_,11 @@ - current = end; +@@ -136,6 +_,11 @@ + j = l; } -+ if (current == 0) { ++ if (j == 0) { + // Forge has some special formatting handlers defined in ForgeI18n, use those if no %s replacements present. -+ current = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, decomposedParts, this.args, template); ++ j = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, decomposedParts, this.args, template); + } + - if (current < template.length()) { - String tail = template.substring(current); - if (tail.indexOf(37) != -1) { + if (j < template.length()) { + String s3 = template.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 25d2a2403d..6d4ce39733 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java -@@ -15,12 +_,12 @@ +@@ -17,12 +_,12 @@ public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { private static final int MAX_PAYLOAD_SIZE = 1048576; public static final StreamCodec GAMEPLAY_STREAM_CODEC = CustomPacketPayload.codec( 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 2fe3bc9c45..0ff99ea96d 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java -@@ -13,7 +_,7 @@ +@@ -15,7 +_,7 @@ public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { private static final int MAX_PAYLOAD_SIZE = 32767; public static final StreamCodec STREAM_CODEC = CustomPacketPayload.codec( 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 2188327f6b..0d250cc8f1 100644 --- a/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/status/ServerStatus.java +++ b/net/minecraft/network/protocol/status/ServerStatus.java -@@ -19,7 +_,8 @@ +@@ -20,7 +_,8 @@ Optional players, Optional version, Optional favicon, @@ -10,7 +10,7 @@ ) { public static final Codec CODEC = RecordCodecBuilder.create( i -> i.group( -@@ -27,7 +_,8 @@ +@@ -28,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), diff --git a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch index 92651f5bda..cd32bbfe62 100644 --- a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch +++ b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch @@ -7,12 +7,12 @@ - if (LOGGER.isDebugEnabled()) { + if (true) { // Forge: This is very useful for mods that register keys on classes that are not their own try { - Class aClass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); - if (!aClass.equals(clazz)) { -- LOGGER.debug("defineId called for: {} from {}", clazz, aClass, new RuntimeException()); + Class oclass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); + if (!oclass.equals(clazz)) { +- LOGGER.debug("defineId called for: {} from {}", clazz, 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 {}", clazz, aClass, new RuntimeException()); -+ else LOGGER.warn("defineId called for: {} from {}", clazz, aClass); ++ if (LOGGER.isDebugEnabled()) LOGGER.warn("defineId called for: {} from {}", clazz, oclass, new RuntimeException()); ++ else LOGGER.warn("defineId called for: {} from {}", clazz, oclass); } - } catch (ClassNotFoundException var3) { + } catch (ClassNotFoundException classnotfoundexception) { } diff --git a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch index 6ddfba8610..23003264b6 100644 --- a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch +++ b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch @@ -8,7 +8,7 @@ + private final Codec, Either, List>>>> combinedCodec; private static Codec>> homogenousList(final Codec> elementCodec, final boolean alwaysUseList) { - Codec>> listCodec = elementCodec.listOf().validate(ExtraCodecs.ensureHomogenous(Holder::kind)); + Codec>> codec = elementCodec.listOf().validate(ExtraCodecs.ensureHomogenous(Holder::kind)); @@ -38,6 +_,10 @@ this.elementCodec = elementCodec; this.homogenousListCodec = homogenousList(elementCodec, alwaysUseList); @@ -21,23 +21,23 @@ @Override @@ -46,14 +_,17 @@ - Optional> registryOptional = registryOps.getter(this.registryKey); - if (registryOptional.isPresent()) { - HolderGetter registry = registryOptional.get(); + Optional> optional = registryops.getter(this.registryKey); + if (optional.isPresent()) { + HolderGetter holdergetter = optional.get(); - return this.registryAwareCodec + return this.combinedCodec .decode(ops, input) .flatMap( p -> { - DataResult> result = p.getFirst() + DataResult> dataresult = p.getFirst() + .map(custom -> DataResult.success(custom), + tagOrList -> tagOrList .map( - tag -> lookupTag(registry, (TagKey)tag), + tag -> lookupTag(holdergetter, (TagKey)tag), values -> DataResult.success(HolderSet.direct((List>)values)) + ) ); - return result.map(holders -> Pair.of((HolderSet)holders, (T)p.getSecond())); + return dataresult.map(holders -> Pair.of((HolderSet)holders, (T)p.getSecond())); } @@ -86,7 +_,7 @@ } @@ -45,7 +45,7 @@ private DataResult, T>> decodeWithoutRegistry(final DynamicOps ops, final T input) { - return this.elementCodec.listOf().decode(ops, input).flatMap(p -> { + return this.homogenousListCodec.decode(ops, input).flatMap(p -> { // Forge: Match encodeWithoutRegistry's use of the homogenousListCodec - List> directHolders = new ArrayList<>(); + List> list = new ArrayList<>(); for (Holder holder : p.getFirst()) { @@ -102,6 +_,9 @@ diff --git a/patches/minecraft/net/minecraft/resources/Identifier.java.patch b/patches/minecraft/net/minecraft/resources/Identifier.java.patch index 302c39ded6..870fa93d0b 100644 --- a/patches/minecraft/net/minecraft/resources/Identifier.java.patch +++ b/patches/minecraft/net/minecraft/resources/Identifier.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/resources/Identifier.java +++ b/net/minecraft/resources/Identifier.java -@@ -274,4 +_,10 @@ +@@ -266,4 +_,10 @@ return path; } } diff --git a/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch b/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch index d76a89a96c..d53de572f7 100644 --- a/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch +++ b/patches/minecraft/net/minecraft/resources/RegistryDataLoader.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/resources/RegistryDataLoader.java +++ b/net/minecraft/resources/RegistryDataLoader.java -@@ -81,7 +_,7 @@ +@@ -80,7 +_,7 @@ public class RegistryDataLoader { private static final Logger LOGGER = LogUtils.getLogger(); private static final Comparator> ERROR_KEY_COMPARATOR = Comparator., Identifier>comparing(ResourceKey::registry).thenComparing(ResourceKey::identifier); @@ -9,7 +9,7 @@ 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), -@@ -132,7 +_,7 @@ +@@ -130,7 +_,7 @@ public static final List> DIMENSION_REGISTRIES = List.of( new RegistryDataLoader.RegistryData<>(Registries.LEVEL_STEM, LevelStem.CODEC) ); @@ -18,7 +18,7 @@ new RegistryDataLoader.RegistryData<>(Registries.BIOME, Biome.NETWORK_CODEC), new RegistryDataLoader.RegistryData<>(Registries.CHAT_TYPE, ChatType.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TRIM_PATTERN, TrimPattern.DIRECT_CODEC), -@@ -163,6 +_,10 @@ +@@ -160,6 +_,10 @@ new RegistryDataLoader.RegistryData<>(Registries.WORLD_CLOCK, WorldClock.DIRECT_CODEC), new RegistryDataLoader.RegistryData<>(Registries.TIMELINE, Timeline.NETWORK_CODEC) ); diff --git a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch index 9ba97434c8..3eaaa3317e 100644 --- a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch +++ b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch @@ -21,5 +21,5 @@ + } + public static RecordCodecBuilder> retrieveElement(final ResourceKey key) { - ResourceKey> registryKey = ResourceKey.createRegistryKey(key.registry()); + ResourceKey> resourcekey = ResourceKey.createRegistryKey(key.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 5b3820256f..071f0c0ff1 100644 --- a/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch +++ b/patches/minecraft/net/minecraft/resources/ResourceKey.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/resources/ResourceKey.java +++ b/net/minecraft/resources/ResourceKey.java -@@ -10,7 +_,7 @@ +@@ -9,7 +_,7 @@ import net.minecraft.core.registries.Registries; import net.minecraft.network.codec.StreamCodec; @@ -9,7 +9,7 @@ private static final ConcurrentMap> VALUES = new MapMaker().weakValues().makeMap(); private final Identifier registryName; private final Identifier identifier; -@@ -74,5 +_,18 @@ +@@ -65,5 +_,18 @@ } private record InternKey(Identifier registry, Identifier identifier) { diff --git a/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch b/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch index 9db7969690..edef63a6ec 100644 --- a/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch +++ b/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch @@ -11,28 +11,28 @@ @@ -40,6 +_,7 @@ @Override public CompletableFuture load(final RegistryOps.RegistryInfoLookup context, final Executor executor) { - FileToIdConverter lister = FileToIdConverter.registry(this.registryKey()); + FileToIdConverter filetoidconverter = FileToIdConverter.registry(this.registryKey()); + var optionalCodec = net.minecraftforge.common.crafting.conditions.ConditionCodec.wrap(this.data.elementCodec()); - return CompletableFuture.>supplyAsync(() -> lister.listMatchingResources(this.resourceManager), executor) + return CompletableFuture.>supplyAsync(() -> filetoidconverter.listMatchingResources(this.resourceManager), executor) .thenCompose( registryResources -> { @@ -49,9 +_,18 @@ (resourceId, thunk) -> { - ResourceKey elementKey = ResourceKey.create(this.registryKey(), lister.fileToId(resourceId)); - RegistrationInfo registrationInfo = REGISTRATION_INFO_CACHE.apply(thunk.knownPackInfo()); + ResourceKey resourcekey = ResourceKey.create(this.registryKey(), filetoidconverter.fileToId(resourceId)); + RegistrationInfo registrationinfo = REGISTRATION_INFO_CACHE.apply(thunk.knownPackInfo()); + // braking types here for smaller patch, its just used for error messages so its fine -+ var result = RegistryLoadTask.PendingRegistration.loadFromResource(optionalCodec, ops, (ResourceKey>)elementKey, thunk); ++ var result = RegistryLoadTask.PendingRegistration.loadFromResource(optionalCodec, registryops, (ResourceKey>)resourcekey, thunk); + if (!result.right().isPresent()) { // Wasn't an error so check if present + var value = result.left().get(); + if (value.isEmpty()) { -+ LOGGER.debug("Skipping {} conditions not met", elementKey); ++ LOGGER.debug("Skipping {} conditions not met", resourcekey); + return null; + } + } return new RegistryLoadTask.PendingRegistration<>( - elementKey, -- RegistryLoadTask.PendingRegistration.loadFromResource(this.data.elementCodec(), ops, elementKey, thunk), + resourcekey, +- RegistryLoadTask.PendingRegistration.loadFromResource(this.data.elementCodec(), registryops, resourcekey, thunk), + result.mapLeft(Optional::get), - registrationInfo + registrationinfo ); }, diff --git a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch index 8392dba490..f103f90d70 100644 --- a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch +++ b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/server/Bootstrap.java +++ b/net/minecraft/server/Bootstrap.java -@@ -59,6 +_,8 @@ - CauldronInteractions.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(start, Instant.now()).toMillis()); - } +@@ -57,6 +_,8 @@ + CauldronInteractions.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()); + } @@ -123,7 +_,6 @@ Commands.validate(); } diff --git a/patches/minecraft/net/minecraft/server/Main.java.patch b/patches/minecraft/net/minecraft/server/Main.java.patch index 6bb69fb7f5..016ca66cd9 100644 --- a/patches/minecraft/net/minecraft/server/Main.java.patch +++ b/patches/minecraft/net/minecraft/server/Main.java.patch @@ -1,53 +1,53 @@ --- a/net/minecraft/server/Main.java +++ b/net/minecraft/server/Main.java -@@ -85,6 +_,17 @@ - OptionSpec jfrProfilingOption = parser.accepts("jfrProfile"); - OptionSpec pidFile = parser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter()); - OptionSpec nonOptions = parser.nonOptions(); -+ parser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed -+ parser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. +@@ -83,6 +_,17 @@ + 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; + OptionSpec uniqueWorld = null; + boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer"); + if (gametestEnabled) { -+ spawnPosOpt = parser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); -+ uniqueWorld = parser.accepts("uniqueWorld"); ++ spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); ++ uniqueWorld = optionparser.accepts("uniqueWorld"); + } else { + spawnPosOpt = null; + } try { - OptionSet options = parser.parse(args); -@@ -93,6 +_,14 @@ + OptionSet optionset = optionparser.parse(args); +@@ -91,6 +_,14 @@ return; } -+ Path eulaFile = Paths.get("eula.txt"); -+ Eula eula = new Eula(eulaFile); ++ 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 pidFilePath = options.valueOf(pidFile); - if (pidFilePath != null) { - writePidFile(pidFilePath); -@@ -107,26 +_,30 @@ + Path path = optionset.valueOf(optionspec14); + if (path != null) { + writePidFile(path); +@@ -105,24 +_,28 @@ Bootstrap.validate(); Util.startTimerHackThread(); - Path settingsFile = Paths.get("server.properties"); -+ if (!options.has(initSettings)) { + 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 settings = new DedicatedServerSettings(settingsFile); - settings.forceSave(); - RegionFileVersion.configure(settings.getProperties().regionFileComression); -- Path eulaFile = Paths.get("eula.txt"); -- Eula eula = new Eula(eulaFile); - if (options.has(initSettings)) { - LOGGER.info("Initialized '{}' and '{}'", settingsFile.toAbsolutePath(), eulaFile.toAbsolutePath()); + 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; } @@ -56,54 +56,52 @@ - return; - } - - File universePath = new File(options.valueOf(universe)); - Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), universePath); - NotificationManager notificationManager = new NotificationManager(); - ManagementServer jsonRpcServer = JsonRpc.create(settings, notificationManager); - String levelName = Optional.ofNullable(options.valueOf(worldName)).orElse(settings.getProperties().levelName); + 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); + // Forge: make each gametest use a timestamped world name -+ if (uniqueWorld != null && options.has(uniqueWorld)) -+ levelName = "gametest_world\\" + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss.SSS").format(java.time.LocalDateTime.now()); -+ if (levelName == null || levelName.isEmpty() || new File(universePath, levelName).getAbsolutePath().equals(new File(levelName).getAbsolutePath())) { -+ LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + levelName); ++ if (uniqueWorld != null && optionset.has(uniqueWorld)) ++ s = "gametest_world\\" + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss.SSS").format(java.time.LocalDateTime.now()); ++ 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(universePath.toPath()); - LevelStorageSource.LevelStorageAccess access = levelStorageSource.validateAndCreateAccess(levelName); - Dynamic levelDataTag; -@@ -162,6 +_,10 @@ + LevelStorageSource levelstoragesource = LevelStorageSource.createDefault(file1.toPath()); + LevelStorageSource.LevelStorageAccess levelstoragesource$levelstorageaccess = levelstoragesource.validateAndCreateAccess(s); + Dynamic dynamic; +@@ -158,6 +_,10 @@ - PackRepository packRepository = ServerPacksSource.createPackRepository(access); + PackRepository packrepository = ServerPacksSource.createPackRepository(levelstoragesource$levelstorageaccess); -+ if (levelDataTag != null) { -+ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(access, access.getLevelDirectory()); ++ if (dynamic != null) { ++ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(levelstoragesource$levelstorageaccess, levelstoragesource$levelstorageaccess.getLevelDirectory()); + } + - WorldStem worldStem; + WorldStem worldstem; try { - WorldLoader.InitConfig worldLoadConfig = loadOrCreateConfig(settings.getProperties(), levelDataTag, safeModeEnabled, packRepository); -@@ -233,6 +_,7 @@ + WorldLoader.InitConfig worldloader$initconfig = loadOrCreateConfig(dedicatedserversettings.getProperties(), dynamic, flag1, packrepository); +@@ -231,6 +_,7 @@ @Override public void run() { - dedicatedServer.halt(true); + 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. } }; - shutdownThread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); -@@ -268,6 +_,16 @@ - worldOptions = bonusChest ? properties.worldOptions.withBonusChest(true) : properties.worldOptions; - dimensions = properties.createDimensions(context.datapackWorldgen()); + thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); +@@ -266,6 +_,16 @@ + worldoptions = bonusChest ? dedicatedserverproperties.worldOptions.withBonusChest(true) : dedicatedserverproperties.worldOptions; + worlddimensions = dedicatedserverproperties.createDimensions(context.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, context.datapackWorldgen()); -+ dimensions = WorldDimensions.CODEC.encoder() -+ .encodeStart(dynamicops, dimensions) ++ worlddimensions = WorldDimensions.CODEC.encoder() ++ .encodeStart(dynamicops, worlddimensions) + .flatMap((writtenPayloadWithModdedDimensions) -> + WorldDimensions.CODEC.decoder().parse(dynamicops, writtenPayloadWithModdedDimensions) + ) + .resultOrPartial(LOGGER::error) -+ .orElse(dimensions); ++ .orElse(worlddimensions); - WorldDimensions.Complete finalDimensions = dimensions.bake(datapackDimensions); - Lifecycle lifecycle = finalDimensions.lifecycle().add(context.datapackWorldgen().allRegistriesLifecycle()); + WorldDimensions.Complete worlddimensions$complete = worlddimensions.bake(datapackDimensions); + Lifecycle lifecycle = worlddimensions$complete.lifecycle().add(context.datapackWorldgen().allRegistriesLifecycle()); diff --git a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch index f8e85ecfb6..e95d01147d 100644 --- a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch +++ b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch @@ -1,47 +1,47 @@ --- a/net/minecraft/server/MinecraftServer.java +++ b/net/minecraft/server/MinecraftServer.java -@@ -296,7 +_,7 @@ +@@ -298,7 +_,7 @@ public static S spin(final Function factory) { - AtomicReference serverReference = new AtomicReference<>(); -- Thread thread = new Thread(() -> serverReference.get().runServer(), "Server thread"); -+ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, () -> serverReference.get().runServer(), "Server thread"); + 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((t, e) -> LOGGER.error("Uncaught exception in server thread", e)); if (Runtime.getRuntime().availableProcessors() > 4) { thread.setPriority(8); -@@ -436,6 +_,7 @@ +@@ -442,6 +_,7 @@ this.scoreboard.load(this.savedDataStorage.computeIfAbsent(ScoreboardSaveData.TYPE).getData()); this.commandStorage = new CommandStorage(this.savedDataStorage); this.stopwatches = this.savedDataStorage.computeIfAbsent(Stopwatches.TYPE); + net.minecraftforge.event.ForgeEventFactory.onLevelLoad(levels.get(Level.OVERWORLD)); - if (!levelData.isInitialized()) { + if (!serverleveldata.isInitialized()) { try { - setInitialSpawn(overworld, levelData, worldOptions.generateBonusChest(), isDebug, this.levelLoadListener); -@@ -470,6 +_,7 @@ - this, this.executor, this.storageSource, derivedLevelData, dimension, entry.getValue(), isDebug, biomeZoomSeed, ImmutableList.of(), false + setInitialSpawn(serverlevel, serverleveldata, worldoptions.generateBonusChest(), flag, this.levelLoadListener); +@@ -476,6 +_,7 @@ + this, this.executor, this.storageSource, derivedleveldata, resourcekey1, entry.getValue(), flag, j, ImmutableList.of(), false ); - this.levels.put(dimension, level); -+ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(level); + this.levels.put(resourcekey1, serverlevel1); ++ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(serverlevel1); } else { - level = overworld; + serverlevel1 = serverlevel; } -@@ -492,6 +_,7 @@ +@@ -498,6 +_,7 @@ levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), BlockPos.ZERO.above(80), 0.0F, 0.0F)); } else { - ServerChunkCache chunkSource = level.getChunkSource(); + ServerChunkCache serverchunkcache = level.getChunkSource(); + if (net.minecraftforge.event.ForgeEventFactory.onCreateWorldSpawn(level, levelData)) return; - ChunkPos spawnChunk = ChunkPos.containing(chunkSource.randomState().sampler().findSpawnPosition()); + ChunkPos chunkpos = ChunkPos.containing(serverchunkcache.randomState().sampler().findSpawnPosition()); levelLoadListener.start(LevelLoadListener.Stage.PREPARE_GLOBAL_SPAWN, 0); - levelLoadListener.updateFocus(level.dimension(), spawnChunk); -@@ -678,6 +_,7 @@ - for (ServerLevel level : this.getAllLevels()) { - if (level != null) { + levelLoadListener.updateFocus(level.dimension(), chunkpos); +@@ -687,6 +_,7 @@ + for (ServerLevel serverlevel2 : this.getAllLevels()) { + if (serverlevel2 != null) { try { -+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(level); - level.close(); - } catch (IOException e) { - LOGGER.error("Exception closing the level", e); -@@ -725,9 +_,11 @@ ++ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(serverlevel2); + serverlevel2.close(); + } catch (IOException ioexception1) { + LOGGER.error("Exception closing the level", (Throwable)ioexception1); +@@ -734,9 +_,11 @@ throw new IllegalStateException("Failed to initialize server"); } @@ -52,33 +52,33 @@ + resetStatusCache(status); while (this.running) { - long thisTickNanos; -@@ -781,6 +_,8 @@ + long i; +@@ -786,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 t) { - LOGGER.error("Encountered an unexpected exception", t); - CrashReport report = constructOrExtractCrashReport(t); -@@ -792,6 +_,7 @@ + } catch (Throwable throwable2) { + LOGGER.error("Encountered an unexpected exception", throwable2); + CrashReport crashreport = constructOrExtractCrashReport(throwable2); +@@ -797,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(report); + this.onServerCrash(crashreport); } finally { try { -@@ -800,6 +_,7 @@ - } catch (Throwable t) { - LOGGER.error("Exception stopping the server", t); +@@ -805,6 +_,7 @@ + } catch (Throwable throwable) { + LOGGER.error("Exception stopping the server", throwable); } finally { + net.minecraftforge.server.ServerLifecycleHooks.handleServerStopped(this); this.onServerExit(); } } -@@ -980,12 +_,14 @@ +@@ -985,12 +_,14 @@ } } @@ -86,23 +86,23 @@ this.tickCount++; this.tickRateManager.tick(); this.tickChildren(haveTime); - if (nano - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { - this.lastServerStatus = nano; + if (i - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { + this.lastServerStatus = i; this.status = this.buildServerStatus(); + resetStatusCache(status); } this.ticksUntilAutosave--; -@@ -1003,6 +_,7 @@ - this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)tickTime / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; - this.logTickMethodTime(nano); - profiler.pop(); +@@ -1008,6 +_,7 @@ + this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)k / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; + this.logTickMethodTime(i); + profilerfiller.pop(); + net.minecraftforge.event.ForgeEventFactory.onPostServerTick(haveTime, this); } protected void processPacketsAndTick(final boolean sprinting) { -@@ -1064,7 +_,8 @@ - Optional.of(players), +@@ -1069,7 +_,8 @@ + Optional.of(serverstatus$players), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), - this.enforceSecureProfile() @@ -111,41 +111,41 @@ ); } -@@ -1109,9 +_,11 @@ - profiler.push("levels"); +@@ -1114,9 +_,11 @@ + profilerfiller.push("levels"); this.updateEffectiveRespawnData(); -- for (ServerLevel level : this.getAllLevels()) { -+ for (ServerLevel level : this.getWorldArray()) { +- for (ServerLevel serverlevel : this.getAllLevels()) { ++ for (ServerLevel serverlevel : this.getWorldArray()) { + long tickStart = Util.getNanos(); - profiler.push(() -> level + " " + level.dimension().identifier()); - profiler.push("tick"); -+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(level, haveTime); + profilerfiller.push(() -> serverlevel + " " + serverlevel.dimension().identifier()); + profilerfiller.push("tick"); ++ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(serverlevel, haveTime); try { - level.tick(haveTime); -@@ -1120,9 +_,11 @@ - level.fillReportDetails(report); - throw new ReportedException(report); + serverlevel.tick(haveTime); +@@ -1125,9 +_,11 @@ + serverlevel.fillReportDetails(crashreport); + throw new ReportedException(crashreport); } -+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(level, haveTime); ++ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(serverlevel, haveTime); - profiler.pop(); - profiler.pop(); -+ perWorldTickTimes.computeIfAbsent(level.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; + profilerfiller.pop(); + profilerfiller.pop(); ++ perWorldTickTimes.computeIfAbsent(serverlevel.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; } - profiler.popPush("connection"); -@@ -1131,7 +_,7 @@ + profilerfiller.popPush("connection"); +@@ -1136,7 +_,7 @@ this.playerList.tick(); - profiler.popPush("debugSubscribers"); + profilerfiller.popPush("debugSubscribers"); this.debugSubscribers.tick(); - if (this.tickRateManager.runsNormally()) { + if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled() && this.tickRateManager.runsNormally()) { - profiler.popPush("gameTests"); + profilerfiller.popPush("gameTests"); GameTestTicker.SINGLETON.tick(); } -@@ -1217,7 +_,7 @@ +@@ -1222,7 +_,7 @@ } public String getServerModName() { @@ -155,31 +155,31 @@ public ServerClockManager clockManager() { @@ -1561,6 +_,7 @@ - this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); - this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); - this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures()); -+ 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(result::isDone); -@@ -1572,12 +_,15 @@ + this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); + this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); + this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures()); ++ this.getPlayerList().getPlayers().forEach(this.getPlayerList()::sendPlayerPermissionLevel); //Forge: Fix newly added/modified commands not being sent to the client when commands reload. + }, + this + ); +@@ -1574,12 +_,15 @@ public static WorldDataConfiguration configurePackRepository( final PackRepository packRepository, final WorldDataConfiguration initialDataConfig, final boolean initMode, final boolean safeMode ) { + net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(packRepository, false); - DataPackConfig dataPackConfig = initialDataConfig.dataPacks(); - FeatureFlagSet forcedFeatures = initMode ? FeatureFlagSet.of() : initialDataConfig.enabledFeatures(); - FeatureFlagSet allowedFeatures = initMode ? FeatureFlags.REGISTRY.allFlags() : initialDataConfig.enabledFeatures(); + DataPackConfig datapackconfig = initialDataConfig.dataPacks(); + FeatureFlagSet featureflagset = initMode ? FeatureFlagSet.of() : initialDataConfig.enabledFeatures(); + FeatureFlagSet featureflagset1 = initMode ? FeatureFlags.REGISTRY.allFlags() : initialDataConfig.enabledFeatures(); packRepository.reload(); + DataPackConfig.DEFAULT.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); -+ dataPackConfig.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); ++ datapackconfig.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); if (safeMode) { -- return configureRepositoryWithSelection(packRepository, List.of("vanilla"), forcedFeatures, false); -+ return configureRepositoryWithSelection(packRepository, net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), forcedFeatures, false); - } +- return configureRepositoryWithSelection(packRepository, List.of("vanilla"), featureflagset, false); ++ return configureRepositoryWithSelection(packRepository, net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), featureflagset, false); + } else { + Set set = Sets.newLinkedHashSet(); - Set selected = Sets.newLinkedHashSet(); -@@ -2226,6 +_,48 @@ +@@ -2235,6 +_,48 @@ public ServerLinks serverLinks() { return ServerLinks.EMPTY; diff --git a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch index bd42a95708..de5ada8ca9 100644 --- a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch +++ b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/server/PlayerAdvancements.java +++ b/net/minecraft/server/PlayerAdvancements.java -@@ -171,6 +_,7 @@ +@@ -173,6 +_,7 @@ this.unregisterListeners(holder); this.progressChanged.add(holder); - result = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, holder, progress, criterion); - if (!wasDone && progress.isDone()) { + flag = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, holder, advancementprogress, criterion); + if (!flag1 && advancementprogress.isDone()) { holder.value().rewards().grant(this.player); holder.value().display().ifPresent(display -> { -@@ -178,6 +_,7 @@ +@@ -180,6 +_,7 @@ this.playerList.broadcastSystemMessage(display.getType().createAnnouncement(holder, this.player), false); } }); @@ -16,11 +16,11 @@ } } -@@ -196,6 +_,7 @@ +@@ -198,6 +_,7 @@ this.registerListeners(advancement); this.progressChanged.add(advancement); - result = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, advancement, progress, criterion); + flag = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, advancement, advancementprogress, criterion); } - if (wasDone && !progress.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 5715cce8ce..2b83c4c672 100644 --- a/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch +++ b/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch @@ -26,8 +26,8 @@ ); return SimpleReloadInstance.create( resourceManager, -- result.listeners(), -+ net.minecraftforge.event.ForgeEventFactory.onResourceReload(result, fullRegistries.lookupWithUpdatedTags(), result.listeners()), +- reloadableserverresources.listeners(), ++ net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, fullRegistries.lookupWithUpdatedTags(), reloadableserverresources.listeners()), backgroundExecutor, mainThreadExecutor, DATA_RELOAD_INITIAL_TASK, diff --git a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch index cc24e84257..12964180ba 100644 --- a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java +++ b/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java @@ -71,6 +_,16 @@ - evaluateVisibility(root, visibilityStack, isDone, output); + evaluateVisibility(advancementnode, stack, isDone, output); } + public static boolean isVisible(AdvancementNode advancement, Predicate test) { diff --git a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch index c32d931e5c..bdd30a179a 100644 --- a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/server/commands/SpreadPlayersCommand.java +++ b/net/minecraft/server/commands/SpreadPlayersCommand.java -@@ -256,11 +_,17 @@ - position = positions[positionIndex++]; +@@ -259,11 +_,17 @@ + spreadplayerscommand$position = positions[i++]; } + var event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportSpreadPlayersCommand(entity, -+ (double)Mth.floor(position.x) + 0.5D, -+ (double)position.getSpawnY(level, maxHeight), -+ (double)Mth.floor(position.z) + 0.5D ++ (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, ++ (double)spreadplayerscommand$position.getSpawnY(level, maxHeight), ++ (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D + ); + if (event != null) entity.teleportTo( level, -- Mth.floor(position.x) + 0.5, -- position.getSpawnY(level, maxHeight), -- Mth.floor(position.z) + 0.5, +- Mth.floor(spreadplayerscommand$position.x) + 0.5, +- spreadplayerscommand$position.getSpawnY(level, maxHeight), +- Mth.floor(spreadplayerscommand$position.z) + 0.5, + event.getTargetX(), + event.getTargetY(), + event.getTargetZ(), diff --git a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch index 11f9610d5d..ce03e555fe 100644 --- a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/commands/TeleportCommand.java +++ b/net/minecraft/server/commands/TeleportCommand.java -@@ -236,14 +_,17 @@ +@@ -237,14 +_,17 @@ final CommandSourceStack source, final Entity victim, final ServerLevel level, @@ -18,6 +18,6 @@ + var event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportCommand(victim, x, y, z); + if (event == null) return; + x = event.getTargetX(); y = event.getTargetY(); z = event.getTargetZ(); - BlockPos blockPos = BlockPos.containing(x, y, z); - if (!Level.isInSpawnableBounds(blockPos)) { + BlockPos blockpos = BlockPos.containing(x, y, z); + 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 bf6bdbf01c..3edd705b17 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch @@ -1,51 +1,51 @@ --- a/net/minecraft/server/dedicated/DedicatedServer.java +++ b/net/minecraft/server/dedicated/DedicatedServer.java -@@ -88,6 +_,7 @@ - private final ServerLinks serverLinks; +@@ -97,6 +_,7 @@ private final Map codeOfConductTexts; - private final @Nullable ManagementServer jsonRpcServer; + private @Nullable ManagementServer jsonRpcServer; + private long lastHeartbeat; + private net.minecraft.client.server.@Nullable LanServerPinger dediLanPinger; public DedicatedServer( final Thread serverThread, -@@ -167,6 +_,7 @@ - Thread consoleThread = new Thread("Server console handler") { +@@ -211,6 +_,7 @@ + @Override public void run() { + if (net.minecraftforge.server.console.TerminalHandler.handleCommands(DedicatedServer.this)) return; - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); - String line; -@@ -241,11 +_,13 @@ - this.tickTimeLogger = new RemoteSampleLogger(TpsDebugDimensions.values().length, this.debugSubscribers(), RemoteDebugSampleType.TICK_TIME); - long levelNanoTime = Util.getNanos(); - this.services.nameToIdCache().resolveOfflineUsers(!this.usesAuthentication()); -+ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; - LOGGER.info("Preparing level \"{}\"", this.getLevelIdName()); - this.loadLevel(); - long elapsed = Util.getNanos() - levelNanoTime; - String time = String.format(Locale.ROOT, "%.3fs", elapsed / 1.0E9); - LOGGER.info("Done ({})! For help, type \"help\"", time); -+ this.nextTickTimeNanos = Util.getNanos(); //Forge: Update server time to prevent watchdog/spaming during long load. - if (properties.announcePlayerAchievements != null) { - this.getGameRules().set(GameRules.SHOW_ADVANCEMENT_MESSAGES, properties.announcePlayerAchievements, this); - } -@@ -274,7 +_,12 @@ + String s4; +@@ -284,11 +_,13 @@ + this.tickTimeLogger = new RemoteSampleLogger(TpsDebugDimensions.values().length, this.debugSubscribers(), RemoteDebugSampleType.TICK_TIME); + long j = Util.getNanos(); + this.services.nameToIdCache().resolveOfflineUsers(!this.usesAuthentication()); ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; + LOGGER.info("Preparing level \"{}\"", this.getLevelIdName()); + this.loadLevel(); + long k = Util.getNanos() - j; + String s3 = String.format(Locale.ROOT, "%.3fs", k / 1.0E9); + LOGGER.info("Done ({})! For help, type \"help\"", s3); ++ this.nextTickTimeNanos = Util.getNanos(); //Forge: Update server time to prevent watchdog/spaming during long load. + if (dedicatedserverproperties.announcePlayerAchievements != null) { + this.getGameRules().set(GameRules.SHOW_ADVANCEMENT_MESSAGES, dedicatedserverproperties.announcePlayerAchievements, this); + } +@@ -318,7 +_,12 @@ - this.saveEverything(false, true, true); - this.notificationManager().serverStarted(); -- 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(); -+ } + this.saveEverything(false, true, true); + this.notificationManager().serverStarted(); +- 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); + } } - @Override -@@ -417,6 +_,13 @@ - LOGGER.error("Interrupted while stopping the management server", e); +@@ -470,6 +_,13 @@ + LOGGER.error("Interrupted while stopping the management server", (Throwable)interruptedexception); } } + @@ -58,7 +58,7 @@ } @Override -@@ -719,8 +_,13 @@ +@@ -751,8 +_,13 @@ @Override protected void stopServer() { diff --git a/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch b/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch index ad47d9f1f5..65f8c6b9e7 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 -@@ -80,7 +_,7 @@ - ThreadInfo[] threadInfos = Util.dumpThreadInfo(); - Arrays.sort(threadInfos, THREAD_INFO_COMPARATOR); - StringBuilder builder = new StringBuilder(); -- Error exception = new Error("Watchdog (" + message + ")"); -+ Error exception = new Error("Watchdog (" + message + ") detected that a single server tick took too long"); // Forge: don't just make a crash report with a seemingly-inexplicable Error +@@ -79,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 too long")); // Forge: don't just make a crash report with a seemingly-inexplicable Error - for (ThreadInfo threadInfo : threadInfos) { - if (threadInfo.getThreadId() == mainThreadId) { + for (ThreadInfo threadinfo : athreadinfo) { + if (threadinfo.getThreadId() == mainThreadId) { diff --git a/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch b/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch index fbbfbafb00..649f6c8dde 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 -@@ -58,7 +_,7 @@ +@@ -66,7 +_,7 @@ public void store(final Path output) { - try (Writer os = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) { -- this.properties.store(os, "Minecraft server properties"); -+ net.minecraftforge.common.util.SortedProperties.store(this.properties, os, "Minecraft server properties"); - } catch (IOException e) { + try (Writer writer = Files.newBufferedWriter(output, 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: {}", output); } diff --git a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch index b6f29e0aa7..a9d82bd6ab 100644 --- a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch +++ b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/gui/MinecraftServerGui.java +++ b/net/minecraft/server/gui/MinecraftServerGui.java -@@ -136,8 +_,10 @@ - return panel; +@@ -142,8 +_,10 @@ + return jpanel; } + private final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); @@ -11,7 +11,7 @@ } public void close() { -@@ -151,6 +_,9 @@ +@@ -157,6 +_,9 @@ } public void print(final JTextArea console, final JScrollPane scrollPane, final String line) { diff --git a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch index a4cd417234..5b7d1ce644 100644 --- a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch @@ -1,35 +1,35 @@ --- a/net/minecraft/server/level/ChunkMap.java +++ b/net/minecraft/server/level/ChunkMap.java -@@ -392,6 +_,7 @@ - this.modified = true; +@@ -402,6 +_,7 @@ + this.modified = true; + } + ++ net.minecraftforge.event.ForgeEventFactory.fireChunkTicketLevelUpdated(this.level, node, oldLevel, level, chunk); + return chunk; } - -+ net.minecraftforge.event.ForgeEventFactory.fireChunkTicketLevelUpdated(this.level, node, oldLevel, level, chunk); - return chunk; } - -@@ -522,6 +_,7 @@ - if (this.pendingUnloads.remove(pos, chunkHolder) && chunk != null) { - if (chunk instanceof LevelChunk levelChunk) { - levelChunk.setLoaded(false); -+ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(chunk); +@@ -533,6 +_,7 @@ + if (this.pendingUnloads.remove(pos, chunkHolder) && chunkaccess != null) { + if (chunkaccess instanceof LevelChunk levelchunk) { + levelchunk.setLoaded(false); ++ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(chunkaccess); } - this.save(chunk); -@@ -767,6 +_,7 @@ - this.activeChunkWrites.incrementAndGet(); - SerializableChunkData data = SerializableChunkData.copyOf(this.level, chunk); - CompletableFuture encodedData = CompletableFuture.supplyAsync(data::write, Util.backgroundExecutor()); -+ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(chunk, chunk.getWorldForge() != null ? chunk.getWorldForge() : this.level, data); - this.write(pos, encodedData::join).handle((ignored, throwable) -> { - if (throwable != null) { - this.level.getServer().reportChunkSaveFailure(throwable, this.storageInfo(), pos); -@@ -1142,7 +_,7 @@ + this.save(chunkaccess); +@@ -775,6 +_,7 @@ + this.activeChunkWrites.incrementAndGet(); + SerializableChunkData serializablechunkdata = SerializableChunkData.copyOf(this.level, chunk); + CompletableFuture completablefuture = CompletableFuture.supplyAsync(serializablechunkdata::write, Util.backgroundExecutor()); ++ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(chunk, chunk.getWorldForge() != null ? chunk.getWorldForge() : this.level, serializablechunkdata); + this.write(chunkpos, completablefuture::join).handle((ignored, throwable) -> { + if (throwable != null) { + this.level.getServer().reportChunkSaveFailure(throwable, this.storageInfo(), chunkpos); +@@ -1153,7 +_,7 @@ } protected void addEntity(final Entity entity) { - if (!(entity instanceof EnderDragonPart)) { + if (!(entity instanceof net.minecraftforge.entity.PartEntity)) { - EntityType type = entity.getType(); - int range = type.clientTrackingRange() * 16; - if (range != 0) { + EntityType entitytype = entity.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 c3e4756ad1..53826a331c 100644 --- a/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/level/DistanceManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/DistanceManager.java +++ b/net/minecraft/server/level/DistanceManager.java -@@ -189,6 +_,10 @@ +@@ -190,6 +_,10 @@ return this.ticketDispatcher.getDebugStatus(); } diff --git a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch index c76f6f6747..9bb577024b 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch @@ -1,14 +1,13 @@ --- a/net/minecraft/server/level/ServerChunkCache.java +++ b/net/minecraft/server/level/ServerChunkCache.java -@@ -194,6 +_,11 @@ - return null; - } - -+ // Forge: If the requested chunk is loading, bypass the future chain to prevent a deadlock. -+ if (chunkHolder.currentlyLoading != null) { -+ return chunkHolder.currentlyLoading; -+ } -+ - ChunkAccess chunk = chunkHolder.getChunkIfPresent(ChunkStatus.FULL); - if (chunk != null) { - this.storeInCache(pos, chunk, ChunkStatus.FULL); +@@ -193,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; ++ } + ChunkAccess chunkaccess1 = chunkholder.getChunkIfPresent(ChunkStatus.FULL); + if (chunkaccess1 != null) { + this.storeInCache(i, chunkaccess1, ChunkStatus.FULL); diff --git a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch index 30b21a502a..9e1502d711 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerEntity.java +++ b/net/minecraft/server/level/ServerEntity.java -@@ -262,6 +_,7 @@ +@@ -258,6 +_,7 @@ public void removePairing(final ServerPlayer player) { this.entity.stopSeenByPlayer(player); player.connection.send(new ClientboundRemoveEntitiesPacket(this.entity.getId())); @@ -8,9 +8,9 @@ } public void addPairing(final ServerPlayer player) { -@@ -269,6 +_,7 @@ - this.sendPairingData(player, packets::add); - player.connection.send(new ClientboundBundlePacket(packets)); +@@ -265,6 +_,7 @@ + this.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); this.entity.startSeenByPlayer(player); + net.minecraftforge.event.ForgeEventFactory.onStartEntityTracking(this.entity, player); } diff --git a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch index d5e687789e..73c8cd7385 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerLevel.java +++ b/net/minecraft/server/level/ServerLevel.java -@@ -217,10 +_,12 @@ +@@ -216,10 +_,12 @@ private final List customSpawners; private @Nullable EnderDragonFight dragonFight; private final Int2ObjectMap dragonParts = new Int2ObjectOpenHashMap<>(); @@ -13,7 +13,7 @@ public ServerLevel( final MinecraftServer server, -@@ -304,6 +_,18 @@ +@@ -303,6 +_,18 @@ this.waypointManager = new ServerWaypointManager(); this.environmentAttributes = EnvironmentAttributeSystem.builder().addDefaultLayers(this).build(); this.updateSkyBrightness(); @@ -31,35 +31,35 @@ + return getCapabilities(); } - @Override -@@ -367,7 +_,9 @@ - if (this.sleepStatus.areEnoughSleeping(percentage) && this.sleepStatus.areEnoughDeepSleeping(percentage, this.players)) { - Optional> defaultClock = this.dimensionType().defaultClock(); - if (this.getGameRules().get(GameRules.ADVANCE_TIME) && defaultClock.isPresent()) { -- this.server.clockManager().moveToTimeMarker(defaultClock.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); -+ long minTime = this.server.clockManager().getTotalTicks(defaultClock.get()); -+ long newTime = this.server.clockManager().getTimeMarker(defaultClock.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); -+ this.server.clockManager().setTotalTicks(defaultClock.get(), net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, newTime, minTime)); + @Deprecated +@@ -354,7 +_,9 @@ + if (this.sleepStatus.areEnoughSleeping(i) && this.sleepStatus.areEnoughDeepSleeping(i, this.players)) { + Optional> optional = this.dimensionType().defaultClock(); + if (this.getGameRules().get(GameRules.ADVANCE_TIME) && optional.isPresent()) { +- this.server.clockManager().moveToTimeMarker(optional.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); ++ long minTime = this.server.clockManager().getTotalTicks(optional.get()); ++ long newTime = this.server.clockManager().getTimeMarker(optional.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); ++ this.server.clockManager().setTotalTicks(optional.get(), net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, newTime, minTime)); } this.wakeUpAllPlayers(); -@@ -441,6 +_,7 @@ +@@ -428,6 +_,7 @@ entity.stopRiding(); } + if (entity.isRemoved() || entity instanceof net.minecraftforge.entity.PartEntity) return; - profiler.push("tick"); + profilerfiller.push("tick"); this.guardEntityTick(this::tickNonPassenger, entity); - profiler.pop(); -@@ -581,6 +_,7 @@ - BlockPos topPos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos); - BlockPos belowPos = topPos.below(); - Biome biome = this.getBiome(topPos).value(); -+ if (this.isAreaLoaded(belowPos, 1)) // Forge: check area to avoid loading neighbors in unloaded chunks - if (biome.shouldFreeze(this, belowPos)) { - this.setBlockAndUpdate(belowPos, Blocks.ICE.defaultBlockState()); + profilerfiller.pop(); +@@ -569,6 +_,7 @@ + BlockPos blockpos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos); + 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()); } -@@ -790,8 +_,8 @@ +@@ -778,8 +_,8 @@ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F)); } @@ -70,23 +70,23 @@ } } -@@ -829,6 +_,7 @@ +@@ -817,6 +_,7 @@ entity.tickCount++; - profiler.push(entity.typeHolder()::getRegisteredName); - profiler.incrementCounter("tickNonPassenger"); + profilerfiller.push(entity.typeHolder()::getRegisteredName); + profilerfiller.incrementCounter("tickNonPassenger"); + if (entity.canUpdate()) entity.tick(); - profiler.pop(); + profilerfiller.pop(); -@@ -846,6 +_,7 @@ - ProfilerFiller profiler = Profiler.get(); - profiler.push(entity.typeHolder()::getRegisteredName); - profiler.incrementCounter("tickPassenger"); +@@ -834,6 +_,7 @@ + ProfilerFiller profilerfiller = Profiler.get(); + profilerfiller.push(entity.typeHolder()::getRegisteredName); + profilerfiller.incrementCounter("tickPassenger"); + if (entity.canUpdate()) entity.rideTick(); - profiler.pop(); + profilerfiller.pop(); -@@ -892,6 +_,7 @@ +@@ -880,6 +_,7 @@ } else { this.entityManager.autoSave(); } @@ -94,16 +94,16 @@ } } -@@ -983,6 +_,7 @@ +@@ -971,6 +_,7 @@ } private void addPlayer(final ServerPlayer player) { + if (net.minecraftforge.event.ForgeEventFactory.onEntityJoinLevel(player, this)) return; - Entity existing = this.getEntity(player.getUUID()); - if (existing != null) { + Entity entity = this.getEntity(player.getUUID()); + if (entity != null) { LOGGER.warn("Force-added player with duplicate UUID {}", player.getUUID()); -@@ -990,7 +_,8 @@ - this.removePlayerImmediately((ServerPlayer)existing, Entity.RemovalReason.DISCARDED); +@@ -978,7 +_,8 @@ + this.removePlayerImmediately((ServerPlayer)entity, Entity.RemovalReason.DISCARDED); } - this.entityManager.addNewEntity(player); @@ -112,7 +112,7 @@ } private boolean addEntity(final Entity entity) { -@@ -998,7 +_,12 @@ +@@ -986,7 +_,12 @@ LOGGER.warn("Tried to add entity {} but it was marked as removed already", entity.typeHolder().getRegisteredName()); return false; } else { @@ -126,7 +126,7 @@ } } -@@ -1047,6 +_,8 @@ +@@ -1035,6 +_,8 @@ final float pitch, final long seed ) { @@ -135,7 +135,7 @@ this.server .getPlayerList() .broadcast( -@@ -1054,9 +_,9 @@ +@@ -1042,9 +_,9 @@ x, y, z, @@ -147,7 +147,7 @@ ); } -@@ -1070,6 +_,8 @@ +@@ -1058,6 +_,8 @@ final float pitch, final long seed ) { @@ -156,7 +156,7 @@ this.server .getPlayerList() .broadcast( -@@ -1079,7 +_,7 @@ +@@ -1067,7 +_,7 @@ sourceEntity.getZ(), sound.value().getRange(volume), this.dimension(), @@ -165,7 +165,7 @@ ); } -@@ -1128,6 +_,7 @@ +@@ -1116,6 +_,7 @@ @Override public void gameEvent(final Holder gameEvent, final Vec3 position, final GameEvent.Context context) { @@ -173,7 +173,7 @@ this.gameEventDispatcher.post(gameEvent, position, context); } -@@ -1166,11 +_,15 @@ +@@ -1154,11 +_,15 @@ @Override public void updateNeighborsAt(final BlockPos pos, final Block sourceBlock) { @@ -189,7 +189,7 @@ this.neighborUpdater.updateNeighborsAtExceptFromFacing(pos, sourceBlock, null, orientation); } -@@ -1178,6 +_,10 @@ +@@ -1166,6 +_,10 @@ public void updateNeighborsAtExceptFromFacing( final BlockPos pos, final Block blockObject, final Direction skipDirection, final @Nullable Orientation orientation ) { @@ -200,8 +200,8 @@ this.neighborUpdater.updateNeighborsAtExceptFromFacing(pos, blockObject, skipDirection, orientation); } -@@ -1226,7 +_,7 @@ - Explosion.BlockInteraction blockInteraction = switch (interactionType) { +@@ -1214,7 +_,7 @@ + Explosion.BlockInteraction explosion$blockinteraction = switch (interactionType) { case NONE -> Explosion.BlockInteraction.KEEP; case BLOCK -> this.getDestroyType(GameRules.BLOCK_EXPLOSION_DROP_DECAY); - case MOB -> this.getGameRules().get(GameRules.MOB_GRIEFING) @@ -209,16 +209,16 @@ ? this.getDestroyType(GameRules.MOB_EXPLOSION_DROP_DECAY) : Explosion.BlockInteraction.KEEP; case TNT -> this.getDestroyType(GameRules.TNT_EXPLOSION_DROP_DECAY); -@@ -1234,6 +_,8 @@ +@@ -1222,6 +_,8 @@ }; - Vec3 center = new Vec3(x, y, z); - ServerExplosion explosion = new ServerExplosion(this, source, damageSource, damageCalculator, center, r, fire, blockInteraction); -+ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, explosion)) + Vec3 vec3 = new Vec3(x, y, z); + ServerExplosion serverexplosion = new ServerExplosion(this, source, damageSource, damageCalculator, vec3, r, fire, explosion$blockinteraction); ++ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, serverexplosion)) + return; - int blockCount = explosion.explode(); - ParticleOptions explosionParticle = explosion.isSmall() ? smallExplosionParticles : largeExplosionParticles; + int i = serverexplosion.explode(); + ParticleOptions particleoptions = serverexplosion.isSmall() ? smallExplosionParticles : largeExplosionParticles; -@@ -1894,6 +_,11 @@ +@@ -1888,6 +_,11 @@ return this.getGameRules().get(GameRules.SPAWNER_BLOCKS_WORK); } @@ -228,9 +228,9 @@ + } + private final class EntityCallbacks implements LevelCallback { - public void onCreated(final Entity entity) { - if (entity instanceof WaypointTransmitter waypoint && waypoint.isTransmittingWaypoint()) { -@@ -1949,6 +_,12 @@ + private EntityCallbacks() { + Objects.requireNonNull(ServerLevel.this); +@@ -1948,6 +_,12 @@ } } @@ -243,7 +243,7 @@ entity.updateDynamicGameEventListener(DynamicGameEventListener::add); } -@@ -1977,8 +_,17 @@ +@@ -1976,8 +_,17 @@ } } diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch index f9691666ec..cc94492ca6 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch @@ -10,40 +10,40 @@ 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; -@@ -881,6 +_,7 @@ +@@ -885,6 +_,7 @@ @Override public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; this.gameEvent(GameEvent.ENTITY_DIE); - boolean showDeathMessage = this.level().getGameRules().get(GameRules.SHOW_DEATH_MESSAGES); - if (showDeathMessage) { -@@ -1093,6 +_,7 @@ + boolean flag = this.level().getGameRules().get(GameRules.SHOW_DEATH_MESSAGES); + if (flag) { +@@ -1098,6 +_,7 @@ } public @Nullable ServerPlayer teleport(final TeleportTransition transition) { + if (net.minecraftforge.event.ForgeEventFactory.onTravelToDimension(this, transition.newLevel().dimension())) return null; if (this.isRemoved()) { return null; + } else { +@@ -1125,7 +_,7 @@ + PlayerList playerlist = this.server.getPlayerList(); + playerlist.sendPlayerPermissionLevel(this); + serverlevel1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); +- this.unsetRemoved(); ++ this.revive(); + ProfilerFiller profilerfiller = Profiler.get(); + profilerfiller.push("moving"); + if (resourcekey == Level.OVERWORLD && serverlevel.dimension() == Level.NETHER) { +@@ -1150,6 +_,7 @@ + this.lastSentHealth = -1.0F; + this.lastSentFood = -1; + this.teleportSpectators(transition, serverlevel1); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, resourcekey, transition.newLevel().dimension()); + return this; + } } -@@ -1122,7 +_,7 @@ - PlayerList playerList = this.server.getPlayerList(); - playerList.sendPlayerPermissionLevel(this); - oldLevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); -- this.unsetRemoved(); -+ this.revive(); - ProfilerFiller profiler = Profiler.get(); - profiler.push("moving"); - if (lastDimension == Level.OVERWORLD && newLevel.dimension() == Level.NETHER) { -@@ -1147,6 +_,7 @@ - this.lastSentHealth = -1.0F; - this.lastSentFood = -1; - this.teleportSpectators(transition, oldLevel); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, lastDimension, transition.newLevel().dimension()); - return this; - } - -@@ -1186,10 +_,13 @@ +@@ -1191,10 +_,13 @@ @Override public Either startSleepInBed(final BlockPos pos) { @@ -52,13 +52,13 @@ + if (ret != null) return Either.left(ret); Direction direction = this.level().getBlockState(pos).getValue(HorizontalDirectionalBlock.FACING); if (!this.isSleeping() && this.isAlive()) { - BedRule rule = this.level().environmentAttributes().getValue(EnvironmentAttributes.BED_RULE, pos); -- boolean canSleep = rule.canSleep(this.level()); -+ boolean canSleep = net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, optAt, rule); - boolean canSetSpawn = rule.canSetSpawn(this.level()); - if (!canSetSpawn && !canSleep) { - return Either.left(rule.asProblem()); -@@ -1250,6 +_,7 @@ + BedRule bedrule = this.level().environmentAttributes().getValue(EnvironmentAttributes.BED_RULE, pos); +- boolean flag = bedrule.canSleep(this.level()); ++ boolean flag = net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, optAt, bedrule); + boolean flag1 = bedrule.canSetSpawn(this.level()); + if (!flag1 && !flag) { + return Either.left(bedrule.asProblem()); +@@ -1251,6 +_,7 @@ } private boolean bedInRange(final BlockPos pos, final Direction direction) { @@ -66,15 +66,15 @@ return this.isReachableBedBlock(pos) || this.isReachableBedBlock(pos.relative(direction.getOpposite())); } -@@ -1354,6 +_,7 @@ - this.connection.send(new ClientboundOpenScreenPacket(menu.containerId, menu.getType(), provider.getDisplayName())); - this.initMenu(menu); - this.containerMenu = menu; -+ net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); - return OptionalInt.of(this.containerCounter); +@@ -1351,6 +_,7 @@ + .send(new ClientboundOpenScreenPacket(abstractcontainermenu.containerId, abstractcontainermenu.getType(), provider.getDisplayName())); + this.initMenu(abstractcontainermenu); + this.containerMenu = abstractcontainermenu; ++ net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); + return OptionalInt.of(this.containerCounter); + } } - } -@@ -1422,6 +_,7 @@ +@@ -1420,6 +_,7 @@ public void doCloseContainer() { this.containerMenu.removed(this); this.inventoryMenu.transferState(this.containerMenu); @@ -82,7 +82,7 @@ this.containerMenu = this.inventoryMenu; } -@@ -1641,6 +_,15 @@ +@@ -1637,6 +_,15 @@ this.setShoulderEntityRight(oldPlayer.getShoulderEntityRight()); this.setLastDeathLocation(oldPlayer.getLastDeathLocation()); this.waypointIcon().copyFrom(oldPlayer.waypointIcon()); @@ -98,28 +98,28 @@ } private void transferInventoryXpAndScore(final Player oldPlayer) { -@@ -1750,8 +_,9 @@ +@@ -1746,8 +_,9 @@ return (ServerLevel)super.level(); } - public boolean setGameMode(final GameType mode) { + public boolean setGameMode(GameType mode) { - boolean wasSpectator = this.isSpectator(); + boolean flag = this.isSpectator(); + mode = net.minecraftforge.common.ForgeHooks.onChangeGameType(this, this.gameMode.getGameModeForPlayer(), mode); if (!this.gameMode.changeGameModeForPlayer(mode)) { return false; - } -@@ -1935,6 +_,9 @@ + } else { +@@ -1931,6 +_,9 @@ public void setCamera(final @Nullable Entity newCamera) { - Entity oldCamera = this.getCamera(); - this.camera = newCamera == null ? this : newCamera; + Entity entity = this.getCamera(); + this.camera = (Entity)(newCamera == null ? this : newCamera); + while (this.camera instanceof net.minecraftforge.entity.PartEntity partEntity) { + this.camera = partEntity.getParent(); // FORGE: fix MC-46486 + } - if (oldCamera != this.camera) { - if (this.camera.level() instanceof ServerLevel level) { - this.teleportTo(level, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false); -@@ -1961,7 +_,11 @@ + if (entity != this.camera) { + if (this.camera.level() instanceof ServerLevel serverlevel) { + this.teleportTo(serverlevel, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false); +@@ -1957,7 +_,11 @@ } public @Nullable Component getTabListDisplayName() { @@ -132,7 +132,7 @@ } public int getTabListOrder() { -@@ -1995,6 +_,7 @@ +@@ -1991,6 +_,7 @@ } public void setRespawnPosition(final ServerPlayer.@Nullable RespawnConfig respawnConfig, final boolean showMessage) { @@ -140,26 +140,26 @@ if (showMessage && respawnConfig != null && !respawnConfig.isSamePosition(this.respawnConfig)) { this.sendSystemMessage(SPAWN_SET_MESSAGE); } -@@ -2082,6 +_,9 @@ +@@ -2078,6 +_,9 @@ public void drop(final boolean all) { Inventory inventory = this.getInventory(); + ItemStack selected = inventory.getSelectedItem(); + if (selected.isEmpty() || !selected.onDroppedByPlayer(this)) return; + if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (all || selected.getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the serverside - ItemStack removed = inventory.removeFromSelected(all); + ItemStack itemstack = inventory.removeFromSelected(all); this.containerMenu .findSlot(inventory, inventory.getSelectedSlot()) -@@ -2090,7 +_,7 @@ +@@ -2086,7 +_,7 @@ this.stopUsingItem(); } -- this.drop(removed, false, true); -+ net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, removed, true); +- this.drop(itemstack, false, true); ++ net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, itemstack, true); } @Override -@@ -2192,6 +_,75 @@ +@@ -2188,6 +_,75 @@ public @Nullable BlockPos getRaidOmenPosition() { return this.raidOmenPosition; diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch index 0f23261e57..f8e2ac3e2f 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerPlayerGameMode.java +++ b/net/minecraft/server/level/ServerPlayerGameMode.java -@@ -150,6 +_,10 @@ +@@ -151,6 +_,10 @@ public void handleBlockBreakAction( final BlockPos pos, final ServerboundPlayerActionPacket.Action action, final Direction direction, final int maxY, final int sequence ) { @@ -11,82 +11,81 @@ if (!this.player.isWithinBlockInteractionRange(pos, 1.0)) { this.debugLogging(pos, false, sequence, "too far"); } else if (pos.getY() > maxY) { -@@ -184,6 +_,7 @@ - float progress = 1.0F; - BlockState blockState = this.level.getBlockState(pos); - if (!blockState.isAir()) { +@@ -185,6 +_,7 @@ + float f = 1.0F; + BlockState blockstate = this.level.getBlockState(pos); + if (!blockstate.isAir()) { + if (!event.getUseBlock().isDenied()) { EnchantmentHelper.onHitBlock( this.level, this.player.getMainHandItem(), -@@ -195,6 +_,7 @@ +@@ -196,6 +_,7 @@ item -> this.player.onEquippedItemBroken(item, EquipmentSlot.MAINHAND) ); - blockState.attack(this.level, pos, this.player); + blockstate.attack(this.level, pos, this.player); + } - progress = blockState.getDestroyProgress(this.player, this.player.level(), pos); + f = blockstate.getDestroyProgress(this.player, this.player.level(), pos); } -@@ -261,7 +_,8 @@ +@@ -262,7 +_,8 @@ public boolean destroyBlock(final BlockPos pos) { - BlockState state = this.level.getBlockState(pos); -- if (!this.player.getMainHandItem().canDestroyBlock(state, this.level, pos, this.player)) { + BlockState blockstate1 = this.level.getBlockState(pos); +- if (!this.player.getMainHandItem().canDestroyBlock(blockstate1, this.level, pos, this.player)) { + int exp = net.minecraftforge.common.ForgeHooks.onBlockBreakEvent(level, gameModeForPlayer, player, pos); + if (exp == -1) { return false; - } - -@@ -272,35 +_,53 @@ - return false; - } - -+ if (player.getMainHandItem().onBlockStartBreak(pos, player)) { -+ return false; -+ } -+ - if (this.player.blockActionRestricted(this.level, pos, this.gameModeForPlayer)) { - return false; - } - -- BlockState adjustedState = block.playerWillDestroy(this.level, pos, state, this.player); -- boolean changed = this.level.removeBlock(pos, false); -- if (SharedConstants.DEBUG_BLOCK_BREAK) { -- LOGGER.info("server broke {} {} -> {}", pos, adjustedState, this.level.getBlockState(pos)); -- } + } else { + BlockEntity blockentity = this.level.getBlockEntity(pos); +@@ -270,34 +_,50 @@ + if (block instanceof GameMasterBlock && !this.player.canUseGameMasterBlocks()) { + this.level.sendBlockUpdated(pos, blockstate1, blockstate1, 3); + return false; ++ } else if (player.getMainHandItem().onBlockStartBreak(pos, player)) { ++ return false; + } else if (this.player.blockActionRestricted(this.level, pos, this.gameModeForPlayer)) { + return false; + } else { +- BlockState blockstate = block.playerWillDestroy(this.level, pos, blockstate1, this.player); +- boolean flag1 = this.level.removeBlock(pos, false); +- if (SharedConstants.DEBUG_BLOCK_BREAK) { +- LOGGER.info("server broke {} {} -> {}", pos, blockstate, this.level.getBlockState(pos)); +- } - -- if (changed) { -- block.destroy(this.level, pos, adjustedState); -- } +- if (flag1) { +- block.destroy(this.level, pos, blockstate); +- } - -+ BlockState adjustedState = state; - if (this.player.preventsBlockDrops()) { -+ removeBlock(pos, false); - return true; ++ BlockState blockstate = blockstate1; + if (this.player.preventsBlockDrops()) { ++ removeBlock(pos, 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, pos, this.player); // previously player.hasCorrectToolForDrops(blockstate) + itemstack.mineBlock(this.level, blockstate, pos, this.player); ++ ++ if (itemstack.isEmpty() && !itemstack1.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, itemstack1, InteractionHand.MAIN_HAND); ++ } ++ boolean flag1 = removeBlock(pos, flag); ++ + if (flag1 && flag) { + block.playerDestroy(this.level, this.player, pos, blockstate, blockentity, itemstack1); + } + ++ if (flag && exp > 0) { ++ blockstate1.getBlock().popExperience(level, pos, exp); ++ } ++ + return true; + } + } } - - ItemStack itemStack = this.player.getMainHandItem(); - ItemStack destroyedWith = itemStack.copy(); -- boolean canDestroy = this.player.hasCorrectToolForDrops(adjustedState); -+ boolean canDestroy = adjustedState.canHarvestBlock(this.level, pos, this.player); // previously player.hasCorrectToolForDrops(blockstate) - itemStack.mineBlock(this.level, adjustedState, pos, this.player); ++ } + -+ if (itemStack.isEmpty() && !destroyedWith.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, destroyedWith, InteractionHand.MAIN_HAND); -+ } -+ boolean changed = removeBlock(pos, canDestroy); -+ - if (changed && canDestroy) { - block.playerDestroy(this.level, this.player, pos, adjustedState, blockEntity, destroyedWith); - } - -+ if (canDestroy && exp > 0) { -+ state.getBlock().popExperience(level, pos, exp); -+ } -+ - return true; - } - + private boolean removeBlock(BlockPos pos, boolean canHarvest) { + BlockState state = this.level.getBlockState(pos); + boolean removed = state.onDestroyedByPlayer(this.level, pos, this.player, canHarvest, this.level.getFluidState(pos)); @@ -97,55 +96,56 @@ + state.getBlock().destroy(this.level, pos, state); + } + return removed; -+ } -+ + } + public InteractionResult useItem(final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand) { - if (this.gameModeForPlayer == GameType.SPECTATOR) { +@@ -306,6 +_,8 @@ + } else if (player.getCooldowns().isOnCooldown(itemStack)) { return InteractionResult.PASS; -@@ -310,6 +_,8 @@ - return InteractionResult.PASS; - } - -+ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(player, hand); -+ if (cancelResult != null) return cancelResult; - int oldCount = itemStack.getCount(); - int oldDamage = itemStack.getDamageValue(); - InteractionResult result = itemStack.use(level, player, hand); -@@ -355,6 +_,8 @@ + } else { ++ InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(player, hand); ++ if (cancelResult != null) return cancelResult; + int i = itemStack.getCount(); + int j = itemStack.getDamageValue(); + InteractionResult interactionresult = itemStack.use(level, player, hand); +@@ -346,6 +_,11 @@ + if (!blockstate.getBlock().isEnabled(level.enabledFeatures())) { return InteractionResult.FAIL; - } - -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, pos, hitResult); + } else if (this.gameModeForPlayer == GameType.SPECTATOR) { ++ } ++ ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, blockpos, hitResult); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock.BUS.post(event)) return event.getCancellationResult(); - if (this.gameModeForPlayer == GameType.SPECTATOR) { - MenuProvider menuProvider = state.getMenuProvider(level, pos); - if (menuProvider != null) { -@@ -364,10 +_,16 @@ ++ if (this.gameModeForPlayer == GameType.SPECTATOR) { + MenuProvider menuprovider = blockstate.getMenuProvider(level, blockpos); + if (menuprovider != null) { + player.openMenu(menuprovider); +@@ -354,10 +_,16 @@ return InteractionResult.PASS; } } else { -+ UseOnContext context = new UseOnContext(player, hand, hitResult); ++ UseOnContext useoncontext = new UseOnContext(player, hand, hitResult); + if (!event.getUseItem().isDenied()) { -+ InteractionResult result = itemStack.onItemUseFirst(context); ++ InteractionResult result = itemStack.onItemUseFirst(useoncontext); + if (result != InteractionResult.PASS) return result; + } - boolean haveSomethingInOurHands = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); - boolean suppressUsingBlock = player.isSecondaryUseActive() && haveSomethingInOurHands; -+ suppressUsingBlock &= !(player.getMainHandItem().doesSneakBypassUse(level, pos, player) && player.getOffhandItem().doesSneakBypassUse(level, pos, player)); - ItemStack usedItemStack = itemStack.copy(); -- if (!suppressUsingBlock) { -+ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !suppressUsingBlock)) { - InteractionResult itemUse = state.useItemOn(player.getItemInHand(hand), level, player, hand, hitResult); - if (itemUse.consumesAction()) { - CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, pos, usedItemStack); -@@ -383,8 +_,8 @@ + boolean flag = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); + boolean flag1 = player.isSecondaryUseActive() && flag; ++ flag1 &= !(player.getMainHandItem().doesSneakBypassUse(level, blockpos, player) && player.getOffhandItem().doesSneakBypassUse(level, blockpos, player)); + ItemStack itemstack = itemStack.copy(); +- if (!flag1) { ++ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !flag1)) { + InteractionResult interactionresult = blockstate.useItemOn(player.getItemInHand(hand), level, player, hand, hitResult); + if (interactionresult.consumesAction()) { + CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, blockpos, itemstack); +@@ -373,8 +_,8 @@ } } - if (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack)) { -- UseOnContext context = new UseOnContext(player, hand, hitResult); +- UseOnContext useoncontext = new UseOnContext(player, hand, hitResult); + if (event.getUseItem().isAllowed() || (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack))) { + if (event.getUseItem().isDenied()) return InteractionResult.PASS; - InteractionResult success; + InteractionResult interactionresult2; if (player.hasInfiniteMaterials()) { - int count = itemStack.getCount(); + int i = itemStack.getCount(); diff --git a/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch b/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch index f78bae86a7..7565a63561 100644 --- a/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/level/ThreadedLevelLightEngine.java +++ b/net/minecraft/server/level/ThreadedLevelLightEngine.java @@ -175,6 +_,7 @@ - }, () -> "lightChunk " + pos + " " + lighted)); + }, () -> "lightChunk " + chunkpos + " " + lighted)); return CompletableFuture.supplyAsync(() -> { centerChunk.setLightCorrect(true); + net.minecraftforge.common.ForgeHooks.fireLightingCalculatedEvent(centerChunk); return centerChunk; - }, r -> this.addTask(pos.x(), pos.z(), ThreadedLevelLightEngine.TaskType.POST_UPDATE, r)); + }, r -> this.addTask(chunkpos.x(), chunkpos.z(), ThreadedLevelLightEngine.TaskType.POST_UPDATE, r)); } diff --git a/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch b/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch index 267dd699cc..bed5d7c261 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 -@@ -341,6 +_,7 @@ +@@ -301,6 +_,7 @@ @Override public boolean addFreshEntity(final Entity entity) { + if (entity instanceof net.minecraft.world.entity.Mob mob && mob.isSpawnCancelled()) return false; - int xc = SectionPos.blockToSectionCoord(entity.getBlockX()); - int zc = SectionPos.blockToSectionCoord(entity.getBlockZ()); - this.getChunk(xc, zc).addEntity(entity); + int i = SectionPos.blockToSectionCoord(entity.getBlockX()); + int j = SectionPos.blockToSectionCoord(entity.getBlockZ()); + this.getChunk(i, j).addEntity(entity); diff --git a/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch b/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch index d6585479fe..42fcd20a34 100644 --- a/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch +++ b/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch @@ -27,24 +27,24 @@ } public EventLoopGroup eventLoopGroup() { -- EventLoopGroup result = this.group; +- EventLoopGroup eventloopgroup = this.group; + return eventLoopGroup(false); + } + + public EventLoopGroup eventLoopGroup(boolean client) { -+ EventLoopGroup result = client ? this.groupClient : this.group; - if (result == null) { ++ EventLoopGroup eventloopgroup = client ? this.groupClient : this.group; + if (eventloopgroup == null) { synchronized (this) { -- result = this.group; -+ result = client ? this.groupClient : this.group; - if (result == null) { -- result = this.createEventLoopGroup(); -- this.group = result; -+ result = this.createEventLoopGroup(client); +- eventloopgroup = this.group; ++ eventloopgroup = client ? this.groupClient : this.group; + if (eventloopgroup == null) { +- eventloopgroup = this.createEventLoopGroup(); +- this.group = eventloopgroup; ++ eventloopgroup = this.createEventLoopGroup(client); + if (client) -+ this.groupClient = result; ++ this.groupClient = eventloopgroup; + else -+ this.group = result; ++ this.group = eventloopgroup; } } } diff --git a/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch index 6458aa4e0c..22c44f0b0c 100644 --- a/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/MemoryServerHandshakePacketListenerImpl.java.patch @@ -7,4 +7,4 @@ + if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerLogin(packet, this.connection)) return; if (packet.intention() != ClientIntent.LOGIN) { throw new UnsupportedOperationException("Invalid intention " + packet.intention()); - } + } else { diff --git a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch index 002bd84c0c..58410340ef 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java -@@ -46,17 +_,20 @@ +@@ -47,17 +_,20 @@ 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 Component DISCONNECT_REASON_CONFIGURATION_ERROR = Component.translatable("multiplayer.disconnect.configuration_error"); @@ -21,16 +21,16 @@ } @Override -@@ -80,22 +_,27 @@ +@@ -81,22 +_,27 @@ return this.connection.isConnected(); } - public void startConfiguration() { + public void vanillaStart() { this.send(new ClientboundCustomPayloadPacket(new BrandPayload(this.server.getServerModName()))); - ServerLinks serverLinks = this.server.serverLinks(); - if (!serverLinks.isEmpty()) { - this.send(new ClientboundServerLinksPacket(serverLinks.untrust())); + ServerLinks serverlinks = this.server.serverLinks(); + if (!serverlinks.isEmpty()) { + this.send(new ClientboundServerLinksPacket(serverlinks.untrust())); } + this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); @@ -38,25 +38,25 @@ + + public void startConfiguration() { + net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.connection, this.configurationTasks::add); - LayeredRegistryAccess registries = this.server.registries(); - List knownPacks = this.server + LayeredRegistryAccess layeredregistryaccess = this.server.registries(); + List list = this.server .getResourceManager() .listPacks() .flatMap(packResources -> packResources.location().knownPackInfo().stream()) .toList(); - this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); - this.synchronizeRegistriesTask = new SynchronizeRegistriesTask(knownPacks, registries); + 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.returnToWorld(); } -@@ -213,7 +_,7 @@ - this.currentTask = task; +@@ -212,7 +_,7 @@ + this.currentTask = configurationtask; try { -- task.start(this::send); -+ task.start(this.taskContext); - } catch (Exception e) { - LOGGER.error("Failed to start configuration task {}", task.type(), e); +- configurationtask.start(this::send); ++ configurationtask.start(this.taskContext); + } catch (Exception exception) { + LOGGER.error("Failed to start configuration task {}", configurationtask.type(), exception); this.disconnect(DISCONNECT_REASON_CONFIGURATION_ERROR); diff --git a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch index 3e7eab4ee0..fb088035e7 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/network/ServerConnectionListener.java +++ b/net/minecraft/server/network/ServerConnectionListener.java -@@ -40,6 +_,7 @@ +@@ -38,6 +_,7 @@ import org.slf4j.Logger; public class ServerConnectionListener { @@ -8,30 +8,30 @@ private static final Logger LOGGER = LogUtils.getLogger(); private final MinecraftServer server; public volatile boolean running; -@@ -53,6 +_,8 @@ +@@ -50,6 +_,8 @@ } public void startTcpServerListener(final @Nullable InetAddress address, final int port) throws IOException { + var fixedAddress = address != null ? address : new java.net.InetSocketAddress(port).getAddress(); + net.minecraftforge.network.DualStackUtils.checkIPv6(fixedAddress); synchronized (this.channels) { - EventLoopGroupHolder eventLoopGroupHolder = EventLoopGroupHolder.remote(this.server.useNativeTransport()); - this.channels -@@ -68,7 +_,7 @@ - } catch (ChannelException var5) { - } + EventLoopGroupHolder eventloopgroupholder = EventLoopGroupHolder.remote(this.server.useNativeTransport()); + this.channels.add(new ServerBootstrap().channel(eventloopgroupholder.serverChannelCls()).childHandler(new ChannelInitializer() { +@@ -64,7 +_,7 @@ + } catch (ChannelException channelexception) { + } + +- ChannelPipeline channelpipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30)); ++ ChannelPipeline channelpipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)); + if (ServerConnectionListener.this.server.repliesToStatus()) { + channelpipeline.addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); + } +@@ -76,7 +_,7 @@ + connection.configurePacketHandler(channelpipeline); + connection.setListenerForServerboundHandshake(new ServerHandshakePacketListenerImpl(ServerConnectionListener.this.server, connection)); + } +- }).group(eventloopgroupholder.eventLoopGroup()).localAddress(address, port).bind().syncUninterruptibly()); ++ }).group(eventloopgroupholder.eventLoopGroup()).localAddress(fixedAddress, port).bind().syncUninterruptibly()); + } + } -- ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30)); -+ ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)); - if (ServerConnectionListener.this.server.repliesToStatus()) { - pipeline.addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); - } -@@ -87,7 +_,7 @@ - } - ) - .group(eventLoopGroupHolder.eventLoopGroup()) -- .localAddress(address, port) -+ .localAddress(fixedAddress, port) - .bind() - .syncUninterruptibly() - ); diff --git a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch index 41650457d9..433ba9e7a4 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java +++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java -@@ -1297,9 +_,10 @@ +@@ -1279,9 +_,10 @@ } case SWAP_ITEM_WITH_OFFHAND: if (!this.player.isSpectator()) { -- ItemStack swap = this.player.getItemInHand(InteractionHand.OFF_HAND); +- ItemStack itemstack1 = this.player.getItemInHand(InteractionHand.OFF_HAND); - this.player.setItemInHand(InteractionHand.OFF_HAND, this.player.getItemInHand(InteractionHand.MAIN_HAND)); -- this.player.setItemInHand(InteractionHand.MAIN_HAND, swap); +- this.player.setItemInHand(InteractionHand.MAIN_HAND, itemstack1); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this.player); + if (event == null) return; + this.player.setItemInHand(InteractionHand.OFF_HAND, event.getItemSwappedToOffHand()); @@ -14,18 +14,18 @@ this.player.stopUsingItem(); } -@@ -1515,8 +_,9 @@ +@@ -1503,8 +_,9 @@ } - CompletableFuture filteredFuture = this.filterTextPacket(signedMessage.signedContent()); -- Component decorated = this.server.getChatDecorator().decorate(this.player, signedMessage.decoratedContent()); -+ Component decorated = net.minecraftforge.common.ForgeHooks.onServerChatSubmittedEvent(this.player, signedMessage.decoratedContent()); - this.chatMessageChain.append(filteredFuture, filtered -> { -+ if (decorated == null) return; - PlayerChatMessage filteredMessage = signedMessage.withUnsignedContent(decorated).filter(filtered.mask()); - this.broadcastChatMessage(filteredMessage); + 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, filtered -> { ++ if (component == null) return; + PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(filtered.mask()); + this.broadcastChatMessage(playerchatmessage1); }); -@@ -2195,6 +_,7 @@ +@@ -2186,6 +_,7 @@ @Override public void handleCustomPayload(final ServerboundCustomPayloadPacket packet) { diff --git a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch index fc5b14c68f..e86aef9472 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch @@ -9,11 +9,11 @@ case LOGIN: this.beginLogin(packet, false); @@ -32,7 +_,7 @@ - ServerStatus status = this.server.getStatus(); + ServerStatus serverstatus = this.server.getStatus(); this.connection.setupOutboundProtocol(StatusProtocols.CLIENTBOUND); - if (this.server.repliesToStatus() && status != null) { -- this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(status, this.connection)); -+ this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(status, this.connection, this.server.getStatusJson())); + 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 7d3d662689..1ae4dbad0f 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java -@@ -188,7 +_,7 @@ - throw new IllegalStateException("Protocol error", e); +@@ -186,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()) { - @Override - public void run() { - String name = Objects.requireNonNull(ServerLoginPacketListenerImpl.this.requestedUsername, "Player name not initialized"); -@@ -234,6 +_,7 @@ + { + Objects.requireNonNull(ServerLoginPacketListenerImpl.this); + } +@@ -236,6 +_,7 @@ @Override public void handleCustomQueryPacket(final ServerboundCustomQueryAnswerPacket packet) { @@ -17,7 +17,7 @@ this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); } -@@ -256,6 +_,11 @@ +@@ -260,6 +_,11 @@ @Override public void handleCookieResponse(final ServerboundCookieResponsePacket packet) { this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); @@ -28,4 +28,4 @@ + return this.authenticatedProfile; } - private enum State { + private static enum State { diff --git a/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch b/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch index f23dea503a..9257f4abc3 100644 --- a/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch +++ b/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/network/config/PrepareSpawnTask.java +++ b/net/minecraft/server/network/config/PrepareSpawnTask.java -@@ -180,6 +_,7 @@ +@@ -192,6 +_,7 @@ .loadPlayerData(PrepareSpawnTask.this.nameAndId) - .map(tag -> TagValueInput.create(reporter, PrepareSpawnTask.this.server.registryAccess(), tag)); - input.ifPresent(player::load); -+ input.ifPresent(v -> net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(player, PrepareSpawnTask.this.server.getPlayerList().getPlayerIo().getPlayerDataFolder(), PrepareSpawnTask.this.nameAndId.id().toString())); - player.snapTo(this.spawnPosition, this.spawnAngle.x, this.spawnAngle.y); - PrepareSpawnTask.this.server.getPlayerList().placeNewPlayer(connection, player, cookie); - input.ifPresent(tag -> { + .map(tag -> TagValueInput.create(problemreporter$scopedcollector, PrepareSpawnTask.this.server.registryAccess(), tag)); + optional.ifPresent(serverplayer::load); ++ optional.ifPresent(v -> net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(serverplayer, PrepareSpawnTask.this.server.getPlayerList().getPlayerIo().getPlayerDataFolder(), PrepareSpawnTask.this.nameAndId.id().toString())); + serverplayer.snapTo(this.spawnPosition, this.spawnAngle.x, this.spawnAngle.y); + PrepareSpawnTask.this.server.getPlayerList().placeNewPlayer(connection, serverplayer, cookie); + optional.ifPresent(tag -> { diff --git a/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch b/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch index 2a159a9ae9..f468936039 100644 --- a/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/AbstractPackResources.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/packs/AbstractPackResources.java +++ b/net/minecraft/server/packs/AbstractPackResources.java -@@ -39,4 +_,9 @@ +@@ -42,4 +_,9 @@ public PackLocationInfo location() { return this.location; } 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 b30611ce73..da6e2cb239 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch @@ -16,16 +16,16 @@ } public static Pack.@Nullable Metadata readPackMetadata( -@@ -63,7 +_,7 @@ - PackCompatibility packCompatibility = PackCompatibility.forVersion(meta.supportedFormats(), currentPackVersion); - OverlayMetadataSection overlays = pack.getMetadataSection(OverlayMetadataSection.forPackType(type)); - List overlaySet = overlays != null ? overlays.overlaysForVersion(currentPackVersion) : List.of(); -- return new Pack.Metadata(meta.description(), packCompatibility, requiredFlags, overlaySet); -+ return new Pack.Metadata(meta.description(), packCompatibility, requiredFlags, overlaySet, pack.isHidden()); +@@ -66,7 +_,7 @@ + PackCompatibility packcompatibility = PackCompatibility.forVersion(packmetadatasection.supportedFormats(), currentPackVersion); + OverlayMetadataSection overlaymetadatasection = packresources.getMetadataSection(OverlayMetadataSection.forPackType(type)); + List list = overlaymetadatasection != null ? overlaymetadatasection.overlaysForVersion(currentPackVersion) : List.of(); +- pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list); ++ pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list, packresources.isHidden()); } - } catch (Exception e) { - LOGGER.warn("Failed to read pack {} metadata", location.id(), e); -@@ -123,6 +_,10 @@ + + return pack$metadata; +@@ -128,6 +_,10 @@ return this.location.source(); } @@ -36,7 +36,7 @@ @Override public boolean equals(final Object o) { if (this == o) { -@@ -137,7 +_,10 @@ +@@ -142,7 +_,10 @@ return this.location.hashCode(); } @@ -47,4 +47,4 @@ + } } - public 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 index 5f54eb5932..6b9c8166a6 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch @@ -8,20 +8,20 @@ + } + @Nullable + public T detectPackResources(Path content, List issues, boolean requireMeta) throws IOException { - Path targetContext = content; + Path path = content; - BasicFileAttributes attributes; + BasicFileAttributes basicfileattributes; @@ -43,10 +_,11 @@ if (!issues.isEmpty()) { return null; } else { -- return !Files.isRegularFile(targetContext.resolve("pack.mcmeta")) ? null : this.createDirectoryPack(targetContext); -+ return !Files.isRegularFile(targetContext.resolve("pack.mcmeta")) && requireMeta ? null : this.createDirectoryPack(targetContext); +- 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 attributes.isRegularFile() && targetContext.getFileName().toString().endsWith(".zip") ? this.createZipPack(targetContext) : null; -+ var name = targetContext.getFileName().toString(); -+ return attributes.isRegularFile() && (name.endsWith(".zip") || name.endsWith(".jar")) ? this.createZipPack(targetContext) : null; +- 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/resources/FallbackResourceManager.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch index a807929241..14fa10c6d6 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch @@ -3,21 +3,21 @@ @@ -103,8 +_,11 @@ for (int i = this.fallbacks.size() - 1; i >= 0; i--) { - FallbackResourceManager.PackEntry entry = this.fallbacks.get(i); -- PackResources fileSource = entry.resources; -- if (fileSource != null) { -+ PackResources pack = entry.resources; + 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 fileSource : packs) { - IoSupplier resource = fileSource.getResource(this.type, location); - if (resource != null) { - IoSupplier metadataGetter; ++ for (final PackResources packresources : packs) { + IoSupplier iosupplier = packresources.getResource(this.type, location); + if (iosupplier != null) { + IoSupplier iosupplier1; @@ -118,6 +_,7 @@ } - result.add(new Resource(fileSource, resource, metadataGetter)); + list.add(new Resource(packresources, iosupplier, iosupplier1)); + } } } 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 83fe9b302e..4454378c2a 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java +++ b/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java -@@ -32,6 +_,10 @@ +@@ -33,6 +_,10 @@ this(registries.createSerializationContext(JsonOps.INSTANCE), codec, FileToIdConverter.registry(registryKey)); } @@ -11,20 +11,20 @@ protected SimpleJsonResourceReloadListener(final Codec codec, final FileToIdConverter lister) { this(JsonOps.INSTANCE, codec, lister); } -@@ -66,7 +_,15 @@ - Identifier id = lister.fileToId(location); +@@ -67,7 +_,15 @@ + Identifier identifier1 = lister.fileToId(identifier); try (Reader reader = entry.getValue().openAsReader()) { - codec.parse(ops, StrictJsonParser.parse(reader)).ifSuccess(parsed -> { + var json = StrictJsonParser.parse(reader); + json = net.minecraftforge.common.ForgeHooks.readConditional(ops, json); + if (json == null) { -+ LOGGER.debug("Skipping loading {} as its conditions were not met", location); ++ LOGGER.debug("Skipping loading {} as its conditions were not met", identifier); + continue; + } + codec.parse(ops, json).ifSuccess(parsed -> { -+ parsed = net.minecraftforge.common.ForgeHooks.onJsonDataParsed(codec, id, parsed); ++ parsed = net.minecraftforge.common.ForgeHooks.onJsonDataParsed(codec, identifier1, parsed); + if (parsed == null) return; - if (result.putIfAbsent(id, (T)parsed) != null) { - throw new IllegalStateException("Duplicate data file ignored with ID " + id); + if (result.putIfAbsent(identifier1, (T)parsed) != null) { + throw new IllegalStateException("Duplicate data file ignored with ID " + identifier1); } diff --git a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch index b5c17dc1d1..22610a76a5 100644 --- a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch +++ b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch @@ -1,54 +1,53 @@ --- a/net/minecraft/server/players/PlayerList.java +++ b/net/minecraft/server/players/PlayerList.java -@@ -126,6 +_,8 @@ +@@ -127,6 +_,7 @@ private int simulationDistance; private boolean allowCommandsForAllPlayers; private int sendAllPlayerInfoIn; + private final List playersView = java.util.Collections.unmodifiableList(players); -+ private final Map playersByUUIDView = java.util.Collections.unmodifiableMap(this.playersByUUID); public PlayerList( final MinecraftServer server, -@@ -189,6 +_,7 @@ - playerConnection.send(new ClientboundPlayerAbilitiesPacket(player.getAbilities())); - playerConnection.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot())); - RecipeManager recipeManager = this.server.getRecipeManager(); +@@ -184,6 +_,7 @@ + servergamepacketlistenerimpl.send(new ClientboundPlayerAbilitiesPacket(player.getAbilities())); + servergamepacketlistenerimpl.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot())); + RecipeManager recipemanager = this.server.getRecipeManager(); + net.minecraftforge.event.OnDatapackSyncEvent.BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, player)); - playerConnection.send( - new ClientboundUpdateRecipesPacket(recipeManager.getSynchronizedItemProperties(), recipeManager.getSynchronizedStonecutterRecipes()) + servergamepacketlistenerimpl.send( + new ClientboundUpdateRecipesPacket(recipemanager.getSynchronizedItemProperties(), recipemanager.getSynchronizedStonecutterRecipes()) ); -@@ -222,6 +_,7 @@ +@@ -217,6 +_,7 @@ player.initInventoryMenu(); this.server.notificationManager().playerJoined(player); - playerConnection.resumeFlushing(); + servergamepacketlistenerimpl.resumeFlushing(); + net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedIn(player); } protected void updateEntireScoreboard(final ServerScoreboard scoreboard, final ServerPlayer player) { -@@ -291,6 +_,7 @@ +@@ -290,6 +_,7 @@ } protected void save(final ServerPlayer player) { + if (player.connection == null) return; // Not sure if still needed -Paint_Ninja this.playerIo.save(player); - ServerStatsCounter stats = this.stats.get(player.getUUID()); - if (stats != null) { -@@ -304,6 +_,7 @@ + ServerStatsCounter serverstatscounter = this.stats.get(player.getUUID()); + if (serverstatscounter != null) { +@@ -303,6 +_,7 @@ } public void remove(final ServerPlayer player) { + net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedOut(player); - ServerLevel level = player.level(); + ServerLevel serverlevel = player.level(); player.awardStat(Stats.LEAVE_GAME); this.save(player); @@ -429,6 +_,7 @@ - this.playersByUUID.put(player.getUUID(), player); - player.initInventoryMenu(); - player.setHealth(player.getHealth()); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(player, keepAllPlayerData); - ServerPlayer.RespawnConfig respawnConfig = player.getRespawnConfig(); - if (!keepAllPlayerData && respawnConfig != null) { - LevelData.RespawnData respawnData = respawnConfig.respawnData(); + this.playersByUUID.put(serverplayer.getUUID(), serverplayer); + serverplayer.initInventoryMenu(); + serverplayer.setHealth(serverplayer.getHealth()); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(serverplayer, keepAllPlayerData); + ServerPlayer.RespawnConfig serverplayer$respawnconfig = serverplayer.getRespawnConfig(); + if (!keepAllPlayerData && serverplayer$respawnconfig != null) { + LevelData.RespawnData leveldata$respawndata = serverplayer$respawnconfig.respawnData(); @@ -542,6 +_,7 @@ } @@ -63,9 +62,9 @@ public void deop(final NameAndId nameAndId) { + if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(nameAndId, null, this)) return; if (this.ops.remove(nameAndId)) { - ServerPlayer player = this.getPlayer(nameAndId.id()); - if (player != null) { -@@ -826,11 +_,11 @@ + ServerPlayer serverplayer = this.getPlayer(nameAndId.id()); + if (serverplayer != null) { +@@ -824,7 +_,7 @@ } public List getPlayers() { @@ -73,21 +72,16 @@ + return this.playersView; //Unmodifiable view, we don't want people removing things without us knowing. } - public Map getPlayersByUUID() { -- return this.playersByUUID; -+ return this.playersByUUIDView; //Unmodifiable view, we don't want people removing things without us knowing. - } - public @Nullable ServerPlayer getPlayer(final UUID uuid) { -@@ -856,6 +_,7 @@ - advancements.reload(this.server.getAdvancements()); +@@ -850,6 +_,7 @@ + playeradvancements.reload(this.server.getAdvancements()); } + net.minecraftforge.event.OnDatapackSyncEvent.BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, null)); this.broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.registries))); - RecipeManager recipeManager = this.server.getRecipeManager(); - ClientboundUpdateRecipesPacket recipes = new ClientboundUpdateRecipesPacket( -@@ -870,5 +_,9 @@ + RecipeManager recipemanager = this.server.getRecipeManager(); + ClientboundUpdateRecipesPacket clientboundupdaterecipespacket = new ClientboundUpdateRecipesPacket( +@@ -864,5 +_,9 @@ public boolean isAllowCommandsForAllPlayers() { return this.allowCommandsForAllPlayers; 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 04cc437302..f71c9d0feb 100644 --- a/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch +++ b/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch @@ -4,14 +4,14 @@ } private void sendCmdResponse(final int requestid, String response) throws IOException { -- int len = response.length(); +- int i = response.length(); - - do { -- int dataLen = 4096 <= len ? 4096 : len; -- this.send(requestid, 0, response.substring(0, dataLen)); -- response = response.substring(dataLen); -- len = response.length(); -- } while (0 != len); +- int j = 4096 <= i ? 4096 : i; +- this.send(requestid, 0, response.substring(0, j)); +- response = response.substring(j); +- i = response.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 = response.getBytes(StandardCharsets.UTF_8); + for (int x = 0; x < data.length; x += 4096) { diff --git a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch index 47a0e6e6d6..f77d3f93c9 100644 --- a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch +++ b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/stats/RecipeBookSettings.java +++ b/net/minecraft/stats/RecipeBookSettings.java -@@ -11,6 +_,7 @@ +@@ -12,6 +_,7 @@ import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.inventory.RecipeBookType; @@ -8,7 +8,7 @@ public final class RecipeBookSettings { public static final StreamCodec STREAM_CODEC = StreamCodec.composite( RecipeBookSettings.TypeSettings.STREAM_CODEC, -@@ -149,5 +_,13 @@ +@@ -150,5 +_,13 @@ .apply(i, RecipeBookSettings.TypeSettings::new) ); } diff --git a/patches/minecraft/net/minecraft/tags/DamageTypeTags.java.patch b/patches/minecraft/net/minecraft/tags/DamageTypeTags.java.patch index de766c6d43..55c5476327 100644 --- a/patches/minecraft/net/minecraft/tags/DamageTypeTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/DamageTypeTags.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/tags/DamageTypeTags.java +++ b/net/minecraft/tags/DamageTypeTags.java -@@ -44,4 +_,12 @@ +@@ -43,4 +_,12 @@ private static TagKey create(final String name) { return TagKey.create(Registries.DAMAGE_TYPE, Identifier.withDefaultNamespace(name)); } diff --git a/patches/minecraft/net/minecraft/tags/EntityTypeTags.java.patch b/patches/minecraft/net/minecraft/tags/EntityTypeTags.java.patch index deef29fb0b..02445ad445 100644 --- a/patches/minecraft/net/minecraft/tags/EntityTypeTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/EntityTypeTags.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/tags/EntityTypeTags.java +++ b/net/minecraft/tags/EntityTypeTags.java -@@ -57,4 +_,12 @@ +@@ -56,4 +_,12 @@ private static TagKey> create(final String name) { return TagKey.create(Registries.ENTITY_TYPE, Identifier.withDefaultNamespace(name)); } diff --git a/patches/minecraft/net/minecraft/tags/ItemTags.java.patch b/patches/minecraft/net/minecraft/tags/ItemTags.java.patch index 508c67264a..78eef07590 100644 --- a/patches/minecraft/net/minecraft/tags/ItemTags.java.patch +++ b/patches/minecraft/net/minecraft/tags/ItemTags.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/tags/ItemTags.java +++ b/net/minecraft/tags/ItemTags.java -@@ -220,4 +_,12 @@ +@@ -219,4 +_,12 @@ private static TagKey bind(final String name) { return TagKey.create(Registries.ITEM, Identifier.withDefaultNamespace(name)); } diff --git a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch index a329bd19e0..e99dec29b2 100644 --- a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/tags/TagEntry.java +++ b/net/minecraft/tags/TagEntry.java -@@ -107,6 +_,18 @@ - return result.toString(); +@@ -108,6 +_,18 @@ + return stringbuilder.toString(); } + public Identifier getId() { diff --git a/patches/minecraft/net/minecraft/tags/TagFile.java.patch b/patches/minecraft/net/minecraft/tags/TagFile.java.patch index 1e7f9fbbd6..c433a0085c 100644 --- a/patches/minecraft/net/minecraft/tags/TagFile.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagFile.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/tags/TagFile.java +++ b/net/minecraft/tags/TagFile.java -@@ -4,11 +_,16 @@ - import com.mojang.serialization.codecs.RecordCodecBuilder; +@@ -5,11 +_,16 @@ + import com.mojang.serialization.codecs.RecordCodecBuilder.Instance; import java.util.List; -public record TagFile(List entries, boolean replace) { diff --git a/patches/minecraft/net/minecraft/tags/TagKey.java.patch b/patches/minecraft/net/minecraft/tags/TagKey.java.patch index 9ae3dab205..6d37669408 100644 --- a/patches/minecraft/net/minecraft/tags/TagKey.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagKey.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/tags/TagKey.java +++ b/net/minecraft/tags/TagKey.java -@@ -38,6 +_,10 @@ +@@ -40,6 +_,10 @@ return (TagKey)VALUES.intern(new TagKey<>(registry, location)); } diff --git a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch index f086720b23..1335999ca2 100644 --- a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch @@ -2,34 +2,34 @@ +++ b/net/minecraft/tags/TagLoader.java @@ -64,6 +_,7 @@ - String sourceId = resource.sourcePackId(); - parsedContents.entries().forEach(ex -> tagContents.add(new TagLoader.EntryWithSource(ex, sourceId))); -+ parsedContents.remove().forEach(e -> tagContents.add(new TagLoader.EntryWithSource(e, sourceId, true))); - } catch (Exception e) { - LOGGER.error("Couldn't read tag list {} from {} in data pack {}", id, location, resource.sourcePackId(), e); + String s = resource.sourcePackId(); + tagfile.entries().forEach(ex -> list.add(new TagLoader.EntryWithSource(ex, 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 {}", identifier1, identifier, resource.sourcePackId(), exception); } @@ -74,16 +_,17 @@ } private Either, List> tryBuildTag(final TagEntry.Lookup lookup, final List entries) { -- SequencedSet values = new LinkedHashSet<>(); +- SequencedSet sequencedset = new LinkedHashSet<>(); + 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 missingElements = new ArrayList<>(); + List list = new ArrayList<>(); - for (TagLoader.EntryWithSource entry : entries) { -- if (!entry.entry().build(lookup, values::add)) { -+ if (!entry.entry().build(lookup, entry.remove() ? builder::remove : builder::add)) { -+ if (!entry.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added. - missingElements.add(entry); + for (TagLoader.EntryWithSource tagloader$entrywithsource : entries) { +- if (!tagloader$entrywithsource.entry().build(lookup, sequencedset::add)) { ++ if (!tagloader$entrywithsource.entry().build(lookup, 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); } } -- return missingElements.isEmpty() ? Either.right(List.copyOf(values)) : Either.left(missingElements); -+ return missingElements.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(missingElements); +- return list.isEmpty() ? Either.right(List.copyOf(sequencedset)) : Either.left(list); ++ return list.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(list); } public Map> build(final Map> builders) { -@@ -107,7 +_,7 @@ +@@ -111,7 +_,7 @@ missing -> LOGGER.error( "Couldn't load tag {} as it is missing following references: {}", id, @@ -37,8 +37,8 @@ + missing.stream().map(Objects::toString).collect(Collectors.joining(", \n\t")) ) ) - .ifRight(tag -> newTags.put(id, (List)tag)) -@@ -188,7 +_,11 @@ + .ifRight(tag -> map.put(id, (List)tag)) +@@ -192,7 +_,11 @@ } } diff --git a/patches/minecraft/net/minecraft/util/LightCoordsUtil.java.patch b/patches/minecraft/net/minecraft/util/LightCoordsUtil.java.patch index 353e0d4a23..14dce9ae6e 100644 --- a/patches/minecraft/net/minecraft/util/LightCoordsUtil.java.patch +++ b/patches/minecraft/net/minecraft/util/LightCoordsUtil.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/util/LightCoordsUtil.java +++ b/net/minecraft/util/LightCoordsUtil.java -@@ -15,7 +_,7 @@ +@@ -10,7 +_,7 @@ } public static int block(final int packed) { @@ -9,12 +9,3 @@ } public static int sky(final int packed) { -@@ -115,7 +_,7 @@ - - int packedBrightness = brightnessGetter.packedBrightness(level, pos); - int block = block(packedBrightness); -- int blockSelfEmission = state.getLightEmission(); -+ int blockSelfEmission = state.getLightEmission(level, pos); - return block < blockSelfEmission ? withBlock(packedBrightness, blockSelfEmission) : packedBrightness; - } - diff --git a/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch b/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch index f55901cfa1..cd4174cc55 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 -@@ -39,7 +_,7 @@ - && (!checkCollisions || level.noCollision(entityType.getSpawnAABB(searchPos.getX() + 0.5, searchPos.getY(), searchPos.getZ() + 0.5)))) { - T mob = (T)entityType.create(level, null, searchPos, spawnReason, false, false); - if (mob != null) { -- if (mob.checkSpawnRules(level, spawnReason) && mob.checkSpawnObstruction(level)) { -+ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, level, spawnReason)) { - level.addFreshEntityWithPassengers(mob); - mob.playAmbientSound(); - return Optional.of(mob); +@@ -46,7 +_,7 @@ + )) { + T t = (T)entityType.create(level, null, blockpos$mutableblockpos, spawnReason, false, false); + if (t != null) { +- if (t.checkSpawnRules(level, spawnReason) && t.checkSpawnObstruction(level)) { ++ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(t, level, spawnReason)) { + level.addFreshEntityWithPassengers(t); + t.playAmbientSound(); + return Optional.of(t); diff --git a/patches/minecraft/net/minecraft/util/Util.java.patch b/patches/minecraft/net/minecraft/util/Util.java.patch index 51be679f5f..4c71772978 100644 --- a/patches/minecraft/net/minecraft/util/Util.java.patch +++ b/patches/minecraft/net/minecraft/util/Util.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/util/Util.java +++ b/net/minecraft/util/Util.java -@@ -313,7 +_,7 @@ +@@ -272,7 +_,7 @@ .getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version())) .getChoiceType(reference, name); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException illegalargumentexception) { - LOGGER.error("No data fixer registered for {}", name); + LOGGER.debug("No data fixer registered for {}", name); if (SharedConstants.IS_RUNNING_IN_IDE) { - throw e; + throw illegalargumentexception; } 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 3ac8a74494..fef9c41c15 100644 --- a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch +++ b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java +++ b/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java @@ -178,7 +_,16 @@ - String key = dynamicKey.asString("UNKNOWN").toLowerCase(Locale.ROOT); - StructuresBecomeConfiguredFix.Conversion conversion = CONVERSION_MAP.get(key); - if (conversion == null) { + String s = dynamicKey.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 -+ conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(key); ++ structuresbecomeconfiguredfix$conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(s); + } -+ if (conversion == null) { -+ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(key)) { ++ if (structuresbecomeconfiguredfix$conversion == null) { ++ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(s)) { + // Forge: pass-through structure IDs which have a non-"minecraft" namespace -+ return chunk.createString(key); ++ return chunk.createString(s); + } + // Forge: Pass-through with "unknown." prefix, so deserializer logs and ignores rather than fixer throwing an exception and dropping chunk data -+ return chunk.createString("unknown." + key); - } - - String resultingId = conversion.fallback; ++ return chunk.createString("unknown." + s); + } else { + String s1 = structuresbecomeconfiguredfix$conversion.fallback; + if (!structuresbecomeconfiguredfix$conversion.biomeMapping().isEmpty()) { diff --git a/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch b/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch index 4ed55e4c00..a5b6de6ba7 100644 --- a/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch +++ b/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch @@ -9,8 +9,8 @@ private static final int FLAT_THRESHOLD = 64; private final int totalWeight; private final List> items; -@@ -153,7 +_,7 @@ - return 31 * result + this.items.hashCode(); +@@ -145,7 +_,7 @@ + return 31 * i + this.items.hashCode(); } - public static class Builder { diff --git a/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch b/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch index 1295489d46..ecf700f126 100644 --- a/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch +++ b/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/clock/ServerClockManager.java +++ b/net/minecraft/world/clock/ServerClockManager.java @@ -97,6 +_,12 @@ - return set.booleanValue(); + return mutableboolean.booleanValue(); } + public long getTimeMarker(final Holder clock, final ResourceKey timeMarkerId) { diff --git a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch index 44c3932444..c1d201134c 100644 --- a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch +++ b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch @@ -11,8 +11,8 @@ public static final StreamCodec> STREAM_CODEC = ByteBufCodecs.holderRegistry(Registries.MOB_EFFECT); private static final int AMBIENT_ALPHA = Mth.floor(38.25F); @@ -58,12 +_,14 @@ - int alpha = effectInstance.isAmbient() ? AMBIENT_ALPHA : 255; - return ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.color(alpha, color)); + int i = effectInstance.isAmbient() ? AMBIENT_ALPHA : 255; + return ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.color(i, color)); }; + initClient(); } diff --git a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch index 902b817cac..1fdc617ab7 100644 --- a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/Entity.java +++ b/net/minecraft/world/entity/Entity.java -@@ -156,7 +_,9 @@ +@@ -160,7 +_,9 @@ import org.slf4j.Logger; public abstract class Entity @@ -10,16 +10,16 @@ EntityAccess, ScoreHolder, SyncedDataHolder, -@@ -205,6 +_,7 @@ +@@ -206,6 +_,7 @@ private static final int MAX_BLOCK_ITERATIONS_ALONG_TRAVEL_PER_TICK = 16; private static final double MAX_MOVEMENT_RESETTING_TRACE_DISTANCE = 8.0; private static double viewScale = 1.0; + @Deprecated // Forge: Use the getter to allow overriding in mods private final EntityType type; private boolean requiresPrecisePosition; - private int id = 0; -@@ -322,6 +_,8 @@ - this.entityData = entityDataBuilder.build(); + private int id = ENTITY_COUNTER.incrementAndGet(); +@@ -321,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); @@ -27,7 +27,7 @@ } public boolean isColliding(final BlockPos pos, final BlockState state) { -@@ -429,6 +_,7 @@ +@@ -424,6 +_,7 @@ public void remove(final Entity.RemovalReason reason) { this.setRemoved(reason); @@ -35,7 +35,7 @@ } public void onClientRemoval() { -@@ -548,7 +_,7 @@ +@@ -543,7 +_,7 @@ } if (this.isInLava()) { @@ -44,44 +44,44 @@ } this.checkBelowWorld(); -@@ -1064,9 +_,7 @@ +@@ -999,9 +_,7 @@ + return blockpos; + } else { + BlockState blockstate = this.level().getBlockState(blockpos); +- return (!(offset <= 0.5) || !blockstate.is(BlockTags.FENCES)) +- && !blockstate.is(BlockTags.WALLS) +- && !(blockstate.getBlock() instanceof FenceGateBlock) ++ return (!((double)offset <= 0.5) || !blockstate.collisionExtendsVertically(this.level(), blockpos, this)) + ? blockpos.atY(Mth.floor(this.position.y - offset)) + : blockpos; } - - BlockState belowState = this.level().getBlockState(getOnPos); -- return (!(offset <= 0.5) || !belowState.is(BlockTags.FENCES)) -- && !belowState.is(BlockTags.WALLS) -- && !(belowState.getBlock() instanceof FenceGateBlock) -+ return (!((double)offset <= 0.5) || !belowState.collisionExtendsVertically(this.level(), getOnPos, this)) - ? getOnPos.atY(Mth.floor(this.position.y - offset)) - : getOnPos; - } else { -@@ -1447,19 +_,19 @@ - return !aboveState.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !aboveState.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? affectingPos : abovePos; +@@ -1356,19 +_,19 @@ + return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? affectingPos : blockpos; } - protected void playCombinationStepSounds(final BlockState primaryStepSound, final BlockState secondaryStepSound) { -- SoundType primaryStepSoundType = primaryStepSound.getSoundType(); +- SoundType soundtype = primaryStepSound.getSoundType(); + protected void playCombinationStepSounds(final BlockState primaryStepSound, final BlockState secondaryStepSound, final BlockPos primaryPos, final BlockPos secondaryPos) { -+ SoundType primaryStepSoundType = primaryStepSound.getSoundType(this.level(), primaryPos, this); - this.playSound(primaryStepSoundType.getStepSound(), primaryStepSoundType.getVolume() * 0.15F, primaryStepSoundType.getPitch()); ++ SoundType soundtype = primaryStepSound.getSoundType(this.level(), primaryPos, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); - this.playMuffledStepSound(secondaryStepSound); + this.playMuffledStepSound(secondaryStepSound, secondaryPos); } - protected void playMuffledStepSound(final BlockState blockState) { -- SoundType secondaryStepSoundType = blockState.getSoundType(); +- SoundType soundtype = blockState.getSoundType(); + protected void playMuffledStepSound(final BlockState blockState, final BlockPos pos) { -+ SoundType secondaryStepSoundType = blockState.getSoundType(this.level(), pos, this); - this.playSound(secondaryStepSoundType.getStepSound(), secondaryStepSoundType.getVolume() * 0.05F, secondaryStepSoundType.getPitch() * 0.8F); ++ SoundType soundtype = blockState.getSoundType(this.level(), pos, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.05F, soundtype.getPitch() * 0.8F); } protected void playStepSound(final BlockPos pos, final BlockState blockState) { -- SoundType soundType = blockState.getSoundType(); -+ SoundType soundType = blockState.getSoundType(this.level(), pos, this); - this.playSound(soundType.getStepSound(), soundType.getVolume() * 0.15F, soundType.getPitch()); +- SoundType soundtype = blockState.getSoundType(); ++ SoundType soundtype = blockState.getSoundType(this.level(), pos, this); + this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); } -@@ -1598,6 +_,10 @@ +@@ -1503,6 +_,10 @@ return this.wasTouchingWater; } @@ -89,10 +89,10 @@ + return this.isInWater() || isInFluidType((fluidType, height) -> canSwimInFluidType(fluidType)); + } + - private boolean isInRain() { - BlockPos pos = this.blockPosition(); - return this.level().isRainingAt(pos) || this.level().isRainingAt(BlockPos.containing(pos.getX(), this.getBoundingBox().maxY, pos.getZ())); -@@ -1635,10 +_,10 @@ + boolean isInRain() { + BlockPos blockpos = this.blockPosition(); + return this.level().isRainingAt(blockpos) +@@ -1541,10 +_,10 @@ public void updateSwimming() { if (this.isSwimming()) { @@ -105,25 +105,25 @@ ); } } -@@ -1655,16 +_,7 @@ +@@ -1561,16 +_,7 @@ } - this.wasTouchingWater = inWater; + this.wasTouchingWater = flag; - if (this.isPushedByFluid()) { -- if (inWater) { +- if (flag) { - this.fluidInteraction.applyCurrentTo(FluidTags.WATER, this, 0.014); - } - -- if (inLava) { -- double lavaFlowScale = this.level.environmentAttributes().getDimensionValue(EnvironmentAttributes.FAST_LAVA) ? 0.007 : 0.0023333333333333335; -- this.fluidInteraction.applyCurrentTo(FluidTags.LAVA, this, lavaFlowScale); +- if (flag1) { +- double d0 = this.level.environmentAttributes().getDimensionValue(EnvironmentAttributes.FAST_LAVA) ? 0.007 : 0.0023333333333333335; +- this.fluidInteraction.applyCurrentTo(FluidTags.LAVA, this, d0); - } - } + this.fluidInteraction.applyCurrentTo(this); - return inWater || inLava; + return flag || flag1; } -@@ -1712,12 +_,13 @@ +@@ -1614,12 +_,13 @@ } public boolean canSpawnSprintParticle() { @@ -132,22 +132,22 @@ } protected void spawnSprintParticle() { - BlockPos pos = this.getOnPosLegacy(); - BlockState blockState = this.level().getBlockState(pos); -+ if (!blockState.addRunningEffects(level, pos, this)) - if (blockState.getRenderShape() != RenderShape.INVISIBLE) { - Vec3 movement = this.getDeltaMovement(); - BlockPos entityPosition = this.blockPosition(); -@@ -1732,7 +_,7 @@ + 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(); +@@ -1633,7 +_,7 @@ + d1 = Mth.clamp(d1, (double)blockpos.getZ(), blockpos.getZ() + 1.0); } - this.level() -- .addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockState), x, this.getY() + 0.1, z, movement.x * -4.0, 1.5, movement.z * -4.0); -+ .addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockState).setPos(pos), x, this.getY() + 0.1, z, movement.x * -4.0, 1.5, movement.z * -4.0); +- this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate), d0, this.getY() + 0.1, d1, vec3.x * -4.0, 1.5, vec3.z * -4.0); ++ this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate).setPos(blockpos), d0, this.getY() + 0.1, d1, vec3.x * -4.0, 1.5, vec3.z * -4.0); } } -@@ -2113,6 +_,10 @@ +@@ -2010,6 +_,10 @@ output.putBoolean("HasVisualFire", this.hasVisualFire); } @@ -158,7 +158,7 @@ if (!this.tags.isEmpty()) { output.store("Tags", TAG_LIST_CODEC, List.copyOf(this.tags)); } -@@ -2184,6 +_,9 @@ +@@ -2077,6 +_,9 @@ this.setGlowingTag(input.getBooleanOr("Glowing", false)); this.setTicksFrozen(input.getIntOr("TicksFrozen", 0)); this.hasVisualFire = input.getBooleanOr("HasVisualFire", false); @@ -168,30 +168,30 @@ this.customData = input.read("data", CustomData.CODEC).orElse(CustomData.EMPTY); this.tags.clear(); input.read("Tags", TAG_LIST_CODEC).ifPresent(this.tags::addAll); -@@ -2234,6 +_,8 @@ - - ItemEntity entity = new ItemEntity(level, this.getX() + offset.x, this.getY() + offset.y, this.getZ() + offset.z, itemStack); - entity.setDefaultPickUpDelay(); -+ if (captureDrops() != null) captureDrops().add(entity); -+ else - level.addFreshEntity(entity); - return entity; - } -@@ -2291,11 +_,11 @@ +@@ -2126,6 +_,8 @@ + } else { + ItemEntity itementity = new ItemEntity(level, this.getX() + offset.x, this.getY() + offset.y, this.getZ() + offset.z, itemStack); + itementity.setDefaultPickUpDelay(); ++ if (captureDrops() != null) captureDrops().add(itementity); ++ else + level.addFreshEntity(itementity); + return itementity; + } +@@ -2184,11 +_,11 @@ } - ItemStack heldItem = player.getItemInHand(hand); -- if (heldItem.is(Items.SHEARS) && this.shearOffAllLeashConnections(player)) { -+ if (heldItem.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.shearOffAllLeashConnections(player)) { - heldItem.hurtAndBreak(1, player, hand); + ItemStack itemstack = player.getItemInHand(hand); +- if (itemstack.is(Items.SHEARS) && this.shearOffAllLeashConnections(player)) { ++ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.shearOffAllLeashConnections(player)) { + itemstack.hurtAndBreak(1, player, hand); return InteractionResult.SUCCESS; - } else if (this instanceof Mob target -- && heldItem.is(Items.SHEARS) -+ && heldItem.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) - && target.canShearEquipment(player) + } else if (this instanceof Mob mob +- && itemstack.is(Items.SHEARS) ++ && itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) + && mob.canShearEquipment(player) && !player.isSecondaryUseActive() - && target.attemptToShearEquipment(player, hand, heldItem)) { -@@ -2379,6 +_,7 @@ + && this.attemptToShearEquipment(player, hand, itemstack, mob)) { +@@ -2296,6 +_,7 @@ public void rideTick() { this.setDeltaMovement(Vec3.ZERO); @@ -199,23 +199,23 @@ this.tick(); if (this.isPassenger()) { this.getVehicle().positionRider(this); -@@ -2444,6 +_,7 @@ +@@ -2356,6 +_,7 @@ + } } - } -+ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entityToRide, true)) return false; - if (force || this.canRide(entityToRide) && entityToRide.canAddPassenger(this)) { - if (this.isPassenger()) { - this.stopRiding(); -@@ -2478,6 +_,7 @@ ++ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entityToRide, true)) return false; + if (force || this.canRide(entityToRide) && entityToRide.canAddPassenger(this)) { + if (this.isPassenger()) { + this.stopRiding(); +@@ -2391,6 +_,7 @@ public void removeVehicle() { if (this.vehicle != null) { - Entity oldVehicle = this.vehicle; -+ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, oldVehicle, false)) return; + Entity entity = this.vehicle; ++ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entity, false)) return; this.vehicle = null; - oldVehicle.removePassenger(this); - Entity.RemovalReason removalReason = this.getRemovalReason(); -@@ -2528,6 +_,8 @@ + entity.removePassenger(this); + Entity.RemovalReason entity$removalreason = this.getRemovalReason(); +@@ -2441,6 +_,8 @@ return this.passengers.isEmpty(); } @@ -224,7 +224,7 @@ protected boolean couldAcceptPassenger() { return true; } -@@ -2724,7 +_,7 @@ +@@ -2638,7 +_,7 @@ } public boolean isVisuallyCrawling() { @@ -233,7 +233,7 @@ } public void setSwimming(final boolean swimming) { -@@ -2840,7 +_,7 @@ +@@ -2754,7 +_,7 @@ this.igniteForSeconds(8.0F); } @@ -242,7 +242,7 @@ } public void onAboveBubbleColumn(final boolean dragDown, final BlockPos pos) { -@@ -2959,7 +_,7 @@ +@@ -2881,7 +_,7 @@ } protected Component getTypeName() { @@ -251,7 +251,7 @@ } public boolean is(final Entity other) { -@@ -3272,6 +_,7 @@ +@@ -3191,6 +_,7 @@ return this.stringUUID; } @@ -259,7 +259,7 @@ public boolean isPushedByFluid() { return true; } -@@ -3682,6 +_,10 @@ +@@ -3597,6 +_,10 @@ return this.fluidInteraction.getFluidHeight(type); } @@ -270,7 +270,7 @@ public double getFluidJumpThreshold() { return this.getEyeHeight() < 0.4 ? 0.0 : 0.4; } -@@ -3694,7 +_,9 @@ +@@ -3609,7 +_,9 @@ return this.dimensions.height(); } @@ -280,7 +280,7 @@ return new ClientboundAddEntityPacket(this, serverEntity); } -@@ -3833,6 +_,11 @@ +@@ -3748,6 +_,11 @@ } } } @@ -292,10 +292,10 @@ } public void checkDespawn() { -@@ -4007,6 +_,83 @@ - float xRot = (float)Mth.lerp(alpha, this.getXRot(), targetXRot); - this.setPos(x, y, z); - this.setRot(yRot, xRot); +@@ -3922,6 +_,83 @@ + float f1 = (float)Mth.lerp(d0, (double)this.getXRot(), targetXRot); + this.setPos(d1, d2, d3); + this.setRot(f, f1); + } + + private boolean canUpdate = true; diff --git a/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch index 98afa9846c..e958dcde14 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/EntityEquipment.java @@ -49,7 +_,7 @@ for (Entry entry : this.items.entrySet()) { - ItemStack item = entry.getValue(); - if (!item.isEmpty()) { -- item.inventoryTick(owner.level(), owner, entry.getKey()); -+ item.inventoryTick(owner.level(), owner, entry.getKey(), -1); + ItemStack itemstack = entry.getValue(); + if (!itemstack.isEmpty()) { +- itemstack.inventoryTick(owner.level(), owner, entry.getKey()); ++ itemstack.inventoryTick(owner.level(), owner, entry.getKey(), -1); } } } diff --git a/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch index 54d1aa113e..547a540d04 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch @@ -18,8 +18,8 @@ + private net.minecraftforge.fluids.FluidType eyeFluid = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); public EntityFluidInteraction(final Set> fluids) { - for (TagKey fluid : fluids) { - this.trackerByFluid.put(fluid, new EntityFluidInteraction.Tracker()); + for (TagKey tagkey : fluids) { + this.trackerByFluid.put(tagkey, new EntityFluidInteraction.Tracker()); } + for (var entry : MODDED_TYPES.entrySet()) { + if (!fluids.contains(entry.getKey())) @@ -37,51 +37,51 @@ + this.isInFluid = false; + this.eyeFluid = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); + - AABB box = entity.getFluidInteractionBox(); - if (box != null) { - int x0 = Mth.floor(box.minX); + AABB aabb = entity.getFluidInteractionBox(); + if (aabb != null) { + int i = Mth.floor(aabb.minX); @@ -45,7 +_,7 @@ - double eyeY = entity.getEyeY(); - int eyeBlockZ = entity.getBlockZ(); - Fluid lastFluidType = null; -- EntityFluidInteraction.Tracker tracker = null; + double d1 = entity.getEyeY(); + int l1 = entity.getBlockZ(); + Fluid fluid = null; +- EntityFluidInteraction.Tracker entityfluidinteraction$tracker = null; + EntityFluidInteraction.Tracker[] trackers = null; - BlockGetter level = entity.level(); - BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); + BlockGetter blockgetter = entity.level(); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); @@ -55,23 +_,26 @@ - mutablePos.set(x, y, z); - FluidState fluidState = level.getFluidState(mutablePos); - if (!fluidState.isEmpty()) { + blockpos$mutableblockpos.set(i2, j2, k2); + FluidState fluidstate = blockgetter.getFluidState(blockpos$mutableblockpos); + if (!fluidstate.isEmpty()) { + isInFluid = true; - double fluidBottom = mutablePos.getY(); - double fluidTop = fluidBottom + fluidState.getHeight(level, mutablePos); - if (!(fluidTop < box.minY)) { - Fluid fluidType = fluidState.getType(); - if (fluidType != lastFluidType) { - lastFluidType = fluidType; -- tracker = this.getTrackerFor(fluidType); -+ trackers = this.getTrackersFor(fluidType); + double d2 = blockpos$mutableblockpos.getY(); + double d3 = d2 + fluidstate.getHeight(blockgetter, blockpos$mutableblockpos); + if (!(d3 < aabb.minY)) { + Fluid fluid1 = fluidstate.getType(); + if (fluid1 != fluid) { + fluid = fluid1; +- entityfluidinteraction$tracker = this.getTrackerFor(fluid1); ++ trackers = this.getTrackersFor(fluid1); } -- if (tracker != null) { -+ for (var tracker : trackers) { - if (x == eyeBlockX && z == eyeBlockZ && eyeY >= fluidBottom && eyeY <= fluidTop) { - tracker.eyesInside = true; -+ this.eyeFluid = lastFluidType.getFluidType(); +- if (entityfluidinteraction$tracker != null) { ++ for (var entityfluidinteraction$tracker : trackers) { + if (i2 == k1 && k2 == l1 && d1 >= d2 && d1 <= d3) { + entityfluidinteraction$tracker.eyesInside = true; ++ this.eyeFluid = fluid.getFluidType(); } - tracker.height = Math.max(fluidTop - entityY, tracker.height); + entityfluidinteraction$tracker.height = Math.max(d3 - d0, entityfluidinteraction$tracker.height); - if (!ignoreCurrent) { -- Vec3 flow = fluidState.getFlow(level, mutablePos); -+ if (!ignoreCurrent || !fluidState.getType().getFluidType().canPushEntity(entity)) { -+ Vec3 flow = fluidState.getFlow(level, mutablePos, entity); +- Vec3 vec3 = fluidstate.getFlow(blockgetter, blockpos$mutableblockpos); ++ if (!ignoreCurrent || !fluidstate.getType().getFluidType().canPushEntity(entity)) { ++ Vec3 vec3 = fluidstate.getFlow(blockgetter, blockpos$mutableblockpos, entity); + - if (tracker.height < 0.4) { - flow = flow.scale(tracker.height); + if (entityfluidinteraction$tracker.height < 0.4) { + vec3 = vec3.scale(entityfluidinteraction$tracker.height); } @@ -118,15 +_,27 @@ - return hasFluid; + return flag; } - private EntityFluidInteraction.@Nullable Tracker getTrackerFor(final Fluid fluid) { @@ -90,8 +90,8 @@ + private EntityFluidInteraction.@Nullable Tracker[] getTrackersFor(final Fluid fluid) { + var ret = new java.util.ArrayList(1); for (Entry, EntityFluidInteraction.Tracker> entry : this.trackerByFluid.entrySet()) { - TagKey tag = entry.getKey(); - if (fluid.is(tag)) { + TagKey tagkey = entry.getKey(); + if (fluid.is(tagkey)) { - return entry.getValue(); + ret.add(entry.getValue()); } @@ -112,7 +112,7 @@ public void applyCurrentTo(final TagKey fluid, final Entity entity, final double scale) { @@ -141,6 +_,19 @@ - return tracker != null ? tracker.height : 0.0; + return entityfluidinteraction$tracker != null ? entityfluidinteraction$tracker.height : 0.0; } + public double getFluidHeight(final Fluid fluid) { @@ -133,8 +133,8 @@ } @@ -148,6 +_,45 @@ public boolean isEyeInFluid(final TagKey fluid) { - EntityFluidInteraction.Tracker tracker = this.trackerByFluid.get(fluid); - return tracker != null && tracker.eyesInside; + EntityFluidInteraction.Tracker entityfluidinteraction$tracker = this.trackerByFluid.get(fluid); + return entityfluidinteraction$tracker != null && entityfluidinteraction$tracker.eyesInside; + } + + public boolean isEyeInFluid(final Fluid fluid) { @@ -166,7 +166,7 @@ + public final boolean isInFluid(java.util.function.BiPredicate predicate, boolean forAllTypes) { + boolean match = false; + for (var entry : this.trackerByFluidType.entrySet()) { -+ if (entry.getValue().height > 0 && predicate.test(entry.getKey(), entry.getValue().height)) { ++ if (predicate.test(entry.getKey(), entry.getValue().height)) { + match = true; + if (!forAllTypes) + return true; diff --git a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch index 1289ce6c6c..5e8f236b2f 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/EntityType.java +++ b/net/minecraft/world/entity/EntityType.java -@@ -73,6 +_,11 @@ +@@ -1225,6 +_,11 @@ private final FeatureFlagSet requiredFeatures; private final boolean allowedInPeaceful; @@ -9,10 +9,10 @@ + private final java.util.function.ToIntFunction> updateIntervalSupplier; + private final java.util.function.BiFunction customClientFactory; + - public static Identifier getKey(final EntityType type) { - return BuiltInRegistries.ENTITY_TYPE.getKey(type); + private static EntityType register(final ResourceKey> id, final EntityType.Builder builder) { + return Registry.register(BuiltInRegistries.ENTITY_TYPE, id, builder.build(id)); } -@@ -92,7 +_,8 @@ +@@ -1260,7 +_,8 @@ final String descriptionId, final Optional> lootTable, final FeatureFlagSet requiredFeatures, @@ -22,7 +22,7 @@ ) { this.factory = factory; this.category = category; -@@ -109,6 +_,10 @@ +@@ -1277,6 +_,10 @@ this.lootTable = lootTable; this.requiredFeatures = requiredFeatures; this.allowedInPeaceful = allowedInPeaceful; @@ -33,7 +33,7 @@ } public @Nullable T spawn( -@@ -424,14 +_,26 @@ +@@ -1580,14 +_,26 @@ } public int clientTrackingRange() { @@ -57,11 +57,11 @@ + } + + private boolean defaultVelocitySupplier() { - return this != EntityTypes.PLAYER - && this != EntityTypes.LLAMA_SPIT - && this != EntityTypes.WITHER -@@ -466,6 +_,15 @@ - return EntityTypes.OP_ONLY_CUSTOM_DATA.contains(this); + return this != PLAYER + && this != LLAMA_SPIT + && this != WITHER +@@ -1638,6 +_,15 @@ + return OP_ONLY_CUSTOM_DATA.contains(this); } + public T customClientSpawn(net.minecraftforge.network.packets.SpawnEntity packet, Level world) { @@ -76,7 +76,7 @@ public static class Builder { private final EntityType.EntityFactory factory; private final MobCategory category; -@@ -485,6 +_,10 @@ +@@ -1657,6 +_,10 @@ ); private final DependantName, String> descriptionId = id -> Util.makeDescriptionId("entity", id.identifier()); private boolean allowedInPeaceful = true; @@ -87,7 +87,7 @@ private Builder(final EntityType.EntityFactory factory, final MobCategory category) { this.factory = factory; -@@ -603,6 +_,30 @@ +@@ -1775,6 +_,30 @@ return this; } @@ -118,7 +118,7 @@ public EntityType build(final ResourceKey> name) { if (this.serialize) { Util.fetchChoiceType(References.ENTITY_TREE, name.identifier().toString()); -@@ -623,7 +_,8 @@ +@@ -1795,7 +_,8 @@ this.descriptionId.get(name), this.lootTable.get(name), this.requiredFeatures, diff --git a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch index 8ae1b260d8..321b0c38dc 100644 --- a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/world/entity/ExperienceOrb.java @@ -136,7 +_,8 @@ this.applyEffectsFromBlocks(); - float friction = this.getAirDrag(); + float f = 0.98F; if (this.onGround()) { -- friction *= this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction(); +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; + BlockPos pos = getBlockPosBelowThatAffectsMyMovement(); -+ friction *= this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; ++ f = this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; } - this.setDeltaMovement(this.getDeltaMovement().scale(friction)); -@@ -282,6 +_,7 @@ + this.setDeltaMovement(this.getDeltaMovement().scale(f)); +@@ -278,6 +_,7 @@ public void playerTouch(final Player player) { - if (player instanceof ServerPlayer serverPlayer) { + if (player instanceof ServerPlayer serverplayer) { if (player.takeXpDelay == 0) { + if (net.minecraftforge.event.ForgeEventFactory.onPlayerPickupXp(player, this)) return; player.takeXpDelay = 2; player.take(this, 1); - int remaining = this.repairPlayerItems(serverPlayer, this.getValue()); + int i = this.repairPlayerItems(serverplayer, this.getValue()); diff --git a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch index 2312813865..f5913ade3d 100644 --- a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch @@ -21,12 +21,12 @@ + } + private void powerLightningRod() { - BlockPos strikePosition = this.getStrikePosition(); - BlockState stateBelow = this.level().getBlockState(strikePosition); + BlockPos blockpos = this.getStrikePosition(); + BlockState blockstate = this.level().getBlockState(blockpos); @@ -150,6 +_,7 @@ ); - for (Entity entity : entities) { + 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 903f63c21f..5d72874683 100644 --- a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/LivingEntity.java +++ b/net/minecraft/world/entity/LivingEntity.java -@@ -138,7 +_,7 @@ +@@ -140,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,16 +9,16 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final String TAG_ACTIVE_EFFECTS = "active_effects"; public static final String TAG_ATTRIBUTES = "attributes"; -@@ -209,6 +_,8 @@ - public static final float ELYTRA_VERTICAL_AIR_DRAG = 0.98F; - public static final float BASE_SWIM_SPEED = 0.02F; +@@ -195,6 +_,8 @@ + private static final int CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME_TICKS = 40; + private static final int DEFAULT_CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME = 0; private int currentImpulseContextResetGraceTime = 0; + /** Forge: Use a variant that calls {@link ItemStack#isMonsterDisguise(Player, net.minecraft.world.entity.monster.Monster)} and {@link net.minecraftforge.event.entity.living.MonsterDisguiseEvent} */ + @Deprecated public static final Predicate PLAYER_NOT_WEARING_DISGUISE_ITEM = livingEntity -> { if (livingEntity instanceof Player player) { - ItemStack helmet = player.getItemBySlot(EquipmentSlot.HEAD); -@@ -292,7 +_,7 @@ + ItemStack itemstack = player.getItemBySlot(EquipmentSlot.HEAD); +@@ -279,7 +_,7 @@ this.reapplyPosition(); this.setYRot(this.random.nextFloat() * (float) (Math.PI * 2)); this.yHeadRot = this.getYRot(); @@ -27,27 +27,27 @@ } @Override -@@ -356,7 +_,8 @@ - .add(Attributes.AIR_DRAG_MODIFIER) - .add(Attributes.FRICTION_MODIFIER) - .add(Attributes.NAME_TAG_DISTANCE) -- .add(Attributes.BELOW_NAME_DISTANCE); -+ .add(Attributes.BELOW_NAME_DISTANCE) +@@ -338,7 +_,8 @@ + .add(Attributes.MOVEMENT_EFFICIENCY) + .add(Attributes.ATTACK_KNOCKBACK) + .add(Attributes.CAMERA_DISTANCE) +- .add(Attributes.WAYPOINT_TRANSMIT_RANGE); ++ .add(Attributes.WAYPOINT_TRANSMIT_RANGE) + .add(Attributes.JUMP_STRENGTH); } @Override -@@ -383,7 +_,8 @@ +@@ -365,7 +_,8 @@ - double scale = Math.min(0.2F + power / 15.0, 2.5); - int particles = (int)(150.0 * scale); -- level.sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), x, y, z, particles, 0.0, 0.0, 0.0, 0.15F); -+ if (!onState.addLandingEffects((ServerLevel) this.level(), pos, onState, this, particles)) -+ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState).setPos(pos), x, y, z, particles, 0.0, 0.0, 0.0, 0.15F); + double d7 = Math.min(0.2F + d6 / 15.0, 2.5); + int i = (int)(150.0 * d7); +- serverlevel.sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), d0, d1, d2, i, 0.0, 0.0, 0.0, 0.15F); ++ if (!onState.addLandingEffects((ServerLevel) this.level(), pos, onState, this, i)) ++ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState).setPos(pos), d0, d1, d2, i, 0.0, 0.0, 0.0, 0.15F); } } -@@ -393,6 +_,7 @@ +@@ -375,6 +_,7 @@ } } @@ -55,27 +55,28 @@ public boolean canBreatheUnderwater() { return this.is(EntityTypeTags.CAN_BREATHE_UNDER_WATER); } -@@ -433,6 +_,9 @@ +@@ -415,6 +_,10 @@ } } ++ + 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) - && !level.getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { - boolean canDrownInWater = !this.canBreatheUnderwater() -@@ -788,6 +_,9 @@ - - ItemEntity entity = this.createItemStackToDrop(itemStack, randomly, thrownFromHand); - if (entity != null) { + && !serverlevel1.getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { + boolean flag1 = !this.canBreatheUnderwater() +@@ -764,6 +_,9 @@ + } else { + ItemEntity itementity = this.createItemStackToDrop(itemStack, randomly, thrownFromHand); + if (itementity != null) { + if (captureDrops() != null) -+ captureDrops().add(entity); ++ captureDrops().add(itementity); + else - this.level().addFreshEntity(entity); - } + this.level().addFreshEntity(itementity); + } -@@ -828,7 +_,7 @@ +@@ -806,7 +_,7 @@ this.setPosToBed(sleepingPos); } }, this::clearSleepingPos); @@ -84,34 +85,34 @@ this.lastHurtByPlayer = EntityReference.read(input, "last_hurt_by_player"); this.lastHurtByPlayerMemoryTime = input.getIntOr("last_hurt_by_player_memory_time", 0); this.lastHurtByMob = EntityReference.read(input, "last_hurt_by_mob"); -@@ -854,8 +_,10 @@ - Holder mobEffect = iterator.next(); - MobEffectInstance effect = this.activeEffects.get(mobEffect); - if (!effect.tickServer(serverLevel, this, () -> this.onEffectUpdated(effect, true, null))) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onLivingEffectExpire(this, effect)) { +@@ -832,8 +_,10 @@ + Holder holder = iterator.next(); + MobEffectInstance mobeffectinstance = this.activeEffects.get(holder); + if (!mobeffectinstance.tickServer(serverlevel, this, () -> this.onEffectUpdated(mobeffectinstance, true, null))) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLivingEffectExpire(this, mobeffectinstance)) { iterator.remove(); - this.onEffectsRemoved(List.of(effect)); + this.onEffectsRemoved(List.of(mobeffectinstance)); + } - } else if (effect.getDuration() % 600 == 0) { - this.onEffectUpdated(effect, false, null); + } else if (mobeffectinstance.getDuration() % 600 == 0) { + this.onEffectUpdated(mobeffectinstance, false, null); } -@@ -942,6 +_,7 @@ +@@ -919,6 +_,7 @@ } } -+ visibilityPercent = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, targetingEntity, visibilityPercent); - return visibilityPercent; ++ d0 = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, targetingEntity, d0); + return d0; } -@@ -1018,6 +_,7 @@ - - MobEffectInstance effect = this.activeEffects.get(newEffect.getEffect()); - boolean changed = false; -+ net.minecraftforge.event.ForgeEventFactory.onLivingEffectAdd(this, effect, newEffect, source); - if (effect == null) { - this.activeEffects.put(newEffect.getEffect(), newEffect); - this.onEffectAdded(newEffect, source); -@@ -1033,6 +_,10 @@ +@@ -992,6 +_,7 @@ + } else { + MobEffectInstance mobeffectinstance = this.activeEffects.get(newEffect.getEffect()); + boolean flag = false; ++ net.minecraftforge.event.ForgeEventFactory.onLivingEffectAdd(this, mobeffectinstance, newEffect, source); + if (mobeffectinstance == null) { + this.activeEffects.put(newEffect.getEffect(), newEffect); + this.onEffectAdded(newEffect, source); +@@ -1008,6 +_,10 @@ } public boolean canBeAffected(final MobEffectInstance newEffect) { @@ -122,27 +123,27 @@ if (this.is(EntityTypeTags.IMMUNE_TO_INFESTED)) { return !newEffect.is(MobEffects.INFESTED); } else if (this.is(EntityTypeTags.IMMUNE_TO_OOZING)) { -@@ -1063,6 +_,9 @@ +@@ -1038,6 +_,9 @@ } public boolean removeEffect(final Holder effect) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, effect.get())) { + return false; + } - MobEffectInstance effectInstance = this.removeEffectNoUpdate(effect); - if (effectInstance != null) { - this.onEffectsRemoved(List.of(effectInstance)); -@@ -1107,6 +_,9 @@ + MobEffectInstance mobeffectinstance = this.removeEffectNoUpdate(effect); + if (mobeffectinstance != null) { + this.onEffectsRemoved(List.of(mobeffectinstance)); +@@ -1082,6 +_,9 @@ this.effectsDirty = true; - for (MobEffectInstance effect : effects) { -+ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, effect)) { + for (MobEffectInstance mobeffectinstance : effects) { ++ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, mobeffectinstance)) { + continue; + } - effect.getEffect().value().removeAttributeModifiers(this.getAttributes()); + mobeffectinstance.getEffect().value().removeAttributeModifiers(this.getAttributes()); - for (Entity passenger : this.getPassengers()) { -@@ -1154,9 +_,13 @@ + for (Entity entity : this.getPassengers()) { +@@ -1129,9 +_,13 @@ } public void heal(final float heal) { @@ -150,14 +151,14 @@ + if (ammount <= 0) { + return; + } - float health = this.getHealth(); - if (health > 0.0F) { -- this.setHealth(health + heal); -+ this.setHealth(health + ammount); + float f = this.getHealth(); + if (f > 0.0F) { +- this.setHealth(f + heal); ++ this.setHealth(f + ammount); } } -@@ -1174,6 +_,9 @@ +@@ -1149,6 +_,9 @@ @Override public boolean hurtServer(final ServerLevel level, final DamageSource source, float damage) { @@ -166,78 +167,78 @@ + } if (this.isInvulnerableTo(level, source)) { return false; - } -@@ -1332,6 +_,10 @@ - } + } else if (this.isDeadOrDying()) { +@@ -1296,6 +_,10 @@ + } - float damageBlocked = blocksAttacks.resolveBlockedDamage(source, damage, angle); -+ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, source, damageBlocked, blockingWith); -+ if (ev == null) return 0.0F; -+ damageBlocked = ev.getBlockedDamage(); -+ if (ev.shieldTakesDamage()) - blocksAttacks.hurtBlockingItem(this.level(), blockingWith, this, this.getUsedItemHand(), damageBlocked); - if (damageBlocked > 0.0F && !source.is(DamageTypeTags.IS_PROJECTILE) && source.getDirectEntity() instanceof LivingEntity livingEntity) { - this.blockUsingItem(level, livingEntity, source, damage); -@@ -1363,7 +_,7 @@ - Entity sourceEntity = source.getEntity(); - if (sourceEntity instanceof Player playerSource) { - this.setLastHurtByPlayer(playerSource, 100); -- } else if (sourceEntity instanceof Wolf wolf && wolf.isTame()) { -+ } else if (sourceEntity instanceof net.minecraft.world.entity.TamableAnimal wolf && wolf.isTame()) { + float f = blocksattacks.resolveBlockedDamage(source, damage, d0); ++ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, source, f, itemstack); ++ if (ev == null) return 0.0F; ++ f = ev.getBlockedDamage(); ++ if (ev.shieldTakesDamage()) + blocksattacks.hurtBlockingItem(this.level(), itemstack, this, this.getUsedItemHand(), f); + if (f > 0.0F && !source.is(DamageTypeTags.IS_PROJECTILE) && source.getDirectEntity() instanceof LivingEntity livingentity) { + this.blockUsingItem(level, livingentity); +@@ -1329,7 +_,7 @@ + Entity entity = source.getEntity(); + if (entity instanceof Player player) { + this.setLastHurtByPlayer(player, 100); +- } else if (entity instanceof Wolf wolf && wolf.isTame()) { ++ } else if (entity instanceof net.minecraft.world.entity.TamableAnimal wolf && wolf.isTame()) { if (wolf.getOwnerReference() != null) { this.setLastHurtByPlayer(wolf.getOwnerReference().getUUID(), 100); } else { -@@ -1394,7 +_,7 @@ - for (InteractionHand hand : InteractionHand.values()) { - ItemStack itemStack = this.getItemInHand(hand); - protection = itemStack.get(DataComponents.DEATH_PROTECTION); -- if (protection != null) { -+ if (protection != null && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, killingDamage, itemStack, hand)) { - protectionItem = itemStack.copy(); - itemStack.shrink(1); - break; -@@ -1449,6 +_,7 @@ +@@ -1359,7 +_,7 @@ + for (InteractionHand interactionhand : InteractionHand.values()) { + ItemStack itemstack1 = this.getItemInHand(interactionhand); + deathprotection = itemstack1.get(DataComponents.DEATH_PROTECTION); +- if (deathprotection != null) { ++ if (deathprotection != null && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, killingDamage, itemstack1, interactionhand)) { + itemstack = itemstack1.copy(); + itemstack1.shrink(1); + break; +@@ -1415,6 +_,7 @@ } public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; if (!this.isRemoved() && !this.dead) { - Entity sourceEntity = source.getEntity(); - LivingEntity killer = this.getKillCredit(); -@@ -1489,10 +_,10 @@ - if (this.level() instanceof ServerLevel serverLevel) { - boolean var6 = false; + Entity entity = source.getEntity(); + LivingEntity livingentity = this.getKillCredit(); +@@ -1451,10 +_,10 @@ + if (this.level() instanceof ServerLevel serverlevel) { + boolean flag = false; if (killer instanceof WitherBoss) { -- if (serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, killer)) { - BlockPos pos = this.blockPosition(); - BlockState state = Blocks.WITHER_ROSE.defaultBlockState(); -- if (this.level().getBlockState(pos).isAir() && state.canSurvive(this.level(), pos)) { -+ if (this.level().isEmptyBlock(pos) && state.canSurvive(this.level(), pos)) { - this.level().setBlock(pos, state, 3); - var6 = true; +- if (serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, killer)) { + 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; } -@@ -1507,6 +_,7 @@ +@@ -1469,6 +_,7 @@ } protected void dropAllDeathLoot(final ServerLevel level, final DamageSource source) { + this.captureDrops(new java.util.ArrayList<>()); - boolean playerKilled = this.lastHurtByPlayerMemoryTime > 0; + boolean flag = this.lastHurtByPlayerMemoryTime > 0; if (this.shouldDropLoot(level)) { - this.dropFromLootTable(level, source, playerKilled); -@@ -1515,6 +_,11 @@ + this.dropFromLootTable(level, source, flag); +@@ -1477,6 +_,11 @@ this.dropEquipment(level); this.dropExperience(level, source.getEntity()); + + var drops = captureDrops(null); -+ if (!net.minecraftforge.event.ForgeEventFactory.onLivingDrops(this, source, drops, playerKilled)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLivingDrops(this, source, drops, flag)) { + drops.forEach(e -> level().addFreshEntity(e)); + } } protected void dropEquipment(final ServerLevel level) { -@@ -1526,7 +_,8 @@ +@@ -1488,7 +_,8 @@ this.isAlwaysExperienceDropper() || this.lastHurtByPlayerMemoryTime > 0 && this.shouldDropExperience() && level.getGameRules().get(GameRules.MOB_DROPS) )) { @@ -247,10 +248,10 @@ } } -@@ -1639,6 +_,11 @@ +@@ -1601,6 +_,11 @@ } - public void knockback(double power, double xd, double zd, final DamageSource source, final float damage, final boolean comesFromEffect) { + public void knockback(double power, double xd, double zd) { + var event = net.minecraftforge.event.ForgeEventFactory.onLivingKnockBack(this, (float)power, xd, zd); + if (event == null) return; + power = event.getStrength(); @@ -259,74 +260,74 @@ power *= 1.0 - this.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); if (!(power <= 0.0)) { this.needsSync = true; -@@ -1724,6 +_,13 @@ +@@ -1678,6 +_,13 @@ } else { - BlockPos ladderCheckPos = this.blockPosition(); - BlockState state = this.getInBlockState(); -+ var ladderPos = net.minecraftforge.common.ForgeHooks.isLivingOnLadder(state, level(), ladderCheckPos, this); + 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 (this.isFallFlying() && state.is(BlockTags.CAN_GLIDE_THROUGH)) { + if (this.isFallFlying() && blockstate.is(BlockTags.CAN_GLIDE_THROUGH)) { return false; - } else if (state.is(BlockTags.CLIMBABLE)) { -@@ -1788,9 +_,11 @@ + } else if (blockstate.is(BlockTags.CLIMBABLE)) { +@@ -1742,9 +_,11 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { + var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, fallDistance, damageModifier); + if (event == null) return false; - double effectiveFallDistance; + double d0; if (this.isIgnoringFallDamageFromCurrentImpulse()) { -- effectiveFallDistance = Math.min(fallDistance, this.currentImpulseImpactPos.y - this.getY()); -+ effectiveFallDistance = Math.min(event.getDistance(), this.currentImpulseImpactPos.y - this.getY()); - boolean hasLandedAboveCurrentImpulseImpactPosY = effectiveFallDistance <= 0.0; - if (hasLandedAboveCurrentImpulseImpactPosY) { +- d0 = Math.min(fallDistance, this.currentImpulseImpactPos.y - this.getY()); ++ d0 = Math.min(event.getDistance(), this.currentImpulseImpactPos.y - this.getY()); + boolean flag = d0 <= 0.0; + if (flag) { this.resetCurrentImpulseContext(); -@@ -1798,11 +_,11 @@ +@@ -1752,11 +_,11 @@ this.tryResetCurrentImpulseContext(); } } else { -- effectiveFallDistance = fallDistance; -+ effectiveFallDistance = event.getDistance(); +- d0 = fallDistance; ++ d0 = event.getDistance(); } -- boolean damaged = super.causeFallDamage(effectiveFallDistance, damageModifier, damageSource); -- int dmg = this.calculateFallDamage(effectiveFallDistance, damageModifier); -+ boolean damaged = super.causeFallDamage(effectiveFallDistance, event.getDamageMultiplier(), damageSource); -+ int dmg = this.calculateFallDamage(effectiveFallDistance, event.getDamageMultiplier()); - if (dmg > 0) { +- boolean flag1 = super.causeFallDamage(d0, damageModifier, damageSource); +- int i = this.calculateFallDamage(d0, damageModifier); ++ boolean flag1 = super.causeFallDamage(d0, event.getDamageMultiplier(), damageSource); ++ int i = this.calculateFallDamage(d0, event.getDamageMultiplier()); + if (i > 0) { this.resetCurrentImpulseContext(); - this.playSound(this.getFallDamageSound(dmg), 1.0F, 1.0F); -@@ -1864,9 +_,10 @@ - int xx = Mth.floor(this.getX()); - int yy = Mth.floor(this.getY() - 0.2F); - int zz = Mth.floor(this.getZ()); -- BlockState state = this.level().getBlockState(new BlockPos(xx, yy, zz)); -+ BlockPos pos = new BlockPos(xx, yy, zz); -+ BlockState state = this.level().getBlockState(pos); - if (!state.isAir()) { -- SoundType soundType = state.getSoundType(); -+ SoundType soundType = state.getSoundType(level(), pos, this); - this.playSound(soundType.getFallSound(), soundType.getVolume() * 0.5F, soundType.getPitch() * 0.75F); + this.playSound(this.getFallDamageSound(i), 1.0F, 1.0F); +@@ -1819,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); } } -@@ -1927,9 +_,9 @@ - float damageResisted = oldDamage - damage; - if (damageResisted > 0.0F && damageResisted < 3.4028235E37F) { - if (this instanceof ServerPlayer serverPlayer) { -- serverPlayer.awardStat(Stats.DAMAGE_RESISTED, Math.round(damageResisted * 10.0F)); -+ serverPlayer.awardStat(Stats.CUSTOM.get(Stats.DAMAGE_RESISTED), Math.round(damageResisted * 10.0F)); - } else if (damageSource.getEntity() instanceof ServerPlayer) { -- ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(damageResisted * 10.0F)); -+ ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(damageResisted * 10.0F)); +@@ -1881,9 +_,9 @@ + float f2 = f1 - damage; + 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 (damageSource.getEntity() instanceof ServerPlayer) { +- ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f2 * 10.0F)); ++ ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(f2 * 10.0F)); + } } } - } -@@ -1958,6 +_,8 @@ +@@ -1911,6 +_,8 @@ protected void actuallyHurt(final ServerLevel level, final DamageSource source, float dmg) { if (!this.isInvulnerableTo(level, source)) { @@ -334,16 +335,16 @@ + if (dmg <= 0) return; dmg = this.getDamageAfterArmorAbsorb(source, dmg); dmg = this.getDamageAfterMagicAbsorb(source, dmg); - float originalDamage = dmg; -@@ -1968,6 +_,7 @@ - serverPlayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(absorbedDamage * 10.0F)); + float f1 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); +@@ -1920,6 +_,7 @@ + serverplayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(f * 10.0F)); } -+ dmg = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, dmg); - if (dmg != 0.0F) { - this.getCombatTracker().recordDamage(source, dmg); - this.setHealth(this.getHealth() - dmg); -@@ -2031,6 +_,8 @@ ++ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, f1); + if (f1 != 0.0F) { + this.getCombatTracker().recordDamage(source, f1); + this.setHealth(this.getHealth() - f1); +@@ -1981,6 +_,8 @@ } public void swing(final InteractionHand hand, final boolean sendToSwingingEntity) { @@ -352,13 +353,13 @@ if (!this.swinging || this.swingTime >= this.getCurrentSwingDuration() / 2 || this.swingTime < 0) { this.swingTime = -1; this.swinging = true; -@@ -2172,9 +_,10 @@ +@@ -2121,9 +_,10 @@ } private void swapHandItems() { -- ItemStack tmp = this.getItemBySlot(EquipmentSlot.OFFHAND); +- ItemStack itemstack = this.getItemBySlot(EquipmentSlot.OFFHAND); - this.setItemSlot(EquipmentSlot.OFFHAND, this.getItemBySlot(EquipmentSlot.MAINHAND)); -- this.setItemSlot(EquipmentSlot.MAINHAND, tmp); +- this.setItemSlot(EquipmentSlot.MAINHAND, itemstack); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this); + if (event == null) return; + this.setItemSlot(EquipmentSlot.OFFHAND, event.getItemSwappedToOffHand()); @@ -366,7 +367,7 @@ } @Override -@@ -2396,15 +_,18 @@ +@@ -2340,15 +_,18 @@ } this.needsSync = true; @@ -387,7 +388,7 @@ } protected float getWaterSlowDown() { -@@ -2427,8 +_,9 @@ +@@ -2370,8 +_,9 @@ } public void travel(final Vec3 input) { @@ -399,7 +400,7 @@ } else if (this.isFallFlying()) { this.travelFallFlying(input); } else { -@@ -2441,7 +_,7 @@ +@@ -2384,7 +_,7 @@ } protected boolean shouldTravelInFluid(final FluidState fluidState) { @@ -408,53 +409,53 @@ } protected void travelFlying(final Vec3 input, final float speed) { -@@ -2468,7 +_,7 @@ - BlockPos posBelow = this.getBlockPosBelowThatAffectsMyMovement(); - float blockFriction = this.onGround() - ? computeModifiedFriction( -- this.level().getBlockState(posBelow).getBlock().getFriction(), (float)this.getAttributeValue(Attributes.FRICTION_MODIFIER) -+ this.level().getBlockState(posBelow).getFriction(level(), posBelow, this), (float)this.getAttributeValue(Attributes.FRICTION_MODIFIER) - ) - : 1.0F; - Vec3 movement = this.handleRelativeFrictionAndCalculateMovement(input, blockFriction); -@@ -2500,10 +_,18 @@ - return computeModifiedFriction(this.omnidirectionalAirMover() ? 0.91F : 0.98F, (float)this.getAttributeValue(Attributes.AIR_DRAG_MODIFIER)); +@@ -2409,7 +_,7 @@ + + private void travelInAir(final Vec3 input) { + BlockPos blockpos = this.getBlockPosBelowThatAffectsMyMovement(); +- float f = this.onGround() ? this.level().getBlockState(blockpos).getBlock().getFriction() : 1.0F; ++ float f = this.onGround() ? this.level().getBlockState(blockpos).getFriction(level(), blockpos, this) : 1.0F; + float f1 = f * 0.91F; + Vec3 vec3 = this.handleRelativeFrictionAndCalculateMovement(input, f); + double d0 = vec3.y; +@@ -2432,10 +_,18 @@ + } } -- protected void travelInFluid(final Vec3 input) { +- private void travelInFluid(final Vec3 input) { + @Deprecated // FORGE: Use the version that takes a FluidState -+ protected void travelInFluid(Vec3 input) { ++ private void travelInFluid(Vec3 input) { + this.travelInFluid(input, net.minecraft.world.level.material.Fluids.WATER.defaultFluidState()); + } + -+ protected void travelInFluid(Vec3 input, FluidState fluidstate) { - boolean isFalling = this.getDeltaMovement().y <= 0.0; - double oldY = this.getY(); - double baseGravity = this.getEffectiveGravity(); -+ if (this.isInFluidType(fluidstate) && this.moveInFluid(fluidstate, input, oldY)) { ++ private void travelInFluid(Vec3 input, FluidState fluidstate) { + boolean flag = this.getDeltaMovement().y <= 0.0; + double d0 = this.getY(); + double d1 = this.getEffectiveGravity(); ++ if (this.isInFluidType(fluidstate) && this.moveInFluid(fluidstate, input, d0)) { + // Modded fluid handled it + } else if (this.isInWater()) { - this.travelInWater(input, baseGravity, isFalling, oldY); + this.travelInWater(input, d1, flag, d0); this.floatInWaterWhileRidden(); -@@ -2529,6 +_,7 @@ - slowDown = 0.96F; +@@ -2461,6 +_,7 @@ + f = 0.96F; } -+ speed *= this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()); - this.moveRelative(speed, input); ++ f1 *= this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()); + this.moveRelative(f1, input); this.move(MoverType.SELF, this.getDeltaMovement()); - Vec3 movement = this.getDeltaMovement(); -@@ -2706,7 +_,7 @@ - double xd = Mth.clamp(delta.x, -0.15F, 0.15F); - double zd = Mth.clamp(delta.z, -0.15F, 0.15F); - double yd = Math.max(delta.y, -0.15F); -- if (yd < 0.0 && !this.getInBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { -+ if (yd < 0.0 && !this.getInBlockState().isScaffolding(this) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { - yd = 0.0; + Vec3 vec3 = this.getDeltaMovement(); +@@ -2632,7 +_,7 @@ + double d0 = Mth.clamp(delta.x, -0.15F, 0.15F); + double d1 = Mth.clamp(delta.z, -0.15F, 0.15F); + double d2 = Math.max(delta.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; } -@@ -2762,6 +_,7 @@ +@@ -2675,6 +_,7 @@ @Override public void tick() { @@ -462,31 +463,31 @@ super.tick(); this.updatingUsingItem(); this.updateSwimAmount(); -@@ -2962,6 +_,7 @@ - ItemStack previous = lastEquipmentItems.get(slot); - ItemStack current = this.getItemBySlot(slot); - if (this.equipmentHasChanged(previous, current)) { -+ net.minecraftforge.event.ForgeEventFactory.onLivingEquipmentChange(this, slot, previous, current); - if (changedItems == null) { - changedItems = Maps.newEnumMap(EquipmentSlot.class); +@@ -2873,6 +_,7 @@ + ItemStack itemstack = this.lastEquipmentItems.get(equipmentslot); + 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); } -@@ -3097,6 +_,10 @@ - profiler.push("jump"); +@@ -3008,6 +_,10 @@ + profilerfiller.push("jump"); if (this.jumping && this.isAffectedByFluids()) { - double fluidHeight; + double d3; + var fluidType = this.getMaxHeightFluidType(); + if (!fluidType.isAir()) { -+ fluidHeight = this.getFluidTypeHeight(fluidType); ++ d3 = this.getFluidTypeHeight(fluidType); + } else if (this.isInLava()) { - fluidHeight = this.getFluidHeight(FluidTags.LAVA); + d3 = this.getFluidHeight(FluidTags.LAVA); } else { -@@ -3107,15 +_,19 @@ - double fluidJumpThreshold = this.getFluidJumpThreshold(); - if (!inWaterAndHasFluidHeight || this.onGround() && !(fluidHeight > fluidJumpThreshold)) { - if (!this.isInLava() || this.onGround() && this.isInShallowFluid(FluidTags.LAVA)) { -+ if (fluidType.isAir() || this.onGround() && !(fluidHeight > fluidJumpThreshold)) { - if ((this.onGround() || inWaterAndHasFluidHeight && fluidHeight <= fluidJumpThreshold) && this.noJumpDelay == 0) { +@@ -3018,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; } @@ -503,7 +504,7 @@ } } else { this.noJumpDelay = 0; -@@ -3434,8 +_,11 @@ +@@ -3346,8 +_,11 @@ private void updatingUsingItem() { if (this.isUsingItem()) { @@ -516,7 +517,7 @@ this.updateUsingItem(this.useItem); } else { this.stopUsingItem(); -@@ -3478,8 +_,12 @@ +@@ -3390,8 +_,12 @@ } protected void updateUsingItem(final ItemStack useItem) { @@ -530,42 +531,42 @@ this.completeUsingItem(); } } -@@ -3507,8 +_,10 @@ +@@ -3419,8 +_,10 @@ public void startUsingItem(final InteractionHand hand) { - ItemStack itemStack = this.getItemInHand(hand); - if (!itemStack.isEmpty() && !this.isUsingItem()) { -+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemStack, itemStack.getUseDuration(this)); + ItemStack itemstack = this.getItemInHand(hand); + if (!itemstack.isEmpty() && !this.isUsingItem()) { ++ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration(this)); + if (duration < 0) return; - this.useItem = itemStack; -- this.useItemRemaining = itemStack.getUseDuration(this); + this.useItem = itemstack; +- this.useItemRemaining = itemstack.getUseDuration(this); + this.useItemRemaining = duration; if (!this.level().isClientSide()) { this.setLivingEntityFlag(1, true); this.setLivingEntityFlag(2, hand == InteractionHand.OFF_HAND); -@@ -3566,6 +_,9 @@ - p = p.xRot(-this.getXRot() * (float) (Math.PI / 180.0)); - p = p.yRot(-this.getYRot() * (float) (Math.PI / 180.0)); - p = p.add(this.getX(), this.getEyeY(), this.getZ()); +@@ -3478,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(breakParticle, p.x, p.y, p.z, 1, d.x, d.y + 0.05D, d.z, 0.0D); ++ serverLevel.sendParticles(itemparticleoption, vec31.x, vec31.y, vec31.z, 1, vec3.x, vec3.y + 0.05D, vec3.z, 0.0D); + else - this.level().addParticle(breakParticle, p.x, p.y, p.z, d.x, d.y + 0.05, d.z); + this.level().addParticle(itemparticleoption, vec31.x, vec31.y, vec31.z, vec3.x, vec3.y + 0.05, vec3.z); } } -@@ -3578,7 +_,9 @@ +@@ -3490,7 +_,9 @@ this.releaseUsingItem(); } else { if (!this.useItem.isEmpty() && this.isUsingItem()) { + ItemStack copy = this.useItem.copy(); - ItemStack result = this.useItem.finishUsingItem(this.level(), this); -+ result = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), result); - if (result != this.useItem) { - this.setItemInHand(hand, result); + 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); } -@@ -3612,7 +_,13 @@ - ItemStack itemInUsedHand = this.getItemInHand(this.getUsedItemHand()); - if (!this.useItem.isEmpty() && ItemStack.isSameItem(itemInUsedHand, this.useItem)) { - this.useItem = itemInUsedHand; +@@ -3524,7 +_,13 @@ + ItemStack itemstack = this.getItemInHand(this.getUsedItemHand()); + if (!this.useItem.isEmpty() && ItemStack.isSameItem(itemstack, this.useItem)) { + this.useItem = itemstack; + 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()); @@ -576,26 +577,26 @@ if (this.useItem.useOnRelease()) { this.updatingUsingItem(); } -@@ -3622,6 +_,7 @@ +@@ -3534,6 +_,7 @@ } public void stopUsingItem() { + if (this.isUsingItem() && !this.useItem.isEmpty()) this.useItem.onStopUsing(this, useItemRemaining); if (!this.level().isClientSide()) { - boolean wasUsingItem = this.isUsingItem(); + boolean flag = this.isUsingItem(); this.recentKineticEnemies = null; -@@ -3783,8 +_,8 @@ +@@ -3702,8 +_,8 @@ } - BlockState blockState = this.level().getBlockState(bedPosition); -- if (blockState.getBlock() instanceof BedBlock) { -- this.level().setBlock(bedPosition, blockState.setValue(BedBlock.OCCUPIED, true), 3); -+ if (blockState.isBed(level(), bedPosition, this)) { -+ blockState.setBedOccupied(level(), bedPosition, this, true); + BlockState blockstate = this.level().getBlockState(bedPosition); +- if (blockstate.getBlock() instanceof BedBlock) { +- this.level().setBlock(bedPosition, blockstate.setValue(BedBlock.OCCUPIED, true), 3); ++ if (blockstate.isBed(level(), bedPosition, this)) { ++ blockstate.setBedOccupied(level(), bedPosition, this, true); } this.setPose(Pose.SLEEPING); -@@ -3799,15 +_,15 @@ +@@ -3718,15 +_,15 @@ } private boolean checkBedExists() { @@ -605,27 +606,27 @@ public void stopSleeping() { this.getSleepingPos().filter(this.level()::hasChunkAt).ifPresent(bedPosition -> { - BlockState state = this.level().getBlockState(bedPosition); -- if (state.getBlock() instanceof BedBlock) { -+ if (state.isBed(level(), bedPosition, this)) { - Direction facing = state.getValue(BedBlock.FACING); -- this.level().setBlock(bedPosition, state.setValue(BedBlock.OCCUPIED, false), 3); -+ state.setBedOccupied(level(), bedPosition, this, false); - Vec3 standUp = BedBlock.findStandUpPosition(this.getType(), this.level(), bedPosition, facing, this.getYRot()).orElseGet(() -> { - BlockPos above = bedPosition.above(); - return new Vec3(above.getX() + 0.5, above.getY() + 0.1, above.getZ() + 0.5); -@@ -3827,7 +_,9 @@ + BlockState blockstate = this.level().getBlockState(bedPosition); +- if (blockstate.getBlock() instanceof BedBlock) { ++ if (blockstate.isBed(level(), bedPosition, this)) { + Direction direction = blockstate.getValue(BedBlock.FACING); +- this.level().setBlock(bedPosition, blockstate.setValue(BedBlock.OCCUPIED, false), 3); ++ blockstate.setBedOccupied(level(), bedPosition, this, false); + Vec3 vec31 = BedBlock.findStandUpPosition(this.getType(), this.level(), bedPosition, direction, this.getYRot()).orElseGet(() -> { + BlockPos blockpos = bedPosition.above(); + return new Vec3(blockpos.getX() + 0.5, blockpos.getY() + 0.1, blockpos.getZ() + 0.5); +@@ -3746,7 +_,9 @@ public @Nullable Direction getBedOrientation() { - BlockPos bedPos = this.getSleepingPos().orElse(null); -- return bedPos != null ? BedBlock.getBedOrientation(this.level(), bedPos) : null; -+ if (bedPos == null) return Direction.UP; -+ BlockState state = this.level().getBlockState(bedPos); -+ return !state.isBed(level(), bedPos, this) ? Direction.UP : state.getBedDirection(level(), bedPos); + 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 -@@ -3836,7 +_,7 @@ +@@ -3755,7 +_,7 @@ } public ItemStack getProjectile(final ItemStack heldWeapon) { @@ -634,16 +635,16 @@ } private static byte entityEventForEquipmentBreak(final EquipmentSlot equipmentSlot) { -@@ -3888,6 +_,8 @@ +@@ -3807,6 +_,8 @@ } - public EquipmentSlot getEquipmentSlotForItem(final ItemStack itemStack) { + public final EquipmentSlot getEquipmentSlotForItem(final ItemStack itemStack) { + final EquipmentSlot slot = itemStack.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 Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE); return equippable != null && this.canUseSlot(equippable.slot()) ? equippable.slot() : EquipmentSlot.MAINHAND; } -@@ -4055,5 +_,42 @@ +@@ -3970,5 +_,42 @@ } public record Fallsounds(SoundEvent small, SoundEvent big) { diff --git a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch index 0c49a6994b..9fb32dee9c 100644 --- a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/Mob.java +++ b/net/minecraft/world/entity/Mob.java -@@ -144,6 +_,9 @@ +@@ -139,6 +_,9 @@ private Leashable.@Nullable LeashData leashData; private BlockPos homePosition = BlockPos.ZERO; private int homeRadius = -1; @@ -10,7 +10,7 @@ protected Mob(final EntityType type, final Level level) { super(type, level); -@@ -249,7 +_,10 @@ +@@ -244,7 +_,10 @@ } public void setTarget(final @Nullable LivingEntity target) { @@ -22,7 +22,7 @@ } @Override -@@ -388,6 +_,10 @@ +@@ -383,6 +_,10 @@ if (this.isNoAi()) { output.putBoolean("NoAI", this.isNoAi()); } @@ -33,7 +33,7 @@ } @Override -@@ -406,6 +_,13 @@ +@@ -401,6 +_,13 @@ this.lootTable = input.read("DeathLootTable", LootTable.KEY_CODEC); this.lootTableSeed = input.getLongOr("DeathLootTableSeed", 0L); this.setNoAi(input.getBooleanOr("NoAI", false)); @@ -47,31 +47,31 @@ } @Override -@@ -464,7 +_,7 @@ +@@ -459,7 +_,7 @@ && this.canPickUpLoot() && this.isAlive() && !this.dead -- && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { - Vec3i pickupReach = this.getPickupReach(); +- && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this)) { + Vec3i vec3i = this.getPickupReach(); - for (ItemEntity entity : this.level() -@@ -691,6 +_,14 @@ + for (ItemEntity itementity : this.level() +@@ -658,6 +_,14 @@ this.discard(); } else if (!this.isPersistenceRequired() && !this.requiresCustomPersistence()) { - Entity player = this.level().getNearestPlayer(this, -1.0); + Entity entity = this.level().getNearestPlayer(this, -1.0); + var result = net.minecraftforge.event.ForgeEventFactory.canEntityDespawn(this, (ServerLevel)this.level()); + if (result.isDenied()) { + noActionTime = 0; -+ player = null; ++ entity = null; + } else if (result.isAllowed()) { + this.discard(); -+ player = null; ++ entity = null; + } - if (player != null) { - double distSqr = player.distanceToSqr(this); - int instantDespawnDistance = this.getType().getCategory().getDespawnDistance(); -@@ -1084,6 +_,16 @@ + if (entity != null) { + double d0 = entity.distanceToSqr(this); + int i = this.getType().getCategory().getDespawnDistance(); +@@ -1059,6 +_,16 @@ } } @@ -88,16 +88,16 @@ public @Nullable SpawnGroupData finalizeSpawn( final ServerLevelAccessor level, final DifficultyInstance difficulty, final EntitySpawnReason spawnReason, final @Nullable SpawnGroupData groupData ) { -@@ -1096,6 +_,7 @@ +@@ -1071,6 +_,7 @@ } - this.setLeftHanded(random.nextFloat() < 0.05F); + this.setLeftHanded(randomsource.nextFloat() < 0.05F); + this.spawnReason = spawnReason; return groupData; } -@@ -1409,15 +_,25 @@ - return wasHurt; +@@ -1382,15 +_,25 @@ + return flag; } + @Deprecated // FORGE: use jumpInFluid instead @@ -123,7 +123,7 @@ @VisibleForTesting public void removeFreeWill() { this.removeAllGoals(goal -> true); -@@ -1449,6 +_,41 @@ +@@ -1416,6 +_,41 @@ @Override public @Nullable ItemStack getPickResult() { return SpawnEggItem.byId(this.getType()).map(ItemStack::new).orElse(null); diff --git a/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch b/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch index 23e7943d2c..3d512b3d11 100644 --- a/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/MobCategory.java.patch @@ -6,12 +6,12 @@ -public enum MobCategory implements StringRepresentable { +public enum MobCategory implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { - MONSTER("monster", "MO", 70, false, false, 128), - CREATURE("creature", "C", 10, true, true, 128), - AMBIENT("ambient", "AM", 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", "WA", 20, true, false, 64), - MISC("misc", "MI", -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); @@ -19,13 +19,13 @@ private final int max; private final boolean isFriendly; private final boolean isPersistent; -@@ -64,5 +_,20 @@ +@@ -56,5 +_,20 @@ public int getNoDespawnDistance() { return 32; + } + -+ public static MobCategory create(String name, String id, String debugAbbreviation, int max, boolean isFriendly, boolean isPersistent, int despawnDistance) { ++ public static MobCategory create(String name, String id, int maxNumberOfCreatureIn, boolean isPeacefulCreatureIn, boolean isAnimalIn, int despawnDistance) { + throw new IllegalStateException("Enum not extended"); + } + diff --git a/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch b/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch index 5dcb3d2016..cefe59c316 100644 --- a/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Shearable.java.patch @@ -1,20 +1,18 @@ --- a/net/minecraft/world/entity/Shearable.java +++ b/net/minecraft/world/entity/Shearable.java -@@ -8,4 +_,17 @@ +@@ -4,8 +_,14 @@ + import net.minecraft.sounds.SoundSource; + import net.minecraft.world.item.ItemStack; + +-public interface Shearable { ++public interface Shearable extends net.minecraftforge.common.IForgeShearable { ++ /** @deprecated Use {@link net.minecraftforge.common.IForgeShearable#onSheared} */ void shear(ServerLevel level, SoundSource soundSource, ItemStack tool); ++ /** @deprecated Use {@link net.minecraftforge.common.IForgeShearable#isShearable} */ boolean readyForShearing(); + -+ /** Equivalent to {@link shear} but returns a list of ItemStacks without actually spawning the entity into the world */ -+ default java.util.List shearItems(ServerLevel level, SoundSource soundSource, ItemStack tool) { -+ var self = (Entity)this; -+ var entities = new java.util.ArrayList(); -+ self.captureDrops(entities); -+ shear(level, soundSource, tool); -+ self.captureDrops(null); -+ var items = new java.util.ArrayList(entities.size()); -+ for (var entity : entities) -+ items.add(entity.getItem()); -+ return items; ++ default boolean isShearable(net.minecraft.world.item.ItemStack item, net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) { ++ return readyForShearing(); + } } diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch index c210084862..38357879f4 100644 --- a/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/SpawnPlacementTypes.java +++ b/net/minecraft/world/entity/SpawnPlacementTypes.java @@ -28,7 +_,7 @@ - BlockPos above = blockPos.above(); - BlockPos below = blockPos.below(); - BlockState belowState = level.getBlockState(below); -- return !belowState.isValidSpawn(level, below, type) -+ return !belowState.isValidSpawn(level, below, this, type) + BlockPos blockpos = blockPos.above(); + BlockPos blockpos1 = blockPos.below(); + BlockState blockstate = level.getBlockState(blockpos1); +- return !blockstate.isValidSpawn(level, blockpos1, type) ++ return !blockstate.isValidSpawn(level, blockpos1, this, type) ? false - : this.isValidEmptySpawnBlock(level, blockPos, type) && this.isValidEmptySpawnBlock(level, above, type); + : this.isValidEmptySpawnBlock(level, blockPos, type) && this.isValidEmptySpawnBlock(level, blockpos, type); } else { diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch index 50ecf121cf..544a91a76c 100644 --- a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/SpawnPlacements.java +++ b/net/minecraft/world/entity/SpawnPlacements.java -@@ -50,6 +_,7 @@ +@@ -48,6 +_,7 @@ public class SpawnPlacements { private static final Map, SpawnPlacements.Data> DATA_BY_TYPE = Maps.newHashMap(); @@ -8,17 +8,17 @@ private static void register( final EntityType type, final SpawnPlacementType placementType, -@@ -84,7 +_,8 @@ - } - - SpawnPlacements.Data data = DATA_BY_TYPE.get(type); -- return data == null || data.predicate.test((EntityType)type, level, spawnReason, pos, random); -+ boolean vanillaResult = data == null || data.predicate.test((EntityType)type, level, spawnReason, pos, random); +@@ -78,7 +_,8 @@ + final EntityType type, final ServerLevelAccessor level, final EntitySpawnReason spawnReason, final BlockPos pos, final RandomSource random + ) { + SpawnPlacements.Data spawnplacements$data = DATA_BY_TYPE.get(type); +- return spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)type, level, spawnReason, pos, random); ++ boolean vanillaResult = spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)type, level, spawnReason, pos, random); + return net.minecraftforge.event.ForgeEventFactory.checkSpawnPlacements(type, level, spawnReason, pos, random, vanillaResult); } static { -@@ -200,5 +_,13 @@ +@@ -191,5 +_,13 @@ @FunctionalInterface public interface SpawnPredicate { boolean test(EntityType type, ServerLevelAccessor level, EntitySpawnReason spawnReason, BlockPos pos, RandomSource random); diff --git a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch index 4f22b12555..4521d3060f 100644 --- a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch @@ -1,17 +1,17 @@ --- a/net/minecraft/world/entity/TamableAnimal.java +++ b/net/minecraft/world/entity/TamableAnimal.java -@@ -134,9 +_,9 @@ +@@ -135,9 +_,9 @@ protected void feed(final Player player, final InteractionHand hand, final ItemStack itemStack, final float healingFactor, final float defaultHeal) { - FoodProperties foodProperties = itemStack.get(DataComponents.FOOD); + FoodProperties foodproperties = itemStack.get(DataComponents.FOOD); - this.usePlayerItem(player, hand, itemStack); - this.heal(foodProperties != null ? healingFactor * foodProperties.nutrition() : defaultHeal); + this.heal(foodproperties != null ? healingFactor * foodproperties.nutrition() : defaultHeal); this.playEatingSound(); + this.usePlayerItem(player, hand, itemStack); } public boolean isInSittingPose() { -@@ -221,13 +_,16 @@ +@@ -222,13 +_,16 @@ @Override public void die(final DamageSource source) { @@ -20,11 +20,11 @@ + super.die(source); + + if (this.dead) - if (this.level() instanceof ServerLevel serverLevel - && serverLevel.getGameRules().get(GameRules.SHOW_DEATH_MESSAGES) - && this.getOwner() instanceof ServerPlayer serverPlayer) { -- serverPlayer.sendSystemMessage(this.getCombatTracker().getDeathMessage()); -+ serverPlayer.sendSystemMessage(deathMessage); + if (this.level() instanceof ServerLevel serverlevel + && serverlevel.getGameRules().get(GameRules.SHOW_DEATH_MESSAGES) + && this.getOwner() instanceof ServerPlayer serverplayer) { +- serverplayer.sendSystemMessage(this.getCombatTracker().getDeathMessage()); ++ serverplayer.sendSystemMessage(deathMessage); } - - super.die(source); 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 c03cfea791..f38f2542a9 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/ai/Brain.java +++ b/net/minecraft/world/entity/ai/Brain.java -@@ -252,6 +_,10 @@ +@@ -259,6 +_,10 @@ this.schedule = schedule; } @@ -11,7 +11,7 @@ public void setCoreActivities(final Set activities) { this.coreActivities = activities; } -@@ -453,6 +_,31 @@ +@@ -460,6 +_,31 @@ public boolean isBrainDead() { return this.memories.isEmpty() && this.sensors.isEmpty() && this.availableBehaviorsByPriority.isEmpty(); 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 7568317e51..aef61b29b6 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 @@ -25,7 +25,7 @@ + } private AttributeInstance create(final Holder attribute) { - AttributeInstance result = new AttributeInstance(attribute, attributeInstance -> { + AttributeInstance attributeinstance = new AttributeInstance(attribute, attributeInstance -> { @@ -91,7 +_,8 @@ public AttributeSupplier build() { 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 7f65824749..ba269cd065 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,6 +1,6 @@ --- a/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java +++ b/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java -@@ -190,11 +_,12 @@ +@@ -188,11 +_,12 @@ .build(); public static AttributeSupplier getSupplier(final EntityType type) { 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 fbefd3402b..9b06cbc7f4 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 @@ -3,9 +3,9 @@ @@ -25,7 +_,7 @@ protected boolean checkExtraStartConditions(final ServerLevel level, final E body) { - LivingEntity attackTarget = getAttackTarget(body); -- return body.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(body, attackTarget) && BehaviorUtils.isWithinAttackRange(body, attackTarget, 0); -+ return body.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(body, attackTarget) && BehaviorUtils.isWithinAttackRange(body, attackTarget, 0); + LivingEntity livingentity = getAttackTarget(body); +- return body.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(body, livingentity) && BehaviorUtils.isWithinAttackRange(body, livingentity, 0); ++ return body.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(body, livingentity) && BehaviorUtils.isWithinAttackRange(body, livingentity, 0); } protected boolean canStillUse(final ServerLevel level, final E body, final long timestamp) { 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 7082259ede..4bfab8f426 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 @@ -7,17 +7,17 @@ - if (!level.getGameRules().get(GameRules.MOB_GRIEFING)) { + if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, body)) { return false; - } - -@@ -120,6 +_,11 @@ - level.setBlockAndUpdate(this.aboveFarmlandPos, place); - level.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(body, place)); - ok = true; -+ } else if (itemStack.getItem() instanceof net.minecraftforge.common.IPlantable) { -+ if (((net.minecraftforge.common.IPlantable) itemStack.getItem()).getPlantType(level, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { -+ level.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable) itemStack.getItem()).getPlant(level, aboveFarmlandPos), 3); -+ ok = true; + } else if (!body.getVillagerData().profession().is(VillagerProfession.FARMER)) { + return false; +@@ -118,6 +_,11 @@ + level.setBlockAndUpdate(this.aboveFarmlandPos, blockstate1); + level.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(body, blockstate1)); + flag = true; ++ } else if (itemstack.getItem() instanceof net.minecraftforge.common.IPlantable) { ++ if (((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlantType(level, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { ++ level.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlant(level, aboveFarmlandPos), 3); ++ flag = true; + } } - if (ok) { + 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 f329ae56a8..272126ac2c 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,14 +1,15 @@ --- a/net/minecraft/world/entity/ai/behavior/StartAttacking.java +++ b/net/minecraft/world/entity/ai/behavior/StartAttacking.java -@@ -32,6 +_,11 @@ - return false; - } - -+ var changeTargetEvent = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetBehavior(body, targetEntity); -+ if (changeTargetEvent == null) -+ return false; -+ targetEntity = changeTargetEvent.getNewTarget(); +@@ -30,7 +_,11 @@ + if (!body.canAttack(livingentity)) { + return false; + } else { +- attackTarget.set(livingentity); ++ var changeTargetEvent = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetBehavior(body, livingentity); ++ if (changeTargetEvent == null) ++ return false; + - attackTarget.set(targetEntity); - cantReachSince.erase(); - return true; ++ attackTarget.set(changeTargetEvent.getNewTarget()); + cantReachSince.erase(); + return true; + } 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 8774cdbd17..74cd9f288c 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 @@ -2,19 +2,19 @@ +++ b/net/minecraft/world/entity/ai/goal/EatBlockGoal.java @@ -61,7 +_,7 @@ if (this.eatAnimationTick == this.adjustedTickDelay(4)) { - BlockPos pos = this.mob.blockPosition(); - if (IS_EDIBLE.test(this.level.getBlockState(pos))) { + BlockPos blockpos = this.mob.blockPosition(); + if (IS_EDIBLE.test(this.level.getBlockState(blockpos))) { - if (getServerLevel(this.level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.level), this.mob)) { - this.level.destroyBlock(pos, false); + this.level.destroyBlock(blockpos, false); } @@ -69,7 +_,7 @@ } else { - BlockPos below = pos.below(); - if (this.level.getBlockState(below).is(Blocks.GRASS_BLOCK)) { + BlockPos blockpos1 = blockpos.below(); + if (this.level.getBlockState(blockpos1).is(Blocks.GRASS_BLOCK)) { - if (getServerLevel(this.level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.level), this.mob)) { - this.level.levelEvent(2001, below, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState())); - this.level.setBlock(below, Blocks.DIRT.defaultBlockState(), 2); + 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/MeleeAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch index ae288af77b..f5f27e8f56 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 @@ -9,32 +9,31 @@ public MeleeAttackGoal(final PathfinderMob mob, final double speedModifier, final boolean followingTargetEvenIfNotSeen) { this.mob = mob; -@@ -46,6 +_,16 @@ - return false; - } - -+ if (canPenalize) { -+ if (--this.ticksUntilNextPathRecalculation <= 0) { -+ this.path = this.mob.getNavigation().createPath(target, 0); -+ this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); -+ return this.path != null? true : this.mob.isWithinMeleeAttackRange(target); -+ } else { -+ return true; -+ } -+ } -+ - this.path = this.mob.getNavigation().createPath(target, 0); - return this.path != null ? true : this.mob.isWithinMeleeAttackRange(target); - } +@@ -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 = target.getZ(); + this.pathedTargetZ = livingentity.getZ(); this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); - double targetDistanceSqr = this.mob.distanceToSqr(target); + double d0 = this.mob.distanceToSqr(livingentity); + if (this.canPenalize) { + this.ticksUntilNextPathRecalculation += failedPathFindingPenalty; + if (this.mob.getNavigation().getPath() != null) { -+ var finalPathPoint = this.mob.getNavigation().getPath().getEndNode(); -+ if (finalPathPoint != null && target.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) ++ 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; @@ -42,6 +41,6 @@ + failedPathFindingPenalty += 10; + } + } - if (targetDistanceSqr > 1024.0) { + if (d0 > 1024.0) { this.ticksUntilNextPathRecalculation += 10; - } else if (targetDistanceSqr > 256.0) { + } else if (d0 > 256.0) { 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 986b766ffa..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 @@ -10,9 +10,9 @@ @Override @@ -99,7 +_,7 @@ - this.mob.getLookControl().setLookAt(target, 30.0F, 30.0F); + this.mob.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); if (this.crossbowState == RangedCrossbowAttackGoal.CrossbowState.UNCHARGED) { - if (!needsToMove) { + 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; 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 cd49045c6c..456058e5ba 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 @@ -9,11 +9,13 @@ return false; } else if (this.nextStartTick > 0) { this.nextStartTick--; -@@ -139,6 +_,6 @@ - ChunkAccess chunk = level.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()), ChunkStatus.FULL, false); - return chunk == null +@@ -142,7 +_,8 @@ + ); + return chunkaccess == null ? false -- : chunk.getBlockState(pos).is(this.blockToRemove) && chunk.getBlockState(pos.above()).isAir() && chunk.getBlockState(pos.above(2)).isAir(); -+ : chunk.getBlockState(pos).canEntityDestroy(level, pos, this.removerMob) && chunk.getBlockState(pos).is(this.blockToRemove) && chunk.getBlockState(pos.above()).isAir() && chunk.getBlockState(pos.above(2)).isAir(); +- : chunkaccess.getBlockState(pos).is(this.blockToRemove) ++ : !chunkaccess.getBlockState(pos).canEntityDestroy(level, pos, this.removerMob) ? false ++ : chunkaccess.getBlockState(pos).is(this.blockToRemove) + && chunkaccess.getBlockState(pos.above()).isAir() + && chunkaccess.getBlockState(pos.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 771a960db6..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 @@ -58,7 +_,7 @@ - if (passenger instanceof Player player) { - int temper = this.horse.getTemper(); - int maxTemper = this.horse.getMaxTemper(); -- if (maxTemper > 0 && this.horse.getRandom().nextInt(maxTemper) < temper) { -+ if (maxTemper > 0 && this.horse.getRandom().nextInt(maxTemper) < temper && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(horse, player)) { + 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/goal/target/HurtByTargetGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch index ca4da7708f..a91e71107a 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch @@ -3,11 +3,11 @@ @@ -83,6 +_,10 @@ } - other = (Mob)var5.next(); + mob = (Mob)iterator.next(); + // Fix NPE if modders do things vanilla doesn't expect. https://github.com/MinecraftForge/MinecraftForge/issues/7853 + if (this.mob.getLastHurtByMob() == null) + return; + - if (this.mob != other - && other.getTarget() == null - && (!(this.mob instanceof TamableAnimal tamableAnimal) || tamableAnimal.getOwner() == ((TamableAnimal)other).getOwner()) + if (this.mob != mob + && mob.getTarget() == null + && (!(this.mob instanceof TamableAnimal) || ((TamableAnimal)this.mob).getOwner() == ((TamableAnimal)mob).getOwner()) 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 2864829c1b..8d2fdb7964 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,21 +1,16 @@ --- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java -@@ -248,12 +_,13 @@ - Vec3 mobPos = this.getTempMobPos(); +@@ -242,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 currentNodePos = this.path.getNextNodePos(); -- double xDistance = Math.abs(this.mob.getX() - (currentNodePos.getX() + 0.5)); -+ //Forge: Fix MC-94054 make so jvm doesn't down grade to float math by casting to doubles -+ double xDistance = Math.abs(this.mob.getX() - ((double)currentNodePos.getX() + (this.mob.getBbWidth() + 1) / 2D)); - double yDistance = Math.abs(this.mob.getY() - currentNodePos.getY()); -- double zDistance = Math.abs(this.mob.getZ() - (currentNodePos.getZ() + 0.5)); -- boolean isCloseEnoughToCurrentNode = xDistance < this.maxDistanceToWaypoint -- && zDistance < this.maxDistanceToWaypoint -- && yDistance < this.getMaxVerticalDistanceToWaypoint(); -+ double zDistance = Math.abs(this.mob.getZ() - ((double)currentNodePos.getZ() + (this.mob.getBbWidth() + 1) / 2D)); -+ boolean isCloseEnoughToCurrentNode = xDistance <= (double)this.maxDistanceToWaypoint -+ && zDistance <= (double)this.maxDistanceToWaypoint -+ && yDistance < (double)this.getMaxVerticalDistanceToWaypoint(); - if (isCloseEnoughToCurrentNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPos)) { + Vec3i vec3i = this.path.getNextNodePos(); +- double d0 = Math.abs(this.mob.getX() - (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() - vec3i.getY()); +- double d2 = Math.abs(this.mob.getZ() - (vec3i.getZ() + 0.5)); +- boolean flag = d0 < this.maxDistanceToWaypoint && d2 < 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/village/VillageSiege.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch index e39a203133..625ea6aecc 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,9 +1,9 @@ --- a/net/minecraft/world/entity/ai/village/VillageSiege.java +++ b/net/minecraft/world/entity/ai/village/VillageSiege.java @@ -78,7 +_,10 @@ - this.spawnX = center.getX() + Mth.floor(Mth.cos(angle) * 32.0F); - this.spawnY = center.getY(); - this.spawnZ = center.getZ() + Mth.floor(Mth.sin(angle) * 32.0F); + 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(level, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)) != null) { + Vec3 siegeLocation = this.findRandomSpawnPos(level, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)); + if (siegeLocation != null) { @@ -13,11 +13,11 @@ this.zombiesToSpawn = 20; break; @@ -98,7 +_,7 @@ - if (spawnPos != null) { + if (vec3 != null) { Zombie zombie; try { - zombie = new Zombie(level); -+ zombie = EntityTypes.ZOMBIE.create(level, EntitySpawnReason.EVENT); //Forge: Direct Initialization is deprecated, use EntityType. ++ zombie = EntityType.ZOMBIE.create(level, EntitySpawnReason.EVENT); //Forge: Direct Initialization is deprecated, use EntityType. zombie.finalizeSpawn(level, level.getCurrentDifficultyAt(zombie.blockPosition()), EntitySpawnReason.EVENT, null); - } catch (Exception e) { - LOGGER.warn("Failed to create zombie for village siege at {}", spawnPos, e); + } 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 7fe4a5237d..a7cda5bfac 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,6 +1,6 @@ --- a/net/minecraft/world/entity/ai/village/poi/PoiTypes.java +++ b/net/minecraft/world/entity/ai/village/poi/PoiTypes.java -@@ -56,7 +_,7 @@ +@@ -80,7 +_,7 @@ .stream() .flatMap(block -> block.getStateDefinition().getPossibleStates().stream()) .collect(ImmutableSet.toImmutableSet()); @@ -9,11 +9,11 @@ private static Set getBlockStates(final Block block) { return ImmutableSet.copyOf(block.getStateDefinition().getPossibleStates()); -@@ -71,7 +_,6 @@ +@@ -95,7 +_,6 @@ ) { - PoiType value = new PoiType(matchingStates, maxTickets, validRange); - Registry.register(registry, id, value); + PoiType poitype = new PoiType(matchingStates, maxTickets, validRange); + Registry.register(registry, id, poitype); - registerBlockStates(registry.getOrThrow(id), matchingStates); - return value; + return poitype; } 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 62dbc2071d..400ed425de 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch @@ -3,10 +3,10 @@ @@ -208,6 +_,17 @@ public void spawnChildFromBreeding(final ServerLevel level, final Animal partner) { - AgeableMob offspring = this.getBreedOffspring(level, partner); -+ final var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, partner, offspring); + AgeableMob ageablemob = this.getBreedOffspring(level, partner); ++ final var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, partner, ageablemob); + final boolean cancelled = net.minecraftforge.event.entity.living.BabyEntitySpawnEvent.BUS.post(event); -+ offspring = event.getChild(); ++ ageablemob = event.getChild(); + if (cancelled) { + //Reset the "inLove" state for the animals + this.setAge(6000); @@ -15,6 +15,6 @@ + partner.resetLove(); + return; + } - if (offspring != null) { - offspring.setBaby(true); - offspring.snapTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); + if (ageablemob != null) { + ageablemob.setBaby(true); + ageablemob.snapTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); 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 1b8ffb5728..6317c63315 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,11 @@ --- a/net/minecraft/world/entity/animal/allay/Allay.java +++ b/net/minecraft/world/entity/animal/allay/Allay.java -@@ -341,7 +_,7 @@ +@@ -336,7 +_,7 @@ public boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack) { - ItemStack itemInHand = this.getItemInHand(InteractionHand.MAIN_HAND); - return !itemInHand.isEmpty() + ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); + return !itemstack.isEmpty() - && level.getGameRules().get(GameRules.MOB_GRIEFING) + && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this) && this.inventory.canAddItem(itemStack) - && this.allayConsidersItemEqual(itemInHand, itemStack); + && this.allayConsidersItemEqual(itemstack, itemStack); } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch index c9f7edb036..0122e94011 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch @@ -1,17 +1,17 @@ --- a/net/minecraft/world/entity/animal/bee/Bee.java +++ b/net/minecraft/world/entity/animal/bee/Bee.java -@@ -473,7 +_,9 @@ +@@ -483,7 +_,9 @@ if (this.hivePos == null) { return null; } else { -- return this.isTooFarAway(this.hivePos) ? null : this.level().getBlockEntity(this.hivePos, BlockEntityTypes.BEEHIVE).orElse(null); +- return this.isTooFarAway(this.hivePos) ? null : this.level().getBlockEntity(this.hivePos, BlockEntityType.BEEHIVE).orElse(null); + if (!this.isTooFarAway(this.hivePos) && this.level().getBlockEntity(this.hivePos) instanceof BeehiveBlockEntity hiveEntity) + return hiveEntity; + return null; } } -@@ -639,13 +_,22 @@ +@@ -649,13 +_,22 @@ } @Override 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 929afa8956..ae3cf693ef 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,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/camel/Camel.java +++ b/net/minecraft/world/entity/animal/camel/Camel.java -@@ -365,7 +_,7 @@ +@@ -359,7 +_,7 @@ @Override protected void playStepSound(final BlockPos pos, final BlockState blockState) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch index 9bb7975d6a..5f90c66e95 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch @@ -1,28 +1,57 @@ --- a/net/minecraft/world/entity/animal/cow/MushroomCow.java +++ b/net/minecraft/world/entity/animal/cow/MushroomCow.java -@@ -122,7 +_,7 @@ +@@ -114,7 +_,7 @@ - this.playSound(milkSound, 1.0F, 1.0F); + this.playSound(soundevent, 1.0F, 1.0F); return InteractionResult.SUCCESS; -- } else if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { -+ } else if (itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.readyForShearing()) { - if (this.level() instanceof ServerLevel level) { - this.shear(level, SoundSource.PLAYERS, itemStack); +- } else if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ } else if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { + if (this.level() instanceof ServerLevel serverlevel) { + this.shear(serverlevel, SoundSource.PLAYERS, itemstack); this.gameEvent(GameEvent.SHEAR, player); -@@ -178,6 +_,8 @@ +@@ -170,15 +_,26 @@ @Override public void shear(final ServerLevel level, final SoundSource soundSource, final ItemStack tool) { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.COW, time -> {})) -+ return; ++ for (var stack : shearInternal(level, soundSource, tool)) { ++ for (int i = 0; i < stack.getCount(); i++) { ++ this.level().addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0D), this.getZ(), stack.copyWithCount(1))); ++ } ++ } ++ } ++ ++ private java.util.List shearInternal(ServerLevel level, SoundSource soundSource, ItemStack tool) { ++ var ret = new java.util.ArrayList(); ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.COW, time -> {})) ++ return ret; level.playSound(null, this, SoundEvents.MOOSHROOM_SHEAR, soundSource, 1.0F, 1.0F); - this.convertTo(EntityTypes.COW, ConversionParams.single(this, false, false), cow -> { + this.convertTo(EntityType.COW, ConversionParams.single(this, false, false), cow -> { level.sendParticles(ParticleTypes.EXPLOSION, this.getX(), this.getY(0.5), this.getZ(), 1, 0.0, 0.0, 0.0, 0.0); -@@ -186,6 +_,7 @@ - l.addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0), this.getZ(), drop.copyWithCount(1))); - } + this.dropFromShearingLootTable(level, BuiltInLootTables.SHEAR_MOOSHROOM, tool, (l, drop) -> { +- for (int i = 0; i < drop.getCount(); i++) { +- l.addFreshEntity(new ItemEntity(this.level(), this.getX(), this.getY(1.0), this.getZ(), drop.copyWithCount(1))); +- } ++ ret.add(tool); }); + net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, cow); }); ++ return ret; } + @Override +@@ -254,6 +_,15 @@ + } + + return mushroomcow$variant2; ++ } ++ ++ @Override ++ public java.util.List onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { ++ if (world instanceof ServerLevel server) { ++ this.gameEvent(GameEvent.SHEAR, player); ++ return shearInternal(server, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, item); ++ } ++ return java.util.Collections.emptyList(); + } + + public static enum Variant implements StringRepresentable { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch index de0805d2b9..8db3819f1d 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/equine/AbstractHorse.java +++ b/net/minecraft/world/entity/animal/equine/AbstractHorse.java -@@ -142,6 +_,7 @@ +@@ -144,6 +_,7 @@ } this.addBehaviourGoals(); @@ -8,7 +8,7 @@ } protected void addBehaviourGoals() { -@@ -277,17 +_,20 @@ +@@ -279,16 +_,19 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { @@ -20,33 +20,32 @@ this.playSound(this.isBaby() ? SoundEvents.HORSE_LAND_BABY : SoundEvents.HORSE_LAND, 0.4F, 1.0F); } -- int dmg = this.calculateFallDamage(fallDistance, damageModifier); -+ int dmg = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); - if (dmg <= 0) { +- int i = this.calculateFallDamage(fallDistance, damageModifier); ++ int i = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); + if (i <= 0) { return false; + } else { + this.hurt(damageSource, i); +- this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); ++ this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); + this.playBlockFallSound(); + return true; } - - this.hurt(damageSource, dmg); -- this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); -+ this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); - this.playBlockFallSound(); - return true; - } -@@ -342,9 +_,9 @@ +@@ -344,9 +_,9 @@ protected void playStepSound(final BlockPos pos, final BlockState blockState) { if (!blockState.liquid()) { - BlockState aboveState = this.level().getBlockState(pos.above()); -- SoundType soundType = blockState.getSoundType(); -+ SoundType soundType = blockState.getSoundType(level(), pos, this); - if (aboveState.is(Blocks.SNOW)) { -- soundType = aboveState.getSoundType(); -+ soundType = aboveState.getSoundType(level(), pos.above(), this); + BlockState blockstate = this.level().getBlockState(pos.above()); +- SoundType soundtype = blockState.getSoundType(); ++ SoundType soundtype = blockState.getSoundType(level(), pos, this); + if (blockstate.is(Blocks.SNOW)) { +- soundtype = blockstate.getSoundType(); ++ soundtype = blockstate.getSoundType(level(), pos.above(), this); } if (this.isVehicle() && this.canGallop) { @@ -778,6 +_,7 @@ - float cos = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)); - this.setDeltaMovement(this.getDeltaMovement().add(-0.4F * sin * amount, 0.0, 0.4F * cos * amount)); + float f1 = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)); + this.setDeltaMovement(this.getDeltaMovement().add(-0.4F * f * amount, 0.0, 0.4F * f1 * amount)); } + net.minecraftforge.common.ForgeHooks.onLivingJump(this); } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch index 14b2350f5e..ce0078bec2 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch @@ -1,22 +1,21 @@ --- a/net/minecraft/world/entity/animal/equine/Llama.java +++ b/net/minecraft/world/entity/animal/equine/Llama.java -@@ -370,14 +_,16 @@ +@@ -369,13 +_,15 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { -- int dmg = this.calculateFallDamage(fallDistance, damageModifier); +- int i = this.calculateFallDamage(fallDistance, damageModifier); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, fallDistance, damageModifier); + if (event == null) return false; -+ int dmg = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); - if (dmg <= 0) { ++ int i = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); + if (i <= 0) { return false; - } + } else { +- if (fallDistance >= 6.0) { ++ if (event.getDistance() >= 6.0) { + this.hurt(damageSource, i); +- this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); ++ this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); + } -- if (fallDistance >= 6.0) { -+ if (event.getDistance() >= 6.0) { - this.hurt(damageSource, dmg); -- this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); -+ this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); - } - - this.playBlockFallSound(); + this.playBlockFallSound(); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch index 8fed45b75d..09b0dbd893 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch @@ -3,14 +3,14 @@ @@ -31,6 +_,13 @@ @Override public void tick() { - ServerLevel level = (ServerLevel)this.horse.level(); + 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) -+ level.getServer().schedule(level.getServer().wrapRunnable(() -> this.convert(level))); ++ serverlevel.getServer().schedule(serverlevel.getServer().wrapRunnable(() -> this.convert(serverlevel))); + } + -+ private void convert(ServerLevel level) { ++ private void convert(ServerLevel serverlevel) { + if (!this.horse.isAlive()) return; - DifficultyInstance difficulty = level.getCurrentDifficultyAt(this.horse.blockPosition()); + DifficultyInstance difficultyinstance = serverlevel.getCurrentDifficultyAt(this.horse.blockPosition()); this.horse.setTrap(false); this.horse.setTamed(true); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch index cb68fc763b..f667dd8ac5 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/feline/Cat.java +++ b/net/minecraft/world/entity/animal/feline/Cat.java -@@ -485,7 +_,7 @@ +@@ -474,7 +_,7 @@ } private void tryToTame(final Player player) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch index a7507eaadc..89727d4951 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/world/entity/animal/feline/Ocelot.java +++ b/net/minecraft/world/entity/animal/feline/Ocelot.java -@@ -168,7 +_,7 @@ - if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemStack) && player.distanceToSqr(this) < 9.0) { - this.usePlayerItem(player, hand, itemStack); +@@ -161,7 +_,7 @@ + if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemstack) && player.distanceToSqr(this) < 9.0) { + this.usePlayerItem(player, hand, itemstack); if (!this.level().isClientSide()) { - if (this.random.nextInt(3) == 0) { + if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, player)) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch index fd188324e4..93b2230e0e 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/entity/animal/fox/Fox.java +++ b/net/minecraft/world/entity/animal/fox/Fox.java -@@ -872,6 +_,17 @@ +@@ -878,6 +_,17 @@ @Override protected void breed() { - Fox offspring = (Fox)this.animal.getBreedOffspring(this.level, this.partner); -+ var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(animal, partner, offspring); + Fox fox = (Fox)this.animal.getBreedOffspring(this.level, this.partner); ++ var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(animal, partner, fox); + var eventWasCancelled = net.minecraftforge.event.entity.living.BabyEntitySpawnEvent.BUS.post(event); -+ offspring = (Fox)event.getChild(); ++ fox = (Fox)event.getChild(); + if (eventWasCancelled) { + //Reset the "inLove" state for the animals + this.animal.setAge(6000); @@ -15,19 +15,19 @@ + this.partner.resetLove(); + return; + } - if (offspring != null) { - ServerPlayer animalLoveCause = this.animal.getLoveCause(); - ServerPlayer partnerLoveCause = this.partner.getLoveCause(); -@@ -949,7 +_,7 @@ + if (fox != null) { + ServerPlayer serverplayer = this.animal.getLoveCause(); + ServerPlayer serverplayer1 = this.partner.getLoveCause(); +@@ -956,7 +_,7 @@ } protected void onReachedTarget() { - if (getServerLevel(Fox.this.level()).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(Fox.this.level()), Fox.this)) { - BlockState state = Fox.this.level().getBlockState(this.blockPos); - if (state.is(Blocks.SWEET_BERRY_BUSH)) { - this.pickSweetBerries(state); -@@ -1008,7 +_,7 @@ + BlockState blockstate = Fox.this.level().getBlockState(this.blockPos); + if (blockstate.is(Blocks.SWEET_BERRY_BUSH)) { + this.pickSweetBerries(blockstate); +@@ -1016,7 +_,7 @@ @Override public boolean canUse() { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch index 4c1a2e6a52..e561961649 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch @@ -4,8 +4,27 @@ } Level level = this.level(); -- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.readyForShearing()) { - if (level instanceof ServerLevel serverLevel) { - this.shear(serverLevel, SoundSource.PLAYERS, itemStack); +- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: Moved to onSheared + if (level instanceof ServerLevel serverlevel) { + this.shear(serverlevel, SoundSource.PLAYERS, itemstack); this.gameEvent(GameEvent.SHEAR, player); +@@ -427,6 +_,18 @@ + ItemStack itemstack = this.getItemBySlot(EQUIPMENT_SLOT_ANTENNA); + this.setItemSlot(EQUIPMENT_SLOT_ANTENNA, ItemStack.EMPTY); + this.spawnAtLocation(level, itemstack, 1.5F); ++ } ++ ++ @Override ++ public java.util.List onSheared(@Nullable Player player, ItemStack item, Level world, net.minecraft.core.BlockPos pos, int fortune) { ++ if (world instanceof ServerLevel server) { ++ server.playSound(null, this, SoundEvents.COPPER_GOLEM_SHEAR, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, 1.0F, 1.0F); ++ var ret = new java.util.ArrayList(); ++ ret.add(this.getItemBySlot(EQUIPMENT_SLOT_ANTENNA)); ++ this.setItemSlot(EQUIPMENT_SLOT_ANTENNA, ItemStack.EMPTY); ++ return ret; ++ } ++ return java.util.Collections.emptyList(); + } + + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch index cf1375a26d..b8e6e513aa 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch @@ -1,29 +1,56 @@ --- a/net/minecraft/world/entity/animal/golem/SnowGolem.java +++ b/net/minecraft/world/entity/animal/golem/SnowGolem.java +@@ -42,7 +_,7 @@ + import net.minecraft.world.phys.Vec3; + import org.jspecify.annotations.Nullable; + +-public class SnowGolem extends AbstractGolem implements RangedAttackMob, Shearable { ++public class SnowGolem extends AbstractGolem implements RangedAttackMob, Shearable, 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 boolean DEFAULT_PUMPKIN = true; @@ -95,7 +_,7 @@ - this.hurtServer(serverLevel, this.damageSources().onFire(), 1.0F); + this.hurtServer(serverlevel, this.damageSources().onFire(), 1.0F); } -- if (!serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { +- if (!serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this)) { return; } @@ -106,7 +_,7 @@ - int yy = Mth.floor(this.getY()); - int zz = Mth.floor(this.getZ() + (i / 2 % 2 * 2 - 1) * 0.25F); - BlockPos snowPos = new BlockPos(xx, yy, zz); -- if (this.level().getBlockState(snowPos).isAir() && snow.canSurvive(this.level(), snowPos)) { -+ if (this.level().isEmptyBlock(snowPos) && snow.canSurvive(this.level(), snowPos)) { - this.level().setBlockAndUpdate(snowPos, snow); - this.level().gameEvent(GameEvent.BLOCK_PLACE, snowPos, GameEvent.Context.of(this, snow)); + int k = Mth.floor(this.getY()); + int l = Mth.floor(this.getZ() + (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)); } @@ -136,7 +_,7 @@ @Override protected InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); -- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.readyForShearing()) { - if (this.level() instanceof ServerLevel level) { - this.shear(level, SoundSource.PLAYERS, itemStack); + ItemStack itemstack = player.getItemInHand(hand); +- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { //Forge: Moved to onSheared + if (this.level() instanceof ServerLevel serverlevel) { + this.shear(serverlevel, SoundSource.PLAYERS, itemstack); this.gameEvent(GameEvent.SHEAR, player); +@@ -193,4 +_,17 @@ + public Vec3 getLeashOffset() { + return new Vec3(0.0, 0.75F * this.getEyeHeight(), this.getBbWidth() * 0.4F); + } ++ ++ @Override ++ public java.util.@org.jspecify.annotations.NonNull List onSheared(@Nullable Player player, @org.jspecify.annotations.NonNull 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() && world instanceof ServerLevel server) { ++ setPumpkin(false); ++ var ret = new java.util.ArrayList(); ++ this.dropFromShearingLootTable(server, BuiltInLootTables.SHEAR_SNOW_GOLEM, item, (slevel, stack) -> ret.add(stack)); ++ return ret; ++ } ++ return java.util.Collections.emptyList(); ++ } + } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch index ae308792f5..5696c2c99f 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/parrot/Parrot.java +++ b/net/minecraft/world/entity/animal/parrot/Parrot.java -@@ -268,7 +_,7 @@ +@@ -269,7 +_,7 @@ } if (!this.level().isClientSide()) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch index 53549b8944..819e5bdb7f 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/animal/pig/Pig.java +++ b/net/minecraft/world/entity/animal/pig/Pig.java -@@ -200,10 +_,11 @@ +@@ -194,10 +_,11 @@ @Override public void thunderHit(final ServerLevel level, final LightningBolt lightningBolt) { - if (level.getDifficulty() != Difficulty.PEACEFUL) { -+ if (level.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.ZOMBIFIED_PIGLIN, (timer) -> {})) { - ZombifiedPiglin zombifiedPiglin = this.convertTo(EntityTypes.ZOMBIFIED_PIGLIN, ConversionParams.single(this, false, true), zp -> { ++ if (level.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> {})) { + ZombifiedPiglin zombifiedpiglin = this.convertTo(EntityType.ZOMBIFIED_PIGLIN, ConversionParams.single(this, false, true), zp -> { zp.populateDefaultEquipmentSlots(this.getRandom(), level.getCurrentDifficultyAt(this.blockPosition())); zp.setPersistenceRequired(); + net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zp); }); - if (zombifiedPiglin == null) { + if (zombifiedpiglin == null) { super.thunderHit(level, lightningBolt); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch index a855468db0..2ec80e1736 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/rabbit/Rabbit.java +++ b/net/minecraft/world/entity/animal/rabbit/Rabbit.java -@@ -603,7 +_,7 @@ +@@ -604,7 +_,7 @@ @Override public boolean canUse() { if (this.nextStartTick <= 0) { @@ -9,12 +9,12 @@ return false; } -@@ -652,7 +_,7 @@ +@@ -653,7 +_,7 @@ @Override protected boolean isValidTarget(final LevelReader level, final BlockPos pos) { - BlockState state = level.getBlockState(pos); -- if (state.is(BlockTags.SUPPORTS_CROPS) && this.wantsToRaid && !this.canRaid) { -+ if ((state.is(BlockTags.SUPPORTS_CROPS) || state.getBlock() instanceof net.minecraft.world.level.block.FarmlandBlock) && this.wantsToRaid && !this.canRaid) { - state = level.getBlockState(pos.above()); - if (state.getBlock() instanceof CarrotBlock carrotBlock && carrotBlock.isMaxAge(state)) { + BlockState blockstate = level.getBlockState(pos); +- if (blockstate.is(BlockTags.SUPPORTS_CROPS) && this.wantsToRaid && !this.canRaid) { ++ if (blockstate.getBlock() instanceof net.minecraft.world.level.block.FarmlandBlock && this.wantsToRaid && !this.canRaid) { + blockstate = level.getBlockState(pos.above()); + if (blockstate.getBlock() instanceof CarrotBlock carrotblock && carrotblock.isMaxAge(blockstate)) { this.canRaid = true; diff --git a/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch index 7d90cbab8d..9b11fcd9f6 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch @@ -1,11 +1,56 @@ --- a/net/minecraft/world/entity/animal/sheep/Sheep.java +++ b/net/minecraft/world/entity/animal/sheep/Sheep.java -@@ -145,7 +_,7 @@ +@@ -137,7 +_,7 @@ @Override public InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); -- if (itemStack.is(Items.SHEARS)) { -+ if (itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - if (this.level() instanceof ServerLevel level && this.readyForShearing()) { - this.shear(level, SoundSource.PLAYERS, itemStack); + ItemStack itemstack = player.getItemInHand(hand); +- if (itemstack.is(Items.SHEARS)) { ++ if (false && itemstack.is(Items.SHEARS)) { // Forge: Moved to onSheared + if (this.level() instanceof ServerLevel serverlevel && this.readyForShearing()) { + this.shear(serverlevel, SoundSource.PLAYERS, itemstack); this.gameEvent(GameEvent.SHEAR, player); +@@ -153,12 +_,27 @@ + + @Override + public void shear(final ServerLevel level, final SoundSource soundSource, final ItemStack tool) { ++ dropItems(level, shearInternal(level, soundSource, tool)); ++ } ++ ++ private java.util.List shearInternal(ServerLevel level, SoundSource soundSource, ItemStack tool) { ++ var ret = new java.util.ArrayList(); + level.playSound(null, this, SoundEvents.SHEEP_SHEAR, soundSource, 1.0F, 1.0F); + this.dropFromShearingLootTable( + level, + BuiltInLootTables.SHEAR_SHEEP, + tool, + (l, drop) -> { ++ ret.add(drop); ++ } ++ ); ++ this.setSheared(true); ++ return ret; ++ } ++ ++ private void dropItems(ServerLevel l, java.util.Collection items) { ++ // double indented to make the patch look nicer ++ for (var drop : items) { + for (int i = 0; i < drop.getCount(); i++) { + ItemEntity itementity = this.spawnAtLocation(l, drop.copyWithCount(1), 1.0F); + if (itementity != null) { +@@ -173,8 +_,14 @@ + } + } + } +- ); +- this.setSheared(true); ++ } ++ ++ @Override ++ public java.util.List onSheared(@Nullable Player player, ItemStack item, Level level, BlockPos pos, int fortune) { ++ if (level instanceof ServerLevel server) { ++ return shearInternal(server, player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS, item); ++ } ++ return java.util.Collections.emptyList(); + } + + @Override 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 588a18f224..c33806747a 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,11 @@ --- a/net/minecraft/world/entity/animal/sniffer/Sniffer.java +++ b/net/minecraft/world/entity/animal/sniffer/Sniffer.java -@@ -308,7 +_,7 @@ +@@ -307,7 +_,7 @@ if (this.tickCount % 10 == 0) { this.level() .playLocalSound( -- this.getX(), this.getY(), this.getZ(), stateBelow.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false -+ this.getX(), this.getY(), this.getZ(), stateBelow.getSoundType(level(), head.below(), this).getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false +- this.getX(), this.getY(), this.getZ(), blockstate.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false ++ 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/animal/wolf/Wolf.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/wolf/Wolf.java.patch index 735cb4dd6e..ba11d99b33 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/wolf/Wolf.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/wolf/Wolf.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/wolf/Wolf.java +++ b/net/minecraft/world/entity/animal/wolf/Wolf.java -@@ -506,7 +_,7 @@ +@@ -499,7 +_,7 @@ } private void tryToTame(final Player player) { 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 3d2e4e1e57..c3a9d284a1 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,6 +1,22 @@ --- a/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java +++ b/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java -@@ -150,8 +_,26 @@ +@@ -100,6 +_,15 @@ + this.setHealth(this.getMaxHealth()); + this.noPhysics = 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 id) { ++ super.setId(id); ++ 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(id + i + 1); ++ } + } + + public void setDragonFight(final EnderDragonFight fight) { +@@ -148,8 +_,26 @@ entityData.define(DATA_PHASE, EnderDragonPhase.HOVERING.getId()); } @@ -27,36 +43,44 @@ this.processFlappingMovement(); if (this.level().isClientSide()) { this.setHealth(this.getHealth()); -@@ -436,7 +_,7 @@ - BlockPos blockPos = new BlockPos(x, y, z); - BlockState state = level.getBlockState(blockPos); - if (!state.isAir() && !state.is(BlockTags.DRAGON_TRANSPARENT)) { -- if (level.getGameRules().get(GameRules.MOB_GRIEFING) && !state.is(BlockTags.DRAGON_IMMUNE)) { -+ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(level, blockPos, this) && !state.is(BlockTags.DRAGON_IMMUNE)) { - destroyedBlock = level.removeBlock(blockPos, false) || destroyedBlock; +@@ -438,7 +_,7 @@ + BlockPos blockpos = new BlockPos(k1, l1, i2); + BlockState blockstate = level.getBlockState(blockpos); + if (!blockstate.isAir() && !blockstate.is(BlockTags.DRAGON_TRANSPARENT)) { +- if (level.getGameRules().get(GameRules.MOB_GRIEFING) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { ++ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(level, blockpos, this) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { + flag1 = level.removeBlock(blockpos, false) || flag1; } else { - hitWall = true; -@@ -540,7 +_,8 @@ + flag = true; +@@ -537,7 +_,8 @@ - if (this.level() instanceof ServerLevel level) { - if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && level.getGameRules().get(GameRules.MOB_DROPS)) { -- ExperienceOrb.award(level, this.position(), Mth.floor(xpCount * 0.08F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)xpCount * 0.08F)); -+ ExperienceOrb.award(level, this.position(), award); + if (this.level() instanceof ServerLevel serverlevel) { + if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && serverlevel.getGameRules().get(GameRules.MOB_DROPS)) { +- ExperienceOrb.award(serverlevel, this.position(), Mth.floor(i * 0.08F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)i * 0.08F)); ++ ExperienceOrb.award(serverlevel, this.position(), award); } if (this.dragonDeathTime == 1 && !this.isSilent()) { -@@ -558,7 +_,8 @@ +@@ -555,7 +_,8 @@ - if (this.dragonDeathTime >= 200 && this.level() instanceof ServerLevel level) { - if (level.getGameRules().get(GameRules.MOB_DROPS)) { -- ExperienceOrb.award(level, this.position(), Mth.floor(xpCount * 0.2F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)xpCount * 0.2F)); -+ ExperienceOrb.award(level, this.position(), award); + if (this.dragonDeathTime >= 200 && this.level() instanceof ServerLevel serverlevel1) { + if (serverlevel1.getGameRules().get(GameRules.MOB_DROPS)) { +- ExperienceOrb.award(serverlevel1, this.position(), Mth.floor(i * 0.2F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)i * 0.2F)); ++ ExperienceOrb.award(serverlevel1, this.position(), award); } if (this.dragonFight != null) { -@@ -884,5 +_,15 @@ +@@ -861,6 +_,7 @@ + @Override + public void recreateFromPacket(final ClientboundAddEntityPacket packet) { + super.recreateFromPacket(packet); ++ if (true) return; // Forge: Fix MC-158205: Moved into setId() + EnderDragonPart[] aenderdragonpart = this.getSubEntities(); + + for (int i = 0; i < aenderdragonpart.length; i++) { +@@ -876,5 +_,15 @@ @Override protected float sanitizeScale(final float scale) { return 1.0F; 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 e4c3d2af8c..be377916c3 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,24 +1,24 @@ --- a/net/minecraft/world/entity/boss/wither/WitherBoss.java +++ b/net/minecraft/world/entity/boss/wither/WitherBoss.java -@@ -319,7 +_,7 @@ +@@ -323,7 +_,7 @@ if (this.destroyBlocksTick > 0) { this.destroyBlocksTick--; - if (this.destroyBlocksTick == 0 && level.getGameRules().get(GameRules.MOB_GRIEFING)) { + if (this.destroyBlocksTick == 0 && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this)) { - boolean destroyed = false; - int width = Mth.floor(this.getBbWidth() / 2.0F + 1.0F); - int height = Mth.floor(this.getBbHeight()); -@@ -333,7 +_,7 @@ - this.getBlockZ() + width + boolean flag = false; + int l = Mth.floor(this.getBbWidth() / 2.0F + 1.0F); + int i1 = Mth.floor(this.getBbHeight()); +@@ -332,7 +_,7 @@ + this.getBlockX() - l, this.getBlockY(), this.getBlockZ() - l, this.getBlockX() + l, this.getBlockY() + i1, this.getBlockZ() + l )) { - BlockState state = level.getBlockState(blockPos); -- if (canDestroy(state)) { -+ if (state.canEntityDestroy(level, blockPos, this) && net.minecraftforge.event.ForgeEventFactory.onEntityDestroyBlock(this, blockPos, state)) { - destroyed = level.destroyBlock(blockPos, true, this) || destroyed; + BlockState blockstate = level.getBlockState(blockpos); +- if (canDestroy(blockstate)) { ++ if (blockstate.canEntityDestroy(level, blockpos, this) && net.minecraftforge.event.ForgeEventFactory.onEntityDestroyBlock(this, blockpos, blockstate)) { + flag = level.destroyBlock(blockpos, true, this) || flag; } } -@@ -352,6 +_,10 @@ +@@ -351,6 +_,10 @@ } } 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 50e6838a1e..5921b6ac02 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 -@@ -86,6 +_,8 @@ - - boolean isSupported = BlockPos.betweenClosedStream(this.calculateSupportBox()).allMatch(pos -> { - BlockState state = this.level().getBlockState(pos); -+ if (net.minecraft.world.level.block.Block.canSupportCenter(this.level(), pos, this.getDirection())) -+ return true; - return state.isSolid() || DiodeBlock.isDiode(state); - }); - return isSupported && this.canCoexist(false); +@@ -85,6 +_,8 @@ + } else { + boolean flag = BlockPos.betweenClosedStream(this.calculateSupportBox()).allMatch(pos -> { + BlockState blockstate = this.level().getBlockState(pos); ++ if (net.minecraft.world.level.block.Block.canSupportCenter(this.level(), pos, this.getDirection())) ++ return true; + return blockstate.isSolid() || DiodeBlock.isDiode(blockstate); + }); + return flag && this.canCoexist(false); diff --git a/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch index 1a5d3a15d5..3225ebca83 100644 --- a/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java +++ b/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java -@@ -77,7 +_,7 @@ +@@ -73,7 +_,7 @@ + if (this.level().isClientSide()) { return InteractionResult.SUCCESS; - } - -- if (player.getItemInHand(hand).is(Items.SHEARS)) { -+ if (player.getItemInHand(hand).canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - InteractionResult result = super.interact(player, hand, location); - if (result instanceof InteractionResult.Success success && success.wasItemInteraction()) { - return result; + } else { +- if (player.getItemInHand(hand).is(Items.SHEARS)) { ++ if (player.getItemInHand(hand).canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { + InteractionResult interactionresult = super.interact(player, hand, location); + if (interactionresult instanceof InteractionResult.Success interactionresult$success && interactionresult$success.wasItemInteraction()) { + return interactionresult; 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 9db3602906..8f83fb5675 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/item/FallingBlockEntity.java +++ b/net/minecraft/world/entity/item/FallingBlockEntity.java @@ -158,7 +_,7 @@ - if (this.level() instanceof ServerLevel serverLevel && (this.isAlive() || this.forceTickAfterTeleportToDuplicate)) { - BlockPos pos = this.blockPosition(); - boolean isConcrete = this.blockState.getBlock() instanceof ConcretePowderBlock; -- boolean isStuckInWater = isConcrete && this.level().getFluidState(pos).is(FluidTags.WATER); -+ boolean isStuckInWater = isConcrete && this.blockState.canBeHydrated(this.level(), pos, this.level().getFluidState(pos), pos); - double moveVec = this.getDeltaMovement().lengthSqr(); - if (isConcrete && moveVec > 1.0) { - BlockHitResult clip = this.level() + if (this.level() instanceof ServerLevel serverlevel && (this.isAlive() || this.forceTickAfterTeleportToDuplicate)) { + 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() @@ -167,7 +_,7 @@ new Vec3(this.xo, this.yo, this.zo), this.position(), ClipContext.Block.COLLIDER, ClipContext.Fluid.SOURCE_ONLY, this ) ); -- if (clip.getType() != HitResult.Type.MISS && this.level().getFluidState(clip.getBlockPos()).is(FluidTags.WATER)) { -+ if (clip.getType() != HitResult.Type.MISS && this.blockState.canBeHydrated(this.level(), pos, this.level().getFluidState(clip.getBlockPos()), clip.getBlockPos())) { - pos = clip.getBlockPos(); - isStuckInWater = true; +- 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 8098c345f0..5046babcb5 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/item/ItemEntity.java +++ b/net/minecraft/world/entity/item/ItemEntity.java -@@ -52,6 +_,10 @@ +@@ -51,6 +_,10 @@ private @Nullable EntityReference thrower; private @Nullable UUID target; public final float bobOffs = this.random.nextFloat() * (float) Math.PI * 2.0F; @@ -11,7 +11,7 @@ public ItemEntity(final EntityType type, final Level level) { super(type, level); -@@ -79,6 +_,7 @@ +@@ -78,6 +_,7 @@ this.setPos(x, y, z); this.setItem(itemStack); this.setDeltaMovement(deltaX, deltaY, deltaZ); @@ -19,7 +19,7 @@ } @Override -@@ -116,6 +_,7 @@ +@@ -115,6 +_,7 @@ @Override public void tick() { @@ -27,10 +27,10 @@ if (this.getItem().isEmpty()) { this.discard(); } else { -@@ -128,6 +_,10 @@ +@@ -127,6 +_,10 @@ this.yo = this.getY(); this.zo = this.getZ(); - Vec3 oldMovement = this.getDeltaMovement(); + Vec3 vec3 = this.getDeltaMovement(); + var fluidType = this.getMaxHeightFluidType(); + if (!fluidType.isAir() && !fluidType.isVanilla() && this.getFluidTypeHeight(fluidType) > 0.1F) { + fluidType.setItemMovement(this); @@ -38,17 +38,17 @@ if (this.isInWater() && this.getFluidHeight(FluidTags.WATER) > 0.1F) { this.setUnderwaterMovement(); } else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > 0.1F) { -@@ -153,7 +_,8 @@ - float airDrag = this.getAirDrag(); - float groundFriction = airDrag; +@@ -151,7 +_,8 @@ + this.applyEffectsFromBlocks(); + float f = 0.98F; if (this.onGround()) { -- groundFriction *= this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction(); +- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; + BlockPos groundPos = getBlockPosBelowThatAffectsMyMovement(); -+ groundFriction *= this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; ++ f = this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; } - this.setDeltaMovement(this.getDeltaMovement().multiply(groundFriction, airDrag, groundFriction)); -@@ -185,7 +_,16 @@ + this.setDeltaMovement(this.getDeltaMovement().multiply(f, 0.98, f)); +@@ -183,7 +_,16 @@ } } @@ -66,16 +66,16 @@ this.discard(); } } -@@ -300,7 +_,7 @@ - this.health = (int)(this.health - damage); - this.gameEvent(GameEvent.ENTITY_DAMAGE, source.getEntity()); - if (this.health <= 0) { -- this.getItem().onDestroyed(this); -+ this.getItem().onDestroyed(this, source); - this.discard(); - } +@@ -293,7 +_,7 @@ + this.health = (int)(this.health - damage); + this.gameEvent(GameEvent.ENTITY_DAMAGE, source.getEntity()); + if (this.health <= 0) { +- this.getItem().onDestroyed(this); ++ this.getItem().onDestroyed(this, source); + this.discard(); + } -@@ -317,6 +_,7 @@ +@@ -311,6 +_,7 @@ output.putShort("Health", (short)this.health); output.putShort("Age", (short)this.age); output.putShort("PickupDelay", (short)this.pickupDelay); @@ -83,7 +83,7 @@ EntityReference.store(this.thrower, output, "Thrower"); output.storeNullable("Owner", UUIDUtil.CODEC, this.target); if (!this.getItem().isEmpty()) { -@@ -329,6 +_,7 @@ +@@ -323,6 +_,7 @@ this.health = input.getShortOr("Health", (short)5); this.age = input.getShortOr("Age", (short)0); this.pickupDelay = input.getShortOr("PickupDelay", (short)0); @@ -91,26 +91,26 @@ this.target = input.read("Owner", UUIDUtil.CODEC).orElse(null); this.thrower = EntityReference.read(input, "Thrower"); this.setItem(input.read("Item", ItemStack.CODEC).orElse(ItemStack.EMPTY)); -@@ -340,10 +_,17 @@ +@@ -334,10 +_,17 @@ @Override public void playerTouch(final Player player) { if (!this.level().isClientSide()) { + if (this.pickupDelay > 0) return; - ItemStack itemStack = this.getItem(); - Item item = itemStack.getItem(); - int orgCount = itemStack.getCount(); -- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && player.getInventory().add(itemStack)) { + ItemStack itemstack = this.getItem(); + Item item = itemstack.getItem(); + int i = itemstack.getCount(); +- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && player.getInventory().add(itemstack)) { + int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(this, player); + if (hook < 0) return; -+ ItemStack copy = itemStack.copy(); -+ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && (hook == 1 || orgCount <= 0 || player.getInventory().add(itemStack))) { -+ orgCount = copy.getCount() - itemStack.getCount(); -+ copy.setCount(orgCount); ++ ItemStack copy = itemstack.copy(); ++ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && (hook == 1 || i <= 0 || player.getInventory().add(itemstack))) { ++ i = copy.getCount() - itemstack.getCount(); ++ copy.setCount(i); + net.minecraftforge.event.ForgeEventFactory.firePlayerItemPickupEvent(player, this, copy); - player.take(this, orgCount); - if (itemStack.isEmpty()) { + player.take(this, i); + if (itemstack.isEmpty()) { this.discard(); -@@ -427,7 +_,7 @@ +@@ -421,7 +_,7 @@ public void makeFakeItem() { this.setNeverPickUp(); 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 dd11a4d067..db4a7fd4ce 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch @@ -4,12 +4,12 @@ void onCrossbowAttackPerformed(); default void performCrossbowAttack(final LivingEntity body, final float crossbowPower) { -- InteractionHand hand = ProjectileUtil.getWeaponHoldingHand(body, Items.CROSSBOW); -+ InteractionHand hand = ProjectileUtil.getWeaponHoldingHand(body, item -> item instanceof CrossbowItem); - ItemStack usedItem = body.getItemInHand(hand); -- if (usedItem.getItem() instanceof CrossbowItem crossbow) { +- InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(body, Items.CROSSBOW); ++ InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(body, item -> item instanceof CrossbowItem); + ItemStack itemstack = body.getItemInHand(interactionhand); +- if (itemstack.getItem() instanceof CrossbowItem crossbowitem) { + if (body.isHolding(is -> is.getItem() instanceof CrossbowItem)) { -+ var crossbow = (CrossbowItem) usedItem.getItem(); - crossbow.performShooting(body.level(), body, hand, usedItem, crossbowPower, 14 - body.level().getDifficulty().getId() * 4, this.getTarget()); - } - ++ var crossbowitem = (CrossbowItem) itemstack.getItem(); + crossbowitem.performShooting( + body.level(), body, interactionhand, itemstack, crossbowPower, 14 - body.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 f905ee625d..2ab9861e0b 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch @@ -5,11 +5,11 @@ @Override public void setTarget(final @Nullable LivingEntity target) { - super.setTarget(target); - AttributeInstance movementSpeed = this.getAttribute(Attributes.MOVEMENT_SPEED); + AttributeInstance attributeinstance = this.getAttribute(Attributes.MOVEMENT_SPEED); if (target == null) { this.targetChangeTime = 0; @@ -135,6 +_,7 @@ - movementSpeed.addTransientModifier(SPEED_MODIFIER_ATTACKING); + attributeinstance.addTransientModifier(SPEED_MODIFIER_ATTACKING); } } + super.setTarget(target); //Forge: Moved down to allow event handlers to write data manager values. @@ -26,18 +26,18 @@ @Override @@ -285,8 +_,10 @@ - boolean couldStandOn = blockState.blocksMotion(); - boolean isWet = blockState.getFluidState().is(FluidTags.WATER); - if (couldStandOn && !isWet) { + boolean flag = blockstate.blocksMotion(); + boolean flag1 = blockstate.getFluidState().is(FluidTags.WATER); + if (flag && !flag1) { + var event = net.minecraftforge.event.ForgeEventFactory.onEnderManTeleport(this, x, y, z); + if (event == null) return false; - Vec3 oldPos = this.position(); -- boolean result = this.randomTeleport(x, y, z, true); -+ boolean result = this.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true); - if (result) { - this.level().gameEvent(GameEvent.TELEPORT, oldPos, GameEvent.Context.of(this)); + Vec3 vec3 = this.position(); +- boolean flag2 = this.randomTeleport(x, y, z, 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()) { -@@ -441,7 +_,7 @@ +@@ -443,7 +_,7 @@ if (this.enderman.getCarriedBlock() == null) { return false; } else { @@ -46,16 +46,16 @@ ? false : this.enderman.getRandom().nextInt(reducedTickDelay(2000)) == 0; } -@@ -461,7 +_,7 @@ - BlockState carried = this.enderman.getCarriedBlock(); - if (carried != null) { - carried = Block.updateFromNeighbourShapes(carried, this.enderman.level(), pos); -- if (this.canPlaceBlock(level, pos, carried, targetState, belowState, below)) { -+ if (this.canPlaceBlock(level, pos, carried, targetState, belowState, below) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(enderman, net.minecraftforge.common.util.BlockSnapshot.create(level.dimension(), level, below), net.minecraft.core.Direction.UP)) { - level.setBlock(pos, carried, 3); - level.gameEvent(GameEvent.BLOCK_PLACE, pos, GameEvent.Context.of(this.enderman, carried)); +@@ -463,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); -@@ -475,6 +_,7 @@ +@@ -477,6 +_,7 @@ return targetState.isAir() && !belowState.isAir() && !belowState.is(Blocks.BEDROCK) @@ -63,7 +63,7 @@ && belowState.isCollisionShapeFullBlock(level, below) && carried.canSurvive(level, pos) && level.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(pos))).isEmpty(); -@@ -585,7 +_,7 @@ +@@ -587,7 +_,7 @@ if (this.enderman.getCarriedBlock() != null) { return false; } else { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/MagmaCube.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch similarity index 67% rename from patches/minecraft/net/minecraft/world/entity/monster/cubemob/MagmaCube.java.patch rename to patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch index 17ca813544..d2cb7f7410 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/MagmaCube.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch @@ -1,8 +1,8 @@ ---- a/net/minecraft/world/entity/monster/cubemob/MagmaCube.java -+++ b/net/minecraft/world/entity/monster/cubemob/MagmaCube.java -@@ -96,17 +_,28 @@ - float sizeJumpBoostPower = this.getSize() * 0.1F; - this.setDeltaMovement(movement.x, this.getJumpPower() + sizeJumpBoostPower, movement.z); +--- a/net/minecraft/world/entity/monster/MagmaCube.java ++++ b/net/minecraft/world/entity/monster/MagmaCube.java +@@ -71,17 +_,28 @@ + float f = this.getSize() * 0.1F; + this.setDeltaMovement(vec3.x, this.getJumpPower() + f, vec3.z); this.needsSync = true; + net.minecraftforge.common.ForgeHooks.onLivingJump(this); } @@ -16,8 +16,8 @@ + + private void jumpInLiquidInternal(java.util.function.BooleanSupplier isLava, Runnable onSuper) { + if (isLava.getAsBoolean()) { - Vec3 movement = this.getDeltaMovement(); - this.setDeltaMovement(movement.x, 0.22F + this.getSize() * 0.05F, movement.z); + Vec3 vec3 = this.getDeltaMovement(); + this.setDeltaMovement(vec3.x, 0.22F + this.getSize() * 0.05F, vec3.z); this.needsSync = true; } else { - super.jumpInLiquid(type); 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 80686f0291..00f779df41 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/Monster.java +++ b/net/minecraft/world/entity/monster/Monster.java -@@ -147,9 +_,9 @@ +@@ -149,9 +_,9 @@ if (heldWeapon.getItem() instanceof ProjectileWeaponItem) { - Predicate supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); - ItemStack heldProjectile = ProjectileWeaponItem.getHeldProjectile(this, supportedProjectiles); -- return heldProjectile.isEmpty() ? new ItemStack(Items.ARROW) : heldProjectile; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, heldProjectile.isEmpty() ? new ItemStack(Items.ARROW) : heldProjectile); + Predicate predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); + ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); +- return itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack); } else { - return ItemStack.EMPTY; + return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, ItemStack.EMPTY); 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 1e737394b4..f2abdcf19f 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 -@@ -143,7 +_,7 @@ - this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1, baseValue, maxSpeed)); +@@ -142,7 +_,7 @@ + this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1, d1, d0)); } -- if (this.level() instanceof ServerLevel serverLevel && this.horizontalCollision && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (this.level() instanceof ServerLevel serverLevel && this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { - boolean destroyedBlock = false; - AABB bb = this.getBoundingBox().inflate(0.2); +- if (this.level() instanceof ServerLevel serverlevel && this.horizontalCollision && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (this.level() instanceof ServerLevel serverlevel && this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, 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 512ab3dd79..50eeb606b7 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 -@@ -401,6 +_,12 @@ - && this.level().noCollision(this, new AABB(target).deflate(1.0E-6))) { - Direction attachmentDirection = this.findAttachableSurface(target); - if (attachmentDirection != null) { -+ var event = new net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity(this, target.getX(), target.getY(), target.getZ()); -+ if (net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity.BUS.post(event)) attachmentDirection = null; -+ target = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); +@@ -384,6 +_,12 @@ + && this.level().noCollision(this, new AABB(blockpos1).deflate(1.0E-6))) { + Direction direction = this.findAttachableSurface(blockpos1); + if (direction != null) { ++ var event = new net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity(this, blockpos1.getX(), blockpos1.getY(), blockpos1.getZ()); ++ if (net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity.BUS.post(event)) direction = null; ++ blockpos1 = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); + } + -+ if (attachmentDirection != null) { ++ if (direction != null) { this.unRide(); - this.setAttachFace(attachmentDirection); + 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 589b3c0372..8bf8bfb76f 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 -@@ -143,7 +_,7 @@ - } - - RandomSource random = this.mob.getRandom(); -- if (getServerLevel(this.mob).getGameRules().get(GameRules.MOB_GRIEFING) && random.nextInt(reducedTickDelay(10)) == 0) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.mob.level()), this.mob) && random.nextInt(reducedTickDelay(10)) == 0) { - this.selectedDirection = Direction.getRandom(random); - BlockPos pos = BlockPos.containing(this.mob.getX(), this.mob.getY() + 0.5, this.mob.getZ()).relative(this.selectedDirection); - BlockState blockState = this.mob.level().getBlockState(pos); -@@ -212,7 +_,7 @@ - BlockPos testPos = basePos.offset(xOff, yOff, zOff); - BlockState blockState = level.getBlockState(testPos); - if (blockState.getBlock() instanceof InfestedBlock infestedBlock) { +@@ -139,7 +_,7 @@ + return false; + } else { + RandomSource randomsource = this.mob.getRandom(); +- if (getServerLevel(this.mob).getGameRules().get(GameRules.MOB_GRIEFING) && randomsource.nextInt(reducedTickDelay(10)) == 0) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(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); + BlockState blockstate = this.mob.level().getBlockState(blockpos); +@@ -210,7 +_,7 @@ + BlockState blockstate = level.getBlockState(blockpos1); + Block block = blockstate.getBlock(); + if (block instanceof InfestedBlock) { - if (getServerLevel(level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(level), this.silverfish)) { - level.destroyBlock(testPos, true, this.silverfish); + level.destroyBlock(blockpos1, true, this.silverfish); } else { - level.setBlock(testPos, infestedBlock.hostStateByInfested(level.getBlockState(testPos)), 3); + level.setBlock(blockpos1, ((InfestedBlock)block).hostStateByInfested(level.getBlockState(blockpos1)), 3); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/AbstractCubeMob.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch similarity index 51% rename from patches/minecraft/net/minecraft/world/entity/monster/cubemob/AbstractCubeMob.java.patch rename to patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch index f2922c2523..d0b40ce95d 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/AbstractCubeMob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch @@ -1,15 +1,15 @@ ---- a/net/minecraft/world/entity/monster/cubemob/AbstractCubeMob.java -+++ b/net/minecraft/world/entity/monster/cubemob/AbstractCubeMob.java -@@ -125,6 +_,8 @@ - float size = this.getDimensions(this.getPose()).width() * 2.0F; - float radius = size / 2.0F; +--- a/net/minecraft/world/entity/monster/Slime.java ++++ b/net/minecraft/world/entity/monster/Slime.java +@@ -139,6 +_,8 @@ + 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 i = 0; i < size * 16.0F; i++) { - float dir = this.random.nextFloat() * (float) (Math.PI * 2); - float d = this.random.nextFloat() * 0.5F + 0.5F; -@@ -145,6 +_,12 @@ + for (int i = 0; i < f * 16.0F; i++) { + float f2 = this.random.nextFloat() * (float) (Math.PI * 2); + float f3 = this.random.nextFloat() * 0.5F + 0.5F; +@@ -156,6 +_,12 @@ this.wasOnGround = this.onGround(); this.decreaseSquish(); } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch index 8568a1f469..04e74aca46 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/creaking/Creaking.java +++ b/net/minecraft/world/entity/monster/creaking/Creaking.java -@@ -468,7 +_,7 @@ - for (Player player : players) { +@@ -458,7 +_,7 @@ + for (Player player : list) { if (this.canAttack(player) && !this.isAlliedTo(player)) { - hasPotentialTarget = true; -- if ((!active || LivingEntity.PLAYER_NOT_WEARING_DISGUISE_ITEM.test(player)) -+ if ((!active || net.minecraftforge.common.ForgeHooks.isNotDisguised(this).test(player)) + flag1 = true; +- if ((!flag || LivingEntity.PLAYER_NOT_WEARING_DISGUISE_ITEM.test(player)) ++ if ((!flag || net.minecraftforge.common.ForgeHooks.isNotDisguised(this).test(player)) && this.isLookingAtMe( player, 0.5, false, true, this.getEyeY(), this.getY() + 0.5 * this.getScale(), (this.getEyeY() + this.getY()) / 2.0 )) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/SulfurCube.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/cubemob/SulfurCube.java.patch deleted file mode 100644 index 53a3f70a64..0000000000 --- a/patches/minecraft/net/minecraft/world/entity/monster/cubemob/SulfurCube.java.patch +++ /dev/null @@ -1,22 +0,0 @@ ---- a/net/minecraft/world/entity/monster/cubemob/SulfurCube.java -+++ b/net/minecraft/world/entity/monster/cubemob/SulfurCube.java -@@ -181,8 +_,8 @@ - } - - @Override -- protected void travelInFluid(final Vec3 input) { -- super.travelInFluid(input); -+ protected void travelInFluid(final Vec3 input, final net.minecraft.world.level.material.FluidState fluid) { -+ super.travelInFluid(input, fluid); - if (this.hasBodyItem() && this.floatsInLiquids) { - float vibeAmount = 0.2F * Mth.sin(this.tickCount * 0.4F); - double immersion = this.getFluidHeight(this.isInWater() ? FluidTags.WATER : FluidTags.LAVA) - this.getFluidJumpThreshold() + vibeAmount; -@@ -452,7 +_,7 @@ - } - - if (!this.canExplode() || !heldItem.is(Items.FLINT_AND_STEEL) && !heldItem.is(Items.FIRE_CHARGE)) { -- if (heldItem.is(Items.SHEARS) && this.readyForShearing()) { -+ if (heldItem.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.readyForShearing()) { - if (this.level() instanceof ServerLevel level) { - ItemStack itemStackToShear = this.getItemBySlot(EquipmentSlot.BODY); - this.shear(level, SoundSource.PLAYERS, heldItem); 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 a2444bba97..0fc753b705 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,22 +1,22 @@ --- a/net/minecraft/world/entity/monster/hoglin/Hoglin.java +++ b/net/minecraft/world/entity/monster/hoglin/Hoglin.java -@@ -148,7 +_,7 @@ +@@ -141,7 +_,7 @@ HoglinAi.updateActivity(this); if (this.isConverting()) { this.timeInOverworld++; - if (this.timeInOverworld > 300) { -+ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.ZOGLIN, (timer) -> this.timeInOverworld = timer)) { ++ 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(); } -@@ -249,9 +_,7 @@ +@@ -237,9 +_,7 @@ } private void finishConversion() { - this.convertTo( -- EntityTypes.ZOGLIN, ConversionParams.single(this, true, false), zoglin -> zoglin.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)) +- EntityType.ZOGLIN, ConversionParams.single(this, true, false), zoglin -> zoglin.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)) - ); -+ this.convertTo(EntityTypes.ZOGLIN, ConversionParams.single(this, true, false), zoglin -> { zoglin.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zoglin); }); ++ this.convertTo(EntityType.ZOGLIN, ConversionParams.single(this, true, false), zoglin -> { zoglin.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zoglin); }); } @Override diff --git a/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch index 7fec99db3b..adfc9bfb5f 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/illager/Evoker.java +++ b/net/minecraft/world/entity/monster/illager/Evoker.java -@@ -305,7 +_,7 @@ - } - - ServerLevel level = getServerLevel(Evoker.this.level()); -- if (!level.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, Evoker.this)) { +@@ -304,7 +_,7 @@ return false; - } - + } else { + ServerLevel serverlevel = getServerLevel(Evoker.this.level()); +- if (!serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, Evoker.this)) { + return false; + } else { + List list = serverlevel.getNearbyEntities( diff --git a/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch index b2d3cc289a..5dbdd1a45b 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/entity/monster/illager/Illusioner.java +++ b/net/minecraft/world/entity/monster/illager/Illusioner.java -@@ -174,9 +_,12 @@ +@@ -175,9 +_,12 @@ @Override public void performRangedAttack(final LivingEntity target, final float power) { -- ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - ItemStack projectile = this.getProjectile(bowItem); - AbstractArrow arrow = ProjectileUtil.getMobArrow(this, projectile, power, bowItem); +- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + ItemStack itemstack1 = this.getProjectile(itemstack); + AbstractArrow abstractarrow = ProjectileUtil.getMobArrow(this, itemstack1, power, itemstack); + if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { -+ arrow = bow.customArrow(arrow); ++ abstractarrow = bow.customArrow(abstractarrow); + } - double xd = target.getX() - this.getX(); - double yd = target.getY(0.3333333333333333) - arrow.getY(); - double zd = target.getZ() - this.getZ(); + double d0 = target.getX() - this.getX(); + double d1 = target.getY(0.3333333333333333) - abstractarrow.getY(); + double d2 = target.getZ() - this.getZ(); 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 7cf9d86c38..5750557767 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,22 @@ --- a/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java +++ b/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java -@@ -86,7 +_,7 @@ +@@ -85,7 +_,7 @@ this.timeInOverworld = 0; } - if (this.timeInOverworld > 300) { -+ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.ZOMBIFIED_PIGLIN, (timer) -> this.timeInOverworld = timer)) { - if (level.getDifficulty() != Difficulty.PEACEFUL) { - this.playConvertedSound(); - } -@@ -110,7 +_,10 @@ ++ if (this.timeInOverworld > 300 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> this.timeInOverworld = timer)) { + this.playConvertedSound(); + this.finishConversion(level); + } +@@ -106,7 +_,10 @@ this.convertTo( - EntityTypes.ZOMBIFIED_PIGLIN, + EntityType.ZOMBIFIED_PIGLIN, ConversionParams.single(this, true, true), - zombified -> zombified.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)) -+ zombified -> { -+ zombified.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombified); ++ p_449701_ -> { ++ p_449701_.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, p_449701_); + } ); } 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 0b63ebe319..85ee0d7ca4 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,6 +1,6 @@ --- a/net/minecraft/world/entity/monster/piglin/Piglin.java +++ b/net/minecraft/world/entity/monster/piglin/Piglin.java -@@ -323,7 +_,7 @@ +@@ -322,7 +_,7 @@ } else if (this.isChargingCrossbow()) { return PiglinArmPose.CROSSBOW_CHARGE; } else { @@ -9,15 +9,16 @@ } } -@@ -362,14 +_,14 @@ +@@ -359,7 +_,7 @@ + } protected void holdInOffHand(final ItemStack itemStack) { - this.setItemSlotAndDropWhenKilled(EquipmentSlot.OFFHAND, itemStack); -- if (!itemStack.is(PiglinAi.BARTERING_ITEM)) { -+ if (!itemStack.isPiglinCurrency()) { - this.setPersistenceRequired(); - } - } +- if (itemStack.is(PiglinAi.BARTERING_ITEM)) { ++ if (itemStack.isPiglinCurrency()) { + this.setItemSlot(EquipmentSlot.OFFHAND, itemStack); + this.setGuaranteedDrop(EquipmentSlot.OFFHAND); + } else { +@@ -369,7 +_,7 @@ @Override public boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack) { 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 6e2e9bdc2b..73239fc941 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,15 +1,15 @@ --- a/net/minecraft/world/entity/monster/piglin/PiglinAi.java +++ b/net/minecraft/world/entity/monster/piglin/PiglinAi.java -@@ -647,7 +_,7 @@ +@@ -646,7 +_,7 @@ public static boolean isWearingSafeArmor(final LivingEntity livingEntity) { - for (EquipmentSlot slot : EquipmentSlotGroup.ARMOR) { -- if (livingEntity.getItemBySlot(slot).is(ItemTags.PIGLIN_SAFE_ARMOR)) { -+ if (livingEntity.getItemBySlot(slot).makesPiglinsNeutral(livingEntity)) { + for (EquipmentSlot equipmentslot : EquipmentSlotGroup.ARMOR) { +- if (livingEntity.getItemBySlot(equipmentslot).is(ItemTags.PIGLIN_SAFE_ARMOR)) { ++ if (livingEntity.getItemBySlot(equipmentslot).makesPiglinsNeutral(livingEntity)) { return true; } } -@@ -799,7 +_,7 @@ +@@ -797,7 +_,7 @@ } private static boolean hasCrossbow(final LivingEntity body) { @@ -18,7 +18,7 @@ } private static void admireGoldItem(final LivingEntity body) { -@@ -811,7 +_,7 @@ +@@ -809,7 +_,7 @@ } private static boolean isBarterCurrency(final ItemStack itemStack) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch index 2e86aca7c1..bc12858ee7 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java +++ b/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java -@@ -133,7 +_,7 @@ +@@ -138,7 +_,7 @@ if (this.level() != null && !this.level().isClientSide()) { this.goalSelector.removeGoal(this.meleeGoal); this.goalSelector.removeGoal(this.bowGoal); -- ItemStack usedWeapon = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack usedWeapon = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - if (usedWeapon.is(Items.BOW)) { - int minAttackInterval = this.getHardAttackInterval(); +- 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) { -@@ -158,9 +_,12 @@ +@@ -163,9 +_,12 @@ @Override public void performRangedAttack(final LivingEntity target, final float power) { -- ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - ItemStack projectile = this.getProjectile(bowItem); - AbstractArrow arrow = this.getArrow(projectile, power, bowItem); +- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + ItemStack itemstack1 = this.getProjectile(itemstack); + AbstractArrow abstractarrow = this.getArrow(itemstack1, power, itemstack); + if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { -+ arrow = bow.customArrow(arrow); ++ abstractarrow = bow.customArrow(abstractarrow); + } - double xd = target.getX() - this.getX(); - double yd = target.getY(0.3333333333333333) - arrow.getY(); - double zd = target.getZ() - this.getZ(); + double d0 = target.getX() - this.getX(); + double d1 = target.getY(0.3333333333333333) - abstractarrow.getY(); + double d2 = target.getZ() - this.getZ(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch index 711d74d763..ec435bcad1 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch @@ -3,9 +3,27 @@ @@ -70,7 +_,7 @@ @Override protected InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); -- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.readyForShearing()) { - if (this.level() instanceof ServerLevel level) { - this.shear(level, SoundSource.PLAYERS, itemStack); + ItemStack itemstack = player.getItemInHand(hand); +- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: move to onSheared + if (this.level() instanceof ServerLevel serverlevel) { + this.shear(serverlevel, SoundSource.PLAYERS, itemstack); this.gameEvent(GameEvent.SHEAR, player); +@@ -137,5 +_,17 @@ + @Override + public boolean readyForShearing() { + return !this.isSheared() && this.isAlive(); ++ } ++ ++ @Override ++ public java.util.List onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, net.minecraft.core.BlockPos pos, int fortune) { ++ if (world instanceof ServerLevel server) { ++ server.playSound(null, this, SoundEvents.BOGGED_SHEAR, SoundSource.PLAYERS, 1.0F, 1.0F); ++ this.setSheared(true); ++ var ret = new java.util.ArrayList(); ++ this.dropFromShearingLootTable(server, BuiltInLootTables.BOGGED_SHEAR, item, (slevel, stack) -> ret.add(stack)); ++ return ret; ++ } ++ return java.util.Collections.emptyList(); + } + } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Skeleton.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Skeleton.java.patch index 62ab199b69..f28f495fd9 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Skeleton.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Skeleton.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/entity/monster/skeleton/Skeleton.java +++ b/net/minecraft/world/entity/monster/skeleton/Skeleton.java -@@ -93,6 +_,7 @@ +@@ -92,6 +_,7 @@ } protected void doFreezeConversion() { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.STRAY, (timer) -> this.conversionTime = timer)) return; - this.convertTo(EntityTypes.STRAY, ConversionParams.single(this, true, true), stray -> { ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.STRAY, (timer) -> this.conversionTime = timer)) return; + this.convertTo(EntityType.STRAY, ConversionParams.single(this, true, true), stray -> { if (!this.isSilent()) { this.level().levelEvent(null, 1048, this.blockPosition(), 0); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/spider/Spider.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/spider/Spider.java.patch index 885cb21e25..272aa837ee 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/spider/Spider.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/spider/Spider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/monster/spider/Spider.java +++ b/net/minecraft/world/entity/monster/spider/Spider.java -@@ -124,7 +_,10 @@ +@@ -123,7 +_,10 @@ @Override public boolean canBeAffected(final MobEffectInstance newEffect) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Husk.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Husk.java.patch index 77619ab765..c4c106ce6e 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Husk.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Husk.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/entity/monster/zombie/Husk.java +++ b/net/minecraft/world/entity/monster/zombie/Husk.java -@@ -80,6 +_,7 @@ +@@ -79,6 +_,7 @@ @Override protected void doUnderWaterConversion(final ServerLevel level) { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.ZOMBIE, (timer) -> this.conversionTime = timer)) return; - this.convertToZombieType(level, EntityTypes.ZOMBIE); ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIE, (timer) -> this.conversionTime = timer)) return; + this.convertToZombieType(level, EntityType.ZOMBIE); if (!this.isSilent()) { level.levelEvent(null, 1041, this.blockPosition(), 0); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch index d1a4f8ed66..1c33cd8e54 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch @@ -20,12 +20,12 @@ @VisibleForTesting public boolean convertVillagerToZombieVillager(final ServerLevel level, final Villager villager) { -+ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(villager, EntityTypes.ZOMBIE_VILLAGER, (timer) -> {})) ++ if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(villager, EntityType.ZOMBIE_VILLAGER, (timer) -> {})) + return false; - ZombieVillager zombieVillager = villager.convertTo( - EntityTypes.ZOMBIE_VILLAGER, + ZombieVillager zombievillager = villager.convertTo( + EntityType.ZOMBIE_VILLAGER, ConversionParams.single(villager, true, true), -@@ -268,6 +_,7 @@ +@@ -267,6 +_,7 @@ zombie.setGossips(villager.getGossips().copy()); zombie.setTradeOffers(villager.getOffers().copy()); zombie.setVillagerXp(villager.getVillagerXp()); @@ -33,33 +33,37 @@ if (!this.isSilent()) { level.levelEvent(null, 1026, this.blockPosition(), 0); } -@@ -291,15 +_,26 @@ - target = (LivingEntity)source.getEntity(); - } +@@ -289,19 +_,26 @@ + livingentity = (LivingEntity)source.getEntity(); + } -- if (target != null -+ var vanilla = (target != null - && level.getDifficulty() == Difficulty.HARD - && this.random.nextFloat() < this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE) -- && level.isSpawningMonsters()) { -+ && level.isSpawningMonsters()); -+ { - int x = Mth.floor(this.getX()); - int y = Mth.floor(this.getY()); - int z = Mth.floor(this.getZ()); - EntityType type = this.getType(); -- Zombie reinforcement = type.create(level, EntitySpawnReason.REINFORCEMENT); +- if (livingentity != null ++ var vanilla = (livingentity != null + && level.getDifficulty() == Difficulty.HARD + && this.random.nextFloat() < this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE) +- && level.isSpawningMonsters()) { ++ && level.isSpawningMonsters()); + int i = Mth.floor(this.getX()); + int j = Mth.floor(this.getY()); + int k = Mth.floor(this.getZ()); + EntityType entitytype = this.getType(); +- Zombie zombie = entitytype.create(level, EntitySpawnReason.REINFORCEMENT); +- if (zombie == null) { +- return true; +- } +- + -+ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), x, y, z, target, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); ++ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); + -+ Zombie reinforcement = null; ++ Zombie zombie = null; + if (event.getResult().isAllowed() || (vanilla && event.getResult().isDefault())) { + if (event.getCustomSummonedAid() != null) -+ reinforcement = event.getCustomSummonedAid(); ++ zombie = event.getCustomSummonedAid(); + else -+ reinforcement = type.create(this.level(), EntitySpawnReason.REINFORCEMENT); ++ zombie = entitytype.create(this.level(), EntitySpawnReason.REINFORCEMENT); + } + - if (reinforcement == null) { - return true; - } ++ 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); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch index 2501359c69..b9e1b18979 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/monster/zombie/ZombieVillager.java +++ b/net/minecraft/world/entity/monster/zombie/ZombieVillager.java -@@ -152,7 +_,7 @@ +@@ -156,7 +_,7 @@ if (!this.level().isClientSide() && this.isAlive() && this.isConverting()) { - int amount = this.getConversionProgress(); - this.villagerConversionTime -= amount; + int i = this.getConversionProgress(); + this.villagerConversionTime -= i; - if (this.villagerConversionTime <= 0) { -+ if (this.villagerConversionTime <= 0 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.VILLAGER, (timer) -> this.villagerConversionTime = timer)) { ++ if (this.villagerConversionTime <= 0 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.VILLAGER, (timer) -> this.villagerConversionTime = timer)) { this.finishConversion((ServerLevel)this.level()); } } -@@ -267,6 +_,7 @@ +@@ -270,6 +_,7 @@ if (!this.isSilent()) { level.levelEvent(null, 1027, this.blockPosition(), 0); } 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 d20a2b3c9a..7b56306d99 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/world/entity/npc/CatSpawner.java +++ b/net/minecraft/world/entity/npc/CatSpawner.java -@@ -65,12 +_,12 @@ +@@ -66,12 +_,12 @@ private void spawnCat(final BlockPos spawnPos, final ServerLevel level, final boolean makePersistent) { - Cat cat = EntityTypes.CAT.create(level, EntitySpawnReason.NATURAL); + Cat cat = EntityType.CAT.create(level, EntitySpawnReason.NATURAL); if (cat != null) { + cat.snapTo(spawnPos, 0.0F, 0.0F); // Fix MC-147659: Some witch huts spawn the incorrect cat cat.finalizeSpawn(level, level.getCurrentDifficultyAt(spawnPos), EntitySpawnReason.NATURAL, null); diff --git a/patches/minecraft/net/minecraft/world/entity/npc/villager/AbstractVillager.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/villager/AbstractVillager.java.patch index 49b20fbe26..d138f7bbd4 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/villager/AbstractVillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/villager/AbstractVillager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/npc/villager/AbstractVillager.java +++ b/net/minecraft/world/entity/npc/villager/AbstractVillager.java -@@ -139,6 +_,8 @@ +@@ -138,6 +_,8 @@ if (this.tradingPlayer instanceof ServerPlayer) { CriteriaTriggers.TRADE.trigger((ServerPlayer)this.tradingPlayer, this, offer.getResult()); } diff --git a/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch index cd35c7a612..c26680700b 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/npc/villager/Villager.java +++ b/net/minecraft/world/entity/npc/villager/Villager.java -@@ -289,7 +_,7 @@ +@@ -299,7 +_,7 @@ @Override public InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); -- if (itemStack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) { -+ if (itemStack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping() || player.isSecondaryUseActive()) { + ItemStack itemstack = player.getItemInHand(hand); +- if (itemstack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) { ++ if (itemstack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping() || player.isSecondaryUseActive()) { return super.mobInteract(player, hand); - } - -@@ -761,7 +_,7 @@ + } else if (this.isBaby()) { + this.setUnhappy(); +@@ -760,7 +_,7 @@ @Override public void thunderHit(final ServerLevel level, final LightningBolt lightningBolt) { - if (level.getDifficulty() != Difficulty.PEACEFUL) { -+ if (level.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityTypes.WITCH, (timer) -> {})) { ++ if (level.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.WITCH, (timer) -> {})) { LOGGER.info("Villager {} was struck by lightning {}.", this, lightningBolt); - Witch witch = this.convertTo(EntityTypes.WITCH, ConversionParams.single(this, false, false), w -> { + Witch witch = this.convertTo(EntityType.WITCH, ConversionParams.single(this, false, false), w -> { w.finalizeSpawn(level, level.getCurrentDifficultyAt(w.blockPosition()), EntitySpawnReason.CONVERSION, null); diff --git a/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch index edb7fda2f1..36e59d98b5 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/world/entity/npc/villager/VillagerType.java +++ b/net/minecraft/world/entity/npc/villager/VillagerType.java -@@ -79,4 +_,9 @@ +@@ -80,4 +_,9 @@ public static ResourceKey byBiome(final Holder biome) { - return biome.unwrapKey().map(BY_BIOME::get).orElse(VillagerData.DEFAULT_TYPE); + return biome.unwrapKey().map(BY_BIOME::get).orElse(PLAINS); } + + /** FORGE: Registers the VillagerType that will spawn in the given biome. This method should be called during FMLCommonSetupEvent using event.enqueueWork() */ 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 fcc33cde89..b0aade4ba3 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch @@ -13,28 +13,28 @@ && ItemStack.isSameItemSameComponents(slotItemStack, newItemStack) @@ -169,7 +_,7 @@ - for (int slot = 0; slot < 9; slot++) { - int index = (this.selected + slot) % 9; -- if (!this.items.get(index).isEnchanted()) { -+ if (!this.items.get(index).isNotReplaceableByPickAction(this.player, index)) { - return index; + 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; } } -@@ -242,7 +_,7 @@ +@@ -240,7 +_,7 @@ for (int i = 0; i < this.items.size(); i++) { - ItemStack itemStack = this.getItem(i); - if (!itemStack.isEmpty()) { -- itemStack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null); -+ itemStack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null, i); + ItemStack itemstack = this.getItem(i); + if (!itemstack.isEmpty()) { +- itemstack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null); ++ itemstack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null, i); } } } -@@ -293,6 +_,8 @@ - } catch (Throwable t) { - CrashReport report = CrashReport.forThrowable(t, "Adding item to inventory"); - CrashReportCategory category = report.addCategory("Item being added"); -+ category.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); -+ category.setDetail("Item Class", () -> itemStack.getItem().getClass().getName()); - category.setDetail("Item ID", Item.getId(itemStack.getItem())); - category.setDetail("Item data", itemStack.getDamageValue()); - category.setDetail("Item name", () -> itemStack.getHoverName().getString()); +@@ -290,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(itemStack.getItem()))); ++ crashreportcategory.setDetail("Item Class", () -> itemStack.getItem().getClass().getName()); + crashreportcategory.setDetail("Item ID", Item.getId(itemStack.getItem())); + crashreportcategory.setDetail("Item data", itemStack.getDamageValue()); + crashreportcategory.setDetail("Item name", () -> itemStack.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 a9f5e2cff1..5f9f869a18 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/player/Player.java +++ b/net/minecraft/world/entity/player/Player.java -@@ -123,7 +_,7 @@ +@@ -124,7 +_,7 @@ import net.minecraft.world.scores.Team; import org.jspecify.annotations.Nullable; @@ -9,7 +9,7 @@ public static final int MAX_HEALTH = 20; public static final int SLEEP_DURATION = 100; public static final int WAKE_UP_DURATION = 10; -@@ -171,6 +_,9 @@ +@@ -172,6 +_,9 @@ private Optional lastDeathLocation = Optional.empty(); public @Nullable FishingHook fishing; protected float hurtDir; @@ -18,8 +18,8 @@ + @Nullable private Pose forcedPose; public Player(final Level level, final GameProfile gameProfile) { - super(EntityTypes.PLAYER, level); -@@ -179,6 +_,17 @@ + super(EntityType.PLAYER, level); +@@ -180,6 +_,17 @@ this.inventory = new Inventory(this, this.equipment); this.inventoryMenu = new InventoryMenu(this.inventory, !level.isClientSide(), this); this.containerMenu = this.inventoryMenu; @@ -37,7 +37,7 @@ } @Override -@@ -216,7 +_,8 @@ +@@ -213,7 +_,8 @@ .add(Attributes.MINING_EFFICIENCY) .add(Attributes.SWEEPING_DAMAGE_RATIO) .add(Attributes.WAYPOINT_TRANSMIT_RANGE, 6.0E7) @@ -47,7 +47,7 @@ } @Override -@@ -230,6 +_,7 @@ +@@ -227,6 +_,7 @@ @Override public void tick() { @@ -55,7 +55,7 @@ this.noPhysics = this.isSpectator(); if (this.isSpectator() || this.isPassenger()) { this.setOnGround(false); -@@ -246,7 +_,7 @@ +@@ -243,7 +_,7 @@ } if (!this.level().isClientSide() @@ -64,15 +64,15 @@ this.stopSleepInBed(false, true); } } else if (this.sleepCounter > 0) { -@@ -282,6 +_,7 @@ - - this.cooldowns.tick(); - this.updatePlayerPose(); +@@ -308,6 +_,7 @@ + if (!this.getAbilities().flying) { + super.onAboveBubbleColumn(dragDown, pos); + } + net.minecraftforge.event.ForgeEventFactory.onPlayerPostTick(this); } @Override -@@ -341,6 +_,10 @@ +@@ -338,6 +_,10 @@ } protected void updatePlayerPose() { @@ -81,17 +81,17 @@ + return; + } if (this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.SWIMMING)) { - Pose desiredPose = this.getDesiredPose(); - Pose actualPose; -@@ -524,6 +_,7 @@ + Pose pose = this.getDesiredPose(); + Pose pose1; +@@ -522,6 +_,7 @@ @Override public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; super.die(source); this.reapplyPosition(); - if (!this.isSpectator() && this.level() instanceof ServerLevel level) { -@@ -580,10 +_,15 @@ + if (!this.isSpectator() && this.level() instanceof ServerLevel serverlevel) { +@@ -578,10 +_,15 @@ } public @Nullable ItemEntity drop(final ItemStack itemStack, final boolean thrownFromHand) { @@ -105,16 +105,16 @@ + } + + public float getDestroySpeed(BlockState state, @Nullable BlockPos pos) { - float speed = this.inventory.getSelectedItem().getDestroySpeed(state); - if (speed > 1.0F) { - speed += (float)this.getAttributeValue(Attributes.MINING_EFFICIENCY); -@@ -612,11 +_,14 @@ - speed /= 5.0F; + float f = this.inventory.getSelectedItem().getDestroySpeed(state); + if (f > 1.0F) { + f += (float)this.getAttributeValue(Attributes.MINING_EFFICIENCY); +@@ -610,11 +_,14 @@ + f /= 5.0F; } -+ speed = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, state, speed, pos); ++ f = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, state, f, pos); + - return speed; + return f; } public boolean hasCorrectToolForDrops(final BlockState state) { @@ -124,15 +124,15 @@ } @Override -@@ -677,6 +_,7 @@ +@@ -675,6 +_,7 @@ @Override public boolean hurtServer(final ServerLevel level, final DamageSource source, float damage) { + if (!net.minecraftforge.common.ForgeHooks.onPlayerAttack(this, source, damage)) return false; if (this.isInvulnerableTo(level, source)) { return false; - } -@@ -747,11 +_,14 @@ + } else if (this.abilities.invulnerable && !source.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { +@@ -743,10 +_,13 @@ @Override protected void actuallyHurt(final ServerLevel level, final DamageSource source, float dmg) { if (!this.isInvulnerableTo(level, source)) { @@ -140,14 +140,13 @@ + if (dmg <= 0) return; dmg = this.getDamageAfterArmorAbsorb(source, dmg); dmg = this.getDamageAfterMagicAbsorb(source, dmg); - float originalDamage = dmg; - dmg = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); - this.setAbsorptionAmount(this.getAbsorptionAmount() - (originalDamage - dmg)); -+ dmg = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, dmg); - float absorbedDamage = originalDamage - dmg; - if (absorbedDamage > 0.0F && absorbedDamage < 3.4028235E37F) { - this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(absorbedDamage * 10.0F)); -@@ -829,6 +_,10 @@ + float f1 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); + this.setAbsorptionAmount(this.getAbsorptionAmount() - (dmg - f1)); ++ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, f1); + float f = dmg - f1; + if (f > 0.0F && f < 3.4028235E37F) { + this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(f * 10.0F)); +@@ -824,6 +_,10 @@ return InteractionResult.PASS; } else { @@ -155,69 +154,69 @@ + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific.BUS.post(event)) { + return event.getCancellationResult(); + } - ItemStack itemStack = this.getItemInHand(hand); - ItemStack itemStackClone = itemStack.copy(); - InteractionResult interact = entity.interact(this, hand, location); -@@ -837,6 +_,10 @@ - itemStack.setCount(itemStackClone.getCount()); + ItemStack itemstack = this.getItemInHand(hand); + ItemStack itemstack1 = itemstack.copy(); + InteractionResult interactionresult = entity.interact(this, hand, location); +@@ -832,6 +_,10 @@ + itemstack.setCount(itemstack1.getCount()); } -+ if (!this.abilities.instabuild && itemStack.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemStackClone, hand.asEquipmentSlot()); ++ if (!this.abilities.instabuild && itemstack.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, hand.asEquipmentSlot()); + } + - return interact; + return interactionresult; } else { - if (!itemStack.isEmpty() && entity instanceof LivingEntity livingEntity) { -@@ -848,6 +_,7 @@ - if (interactionResult.consumesAction()) { + if (!itemstack.isEmpty() && entity instanceof LivingEntity) { +@@ -843,6 +_,7 @@ + if (interactionresult1.consumesAction()) { this.level().gameEvent(GameEvent.ENTITY_INTERACT, entity.position(), GameEvent.Context.of(this)); - if (itemStack.isEmpty() && !this.hasInfiniteMaterials()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemStackClone, hand.asEquipmentSlot()); + if (itemstack.isEmpty() && !this.hasInfiniteMaterials()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, hand.asEquipmentSlot()); this.setItemInHand(hand, ItemStack.EMPTY); } -@@ -949,6 +_,7 @@ +@@ -942,6 +_,7 @@ } public void attack(final Entity entity) { + if (!net.minecraftforge.common.ForgeHooks.onPlayerAttackTarget(this, entity)) return; if (!this.cannotAttack(entity)) { - float baseDamage = this.isAutoSpinAttack() ? this.autoSpinAttackDmg : (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); - ItemStack attackingItemStack = this.getWeaponItem(); -@@ -970,8 +_,10 @@ + float f = this.isAutoSpinAttack() ? this.autoSpinAttackDmg : (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); + ItemStack itemstack = this.getWeaponItem(); +@@ -963,8 +_,10 @@ - baseDamage += attackingItemStack.getItem().getAttackDamageBonus(entity, baseDamage, damageSource); - boolean criticalAttack = fullStrengthAttack && this.canCriticalAttack(entity); -+ var hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, entity, criticalAttack, criticalAttack ? 1.5F : 1.0F); -+ criticalAttack = hitResult != null; - if (criticalAttack) { -- baseDamage *= 1.5F; -+ baseDamage *= hitResult.getDamageModifier(); + f += itemstack.getItem().getAttackDamageBonus(entity, f, damagesource); + boolean flag2 = flag && this.canCriticalAttack(entity); ++ var hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, entity, flag2, flag2 ? 1.5F : 1.0F); ++ flag2 = hitResult != null; + if (flag2) { +- f *= 1.5F; ++ f *= hitResult.getDamageModifier(); } - float totalDamage = baseDamage + magicBoost; -@@ -1045,7 +_,7 @@ - double approximateSpeedSq = this.getKnownMovement().horizontalDistanceSqr(); - double maxSpeedForSweepAttack = this.getSpeed() * 2.5; - if (approximateSpeedSq < Mth.square(maxSpeedForSweepAttack)) { + float f3 = f + f2; +@@ -1036,7 +_,7 @@ + double d0 = this.getKnownMovement().horizontalDistanceSqr(); + double d1 = this.getSpeed() * 2.5; + if (d0 < Mth.square(d1)) { - return this.getItemInHand(InteractionHand.MAIN_HAND).is(ItemTags.SWORDS); + return this.getItemInHand(InteractionHand.MAIN_HAND).canPerformAction(net.minecraftforge.common.ToolActions.SWORD_SWEEP); } } -@@ -1088,8 +_,8 @@ +@@ -1079,8 +_,8 @@ private void itemAttackInteraction(final Entity entity, final ItemStack attackingItemStack, final DamageSource damageSource, final boolean applyToTarget) { - Entity hurtTarget = entity; -- if (entity instanceof EnderDragonPart enderDragonPart) { -- hurtTarget = enderDragonPart.parentMob; + Entity entityx = entity; +- if (entity instanceof EnderDragonPart) { +- entityx = ((EnderDragonPart)entity).parentMob; + if (entity instanceof net.minecraftforge.entity.PartEntity pe) { -+ hurtTarget = pe.getParent(); ++ entityx = pe.getParent(); } - boolean itemHurtEnemy = false; -@@ -1114,6 +_,7 @@ + boolean flag = false; +@@ -1105,6 +_,7 @@ } else { this.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); } @@ -225,16 +224,16 @@ } } } -@@ -1166,7 +_,7 @@ - if (this.level() instanceof ServerLevel serverLevel) { - float var12 = 1.0F + (float)this.getAttributeValue(Attributes.SWEEPING_DAMAGE_RATIO) * baseDamage; +@@ -1145,7 +_,7 @@ + if (this.level() instanceof ServerLevel serverlevel) { + float f = 1.0F + (float)this.getAttributeValue(Attributes.SWEEPING_DAMAGE_RATIO) * baseDamage; -- for (LivingEntity nearby : this.level().getEntitiesOfClass(LivingEntity.class, entity.getBoundingBox().inflate(1.0, 0.25, 1.0))) { -+ for (LivingEntity nearby : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, entity))) { - if (nearby != this - && nearby != entity - && !this.isAlliedTo(nearby) -@@ -1339,6 +_,7 @@ +- for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, entity.getBoundingBox().inflate(1.0, 0.25, 1.0))) { ++ for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, entity))) { + if (livingentity != this + && livingentity != entity + && !this.isAlliedTo(livingentity) +@@ -1311,6 +_,7 @@ } public void stopSleepInBed(final boolean forcefulWakeUp, final boolean updateLevelList) { @@ -242,31 +241,31 @@ super.stopSleeping(); if (this.level() instanceof ServerLevel && updateLevelList) { ((ServerLevel)this.level()).updateSleepingPlayerList(); -@@ -1450,6 +_,7 @@ +@@ -1420,6 +_,7 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { if (this.abilities.mayfly) { + net.minecraftforge.event.ForgeEventFactory.onPlayerFall(this, fallDistance, damageModifier); return false; - } - -@@ -1484,13 +_,13 @@ + } else { + if (fallDistance >= 2.0) { +@@ -1454,13 +_,13 @@ protected void playStepSound(final BlockPos onPos, final BlockState onState) { if (this.isInWater()) { this.waterSwimSound(); - this.playMuffledStepSound(onState); + this.playMuffledStepSound(onState, onPos); } else { - BlockPos primaryStepSoundPos = this.getPrimaryStepSoundBlockPos(onPos); - if (!onPos.equals(primaryStepSoundPos)) { - BlockState primaryStepState = this.level().getBlockState(primaryStepSoundPos); - if (primaryStepState.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { -- this.playCombinationStepSounds(primaryStepState, onState); -+ this.playCombinationStepSounds(primaryStepState, onState, primaryStepSoundPos, onPos); + BlockPos blockpos = this.getPrimaryStepSoundBlockPos(onPos); + if (!onPos.equals(blockpos)) { + BlockState blockstate = this.level().getBlockState(blockpos); + if (blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { +- this.playCombinationStepSounds(blockstate, onState); ++ this.playCombinationStepSounds(blockstate, onState, blockpos, onPos); } else { - super.playStepSound(primaryStepSoundPos, primaryStepState); + super.playStepSound(blockpos, blockstate); } -@@ -1520,7 +_,13 @@ +@@ -1490,7 +_,13 @@ this.tryResetCurrentImpulseContext(); } @@ -281,7 +280,7 @@ this.increaseScore(i); this.experienceProgress = this.experienceProgress + (float)i / this.getXpNeededForNextLevel(); this.totalExperience = Mth.clamp(this.totalExperience + i, 0, Integer.MAX_VALUE); -@@ -1548,7 +_,7 @@ +@@ -1518,7 +_,7 @@ } public void onEnchantmentPerformed(final ItemStack itemStack, final int enchantmentCost) { @@ -290,7 +289,7 @@ if (this.experienceLevel < 0) { this.experienceLevel = 0; this.experienceProgress = 0.0F; -@@ -1558,7 +_,13 @@ +@@ -1528,7 +_,13 @@ this.enchantmentSeed = this.random.nextInt(); } @@ -305,48 +304,47 @@ this.experienceLevel = IntMath.saturatedAdd(this.experienceLevel, amount); if (this.experienceLevel < 0) { this.experienceLevel = 0; -@@ -1697,7 +_,13 @@ +@@ -1667,7 +_,13 @@ @Override public Component getDisplayName() { -- MutableComponent result = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); +- MutableComponent mutablecomponent = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); + if (this.displayname == null) { + this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); + } -+ MutableComponent result = Component.literal(""); -+ result = prefixes.stream().reduce(result, MutableComponent::append); -+ result = result.append(PlayerTeam.formatNameForTeam(this.getTeam(), this.displayname)); -+ result = suffixes.stream().reduce(result, MutableComponent::append); - return this.decorateDisplayNameComponent(result); ++ 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); } -@@ -1882,7 +_,7 @@ - Predicate supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); - ItemStack heldProjectile = ProjectileWeaponItem.getHeldProjectile(this, supportedProjectiles); - if (!heldProjectile.isEmpty()) { -- return heldProjectile; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, heldProjectile); - } +@@ -1857,18 +_,19 @@ + Predicate predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); + ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); + if (!itemstack.isEmpty()) { +- return itemstack; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemstack); + } else { + predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getAllSupportedProjectiles(); - supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getAllSupportedProjectiles(); -@@ -1890,11 +_,12 @@ - for (int i = 0; i < this.inventory.getContainerSize(); i++) { - ItemStack itemStack = this.inventory.getItem(i); - if (supportedProjectiles.test(itemStack)) { -- return itemStack; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemStack); + 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, heldWeapon, itemstack1); + } + } + +- return this.hasInfiniteMaterials() ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; ++ var vanilla = this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, vanilla); } } - -- return this.hasInfiniteMaterials() ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; -+ var vanilla = this.abilities.instabuild ? new ItemStack(Items.ARROW) : ItemStack.EMPTY; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, vanilla); } - - @Override -@@ -2015,6 +_,54 @@ - double maxRange = this.blockInteractionRange() + buffer; - return new AABB(pos).distanceToSqr(this.getEyePosition()) < maxRange * maxRange; +@@ -1989,6 +_,54 @@ + double d0 = this.blockInteractionRange() + buffer; + return new AABB(pos).distanceToSqr(this.getEyePosition()) < d0 * d0; } + + public Collection getPrefixes() { 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 c484ae4a55..952f0d7bc2 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch @@ -12,5 +12,5 @@ + + @Override public DoubleDoubleImmutablePair calculateHorizontalHurtKnockbackDirection(final LivingEntity hurtEntity, final DamageSource damageSource) { - double dx = hurtEntity.position().x - this.position().x; - double dz = hurtEntity.position().z - this.position().z; + double d0 = hurtEntity.position().x - this.position().x; + double d1 = hurtEntity.position().z - this.position().z; 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 d78b9f93df..091b24e54e 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,55 @@ --- a/net/minecraft/world/entity/projectile/FishingHook.java +++ b/net/minecraft/world/entity/projectile/FishingHook.java -@@ -254,8 +_,8 @@ +@@ -251,8 +_,8 @@ if (owner.canInteractWithLevel()) { - ItemStack selectedItem = owner.getMainHandItem(); - ItemStack selectedItemOffHand = owner.getOffhandItem(); -- boolean mainHandIsFishing = selectedItem.is(Items.FISHING_ROD); -- boolean offHandIsFishing = selectedItemOffHand.is(Items.FISHING_ROD); -+ boolean mainHandIsFishing = selectedItem.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); -+ boolean offHandIsFishing = selectedItemOffHand.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); - if ((mainHandIsFishing || offHandIsFishing) && this.distanceToSqr(owner) <= 1024.0) { + ItemStack itemstack = owner.getMainHandItem(); + ItemStack itemstack1 = owner.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 ((flag || flag1) && this.distanceToSqr(owner) <= 1024.0) { return false; } -@@ -267,6 +_,7 @@ +@@ -264,6 +_,7 @@ 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); + HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); ++ if (hitresult.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) + this.hitTargetOrDeflectSelf(hitresult); } -@@ -448,6 +_,7 @@ - Player owner = this.getPlayerOwner(); - if (!this.level().isClientSide() && owner != null && !this.shouldStopFishing(owner)) { - int dmg = 0; +@@ -453,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)owner, rod, this, Collections.emptyList()); -@@ -458,10 +_,16 @@ + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, rod, this, Collections.emptyList()); +@@ -463,10 +_,16 @@ .withParameter(LootContextParams.ORIGIN, this.position()) .withParameter(LootContextParams.TOOL, rod) .withParameter(LootContextParams.THIS_ENTITY, this) + .withParameter(LootContextParams.ATTACKING_ENTITY, this.getOwner()) - .withLuck(this.luck + owner.getLuck()) + .withLuck(this.luck + player.getLuck()) .create(LootContextParamSets.FISHING); - LootTable lootTable = this.level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); - List items = lootTable.getRandomItems(params); -+ event = new net.minecraftforge.event.entity.player.ItemFishedEvent(items, this.onGround() ? 2 : 1, this); + LootTable loottable = this.level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); + List list = loottable.getRandomItems(lootparams); ++ event = new net.minecraftforge.event.entity.player.ItemFishedEvent(list, this.onGround() ? 2 : 1, this); + if (net.minecraftforge.event.entity.player.ItemFishedEvent.BUS.post(event)) { + this.discard(); + return event.getRodDamage(); + } - CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)owner, rod, this, items); + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, rod, this, list); - for (ItemStack itemStack : items) { -@@ -487,7 +_,7 @@ + for (ItemStack itemstack : list) { +@@ -492,7 +_,7 @@ } this.discard(); -- return dmg; -+ return event == null ? dmg : event.getRodDamage(); +- return i; ++ return event == null ? i : event.getRodDamage(); } else { return 0; } 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 12dfb84f1e..da4ffbc292 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/entity/projectile/LlamaSpit.java +++ b/net/minecraft/world/entity/projectile/LlamaSpit.java -@@ -44,7 +_,8 @@ +@@ -43,7 +_,8 @@ super.tick(); - Vec3 movement = 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 x = this.getX() + movement.x; - double y = this.getY() + movement.y; - double z = this.getZ() + movement.z; + 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 7702952934..26017c4257 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch @@ -3,9 +3,9 @@ @@ -363,7 +_,7 @@ @Override public boolean mayInteract(final ServerLevel level, final BlockPos pos) { - Entity owner = this.getOwner(); -- return owner instanceof Player ? owner.mayInteract(level, pos) : owner == null || level.getGameRules().get(GameRules.MOB_GRIEFING); -+ return owner instanceof Player ? owner.mayInteract(level, pos) : owner == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, owner); + Entity entity = this.getOwner(); +- return entity instanceof Player ? entity.mayInteract(level, pos) : entity == null || level.getGameRules().get(GameRules.MOB_GRIEFING); ++ return entity instanceof Player ? entity.mayInteract(level, pos) : entity == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, entity); } public boolean mayBreak(final ServerLevel level) { 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 d7381e8823..0699accf74 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/projectile/ProjectileUtil.java +++ b/net/minecraft/world/entity/projectile/ProjectileUtil.java @@ -127,7 +_,7 @@ - Vec3 location = clipPoint.get(); - double dd = from.distanceToSqr(location); - if (dd < nearest || nearest == 0.0) { -- if (entity.getRootVehicle() == except.getRootVehicle()) { -+ if (entity.getRootVehicle() == except.getRootVehicle() && !entity.canRiderInteract()) { - if (nearest == 0.0) { - hovered = entity; - hoveredPos = location; -@@ -268,8 +_,13 @@ + Vec3 vec31 = optional.get(); + double d1 = from.distanceToSqr(vec31); + if (d1 < d0 || d0 == 0.0) { +- if (entity1.getRootVehicle() == except.getRootVehicle()) { ++ if (entity1.getRootVehicle() == except.getRootVehicle() && !entity1.canRiderInteract()) { + if (d0 == 0.0) { + entity = entity1; + vec3 = vec31; +@@ -266,8 +_,13 @@ } } 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 60354ed24f..72d334cb43 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 -@@ -218,7 +_,7 @@ +@@ -215,7 +_,7 @@ this.handlePortal(); } -- if (hitResult != null && this.isAlive() && hitResult.getType() != HitResult.Type.MISS) { -+ if (hitResult != null && this.isAlive() && hitResult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) { - this.hitTargetOrDeflectSelf(hitResult); +- if (hitresult != null && this.isAlive() && hitresult.getType() != HitResult.Type.MISS) { ++ if (hitresult != null && this.isAlive() && 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/ThrowableProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch index 39f52acee7..41d4112127 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch @@ -4,8 +4,8 @@ this.updateRotation(); this.applyEffectsFromBlocks(); super.tick(); -- if (result.getType() != HitResult.Type.MISS && this.isAlive()) { -+ if (result.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, result)) { - this.hitTargetOrDeflectSelf(result); +- if (hitresult.getType() != HitResult.Type.MISS && this.isAlive()) { ++ if (hitresult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { + this.hitTargetOrDeflectSelf(hitresult); } } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch index bfe8e60770..3b81caadd6 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java +++ b/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java -@@ -79,6 +_,7 @@ +@@ -78,6 +_,7 @@ private @Nullable List piercedAndKilledEntities; private ItemStack pickupItemStack = this.getDefaultPickupItem(); private @Nullable ItemStack firedFromWeapon = null; @@ -8,7 +8,7 @@ protected AbstractArrow(final EntityType type, final Level level) { super(type, level); -@@ -196,7 +_,7 @@ +@@ -195,7 +_,7 @@ this.shakeTime--; } @@ -17,9 +17,9 @@ this.clearFire(); } -@@ -601,7 +_,7 @@ +@@ -585,7 +_,7 @@ protected boolean canHitEntity(final Entity entity) { - return entity instanceof Player playerEntity && this.getOwner() instanceof Player player && !player.canHarmPlayer(playerEntity) + return entity instanceof Player && this.getOwner() instanceof Player player && !player.canHarmPlayer((Player)entity) ? false - : super.canHitEntity(entity) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(entity.getId())); + : super.canHitEntity(entity) && (this.piercingIgnoreEntityIds == null || !this.piercingIgnoreEntityIds.contains(entity.getId())) && !this.ignoredEntities.contains(entity.getId()); diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch index dc1b951871..65590d2f72 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch @@ -4,8 +4,8 @@ this.igniteForSeconds(1.0F); } -- if (hitResult.getType() != HitResult.Type.MISS && this.isAlive()) { -+ if (hitResult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) { - this.hitTargetOrDeflectSelf(hitResult); +- if (hitresult.getType() != HitResult.Type.MISS && this.isAlive()) { ++ if (hitresult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { + this.hitTargetOrDeflectSelf(hitresult); } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch index 22cf159ffe..414c0ed86b 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java +++ b/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java -@@ -32,7 +_,7 @@ +@@ -31,7 +_,7 @@ protected void onHit(final HitResult hitResult) { super.onHit(hitResult); - if (this.level() instanceof ServerLevel serverLevel) { -- boolean grief = serverLevel.getGameRules().get(GameRules.MOB_GRIEFING); -+ boolean grief = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this.getOwner()); - this.level().explode(this, this.getX(), this.getY(), this.getZ(), this.explosionPower, grief, Level.ExplosionInteraction.MOB); + if (this.level() instanceof ServerLevel serverlevel) { +- boolean flag = serverlevel.getGameRules().get(GameRules.MOB_GRIEFING); ++ boolean flag = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this.getOwner()); + this.level().explode(this, this.getX(), this.getY(), this.getZ(), this.explosionPower, flag, Level.ExplosionInteraction.MOB); this.discard(); } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch index 35452cb788..453ccada82 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java +++ b/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java -@@ -52,7 +_,7 @@ +@@ -51,7 +_,7 @@ super.onHitBlock(hitResult); - if (this.level() instanceof ServerLevel serverLevel) { - Entity owner = this.getOwner(); -- if (!(owner instanceof Mob) || serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!(owner instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, owner)) { - BlockPos pos = hitResult.getBlockPos().relative(hitResult.getDirection()); - if (this.level().isEmptyBlock(pos)) { - this.level().setBlockAndUpdate(pos, BaseFireBlock.getState(this.level(), pos)); + if (this.level() instanceof ServerLevel serverlevel) { + Entity entity = this.getOwner(); +- if (!(entity instanceof Mob) || serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!(entity instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, entity)) { + BlockPos blockpos = hitResult.getBlockPos().relative(hitResult.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/hurtingprojectile/WitherSkull.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/WitherSkull.java.patch index d9ef30e129..2daf337cb4 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/WitherSkull.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/WitherSkull.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/projectile/hurtingprojectile/WitherSkull.java +++ b/net/minecraft/world/entity/projectile/hurtingprojectile/WitherSkull.java -@@ -52,7 +_,7 @@ +@@ -51,7 +_,7 @@ public float getBlockExplosionResistance( final Explosion explosion, final BlockGetter level, final BlockPos pos, final BlockState block, final FluidState fluid, final float resistance ) { diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch index 7cc436e850..d5244c229f 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java +++ b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java -@@ -104,6 +_,13 @@ - Vec3 teleportPos = this.oldPosition(); - if (owner instanceof ServerPlayer player) { - if (player.connection.isAcceptingMessages()) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(player, this.getX(), this.getY(), this.getZ(), this, 5.0F, hitResult); +@@ -102,6 +_,13 @@ + Vec3 vec3 = this.oldPosition(); + if (entity instanceof ServerPlayer serverplayer) { + if (serverplayer.connection.isAcceptingMessages()) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(serverplayer, this.getX(), this.getY(), this.getZ(), this, 5.0F, hitResult); + if (event == null) { + this.discard(); + return; + } -+ teleportPos = event.getTarget(); ++ vec3 = event.getTarget(); + - if (this.random.nextFloat() < 0.05F && level.isSpawningMonsters() && level.getLevelData().getDifficulty() != Difficulty.PEACEFUL) { - Endermite endermite = EntityTypes.ENDERMITE.create(level, EntitySpawnReason.TRIGGERED); + if (this.random.nextFloat() < 0.05F && serverlevel.isSpawningMonsters()) { + Endermite endermite = EntityType.ENDERMITE.create(serverlevel, EntitySpawnReason.TRIGGERED); if (endermite != null) { -@@ -124,7 +_,7 @@ - if (newOwner != null) { - newOwner.resetFallDistance(); - newOwner.resetCurrentImpulseContext(); -- newOwner.hurtServer(player.level(), this.damageSources().enderPearl(), 5.0F); -+ newOwner.hurtServer(player.level(), this.damageSources().enderPearl(), event.getAttackDamage()); +@@ -122,7 +_,7 @@ + if (serverplayer1 != null) { + serverplayer1.resetFallDistance(); + serverplayer1.resetCurrentImpulseContext(); +- serverplayer1.hurtServer(serverplayer.level(), this.damageSources().enderPearl(), 5.0F); ++ serverplayer1.hurtServer(serverplayer.level(), this.damageSources().enderPearl(), event.getAttackDamage()); } - this.playSound(level, teleportPos); + this.playSound(serverlevel, vec3); 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 650d7048c3..0186384999 100644 --- a/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch @@ -4,13 +4,13 @@ } } -- public enum RaiderType { -+ public enum RaiderType implements net.minecraftforge.common.IExtensibleEnum { - VINDICATOR(EntityTypes.VINDICATOR, new int[]{0, 0, 2, 0, 1, 4, 2, 5}), - EVOKER(EntityTypes.EVOKER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}), - PILLAGER(EntityTypes.PILLAGER, new int[]{0, 4, 3, 3, 4, 4, 4, 2}), +- public 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}), @@ -844,6 +_,20 @@ - RaiderType(final EntityType entityType, final int[] spawnsPerWaveBeforeBonus) { + private RaiderType(final EntityType entityType, final int[] spawnsPerWaveBeforeBonus) { this.entityType = entityType; this.spawnsPerWaveBeforeBonus = spawnsPerWaveBeforeBonus; + } 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 c9931d4fad..eba148ab08 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 -@@ -100,6 +_,9 @@ +@@ -101,6 +_,9 @@ this.setContainerLootTable(null); - LootParams.Builder builder = new LootParams.Builder((ServerLevel)this.level()).withParameter(LootContextParams.ORIGIN, this.position()); + 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 net.minecraft.world.entity.vehicle.minecart.AbstractMinecartContainer entityContainer) -+ builder.withParameter(LootContextParams.ATTACKING_ENTITY, entityContainer); ++ lootparams$builder.withParameter(LootContextParams.ATTACKING_ENTITY, entityContainer); if (player != null) { - builder.withLuck(player.getLuck()).withParameter(LootContextParams.THIS_ENTITY, player); + lootparams$builder.withLuck(player.getLuck()).withParameter(LootContextParams.THIS_ENTITY, player); } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch index b0daa4861e..2935d225bf 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch @@ -10,42 +10,42 @@ private static final EntityDataAccessor DATA_ID_PADDLE_RIGHT = SynchedEntityData.defineId(AbstractBoat.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor DATA_ID_BUBBLE_TIME = SynchedEntityData.defineId(AbstractBoat.class, EntityDataSerializers.INT); @@ -416,7 +_,7 @@ - for (int z = minZ; z < maxZ; z++) { - pos.set(x, y, z); - FluidState fluidState = this.level().getFluidState(pos); -- if (fluidState.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidState)) { - blockHeight = Math.max(blockHeight, fluidState.getHeight(this.level(), pos)); + 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)); } -@@ -458,7 +_,7 @@ - BlockState blockState = this.level().getBlockState(blockPos); - if (!(blockState.getBlock() instanceof LilyPadBlock) - && Shapes.joinIsNotEmpty(blockState.getCollisionShape(this.level(), blockPos).move(blockPos), boatShape, BooleanOp.AND)) { -- friction += blockState.getBlock().getFriction(); -+ friction += blockState.getFriction(this.level(), blockPos, this); - count++; +@@ -462,7 +_,7 @@ + voxelshape, + BooleanOp.AND + )) { +- f += blockstate.getBlock().getFriction(); ++ f += blockstate.getFriction(this.level(), blockpos$mutableblockpos, this); + k1++; } } -@@ -487,7 +_,7 @@ - for (int z = minZ; z < maxZ; z++) { - pos.set(x, y, z); - FluidState fluidState = this.level().getFluidState(pos); -- if (fluidState.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidState)) { - float height = y + fluidState.getHeight(this.level(), pos); - this.waterLevel = Math.max(height, this.waterLevel); - inWater |= bb.minY < height; -@@ -516,7 +_,7 @@ - for (int z = z0; z < z1; z++) { - pos.set(x, y, z); - FluidState fluidState = this.level().getFluidState(pos); -- if (fluidState.is(FluidTags.WATER) && maxY < pos.getY() + fluidState.getHeight(this.level(), pos)) { -+ if (this.canBoatInFluid(fluidState) && maxY < pos.getY() + fluidState.getHeight(this.level(), pos)) { - if (!fluidState.isSource()) { +@@ -491,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 = l1 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos); + this.waterLevel = Math.max((double)f, this.waterLevel); + flag |= aabb.minY < f; +@@ -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) && d0 < blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)) { ++ if (this.canBoatInFluid(fluidstate) && d0 < blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)) { + if (!fluidstate.isSource()) { return AbstractBoat.Status.UNDER_FLOWING_WATER; } -@@ -725,7 +_,7 @@ +@@ -722,7 +_,7 @@ if (!this.isPassenger()) { if (onGround) { this.resetFallDistance(); @@ -54,7 +54,7 @@ this.fallDistance -= (float)ya; } } -@@ -749,7 +_,7 @@ +@@ -746,7 +_,7 @@ @Override protected boolean canAddPassenger(final Entity passenger) { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch index a6ea0ec349..bd5ae354b5 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch @@ -36,14 +36,14 @@ } @Override -@@ -367,22 +_,31 @@ +@@ -365,16 +_,24 @@ } protected void comeOffTrack(final ServerLevel level) { -- double maxSpeed = this.getMaxSpeed(level); -+ double maxSpeed = this.onGround() ? this.getMaxSpeed(level) : getMaxSpeedAirLateral(); - Vec3 movement = this.getDeltaMovement(); - this.setDeltaMovement(Mth.clamp(movement.x, -maxSpeed, maxSpeed), movement.y, Mth.clamp(movement.z, -maxSpeed, maxSpeed)); +- double d0 = this.getMaxSpeed(level); ++ double d0 = this.onGround() ? this.getMaxSpeed(level) : 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)); } @@ -58,28 +58,21 @@ + this.move(MoverType.SELF, this.getDeltaMovement()); if (!this.onGround()) { - this.setDeltaMovement(this.getDeltaMovement().scale(this.getAirDrag())); +- this.setDeltaMovement(this.getDeltaMovement().scale(0.95)); ++ this.setDeltaMovement(this.getDeltaMovement().scale(getDragAir())); } } -+ private float airDrag = DEFAULT_AIR_DRAG; - @Override - protected float getAirDrag() { -- return 0.95F; -+ return airDrag; - } - - protected double makeStepAlongTrack(final BlockPos pos, final RailShape shape, final double movementLeft) { -@@ -438,7 +_,7 @@ +@@ -431,7 +_,7 @@ public Vec3 getRedstoneDirection(final BlockPos pos) { - BlockState state = this.level().getBlockState(pos); - if (state.is(Blocks.POWERED_RAIL) && state.getValue(PoweredRailBlock.POWERED)) { -- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); -+ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), pos, this); - if (shape == RailShape.EAST_WEST) { + BlockState blockstate = this.level().getBlockState(pos); + if (blockstate.is(Blocks.POWERED_RAIL) && blockstate.getValue(PoweredRailBlock.POWERED)) { +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), pos, this); + if (railshape == RailShape.EAST_WEST) { if (this.isRedstoneConductor(pos.west())) { return new Vec3(1.0, 0.0, 0.0); -@@ -609,5 +_,40 @@ +@@ -602,5 +_,42 @@ public boolean isFurnace() { return false; @@ -103,7 +96,9 @@ + private float maxSpeedAirVertical = DEFAULT_MAX_SPEED_AIR_VERTICAL; + @Override public float getMaxSpeedAirVertical() { return maxSpeedAirVertical; } + @Override public void setMaxSpeedAirVertical(float value) { maxSpeedAirVertical = value; } -+ @Override public void setAirDrag(float value) { airDrag = 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()) { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java.patch index 20536dbc0b..be62403c6c 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java +++ b/net/minecraft/world/entity/vehicle/minecart/MinecartCommandBlock.java -@@ -87,6 +_,8 @@ +@@ -88,6 +_,8 @@ @Override public InteractionResult interact(final Player player, final InteractionHand hand, final Vec3 location) { @@ -8,4 +8,4 @@ + if (ret.consumesAction()) return ret; if (!player.canUseGameMasterBlocks()) { return InteractionResult.PASS; - } + } else { diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java.patch index ecdf77384e..a1dd91697f 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java +++ b/net/minecraft/world/entity/vehicle/minecart/MinecartSpawner.java -@@ -19,6 +_,11 @@ +@@ -24,6 +_,11 @@ public void broadcastEvent(final Level level, final BlockPos pos, final int id) { level.broadcastEntityEvent(MinecartSpawner.this, (byte)id); } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch index e0b8e71275..8fd49d5283 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch @@ -1,30 +1,29 @@ --- a/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java +++ b/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java -@@ -153,7 +_,7 @@ +@@ -169,7 +_,7 @@ public void adjustToRails(final BlockPos targetBlockPos, final BlockState currentState, final boolean instant) { if (BaseRailBlock.isRail(currentState)) { -- RailShape shape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); -+ RailShape shape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), targetBlockPos, this.minecart); - Pair exits = AbstractMinecart.exits(shape); - Vec3 exit0 = new Vec3(exits.getFirst()).scale(0.5); - Vec3 exit1 = new Vec3(exits.getSecond()).scale(0.5); -@@ -246,12 +_,12 @@ - if (onRails) { +- RailShape railshape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), targetBlockPos, this.minecart); + Pair pair = AbstractMinecart.exits(railshape); + Vec3 vec3 = new Vec3(pair.getFirst()).scale(0.5); + Vec3 vec31 = new Vec3(pair.getSecond()).scale(0.5); +@@ -257,11 +_,11 @@ + if (flag) { this.minecart.resetFallDistance(); this.minecart.setOldPosAndRot(); -- if (currentState.is(Blocks.ACTIVATOR_RAIL)) { -+ if (currentState.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { - this.minecart - .activateMinecart(level, currentPos.getX(), currentPos.getY(), currentPos.getZ(), currentState.getValue(PoweredRailBlock.POWERED)); +- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { ++ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { + this.minecart.activateMinecart(level, blockpos.getX(), blockpos.getY(), blockpos.getZ(), blockstate.getValue(PoweredRailBlock.POWERED)); } -- RailShape shape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); -+ RailShape shape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), currentPos, this.minecart); - Vec3 newDeltaMovement = this.calculateTrackSpeed(level, initialStepDeltaMovement.horizontal(), trackIteration, currentPos, currentState, shape); - if (trackIteration.firstIteration) { - trackIteration.movementLeft = newDeltaMovement.horizontalDistance(); -@@ -386,7 +_,7 @@ +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), blockpos, this.minecart); + Vec3 vec31 = this.calculateTrackSpeed(level, vec3.horizontal(), newminecartbehavior$trackiteration, blockpos, blockstate, railshape); + if (newminecartbehavior$trackiteration.firstIteration) { + newminecartbehavior$trackiteration.movementLeft = vec31.horizontalDistance(); +@@ -397,7 +_,7 @@ } private Vec3 calculateHaltTrackSpeed(final Vec3 deltaMovement, final BlockState state) { @@ -33,7 +32,7 @@ return deltaMovement.length() < 0.03 ? Vec3.ZERO : deltaMovement.scale(0.5); } else { return deltaMovement; -@@ -394,7 +_,7 @@ +@@ -405,7 +_,7 @@ } private Vec3 calculateBoostTrackSpeed(final Vec3 deltaMovement, final BlockPos pos, final BlockState state) { @@ -41,13 +40,13 @@ + if (state.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail() && state.getValue(PoweredRailBlock.POWERED)) { if (deltaMovement.length() > 0.01) { return deltaMovement.normalize().scale(deltaMovement.length() + 0.06); - } -@@ -448,7 +_,7 @@ - BlockState newBlockState = this.level().getBlockState(BlockPos.containing(newPosition)); - if (inHill) { - if (BaseRailBlock.isRail(newBlockState)) { -- RailShape newRailShape = newBlockState.getValue(((BaseRailBlock)newBlockState.getBlock()).getShapeProperty()); -+ RailShape newRailShape = ((BaseRailBlock)newBlockState.getBlock()).getRailDirection(newBlockState, this.level(), BlockPos.containing(newPosition), this.minecart); - if (this.restAtVShape(shape, newRailShape)) { - return 0.0; - } + } else { +@@ -457,7 +_,7 @@ + BlockState blockstate = this.level().getBlockState(BlockPos.containing(vec36)); + if (flag) { + if (BaseRailBlock.isRail(blockstate)) { +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), BlockPos.containing(vec36), this.minecart); + if (this.restAtVShape(shape, railshape)) { + return 0.0; + } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch index 53f4548353..33b39e5fcd 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch @@ -1,94 +1,93 @@ --- a/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java +++ b/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java @@ -60,9 +_,9 @@ - BlockState state = this.level().getBlockState(var11); - boolean onRails = BaseRailBlock.isRail(state); + BlockState blockstate = this.level().getBlockState(blockpos); + boolean onRails = BaseRailBlock.isRail(blockstate); this.minecart.setOnRails(onRails); - if (onRails) { + if (this.minecart.canUseRail() && onRails) { - this.moveAlongTrack(level); -- if (state.is(Blocks.ACTIVATOR_RAIL)) { -+ if (state.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { - this.minecart.activateMinecart(level, var11.getX(), var11.getY(), var11.getZ(), state.getValue(PoweredRailBlock.POWERED)); + this.moveAlongTrack(serverlevel); +- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { ++ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { + this.minecart + .activateMinecart(serverlevel, blockpos.getX(), blockpos.getY(), blockpos.getZ(), blockstate.getValue(PoweredRailBlock.POWERED)); } - } else { -@@ -112,18 +_,19 @@ - y = pos.getY(); - boolean powerTrack = false; - boolean haltTrack = false; -- if (state.is(Blocks.POWERED_RAIL)) { -+ BaseRailBlock baserailblock = (BaseRailBlock)state.getBlock(); -+ if (state.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail()) { - powerTrack = state.getValue(PoweredRailBlock.POWERED); - haltTrack = !powerTrack; +@@ -113,18 +_,19 @@ + d1 = blockpos.getY(); + boolean flag = false; + boolean flag1 = false; +- if (blockstate.is(Blocks.POWERED_RAIL)) { ++ BaseRailBlock baserailblock = (BaseRailBlock)blockstate.getBlock(); ++ if (blockstate.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail()) { + flag = blockstate.getValue(PoweredRailBlock.POWERED); + flag1 = !flag; } -- double slideSpeed = 0.0078125; -+ double slideSpeed = getSlopeAdjustment(); +- double d3 = 0.0078125; ++ double d3 = getSlopeAdjustment(); if (this.minecart.isInWater()) { - slideSpeed *= 0.2; + d3 *= 0.2; } - Vec3 movement = this.getDeltaMovement(); -- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); -+ RailShape shape = baserailblock.getRailDirection(state, this.level(), pos, this.minecart); - switch (shape) { + Vec3 vec31 = this.getDeltaMovement(); +- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); ++ RailShape railshape = baserailblock.getRailDirection(blockstate, this.level(), blockpos, this.minecart); + switch (railshape) { case ASCENDING_EAST: - this.setDeltaMovement(movement.add(-slideSpeed, 0.0, 0.0)); -@@ -175,7 +_,7 @@ + this.setDeltaMovement(vec31.add(-d3, 0.0, 0.0)); +@@ -176,7 +_,7 @@ } } -- if (haltTrack) { -+ if (haltTrack && shouldDoRailFunctions()) { - double speedLength = this.getDeltaMovement().horizontalDistance(); - if (speedLength < 0.03) { +- if (flag1) { ++ if (flag1 && shouldDoRailFunctions()) { + double d20 = this.getDeltaMovement().horizontalDistance(); + if (d20 < 0.03) { this.setDeltaMovement(Vec3.ZERO); -@@ -204,11 +_,7 @@ - x = x0 + xD * progress; - z = z0 + zD * progress; - this.setPos(x, y, z); -- double scale = this.minecart.isVehicle() ? 0.75 : 1.0; -- double maxSpeed = this.minecart.getMaxSpeed(level); -- movement = this.getDeltaMovement(); -- this.minecart -- .move(MoverType.SELF, new Vec3(Mth.clamp(scale * movement.x, -maxSpeed, maxSpeed), 0.0, Mth.clamp(scale * movement.z, -maxSpeed, maxSpeed))); +@@ -205,10 +_,7 @@ + d0 = d21 + d4 * d12; + d2 = d9 + d5 * d12; + this.setPos(d0, d1, d2); +- double d23 = this.minecart.isVehicle() ? 0.75 : 1.0; +- double d24 = this.minecart.getMaxSpeed(level); +- vec31 = this.getDeltaMovement(); +- this.minecart.move(MoverType.SELF, new Vec3(Mth.clamp(d23 * vec31.x, -d24, d24), 0.0, Mth.clamp(d23 * vec31.z, -d24, d24))); + this.moveMinecartOnRail(level); - if (exit0.getY() != 0 && Mth.floor(this.minecart.getX()) - pos.getX() == exit0.getX() && Mth.floor(this.minecart.getZ()) - pos.getZ() == exit0.getZ()) { - this.setPos(this.minecart.getX(), this.minecart.getY() + exit0.getY(), this.minecart.getZ()); - } else if (exit1.getY() != 0 -@@ -238,7 +_,11 @@ - this.setDeltaMovement(otherPow * (xn - pos.getX()), vec3.y, otherPow * (zn - pos.getZ())); + if (vec3i.getY() != 0 + && Mth.floor(this.minecart.getX()) - blockpos.getX() == vec3i.getX() + && Mth.floor(this.minecart.getZ()) - blockpos.getZ() == vec3i.getZ()) { +@@ -240,7 +_,11 @@ + this.setDeltaMovement(d25 * (j - blockpos.getX()), vec36.y, d25 * (i - blockpos.getZ())); } -- if (powerTrack) { +- if (flag) { + if (shouldDoRailFunctions()) { -+ baserailblock.onMinecartPass(state, level(), pos, this.minecart); ++ baserailblock.onMinecartPass(blockstate, level(), blockpos, this.minecart); + } + -+ if (powerTrack && shouldDoRailFunctions()) { - Vec3 vec3 = this.getDeltaMovement(); - double speedLength = vec3.horizontalDistance(); - if (speedLength > 0.01) { -@@ -281,7 +_,7 @@ ++ if (flag && shouldDoRailFunctions()) { + Vec3 vec37 = this.getDeltaMovement(); + double d26 = vec37.horizontalDistance(); + if (d26 > 0.01) { +@@ -283,7 +_,7 @@ - BlockState state = this.level().getBlockState(new BlockPos(xt, yt, zt)); - if (BaseRailBlock.isRail(state)) { -- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); -+ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), new BlockPos(xt, yt, zt), this.minecart); - y = yt; - if (shape.isSlope()) { - y = yt + 1; -@@ -319,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.minecart); + y = j; + if (railshape.isSlope()) { + y = j + 1; +@@ -321,7 +_,7 @@ - BlockState state = this.level().getBlockState(new BlockPos(xt, yt, zt)); - if (BaseRailBlock.isRail(state)) { -- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); -+ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), new BlockPos(xt, yt, zt), this.minecart); - Pair exits = AbstractMinecart.exits(shape); - Vec3i exit0 = exits.getFirst(); - Vec3i exit1 = exits.getSecond(); -@@ -412,5 +_,20 @@ + 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.minecart); + Pair pair = AbstractMinecart.exits(railshape); + Vec3i vec3i = pair.getFirst(); + Vec3i vec3i1 = pair.getSecond(); +@@ -414,5 +_,20 @@ @Override public double getSlowdownFactor() { return this.minecart.isVehicle() ? 0.997 : 0.96; diff --git a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch index b7e2243a9e..fb1aade29d 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/inventory/AbstractContainerMenu.java +++ b/net/minecraft/world/inventory/AbstractContainerMenu.java -@@ -435,6 +_,7 @@ - ItemStack carried = this.getCarried(); - player.updateTutorialInventoryAction(carried, slot.getItem(), clickAction); - if (!this.tryItemClickBehaviourOverride(player, clickAction, slot, clicked, carried)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onItemStackedOn(carried, clicked, slot, clickAction, player, createCarriedSlotAccess())) - if (clicked.isEmpty()) { - if (!carried.isEmpty()) { - int amount = clickAction == ClickAction.PRIMARY ? carried.getCount() : 1; -@@ -648,7 +_,7 @@ - ItemStack target = slot.getItem(); - if (!target.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, target)) { - int totalStack = target.getCount() + itemStack.getCount(); -- int maxStackSize = slot.getMaxStackSize(target); -+ int maxStackSize = Math.min(slot.getMaxStackSize(target), target.getMaxStackSize()); - if (totalStack <= maxStackSize) { +@@ -438,6 +_,7 @@ + ItemStack itemstack10 = this.getCarried(); + player.updateTutorialInventoryAction(itemstack10, slot7.getItem(), clickaction); + if (!this.tryItemClickBehaviourOverride(player, clickaction, slot7, itemstack9, itemstack10)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onItemStackedOn(itemstack10, itemstack9, slot7, clickaction, player, createCarriedSlotAccess())) + if (itemstack9.isEmpty()) { + if (!itemstack10.isEmpty()) { + int i3 = clickaction == ClickAction.PRIMARY ? itemstack10.getCount() : 1; +@@ -658,7 +_,7 @@ + ItemStack itemstack = slot.getItem(); + if (!itemstack.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, itemstack)) { + int j = itemstack.getCount() + itemStack.getCount(); +- int k = slot.getMaxStackSize(itemstack); ++ int k = Math.min(slot.getMaxStackSize(itemstack), itemstack.getMaxStackSize()); + if (j <= k) { itemStack.setCount(0); - target.setCount(totalStack); + itemstack.setCount(j); diff --git a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch index c7ebd6ab50..9c54dca6e4 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch @@ -1,48 +1,48 @@ --- a/net/minecraft/world/inventory/AnvilMenu.java +++ b/net/minecraft/world/inventory/AnvilMenu.java -@@ -77,6 +_,8 @@ +@@ -79,6 +_,8 @@ player.giveExperienceLevels(-this.cost.get()); } + float breakChance = net.minecraftforge.event.ForgeEventFactory.onAnvilRepair(player, carried, AnvilMenu.this.inputSlots.getItem(0), AnvilMenu.this.inputSlots.getItem(1)).getBreakChance(); + if (this.repairItemCountCost > 0) { - ItemStack addition = this.inputSlots.getItem(1); - if (!addition.isEmpty() && addition.getCount() > this.repairItemCountCost) { -@@ -99,7 +_,7 @@ + ItemStack itemstack = this.inputSlots.getItem(1); + if (!itemstack.isEmpty() && itemstack.getCount() > this.repairItemCountCost) { +@@ -101,7 +_,7 @@ this.inputSlots.setItem(0, ItemStack.EMPTY); this.access.execute((level, pos) -> { - BlockState state = level.getBlockState(pos); -- if (!player.hasInfiniteMaterials() && state.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { -+ if (!player.hasInfiniteMaterials() && state.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < breakChance) { - BlockState newBlockState = AnvilBlock.damage(state); - if (newBlockState == null) { + BlockState blockstate = level.getBlockState(pos); +- if (!player.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { ++ if (!player.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < breakChance) { + BlockState blockstate1 = AnvilBlock.damage(blockstate); + if (blockstate1 == null) { level.removeBlock(pos, false); -@@ -128,8 +_,11 @@ - ItemEnchantments.Mutable enchantments = new ItemEnchantments.Mutable(EnchantmentHelper.getEnchantmentsForCrafting(result)); - tax += (long)input.getOrDefault(DataComponents.REPAIR_COST, 0).intValue() + addition.getOrDefault(DataComponents.REPAIR_COST, 0).intValue(); +@@ -130,8 +_,11 @@ + ItemEnchantments.Mutable itemenchantments$mutable = new ItemEnchantments.Mutable(EnchantmentHelper.getEnchantmentsForCrafting(itemstack1)); + j += (long)itemstack.getOrDefault(DataComponents.REPAIR_COST, 0).intValue() + itemstack2.getOrDefault(DataComponents.REPAIR_COST, 0).intValue(); this.repairItemCountCost = 0; -+ boolean usingBook = false; ++ boolean flag = false; + -+ if (!net.minecraftforge.common.ForgeHooks.onAnvilChange(this, input, addition, resultSlots, itemName, tax, this.player)) return; - if (!addition.isEmpty()) { -- boolean usingBook = addition.has(DataComponents.STORED_ENCHANTMENTS); -+ usingBook = addition.has(DataComponents.STORED_ENCHANTMENTS); - if (result.isDamageableItem() && input.isValidRepairItem(addition)) { - int repairAmount = Math.min(result.getDamageValue(), result.getMaxDamage() / 4); - if (repairAmount <= 0) { -@@ -233,6 +_,10 @@ - result.remove(DataComponents.CUSTOM_NAME); ++ 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() && itemstack.isValidRepairItem(itemstack2)) { + int l2 = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); + if (l2 <= 0) { +@@ -235,6 +_,10 @@ + itemstack1.remove(DataComponents.CUSTOM_NAME); } -+ if (usingBook && !result.isBookEnchantable(addition)) { -+ result = ItemStack.EMPTY; ++ if (flag && !itemstack1.isBookEnchantable(itemstack2)) { ++ itemstack1 = ItemStack.EMPTY; + } + - int finalPrice = price <= 0 ? 0 : (int)Mth.clamp(tax + price, 0L, 2147483647L); - this.cost.set(finalPrice); - if (price <= 0) { -@@ -304,5 +_,9 @@ + int k2 = i <= 0 ? 0 : (int)Mth.clamp(j + i, 0L, 2147483647L); + this.cost.set(k2); + if (i <= 0) { +@@ -306,5 +_,9 @@ public int getCost() { return this.cost.get(); diff --git a/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch index ea2a685a9a..1463d1a285 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 -@@ -88,10 +_,8 @@ +@@ -92,10 +_,8 @@ } - slot.onQuickCraft(stack, clicked); -- } else if (!this.paymentSlot.hasItem() && this.paymentSlot.mayPlace(stack) && stack.getCount() == 1) { -- if (!this.moveItemStackTo(stack, 0, 1, false)) { + 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(stack, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. ++ } else if (this.moveItemStackTo(itemstack1, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. + return ItemStack.EMPTY; } else if (slotIndex >= 1 && slotIndex < 28) { - if (!this.moveItemStackTo(stack, 28, 37, false)) { + 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 701b3abb7b..d372d8fd27 100644 --- a/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch @@ -3,26 +3,26 @@ @@ -45,9 +_,9 @@ this.brewingStand = brewingStand; this.brewingStandData = brewingStandData; - PotionBrewing potionBrewing = inventory.player.level().potionBrewing(); + PotionBrewing potionbrewing = inventory.player.level().potionBrewing(); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51)); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58)); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51, potionBrewing)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58, potionBrewing)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51, potionBrewing)); - this.ingredientSlot = this.addSlot(new BrewingStandMenu.IngredientsSlot(potionBrewing, brewingStand, 3, 79, 17)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51, potionbrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58, potionbrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51, potionbrewing)); + this.ingredientSlot = this.addSlot(new BrewingStandMenu.IngredientsSlot(potionbrewing, brewingStand, 3, 79, 17)); this.addSlot(new BrewingStandMenu.FuelSlot(brewingStand, 4, 17, 17)); this.addDataSlots(brewingStandData); -@@ -75,7 +_,7 @@ - if (!this.moveItemStackTo(stack, 3, 4, false)) { +@@ -76,7 +_,7 @@ + if (!this.moveItemStackTo(itemstack1, 3, 4, false)) { return ItemStack.EMPTY; } -- } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(clicked)) { -+ } else if (this.slots.get(0).mayPlace(clicked)) { // Forge: Use the slot's place which goes through custom recipes. - if (!this.moveItemStackTo(stack, 0, 3, false)) { +- } 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 @@ +@@ -158,12 +_,23 @@ } public static class PotionSlot extends Slot { @@ -46,11 +46,11 @@ return mayPlaceItem(itemStack); } -@@ -175,6 +_,7 @@ +@@ -176,6 +_,7 @@ public void onTake(final Player player, final ItemStack carried) { - Optional> potion = carried.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); - if (potion.isPresent() && player instanceof ServerPlayer serverPlayer) { + Optional> optional = carried.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (optional.isPresent() && player instanceof ServerPlayer serverplayer) { + net.minecraftforge.event.ForgeEventFactory.onPlayerBrewedPotion(player, carried); - CriteriaTriggers.BREWED_POTION.trigger(serverPlayer, potion.get()); + CriteriaTriggers.BREWED_POTION.trigger(serverplayer, optional.get()); } diff --git a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch index 2f1523645e..6d9da3c3de 100644 --- a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/inventory/EnchantmentMenu.java +++ b/net/minecraft/world/inventory/EnchantmentMenu.java -@@ -61,7 +_,7 @@ - this.addSlot(new Slot(this.enchantSlots, 1, 35, 47) { +@@ -75,7 +_,7 @@ + @Override public boolean mayPlace(final ItemStack itemStack) { - return itemStack.is(Items.LAPIS_LAZULI); @@ -9,40 +9,40 @@ } @Override -@@ -89,23 +_,24 @@ - if (!itemStack.isEmpty() && itemStack.isEnchantable()) { +@@ -103,23 +_,24 @@ + if (!itemstack.isEmpty() && itemstack.isEnchantable()) { this.access.execute((level, pos) -> { - IdMap> holders = level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); -- int bookcases = 0; -+ float bookcases = 0; + IdMap> idmap = level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); +- int j = 0; ++ float j = 0; - for (BlockPos offset : EnchantingTableBlock.BOOKSHELF_OFFSETS) { - if (EnchantingTableBlock.isValidBookShelf(level, pos, offset)) { -- bookcases++; -+ bookcases += level.getBlockState(pos.offset(offset)).getEnchantPowerBonus(level, pos.offset(offset)); + for (BlockPos blockpos : EnchantingTableBlock.BOOKSHELF_OFFSETS) { + if (EnchantingTableBlock.isValidBookShelf(level, pos, blockpos)) { +- j++; ++ j += level.getBlockState(pos.offset(blockpos)).getEnchantPowerBonus(level, pos.offset(blockpos)); } } this.random.setSeed(this.enchantmentSeed.get()); - for (int ixx = 0; ixx < 3; ixx++) { -- this.costs[ixx] = EnchantmentHelper.getEnchantmentCost(this.random, ixx, bookcases, itemStack); -+ this.costs[ixx] = EnchantmentHelper.getEnchantmentCost(this.random, ixx, (int)bookcases, itemStack); - this.enchantClue[ixx] = -1; - this.levelClue[ixx] = -1; - if (this.costs[ixx] < ixx + 1) { - this.costs[ixx] = 0; + 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[ixx] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(level, pos, ixx, (int)bookcases, itemStack, costs[ixx]); ++ this.costs[k] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(level, pos, k, (int)j, itemstack, costs[k]); } - for (int ix = 0; ix < 3; ix++) { -@@ -234,7 +_,7 @@ - if (!this.moveItemStackTo(stack, 2, 38, true)) { + for (int l = 0; l < 3; l++) { +@@ -246,7 +_,7 @@ + if (!this.moveItemStackTo(itemstack1, 2, 38, true)) { return ItemStack.EMPTY; } -- } else if (stack.is(Items.LAPIS_LAZULI)) { -+ } else if (stack.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS)) { - if (!this.moveItemStackTo(stack, 1, 2, true)) { +- } 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/GrindstoneMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch index ad4727baae..6edafc7e09 100644 --- a/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/inventory/GrindstoneMenu.java +++ b/net/minecraft/world/inventory/GrindstoneMenu.java -@@ -37,6 +_,7 @@ +@@ -43,6 +_,7 @@ } }; private final ContainerLevelAccess access; @@ -8,8 +8,8 @@ public GrindstoneMenu(final int containerId, final Inventory inventory) { this(containerId, inventory, ContainerLevelAccess.NULL); -@@ -48,13 +_,13 @@ - this.addSlot(new Slot(this.repairSlots, 0, 49, 19) { +@@ -58,7 +_,7 @@ + @Override public boolean mayPlace(final ItemStack itemStack) { - return itemStack.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(itemStack); @@ -17,6 +17,8 @@ } }); this.addSlot(new Slot(this.repairSlots, 1, 49, 40) { +@@ -68,7 +_,7 @@ + @Override public boolean mayPlace(final ItemStack itemStack) { - return itemStack.isDamageableItem() || EnchantmentHelper.hasAnyEnchantments(itemStack); @@ -24,23 +26,23 @@ } }); this.addSlot(new Slot(this.resultSlots, 2, 129, 34) { -@@ -65,6 +_,7 @@ +@@ -83,6 +_,7 @@ @Override public void onTake(final Player player, final ItemStack carried) { + if (net.minecraftforge.common.ForgeHooks.onGrindstoneTake(GrindstoneMenu.this.repairSlots, access, this::getExperienceAmount)) return; access.execute((level, pos) -> { - if (level instanceof ServerLevel serverLevel) { - ExperienceOrb.award(serverLevel, Vec3.atCenterOf(pos), this.getExperienceAmount(level)); -@@ -77,6 +_,7 @@ + if (level instanceof ServerLevel) { + ExperienceOrb.award((ServerLevel)level, Vec3.atCenterOf(pos), this.getExperienceAmount(level)); +@@ -95,6 +_,7 @@ } private int getExperienceAmount(final Level level) { + if (xp > -1) return xp; - int amount = 0; - amount += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); - amount += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); -@@ -120,6 +_,17 @@ + int i = 0; + i += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); + i += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); +@@ -138,6 +_,17 @@ } private ItemStack computeResult(final ItemStack input, final ItemStack additional) { @@ -55,6 +57,6 @@ + this.xp = Integer.MIN_VALUE; + } + - boolean hasAnItem = !input.isEmpty() || !additional.isEmpty(); - if (!hasAnItem) { + boolean flag = !input.isEmpty() || !additional.isEmpty(); + if (!flag) { return ItemStack.EMPTY; diff --git a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch index 05358614f9..d3cfff9f31 100644 --- a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/inventory/ResultSlot.java +++ b/net/minecraft/world/inventory/ResultSlot.java -@@ -57,6 +_,7 @@ +@@ -51,6 +_,7 @@ protected void checkTakeAchievements(final ItemStack carried) { if (this.removeCount > 0) { carried.onCraftedBy(this.player, this.removeCount); + net.minecraftforge.event.ForgeEventFactory.firePlayerCraftingEvent(this.player, carried, this.craftSlots); } - if (this.container instanceof RecipeCraftingHolder recipeCraftingHolder) { -@@ -92,7 +_,9 @@ - CraftingInput input = positionedRecipe.input(); - int recipeLeft = positionedRecipe.left(); - int recipeTop = positionedRecipe.top(); + if (this.container instanceof RecipeCraftingHolder recipecraftingholder) { +@@ -86,7 +_,9 @@ + CraftingInput craftinginput = craftinginput$positioned.input(); + int i = craftinginput$positioned.left(); + int j = craftinginput$positioned.top(); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(player); - NonNullList remaining = this.getRemainingItems(input, player.level()); + NonNullList nonnulllist = this.getRemainingItems(craftinginput, player.level()); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null); - for (int y = 0; y < input.height(); y++) { - for (int x = 0; x < input.width(); x++) { + for (int k = 0; k < craftinginput.height(); k++) { + for (int l = 0; l < craftinginput.width(); l++) { diff --git a/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch b/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch index 1ea69e510c..ecdf530966 100644 --- a/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/Slot.java.patch @@ -9,7 +9,7 @@ } public ItemStack remove(final int amount) { -@@ -167,5 +_,36 @@ +@@ -160,5 +_,36 @@ public boolean isFake() { return false; diff --git a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch index 08f09afa2a..d0eee74502 100644 --- a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch @@ -1,41 +1,41 @@ --- a/net/minecraft/world/item/AxeItem.java +++ b/net/minecraft/world/item/AxeItem.java -@@ -65,7 +_,7 @@ +@@ -64,7 +_,7 @@ + if (playerHasBlockingItemUseIntent(context)) { return InteractionResult.PASS; - } - -- Optional newBlock = this.evaluateNewBlockState(level, pos, player, level.getBlockState(pos)); -+ Optional newBlock = this.evaluateNewBlockState(level, pos, player, level.getBlockState(pos), context); - if (newBlock.isEmpty()) { - return InteractionResult.PASS; - } + } else { +- Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); ++ Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos), context); + if (optional.isEmpty()) { + return InteractionResult.PASS; + } else { @@ -92,17 +_,24 @@ } private Optional evaluateNewBlockState(final Level level, final BlockPos pos, final @Nullable Player player, final BlockState oldState) { -- Optional strippedBlock = this.getStripped(oldState); +- Optional optional = this.getStripped(oldState); + return this.evaluateNewBlockState(level, pos, player, oldState, null); + } + + private Optional evaluateNewBlockState(final Level level, final BlockPos pos, final @Nullable Player player, final BlockState oldState, final @Nullable UseOnContext ctx) { + var strip = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_STRIP, false); -+ Optional strippedBlock = strip != null ? Optional.of(strip) : this.getStripped(oldState); - if (strippedBlock.isPresent()) { ++ Optional optional = strip != null ? Optional.of(strip) : this.getStripped(oldState); + if (optional.isPresent()) { level.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); - return strippedBlock; + return optional; } else { -- Optional scrapedBlock = WeatheringCopper.getPrevious(oldState); +- Optional optional1 = WeatheringCopper.getPrevious(oldState); + var scrape = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_STRIP, false); -+ Optional scrapedBlock = scrape != null ? Optional.of(scrape) : WeatheringCopper.getPrevious(oldState); - if (scrapedBlock.isPresent()) { ++ Optional optional1 = scrape != null ? Optional.of(scrape) : WeatheringCopper.getPrevious(oldState); + if (optional1.isPresent()) { spawnSoundAndParticle(level, pos, player, oldState, SoundEvents.AXE_SCRAPE, 3005); - return scrapedBlock; + return optional1; } else { -- Optional waxoffBlock = Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) +- Optional optional2 = Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) + var waxOff = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_WAX_OFF, false); -+ Optional waxoffBlock = waxOff != null ? Optional.of(waxOff) : Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) ++ Optional optional2 = waxOff != null ? Optional.of(waxOff) : Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) .map(b -> b.withPropertiesOf(oldState)); - if (waxoffBlock.isPresent()) { + if (optional2.isPresent()) { spawnSoundAndParticle(level, pos, player, oldState, SoundEvents.AXE_WAX_OFF, 3004); @@ -129,5 +_,16 @@ private Optional getStripped(final BlockState state) { diff --git a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch index 8a01695623..8ef00f7518 100644 --- a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch @@ -1,16 +1,21 @@ --- a/net/minecraft/world/item/BlockItem.java +++ b/net/minecraft/world/item/BlockItem.java -@@ -83,17 +_,23 @@ - } - } +@@ -76,11 +_,11 @@ + } + } -- SoundType soundType = placedState.getSoundType(); -- level.playSound(player, pos, this.getPlaceSound(placedState), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F); -+ SoundType soundType = placedState.getSoundType(level, pos, placeContext.getPlayer()); -+ level.playSound(player, pos, this.getPlaceSound(placedState, level, pos, placeContext.getPlayer()), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F); - level.gameEvent(GameEvent.BLOCK_PLACE, pos, GameEvent.Context.of(player, placedState)); - itemStack.consume(1, player); - return InteractionResult.SUCCESS; +- SoundType soundtype = blockstate1.getSoundType(); ++ SoundType soundtype = blockstate1.getSoundType(level, blockpos, placeContext.getPlayer()); + level.playSound( + player, + blockpos, +- this.getPlaceSound(blockstate1), ++ this.getPlaceSound(blockstate1, level, blockpos, placeContext.getPlayer()), + SoundSource.BLOCKS, + (soundtype.getVolume() + 1.0F) / 2.0F, + soundtype.getPitch() * 0.8F +@@ -93,10 +_,16 @@ + } } + @Deprecated //Forge: Use more sensitive version {@link BlockItem#getPlaceSound(BlockState, IBlockReader, BlockPos, Entity) } @@ -26,7 +31,7 @@ public @Nullable BlockPlaceContext updatePlacementContext(final BlockPlaceContext context) { return context; } -@@ -188,6 +_,10 @@ +@@ -191,6 +_,10 @@ public void registerBlocks(final Map map, final Item item) { map.put(this.getBlock(), item); diff --git a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch index f6bccac981..63202c15b3 100644 --- a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/item/BoneMealItem.java +++ b/net/minecraft/world/item/BoneMealItem.java -@@ -37,7 +_,7 @@ - BlockPos pos = context.getClickedPos(); - BlockPos relative = pos.relative(context.getClickedFace()); - ItemStack boneMealStack = context.getItemInHand(); -- if (growCrop(boneMealStack, level, pos)) { -+ if (applyBonemeal(boneMealStack, level, pos, context.getPlayer())) { +@@ -38,7 +_,7 @@ + BlockPos blockpos = context.getClickedPos(); + BlockPos blockpos1 = blockpos.relative(context.getClickedFace()); + ItemStack itemstack = context.getItemInHand(); +- if (growCrop(itemstack, level, blockpos)) { ++ if (applyBonemeal(itemstack, level, blockpos, context.getPlayer())) { if (!level.isClientSide()) { - boneMealStack.causeUseVibration(context.getPlayer(), GameEvent.ITEM_INTERACT_FINISH); - level.levelEvent(1505, pos, 15); -@@ -61,8 +_,18 @@ + itemstack.causeUseVibration(context.getPlayer(), GameEvent.ITEM_INTERACT_FINISH); + level.levelEvent(1505, blockpos, 15); +@@ -62,8 +_,18 @@ } } @@ -22,9 +22,9 @@ + } + + public static boolean applyBonemeal(final ItemStack itemStack, final Level level, final BlockPos pos, net.minecraft.world.entity.player.Player player) { - BlockState state = level.getBlockState(pos); -+ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, level, pos, state, itemStack); + BlockState blockstate = level.getBlockState(pos); ++ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, level, pos, blockstate, itemStack); + if (hook != 0) return hook > 0; - if (state.getBlock() instanceof BonemealableBlock block && block.isValidBonemealTarget(level, pos, state)) { - if (level instanceof ServerLevel serverLevel) { - if (block.isBonemealSuccess(level, level.getRandom(), pos, state)) { + if (blockstate.getBlock() instanceof BonemealableBlock bonemealableblock && bonemealableblock.isValidBonemealTarget(level, pos, blockstate)) { + if (level instanceof ServerLevel) { + if (bonemealableblock.isBonemealSuccess(level, level.getRandom(), pos, blockstate)) { diff --git a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch index 4e7b7d26fd..e0d7631219 100644 --- a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/item/BowItem.java +++ b/net/minecraft/world/item/BowItem.java -@@ -31,6 +_,9 @@ - } - - int timeHeld = this.getUseDuration(itemStack, entity) - remainingTime; -+ timeHeld = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(itemStack, level, player, timeHeld, true); -+ if (timeHeld < 0) return false; -+ - float pow = getPowerForTime(timeHeld); - if (pow < 0.1) { +@@ -32,6 +_,9 @@ return false; + } else { + int i = this.getUseDuration(itemStack, entity) - remainingTime; ++ i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(itemStack, level, player, i, true); ++ if (i < 0) return false; ++ + float f = getPowerForTime(i); + if (f < 0.1) { + return false; @@ -95,6 +_,8 @@ public InteractionResult use(final Level level, final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); - boolean foundProjectile = !player.getProjectile(itemStack).isEmpty(); -+ var ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemStack, level, player, hand, foundProjectile); + ItemStack itemstack = player.getItemInHand(hand); + boolean flag = !player.getProjectile(itemstack).isEmpty(); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, level, player, hand, flag); + if (ret != null) return ret; - if (!player.hasInfiniteMaterials() && !foundProjectile) { + if (!player.hasInfiniteMaterials() && !flag) { return InteractionResult.FAIL; - } + } else { diff --git a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch index b90ffe3574..3f638517e7 100644 --- a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch @@ -1,11 +1,8 @@ --- a/net/minecraft/world/item/BucketItem.java +++ b/net/minecraft/world/item/BucketItem.java -@@ -32,17 +_,31 @@ - import org.jspecify.annotations.Nullable; - +@@ -34,9 +_,21 @@ public class BucketItem extends Item implements DispensibleContainerItem { -- protected final Fluid content; -+ private final Fluid content; // Needs to be private for ASM transformer + private final Fluid content; + // Forge: Use the other constructor that takes a Supplier + @Deprecated @@ -25,35 +22,36 @@ } @Override - public InteractionResult use(final Level level, final Player player, final InteractionHand hand) { - ItemStack itemStack = player.getItemInHand(hand); - BlockHitResult hitResult = getPlayerPOVHitResult(level, player, this.getFluidContext()); -+ var ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(player, level, itemStack, hitResult); +@@ -45,6 +_,8 @@ + BlockHitResult blockhitresult = getPlayerPOVHitResult( + level, player, this.content == Fluids.EMPTY ? ClipContext.Fluid.SOURCE_ONLY : ClipContext.Fluid.NONE + ); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(player, level, itemstack, blockhitresult); + if (ret != null) return ret; - if (hitResult.getType() == HitResult.Type.MISS) { + if (blockhitresult.getType() == HitResult.Type.MISS) { return InteractionResult.PASS; - } -@@ -56,8 +_,8 @@ - BlockPos directionOffsetPos = pos.relative(direction); - if (level.mayInteract(player, pos) && player.mayUseItemAt(directionOffsetPos, direction, itemStack)) { - BlockState clicked = level.getBlockState(pos); -- BlockPos placePos = clicked.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? pos : directionOffsetPos; -- if (this.emptyContents(player, level, placePos, hitResult)) { -+ BlockPos placePos = canBlockContainFluid(level, pos, clicked) ? pos : directionOffsetPos; -+ if (this.emptyContents(player, level, placePos, hitResult, itemStack)) { - this.checkExtraContent(player, level, itemStack, placePos); - if (player instanceof ServerPlayer serverPlayer && this.content != Fluids.EMPTY) { - CriteriaTriggers.PLACED_BLOCK.trigger(serverPlayer, placePos, itemStack); -@@ -73,7 +_,7 @@ - ItemStack taken = bucketPickupBlock.pickupBlock(player, level, pos, blockState); - if (!taken.isEmpty()) { - player.awardStat(Stats.ITEM_USED.get(this)); -- bucketPickupBlock.getPickupSound().ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); -+ bucketPickupBlock.getPickupSound(blockState).ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); - level.gameEvent(player, GameEvent.FLUID_PICKUP, pos); - ItemStack result = ItemUtils.createFilledResult(itemStack, player, taken); - if (!level.isClientSide()) { -@@ -104,8 +_,13 @@ + } else if (blockhitresult.getType() != HitResult.Type.BLOCK) { +@@ -61,7 +_,7 @@ + ItemStack itemstack3 = bucketpickup.pickupBlock(player, level, blockpos, blockstate1); + if (!itemstack3.isEmpty()) { + player.awardStat(Stats.ITEM_USED.get(this)); +- bucketpickup.getPickupSound().ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); ++ bucketpickup.getPickupSound(blockstate1).ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); + level.gameEvent(player, GameEvent.FLUID_PICKUP, blockpos); + ItemStack itemstack2 = ItemUtils.createFilledResult(itemstack, player, itemstack3); + if (!level.isClientSide()) { +@@ -75,8 +_,8 @@ + return InteractionResult.FAIL; + } else { + BlockState blockstate = level.getBlockState(blockpos); +- BlockPos blockpos2 = blockstate.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? blockpos : blockpos1; +- if (this.emptyContents(player, level, blockpos2, blockhitresult)) { ++ BlockPos blockpos2 = canBlockContainFluid(level, blockpos, blockstate) ? blockpos : blockpos1; ++ if (this.emptyContents(player, level, blockpos2, blockhitresult, itemstack)) { + this.checkExtraContent(player, level, itemstack, blockpos2); + if (player instanceof ServerPlayer) { + CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayer)player, blockpos2, itemstack); +@@ -100,8 +_,13 @@ public void checkExtraContent(final @Nullable LivingEntity user, final Level level, final ItemStack itemStack, final BlockPos pos) { } @@ -63,44 +61,42 @@ + return this.emptyContents(user, level, pos, hitResult, null); + } + -+ public boolean emptyContents(final @Nullable LivingEntity user, final Level level, final BlockPos pos, final @Nullable BlockHitResult hitResult, final @Nullable ItemStack containerItem) { - if (!(this.content instanceof FlowingFluid flowingFluid)) { ++ public boolean emptyContents(final @Nullable LivingEntity user, final Level level, final BlockPos pos, final @Nullable BlockHitResult hitResult, final @Nullable ItemStack container) { + if (!(this.content instanceof FlowingFluid flowingfluid)) { return false; } else { -@@ -116,8 +_,14 @@ - boolean placeLiquid = mayReplace - || block instanceof LiquidBlockContainer container && container.canPlaceLiquid(user, level, pos, blockState, this.content); - boolean canPlaceFluidInsideBlock = blockState.isAir() || placeLiquid && (!shiftKeyDown || hitResult == null); -+ var containedFluidStack = java.util.Optional.ofNullable(containerItem).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); - if (!canPlaceFluidInsideBlock) { +@@ -113,8 +_,12 @@ + || block instanceof LiquidBlockContainer liquidblockcontainer + && liquidblockcontainer.canPlaceLiquid(user, level, pos, blockstate, this.content); + boolean flag3 = blockstate.isAir() || flag2 && (!flag1 || hitResult == null); ++ java.util.Optional containedFluidStack = java.util.Optional.ofNullable(container).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); + if (!flag3) { - return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null); -+ return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null, containerItem); -+ } -+ -+ if (containedFluidStack.isPresent() && this.content.getFluidType().isVaporizedOnPlacement(level, pos, containedFluidStack.get())) { ++ return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null, container); ++ } else if (containedFluidStack.isPresent() && this.content.getFluidType().isVaporizedOnPlacement(level, pos, containedFluidStack.get())) { + this.content.getFluidType().onVaporize(user, level, pos, containedFluidStack.get()); + return true; - } - - if (level.environmentAttributes().getValue(EnvironmentAttributes.WATER_EVAPORATES, pos) && this.content.is(FluidTags.WATER)) { -@@ -132,7 +_,7 @@ + } else if (level.environmentAttributes().getValue(EnvironmentAttributes.WATER_EVAPORATES, pos) && this.content.is(FluidTags.WATER)) { + int l = pos.getX(); + int i = pos.getY(); +@@ -131,7 +_,7 @@ } return true; -- } else if (block instanceof LiquidBlockContainer container && this.content == Fluids.WATER) { -+ } else if (block instanceof LiquidBlockContainer container && container.canPlaceLiquid(user, level, pos, blockState, content) && this.content == Fluids.WATER) { - container.placeLiquid(level, pos, blockState, flowingFluid.getSource(false)); +- } else if (block instanceof LiquidBlockContainer liquidblockcontainer1 && this.content == Fluids.WATER) { ++ } else if (block instanceof LiquidBlockContainer liquidblockcontainer1 && liquidblockcontainer1.canPlaceLiquid(user, level, pos, blockstate, content) && this.content == Fluids.WATER) { + liquidblockcontainer1.placeLiquid(level, pos, blockstate, flowingfluid.getSource(false)); this.playEmptySound(user, level, pos); return true; -@@ -153,8 +_,33 @@ +@@ -152,8 +_,33 @@ protected void playEmptySound(final @Nullable LivingEntity user, final LevelAccessor level, final BlockPos pos) { - SoundEvent soundEvent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; + SoundEvent soundevent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; + var custom = this.content.getFluidType().getSound(user, level, pos, net.minecraftforge.common.SoundActions.BUCKET_EMPTY); + if (custom != null) { -+ soundEvent = custom; ++ soundevent = custom; + } - level.playSound(user, pos, soundEvent, SoundSource.BLOCKS, 1.0F, 1.0F); + level.playSound(user, pos, soundevent, SoundSource.BLOCKS, 1.0F, 1.0F); level.gameEvent(user, GameEvent.FLUID_PLACE, pos); + } + diff --git a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch index 428c06f7a2..a47e0dc36d 100644 --- a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch +++ b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch @@ -54,11 +54,11 @@ @@ -100,7 +_,7 @@ public void buildContents(final CreativeModeTab.ItemDisplayParameters parameters) { - CreativeModeTab.ItemDisplayBuilder displayList = new CreativeModeTab.ItemDisplayBuilder(this, parameters.enabledFeatures); -- this.displayItemsGenerator.accept(parameters, displayList); -+ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, this.displayItemsGenerator, parameters, displayList); - this.displayItems = displayList.tabContents; - this.displayItemsSearchTab = displayList.searchTabContents; + CreativeModeTab.ItemDisplayBuilder creativemodetab$itemdisplaybuilder = new CreativeModeTab.ItemDisplayBuilder(this, parameters.enabledFeatures); +- this.displayItemsGenerator.accept(parameters, creativemodetab$itemdisplaybuilder); ++ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, this.displayItemsGenerator, parameters, creativemodetab$itemdisplaybuilder); + this.displayItems = creativemodetab$itemdisplaybuilder.tabContents; + this.displayItemsSearchTab = creativemodetab$itemdisplaybuilder.searchTabContents; } @@ -117,6 +_,22 @@ return this.displayItemsSearchTab.contains(stack); @@ -108,7 +108,7 @@ return this; } -@@ -175,12 +_,81 @@ +@@ -175,13 +_,80 @@ return this; } @@ -184,10 +184,11 @@ public CreativeModeTab build() { 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"); - } - -- CreativeModeTab tab = new CreativeModeTab(this.row, this.column, this.type, this.displayName, this.iconGenerator, this.displayItemsGenerator); -+ CreativeModeTab tab = this.tabFactory.apply(this); - tab.alignedRight = this.alignedRight; - tab.showTitle = this.showTitle; - tab.canScroll = this.canScroll; + } 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; diff --git a/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch b/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch index 1874ab130d..ab206d9169 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 -@@ -185,6 +_,7 @@ +@@ -177,6 +_,7 @@ final @Nullable LivingEntity targetOverride ) { - if (level instanceof ServerLevel serverLevel) { + if (level instanceof ServerLevel serverlevel) { + if (shooter instanceof Player player && net.minecraftforge.event.ForgeEventFactory.onArrowLoose(weapon, shooter.level(), player, 1, true) < 0) return; - ChargedProjectiles charged = weapon.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); - if (charged != null && !charged.isEmpty()) { - this.shoot(serverLevel, shooter, hand, weapon, charged.itemCopies(), power, uncertainty, shooter instanceof Player, targetOverride); + ChargedProjectiles chargedprojectiles = weapon.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); + if (chargedprojectiles != null && !chargedprojectiles.isEmpty()) { + this.shoot(serverlevel, shooter, hand, weapon, chargedprojectiles.itemCopies(), power, uncertainty, shooter instanceof Player, targetOverride); diff --git a/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch b/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch index b7f6c100bf..f1376f5fd9 100644 --- a/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch +++ b/patches/minecraft/net/minecraft/world/item/DyeColor.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/item/DyeColor.java +++ b/net/minecraft/world/item/DyeColor.java -@@ -60,6 +_,8 @@ +@@ -59,6 +_,8 @@ private final int textureDiffuseColor; private final int fireworkColor; private final int textColor; + private final net.minecraft.tags.TagKey dyesTag; + private final net.minecraft.tags.TagKey dyedTag; - DyeColor( - final int id, -@@ -77,6 +_,8 @@ + private DyeColor(final int id, final String name, final int textureDiffuseColor, final MapColor mapColor, final int fireworkColor, final int textColor) { + this.id = id; +@@ -67,6 +_,8 @@ this.textColor = ARGB.opaque(textColor); this.textureDiffuseColor = ARGB.opaque(textureDiffuseColor); this.fireworkColor = fireworkColor; @@ -18,7 +18,7 @@ } public int getId() { -@@ -129,6 +_,27 @@ +@@ -115,6 +_,27 @@ @Override public String getSerializedName() { return this.name; diff --git a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch index 4f670b94f4..4db27efb05 100644 --- a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch @@ -3,10 +3,10 @@ @@ -24,7 +_,11 @@ if (player.fishing != null) { if (!level.isClientSide()) { - int dmg = player.fishing.retrieve(itemStack); -+ ItemStack original = itemStack.copy(); - itemStack.hurtAndBreak(dmg, player, hand.asEquipmentSlot()); -+ if (itemStack.isEmpty()) { + int i = player.fishing.retrieve(itemstack); ++ ItemStack original = itemstack.copy(); + itemstack.hurtAndBreak(i, player, hand.asEquipmentSlot()); ++ if (itemstack.isEmpty()) { + net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, original, hand.asEquipmentSlot()); + } } diff --git a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch index 590f71809b..1c37971385 100644 --- a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch @@ -16,13 +16,13 @@ @@ -44,7 +_,8 @@ public InteractionResult useOn(final UseOnContext context) { Level level = context.getLevel(); - BlockPos pos = context.getClickedPos(); -- Pair, Consumer> logicPair = TILLABLES.get(level.getBlockState(pos).getBlock()); -+ BlockState toolModifiedState = level.getBlockState(pos).getToolModifiedState(context, net.minecraftforge.common.ToolActions.HOE_TILL, false); -+ Pair, Consumer> logicPair = toolModifiedState == null ? null : Pair.of(ctx -> true, changeIntoState(toolModifiedState)); - if (logicPair == null) { + BlockPos blockpos = context.getClickedPos(); +- Pair, Consumer> pair = TILLABLES.get(level.getBlockState(blockpos).getBlock()); ++ BlockState toolModifiedState = level.getBlockState(blockpos).getToolModifiedState(context, 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 { @@ -84,5 +_,10 @@ public static boolean onlyIfAirAbove(final UseOnContext context) { diff --git a/patches/minecraft/net/minecraft/world/item/Item.java.patch b/patches/minecraft/net/minecraft/world/item/Item.java.patch index 6643c1cfdd..4bf667d719 100644 --- a/patches/minecraft/net/minecraft/world/item/Item.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Item.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/Item.java +++ b/net/minecraft/world/item/Item.java -@@ -96,7 +_,7 @@ +@@ -95,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ public static final Codec> CODEC = BuiltInRegistries.ITEM .holderByNameCodec() .validate(item -> item.is(Items.AIR.builtInRegistryHolder()) ? DataResult.error(() -> "Item must not be minecraft:air") : DataResult.success(item)); -@@ -107,7 +_,7 @@ +@@ -106,7 +_,7 @@ : DataResult.success(item) ); private static final Logger LOGGER = LogUtils.getLogger(); @@ -18,15 +18,15 @@ public static final Identifier BASE_ATTACK_DAMAGE_ID = Identifier.withDefaultNamespace("base_attack_damage"); public static final Identifier BASE_ATTACK_SPEED_ID = Identifier.withDefaultNamespace("base_attack_speed"); public static final int DEFAULT_MAX_STACK_SIZE = 64; -@@ -146,6 +_,7 @@ - LOGGER.error("Item classes should end with Item and {} doesn't.", className); +@@ -145,6 +_,7 @@ + LOGGER.error("Item classes should end with Item and {} doesn't.", s); } } + initClient(); } @Deprecated -@@ -153,8 +_,15 @@ +@@ -152,8 +_,15 @@ return this.builtInRegistryHolder; } @@ -43,7 +43,7 @@ } public int getDefaultMaxStackSize() { -@@ -164,6 +_,7 @@ +@@ -163,6 +_,7 @@ public void onUseTick(final Level level, final LivingEntity livingEntity, final ItemStack itemStack, final int ticksRemaining) { } @@ -51,7 +51,7 @@ public void onDestroyed(final ItemEntity itemEntity) { } -@@ -282,6 +_,8 @@ +@@ -281,6 +_,8 @@ return BuiltInRegistries.ITEM.wrapAsHolder(this).getRegisteredName(); } @@ -60,7 +60,7 @@ public final @Nullable ItemStackTemplate getCraftingRemainder() { return this.craftingRemainingItem; } -@@ -374,6 +_,30 @@ +@@ -373,6 +_,30 @@ return false; } @@ -91,7 +91,7 @@ public static class Properties { private static final DependantName BLOCK_DESCRIPTION_ID = id -> Util.makeDescriptionId("block", id.identifier()); private static final DependantName ITEM_DESCRIPTION_ID = id -> Util.makeDescriptionId("item", id.identifier()); -@@ -722,6 +_,11 @@ +@@ -721,6 +_,11 @@ boolean isPeaceful(); @@ -103,7 +103,7 @@ static Item.TooltipContext of(final @Nullable Level level) { return level == null ? EMPTY : new Item.TooltipContext() { @Override -@@ -742,6 +_,11 @@ +@@ -741,6 +_,11 @@ @Override public boolean isPeaceful() { return level.getDifficulty() == Difficulty.PEACEFUL; diff --git a/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch b/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch index 1edea0db85..08d4cfa626 100644 --- a/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ItemDisplayContext.java.patch @@ -20,7 +20,7 @@ private byte id; private final String name; - ItemDisplayContext(final int id, final String name) { + private ItemDisplayContext(final int id, final String name) { this.name = name; this.id = (byte)id; + this.isModded = false; diff --git a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch index 559de64dbb..f9339ef948 100644 --- a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/ItemStack.java +++ b/net/minecraft/world/item/ItemStack.java -@@ -99,7 +_,7 @@ +@@ -102,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ private static final List OP_NBT_WARNING = List.of( Component.translatable("item.op_warning.line1").withStyle(ChatFormatting.RED, ChatFormatting.BOLD), Component.translatable("item.op_warning.line2").withStyle(ChatFormatting.RED), -@@ -257,12 +_,15 @@ +@@ -260,12 +_,15 @@ } private ItemStack(final Holder item, final int count, final PatchedDataComponentMap components) { @@ -25,7 +25,7 @@ this.item = null; this.components = new PatchedDataComponentMap(DataComponentMap.EMPTY); } -@@ -355,6 +_,15 @@ +@@ -358,13 +_,22 @@ } public InteractionResult useOn(final UseOnContext context) { @@ -39,26 +39,25 @@ + + private InteractionResult onItemUse(UseOnContext context, java.util.function.Function callback) { Player player = context.getPlayer(); - BlockPos pos = context.getClickedPos(); - if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(context.getLevel(), pos, false))) { -@@ -362,7 +_,7 @@ - } - - Item usedItem = this.getItem(); -- InteractionResult result = usedItem.useOn(context); -+ InteractionResult result = callback.apply(context); - if (player != null && result instanceof InteractionResult.Success success && success.wasItemInteraction()) { - player.awardStat(Stats.ITEM_USED.get(usedItem)); - } -@@ -442,18 +_,26 @@ + BlockPos blockpos = context.getClickedPos(); + if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(context.getLevel(), blockpos, false))) { + return InteractionResult.PASS; + } else { + Item item = this.getItem(); +- InteractionResult interactionresult = item.useOn(context); ++ InteractionResult interactionresult = callback.apply(context); + if (player != null + && interactionresult instanceof InteractionResult.Success interactionresult$success + && interactionresult$success.wasItemInteraction()) { +@@ -447,18 +_,26 @@ } public void hurtAndBreak(final int amount, final ServerLevel level, final @Nullable ServerPlayer player, final Consumer onBreak) { -- int newAmount = this.processDurabilityChange(amount, level, player); +- int i = this.processDurabilityChange(amount, level, player); + // FORGE: use context-sensitive sister of processDurabilityChange that calls IForgeItem.damageItem -+ int newAmount = this.processDurabilityChange(amount, level, player, true, onBreak); - if (newAmount != 0) { - this.applyDamage(this.getDamageValue() + newAmount, player, onBreak); ++ int i = this.processDurabilityChange(amount, level, player, true, onBreak); + if (i != 0) { + this.applyDamage(this.getDamageValue() + i, player, onBreak); } } @@ -78,15 +77,15 @@ return amount > 0 ? EnchantmentHelper.processDurabilityChange(level, this, amount) : amount; } } -@@ -490,7 +_,13 @@ - public void hurtAndBreak(final int amount, final LivingEntity owner, final EquipmentSlot slot) { - if (owner.level() instanceof ServerLevel serverLevel) { - this.hurtAndBreak( -- amount, serverLevel, owner instanceof ServerPlayer player ? player : null, brokenItem -> owner.onEquippedItemBroken(brokenItem, slot) -+ amount, serverLevel, owner instanceof ServerPlayer player ? player : null, brokenItem -> { -+ if (owner instanceof Player ownerPlayer) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(ownerPlayer, this, slot); -+ if (ownerPlayer.getUseItem() == this) ownerPlayer.stopUsingItem(); // Forge: fix MC-168573 +@@ -498,7 +_,13 @@ + amount, + serverlevel, + owner instanceof ServerPlayer serverplayer ? serverplayer : null, +- brokenItem -> owner.onEquippedItemBroken(brokenItem, slot) ++ brokenItem -> { ++ if (owner instanceof Player player) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, this, slot); ++ if (player.getUseItem() == this) player.stopUsingItem(); // Forge: fix MC-168573 + } + owner.onEquippedItemBroken(brokenItem, slot); + } @@ -94,11 +93,11 @@ } } @@ -857,6 +_,7 @@ - List lines = Lists.newArrayList(); - lines.add(this.getStyledHoverName()); - this.addDetailsToTooltip(context, display, player, tooltipFlag, lines::add); -+ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, player, lines, tooltipFlag, context, display); - return lines; + List list = Lists.newArrayList(); + list.add(this.getStyledHoverName()); + this.addDetailsToTooltip(context, tooltipdisplay, player, tooltipFlag, list::add); ++ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, player, list, tooltipFlag); + return list; } } @@ -1105,6 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/world/item/Items.java.patch b/patches/minecraft/net/minecraft/world/item/Items.java.patch index 3e3e617bf7..762c1d7b7c 100644 --- a/patches/minecraft/net/minecraft/world/item/Items.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Items.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/Items.java +++ b/net/minecraft/world/item/Items.java -@@ -2099,7 +_,25 @@ +@@ -2359,7 +_,25 @@ } - private static Item registerBlock(final BlockItemId id, final Block block, final Block... alternatives) { -- Item item = registerBlock(id, block); -+ Item item = registerBlock(id, block, (block_, prop_) -> { + private static Item registerBlock(final Block block, final Block... alternatives) { +- Item item = registerBlock(block); ++ Item item = registerBlock(block, (block_, prop_) -> { + return new BlockItem(block_, prop_) { + @Override + public void registerBlocks(java.util.Map map, Item self) { @@ -25,16 +25,16 @@ + }; + }); - for (Block alternative : alternatives) { - Item.BY_BLOCK.put(alternative, item); -@@ -2140,10 +_,6 @@ + for (Block blockx : alternatives) { + Item.BY_BLOCK.put(blockx, item); +@@ -2402,10 +_,6 @@ - private static Item registerItem(final ResourceKey id, final Function itemFactory, final Item.Properties properties) { - Item item = itemFactory.apply(properties.setId(id)); -- if (item instanceof BlockItem blockItem) { -- blockItem.registerBlocks(Item.BY_BLOCK, item); + private static Item registerItem(final ResourceKey key, final Function itemFactory, final Item.Properties properties) { + Item item = itemFactory.apply(properties.setId(key)); +- if (item instanceof BlockItem blockitem) { +- blockitem.registerBlocks(Item.BY_BLOCK, item); - } - - return Registry.register(BuiltInRegistries.ITEM, id, item); + return Registry.register(BuiltInRegistries.ITEM, key, item); } } diff --git a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch index 3201c6da54..a25f5ff592 100644 --- a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/MobBucketItem.java +++ b/net/minecraft/world/item/MobBucketItem.java -@@ -21,13 +_,18 @@ +@@ -18,13 +_,18 @@ import org.jspecify.annotations.Nullable; public class MobBucketItem extends BucketItem { @@ -24,7 +24,7 @@ } @Override -@@ -40,11 +_,11 @@ +@@ -37,11 +_,11 @@ @Override protected void playEmptySound(final @Nullable LivingEntity user, final LevelAccessor level, final BlockPos pos) { @@ -36,24 +36,19 @@ - Mob mob = this.type.create(level, EntityType.createDefaultStackConfig(level, itemStack, null), spawnPos, EntitySpawnReason.BUCKET, true, false); + Mob mob = this.getFishType().create(level, EntityType.createDefaultStackConfig(level, itemStack, null), spawnPos, EntitySpawnReason.BUCKET, true, false); if (mob instanceof Bucketable bucketable) { - CustomData entityData = itemStack.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); - bucketable.loadFromBucketTag(entityData.copyTag()); -@@ -57,9 +_,17 @@ + CustomData customdata = itemStack.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); + bucketable.loadFromBucketTag(customdata.copyTag()); +@@ -52,5 +_,13 @@ + level.addFreshEntityWithPassengers(mob); + mob.playAmbientSound(); } - } - ++ } ++ + protected EntityType getFishType() { + return entityTypeSupplier.get(); + } + + protected SoundEvent getEmptySound() { + return emptySoundSupplier.get(); -+ } -+ - @Override - public boolean emptyContents(final @Nullable LivingEntity user, final Level level, final BlockPos pos, final @Nullable BlockHitResult hitResult) { -- if (this.content == Fluids.EMPTY) { -+ if (this.getContent() == Fluids.EMPTY) { - this.playEmptySound(user, level, pos); - return true; - } else { + } + } diff --git a/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch index cc2c0b2383..c07bb2ac52 100644 --- a/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch @@ -2,28 +2,28 @@ +++ b/net/minecraft/world/item/ProjectileWeaponItem.java @@ -95,6 +_,7 @@ ) { - ArrowItem arrowItem = projectile.getItem() instanceof ArrowItem arrow ? arrow : (ArrowItem)Items.ARROW; - AbstractArrow arrow = arrowItem.createArrow(level, projectile, shooter, weapon); -+ arrow = customArrow(arrow); + ArrowItem arrowitem = projectile.getItem() instanceof ArrowItem arrowitem1 ? arrowitem1 : (ArrowItem)Items.ARROW; + AbstractArrow abstractarrow = arrowitem.createArrow(level, projectile, shooter, weapon); ++ abstractarrow = customArrow(abstractarrow); if (isCrit) { - arrow.setCritArrow(true); + abstractarrow.setCritArrow(true); } -@@ -110,9 +_,10 @@ - int numProjectiles = shooter.level() instanceof ServerLevel serverLevel ? EnchantmentHelper.processProjectileCount(serverLevel, weapon, shooter, 1) : 1; - List drawn = new ArrayList<>(numProjectiles); - ItemStack projectileCopy = projectile.copy(); -+ boolean infinite = projectile.getItem() instanceof ArrowItem arrow && arrow.isInfinite(projectile, weapon, shooter); +@@ -109,9 +_,10 @@ + int i = shooter.level() instanceof ServerLevel serverlevel ? EnchantmentHelper.processProjectileCount(serverlevel, weapon, shooter, 1) : 1; + List list = new ArrayList<>(i); + ItemStack itemstack1 = projectile.copy(); ++ boolean infinite = projectile.getItem() instanceof ArrowItem arrow && arrow.isInfinite(projectile, weapon, shooter); - for (int i = 0; i < numProjectiles; i++) { -- ItemStack drawnStack = useAmmo(weapon, i == 0 ? projectile : projectileCopy, shooter, i > 0); -+ ItemStack drawnStack = useAmmo(weapon, i == 0 ? projectile : projectileCopy, shooter, i > 0 || infinite); - if (!drawnStack.isEmpty()) { - drawn.add(drawnStack); - } -@@ -141,5 +_,9 @@ + for (int j = 0; j < i; j++) { +- ItemStack itemstack = useAmmo(weapon, j == 0 ? projectile : itemstack1, shooter, j > 0); ++ ItemStack itemstack = useAmmo(weapon, j == 0 ? projectile : itemstack1, shooter, j > 0 || infinite); + if (!itemstack.isEmpty()) { + list.add(itemstack); + } +@@ -139,5 +_,9 @@ + + return itemstack; } - - return used; + } + + public AbstractArrow customArrow(AbstractArrow arrow) { diff --git a/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch index 188a0fb9fe..b11010ee40 100644 --- a/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShearsItem.java.patch @@ -1,20 +1,31 @@ --- a/net/minecraft/world/item/ShearsItem.java +++ b/net/minecraft/world/item/ShearsItem.java -@@ -83,4 +_,23 @@ +@@ -83,4 +_,34 @@ return super.useOn(context); } } + + @Override + public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity entity, net.minecraft.world.InteractionHand hand) { -+ if (entity instanceof net.minecraft.world.entity.Shearable target) { -+ if (entity.level().isClientSide() || !target.readyForShearing()) -+ return InteractionResult.CONSUME; ++ if (entity instanceof net.minecraftforge.common.IForgeShearable target) { ++ if (entity.level().isClientSide()) { ++ return InteractionResult.SUCCESS; ++ } + var serverLevel = (net.minecraft.server.level.ServerLevel)entity.level(); -+ target.shear(serverLevel, SoundSource.PLAYERS, stack); -+ serverLevel.gameEvent(playerIn, GameEvent.SHEAR, entity.position()); -+ stack.hurtAndBreak(1, playerIn, hand.asEquipmentSlot()); -+ return InteractionResult.SUCCESS_SERVER; ++ ++ BlockPos pos = BlockPos.containing(entity.position()); ++ if (target.isShearable(stack, entity.level(), pos)) { ++ var key = net.minecraft.world.item.enchantment.Enchantments.FORTUNE; ++ var drops = target.onSheared(playerIn, stack, entity.level(), pos, net.minecraft.world.item.enchantment.EnchantmentHelper.getItemEnchantmentLevel(entity.level().holderLookup(key.registryKey()).getOrThrow(key), stack)); ++ var rand = new java.util.Random(); ++ for (var drop : drops) { ++ var ent = entity.spawnAtLocation(serverLevel, drop, 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))); ++ } ++ if (!drops.isEmpty()) ++ stack.hurtAndBreak(1, playerIn, hand.asEquipmentSlot()); ++ } ++ return InteractionResult.SUCCESS; + } + return InteractionResult.PASS; + } diff --git a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch index 8d0bc05084..faa41c8618 100644 --- a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/item/ShovelItem.java +++ b/net/minecraft/world/item/ShovelItem.java -@@ -43,9 +_,9 @@ - } - - Player player = context.getPlayer(); -- BlockState newState = FLATTENABLES.get(blockState.getBlock()); -+ BlockState newState = blockState.getToolModifiedState(context, net.minecraftforge.common.ToolActions.SHOVEL_FLATTEN, false); - BlockState updatedState = null; -- if (newState != null && level.getBlockState(pos.above()).isAir()) { -+ if (newState != null && level.isEmptyBlock(pos.above())) { - level.playSound(player, pos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); - updatedState = newState; - } else if (blockState.getBlock() instanceof CampfireBlock && blockState.getValue(CampfireBlock.LIT)) { -@@ -70,5 +_,15 @@ - } else { +@@ -42,9 +_,9 @@ return InteractionResult.PASS; + } else { + Player player = context.getPlayer(); +- BlockState blockstate1 = FLATTENABLES.get(blockstate.getBlock()); ++ BlockState blockstate1 = blockstate.getToolModifiedState(context, 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)) { +@@ -70,5 +_,15 @@ + return InteractionResult.PASS; + } } + } + 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 b6321fc02b..db618528a1 100644 --- a/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch +++ b/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch @@ -57,8 +57,8 @@ + /** @deprecated Forge: use hasMix(ItemStack, ItemStack)*/ public boolean hasPotionMix(final ItemStack source, final ItemStack ingredient) { - Optional> potion = source.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); - if (potion.isEmpty()) { + Optional> optional = source.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (optional.isEmpty()) { @@ -102,6 +_,19 @@ } @@ -78,9 +78,9 @@ + private ItemStack mixVanilla(final ItemStack ingredient, final ItemStack source) { if (source.isEmpty()) { return source; - } + } else { @@ -126,9 +_,29 @@ - return source; + } } + /** @@ -103,10 +103,10 @@ + } + public static PotionBrewing bootstrap(final FeatureFlagSet enabledFeatures) { - PotionBrewing.Builder builder = new PotionBrewing.Builder(enabledFeatures); - addVanillaMixes(builder); -+ net.minecraftforge.event.ForgeEventFactory.onBrewingRecipeRegister(builder, enabledFeatures); - return builder.build(); + PotionBrewing.Builder potionbrewing$builder = new PotionBrewing.Builder(enabledFeatures); + addVanillaMixes(potionbrewing$builder); ++ net.minecraftforge.event.ForgeEventFactory.onBrewingRecipeRegister(potionbrewing$builder, enabledFeatures); + return potionbrewing$builder.build(); } @@ -197,6 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch b/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch index 85f0f844d2..5653ab27e4 100644 --- a/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch +++ b/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch @@ -9,5 +9,5 @@ + } + public static void update(final DataComponentType component, final ItemStack itemStack, final Consumer consumer) { - CustomData newData = itemStack.getOrDefault(component, EMPTY).update(consumer); - if (newData.tag.isEmpty()) { + CustomData customdata = itemStack.getOrDefault(component, EMPTY).update(consumer); + if (customdata.tag.isEmpty()) { 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 556426ce03..738e31b1eb 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java +++ b/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java -@@ -97,7 +_,7 @@ - for (int slot = 0; slot < result.size(); slot++) { - ItemStack itemStack = input.getItem(slot); - if (!itemStack.isEmpty()) { -- ItemStackTemplate remainder = itemStack.getItem().getCraftingRemainder(); -+ ItemStackTemplate remainder = itemStack.getCraftingRemainder(); - if (remainder != null) { - result.set(slot, remainder.create()); - } else if (!itemStack.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers().isEmpty()) { +@@ -98,7 +_,7 @@ + for (int i = 0; i < nonnulllist.size(); i++) { + ItemStack itemstack = input.getItem(i); + if (!itemstack.isEmpty()) { +- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); ++ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); + if (itemstacktemplate != null) { + nonnulllist.set(i, itemstacktemplate.create()); + } else if (!itemstack.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers().isEmpty()) { 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 bb1f36ea96..2eb08ed87a 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/BookCloningRecipe.java +++ b/net/minecraft/world/item/crafting/BookCloningRecipe.java -@@ -130,7 +_,7 @@ +@@ -131,7 +_,7 @@ - for (int slot = 0; slot < result.size(); slot++) { - ItemStack itemStack = input.getItem(slot); -- ItemStackTemplate remainder = itemStack.getItem().getCraftingRemainder(); -+ ItemStackTemplate remainder = itemStack.getCraftingRemainder(); - if (remainder != null) { - result.set(slot, remainder.create()); - } else if (itemStack.has(DataComponents.WRITTEN_BOOK_CONTENT)) { + for (int i = 0; i < nonnulllist.size(); i++) { + ItemStack itemstack = input.getItem(i); +- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); ++ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); + if (itemstacktemplate != null) { + nonnulllist.set(i, itemstacktemplate.create()); + } else if (itemstack.has(DataComponents.WRITTEN_BOOK_CONTENT)) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch index 70076f9f32..6a1512f8e3 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/item/crafting/CraftingRecipe.java +++ b/net/minecraft/world/item/crafting/CraftingRecipe.java @@ -27,8 +_,7 @@ - NonNullList result = NonNullList.withSize(input.size(), ItemStack.EMPTY); + NonNullList nonnulllist = NonNullList.withSize(input.size(), ItemStack.EMPTY); - for (int slot = 0; slot < result.size(); slot++) { -- Item item = input.getItem(slot).getItem(); -- ItemStackTemplate remainder = item.getCraftingRemainder(); -+ ItemStackTemplate remainder = input.getItem(slot).getCraftingRemainder(); - result.set(slot, remainder != null ? remainder.create() : ItemStack.EMPTY); + for (int i = 0; i < nonnulllist.size(); i++) { +- Item item = input.getItem(i).getItem(); +- ItemStackTemplate itemstacktemplate = item.getCraftingRemainder(); ++ ItemStackTemplate itemstacktemplate = input.getItem(i).getCraftingRemainder(); + nonnulllist.set(i, itemstacktemplate != null ? itemstacktemplate.create() : ItemStack.EMPTY); } 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 3defabf390..413a9fab4e 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/Ingredient.java +++ b/net/minecraft/world/item/crafting/Ingredient.java -@@ -23,18 +_,26 @@ +@@ -24,18 +_,26 @@ import net.minecraft.world.level.ItemLike; public class Ingredient implements Predicate, StackedContents.IngredientInfo> { @@ -33,9 +33,9 @@ values.unwrap().ifRight(directValues -> { if (directValues.isEmpty()) { throw new UnsupportedOperationException("Ingredients can't be empty"); -@@ -113,5 +_,50 @@ +@@ -107,5 +_,50 @@ } else { - return inputDisplay; + return slotdisplay; } + } + 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 c46060b222..dfeb371ee6 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/RecipeManager.java +++ b/net/minecraft/world/item/crafting/RecipeManager.java -@@ -61,15 +_,22 @@ +@@ -63,15 +_,22 @@ private SelectableRecipe.SingleInputSet stonecutterRecipes = SelectableRecipe.SingleInputSet.empty(); private List allDisplays = List.of(); private Map>, List> recipeToDisplay = Map.of(); @@ -17,18 +17,18 @@ } protected RecipeMap prepare(final ResourceManager manager, final ProfilerFiller profiler) { - SortedMap> recipes = new TreeMap<>(); + SortedMap> sortedmap = new TreeMap<>(); SimpleJsonResourceReloadListener.scanDirectory( -- manager, RECIPE_LISTER, this.registries.createSerializationContext(JsonOps.INSTANCE), Recipe.CODEC, recipes -+ manager, RECIPE_LISTER, this.context.wrap(this.registries.createSerializationContext(JsonOps.INSTANCE)), Recipe.CODEC, recipes +- manager, RECIPE_LISTER, this.registries.createSerializationContext(JsonOps.INSTANCE), Recipe.CODEC, sortedmap ++ manager, RECIPE_LISTER, this.context.wrap(this.registries.createSerializationContext(JsonOps.INSTANCE)), Recipe.CODEC, sortedmap ); - List> recipeHolders = new ArrayList<>(recipes.size()); - recipes.forEach((id, recipe) -> { -@@ -86,6 +_,7 @@ + List> list = new ArrayList<>(sortedmap.size()); + sortedmap.forEach((id, recipe) -> { +@@ -88,6 +_,7 @@ } public void finalizeRecipeLoading(final FeatureFlagSet enabledFlags) { + //net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.registries, false, false); - List> stonecutterRecipes = new ArrayList<>(); - List propertySetCollectors = RECIPE_PROPERTY_SETS.entrySet() + List> list = new ArrayList<>(); + List list1 = RECIPE_PROPERTY_SETS.entrySet() .stream() 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 4c42452a08..44956beb32 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipe.java +++ b/net/minecraft/world/item/crafting/ShapedRecipe.java -@@ -15,7 +_,19 @@ +@@ -16,7 +_,19 @@ import net.minecraft.world.item.crafting.display.SlotDisplay; import net.minecraft.world.level.Level; @@ -21,7 +21,7 @@ public static final MapCodec MAP_CODEC = RecordCodecBuilder.mapCodec( i -> i.group( Recipe.CommonInfo.MAP_CODEC.forGetter(o -> o.commonInfo), -@@ -77,6 +_,16 @@ +@@ -78,6 +_,16 @@ public int getHeight() { return this.pattern.height(); 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 96480b3066..e0868266cd 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipePattern.java +++ b/net/minecraft/world/item/crafting/ShapedRecipePattern.java -@@ -203,10 +_,14 @@ +@@ -204,18 +_,22 @@ return this.ingredients; } @@ -14,17 +14,16 @@ - return DataResult.error(() -> "Invalid pattern: too many rows, 3 is maximum"); + if (strings.size() > ShapedRecipe.MAX_HEIGHT) { + return DataResult.error(() -> "Invalid pattern: too many rows, " + ShapedRecipe.MAX_HEIGHT + " is maximum"); - } + } else if (strings.isEmpty()) { + return DataResult.error(() -> "Invalid pattern: empty pattern not allowed"); + } else { + int i = strings.getFirst().length(); - if (strings.isEmpty()) { -@@ -216,8 +_,8 @@ - int firstLength = strings.getFirst().length(); + for (String s : strings) { +- 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"); + } - for (String line : strings) { -- if (line.length() > 3) { -- return DataResult.error(() -> "Invalid pattern: too many columns, 3 is maximum"); -+ if (line.length() > ShapedRecipe.MAX_HEIGHT) { -+ return DataResult.error(() -> "Invalid pattern: too many columns, " + ShapedRecipe.MAX_HEIGHT + " is maximum"); - } - - if (firstLength != line.length()) { + 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 84301529be..b9c2ceef46 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapelessRecipe.java +++ b/net/minecraft/world/item/crafting/ShapelessRecipe.java -@@ -20,7 +_,7 @@ +@@ -21,7 +_,7 @@ Recipe.CommonInfo.MAP_CODEC.forGetter(o -> o.commonInfo), CraftingRecipe.CraftingBookInfo.MAP_CODEC.forGetter(o -> o.bookInfo), ItemStackTemplate.CODEC.fieldOf("result").forGetter(o -> o.result), @@ -9,7 +9,7 @@ ) .apply(i, ShapelessRecipe::new) ); -@@ -38,6 +_,7 @@ +@@ -39,6 +_,7 @@ public static final RecipeSerializer SERIALIZER = new RecipeSerializer<>(MAP_CODEC, STREAM_CODEC); private final ItemStackTemplate result; private final List ingredients; @@ -17,7 +17,7 @@ public ShapelessRecipe( final Recipe.CommonInfo commonInfo, final CraftingRecipe.CraftingBookInfo bookInfo, final ItemStackTemplate result, final List ingredients -@@ -45,6 +_,7 @@ +@@ -46,6 +_,7 @@ super(commonInfo, bookInfo); this.result = result; this.ingredients = ingredients; @@ -25,7 +25,7 @@ } @Override -@@ -60,10 +_,12 @@ +@@ -61,10 +_,12 @@ public boolean matches(final CraftingInput input, final Level level) { if (input.ingredientCount() != this.ingredients.size()) { return false; 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 77af83fa5c..c6a9267b6d 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/enchantment/EnchantmentHelper.java +++ b/net/minecraft/world/item/enchantment/EnchantmentHelper.java -@@ -602,7 +_,7 @@ +@@ -612,7 +_,7 @@ public static List getAvailableEnchantmentResults(final int value, final ItemStack itemStack, final Stream> source) { - List results = Lists.newArrayList(); - boolean isBook = itemStack.is(Items.BOOK); -- source.filter(enchantment -> enchantment.value().isPrimaryItem(itemStack) || isBook).forEach(holder -> { -+ source.filter(enchantment -> itemStack.canApplyAtEnchantingTable(enchantment) || isBook).forEach(holder -> { + List list = Lists.newArrayList(); + boolean flag = itemStack.is(Items.BOOK); +- source.filter(enchantment -> enchantment.value().isPrimaryItem(itemStack) || flag).forEach(holder -> { ++ source.filter(enchantment -> itemStack.canApplyAtEnchantingTable(enchantment) || flag).forEach(holder -> { Enchantment enchantment = holder.value(); - for (int level = enchantment.getMaxLevel(); level >= enchantment.getMinLevel(); level--) { + for (int i = enchantment.getMaxLevel(); i >= enchantment.getMinLevel(); i--) { diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch index bec1e9be00..f18a22f854 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java +++ b/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java -@@ -47,6 +_,7 @@ - for (BlockPos pos : BlockPos.betweenClosed(centerBlock.offset(-dist, 0, -dist), centerBlock.offset(dist, Math.min(height - 1, 0), dist))) { - if (pos.distToCenterSqr(position.x(), pos.getY() + 0.5, position.z()) < Mth.square(dist) - && this.predicate.map(p -> p.test(serverLevel, pos)).orElse(true) -+ && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(entity, net.minecraftforge.common.util.BlockSnapshot.create(serverLevel.dimension(), serverLevel, centerBlock), net.minecraft.core.Direction.UP) - && serverLevel.setBlockAndUpdate(pos, this.blockState.getState(serverLevel, random, pos))) { - this.triggerGameEvent.ifPresent(event -> serverLevel.gameEvent(entity, (Holder)event, pos)); +@@ -48,6 +_,7 @@ + for (BlockPos blockpos1 : BlockPos.betweenClosed(blockpos.offset(-i, 0, -i), blockpos.offset(i, Math.min(j - 1, 0), i))) { + if (blockpos1.distToCenterSqr(position.x(), blockpos1.getY() + 0.5, position.z()) < Mth.square(i) + && this.predicate.map(p -> p.test(serverLevel, blockpos1)).orElse(true) ++ && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(entity, net.minecraftforge.common.util.BlockSnapshot.create(serverLevel.dimension(), serverLevel, blockpos), net.minecraft.core.Direction.UP) + && serverLevel.setBlockAndUpdate(blockpos1, this.blockState.getState(serverLevel, randomsource, blockpos1))) { + this.triggerGameEvent.ifPresent(event -> serverLevel.gameEvent(entity, (Holder)event, blockpos1)); } diff --git a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch index 29f5661043..ddb16b6f1e 100644 --- a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch @@ -1,27 +1,26 @@ --- a/net/minecraft/world/level/BaseSpawner.java +++ b/net/minecraft/world/level/BaseSpawner.java -@@ -152,15 +_,16 @@ +@@ -146,14 +_,15 @@ - entity.snapTo(entity.getX(), entity.getY(), entity.getZ(), random.nextFloat() * 360.0F, 0.0F); + entity.snapTo(entity.getX(), entity.getY(), entity.getZ(), randomsource.nextFloat() * 360.0F, 0.0F); if (entity instanceof Mob mob) { -- if (nextSpawnData.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(level, EntitySpawnReason.SPAWNER) +- if (spawndata.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(level, EntitySpawnReason.SPAWNER) - || !mob.checkSpawnObstruction(level)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, level, EntitySpawnReason.SPAWNER, nextSpawnData, this)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, level, EntitySpawnReason.SPAWNER, spawndata, this)) { continue; } - boolean hasNoConfiguration = nextSpawnData.getEntityToSpawn().size() == 1 - && nextSpawnData.getEntityToSpawn().getString("id").isPresent(); -- if (hasNoConfiguration) { + boolean flag1 = spawndata.getEntityToSpawn().size() == 1 && spawndata.getEntityToSpawn().getString("id").isPresent(); +- if (flag1) { - ((Mob)entity).finalizeSpawn(level, level.getCurrentDifficultyAt(entity.blockPosition()), EntitySpawnReason.SPAWNER, 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, level, level.getCurrentDifficultyAt(entity.blockPosition()), null, input, this); -+ if (event != null && hasNoConfiguration) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onFinalizeSpawnSpawner(mob, level, level.getCurrentDifficultyAt(entity.blockPosition()), null, valueinput, this); ++ if (event != null && flag1) { + mob.finalizeSpawn(level, event.getDifficulty(), EntitySpawnReason.SPAWNER, null); } - nextSpawnData.getEquipment().ifPresent(mob::equip); -@@ -279,5 +_,14 @@ + spawndata.getEquipment().ifPresent(mob::equip); +@@ -270,5 +_,14 @@ public double getOSpin() { return this.oSpin; diff --git a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch index cd03031fdc..270fd943b1 100644 --- a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch +++ b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/DataPackConfig.java +++ b/net/minecraft/world/level/DataPackConfig.java -@@ -15,7 +_,7 @@ +@@ -16,7 +_,7 @@ private final List disabled; public DataPackConfig(final List enabled, final List disabled) { @@ -9,7 +9,7 @@ this.disabled = ImmutableList.copyOf(disabled); } -@@ -25,5 +_,9 @@ +@@ -26,5 +_,9 @@ public List getDisabled() { return this.disabled; diff --git a/patches/minecraft/net/minecraft/world/level/Level.java.patch b/patches/minecraft/net/minecraft/world/level/Level.java.patch index c0ee39b1c6..86cf72c35b 100644 --- a/patches/minecraft/net/minecraft/world/level/Level.java.patch +++ b/patches/minecraft/net/minecraft/world/level/Level.java.patch @@ -9,7 +9,7 @@ public static final Codec> RESOURCE_KEY_CODEC = ResourceKey.codec(Registries.DIMENSION); public static final ResourceKey OVERWORLD = ResourceKey.create(Registries.DIMENSION, Identifier.withDefaultNamespace("overworld")); public static final ResourceKey NETHER = ResourceKey.create(Registries.DIMENSION, Identifier.withDefaultNamespace("the_nether")); -@@ -131,6 +_,11 @@ +@@ -130,6 +_,11 @@ private final DamageSources damageSources; private final PalettedContainerFactory palettedContainerFactory; private long subTickCount; @@ -21,60 +21,63 @@ protected Level( final WritableLevelData levelData, -@@ -219,7 +_,7 @@ +@@ -214,7 +_,7 @@ } @Override -- public boolean setBlock(final BlockPos pos, final BlockState blockState, final @Block.UpdateFlags int updateFlags, final int updateLimit) { +- public boolean setBlock(final BlockPos pos, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { + public boolean setBlock(BlockPos pos, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { if (!this.isInValidBounds(pos)) { return false; - } -@@ -230,12 +_,31 @@ - - LevelChunk chunk = this.getChunkAt(pos); - Block block = blockState.getBlock(); + } else if (!this.isClientSide() && this.isDebug()) { +@@ -222,11 +_,35 @@ + } else { + LevelChunk levelchunk = this.getChunkAt(pos); + Block block = blockState.getBlock(); + -+ pos = pos.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, pos, updateFlags); -+ this.capturedBlockSnapshots.add(blockSnapshot); ++ pos = pos.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, pos, updateFlags); ++ this.capturedBlockSnapshots.add(blockSnapshot); ++ } ++ + BlockState blockstate = levelchunk.setBlockState(pos, blockState, updateFlags); + if (blockstate == null) { ++ if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); + return false; + } else { + BlockState blockstate1 = this.getBlockState(pos); ++ if (blockSnapshot == null) { // Don't notify clients or update physics while capturing blockstates ++ this.markAndNotifyBlock(pos, levelchunk, blockstate, blockState, updateFlags, updateLimit); ++ } ++ ++ return true; ++ } + } -+ - BlockState oldState = chunk.setBlockState(pos, blockState, updateFlags); - if (oldState == null) { -+ if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); - return false; - } - -- BlockState newState = this.getBlockState(pos); -+ if (blockSnapshot == null) { // Don't notify clients or update physics while capturing blockstates -+ this.markAndNotifyBlock(pos, chunk, oldState, blockState, updateFlags, updateLimit); -+ } -+ -+ return true; + } + + // Split off from original setBlockState(BlockPos, BlockState, int, int) method in order to directly send client and physic updates -+ public void markAndNotifyBlock(final BlockPos pos, final @Nullable LevelChunk chunk, final BlockState oldState, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { ++ public void markAndNotifyBlock(final BlockPos pos, final @Nullable LevelChunk levelchunk, final BlockState blockstate, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { + Block block = blockState.getBlock(); -+ BlockState newState = getBlockState(pos); - if (newState == blockState) { - if (oldState != newState) { - this.setBlocksDirty(pos, oldState, newState); -@@ -262,9 +_,8 @@ - } ++ BlockState blockstate1 = getBlockState(pos); ++ { ++ { + if (blockstate1 == blockState) { + if (blockstate != blockstate1) { + this.setBlocksDirty(pos, blockstate, blockstate1); +@@ -253,9 +_,8 @@ + } - this.updatePOIOnBlockStateChange(pos, oldState, newState); -+ blockState.onBlockStateChange(this, pos, oldState); - } + this.updatePOIOnBlockStateChange(pos, blockstate, blockstate1); ++ blockState.onBlockStateChange(this, pos, blockstate); + } - -- return true; +- return true; + } + } } - - public void updatePOIOnBlockStateChange(final BlockPos pos, final BlockState oldState, final BlockState newState) { -@@ -531,8 +_,27 @@ +@@ -524,8 +_,27 @@ (this.tickingBlockEntities ? this.pendingBlockEntityTickers : this.blockEntityTickers).add(ticker); } @@ -102,27 +105,27 @@ if (!this.pendingBlockEntityTickers.isEmpty()) { this.blockEntityTickers.addAll(this.pendingBlockEntityTickers); this.pendingBlockEntityTickers.clear(); -@@ -555,12 +_,19 @@ +@@ -548,12 +_,19 @@ public void guardEntityTick(final Consumer tick, final T entity) { try { + net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackStart(entity); tick.accept(entity); - } catch (Throwable t) { - CrashReport report = CrashReport.forThrowable(t, "Ticking entity"); - CrashReportCategory category = report.addCategory("Entity being ticked"); - entity.fillCrashReportCategory(category); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking entity"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Entity being ticked"); + entity.fillCrashReportCategory(crashreportcategory); + if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringEntities.get()) { -+ com.mojang.logging.LogUtils.getLogger().error("{}", report.getFriendlyReport(net.minecraft.ReportType.CRASH)); ++ com.mojang.logging.LogUtils.getLogger().error("{}", crashreport.getFriendlyReport(net.minecraft.ReportType.CRASH)); + entity.discard(); + } else - throw new ReportedException(report); + throw new ReportedException(crashreport); + } finally { + net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackEnd(entity); } } -@@ -716,6 +_,7 @@ +@@ -709,6 +_,7 @@ if (this.isInValidBounds(pos)) { this.getChunkAt(pos).removeBlockEntity(pos); } @@ -130,52 +133,53 @@ } public boolean isLoaded(final BlockPos pos) { -@@ -781,8 +_,8 @@ +@@ -776,9 +_,9 @@ } }); -- for (EnderDragonPart dragonPart : this.dragonParts()) { -- if (dragonPart != except && dragonPart.parentMob != except && selector.test(dragonPart) && bb.intersects(dragonPart.getBoundingBox())) { -+ for (var dragonPart : this.getPartEntities()) { -+ if (dragonPart != except && dragonPart.getParent() != except && selector.test(dragonPart) && bb.intersects(dragonPart.getBoundingBox())) { - output.add(dragonPart); - } - } -@@ -815,8 +_,8 @@ +- for (EnderDragonPart enderdragonpart : this.dragonParts()) { ++ for (var enderdragonpart : this.getPartEntities()) { + if (enderdragonpart != except +- && enderdragonpart.parentMob != except ++ && enderdragonpart.getParent() != except + && selector.test(enderdragonpart) + && bb.intersects(enderdragonpart.getBoundingBox())) { + list.add(enderdragonpart); +@@ -813,8 +_,8 @@ } } -- if (e instanceof EnderDragon enderDragon) { -- for (EnderDragonPart subEntity : enderDragon.getSubEntities()) { +- if (e instanceof EnderDragon enderdragon) { +- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { + if (e.isMultipartEntity()) { -+ for (var subEntity : e.getParts()) { - T castSubPart = type.tryCast(subEntity); - if (castSubPart != null && selector.test(castSubPart)) { - output.add(castSubPart); -@@ -1004,17 +_,16 @@ ++ for (var enderdragonpart : e.getParts()) { + T t = type.tryCast(enderdragonpart); + if (t != null && selector.test(t)) { + output.add(t); +@@ -1000,17 +_,16 @@ public abstract Scoreboard getScoreboard(); public void updateNeighbourForOutputSignal(final BlockPos pos, final Block changedBlock) { - for (Direction direction : Direction.Plane.HORIZONTAL) { + for (Direction direction : Direction.getUpdateOrder()) { - BlockPos relativePos = pos.relative(direction); - if (this.hasChunkAt(relativePos)) { - BlockState state = this.getBlockState(relativePos); -- if (state.is(Blocks.COMPARATOR)) { -- this.neighborChanged(state, relativePos, changedBlock, null, false); -- } else if (state.isRedstoneConductor(this, relativePos)) { -+ state.onNeighborChange(this, relativePos, pos); -+ if (state.isRedstoneConductor(this, relativePos)) { - relativePos = relativePos.relative(direction); - state = this.getBlockState(relativePos); -- if (state.is(Blocks.COMPARATOR)) { -- this.neighborChanged(state, relativePos, changedBlock, null, false); -+ if (state.getWeakChanges(this, relativePos)) { -+ state.onNeighborChange(this, relativePos, pos); + BlockPos blockpos = pos.relative(direction); + if (this.hasChunkAt(blockpos)) { + BlockState blockstate = this.getBlockState(blockpos); +- if (blockstate.is(Blocks.COMPARATOR)) { +- this.neighborChanged(blockstate, blockpos, changedBlock, null, false); +- } else if (blockstate.isRedstoneConductor(this, blockpos)) { ++ blockstate.onNeighborChange(this, blockpos, pos); ++ if (blockstate.isRedstoneConductor(this, blockpos)) { + blockpos = blockpos.relative(direction); + blockstate = this.getBlockState(blockpos); +- if (blockstate.is(Blocks.COMPARATOR)) { +- this.neighborChanged(blockstate, blockpos, changedBlock, null, false); ++ if (blockstate.getWeakChanges(this, blockpos)) { ++ blockstate.onNeighborChange(this, blockpos, pos); } } } -@@ -1099,6 +_,20 @@ +@@ -1095,6 +_,20 @@ } public abstract ClockManager clockManager(); diff --git a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch index c06f4d8b78..0b313df067 100644 --- a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/LevelSettings.java +++ b/net/minecraft/world/level/LevelSettings.java -@@ -6,8 +_,12 @@ +@@ -7,8 +_,12 @@ import net.minecraft.world.Difficulty; public record LevelSettings( @@ -12,12 +12,12 @@ + } + public static LevelSettings parse(final Dynamic input, final WorldDataConfiguration loadConfig) { - GameType gameType = GameType.byId(input.get("GameType").asInt(0)); + GameType gametype = GameType.byId(input.get("GameType").asInt(0)); return new LevelSettings( -@@ -15,12 +_,13 @@ - gameType, +@@ -16,12 +_,13 @@ + gametype, input.get("difficulty_settings").read(LevelSettings.DifficultySettings.CODEC).result().orElse(LevelSettings.DifficultySettings.DEFAULT), - input.get("allowCommands").asBoolean(gameType == GameType.CREATIVE), + input.get("allowCommands").asBoolean(gametype == GameType.CREATIVE), - loadConfig + loadConfig, + net.minecraftforge.common.ForgeHooks.parseLifecycle(input.get("forgeLifecycle").asString("stable")) @@ -29,8 +29,8 @@ + return new LevelSettings(this.levelName, gameType, this.difficultySettings, this.allowCommands, this.dataConfiguration, this.lifecycle); } - public LevelSettings withAllowCommands(final boolean allowCommands) { -@@ -33,7 +_,8 @@ + public LevelSettings withDifficulty(final Difficulty difficulty) { +@@ -30,7 +_,8 @@ this.gameType, new LevelSettings.DifficultySettings(difficulty, this.difficultySettings.hardcore(), this.difficultySettings.locked()), this.allowCommands, @@ -40,7 +40,7 @@ ); } -@@ -43,16 +_,21 @@ +@@ -40,16 +_,21 @@ this.gameType, new LevelSettings.DifficultySettings(this.difficultySettings.difficulty(), this.difficultySettings.hardcore(), locked), this.allowCommands, diff --git a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch index 42d63762ca..afe44eabfc 100644 --- a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch @@ -4,21 +4,21 @@ for (Entity entity : entities) { if (!(entity instanceof Mob mob && (mob.isPersistenceRequired() || mob.requiresCustomPersistence()))) { -- MobCategory category = entity.getType().getCategory(); -+ MobCategory category = entity.getClassification(true); - if (category != MobCategory.MISC) { - BlockPos pos = entity.blockPosition(); - chunkGetter.query(ChunkPos.pack(pos), chunk -> { -@@ -211,7 +_,7 @@ - groupSize++; +- MobCategory mobcategory = entity.getType().getCategory(); ++ MobCategory mobcategory = entity.getClassification(true); + if (mobcategory != MobCategory.MISC) { + BlockPos blockpos = entity.blockPosition(); + chunkGetter.query( +@@ -222,7 +_,7 @@ + l1++; level.addFreshEntityWithPassengers(mob); spawnCallback.run(mob, chunk); -- if (clusterSize >= mob.getMaxSpawnClusterSize()) { -+ if (clusterSize >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { +- if (j >= mob.getMaxSpawnClusterSize()) { ++ if (j >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { return; } -@@ -288,7 +_,7 @@ +@@ -299,7 +_,7 @@ return nearestPlayerDistanceSqr > mob.getType().getCategory().getDespawnDistance() * mob.getType().getCategory().getDespawnDistance() && mob.removeWhenFarAway(nearestPlayerDistanceSqr) ? false @@ -27,7 +27,7 @@ } private static Optional getRandomSpawnMobAt( -@@ -324,9 +_,11 @@ +@@ -335,9 +_,11 @@ final BlockPos pos, final @Nullable Holder biome ) { @@ -42,22 +42,22 @@ } public static boolean isInNetherFortressBounds( -@@ -417,8 +_,7 @@ +@@ -430,8 +_,7 @@ - entity.snapTo(fx, pos.getY(), fz, random.nextFloat() * 360.0F, 0.0F); + entity.snapTo(d0, blockpos.getY(), d1, random.nextFloat() * 360.0F, 0.0F); if (entity instanceof Mob mob - && mob.checkSpawnRules(level, EntitySpawnReason.CHUNK_GENERATION) - && mob.checkSpawnObstruction(level)) { + && net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, level, EntitySpawnReason.CHUNK_GENERATION)) { - groupSpawnData = mob.finalizeSpawn( - level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.CHUNK_GENERATION, groupSpawnData + spawngroupdata = mob.finalizeSpawn( + level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.CHUNK_GENERATION, spawngroupdata ); -@@ -527,7 +_,7 @@ +@@ -542,7 +_,7 @@ } - this.spawnPotential.addCharge(pos, charge); -- MobCategory category = type.getCategory(); -+ MobCategory category = mob.getClassification(true); - this.mobCategoryCounts.addTo(category, 1); - this.localMobCapCalculator.addMob(ChunkPos.containing(pos), category); + this.spawnPotential.addCharge(blockpos, d0); +- MobCategory mobcategory = entitytype.getCategory(); ++ MobCategory mobcategory = mob.getClassification(true); + this.mobCategoryCounts.addTo(mobcategory, 1); + this.localMobCapCalculator.addMob(ChunkPos.containing(blockpos), mobcategory); } diff --git a/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch b/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch index 57726cd98d..a26d1b7f6a 100644 --- a/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch +++ b/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/world/level/ServerExplosion.java +++ b/net/minecraft/world/level/ServerExplosion.java -@@ -169,7 +_,7 @@ - return new ObjectArrayList<>(toBlowSet); +@@ -167,7 +_,7 @@ + return new ObjectArrayList<>(set); } - private void hurtEntities() { + private void hurtEntities(List blocks) { if (!(this.radius < 1.0E-5F)) { - float doubleRadius = this.radius * 2.0F; - int x0 = Mth.floor(this.center.x - doubleRadius - 1.0); -@@ -179,7 +_,9 @@ - int z0 = Mth.floor(this.center.z - doubleRadius - 1.0); - int z1 = Mth.floor(this.center.z + doubleRadius + 1.0); + float f = this.radius * 2.0F; + int i = Mth.floor(this.center.x - f - 1.0); +@@ -177,7 +_,9 @@ + int i1 = Mth.floor(this.center.z - f - 1.0); + int j1 = Mth.floor(this.center.z + f + 1.0); -- for (Entity entity : this.level.getEntities(this.source, new AABB(x0, y0, z0, x1, y1, z1))) { -+ var entities = this.level.getEntities(this.source, new AABB(x0, y0, z0, x1, y1, z1)); -+ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, blocks, entities, doubleRadius); +- for (Entity entity : this.level.getEntities(this.source, new AABB(i, k, i1, j, l, j1))) { ++ var entities = this.level.getEntities(this.source, new AABB(i, k, i1, j, l, j1)); ++ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, blocks, entities, f); + for (Entity entity : entities) { if (!entity.ignoreExplosion(this)) { - double dist = Math.sqrt(entity.distanceToSqr(this.center)) / doubleRadius; - if (!(dist > 1.0)) { -@@ -235,7 +_,7 @@ + double d0 = Math.sqrt(entity.distanceToSqr(this.center)) / f; + if (!(d0 > 1.0)) { +@@ -233,7 +_,7 @@ public int explode() { this.level.gameEvent(this.source, GameEvent.EXPLODE, this.center); - List toBlow = this.calculateExplodedPositions(); + List list = this.calculateExplodedPositions(); - this.hurtEntities(); -+ this.hurtEntities(toBlow); ++ this.hurtEntities(list); if (this.interactsWithBlocks()) { - ProfilerFiller profiler = Profiler.get(); - profiler.push("explosion_blocks"); + ProfilerFiller profilerfiller = Profiler.get(); + profilerfiller.push("explosion_blocks"); diff --git a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch index 8e06992beb..4e4b9d6ea4 100644 --- a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch +++ b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/level/SignalGetter.java @@ -65,7 +_,7 @@ default int getSignal(final BlockPos pos, final Direction direction) { - BlockState state = this.getBlockState(pos); - int signal = state.getSignal(this, pos, direction); -- return state.isRedstoneConductor(this, pos) ? Math.max(signal, this.getDirectSignalTo(pos)) : signal; -+ return state.shouldCheckWeakPower(this, pos, direction) ? Math.max(signal, this.getDirectSignalTo(pos)) : signal; + BlockState blockstate = this.getBlockState(pos); + int i = blockstate.getSignal(this, pos, direction); +- return blockstate.isRedstoneConductor(this, pos) ? Math.max(i, this.getDirectSignalTo(pos)) : i; ++ return blockstate.shouldCheckWeakPower(this, pos, direction) ? Math.max(i, this.getDirectSignalTo(pos)) : i; } - default int getBestOwnOrNeighbourSignal(final BlockPos pos) { + default boolean hasNeighborSignal(final BlockPos blockPos) { 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 f847507ef4..e78aab7828 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/Biome.java +++ b/net/minecraft/world/level/biome/Biome.java -@@ -35,9 +_,9 @@ +@@ -37,9 +_,9 @@ public final class Biome { public static final Codec DIRECT_CODEC = RecordCodecBuilder.create( i -> i.group( @@ -12,7 +12,7 @@ BiomeGenerationSettings.CODEC.forGetter(b -> b.generationSettings), MobSpawnSettings.CODEC.forGetter(b -> b.mobSettings) ) -@@ -65,8 +_,10 @@ +@@ -67,8 +_,10 @@ @Deprecated(forRemoval = true) public static final PerlinSimplexNoise BIOME_INFO_NOISE = new PerlinSimplexNoise(new WorldgenRandom(new LegacyRandomSource(2345L)), ImmutableList.of(0)); private static final int TEMPERATURE_CACHE_SIZE = 1024; @@ -23,15 +23,15 @@ private final MobSpawnSettings mobSettings; private final EnvironmentAttributeMap attributes; private final BiomeSpecialEffects specialEffects; -@@ -79,6 +_,7 @@ - map.defaultReturnValue(Float.NaN); - return map; +@@ -85,6 +_,7 @@ + long2floatlinkedopenhashmap.defaultReturnValue(Float.NaN); + return long2floatlinkedopenhashmap; }); + private final net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo; private Biome( final Biome.ClimateSettings climateSettings, -@@ -92,10 +_,11 @@ +@@ -98,10 +_,11 @@ this.mobSettings = mobSettings; this.attributes = attributes; this.specialEffects = specialEffects; @@ -44,7 +44,7 @@ } public boolean hasPrecipitation() { -@@ -197,7 +_,7 @@ +@@ -200,7 +_,7 @@ } public BiomeGenerationSettings getGenerationSettings() { @@ -53,7 +53,7 @@ } public int getGrassColor(final double x, final double z) { -@@ -250,6 +_,31 @@ +@@ -253,6 +_,31 @@ public int getWaterColor() { return this.specialEffects.waterColor(); 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 32e97a6bf5..ecb47140dd 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/BiomeGenerationSettings.java +++ b/net/minecraft/world/level/biome/BiomeGenerationSettings.java -@@ -92,6 +_,17 @@ +@@ -93,6 +_,17 @@ protected final List>> carvers = new ArrayList<>(); protected final List>> features = new ArrayList<>(); @@ -18,7 +18,7 @@ public BiomeGenerationSettings.PlainBuilder addFeature(final GenerationStep.Decoration step, final Holder feature) { return this.addFeature(step.ordinal(), feature); } -@@ -100,6 +_,11 @@ +@@ -101,6 +_,11 @@ this.addFeatureStepsUpTo(index); this.features.get(index).add(feature); return this; 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 5e4c8d0438..2823eb2266 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/BiomeSpecialEffects.java +++ b/net/minecraft/world/level/biome/BiomeSpecialEffects.java -@@ -28,6 +_,10 @@ +@@ -29,6 +_,10 @@ .apply(i, BiomeSpecialEffects::new) ); @@ -11,7 +11,7 @@ public static class Builder { protected OptionalInt waterColor = OptionalInt.empty(); protected Optional foliageColorOverride = Optional.empty(); -@@ -35,6 +_,10 @@ +@@ -36,6 +_,10 @@ protected Optional grassColorOverride = Optional.empty(); protected BiomeSpecialEffects.GrassColorModifier grassColorModifier = BiomeSpecialEffects.GrassColorModifier.NONE; @@ -22,16 +22,16 @@ public BiomeSpecialEffects.Builder waterColor(final int waterColor) { this.waterColor = OptionalInt.of(waterColor); return this; -@@ -71,7 +_,7 @@ +@@ -72,7 +_,7 @@ } } -- public enum GrassColorModifier implements StringRepresentable { +- public static enum GrassColorModifier implements StringRepresentable { + public static enum GrassColorModifier implements StringRepresentable, net.minecraftforge.common.IExtensibleEnum { NONE("none") { @Override public int modifyColor(final double x, final double z, final int baseColor) { -@@ -93,9 +_,16 @@ +@@ -94,9 +_,16 @@ }; private final String name; @@ -48,9 +48,9 @@ + return delegate.modifyGrassColor(x, z, baseColor); + } - GrassColorModifier(final String name) { + private GrassColorModifier(final String name) { this.name = name; -@@ -108,6 +_,30 @@ +@@ -109,6 +_,30 @@ @Override public String getSerializedName() { return this.name; diff --git a/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch index a8c65d1e04..63995d9cd6 100644 --- a/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/AttachedStemBlock.java +++ b/net/minecraft/world/level/block/AttachedStemBlock.java -@@ -90,7 +_,7 @@ +@@ -91,7 +_,7 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { 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 ee5352661c..3332f9b5ed 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch @@ -16,18 +16,18 @@ - if (random.nextInt(3) == 0 && level.isEmptyBlock(pos.above()) && level.getRawBrightness(pos.above(), 0) >= 9) { + boolean vanilla = random.nextInt(3) == 0; + if (level.isEmptyBlock(pos.above()) && level.getRawBrightness(pos.above(), 0) >= 9) { - int height = this.getHeightBelowUpToMax(level, pos) + 1; -- if (height < 16) { -+ if (height < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { - this.growBamboo(state, level, pos, random, height); + int i = this.getHeightBelowUpToMax(level, pos) + 1; +- if (i < 16) { ++ if (i < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { + this.growBamboo(state, level, pos, random, i); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } } -@@ -230,5 +_,11 @@ +@@ -227,5 +_,11 @@ } - return height; + return i; + } + + @Override 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 a3f3d83125..db922be865 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch @@ -3,17 +3,17 @@ @@ -161,6 +_,7 @@ if (!oldState.is(state.getBlock())) { if (inPortalDimension(level)) { - Optional optionalShape = PortalShape.findEmptyPortalShape(level, pos, Direction.Axis.X); -+ optionalShape = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(level, pos, optionalShape); - if (optionalShape.isPresent()) { - optionalShape.get().createPortalBlocks(level); + Optional optional = PortalShape.findEmptyPortalShape(level, pos, Direction.Axis.X); ++ optional = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(level, pos, optional); + if (optional.isPresent()) { + optional.get().createPortalBlocks(level); return; -@@ -204,7 +_,7 @@ - boolean hasObsidian = false; +@@ -203,7 +_,7 @@ + boolean flag = false; - for (Direction face : Direction.values()) { -- if (level.getBlockState(testPos.set(pos).move(face)).is(Blocks.OBSIDIAN)) { -+ if (level.getBlockState(testPos.set(pos).move(face)).isPortalFrame(level, testPos)) { - hasObsidian = true; - break; - } + for (Direction direction : Direction.values()) { +- if (level.getBlockState(blockpos$mutableblockpos.set(pos).move(direction)).is(Blocks.OBSIDIAN)) { ++ if (level.getBlockState(blockpos$mutableblockpos.set(pos).move(direction)).isPortalFrame(level, 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 9ccda93a2a..d43f09eb68 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch @@ -13,12 +13,12 @@ final BlockState state, final Level level, final BlockPos pos, final Block block, final @Nullable Orientation orientation, final boolean movedByPiston ) { if (!level.isClientSide() && level.getBlockState(pos).is(this)) { -- RailShape shape = state.getValue(this.getShapeProperty()); -+ RailShape shape = getRailDirection(state, level, pos, null); - if (shouldBeRemoved(pos, level, shape)) { +- RailShape railshape = state.getValue(this.getShapeProperty()); ++ RailShape railshape = getRailDirection(state, level, pos, null); + if (shouldBeRemoved(pos, level, railshape)) { dropResources(state, level, pos); level.removeBlock(pos, movedByPiston); -@@ -120,7 +_,7 @@ +@@ -125,7 +_,7 @@ @Override protected void affectNeighborsAfterRemoval(final BlockState state, final ServerLevel level, final BlockPos pos, final boolean movedByPiston) { if (!movedByPiston) { @@ -27,8 +27,8 @@ level.updateNeighborsAt(pos.above(), this); } -@@ -141,6 +_,11 @@ - return state.setValue(this.getShapeProperty(), isEastWest ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, isWaterSource); +@@ -146,6 +_,11 @@ + return blockstate.setValue(this.getShapeProperty(), flag1 ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, flag); } + /** @@ -39,7 +39,7 @@ public abstract Property getShapeProperty(); protected RailShape rotate(final RailShape shape, final Rotation rotation) { -@@ -296,5 +_,15 @@ +@@ -301,5 +_,15 @@ @Override protected FluidState getFluidState(final BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); 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 887e3eeda0..1d595e181a 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 -@@ -161,7 +_,7 @@ - boolean hiveEmptied = false; - if (honeyLevel >= 5) { +@@ -160,7 +_,7 @@ + boolean flag = false; + if (i >= 5) { Item item = itemStack.getItem(); -- if (level instanceof ServerLevel serverLevel && itemStack.is(Items.SHEARS)) { -+ if (level instanceof ServerLevel serverLevel && itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - dropHoneycomb(serverLevel, itemStack, state, level.getBlockEntity(pos), player, pos); +- if (level instanceof ServerLevel serverlevel && itemStack.is(Items.SHEARS)) { ++ if (level instanceof ServerLevel serverlevel && itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { + dropHoneycomb(serverlevel, itemStack, state, level.getBlockEntity(pos), player, pos); level.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.BEEHIVE_SHEAR, SoundSource.BLOCKS, 1.0F, 1.0F); itemStack.hurtAndBreak(1, player, hand.asEquipmentSlot()); 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 c58c556221..70dbd9ad41 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Block.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Block.java.patch @@ -15,15 +15,15 @@ private static final LoadingCache SHAPE_FULL_BLOCK_CACHE = CacheBuilder.newBuilder() .maximumSize(512L) .weakKeys() -@@ -247,6 +_,7 @@ - LOGGER.error("Block classes should end with Block and {} doesn't.", className); +@@ -253,6 +_,7 @@ + LOGGER.error("Block classes should end with Block and {} doesn't.", s); } } + initClient(); } public static boolean isExceptionForConnection(final BlockState state) { -@@ -297,7 +_,12 @@ +@@ -303,7 +_,12 @@ } } @@ -33,10 +33,10 @@ + } + + public static boolean shouldRenderFace(final BlockGetter level, final BlockPos pos, final BlockState state, final BlockState neighborState, final Direction direction) { - VoxelShape occluder = neighborState.getFaceOcclusionShape(direction.getOpposite()); - if (occluder == Shapes.block()) { + VoxelShape voxelshape = neighborState.getFaceOcclusionShape(direction.getOpposite()); + if (voxelshape == Shapes.block()) { return false; -@@ -396,17 +_,22 @@ +@@ -398,17 +_,22 @@ } } @@ -54,23 +54,23 @@ + final ItemStack tool, + final boolean dropXp ) { - if (level instanceof ServerLevel serverLevel) { - getDrops(state, serverLevel, pos, blockEntity, breaker, tool).forEach(stack -> popResource(level, pos, stack)); -- state.spawnAfterBreak(serverLevel, pos, tool, true); -+ state.spawnAfterBreak(serverLevel, pos, tool, dropXp); + if (level instanceof ServerLevel serverlevel) { + getDrops(state, serverlevel, pos, blockEntity, breaker, tool).forEach(stack -> popResource(level, pos, stack)); +- state.spawnAfterBreak(serverlevel, pos, tool, true); ++ state.spawnAfterBreak(serverlevel, pos, tool, dropXp); } } -@@ -436,7 +_,7 @@ +@@ -438,7 +_,7 @@ } private static void popResource(final Level level, final Supplier entityFactory, final ItemStack itemStack) { -- if (level instanceof ServerLevel serverLevel && !itemStack.isEmpty() && serverLevel.getGameRules().get(GameRules.BLOCK_DROPS)) { -+ if (level instanceof ServerLevel serverLevel && !itemStack.isEmpty() && serverLevel.getGameRules().get(GameRules.BLOCK_DROPS) && !level.restoringBlockSnapshots) { - ItemEntity entity = entityFactory.get(); - entity.setDefaultPickUpDelay(); - level.addFreshEntity(entity); -@@ -444,11 +_,12 @@ +- if (level instanceof ServerLevel serverlevel && !itemStack.isEmpty() && serverlevel.getGameRules().get(GameRules.BLOCK_DROPS)) { ++ if (level instanceof ServerLevel serverlevel && !itemStack.isEmpty() && serverlevel.getGameRules().get(GameRules.BLOCK_DROPS) && !level.restoringBlockSnapshots) { + ItemEntity itementity = entityFactory.get(); + itementity.setDefaultPickUpDelay(); + level.addFreshEntity(itementity); +@@ -446,11 +_,12 @@ } public void popExperience(final ServerLevel level, final BlockPos pos, final int amount) { @@ -84,7 +84,7 @@ public float getExplosionResistance() { return this.explosionResistance; } -@@ -473,7 +_,8 @@ +@@ -475,7 +_,8 @@ ) { player.awardStat(Stats.BLOCK_MINED.get(this)); player.causeFoodExhaustion(0.005F); @@ -94,15 +94,15 @@ } public void setPlacedBy(final Level level, final BlockPos pos, final BlockState state, final @Nullable LivingEntity by, final ItemStack itemStack) { -@@ -495,6 +_,7 @@ - return this.bounceRestitution; +@@ -497,6 +_,7 @@ + entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.0, 0.0, 1.0)); } + /** @deprecated Forge: use {@link net.minecraftforge.common.extensions.IForgeBlockState#getFriction(LevelReader, BlockPos, Entity)}*/ public float getFriction() { return this.friction; } -@@ -565,7 +_,7 @@ +@@ -567,7 +_,7 @@ this.item = Item.byBlock(this); } @@ -111,7 +111,7 @@ } public boolean hasDynamicShape() { -@@ -630,6 +_,79 @@ +@@ -632,6 +_,79 @@ public int hashCode() { return System.identityHashCode(this.first) * 31 + System.identityHashCode(this.second); } 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 60a67065f3..2ef4a20ddc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/world/level/block/Blocks.java +++ b/net/minecraft/world/level/block/Blocks.java -@@ -705,7 +_,7 @@ - .pushReaction(PushReaction.DESTROY) - ); +@@ -686,7 +_,7 @@ + public static final Block RED_BED = registerBed("red_bed", DyeColor.RED); + public static final Block BLACK_BED = registerBed("black_bed", DyeColor.BLACK); public static final Block POWERED_RAIL = register( -- BlockItemIds.POWERED_RAIL, PoweredRailBlock::new, BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) -+ BlockItemIds.POWERED_RAIL, prop -> new PoweredRailBlock(prop, true), BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) +- "powered_rail", PoweredRailBlock::new, BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) ++ "powered_rail", prop -> new PoweredRailBlock(prop, true), BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) ); public static final Block DETECTOR_RAIL = register( - BlockItemIds.DETECTOR_RAIL, DetectorRailBlock::new, BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) -@@ -5992,14 +_,5 @@ + "detector_rail", DetectorRailBlock::new, BlockBehaviour.Properties.of().noCollision().strength(0.7F).sound(SoundType.METAL) +@@ -7218,14 +_,5 @@ - private static Block register(final ResourceKey id, final BlockBehaviour.Properties properties) { + private static Block register(final String id, final BlockBehaviour.Properties properties) { return register(id, Block::new, properties); - } - - static { - for (Block block : BuiltInRegistries.BLOCK) { -- for (BlockState state : block.getStateDefinition().getPossibleStates()) { -- Block.BLOCK_STATE_REGISTRY.add(state); -- state.initCache(); +- for (BlockState blockstate : block.getStateDefinition().getPossibleStates()) { +- Block.BLOCK_STATE_REGISTRY.add(blockstate); +- blockstate.initCache(); - } - } } 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 577502a100..3652b5d983 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch @@ -22,12 +22,12 @@ } + if (!net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, true)) return; - if (age == 8 && this.canSurvive(this.defaultBlockState(), level, pos.above())) { - double chanceToGrowFlower = height >= 3 ? 0.25 : 0.1; - if (random.nextDouble() <= chanceToGrowFlower) { + if (j == 8 && this.canSurvive(this.defaultBlockState(), level, pos.above())) { + double d0 = i >= 3 ? 0.25 : 0.1; + if (random.nextDouble() <= d0) { @@ -78,6 +_,7 @@ - if (age < 15) { - level.setBlock(pos, state.setValue(AGE, age + 1), 260); + if (j < 15) { + level.setBlock(pos, state.setValue(AGE, j + 1), 260); } + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } @@ -36,9 +36,9 @@ @@ -119,7 +_,7 @@ } - BlockState belowState = level.getBlockState(pos.below()); -- return (belowState.is(this) || belowState.is(BlockTags.SUPPORTS_CACTUS)) && !level.getBlockState(pos.above()).liquid(); -+ return belowState.canSustainPlant(level, pos, Direction.UP, this) && !level.getBlockState(pos.above()).liquid(); + BlockState blockstate1 = level.getBlockState(pos.below()); +- return (blockstate1.is(this) || blockstate1.is(BlockTags.SUPPORTS_CACTUS)) && !level.getBlockState(pos.above()).liquid(); ++ return blockstate1.canSustainPlant(level, pos, Direction.UP, this) && !level.getBlockState(pos.above()).liquid(); } @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch index 9deaf39f07..055b7915b4 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch @@ -3,8 +3,8 @@ @@ -31,6 +_,6 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { - BlockState blockBelow = level.getBlockState(pos); -- return blockBelow.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockBelow.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER); -+ return blockBelow.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockBelow.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER) || blockBelow.getBlock() instanceof FarmlandBlock; + BlockState blockstate = level.getBlockState(pos); +- return blockstate.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockstate.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER); ++ return blockstate.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockstate.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER) || blockstate.getBlock() instanceof FarmlandBlock; } } 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 9f3bc3982b..940ff7a907 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch @@ -4,8 +4,8 @@ return true; } -- boolean smokeBlocked = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockState.getCollisionShape(level, pos, CollisionContext.empty()), BooleanOp.AND); -+ boolean smokeBlocked = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockState.getCollisionShape(level, posToCheck, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 - if (smokeBlocked) { - BlockState belowState = level.getBlockState(posToCheck.below()); - return isLitCampfire(belowState); +- boolean flag = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockstate.getCollisionShape(level, pos, CollisionContext.empty()), BooleanOp.AND); ++ boolean flag = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockstate.getCollisionShape(level, blockpos, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 + if (flag) { + BlockState blockstate1 = level.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 97cdda45c1..d246058089 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/ChestBlock.java +++ b/net/minecraft/world/level/block/ChestBlock.java -@@ -368,7 +_,8 @@ +@@ -369,7 +_,8 @@ @Override protected BlockState mirror(final BlockState state, final Mirror mirror) { 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 ec7947bafe..d64303969e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/block/ChorusFlowerBlock.java +++ b/net/minecraft/world/level/block/ChorusFlowerBlock.java -@@ -65,7 +_,7 @@ - BlockPos above = pos.above(); - if (level.isEmptyBlock(above) && above.getY() <= level.getMaxY()) { - int currentAge = state.getValue(AGE); -- if (currentAge < 5) { -+ if (currentAge < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, above, state, true)) { - boolean growUpwards = false; - boolean pillarOnSupportBlock = false; - BlockState belowState = level.getBlockState(pos.below()); -@@ -121,6 +_,7 @@ +@@ -66,7 +_,7 @@ + BlockPos blockpos = pos.above(); + if (level.isEmptyBlock(blockpos) && blockpos.getY() <= level.getMaxY()) { + int i = state.getValue(AGE); +- if (i < 5) { ++ if (i < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, blockpos, state, true)) { + boolean flag = false; + boolean flag1 = false; + BlockState blockstate = level.getBlockState(pos.below()); +@@ -124,6 +_,7 @@ } else { this.placeDeadFlower(level, pos); } 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 802af346aa..e66c11da26 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch @@ -6,10 +6,10 @@ protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - if (level.getRandom().nextInt(5) == 0) { + { - int age = state.getValue(AGE); -- if (age < 2) { -+ if (age < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, level.getRandom().nextInt(5) == 0)) { - level.setBlock(pos, state.setValue(AGE, age + 1), 2); + int i = state.getValue(AGE); +- if (i < 2) { ++ if (i < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, level.getRandom().nextInt(5) == 0)) { + level.setBlock(pos, state.setValue(AGE, i + 1), 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } 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 52d73a8d8b..9e6cb3e253 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ComparatorBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/ComparatorBlock.java +++ b/net/minecraft/world/level/block/ComparatorBlock.java -@@ -198,4 +_,16 @@ +@@ -197,4 +_,16 @@ protected void createBlockStateDefinition(final StateDefinition.Builder builder) { builder.add(FACING, MODE, POWERED); } 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 2b9bcbec80..559288e26a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/ConcretePowderBlock.java +++ b/net/minecraft/world/level/block/ConcretePowderBlock.java -@@ -35,7 +_,7 @@ +@@ -36,7 +_,7 @@ @Override public void onLand(final Level level, final BlockPos pos, final BlockState state, final BlockState replacedBlock, final FallingBlockEntity entity) { @@ -9,8 +9,8 @@ level.setBlock(pos, this.concrete.defaultBlockState(), 3); } } -@@ -48,20 +_,24 @@ - return shouldSolidify(level, pos, replacedBlock) ? this.concrete.defaultBlockState() : super.getStateForPlacement(context); +@@ -49,20 +_,24 @@ + return shouldSolidify(blockgetter, blockpos, blockstate) ? this.concrete.defaultBlockState() : super.getStateForPlacement(context); } + private static boolean shouldSolidify(final BlockGetter level, final BlockPos pos, final BlockState state, final net.minecraft.world.level.material.FluidState fluidState) { @@ -24,21 +24,21 @@ - private static boolean touchesLiquid(final BlockGetter level, final BlockPos pos) { + private static boolean touchesLiquid(final BlockGetter level, BlockPos pos, BlockState state) { - boolean touchesLiquid = false; - BlockPos.MutableBlockPos testPos = pos.mutable(); + boolean flag = false; + BlockPos.MutableBlockPos blockpos$mutableblockpos = pos.mutable(); for (Direction direction : Direction.values()) { - BlockState blockState = level.getBlockState(testPos); -- if (direction != Direction.DOWN || canSolidify(blockState)) { -+ if (direction != Direction.DOWN || state.canBeHydrated(level, pos, blockState.getFluidState(), testPos)) { - testPos.setWithOffset(pos, direction); - blockState = level.getBlockState(testPos); -- if (canSolidify(blockState) && !blockState.isFaceSturdy(level, pos, direction.getOpposite())) { -+ if (state.canBeHydrated(level, pos, blockState.getFluidState(), testPos) && !blockState.isFaceSturdy(level, pos, direction.getOpposite())) { - touchesLiquid = true; + BlockState blockstate = level.getBlockState(blockpos$mutableblockpos); +- if (direction != Direction.DOWN || canSolidify(blockstate)) { ++ if (direction != Direction.DOWN || state.canBeHydrated(level, pos, blockstate.getFluidState(), blockpos$mutableblockpos)) { + blockpos$mutableblockpos.setWithOffset(pos, direction); + blockstate = level.getBlockState(blockpos$mutableblockpos); +- if (canSolidify(blockstate) && !blockstate.isFaceSturdy(level, pos, direction.getOpposite())) { ++ if (state.canBeHydrated(level, pos, blockstate.getFluidState(), blockpos$mutableblockpos) && !blockstate.isFaceSturdy(level, pos, direction.getOpposite())) { + flag = true; break; } -@@ -86,7 +_,7 @@ +@@ -87,7 +_,7 @@ final BlockState neighbourState, final RandomSource random ) { 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 6538cf0c9c..886c415d29 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 -@@ -60,9 +_,10 @@ +@@ -61,9 +_,10 @@ } protected boolean scanForWater(final BlockGetter level, final BlockPos blockPos) { + BlockState state = level.getBlockState(blockPos); for (Direction direction : Direction.values()) { - FluidState fluidState = level.getFluidState(blockPos.relative(direction)); -- if (fluidState.is(FluidTags.WATER)) { -+ if (state.canBeHydrated(level, blockPos, fluidState, blockPos.relative(direction))) { + FluidState fluidstate = level.getFluidState(blockPos.relative(direction)); +- if (fluidstate.is(FluidTags.WATER)) { ++ if (state.canBeHydrated(level, blockPos, fluidstate, blockPos.relative(direction))) { return true; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch index 7f997a1db0..93bdc523f5 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch @@ -1,33 +1,33 @@ --- a/net/minecraft/world/level/block/CrafterBlock.java +++ b/net/minecraft/world/level/block/CrafterBlock.java -@@ -194,12 +_,15 @@ +@@ -193,12 +_,15 @@ final RecipeHolder recipe ) { Direction direction = blockState.getValue(ORIENTATION).front(); + var itemhandler = net.minecraftforge.items.VanillaInventoryCodeHooks.getItemHandler(level, pos.relative(direction), direction.getOpposite()).orElse(null); - Container into = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); - ItemStack remaining = results.copy(); - if (into != null && (into instanceof CrafterBlockEntity || results.getCount() > into.getMaxStackSize(results))) { - while (!remaining.isEmpty()) { - ItemStack copy = remaining.copyWithCount(1); - ItemStack itemStack = HopperBlockEntity.addItem(blockEntity, into, copy, direction.getOpposite()); -+ if (itemhandler != null && !itemStack.isEmpty()) // Vanilla insert failed, try IItemHandler -+ itemStack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemStack, false); - if (!itemStack.isEmpty()) { + Container container = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); + ItemStack itemstack = results.copy(); + if (container != null && (container instanceof CrafterBlockEntity || results.getCount() > container.getMaxStackSize(results))) { + while (!itemstack.isEmpty()) { + ItemStack itemstack2 = itemstack.copyWithCount(1); + ItemStack itemstack1 = HopperBlockEntity.addItem(blockEntity, container, itemstack2, direction.getOpposite()); ++ if (itemhandler != null && !itemstack1.isEmpty()) // Vanilla insert failed, try IItemHandler ++ itemstack1 = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack1, false); + if (!itemstack1.isEmpty()) { break; } -@@ -210,10 +_,14 @@ - while (!remaining.isEmpty()) { - int oldSize = remaining.getCount(); - remaining = HopperBlockEntity.addItem(blockEntity, into, remaining, direction.getOpposite()); -+ if (itemhandler != null && oldSize == remaining.getCount()) // Vanilla insert failed, try IItemHandler -+ remaining = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, remaining, false); - if (oldSize == remaining.getCount()) { +@@ -209,10 +_,14 @@ + while (!itemstack.isEmpty()) { + int i = itemstack.getCount(); + itemstack = HopperBlockEntity.addItem(blockEntity, container, itemstack, direction.getOpposite()); ++ if (itemhandler != null && i == itemstack.getCount()) // Vanilla insert failed, try IItemHandler ++ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false); + if (i == itemstack.getCount()) { break; } } + } else { -+ remaining = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, remaining, false); ++ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false); } - if (!remaining.isEmpty()) { + if (!itemstack.isEmpty()) { 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 b1f8f5aa24..e24e03bb40 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch @@ -10,34 +10,34 @@ protected IntegerProperty getAgeProperty() { @@ -81,8 +_,9 @@ - int age = this.getAge(state); - if (age < this.getMaxAge()) { - float growthSpeed = getGrowthSpeed(this, level, pos); -- if (random.nextInt((int)(25.0F / growthSpeed) + 1) == 0) { -+ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt((int)(25.0F / growthSpeed) + 1) == 0)) { - level.setBlock(pos, this.getStateForAge(age + 1), 2); + int i = this.getAge(state); + if (i < this.getMaxAge()) { + float f = getGrowthSpeed(this, level, pos); +- if (random.nextInt((int)(25.0F / f) + 1) == 0) { ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt((int)(25.0F / f) + 1) == 0)) { + level.setBlock(pos, this.getStateForAge(i + 1), 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } } @@ -105,9 +_,9 @@ - for (int zz = -1; zz <= 1; zz++) { - float blockSpeed = 0.0F; - BlockState blockState = level.getBlockState(below.offset(xx, 0, zz)); -- if (blockState.is(BlockTags.GROWS_CROPS)) { -+ if (blockState.canSustainPlant(level, below.offset(xx, 0, zz), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable)type)) { - blockSpeed = 1.0F; -- if (blockState.getValueOrElse(FarmlandBlock.MOISTURE, 0) > 0) { -+ if (blockState.isFertile(level, below.offset(xx, 0, zz))) { - blockSpeed = 3.0F; + for (int j = -1; j <= 1; j++) { + float f1 = 0.0F; + BlockState blockstate = level.getBlockState(blockpos.offset(i, 0, j)); +- if (blockstate.is(BlockTags.GROWS_CROPS)) { ++ if (blockstate.canSustainPlant(level, blockpos.offset(i, 0, j), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable)type)) { + f1 = 1.0F; +- if (blockstate.getValueOrElse(FarmlandBlock.MOISTURE, 0) > 0) { ++ if (blockstate.isFertile(level, blockpos.offset(i, 0, j))) { + f1 = 3.0F; } } @@ -159,7 +_,7 @@ final InsideBlockEffectApplier effectApplier, final boolean isPrecise ) { -- if (level instanceof ServerLevel serverLevel && entity instanceof Ravager && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (level instanceof ServerLevel serverLevel && entity instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, entity)) { - serverLevel.destroyBlock(pos, true, entity); +- if (level instanceof ServerLevel serverlevel && entity instanceof Ravager && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (level instanceof ServerLevel serverlevel && entity instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, entity)) { + serverlevel.destroyBlock(pos, true, entity); } 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 ef9b8bde3e..6f6dc6505e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch @@ -12,16 +12,16 @@ } @@ -154,7 +_,10 @@ - return commandBlocks.get(0).getCommandBlock().getSuccessCount(); + return list.get(0).getCommandBlock().getSuccessCount(); } -- List entities = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); +- List list1 = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); + List carts = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, e -> e.isAlive()); + if (!carts.isEmpty() && carts.get(0).getComparatorLevel() > -1) return carts.get(0).getComparatorLevel(); -+ List entities = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).toList(); ++ List list1 = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).toList(); + - if (!entities.isEmpty()) { - return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)entities.get(0)); + if (!list1.isEmpty()) { + return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)list1.get(0)); } @@ -190,6 +_,6 @@ 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 1bb6cc9725..4706c7c0a9 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/DiodeBlock.java +++ b/net/minecraft/world/level/block/DiodeBlock.java -@@ -181,6 +_,9 @@ +@@ -177,6 +_,9 @@ Direction direction = state.getValue(FACING); - BlockPos oppositePos = pos.relative(direction.getOpposite()); + BlockPos blockpos = pos.relative(direction.getOpposite()); Orientation orientation = ExperimentalRedstoneUtils.initialOrientation(level, direction.getOpposite(), Direction.UP); + if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(level, pos, level.getBlockState(pos), java.util.EnumSet.of(direction.getOpposite()), false)) { + return; + } - level.neighborChanged(oppositePos, this, orientation); - level.updateNeighborsAtExceptFromFacing(oppositePos, this, direction, orientation); + level.neighborChanged(blockpos, this, orientation); + level.updateNeighborsAtExceptFromFacing(blockpos, this, direction, orientation); } 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 445be8a492..40a99dd83c 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 -@@ -80,6 +_,7 @@ +@@ -79,6 +_,7 @@ + return super.canSurvive(state, level, pos); + } else { + BlockState blockstate = level.getBlockState(pos.below()); ++ if (state.getBlock() != this) return super.canSurvive(state, level, pos); //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; } - - BlockState belowState = level.getBlockState(pos.below()); -+ if (state.getBlock() != this) return super.canSurvive(state, level, pos); //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 belowState.is(this) && belowState.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 d91f08f9ac..31148742c9 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/DropExperienceBlock.java +++ b/net/minecraft/world/level/block/DropExperienceBlock.java -@@ -29,8 +_,13 @@ +@@ -30,8 +_,13 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); 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 934255a286..4f1ef406d8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch @@ -3,9 +3,9 @@ @@ -56,7 +_,7 @@ level.levelEvent(1001, pos, 0); } else { - ItemStack itemStack = blockEntity.getItem(slot); -- if (!itemStack.isEmpty()) { -+ if (!itemStack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(level, pos, blockEntity, slot, itemStack)) { + ItemStack itemstack = dispenserblockentity.getItem(i); +- if (!itemstack.isEmpty()) { ++ if (!itemstack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(level, pos, dispenserblockentity, i, itemstack)) { Direction direction = level.getBlockState(pos).getValue(FACING); - Container into = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); - ItemStack remaining; + Container container = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); + ItemStack itemstack1; diff --git a/patches/minecraft/net/minecraft/world/level/block/DryVegetationBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DryVegetationBlock.java.patch new file mode 100644 index 0000000000..026a05e152 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/DryVegetationBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/DryVegetationBlock.java ++++ b/net/minecraft/world/level/block/DryVegetationBlock.java +@@ -12,7 +_,7 @@ + import net.minecraft.world.phys.shapes.CollisionContext; + import net.minecraft.world.phys.shapes.VoxelShape; + +-public class DryVegetationBlock extends VegetationBlock { ++public class DryVegetationBlock extends VegetationBlock implements net.minecraftforge.common.IForgeShearable { + public static final MapCodec CODEC = simpleCodec(DryVegetationBlock::new); + private static final VoxelShape SHAPE = Block.column(12.0, 0.0, 13.0); + diff --git a/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch index a0834c0c7c..e6e9db89cb 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch @@ -3,12 +3,12 @@ @@ -108,10 +_,7 @@ @Override public void fallOn(final Level level, final BlockState state, final BlockPos pos, final Entity entity, final double fallDistance) { - if (level instanceof ServerLevel serverLevel + if (level instanceof ServerLevel serverlevel - && level.getRandom().nextFloat() < fallDistance - 0.5 - && entity instanceof LivingEntity -- && (entity instanceof Player || serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) +- && (entity instanceof Player || serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) - && entity.getBbWidth() * entity.getBbWidth() * entity.getBbHeight() > 0.512F) { -+ && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(serverLevel, pos, state, fallDistance, entity)) { // Forge: Move logic to Entity#canTrample ++ && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(serverlevel, pos, state, fallDistance, entity)) { // Forge: Move logic to Entity#canTrample turnToDirt(entity, state, level, pos); } @@ -25,9 +25,9 @@ private static boolean isNearWater(final LevelReader level, final BlockPos pos) { + BlockState state = level.getBlockState(pos); - for (BlockPos blockPos : BlockPos.betweenClosed(pos.offset(-4, 0, -4), pos.offset(4, 1, 4))) { -- if (level.getFluidState(blockPos).is(FluidTags.WATER)) { -+ if (state.canBeHydrated(level, pos, level.getFluidState(blockPos), blockPos)) { + for (BlockPos blockpos : BlockPos.betweenClosed(pos.offset(-4, 0, -4), pos.offset(4, 1, 4))) { +- if (level.getFluidState(blockpos).is(FluidTags.WATER)) { ++ if (state.canBeHydrated(level, pos, level.getFluidState(blockpos), blockpos)) { return true; } } 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 097e64d0ce..a7954ff440 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/FenceGateBlock.java +++ b/net/minecraft/world/level/block/FenceGateBlock.java -@@ -57,6 +_,8 @@ +@@ -58,6 +_,8 @@ Util.mapValues(SHAPE_OCCLUSION, v -> v.move(0.0, -0.1875, 0.0).optimize()) ); private final WoodType type; @@ -9,7 +9,7 @@ @Override public MapCodec codec() { -@@ -64,8 +_,14 @@ +@@ -65,8 +_,14 @@ } public FenceGateBlock(final WoodType type, final BlockBehaviour.Properties properties) { @@ -25,30 +25,30 @@ this.registerDefaultState(this.stateDefinition.any().setValue(OPEN, false).setValue(POWERED, false).setValue(IN_WALL, false)); } -@@ -156,7 +_,7 @@ +@@ -162,7 +_,7 @@ - boolean opens = state.getValue(OPEN); + boolean flag = state.getValue(OPEN); level.playSound( -- player, pos, opens ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F -+ player, pos, opens ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F +- player, pos, flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ++ player, pos, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ); - level.gameEvent(player, opens ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos); + level.gameEvent(player, flag ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos); return InteractionResult.SUCCESS; -@@ -170,7 +_,7 @@ - boolean open = state.getValue(OPEN); - level.setBlockAndUpdate(pos, state.setValue(OPEN, !open)); +@@ -176,7 +_,7 @@ + boolean flag = state.getValue(OPEN); + level.setBlockAndUpdate(pos, state.setValue(OPEN, !flag)); level.playSound( -- null, pos, open ? this.type.fenceGateClose() : this.type.fenceGateOpen(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F -+ null, pos, open ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F +- null, pos, flag ? this.type.fenceGateClose() : this.type.fenceGateOpen(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ++ null, pos, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ); - level.gameEvent(open ? GameEvent.BLOCK_CLOSE : GameEvent.BLOCK_OPEN, pos, GameEvent.Context.of(state)); + level.gameEvent(flag ? GameEvent.BLOCK_CLOSE : GameEvent.BLOCK_OPEN, pos, GameEvent.Context.of(state)); } -@@ -190,7 +_,7 @@ +@@ -196,7 +_,7 @@ level.playSound( null, pos, -- hasPower ? this.type.fenceGateOpen() : this.type.fenceGateClose(), -+ hasPower ? this.openSound : this.closeSound, +- flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), ++ flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.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 c3f5c9deec..076bae73be 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch @@ -2,57 +2,57 @@ +++ b/net/minecraft/world/level/block/FireBlock.java @@ -115,13 +_,13 @@ protected BlockState getStateForPlacement(final BlockGetter level, final BlockPos pos) { - BlockPos below = pos.below(); - BlockState belowState = level.getBlockState(below); -- if (!this.canBurn(belowState) && !belowState.isFaceSturdy(level, below, Direction.UP)) { -+ if (!this.canCatchFire(level, pos, Direction.UP) && !belowState.isFaceSturdy(level, below, Direction.UP)) { - BlockState result = this.defaultBlockState(); + BlockPos blockpos = pos.below(); + BlockState blockstate = level.getBlockState(blockpos); +- if (!this.canBurn(blockstate) && !blockstate.isFaceSturdy(level, blockpos, Direction.UP)) { ++ if (!this.canCatchFire(level, pos, Direction.UP) && !blockstate.isFaceSturdy(level, blockpos, Direction.UP)) { + BlockState blockstate1 = this.defaultBlockState(); for (Direction direction : Direction.values()) { - BooleanProperty property = PROPERTY_BY_DIRECTION.get(direction); - if (property != null) { -- result = result.setValue(property, this.canBurn(level.getBlockState(pos.relative(direction)))); -+ result = result.setValue(property, Boolean.valueOf(this.canCatchFire(level, pos.relative(direction), direction.getOpposite()))); + BooleanProperty booleanproperty = PROPERTY_BY_DIRECTION.get(direction); + if (booleanproperty != null) { +- blockstate1 = blockstate1.setValue(booleanproperty, this.canBurn(level.getBlockState(pos.relative(direction)))); ++ blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canCatchFire(level, pos.relative(direction), direction.getOpposite()))); } } @@ -146,7 +_,7 @@ } - BlockState belowState = level.getBlockState(pos.below()); -- boolean infiniBurn = belowState.is(level.dimensionType().infiniburn()); -+ boolean infiniBurn = belowState.isFireSource(level, pos, Direction.UP); - int age = state.getValue(AGE); - if (!infiniBurn && level.isRaining() && this.isNearRain(level, pos) && random.nextFloat() < 0.2F + age * 0.03F) { + BlockState blockstate = level.getBlockState(pos.below()); +- boolean flag = blockstate.is(level.dimensionType().infiniburn()); ++ boolean flag = blockstate.isFireSource(level, pos, Direction.UP); + int i = state.getValue(AGE); + if (!flag && level.isRaining() && this.isNearRain(level, pos) && random.nextFloat() < 0.2F + i * 0.03F) { level.removeBlock(pos, false); @@ -167,7 +_,7 @@ return; } -- if (age == 15 && random.nextInt(4) == 0 && !this.canBurn(level.getBlockState(pos.below()))) { -+ if (age == 15 && random.nextInt(4) == 0 && !this.canCatchFire(level, pos.below(), Direction.UP)) { +- if (i == 15 && random.nextInt(4) == 0 && !this.canBurn(level.getBlockState(pos.below()))) { ++ if (i == 15 && random.nextInt(4) == 0 && !this.canCatchFire(level, pos.below(), Direction.UP)) { level.removeBlock(pos, false); return; } @@ -175,12 +_,12 @@ - boolean increasedBurnout = level.environmentAttributes().getValue(EnvironmentAttributes.INCREASED_FIRE_BURNOUT, pos); - int extra = increasedBurnout ? -50 : 0; -- this.checkBurnOut(level, pos.east(), 300 + extra, random, age); -- this.checkBurnOut(level, pos.west(), 300 + extra, random, age); -- this.checkBurnOut(level, pos.below(), 250 + extra, random, age); -- this.checkBurnOut(level, pos.above(), 250 + extra, random, age); -- this.checkBurnOut(level, pos.north(), 300 + extra, random, age); -- this.checkBurnOut(level, pos.south(), 300 + extra, random, age); -+ this.checkBurnOut(level, pos.east(), 300 + extra, random, age, Direction.WEST); -+ this.checkBurnOut(level, pos.west(), 300 + extra, random, age, Direction.EAST); -+ this.checkBurnOut(level, pos.below(), 250 + extra, random, age, Direction.UP); -+ this.checkBurnOut(level, pos.above(), 250 + extra, random, age, Direction.DOWN); -+ this.checkBurnOut(level, pos.north(), 300 + extra, random, age, Direction.SOUTH); -+ this.checkBurnOut(level, pos.south(), 300 + extra, random, age, Direction.NORTH); - BlockPos.MutableBlockPos testPos = new BlockPos.MutableBlockPos(); + boolean flag1 = level.environmentAttributes().getValue(EnvironmentAttributes.INCREASED_FIRE_BURNOUT, pos); + int k = flag1 ? -50 : 0; +- this.checkBurnOut(level, pos.east(), 300 + k, random, i); +- this.checkBurnOut(level, pos.west(), 300 + k, random, i); +- this.checkBurnOut(level, pos.below(), 250 + k, random, i); +- this.checkBurnOut(level, pos.above(), 250 + k, random, i); +- this.checkBurnOut(level, pos.north(), 300 + k, random, i); +- this.checkBurnOut(level, pos.south(), 300 + k, random, i); ++ this.checkBurnOut(level, pos.east(), 300 + k, random, i, Direction.WEST); ++ this.checkBurnOut(level, pos.west(), 300 + k, random, i, Direction.EAST); ++ this.checkBurnOut(level, pos.below(), 250 + k, random, i, Direction.UP); ++ this.checkBurnOut(level, pos.above(), 250 + k, random, i, Direction.DOWN); ++ this.checkBurnOut(level, pos.north(), 300 + k, random, i, Direction.SOUTH); ++ this.checkBurnOut(level, pos.south(), 300 + k, random, i, Direction.NORTH); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - for (int xx = -1; xx <= 1; xx++) { + for (int l = -1; l <= 1; l++) { @@ -221,33 +_,31 @@ || level.isRainingAt(testPos.south()); } @@ -72,20 +72,20 @@ } - private void checkBurnOut(final Level level, final BlockPos pos, final int chance, final RandomSource random, final int age) { -- int odds = this.getBurnOdds(level.getBlockState(pos)); +- int i = this.getBurnOdds(level.getBlockState(pos)); + private void checkBurnOut(final Level level, final BlockPos pos, final int chance, final RandomSource random, final int age, final Direction face) { -+ int odds = level.getBlockState(pos).getFlammability(level, pos, face); - if (random.nextInt(chance) < odds) { - BlockState oldState = level.getBlockState(pos); -+ oldState.onCaughtFire(level, pos, face, null); ++ int i = level.getBlockState(pos).getFlammability(level, pos, face); + if (random.nextInt(chance) < i) { + BlockState blockstate = level.getBlockState(pos); ++ blockstate.onCaughtFire(level, pos, face, null); if (random.nextInt(age + 10) < 5 && !level.isRainingAt(pos)) { - int newAge = Math.min(age + random.nextInt(5) / 4, 15); - level.setBlock(pos, this.getStateWithAge(level, pos, newAge), 3); + int j = Math.min(age + random.nextInt(5) / 4, 15); + level.setBlock(pos, this.getStateWithAge(level, pos, j), 3); } else { level.removeBlock(pos, false); } - -- Block block = oldState.getBlock(); +- Block block = blockstate.getBlock(); - if (block instanceof TntBlock) { - TntBlock.prime(level, pos); - } @@ -101,15 +101,16 @@ return true; } } -@@ -275,12 +_,13 @@ +@@ -274,13 +_,14 @@ - for (Direction direction : Direction.values()) { - BlockState blockState = level.getBlockState(pos.relative(direction)); -- odds = Math.max(this.getIgniteOdds(blockState), odds); -+ odds = Math.max(blockState.getFireSpreadSpeed(level, pos.relative(direction), direction.getOpposite()), odds); + for (Direction direction : Direction.values()) { + BlockState blockstate = level.getBlockState(pos.relative(direction)); +- i = Math.max(this.getIgniteOdds(blockstate), i); ++ i = Math.max(blockstate.getFireSpreadSpeed(level, pos.relative(direction), direction.getOpposite()), i); + } + + return i; } - - return odds; } + @Deprecated //Forge: Use canCatchFire with more context 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 4ae076fdd6..9c1e316842 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/FlowerPotBlock.java +++ b/net/minecraft/world/level/block/FlowerPotBlock.java -@@ -43,9 +_,31 @@ +@@ -44,9 +_,31 @@ } public FlowerPotBlock(final Block potted, final BlockBehaviour.Properties properties) { @@ -34,25 +34,25 @@ } @Override -@@ -64,7 +_,7 @@ +@@ -65,7 +_,7 @@ final BlockHitResult hitResult ) { - BlockState newContents = (itemStack.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() + BlockState blockstate = (itemStack.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 (newContents.isAir()) { -@@ -95,7 +_,7 @@ - player.drop(plant, false); - } + if (blockstate.isAir()) { +@@ -93,7 +_,7 @@ + player.drop(itemstack, false); + } -- level.setBlock(pos, Blocks.FLOWER_POT.defaultBlockState(), 3); -+ level.setBlock(pos, getEmptyPot().defaultBlockState(), 3); - level.gameEvent(player, GameEvent.BLOCK_CHANGE, pos); - return InteractionResult.SUCCESS; - } -@@ -126,7 +_,7 @@ +- level.setBlock(pos, Blocks.FLOWER_POT.defaultBlockState(), 3); ++ level.setBlock(pos, getEmptyPot().defaultBlockState(), 3); + level.gameEvent(player, GameEvent.BLOCK_CHANGE, pos); + return InteractionResult.SUCCESS; + } +@@ -125,7 +_,7 @@ } public Block getPotted() { @@ -61,7 +61,7 @@ } @Override -@@ -161,5 +_,24 @@ +@@ -160,5 +_,24 @@ } else { return state.is(Blocks.POTTED_CLOSED_EYEBLOSSOM) ? Blocks.POTTED_OPEN_EYEBLOSSOM.defaultBlockState() : state; } 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 affd25cb75..c974ea5f03 100644 --- a/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch @@ -8,10 +8,10 @@ + var vanilla = random.nextDouble() < this.growPerTickProbability; + var target = pos.relative(this.growthDirection); + if (state.getValue(AGE) < 25 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, target, level.getBlockState(target), vanilla)) { - BlockPos growthPos = pos.relative(this.growthDirection); - if (this.canGrowInto(level.getBlockState(growthPos))) { - level.setBlockAndUpdate(growthPos, this.getGrowIntoState(state, level.getRandom())); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, growthPos, level.getBlockState(growthPos)); + BlockPos blockpos = pos.relative(this.growthDirection); + if (this.canGrowInto(level.getBlockState(blockpos))) { + level.setBlockAndUpdate(blockpos, this.getGrowIntoState(state, level.getRandom())); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, blockpos, level.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 new file mode 100644 index 0000000000..4e47c3c6e6 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/LeavesBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/LeavesBlock.java ++++ b/net/minecraft/world/level/block/LeavesBlock.java +@@ -26,7 +_,7 @@ + import net.minecraft.world.phys.shapes.Shapes; + import net.minecraft.world.phys.shapes.VoxelShape; + +-public abstract class LeavesBlock extends Block implements SimpleWaterloggedBlock { ++public abstract class LeavesBlock extends Block implements SimpleWaterloggedBlock, net.minecraftforge.common.IForgeShearable { + public static final int DECAY_DISTANCE = 7; + public static final IntegerProperty DISTANCE = BlockStateProperties.DISTANCE; + public static final BooleanProperty PERSISTENT = BlockStateProperties.PERSISTENT; 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 02758f99bc..c80ec25edb 100644 --- a/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/LiquidBlock.java +++ b/net/minecraft/world/level/block/LiquidBlock.java -@@ -52,7 +_,8 @@ +@@ -53,7 +_,8 @@ i -> i.group(FLOWING_FLUID.fieldOf("fluid").forGetter(b -> b.fluid), propertiesCodec()).apply(i, LiquidBlock::new) ); public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; @@ -10,7 +10,7 @@ private final List stateCache; public static final ImmutableList POSSIBLE_FLOW_DIRECTIONS = ImmutableList.of( Direction.DOWN, Direction.SOUTH, Direction.NORTH, Direction.EAST, Direction.WEST -@@ -64,6 +_,7 @@ +@@ -65,6 +_,7 @@ return CODEC; } @@ -18,7 +18,7 @@ public LiquidBlock(final FlowingFluid fluid, final BlockBehaviour.Properties properties) { super(properties); this.fluid = fluid; -@@ -76,6 +_,19 @@ +@@ -77,6 +_,19 @@ this.stateCache.add(fluid.getFlowing(8, true)); this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 0)); @@ -38,15 +38,15 @@ } @Override -@@ -124,6 +_,7 @@ +@@ -125,6 +_,7 @@ @Override protected FluidState getFluidState(final BlockState state) { - int level = state.getValue(LEVEL); + int i = state.getValue(LEVEL); + if (!fluidStateCacheInitialized) initFluidStateCache(); - return this.stateCache.get(Math.min(level, 8)); + return this.stateCache.get(Math.min(i, 8)); } -@@ -149,7 +_,7 @@ +@@ -150,7 +_,7 @@ @Override protected void onPlace(final BlockState state, final Level level, final BlockPos pos, final BlockState oldState, final boolean movedByPiston) { @@ -55,7 +55,7 @@ level.scheduleTick(pos, state.getFluidState().getType(), this.fluid.getTickDelay(level)); } -@@ -197,7 +_,7 @@ +@@ -198,7 +_,7 @@ protected void neighborChanged( final BlockState state, final Level level, final BlockPos pos, final Block block, final @Nullable Orientation orientation, final boolean movedByPiston ) { @@ -64,15 +64,15 @@ level.scheduleTick(pos, state.getFluidState().getType(), this.fluid.getTickDelay(level)); } -@@ -213,6 +_,7 @@ +@@ -214,6 +_,7 @@ } } + @Deprecated // FORGE: Use FluidInteractionRegistry#canInteract instead private boolean shouldSpreadLiquid(final Level level, final BlockPos pos, final BlockState state) { if (this.fluid.is(FluidTags.LAVA)) { - boolean isOverSoulSoil = level.getBlockState(pos.below()).is(Blocks.SOUL_SOIL); -@@ -259,5 +_,24 @@ + boolean flag = level.getBlockState(pos.below()).is(Blocks.SOUL_SOIL); +@@ -260,5 +_,24 @@ @Override public Optional getPickupSound() { return this.fluid.getPickupSound(); 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 09c7d20ef3..d808cb38f3 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 @@ - protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { - BlockPos belowPos = pos.below(); - BlockState below = level.getBlockState(belowPos); -- return below.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) ? true : level.getRawBrightness(pos, 0) < 13 && this.mayPlaceOn(below, level, belowPos); -+ return below.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) ? true : level.getRawBrightness(pos, 0) < 13 && below.canSustainPlant(level, belowPos, net.minecraft.core.Direction.UP, this); +@@ -86,7 +_,7 @@ + BlockState blockstate = level.getBlockState(blockpos); + return blockstate.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) + ? true +- : level.getRawBrightness(pos, 0) < 13 && this.mayPlaceOn(blockstate, level, blockpos); ++ : level.getRawBrightness(pos, 0) < 13 && blockstate.canSustainPlant(level, blockpos, net.minecraft.core.Direction.UP, this); } public boolean growMushroom(final ServerLevel level, final BlockPos pos, final BlockState state, final RandomSource random) { -@@ -92,8 +_,10 @@ +@@ -94,8 +_,10 @@ + if (optional.isEmpty()) { return false; - } - -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, feature.get()); -+ if (event.getResult().isDenied()) return false; - level.removeBlock(pos, false); -- if (feature.get().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { -+ if (event.getFeature().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { - return true; - } - + } else { ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, optional.get()); ++ if (event.getResult().isDenied()) return false; + level.removeBlock(pos, false); +- if (optional.get().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { ++ if (event.getFeature().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { + return true; + } else { + level.setBlock(pos, state, 3); diff --git a/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch index 6aea05dc2f..26a4807f44 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/NetherFungusBlock.java +++ b/net/minecraft/world/level/block/NetherFungusBlock.java -@@ -81,5 +_,10 @@ +@@ -82,5 +_,10 @@ @Override public void performBonemeal(final ServerLevel level, final RandomSource random, final BlockPos pos, final BlockState state) { this.getFeature(level).ifPresent(feature -> feature.value().place(level, level.getChunkSource().getGenerator(), random, pos)); 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 c42fe54bec..46dc3bb4e8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch @@ -3,10 +3,10 @@ @@ -51,9 +_,10 @@ @Override protected void randomTick(BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - int age = state.getValue(AGE); -- if (age < 3 && random.nextInt(10) == 0) { -+ if (age < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(10) == 0)) { - state = state.setValue(AGE, age + 1); + int i = state.getValue(AGE); +- if (i < 3 && random.nextInt(10) == 0) { ++ if (i < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(10) == 0)) { + state = state.setValue(AGE, i + 1); level.setBlock(pos, state, 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } 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 96515ff319..50b155b569 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch @@ -15,15 +15,15 @@ @Override protected boolean triggerEvent(final BlockState state, final Level level, final BlockPos pos, final int b0, final int b1) { -- NoteBlockInstrument instrument = state.getValue(INSTRUMENT); +- NoteBlockInstrument noteblockinstrument = state.getValue(INSTRUMENT); + var event = net.minecraftforge.event.ForgeEventFactory.onNotePlay(level, pos, state, state.getValue(NOTE), state.getValue(INSTRUMENT)); + if (event == null) return false; + var newState = state.setValue(NOTE, event.getVanillaNoteId()).setValue(INSTRUMENT, event.getInstrument()); -+ NoteBlockInstrument instrument = newState.getValue(INSTRUMENT); - float pitch; - if (instrument.isTunable()) { -- int note = state.getValue(NOTE); -+ int note = newState.getValue(NOTE); - pitch = getPitchFromNote(note); - level.addParticle(ParticleTypes.NOTE, pos.getX() + 0.5, pos.getY() + 1.2, pos.getZ() + 0.5, note / 24.0, 0.0, 0.0); ++ NoteBlockInstrument noteblockinstrument = newState.getValue(INSTRUMENT); + float f; + if (noteblockinstrument.isTunable()) { +- int i = state.getValue(NOTE); ++ int i = newState.getValue(NOTE); + f = getPitchFromNote(i); + level.addParticle(ParticleTypes.NOTE, pos.getX() + 0.5, pos.getY() + 1.2, pos.getZ() + 0.5, i / 24.0, 0.0, 0.0); } else { 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 96ba84c66a..5ec3357886 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PowderSnowBlock.java.patch @@ -4,8 +4,8 @@ if (entity.is(EntityTypeTags.POWDER_SNOW_WALKABLE_MOBS)) { return true; } else { -- return entity instanceof LivingEntity livingEntity ? livingEntity.getItemBySlot(EquipmentSlot.FEET).is(Items.LEATHER_BOOTS) : false; -+ return entity instanceof LivingEntity livingEntity ? livingEntity.getItemBySlot(EquipmentSlot.FEET).canWalkOnPowderedSnow((LivingEntity)entity) : false; +- return entity instanceof LivingEntity ? ((LivingEntity)entity).getItemBySlot(EquipmentSlot.FEET).is(Items.LEATHER_BOOTS) : false; ++ return entity instanceof LivingEntity ? ((LivingEntity)entity).getItemBySlot(EquipmentSlot.FEET).canWalkOnPowderedSnow((LivingEntity)entity) : 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 f487481ef3..dd15e2e28a 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch @@ -25,46 +25,47 @@ this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, RailShape.NORTH_SOUTH).setValue(POWERED, false).setValue(WATERLOGGED, false)); } -@@ -36,7 +_,7 @@ - int y = pos.getY(); - int z = pos.getZ(); - boolean checkBelow = true; -- RailShape shape = state.getValue(SHAPE); -+ RailShape shape = state.getValue(getShapeProperty()); - switch (shape) { - case NORTH_SOUTH: - if (forward) { -@@ -104,17 +_,17 @@ +@@ -35,7 +_,7 @@ + int j = pos.getY(); + int k = pos.getZ(); + boolean flag = true; +- RailShape railshape = state.getValue(SHAPE); ++ RailShape railshape = state.getValue(getShapeProperty()); + switch (railshape) { + case NORTH_SOUTH: + if (forward) { +@@ -104,10 +_,10 @@ protected boolean isSameRailWithPower(final Level level, final BlockPos pos, final boolean forward, final int searchDepth, final RailShape dir) { - BlockState state = level.getBlockState(pos); -- if (!state.is(this)) { -+ if (!(state.getBlock() instanceof PoweredRailBlock other) || this.isActivatorRail() != other.isActivatorRail()) { + BlockState blockstate = level.getBlockState(pos); +- if (!blockstate.is(this)) { ++ if (!(blockstate.getBlock() instanceof PoweredRailBlock other) || this.isActivatorRail() != other.isActivatorRail()) { return false; - } - -- RailShape myShape = state.getValue(SHAPE); -+ RailShape myShape = other.getRailDirection(state, level, pos, null); - if (dir != RailShape.EAST_WEST || myShape != RailShape.NORTH_SOUTH && myShape != RailShape.ASCENDING_NORTH && myShape != RailShape.ASCENDING_SOUTH) { - if (dir != RailShape.NORTH_SOUTH || myShape != RailShape.EAST_WEST && myShape != RailShape.ASCENDING_EAST && myShape != RailShape.ASCENDING_WEST) { - if (!state.getValue(POWERED)) { - return false; + } else { +- RailShape railshape = blockstate.getValue(SHAPE); ++ RailShape railshape = other.getRailDirection(blockstate, level, pos, null); + if (dir != RailShape.EAST_WEST + || railshape != RailShape.NORTH_SOUTH && railshape != RailShape.ASCENDING_NORTH && railshape != RailShape.ASCENDING_SOUTH) { + if (dir != RailShape.NORTH_SOUTH +@@ -115,7 +_,7 @@ + if (!blockstate.getValue(POWERED)) { + return false; + } else { +- return level.hasNeighborSignal(pos) ? true : this.findPoweredRailSignal(level, pos, blockstate, forward, searchDepth + 1); ++ return level.hasNeighborSignal(pos) ? true : other.findPoweredRailSignal(level, pos, blockstate, forward, searchDepth + 1); + } } else { -- return level.hasNeighborSignal(pos) ? true : this.findPoweredRailSignal(level, pos, state, forward, searchDepth + 1); -+ return level.hasNeighborSignal(pos) ? true : other.findPoweredRailSignal(level, pos, state, forward, searchDepth + 1); - } - } else { - return false; -@@ -133,7 +_,7 @@ - if (shouldPower != isPowered) { - level.setBlock(pos, state.setValue(POWERED, shouldPower), 3); + return false; +@@ -135,7 +_,7 @@ + if (flag1 != flag) { + level.setBlock(pos, state.setValue(POWERED, flag1), 3); level.updateNeighborsAt(pos.below(), this); - if (state.getValue(SHAPE).isSlope()) { + if (state.getValue(getShapeProperty()).isSlope()) { level.updateNeighborsAt(pos.above(), this); } } -@@ -160,6 +_,10 @@ +@@ -162,6 +_,10 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { 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 524f64ecd0..1083fad13e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch @@ -7,5 +7,5 @@ - if (!itemStack.is(Items.SHEARS)) { + if (!itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_CARVE)) { return super.useItemOn(itemStack, state, level, pos, player, hand, hitResult); - } else if (level instanceof ServerLevel serverLevel) { - Direction clickedDirection = hitResult.getDirection(); + } else if (level instanceof ServerLevel serverlevel) { + Direction direction = hitResult.getDirection(); 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 d952dad891..53327dbcbd 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch @@ -11,68 +11,68 @@ this.pos = pos; this.state = state; this.block = (BaseRailBlock)state.getBlock(); -- RailShape direction = state.getValue(this.block.getShapeProperty()); +- RailShape railshape = state.getValue(this.block.getShapeProperty()); - this.isStraight = this.block.isStraight(); -+ RailShape direction = this.block.getRailDirection(state, level, pos, null); ++ RailShape railshape = this.block.getRailDirection(state, level, pos, null); + this.isStraight = !this.block.isFlexibleRail(state, level, pos); + this.canMakeSlopes = this.block.canMakeSlopes(state, level, pos); - this.updateConnections(direction); + this.updateConnections(railshape); } -@@ -177,7 +_,7 @@ +@@ -176,7 +_,7 @@ } } -- if (shape == RailShape.NORTH_SOUTH) { -+ if (shape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, north.above())) { - shape = 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; } -@@ -187,7 +_,7 @@ +@@ -186,7 +_,7 @@ } } -- if (shape == RailShape.EAST_WEST) { -+ if (shape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, east.above())) { - shape = 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; } -@@ -199,6 +_,11 @@ +@@ -198,6 +_,11 @@ - if (shape == null) { - shape = RailShape.NORTH_SOUTH; + if (railshape == null) { + railshape = RailShape.NORTH_SOUTH; + } + -+ if (!this.block.isValidRailShape(shape)) { // Forge: allow rail block to decide if the new shape is valid ++ if (!this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid + this.connections.remove(rail.pos); + return; } - this.state = this.state.setValue(this.block.getShapeProperty(), shape); -@@ -303,7 +_,7 @@ + this.state = this.state.setValue(this.block.getShapeProperty(), railshape); +@@ -302,7 +_,7 @@ } } -- if (shape == RailShape.NORTH_SOUTH) { -+ if (shape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, north.above())) { - shape = 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; } -@@ -313,7 +_,7 @@ +@@ -312,7 +_,7 @@ } } -- if (shape == RailShape.EAST_WEST) { -+ if (shape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, east.above())) { - shape = 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; } -@@ -323,7 +_,7 @@ +@@ -322,7 +_,7 @@ } } -- if (shape == null) { -+ if (shape == null || !this.block.isValidRailShape(shape)) { // Forge: allow rail block to decide if the new shape is valid - shape = defaultShape; +- if (railshape == null) { ++ if (railshape == null || !this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid + railshape = defaultShape; } 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 87973efc87..108ccb12bd 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/world/level/block/RedStoneWireBlock.java +++ b/net/minecraft/world/level/block/RedStoneWireBlock.java -@@ -242,7 +_,7 @@ - BlockState relativeState = level.getBlockState(relativePos); +@@ -244,7 +_,7 @@ + BlockState blockstate = level.getBlockState(blockpos); if (canConnectUp) { - boolean isPlaceableAbove = relativeState.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(level, relativePos, relativeState); -- if (isPlaceableAbove && shouldConnectTo(level.getBlockState(relativePos.above()))) { -+ if (isPlaceableAbove && level.getBlockState(relativePos.above()).canRedstoneConnectTo(level, relativePos.above(), null)) { - if (relativeState.isFaceSturdy(level, relativePos, direction.getOpposite())) { + boolean flag = blockstate.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(level, blockpos, blockstate); +- if (flag && shouldConnectTo(level.getBlockState(blockpos.above()))) { ++ if (flag && level.getBlockState(blockpos.above()).canRedstoneConnectTo(level, blockpos.above(), null)) { + if (blockstate.isFaceSturdy(level, blockpos, direction.getOpposite())) { return RedstoneSide.UP; } -@@ -251,10 +_,14 @@ +@@ -253,10 +_,14 @@ } } -- return !shouldConnectTo(relativeState, direction) -- && (relativeState.isRedstoneConductor(level, relativePos) || !shouldConnectTo(level.getBlockState(relativePos.below()))) +- return !shouldConnectTo(blockstate, direction) +- && (blockstate.isRedstoneConductor(level, blockpos) || !shouldConnectTo(level.getBlockState(blockpos.below()))) - ? RedstoneSide.NONE - : RedstoneSide.SIDE; -+ if (relativeState.canRedstoneConnectTo(level, relativePos, direction)) { ++ if (blockstate.canRedstoneConnectTo(level, blockpos, direction)) { + return RedstoneSide.SIDE; -+ } else if (relativeState.isRedstoneConductor(level, relativePos)) { ++ } else if (blockstate.isRedstoneConductor(level, blockpos)) { + return RedstoneSide.NONE; + } else { -+ BlockPos blockPosBelow = relativePos.below(); ++ BlockPos blockPosBelow = blockpos.below(); + return level.getBlockState(blockPosBelow).canRedstoneConnectTo(level, blockPosBelow, null) ? RedstoneSide.SIDE : RedstoneSide.NONE; + } } 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 84dea3faff..cc52c409f2 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SaplingBlock.java +++ b/net/minecraft/world/level/block/SaplingBlock.java -@@ -43,6 +_,7 @@ +@@ -44,6 +_,7 @@ @Override protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { 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 5800c0472c..4c76d9a712 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkCatalystBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SculkCatalystBlock.java +++ b/net/minecraft/world/level/block/SculkCatalystBlock.java -@@ -60,8 +_,13 @@ +@@ -59,8 +_,13 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); 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 faaa52905c..51d7f66788 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkSensorBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SculkSensorBlock.java +++ b/net/minecraft/world/level/block/SculkSensorBlock.java -@@ -288,8 +_,13 @@ +@@ -287,8 +_,13 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); 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 a04576377c..4b9bbc3160 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SculkShriekerBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SculkShriekerBlock.java +++ b/net/minecraft/world/level/block/SculkShriekerBlock.java -@@ -127,7 +_,7 @@ +@@ -126,7 +_,7 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); @@ -9,7 +9,7 @@ this.tryDropExperience(level, pos, tool, ConstantInt.of(5)); } } -@@ -141,5 +_,10 @@ +@@ -140,5 +_,10 @@ (innerLevel, pos, state, entity) -> VibrationSystem.Ticker.tick(innerLevel, entity.getVibrationData(), entity.getVibrationUser()) ) : null; diff --git a/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch new file mode 100644 index 0000000000..f8b570e664 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/SeagrassBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/SeagrassBlock.java ++++ b/net/minecraft/world/level/block/SeagrassBlock.java +@@ -24,7 +_,7 @@ + import net.minecraft.world.phys.shapes.VoxelShape; + import org.jspecify.annotations.Nullable; + +-public class SeagrassBlock extends VegetationBlock implements BonemealableBlock, LiquidBlockContainer { ++public class SeagrassBlock extends VegetationBlock implements BonemealableBlock, LiquidBlockContainer, net.minecraftforge.common.IForgeShearable { + public static final MapCodec CODEC = simpleCodec(SeagrassBlock::new); + private static final VoxelShape SHAPE = Block.column(12.0, 0.0, 12.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 f1b8ad2ee5..998f15ccf0 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SoundType.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SoundType.java +++ b/net/minecraft/world/level/block/SoundType.java -@@ -855,6 +_,7 @@ +@@ -831,6 +_,7 @@ private final SoundEvent hitSound; private final SoundEvent fallSound; 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 19424b9a3a..4d8cda0d3b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/SpawnerBlock.java +++ b/net/minecraft/world/level/block/SpawnerBlock.java -@@ -40,10 +_,15 @@ +@@ -39,10 +_,15 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); - if (dropExperience) { + if (false && dropExperience) { // Forge: moved to getExpDrop - RandomSource random = level.getRandom(); - int magicCount = 15 + random.nextInt(15) + random.nextInt(15); - this.popExperience(level, pos, magicCount); + RandomSource randomsource = level.getRandom(); + int i = 15 + randomsource.nextInt(15) + randomsource.nextInt(15); + this.popExperience(level, pos, i); } + } + 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 6adf106c89..0fc44ada10 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 -@@ -52,6 +_,7 @@ +@@ -53,6 +_,7 @@ } private boolean removeWaterBreadthFirstSearch(final Level level, final BlockPos startPos) { + BlockState spongeState = level.getBlockState(startPos); - return BlockPos.breadthFirstTraversal(startPos, 6, 65, (pos, consumer) -> { - for (Direction direction : ALL_DIRECTIONS) { - consumer.accept(pos.relative(direction)); -@@ -62,7 +_,7 @@ - } else { - BlockState state = level.getBlockState(pos); - FluidState fluidState = level.getFluidState(pos); -- if (!fluidState.is(FluidTags.WATER)) { -+ if (!spongeState.canBeHydrated(level, startPos, fluidState, pos)) { - return BlockPos.TraversalNodeStatus.SKIP; - } else if (state.getBlock() instanceof BucketPickup bucketPickup && !bucketPickup.pickupBlock(null, level, pos, state).isEmpty()) { - return BlockPos.TraversalNodeStatus.ACCEPT; + return BlockPos.breadthFirstTraversal( + startPos, + 6, +@@ -68,7 +_,7 @@ + } else { + BlockState blockstate = level.getBlockState(pos); + FluidState fluidstate = level.getFluidState(pos); +- if (!fluidstate.is(FluidTags.WATER)) { ++ if (!spongeState.canBeHydrated(level, startPos, fluidstate, pos)) { + return BlockPos.TraversalNodeStatus.SKIP; + } else if (blockstate.getBlock() instanceof BucketPickup bucketpickup + && !bucketpickup.pickupBlock(null, level, pos, blockstate).isEmpty()) { diff --git a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch index dfb893448b..f662040538 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/SpreadingSnowyBlock.java +++ b/net/minecraft/world/level/block/SpreadingSnowyBlock.java -@@ -52,8 +_,10 @@ - Optional baseBlock = blocks.getOptional(this.baseBlock); - if (!baseBlock.isEmpty()) { +@@ -50,8 +_,10 @@ + Optional optional = registry.getOptional(this.baseBlock); + if (!optional.isEmpty()) { if (!canStayAlive(state, level, pos)) { + if (!level.isAreaLoaded(pos, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading - level.setBlockAndUpdate(pos, baseBlock.get().defaultBlockState()); + level.setBlockAndUpdate(pos, optional.get().defaultBlockState()); } else { + if (!level.isAreaLoaded(pos, 3)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading if (level.getMaxLocalRawBrightness(pos.above()) >= 9) { - BlockState defaultBlockState = this.defaultBlockState(); + 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 f254b11706..24f643571d 100644 --- a/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/StemBlock.java +++ b/net/minecraft/world/level/block/StemBlock.java -@@ -76,14 +_,16 @@ +@@ -77,14 +_,16 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { @@ -12,23 +12,23 @@ protected void randomTick(BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { + if (!level.isAreaLoaded(pos, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light if (level.getRawBrightness(pos, 0) >= 9) { - float growthSpeed = CropBlock.getGrowthSpeed(this, level, pos); -- if (random.nextInt((int)(25.0F / growthSpeed) + 1) == 0) { -+ var vanilla = random.nextInt((int)(25.0F / growthSpeed) + 1) == 0; + float f = CropBlock.getGrowthSpeed(this, level, pos); +- if (random.nextInt((int)(25.0F / f) + 1) == 0) { ++ var vanilla = random.nextInt((int)(25.0F / f) + 1) == 0; + if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { - int age = state.getValue(AGE); - if (age < 7) { - state = state.setValue(AGE, age + 1); -@@ -92,7 +_,7 @@ + int i = state.getValue(AGE); + if (i < 7) { + state = state.setValue(AGE, i + 1); +@@ -93,7 +_,7 @@ Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(random); - BlockPos relative = pos.relative(direction); - BlockState stateBelow = level.getBlockState(relative.below()); -- if (level.getBlockState(relative).isAir() && stateBelow.is(this.fruitSupportBlocks)) { -+ if (level.getBlockState(relative).isAir() && (stateBelow.is(this.fruitSupportBlocks) || stateBelow.getBlock() instanceof FarmlandBlock)) { - Registry blocks = level.registryAccess().lookupOrThrow(Registries.BLOCK); - Optional fruit = blocks.getOptional(this.fruit); - Optional stem = blocks.getOptional(this.attachedStem); -@@ -102,6 +_,7 @@ + BlockPos blockpos = pos.relative(direction); + BlockState blockstate = level.getBlockState(blockpos.below()); +- if (level.getBlockState(blockpos).isAir() && blockstate.is(this.fruitSupportBlocks)) { ++ if (level.getBlockState(blockpos).isAir() && (blockstate.is(this.fruitSupportBlocks) || blockstate.getBlock() instanceof FarmlandBlock)) { + Registry registry = level.registryAccess().lookupOrThrow(Registries.BLOCK); + Optional optional = registry.getOptional(this.fruit); + Optional optional1 = registry.getOptional(this.attachedStem); +@@ -103,6 +_,7 @@ } } } @@ -36,7 +36,7 @@ } } } -@@ -134,5 +_,10 @@ +@@ -135,5 +_,10 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { builder.add(AGE); 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 9da411aa67..f8e563c098 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch @@ -11,15 +11,15 @@ private static final VoxelShape SHAPE = Block.column(12.0, 0.0, 16.0); @@ -57,12 +_,15 @@ - if (height < 3) { - int age = state.getValue(AGE); + if (i < 3) { + int j = state.getValue(AGE); + if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, true)) { - if (age == 15) { + if (j == 15) { level.setBlockAndUpdate(pos.above(), this.defaultBlockState()); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos.above(), this.defaultBlockState()); level.setBlock(pos, state.setValue(AGE, 0), 260); } else { - level.setBlock(pos, state.setValue(AGE, age + 1), 260); + level.setBlock(pos, state.setValue(AGE, j + 1), 260); } + } } @@ -31,18 +31,18 @@ protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { + BlockState soil = level.getBlockState(pos.below()); + if (soil.canSustainPlant(level, pos.below(), Direction.UP, this)) return true; - BlockState stateBelow = level.getBlockState(pos.below()); - if (stateBelow.is(this)) { + BlockState blockstate = level.getBlockState(pos.below()); + if (blockstate.is(this)) { return true; -@@ -98,7 +_,7 @@ - for (Direction direction : Direction.Plane.HORIZONTAL) { - BlockState blockState = level.getBlockState(below.relative(direction)); - FluidState fluidState = level.getFluidState(below.relative(direction)); -- if (fluidState.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockState.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)) { -+ if (fluidState.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockState.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || state.canBeHydrated(level, pos, fluidState, below.relative(direction))) { - return true; +@@ -97,7 +_,7 @@ + for (Direction direction : Direction.Plane.HORIZONTAL) { + BlockState blockstate1 = level.getBlockState(blockpos.relative(direction)); + FluidState fluidstate = level.getFluidState(blockpos.relative(direction)); +- if (fluidstate.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockstate1.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)) { ++ if (fluidstate.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockstate1.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || state.canBeHydrated(level, pos, fluidstate, blockpos.relative(direction))) { + return true; + } } - } @@ -110,5 +_,15 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { 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 1319def1dc..949a436983 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch @@ -3,12 +3,12 @@ @@ -71,10 +_,11 @@ @Override protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - int age = state.getValue(AGE); -- if (age < 3 && random.nextInt(5) == 0 && level.getRawBrightness(pos.above(), 0) >= 9) { -+ if (age < 3 && level.getRawBrightness(pos.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(5) == 0)) { - BlockState newState = state.setValue(AGE, age + 1); - level.setBlock(pos, newState, 2); - level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(newState)); + int i = state.getValue(AGE); +- if (i < 3 && random.nextInt(5) == 0 && level.getRawBrightness(pos.above(), 0) >= 9) { ++ if (i < 3 && level.getRawBrightness(pos.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(5) == 0)) { + BlockState blockstate = state.setValue(AGE, i + 1); + level.setBlock(pos, blockstate, 2); + level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(blockstate)); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } diff --git a/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch new file mode 100644 index 0000000000..ae8704af63 --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/TallGrassBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/TallGrassBlock.java ++++ b/net/minecraft/world/level/block/TallGrassBlock.java +@@ -12,7 +_,7 @@ + import net.minecraft.world.phys.shapes.CollisionContext; + import net.minecraft.world.phys.shapes.VoxelShape; + +-public class TallGrassBlock extends VegetationBlock implements BonemealableBlock { ++public class TallGrassBlock extends VegetationBlock implements BonemealableBlock, net.minecraftforge.common.IForgeShearable { + public static final MapCodec CODEC = simpleCodec(TallGrassBlock::new); + private static final VoxelShape SHAPE = Block.column(12.0, 0.0, 13.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 5536967c13..3aec1d172c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch @@ -27,7 +27,7 @@ } return super.playerWillDestroy(level, pos, state, player); -@@ -80,10 +_,12 @@ +@@ -81,10 +_,12 @@ } } @@ -38,27 +38,27 @@ + @Deprecated //Forge: Prefer using IForgeBlock#onCaughtFire private static boolean prime(final Level level, final BlockPos pos, final @Nullable LivingEntity source) { - if (level instanceof ServerLevel serverLevel && serverLevel.getGameRules().get(GameRules.TNT_EXPLODES)) { - PrimedTnt tnt = new PrimedTnt(level, pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, source); + if (level instanceof ServerLevel serverlevel && serverlevel.getGameRules().get(GameRules.TNT_EXPLODES)) { + PrimedTnt primedtnt = new PrimedTnt(level, pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, source); @@ -110,7 +_,7 @@ + if (!itemStack.is(Items.FLINT_AND_STEEL) && !itemStack.is(Items.FIRE_CHARGE)) { return super.useItemOn(itemStack, state, level, pos, player, hand, hitResult); - } - -- if (prime(level, pos, player)) { -+ if (onCaughtFire(state, level, pos, hitResult.getDirection(), player)) { - level.setBlock(pos, Blocks.AIR.defaultBlockState(), 11); - Item item = itemStack.getItem(); - if (itemStack.is(Items.FLINT_AND_STEEL)) { -@@ -135,7 +_,7 @@ - Entity owner = projectile.getOwner(); + } else { +- if (prime(level, pos, player)) { ++ if (onCaughtFire(state, level, pos, hitResult.getDirection(), player)) { + level.setBlock(pos, Blocks.AIR.defaultBlockState(), 11); + Item item = itemStack.getItem(); + if (itemStack.is(Items.FLINT_AND_STEEL)) { +@@ -136,7 +_,7 @@ + Entity entity = projectile.getOwner(); if (projectile.isOnFire() - && projectile.mayInteract(serverLevel, pos) -- && prime(level, pos, owner instanceof LivingEntity livingEntity ? livingEntity : null)) { -+ && onCaughtFire(state, level, pos, null, owner instanceof LivingEntity livingEntity ? livingEntity : null)) { - level.removeBlock(pos, false); + && projectile.mayInteract(serverlevel, blockpos) +- && prime(level, blockpos, entity instanceof LivingEntity ? (LivingEntity)entity : null)) { ++ && onCaughtFire(state, level, blockpos, null, entity instanceof LivingEntity ? (LivingEntity)entity : null)) { + level.removeBlock(blockpos, false); } } -@@ -149,5 +_,9 @@ +@@ -150,5 +_,9 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { builder.add(UNSTABLE); 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 14dbaea906..4bf4f864d7 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/TrapDoorBlock.java +++ b/net/minecraft/world/level/block/TrapDoorBlock.java -@@ -192,4 +_,14 @@ +@@ -198,4 +_,14 @@ protected BlockSetType getType() { return this.type; } 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 6a3705dd27..d591c0be6b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/TripWireBlock.java +++ b/net/minecraft/world/level/block/TripWireBlock.java -@@ -113,7 +_,7 @@ +@@ -114,7 +_,7 @@ @Override public BlockState playerWillDestroy(final Level level, final BlockPos pos, final BlockState state, final Player player) { diff --git a/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch index 07acf2acd8..c6e9af1307 100644 --- a/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch @@ -21,11 +21,11 @@ @@ -43,6 +_,9 @@ @Override protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { - BlockPos below = pos.below(); + BlockPos blockpos = pos.below(); + if (state.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 level.getBlockState(below).canSustainPlant(level, below, Direction.UP, this); ++ return level.getBlockState(blockpos).canSustainPlant(level, blockpos, Direction.UP, this); + } - return this.mayPlaceOn(level.getBlockState(below), level, below); + return this.mayPlaceOn(level.getBlockState(blockpos), level, blockpos); } @@ -54,5 +_,11 @@ 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 c9fe2eac9c..60710b01a8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch @@ -1,11 +1,20 @@ --- a/net/minecraft/world/level/block/VineBlock.java +++ b/net/minecraft/world/level/block/VineBlock.java -@@ -168,7 +_,7 @@ +@@ -23,7 +_,7 @@ + import net.minecraft.world.phys.shapes.VoxelShape; + import org.jspecify.annotations.Nullable; + +-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; +@@ -166,7 +_,7 @@ @Override protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { if (level.getGameRules().get(GameRules.SPREAD_VINES)) { - if (random.nextInt(4) == 0) { + if (random.nextInt(4) == 0 && level.isAreaLoaded(pos, 4)) { // Forge: check area to prevent loading unloaded chunks - Direction testDirection = Direction.getRandom(random); - BlockPos abovePos = pos.above(); - if (testDirection.getAxis().isHorizontal() && !state.getValue(getPropertyForFace(testDirection))) { + Direction direction = Direction.getRandom(random); + BlockPos blockpos = pos.above(); + if (direction.getAxis().isHorizontal() && !state.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 new file mode 100644 index 0000000000..dd6b57ba4c --- /dev/null +++ b/patches/minecraft/net/minecraft/world/level/block/WebBlock.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/world/level/block/WebBlock.java ++++ b/net/minecraft/world/level/block/WebBlock.java +@@ -11,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); + + @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 e82a4b0746..cf902c3caf 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,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java +++ b/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java -@@ -57,6 +_,7 @@ +@@ -58,6 +_,7 @@ private static final short DEFAULT_COOKING_TOTAL_TIME = 0; private static final short DEFAULT_LIT_TIME_REMAINING = 0; private static final short DEFAULT_LIT_TOTAL_TIME = 0; @@ -8,7 +8,7 @@ protected NonNullList items = NonNullList.withSize(3, ItemStack.EMPTY); private int litTimeRemaining; private int litTotalTime; -@@ -109,6 +_,7 @@ +@@ -114,6 +_,7 @@ ) { super(type, worldPosition, blockState); this.quickCheck = RecipeManager.createCheck(recipeType); @@ -16,7 +16,7 @@ } @Override -@@ -116,10 +_,10 @@ +@@ -121,10 +_,10 @@ super.loadAdditional(input); this.items = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); ContainerHelper.loadAllItems(input, this.items); @@ -31,7 +31,7 @@ this.recipesUsed.clear(); this.recipesUsed.putAll(input.read("RecipesUsed", RECIPES_USED_CODEC).orElse(Map.of())); } -@@ -127,10 +_,10 @@ +@@ -132,10 +_,10 @@ @Override protected void saveAdditional(final ValueOutput output) { super.saveAdditional(output); @@ -46,65 +46,65 @@ ContainerHelper.saveAllItems(output, this.items); output.store("RecipesUsed", RECIPES_USED_CODEC, this.recipesUsed); } -@@ -159,13 +_,13 @@ - if (recipe != null) { - int maxStackSize = entity.getMaxStackSize(); - ItemStack burnResult = recipe.value().assemble(input); -- if (!burnResult.isEmpty() && canBurn(entity.items, maxStackSize, burnResult)) { -+ if (!burnResult.isEmpty() && entity.canBurn(entity.items, maxStackSize, burnResult)) { - if (!isLit) { - int newLitTime = entity.getBurnDuration(level.fuelValues(), fuel); - entity.litTimeRemaining = newLitTime; - entity.litTotalTime = newLitTime; - if (newLitTime > 0) { -- consumeFuel(entity.items, fuel); -+ entity.consumeFuel(entity.items, fuel); - isLit = true; - changed = true; +@@ -164,13 +_,13 @@ + if (recipeholder != null) { + int i = entity.getMaxStackSize(); + ItemStack itemstack2 = recipeholder.value().assemble(singlerecipeinput); +- if (!itemstack2.isEmpty() && canBurn(entity.items, i, itemstack2)) { ++ if (!itemstack2.isEmpty() && entity.canBurn(entity.items, i, itemstack2)) { + if (!flag1) { + int j = entity.getBurnDuration(level.fuelValues(), itemstack); + entity.litTimeRemaining = j; + entity.litTotalTime = j; + if (j > 0) { +- consumeFuel(entity.items, itemstack); ++ entity.consumeFuel(entity.items, itemstack); + flag1 = true; + flag = true; } -@@ -176,7 +_,7 @@ +@@ -181,7 +_,7 @@ if (entity.cookingTimer == entity.cookingTotalTime) { entity.cookingTimer = 0; - entity.cookingTotalTime = recipe.value().cookingTime(); -- burn(entity.items, ingredient, burnResult); -+ entity.burn(entity.items, ingredient, burnResult); - entity.setRecipeUsed(recipe); - changed = true; + entity.cookingTotalTime = recipeholder.value().cookingTime(); +- burn(entity.items, itemstack1, itemstack2); ++ entity.burn(entity.items, itemstack1, itemstack2); + entity.setRecipeUsed(recipeholder); + flag = true; } -@@ -205,16 +_,16 @@ +@@ -210,16 +_,16 @@ } } - private static void consumeFuel(final NonNullList items, final ItemStack fuel) { + protected void consumeFuel(final NonNullList items, final ItemStack fuel) { - Item fuelItem = fuel.getItem(); + Item item = fuel.getItem(); - fuel.shrink(1); - if (fuel.isEmpty()) { -- ItemStackTemplate remainder = fuelItem.getCraftingRemainder(); +- ItemStackTemplate itemstacktemplate = item.getCraftingRemainder(); + if (fuel.count() == 1) { -+ ItemStackTemplate remainder = fuel.getCraftingRemainder(); - items.set(1, remainder != null ? remainder.create() : ItemStack.EMPTY); ++ ItemStackTemplate itemstacktemplate = fuel.getCraftingRemainder(); + items.set(1, itemstacktemplate != null ? itemstacktemplate.create() : ItemStack.EMPTY); } + fuel.shrink(1); } - private static boolean canBurn(final NonNullList items, final int maxStackSize, final ItemStack burnResult) { + protected boolean canBurn(final NonNullList items, final int maxStackSize, final ItemStack burnResult) { - ItemStack resultItemStack = items.get(2); - if (resultItemStack.isEmpty()) { + ItemStack itemstack = items.get(2); + if (itemstack.isEmpty()) { return true; -@@ -229,7 +_,7 @@ - return resultCount <= maxResultCount; +@@ -232,7 +_,7 @@ + } } - private static void burn(final NonNullList items, final ItemStack inputItemStack, final ItemStack result) { + protected void burn(final NonNullList items, final ItemStack inputItemStack, final ItemStack result) { - ItemStack resultItemStack = items.get(2); - if (resultItemStack.isEmpty()) { + ItemStack itemstack = items.get(2); + if (itemstack.isEmpty()) { items.set(2, result.copy()); -@@ -370,6 +_,35 @@ - for (ItemStack itemStack : this.items) { - contents.accountStack(itemStack); +@@ -371,6 +_,35 @@ + for (ItemStack itemstack : this.items) { + contents.accountStack(itemstack); } + } + 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 cab4941038..be4c757c69 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 -@@ -138,8 +_,8 @@ +@@ -141,8 +_,8 @@ - for (int i = 0; i < 10 && checkPos.getY() <= lastSetBlock; i++) { - BlockState state = level.getBlockState(checkPos); -- if (state.getBlock() instanceof BeaconBeamBlock beaconBeamBlock) { -- int color = beaconBeamBlock.getColor().getTextureDiffuseColor(); -+ int color = state.getBeaconColorMultiplier(level, checkPos, pos); -+ if (color != -1) { + for (int i1 = 0; i1 < 10 && blockpos.getY() <= l; i1++) { + BlockState blockstate = level.getBlockState(blockpos); +- if (blockstate.getBlock() instanceof BeaconBeamBlock beaconbeamblock) { +- int j1 = beaconbeamblock.getColor().getTextureDiffuseColor(); ++ int j1 = blockstate.getBeaconColorMultiplier(level, blockpos, pos); ++ if (j1 != -1) { if (entity.checkingBeamSections.size() <= 1) { - lastBeamSection = new BeaconBeamOwner.Section(color); - entity.checkingBeamSections.add(lastBeamSection); + beaconbeamowner$section = new BeaconBeamOwner.Section(j1); + entity.checkingBeamSections.add(beaconbeamowner$section); 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 688d43d928..a427d27062 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,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/BlockEntity.java +++ b/net/minecraft/world/level/block/entity/BlockEntity.java -@@ -38,7 +_,7 @@ +@@ -39,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ private static final Codec> TYPE_CODEC = BuiltInRegistries.BLOCK_ENTITY_TYPE.byNameCodec(); private static final Logger LOGGER = LogUtils.getLogger(); private final BlockEntityType type; -@@ -53,6 +_,7 @@ +@@ -54,6 +_,7 @@ this.worldPosition = worldPosition.immutable(); this.validateBlockState(blockState); this.blockState = blockState; @@ -17,7 +17,7 @@ } private void validateBlockState(final BlockState blockState) { -@@ -62,7 +_,7 @@ +@@ -63,7 +_,7 @@ } public boolean isValidBlockState(final BlockState blockState) { @@ -26,7 +26,7 @@ } public static BlockPos getPosFromTag(final ChunkPos base, final CompoundTag entityTag) { -@@ -93,6 +_,7 @@ +@@ -94,6 +_,7 @@ } protected void loadAdditional(final ValueInput input) { @@ -34,7 +34,7 @@ } public final void loadWithComponents(final ValueInput input) { -@@ -105,6 +_,7 @@ +@@ -106,6 +_,7 @@ } protected void saveAdditional(final ValueOutput output) { @@ -42,7 +42,7 @@ } public final CompoundTag saveWithFullMetadata(final HolderLookup.Provider registries) { -@@ -224,6 +_,13 @@ +@@ -239,6 +_,13 @@ public void setRemoved() { this.remove = true; 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 7bc20415f3..a87441d396 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,28 +1,28 @@ --- a/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java -@@ -177,9 +_,10 @@ - for (int dest = 0; dest < 3; dest++) { - items.set(dest, potionBrewing.mix(ingredient, items.get(dest))); +@@ -180,9 +_,10 @@ + for (int i = 0; i < 3; i++) { + items.set(i, potionbrewing.mix(itemstack, items.get(i))); } + net.minecraftforge.event.ForgeEventFactory.onPotionBrewed(items); -+ ItemStackTemplate remainder = ingredient.getCraftingRemainder(); - ingredient.shrink(1); -- ItemStackTemplate remainder = ingredient.getItem().getCraftingRemainder(); - if (remainder != null) { - if (ingredient.isEmpty()) { - ingredient = remainder.create(); -@@ -218,6 +_,9 @@ ++ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); + itemstack.shrink(1); +- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); + if (itemstacktemplate != null) { + if (itemstack.isEmpty()) { + itemstack = itemstacktemplate.create(); +@@ -221,6 +_,9 @@ if (slot == 3) { - PotionBrewing potionBrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; - return potionBrewing.isIngredient(itemStack); + PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; + return potionbrewing.isIngredient(itemStack); + } else if (slot != 4) { + PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; + return this.getItem(slot).isEmpty() && potionbrewing.isValidInput(itemStack); } else { return slot == 4 ? itemStack.is(ItemTags.BREWING_FUEL) -@@ -248,5 +_,34 @@ +@@ -251,5 +_,34 @@ @Override protected AbstractContainerMenu createMenu(final int containerId, final Inventory inventory) { return new BrewingStandMenu(containerId, inventory, this, this.dataAccess); 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 248134efc3..71820d3a76 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,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/ChestBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ChestBlockEntity.java -@@ -192,4 +_,43 @@ +@@ -202,4 +_,43 @@ Block block = blockState.getBlock(); level.blockEvent(pos, block, 1, current); } 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 9bae0e2987..cc6b2a7fb7 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,13 +1,13 @@ --- a/net/minecraft/world/level/block/entity/ConduitBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ConduitBlockEntity.java -@@ -150,8 +_,8 @@ - BlockPos testPos = worldPosition.offset(ox, oy, oz); - BlockState testBlock = level.getBlockState(testPos); +@@ -148,8 +_,8 @@ + BlockPos blockpos1 = worldPosition.offset(j1, k1, l1); + BlockState blockstate = level.getBlockState(blockpos1); -- for (Block type : VALID_BLOCKS) { -- if (testBlock.is(type)) { +- for (Block block : VALID_BLOCKS) { +- if (blockstate.is(block)) { + { -+ if (testBlock.isConduitFrame(level, testPos, worldPosition)) { - effectBlocks.add(testPos); ++ if (blockstate.isConduitFrame(level, blockpos1, worldPosition)) { + effectBlocks.add(blockpos1); } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch index 405f8ffafc..4d99d967ce 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/FuelValues.java +++ b/net/minecraft/world/level/block/entity/FuelValues.java -@@ -24,7 +_,11 @@ +@@ -25,7 +_,11 @@ } public boolean isFuel(final ItemStack itemStack) { @@ -13,7 +13,7 @@ } public SequencedSet fuelItems() { -@@ -32,7 +_,16 @@ +@@ -33,7 +_,16 @@ } public int burnDuration(final ItemStack itemStack) { diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java.patch index 7a66fc7704..e56b943f39 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java +++ b/net/minecraft/world/level/block/entity/HangingSignBlockEntity.java @@ -13,6 +_,10 @@ - super(BlockEntityTypes.HANGING_SIGN, worldPosition, blockState); + super(BlockEntityType.HANGING_SIGN, worldPosition, blockState); } + public HangingSignBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { 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 1854dd3606..b3fdae3c79 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 @@ -14,10 +14,10 @@ public static boolean suckInItems(final Level level, final Hopper hopper) { + Boolean ret = net.minecraftforge.items.VanillaInventoryCodeHooks.extractHook(level, hopper); + if (ret != null) return ret; - BlockPos blockPos = BlockPos.containing(hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ()); - BlockState blockState = level.getBlockState(blockPos); - Container container = getSourceContainer(level, hopper, blockPos, blockState); -@@ -454,5 +_,14 @@ + BlockPos blockpos = BlockPos.containing(hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ()); + BlockState blockstate = level.getBlockState(blockpos); + Container container = getSourceContainer(level, hopper, blockpos, blockstate); +@@ -452,5 +_,14 @@ @Override protected AbstractContainerMenu createMenu(final int containerId, final Inventory inventory) { return new HopperMenu(containerId, inventory, this); 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 e1909e1b8b..c702df30ae 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 @@ -20,4 +20,4 @@ + return new net.minecraftforge.items.wrapper.SidedInvWrapper(this, Direction.UP); } - public 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 70241aed4a..cc6abc4d65 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,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/SignBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SignBlockEntity.java -@@ -275,6 +_,11 @@ +@@ -274,6 +_,11 @@ } } 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 caf9bdce3c..2ddd14150f 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,7 +1,7 @@ --- a/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java -@@ -32,6 +_,13 @@ - level.sendBlockUpdated(pos, state, state, 260); +@@ -37,6 +_,13 @@ + level.sendBlockUpdated(pos, blockstate, blockstate, 260); } } + 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 264e201f4d..1381d170a6 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 -@@ -131,6 +_,9 @@ - .lookupOrThrow(Registries.CONFIGURED_FEATURE) - .get(megaFeatureKey) - .orElse(null); -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, featureHolder); -+ featureHolder = event.getFeature(); +@@ -128,6 +_,9 @@ + ResourceKey> resourcekey = this.getConfiguredMegaFeature(random); + if (resourcekey != null) { + Holder> holder = level.registryAccess().lookupOrThrow(Registries.CONFIGURED_FEATURE).get(resourcekey).orElse(null); ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, holder); ++ holder = event.getFeature(); + if (event.getResult().isDenied()) return false; - if (featureHolder != null) { - for (int dx = 0; dx >= -1; dx--) { - for (int dz = 0; dz >= -1; dz--) { + 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 2cfc4dc425..6ce710b0c8 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,30 +1,30 @@ --- a/net/minecraft/world/level/block/piston/PistonBaseBlock.java +++ b/net/minecraft/world/level/block/piston/PistonBaseBlock.java -@@ -164,6 +_,7 @@ +@@ -169,6 +_,7 @@ - RandomSource random = level.getRandom(); + RandomSource randomsource = level.getRandom(); if (b0 == 0) { + if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(level, pos, direction, true)) return false; if (!this.moveBlocks(level, pos, direction, true)) { return false; } -@@ -172,6 +_,7 @@ - level.playSound(null, pos, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, random.nextFloat() * 0.25F + 0.6F); - level.gameEvent(GameEvent.BLOCK_ACTIVATE, pos, GameEvent.Context.of(extendedState)); +@@ -177,6 +_,7 @@ + level.playSound(null, pos, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, randomsource.nextFloat() * 0.25F + 0.6F); + level.gameEvent(GameEvent.BLOCK_ACTIVATE, pos, GameEvent.Context.of(blockstate)); } else if (b0 == 1 || b0 == 2) { + if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(level, pos, direction, false)) return false; - if (level.getBlockEntity(pos.relative(direction)) instanceof PistonMovingBlockEntity pistonMovingBlockEntity) { - pistonMovingBlockEntity.finalTick(); - } -@@ -220,6 +_,7 @@ - level.gameEvent(GameEvent.BLOCK_DEACTIVATE, pos, GameEvent.Context.of(movingPistonState)); + BlockEntity blockentity = level.getBlockEntity(pos.relative(direction)); + if (blockentity instanceof PistonMovingBlockEntity) { + ((PistonMovingBlockEntity)blockentity).finalTick(); +@@ -226,6 +_,7 @@ + level.gameEvent(GameEvent.BLOCK_DEACTIVATE, pos, GameEvent.Context.of(blockstate1)); } + net.minecraftforge.event.ForgeEventFactory.onPistonMovePost(level, pos, direction, (b0 == 0)); return true; } -@@ -376,6 +_,11 @@ +@@ -377,6 +_,11 @@ @Override protected BlockState rotate(final BlockState state, final Rotation rotation) { return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); 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 8f66434ff9..013a0b0852 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 @@ -126,7 +_,7 @@ - List entities = level.getEntities(null, PistonMath.getMovementArea(aabb, movement, deltaProgress).minmax(aabb)); - if (!entities.isEmpty()) { - List shapeAabbs = shape.toAabbs(); -- boolean causeBounce = self.movedState.is(Blocks.SLIME_BLOCK); -+ boolean causeBounce = self.movedState.isSlimeBlock(); - Iterator var12 = entities.iterator(); + List list = level.getEntities(null, PistonMath.getMovementArea(aabb, direction, d0).minmax(aabb)); + if (!list.isEmpty()) { + List list1 = voxelshape.toAabbs(); +- boolean flag = self.movedState.is(Blocks.SLIME_BLOCK); ++ boolean flag = self.movedState.isSlimeBlock(); + Iterator iterator = list.iterator(); 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 929b482de9..8a68473bd0 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,15 +1,15 @@ --- a/net/minecraft/world/level/block/piston/PistonStructureResolver.java +++ b/net/minecraft/world/level/block/piston/PistonStructureResolver.java -@@ -52,7 +_,7 @@ - +@@ -50,7 +_,7 @@ + } else { for (int i = 0; i < this.toPush.size(); i++) { - BlockPos pos = this.toPush.get(i); -- if (isSticky(this.level.getBlockState(pos)) && !this.addBranchingBlocks(pos)) { -+ if (this.level.getBlockState(pos).isStickyBlock() && !this.addBranchingBlocks(pos)) { + 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; } } -@@ -61,21 +_,9 @@ +@@ -59,21 +_,9 @@ } } @@ -26,42 +26,42 @@ - } - private boolean addBlockLine(final BlockPos start, final Direction direction) { - BlockState nextState = this.level.getBlockState(start); -- if (nextState.isAir()) { + BlockState blockstate = this.level.getBlockState(start); +- if (blockstate.isAir()) { + if (level.isEmptyBlock(start)) { return true; - } + } else if (!PistonBaseBlock.isPushable(blockstate, this.level, start, this.pushDirection, false, direction)) { + return true; +@@ -86,12 +_,12 @@ + if (i + this.toPush.size() > 12) { + return false; + } else { +- while (isSticky(blockstate)) { ++ while (blockstate.isStickyBlock()) { + BlockPos blockpos = start.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 @@ -@@ -96,12 +_,12 @@ - return false; - } - -- while (isSticky(nextState)) { -+ while (nextState.isStickyBlock()) { - BlockPos pos = start.relative(this.pushDirection.getOpposite(), blockCount); - BlockState previousState = nextState; - nextState = this.level.getBlockState(pos); - if (nextState.isAir() -- || !canStickToEachOther(previousState, nextState) -+ || !(previousState.canStickTo(nextState) && nextState.canStickTo(previousState)) - || !PistonBaseBlock.isPushable(nextState, this.level, pos, this.pushDirection, false, this.pushDirection.getOpposite()) - || pos.equals(this.pistonPos)) { - break; -@@ -129,7 +_,7 @@ - - for (int j = 0; j <= collisionPos + blocksAdded; j++) { - BlockPos blockPos = this.toPush.get(j); -- if (isSticky(this.level.getBlockState(blockPos)) && !this.addBranchingBlocks(blockPos)) { -+ if (this.level.getBlockState(blockPos).isStickyBlock() && !this.addBranchingBlocks(blockPos)) { - return false; - } - } -@@ -181,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 neighbourPos = fromPos.relative(direction); - BlockState neighbourState = this.level.getBlockState(neighbourPos); -- if (canStickToEachOther(neighbourState, fromState) && !this.addBlockLine(neighbourPos, direction)) { -+ if (neighbourState.canStickTo(fromState) && fromState.canStickTo(neighbourState) && !this.addBlockLine(neighbourPos, direction)) { + BlockPos blockpos = fromPos.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 4017a55bf9..31425e5253 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,16 +1,16 @@ --- a/net/minecraft/world/level/block/state/BlockBehaviour.java +++ b/net/minecraft/world/level/block/state/BlockBehaviour.java -@@ -178,7 +_,7 @@ +@@ -181,7 +_,7 @@ if (!state.isAir() && explosion.getBlockInteraction() != Explosion.BlockInteraction.TRIGGER_BLOCK) { Block block = state.getBlock(); - boolean doDropExperienceHack = explosion.getIndirectSourceEntity() instanceof Player; + boolean flag = explosion.getIndirectSourceEntity() instanceof Player; - if (block.dropFromExplosion(explosion)) { + if (state.canDropFromExplosion(level, pos, explosion)) { - BlockEntity blockEntity = state.hasBlockEntity() ? level.getBlockEntity(pos) : null; - LootParams.Builder params = new LootParams.Builder(level) + BlockEntity blockentity = state.hasBlockEntity() ? level.getBlockEntity(pos) : null; + LootParams.Builder lootparams$builder = new LootParams.Builder(level) .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos)) -@@ -193,8 +_,7 @@ - state.getDrops(params).forEach(stack -> onHit.accept(stack, pos)); +@@ -196,8 +_,7 @@ + state.getDrops(lootparams$builder).forEach(stack -> onHit.accept(stack, pos)); } - level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); @@ -19,14 +19,15 @@ } } -@@ -352,11 +_,14 @@ +@@ -358,12 +_,15 @@ + if (f == -1.0F) { return 0.0F; + } else { +- int i = player.hasCorrectToolForDrops(state) ? 30 : 100; +- return player.getDestroySpeed(state) / f / i; ++ int i = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(state, player) ? 30 : 100; ++ return player.getDestroySpeed(state, pos) / f / (float)i; } - -- int modifier = player.hasCorrectToolForDrops(state) ? 30 : 100; -- return player.getDestroySpeed(state) / destroySpeed / modifier; -+ int modifier = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(state, player) ? 30 : 100; -+ return player.getDestroySpeed(state, pos) / destroySpeed / (float)modifier; } protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { @@ -36,7 +37,7 @@ } protected void attack(final BlockState state, final Level level, final BlockPos pos, final Player player) { -@@ -407,6 +_,8 @@ +@@ -406,6 +_,8 @@ return this.isRandomlyTicking; } @@ -45,7 +46,7 @@ protected SoundType getSoundType(final BlockState state) { return this.soundType; } -@@ -427,6 +_,10 @@ +@@ -426,6 +_,10 @@ return this.properties.destroyTime; } @@ -56,7 +57,7 @@ public abstract static class BlockStateBase extends StateHolder implements TypedInstance { private static final Direction[] DIRECTIONS = Direction.values(); private static final VoxelShape[] EMPTY_OCCLUSION_SHAPES = Util.make(new VoxelShape[DIRECTIONS.length], s -> Arrays.fill(s, Shapes.empty())); -@@ -582,12 +_,14 @@ +@@ -577,12 +_,14 @@ return this.useShapeForLightOcclusion; } @@ -72,7 +73,7 @@ } public boolean ignitedByLava() { -@@ -600,9 +_,11 @@ +@@ -595,9 +_,11 @@ } public MapColor getMapColor(final BlockGetter level, final BlockPos pos) { @@ -85,7 +86,7 @@ public BlockState rotate(final Rotation rotation) { return this.getBlock().rotate(this.asState(), rotation); } -@@ -660,6 +_,8 @@ +@@ -651,6 +_,8 @@ } public PushReaction getPistonPushReaction() { @@ -94,7 +95,7 @@ return this.pushReaction; } -@@ -1013,7 +_,7 @@ +@@ -1005,7 +_,7 @@ private BlockBehaviour.StateArgumentPredicate> isValidSpawn = (state, level, pos, entityType) -> state.isFaceSturdy( level, pos, Direction.UP ) 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 55fbda9d78..9c38e0a8c9 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch @@ -13,27 +13,27 @@ + } + + public void findBlocks(final java.util.function.BiPredicate predicate, final BiConsumer consumer) { - BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - for (int sectionY = this.getMinSectionY(); sectionY <= this.getMaxSectionY(); sectionY++) { - LevelChunkSection section = this.getSection(this.getSectionIndexFromSectionY(sectionY)); -- if (section.maybeHas(predicate)) { -+ if (section.maybeHas(state -> predicate.test(state, BlockPos.ZERO))) { - BlockPos origin = SectionPos.of(this.chunkPos, sectionY).origin(); + for (int i = this.getMinSectionY(); i <= this.getMaxSectionY(); i++) { + LevelChunkSection levelchunksection = this.getSection(this.getSectionIndexFromSectionY(i)); +- if (levelchunksection.maybeHas(predicate)) { ++ if (levelchunksection.maybeHas(state -> predicate.test(state, BlockPos.ZERO))) { + BlockPos blockpos = SectionPos.of(this.chunkPos, i).origin(); - for (int y = 0; y < 16; y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - BlockState state = section.getBlockState(x, y, z); -- if (predicate.test(state)) { -- consumer.accept(mutablePos.setWithOffset(origin, x, y, z), state); -+ mutablePos.setWithOffset(origin, x, y, z); -+ if (predicate.test(state, mutablePos.immutable())) { -+ consumer.accept(mutablePos, state); + 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 (predicate.test(blockstate)) { +- consumer.accept(blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k), blockstate); ++ blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k); ++ if (predicate.test(blockstate, blockpos$mutableblockpos.immutable())) { ++ consumer.accept(blockpos$mutableblockpos, blockstate); } } } -@@ -499,5 +_,9 @@ +@@ -493,5 +_,9 @@ } public record PackedTicks(List> blocks, List> fluids) { 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 3de8c270aa..a814638c00 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/chunk/LevelChunk.java +++ b/net/minecraft/world/level/chunk/LevelChunk.java -@@ -63,7 +_,7 @@ +@@ -64,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final TickingBlockEntity NULL_TICKER = new TickingBlockEntity() { @Override -@@ -123,6 +_,7 @@ +@@ -124,6 +_,7 @@ this.postLoad = postLoad; this.blockTicks = blockTicks; this.fluidTicks = fluidTicks; @@ -17,39 +17,39 @@ } public LevelChunk(final ServerLevel level, final ProtoChunk protoChunk, final LevelChunk.@Nullable PostLoadProcessor postLoad) { -@@ -323,7 +_,7 @@ - return null; - } +@@ -321,7 +_,7 @@ + if (!levelchunksection.getBlockState(j, k, l).is(block)) { + return null; + } else { +- if (!this.level.isClientSide() && (flags & 512) == 0) { ++ if (!this.level.isClientSide() && (flags & 512) == 0 && !this.level.captureBlockSnapshots) { + state.onPlace(this.level, pos, blockstate, flag2); + } -- if (!this.level.isClientSide() && (flags & 512) == 0) { -+ if (!this.level.isClientSide() && (flags & 512) == 0 && !this.level.captureBlockSnapshots) { - state.onPlace(this.level, pos, oldState, movedByPiston); - } - -@@ -367,6 +_,12 @@ +@@ -368,6 +_,12 @@ public @Nullable BlockEntity getBlockEntity(final BlockPos pos, final LevelChunk.EntityCreationType creationType) { - BlockEntity blockEntity = this.blockEntities.get(pos); + BlockEntity blockentity = this.blockEntities.get(pos); + -+ if (blockEntity != null && blockEntity.isRemoved()) { ++ if (blockentity != null && blockentity.isRemoved()) { + blockEntities.remove(pos); -+ blockEntity = null; ++ blockentity = null; + } + - if (blockEntity == null) { - CompoundTag tag = this.pendingBlockEntities.remove(pos); - if (tag != null) { -@@ -384,9 +_,6 @@ - this.addAndRegisterBlockEntity(blockEntity); + if (blockentity == null) { + CompoundTag compoundtag = this.pendingBlockEntities.remove(pos); + if (compoundtag != null) { +@@ -385,9 +_,6 @@ + this.addAndRegisterBlockEntity(blockentity); } } -- } else if (blockEntity.isRemoved()) { +- } else if (blockentity.isRemoved()) { - this.blockEntities.remove(pos); - return null; } - return blockEntity; -@@ -401,6 +_,7 @@ + return blockentity; +@@ -402,6 +_,7 @@ this.level.onBlockEntityAdded(blockEntity); this.updateBlockEntityTicker(blockEntity); @@ -57,31 +57,34 @@ } } -@@ -452,9 +_,14 @@ +@@ -453,9 +_,14 @@ public @Nullable CompoundTag getBlockEntityNbtForSaving(final BlockPos blockPos, final HolderLookup.Provider registryAccess) { - BlockEntity blockEntity = this.getBlockEntity(blockPos); - if (blockEntity != null && !blockEntity.isRemoved()) { + BlockEntity blockentity = this.getBlockEntity(blockPos); + if (blockentity != null && !blockentity.isRemoved()) { + try { - CompoundTag result = blockEntity.saveWithFullMetadata(this.level.registryAccess()); - result.putBoolean("keepPacked", false); - return result; + 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); ++ 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; + } - } - - CompoundTag result = this.pendingBlockEntities.get(blockPos); -@@ -534,7 +_,7 @@ - blockEntities.accept((pos, type, tag) -> { - BlockEntity blockEntity = this.getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); - if (blockEntity != null && tag != null && blockEntity.getType() == type) { -- blockEntity.loadWithComponents(TagValueInput.create(reporter.forChild(blockEntity.problemPath()), this.level.registryAccess(), tag)); -+ blockEntity.handleUpdateTag(TagValueInput.create(reporter.forChild(blockEntity.problemPath()), this.level.registryAccess(), tag), this.level.registryAccess()); + } else { + CompoundTag compoundtag = this.pendingBlockEntities.get(blockPos); + if (compoundtag != null) { +@@ -537,9 +_,10 @@ + (pos, type, tag) -> { + BlockEntity blockentity = this.getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + if (blockentity != null && tag != null && blockentity.getType() == type) { +- blockentity.loadWithComponents( ++ var input = ( + TagValueInput.create(problemreporter$scopedcollector.forChild(blockentity.problemPath()), this.level.registryAccess(), tag) + ); ++ blockentity.handleUpdateTag(input, this.level.registryAccess()); + } } - }); - } -@@ -673,6 +_,7 @@ + ); +@@ -679,6 +_,7 @@ } public void clearAllBlockEntities() { @@ -89,15 +92,15 @@ this.blockEntities.values().forEach(BlockEntity::setRemoved); this.blockEntities.clear(); this.tickersInLevel.values().forEach(ticker -> ticker.rebind(NULL_TICKER)); -@@ -680,6 +_,7 @@ +@@ -686,6 +_,7 @@ } public void registerAllBlockEntitiesAfterLevelLoad() { + this.level.addFreshBlockEntities(this.blockEntities.values()); this.blockEntities.values().forEach(blockEntity -> { - if (this.level instanceof ServerLevel serverLevel) { - this.addGameEventListener(blockEntity, serverLevel); -@@ -725,6 +_,24 @@ + if (this.level instanceof ServerLevel serverlevel) { + this.addGameEventListener(blockEntity, serverlevel); +@@ -738,6 +_,24 @@ return new LevelChunk.BoundTickingBlockEntity<>(blockEntity, ticker); } @@ -122,27 +125,27 @@ private class BoundTickingBlockEntity implements TickingBlockEntity { private final T blockEntity; private final BlockEntityTicker ticker; -@@ -742,6 +_,7 @@ - if (LevelChunk.this.isTicking(pos)) { +@@ -757,6 +_,7 @@ + if (LevelChunk.this.isTicking(blockpos)) { try { - ProfilerFiller profiler = Profiler.get(); + ProfilerFiller profilerfiller = Profiler.get(); + net.minecraftforge.server.timings.TimeTracker.BLOCK_ENTITY_UPDATE.trackStart(blockEntity); - profiler.push(this::getType); - BlockState blockState = LevelChunk.this.getBlockState(pos); - if (this.blockEntity.getType().isValid(blockState)) { -@@ -763,6 +_,11 @@ - CrashReport report = CrashReport.forThrowable(t, "Ticking block entity"); - CrashReportCategory category = report.addCategory("Block entity being ticked"); - this.blockEntity.fillCrashReportCategory(category); + profilerfiller.push(this::getType); + BlockState blockstate = LevelChunk.this.getBlockState(blockpos); + if (this.blockEntity.getType().isValid(blockstate)) { +@@ -778,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("{}", report.getFriendlyReport(net.minecraft.ReportType.CRASH)); ++ LOGGER.error("{}", crashreport.getFriendlyReport(net.minecraft.ReportType.CRASH)); + blockEntity.setRemoved(); + LevelChunk.this.removeBlockEntity(blockEntity.getBlockPos()); + } else - throw new ReportedException(report); + throw new ReportedException(crashreport); } } -@@ -836,6 +_,33 @@ +@@ -851,6 +_,33 @@ public String toString() { return this.ticker + " "; } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch index 71dc0443e4..1bad85c6fd 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java +++ b/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java -@@ -201,9 +_,15 @@ - levelChunk.setFullStatus(holder::getFullStatus); - levelChunk.runPostLoad(); - levelChunk.setLoaded(true); -+ try { -+ holder.currentlyLoading = levelChunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. - levelChunk.registerAllBlockEntitiesAfterLevelLoad(); - levelChunk.registerTickContainerInLevel(level); - levelChunk.setUnsavedListener(context.unsavedListener()); -+ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelChunk, !(protoChunk instanceof ImposterProtoChunk)); -+ } finally { -+ holder.currentlyLoading = null; // Forge - Stop bypassing the future chain. -+ } - return levelChunk; - }, context.mainThreadExecutor()); - } +@@ -215,9 +_,15 @@ + levelchunk.setFullStatus(generationchunkholder::getFullStatus); + levelchunk.runPostLoad(); + levelchunk.setLoaded(true); ++ try { ++ generationchunkholder.currentlyLoading = levelchunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. + levelchunk.registerAllBlockEntitiesAfterLevelLoad(); + levelchunk.registerTickContainerInLevel(serverlevel); + levelchunk.setUnsavedListener(context.unsavedListener()); ++ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelchunk, !(protochunk instanceof ImposterProtoChunk)); ++ } finally { ++ generationchunkholder.currentlyLoading = null; // Forge - Stop bypassing the future chain. ++ } + return levelchunk; + }, + context.mainThreadExecutor() 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 3a32c4b84a..55f8e8d5f3 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,16 +1,16 @@ --- a/net/minecraft/world/level/chunk/storage/EntityStorage.java +++ b/net/minecraft/world/level/chunk/storage/EntityStorage.java -@@ -94,9 +_,13 @@ - ListTag entities = new ListTag(); - chunk.getEntities().forEach(e -> { - TagValueOutput output = TagValueOutput.createWithContext(reporter.forChild(e.problemPath()), e.registryAccess()); -+ try { - if (e.save(output)) { - CompoundTag result = output.buildResult(); - entities.add(result); -+ } -+ } catch (Exception exception) { -+ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", e.getType(), exception); - } - }); - CompoundTag chunkTag = NbtUtils.addCurrentDataVersion(new CompoundTag()); +@@ -108,9 +_,13 @@ + TagValueOutput tagvalueoutput = TagValueOutput.createWithContext( + problemreporter$scopedcollector.forChild(e.problemPath()), e.registryAccess() + ); ++ try { + if (e.save(tagvalueoutput)) { + CompoundTag compoundtag1 = tagvalueoutput.buildResult(); + listtag.add(compoundtag1); ++ } ++ } catch (Exception exception) { ++ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", e.getType(), exception); + } + } + ); diff --git a/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch b/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch index d20866b88c..12e2a5402f 100644 --- a/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch +++ b/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/dimension/end/EnderDragonFight.java +++ b/net/minecraft/world/level/dimension/end/EnderDragonFight.java -@@ -580,6 +_,14 @@ +@@ -586,6 +_,14 @@ } } 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 02b0eda36e..f7431c229d 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/entity/PersistentEntitySectionManager.java +++ b/net/minecraft/world/level/entity/PersistentEntitySectionManager.java -@@ -71,7 +_,18 @@ +@@ -72,7 +_,18 @@ return this.addEntity(entity, false); } @@ -18,19 +18,19 @@ + private boolean addEntityWithoutEvent(final T entity, final boolean loaded) { if (!this.addEntityUuid(entity)) { return false; - } + } else { @@ -93,6 +_,10 @@ - this.startTicking(entity); - } + this.startTicking(entity); + } + if (entity instanceof Entity) { + ((Entity)entity).onAddedToLevel(); + } + - return true; + return true; + } } - -@@ -369,11 +_,13 @@ +@@ -370,6 +_,7 @@ private class Callback implements EntityInLevelCallback { private final T entity; @@ -38,22 +38,24 @@ private long currentSectionKey; private EntitySection currentSection; - private Callback(final T entity, final long currentSectionKey, final EntitySection currentSection) { +@@ -377,6 +_,7 @@ + Objects.requireNonNull(PersistentEntitySectionManager.this); + super(); this.entity = entity; + this.realEntity = entity instanceof Entity e ? e : null; this.currentSectionKey = currentSectionKey; this.currentSection = currentSection; } -@@ -392,9 +_,13 @@ +@@ -395,9 +_,13 @@ PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection newSection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(newSectionPos); - newSection.add(this.entity); + EntitySection entitysection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(i); + entitysection.add(this.entity); + long oldSectionKey = currentSectionKey; - this.currentSection = newSection; - this.currentSectionKey = newSectionPos; - this.updateStatus(previousStatus, newSection.getStatus()); + this.currentSection = entitysection; + this.currentSectionKey = i; + this.updateStatus(visibility, entitysection.getStatus()); + if (this.realEntity != null) { -+ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, newSectionPos); ++ 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 2c05951f46..63426b7617 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/entity/TransientEntitySectionManager.java +++ b/net/minecraft/world/level/entity/TransientEntitySectionManager.java -@@ -82,11 +_,13 @@ +@@ -83,6 +_,7 @@ private class Callback implements EntityInLevelCallback { private final T entity; @@ -8,27 +8,29 @@ private long currentSectionKey; private EntitySection currentSection; - private Callback(final T entity, final long currentSectionKey, final EntitySection currentSection) { +@@ -90,6 +_,7 @@ + Objects.requireNonNull(TransientEntitySectionManager.this); + super(); this.entity = entity; + this.realEntity = entity instanceof Entity ? (Entity)entity : null; this.currentSectionKey = currentSectionKey; this.currentSection = currentSection; } -@@ -105,6 +_,7 @@ +@@ -108,6 +_,7 @@ TransientEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection newSection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(newSectionPos); - newSection.add(this.entity); + EntitySection entitysection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(i); + entitysection.add(this.entity); + long oldSectionKey = currentSectionKey; - this.currentSection = newSection; - this.currentSectionKey = newSectionPos; + this.currentSection = entitysection; + this.currentSectionKey = i; TransientEntitySectionManager.this.callbacks.onSectionChange(this.entity); -@@ -116,6 +_,9 @@ - } else if (!wasTicking && isTicking) { +@@ -119,6 +_,9 @@ + } else if (!flag && flag1) { TransientEntitySectionManager.this.callbacks.onTickingStart(this.entity); } + } + if (this.realEntity != null) { -+ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, newSectionPos); ++ 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 7f345cfec7..81292972f6 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch @@ -2,13 +2,13 @@ +++ b/net/minecraft/world/level/levelgen/Beardifier.java @@ -52,6 +_,11 @@ - for (StructurePiece piece : start.getPieces()) { - if (piece.isCloseToChunk(chunkPos, 12)) { -+ if (piece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { -+ if (pieceBeardifierModifier.getTerrainAdjustment() != TerrainAdjustment.NONE) { -+ rigids.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); -+ } -+ } else - if (piece instanceof PoolElementStructurePiece poolPiece) { - StructureTemplatePool.Projection projection = poolPiece.getElement().getProjection(); - if (projection == StructureTemplatePool.Projection.RIGID) { + for (StructurePiece structurepiece : structurestart.getPieces()) { + if (structurepiece.isCloseToChunk(chunkPos, 12)) { ++ if (structurepiece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { ++ if (pieceBeardifierModifier.getTerrainAdjustment() != TerrainAdjustment.NONE) { ++ list1.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); ++ } ++ } else + if (structurepiece instanceof PoolElementStructurePiece poolelementstructurepiece) { + StructureTemplatePool.Projection structuretemplatepool$projection = poolelementstructurepiece.getElement().getProjection(); + if (structuretemplatepool$projection == StructureTemplatePool.Projection.RIGID) { 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 bf5d375d8f..bdcd391b23 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/DebugLevelSource.java +++ b/net/minecraft/world/level/levelgen/DebugLevelSource.java -@@ -140,4 +_,10 @@ +@@ -142,4 +_,10 @@ public int getSeaLevel() { return 63; } 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 7f39b11522..61aa7eb110 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/world/level/levelgen/PhantomSpawner.java +++ b/net/minecraft/world/level/levelgen/PhantomSpawner.java @@ -33,13 +_,18 @@ - for (ServerPlayer player : level.players()) { - if (!player.isSpectator()) { - BlockPos playerPos = player.blockPosition(); -- if (!level.dimensionType().hasSkyLight() || playerPos.getY() >= level.getSeaLevel() && level.canSeeSky(playerPos)) { - DifficultyInstance difficulty = level.getCurrentDifficultyAt(playerPos); -+ var vanillaPosition = (!level.dimensionType().hasSkyLight() || playerPos.getY() >= level.getSeaLevel() && level.canSeeSky(playerPos)); -+ var count = 1 + random.nextInt(difficulty.getDifficulty().getId() + 1); -+ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnPhantom(player, count); + for (ServerPlayer serverplayer : level.players()) { + if (!serverplayer.isSpectator()) { + BlockPos blockpos = serverplayer.blockPosition(); +- if (!level.dimensionType().hasSkyLight() || blockpos.getY() >= level.getSeaLevel() && level.canSeeSky(blockpos)) { + DifficultyInstance difficultyinstance = level.getCurrentDifficultyAt(blockpos); ++ var vanillaPosition = (!level.dimensionType().hasSkyLight() || blockpos.getY() >= level.getSeaLevel() && level.canSeeSky(blockpos)); ++ var count = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnPhantom(serverplayer, count); + var eventResult = event.getResult(); + if (eventResult.isDenied()) continue; + if (vanillaPosition || eventResult.isAllowed()) { - if (difficulty.isHarderThan(random.nextFloat() * 3.0F)) { - ServerStatsCounter stats = player.getStats(); - int value = Mth.clamp(stats.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); - int dayLength = 24000; -- if (random.nextInt(value) >= 72000) { -+ if (eventResult.isAllowed() || random.nextInt(value) >= 72000) { - BlockPos spawnPos = playerPos.above(20 + random.nextInt(15)) - .east(-10 + random.nextInt(21)) - .south(-10 + random.nextInt(21)); + if (difficultyinstance.isHarderThan(randomsource.nextFloat() * 3.0F)) { + ServerStatsCounter serverstatscounter = serverplayer.getStats(); + int i = Mth.clamp(serverstatscounter.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); + int j = 24000; +- if (randomsource.nextInt(i) >= 72000) { ++ if (eventResult.isAllowed() || randomsource.nextInt(i) >= 72000) { + BlockPos blockpos1 = blockpos.above(20 + randomsource.nextInt(15)) + .east(-10 + randomsource.nextInt(21)) + .south(-10 + randomsource.nextInt(21)); @@ -47,7 +_,7 @@ - FluidState fluidState = level.getFluidState(spawnPos); - if (NaturalSpawner.isValidEmptySpawnBlock(level, spawnPos, blockState, fluidState, EntityTypes.PHANTOM)) { - SpawnGroupData groupData = null; -- int groupSize = 1 + random.nextInt(difficulty.getDifficulty().getId() + 1); -+ int groupSize = event.getPhantomsToSpawn(); + FluidState fluidstate = level.getFluidState(blockpos1); + if (NaturalSpawner.isValidEmptySpawnBlock(level, blockpos1, blockstate, fluidstate, EntityType.PHANTOM)) { + SpawnGroupData spawngroupdata = null; +- int k = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); ++ int k = event.getPhantomsToSpawn(); - for (int i = 0; i < groupSize; i++) { - Phantom phantom = EntityTypes.PHANTOM.create(level, EntitySpawnReason.NATURAL); + for (int l = 0; l < k; l++) { + Phantom phantom = EntityType.PHANTOM.create(level, EntitySpawnReason.NATURAL); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch index be4ef92502..01c1b2026a 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/WorldDimensions.java +++ b/net/minecraft/world/level/levelgen/WorldDimensions.java -@@ -36,7 +_,7 @@ +@@ -37,7 +_,7 @@ public record WorldDimensions(Map, LevelStem> dimensions) { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec( 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 23d9227307..0663badd03 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,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java +++ b/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java -@@ -129,6 +_,6 @@ +@@ -131,6 +_,6 @@ } private EntityType randomEntityId(final RandomSource random) { 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 eee77ce551..6355a3511c 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,10 +1,10 @@ --- a/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java +++ b/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java @@ -58,6 +_,7 @@ - BlockPos cursor = pos.above(dy); - BlockState replaceWith = this.provider.getOptionalState(context.level(), context.random(), cursor); - if (replaceWith != null) { -+ replaceWith = net.minecraftforge.event.ForgeEventFactory.alterGround(context.level(), context.random(), cursor, replaceWith); - context.setBlock(cursor, replaceWith); + BlockPos blockpos = pos.above(i); + BlockState blockstate = this.provider.getOptionalState(context.level(), context.random(), blockpos); + if (blockstate != null) { ++ blockstate = net.minecraftforge.event.ForgeEventFactory.alterGround(context.level(), context.random(), blockpos, blockstate); + context.setBlock(blockpos, blockstate); 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 36b7e245d8..84ed98f18f 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 @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java @@ -68,6 +_,8 @@ ) { - BlockState blockBelowTrunk = config.belowTrunkProvider.getOptionalState(level, random, pos); - if (blockBelowTrunk != null) { + BlockState blockstate = config.belowTrunkProvider.getOptionalState(level, random, pos); + if (blockstate != null) { + var levelReader = (net.minecraft.world.level.LevelReader)level; + if (!levelReader.getBlockState(pos).onTreeGrow(levelReader, trunkSetter, random, pos, config)) - trunkSetter.accept(pos, blockBelowTrunk); + trunkSetter.accept(pos, blockstate); } } 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 6c40ecea1b..408f6294c8 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 -@@ -81,6 +_,9 @@ +@@ -82,6 +_,9 @@ } public final CompoundTag createTag(final StructurePieceSerializationContext context) { + 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 tag = new CompoundTag(); - tag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); - tag.store("BB", BoundingBox.CODEC, this.boundingBox); + CompoundTag compoundtag = new CompoundTag(); + compoundtag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); + compoundtag.store("BB", BoundingBox.CODEC, this.boundingBox); 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 4122d3467d..ce30309de7 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 @@ -2,11 +2,11 @@ +++ b/net/minecraft/world/level/levelgen/structure/StructureStart.java @@ -103,6 +_,9 @@ public CompoundTag createTag(final StructurePieceSerializationContext context, final ChunkPos chunkPos) { - CompoundTag tag = new CompoundTag(); + CompoundTag compoundtag = new CompoundTag(); if (this.isValid()) { + if (context.registryAccess().lookupOrThrow(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."); + } - tag.putString("id", context.registryAccess().lookupOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); - tag.putInt("ChunkX", chunkPos.x()); - tag.putInt("ChunkZ", chunkPos.z()); + compoundtag.putString("id", context.registryAccess().lookupOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); + compoundtag.putInt("ChunkX", chunkPos.x()); + compoundtag.putInt("ChunkZ", chunkPos.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 22b4f887fa..c167e58019 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,33 +1,33 @@ --- a/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java +++ b/net/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessor.java -@@ -8,6 +_,7 @@ +@@ -7,6 +_,7 @@ import org.jspecify.annotations.Nullable; - public interface StructureProcessor { + public abstract class StructureProcessor { + /** @deprecated Use variant with StructureTemplate argument */ - default StructureTemplate.@Nullable StructureBlockInfo processBlock( + public StructureTemplate.@Nullable StructureBlockInfo processBlock( final LevelReader level, final BlockPos targetPosition, -@@ -19,6 +_,18 @@ +@@ -18,6 +_,18 @@ return processedBlockInfo; } -+ default StructureTemplate.@Nullable StructureBlockInfo processBlock( ++ public StructureTemplate.@Nullable StructureBlockInfo processBlock( + final LevelReader level, + final BlockPos targetPosition, + final BlockPos referencePos, -+ final BlockPos templateRelativePos, ++ final StructureTemplate.StructureBlockInfo originalBlockInfo, + final StructureTemplate.StructureBlockInfo processedBlockInfo, + final StructurePlaceSettings settings, + final @Nullable StructureTemplate template + ) { -+ return processBlock(level, targetPosition, referencePos, templateRelativePos, processedBlockInfo, settings); ++ return processBlock(level, targetPosition, referencePos, originalBlockInfo, processedBlockInfo, settings); + } + - MapCodec codec(); + protected abstract StructureProcessorType getType(); - default List finalizeProcessing( -@@ -30,6 +_,21 @@ + public List finalizeProcessing( +@@ -29,5 +_,20 @@ final StructurePlaceSettings settings ) { return processedBlockInfoList; @@ -37,7 +37,7 @@ + * Use this method to process entities from a structure in much the same way as + * blocks, parameters are analogous. + */ -+ default StructureTemplate.@Nullable StructureEntityInfo processEntity( ++ public StructureTemplate.@Nullable StructureEntityInfo processEntity( + final LevelReader level, + final BlockPos targetPosition, + final StructureTemplate.StructureEntityInfo originalEntityInfo, @@ -47,5 +47,4 @@ + ) { + return processedEntityInfo; } - - default boolean evaluatesEntirePieceState() { + } 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 6678e7627e..8bf52c77d6 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,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java +++ b/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java -@@ -249,6 +_,10 @@ +@@ -256,6 +_,10 @@ return transform(pos, settings.getMirror(), settings.getRotation(), settings.getRotationPivot()); } @@ -11,30 +11,30 @@ public boolean placeInWorld( final ServerLevelAccessor level, final BlockPos position, -@@ -276,7 +_,7 @@ - int maxX = Integer.MIN_VALUE; - int maxY = Integer.MIN_VALUE; - int maxZ = Integer.MIN_VALUE; -- List processedBlockInfoList = processBlockInfos(level, position, referencePos, settings, blockInfoList); -+ List processedBlockInfoList = processBlockInfos(level, position, referencePos, settings, blockInfoList, this); +@@ -282,7 +_,7 @@ + int l = Integer.MIN_VALUE; + int i1 = Integer.MIN_VALUE; + int j1 = Integer.MIN_VALUE; +- List list4 = processBlockInfos(level, position, referencePos, settings, list); ++ List list4 = processBlockInfos(level, position, referencePos, settings, list, this); - try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(LOGGER)) { - for (StructureTemplate.StructureBlockInfo blockInfo : processedBlockInfoList) { -@@ -395,10 +_,10 @@ - position, - settings.getMirror(), - settings.getRotation(), -- settings.getRotationPivot(), - boundingBox, - settings.shouldFinalizeEntities(), -- reporter -+ reporter, -+ settings - ); + try (ProblemReporter.ScopedCollector problemreporter$scopedcollector = new ProblemReporter.ScopedCollector(LOGGER)) { + for (StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : list4) { +@@ -406,10 +_,10 @@ + position, + settings.getMirror(), + settings.getRotation(), +- settings.getRotationPivot(), + boundingbox, + settings.shouldFinalizeEntities(), +- problemreporter$scopedcollector ++ problemreporter$scopedcollector, ++ settings + ); + } } - } -@@ -440,12 +_,21 @@ - }); +@@ -458,12 +_,21 @@ + ); } + /** @@ -54,18 +54,18 @@ + List blockInfoList, + @Nullable StructureTemplate template ) { - List originalBlockInfoList = new ArrayList<>(); - List processedBlockInfoList = new ArrayList<>(); -@@ -469,7 +_,7 @@ - Iterator iterator = settings.getProcessors().iterator(); + List list = new ArrayList<>(); + List list1 = new ArrayList<>(); +@@ -479,7 +_,7 @@ - while (processedBlockInfo != null && iterator.hasNext()) { -- processedBlockInfo = iterator.next().processBlock(level, position, referencePos, blockInfo.pos, processedBlockInfo, settings); -+ processedBlockInfo = iterator.next().processBlock(level, position, referencePos, blockInfo.pos, processedBlockInfo, settings, template); - } + while (structuretemplate$structureblockinfo1 != null && iterator.hasNext()) { + structuretemplate$structureblockinfo1 = iterator.next() +- .processBlock(level, position, referencePos, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, settings); ++ .processBlock(level, position, referencePos, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, settings, template); + } - if (processedBlockInfo != null) { -@@ -491,17 +_,17 @@ + if (structuretemplate$structureblockinfo1 != null) { +@@ -500,17 +_,17 @@ final BlockPos position, final Mirror mirror, final Rotation rotation, @@ -76,20 +76,20 @@ + final ProblemReporter problemReporter, + final StructurePlaceSettings placementIn ) { -- for (StructureTemplate.StructureEntityInfo entityInfo : this.entityInfoList) { -- BlockPos blockPos = transform(entityInfo.blockPos, mirror, rotation, pivot).offset(position); +- for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : this.entityInfoList) { +- BlockPos blockpos = transform(structuretemplate$structureentityinfo.blockPos, mirror, rotation, pivot).offset(position); + var entities = processEntityInfos(this, level, position, placementIn, this.entityInfoList); -+ for (StructureTemplate.StructureEntityInfo entityInfo : entities) { -+ BlockPos blockPos = entityInfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos - if (boundingBox == null || boundingBox.isInside(blockPos)) { - CompoundTag tag = entityInfo.nbt.copy(); -- Vec3 relativePos = transform(entityInfo.pos, mirror, rotation, pivot); -- Vec3 pos = relativePos.add(position.getX(), position.getY(), position.getZ()); -+ Vec3 pos = entityInfo.pos; // FORGE: Position will have already been transformed by processEntityInfos - ListTag posTag = new ListTag(); - posTag.add(DoubleTag.valueOf(pos.x)); - posTag.add(DoubleTag.valueOf(pos.y)); -@@ -523,6 +_,30 @@ ++ for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : entities) { ++ BlockPos blockpos = structuretemplate$structureentityinfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos + if (boundingBox == null || boundingBox.isInside(blockpos)) { + CompoundTag compoundtag = structuretemplate$structureentityinfo.nbt.copy(); +- Vec3 vec3 = transform(structuretemplate$structureentityinfo.pos, mirror, rotation, pivot); +- Vec3 vec31 = vec3.add(position.getX(), position.getY(), position.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)); +@@ -532,6 +_,30 @@ } } } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch index fbc7da494b..d080f2ddf0 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch @@ -3,8 +3,8 @@ @@ -77,6 +_,7 @@ } - sources.add(this.resourceManagerSource); -+ sources.add(net.minecraftforge.common.ForgeHooks.emptyStructureSource()); - this.sources = sources.build(); + builder.add(this.resourceManagerSource); ++ builder.add(net.minecraftforge.common.ForgeHooks.emptyStructureSource()); + this.sources = builder.build(); } 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 d84e29b260..157ec10d2b 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 -@@ -110,7 +_,7 @@ +@@ -109,7 +_,7 @@ } private int getEmission(final long blockNode, final BlockState state) { -- int emission = state.getLightEmission(); -+ int emission = state.getLightEmission(chunkSource.getLevel(), mutablePos); - return emission > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(blockNode)) ? emission : 0; +- int i = state.getLightEmission(); ++ int i = state.getLightEmission(chunkSource.getLevel(), mutablePos); + return i > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(blockNode)) ? i : 0; } -@@ -120,7 +_,7 @@ - LightChunk chunk = this.chunkSource.getChunkForLighting(pos.x(), pos.z()); - if (chunk != null) { - chunk.findBlockLightSources((lightPos, state) -> { -- int lightEmission = state.getLightEmission(); -+ int lightEmission = state.getLightEmission(chunkSource.getLevel(), lightPos); - this.enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(lightEmission, isEmptyShape(state))); +@@ -119,7 +_,7 @@ + LightChunk lightchunk = this.chunkSource.getChunkForLighting(pos.x(), pos.z()); + if (lightchunk != null) { + lightchunk.findBlockLightSources((lightPos, state) -> { +- int i = state.getLightEmission(); ++ int i = state.getLightEmission(chunkSource.getLevel(), lightPos); + this.enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(i, isEmptyShape(state))); }); } 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 afd6d6b12b..b95cbf6518 100644 --- a/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/world/level/material/FlowingFluid.java +++ b/net/minecraft/world/level/material/FlowingFluid.java -@@ -168,7 +_,7 @@ - BlockState blockState = level.getBlockState(relativePos); - FluidState fluidState = blockState.getFluidState(); - if (fluidState.getType().isSame(this) && canPassThroughWall(direction, level, pos, state, relativePos, blockState)) { -- if (fluidState.isSource()) { -+ if (fluidState.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(level, relativePos, blockState, fluidState.canConvertToSource(level, relativePos))) { - neighbourSources++; +@@ -172,7 +_,7 @@ + BlockState blockstate = level.getBlockState(blockpos); + FluidState fluidstate = blockstate.getFluidState(); + if (fluidstate.getType().isSame(this) && canPassThroughWall(direction, level, pos, state, blockpos, blockstate)) { +- if (fluidstate.isSource()) { ++ if (fluidstate.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(level, blockpos, blockstate, fluidstate.canConvertToSource(level, blockpos))) { + j++; } -@@ -176,7 +_,7 @@ +@@ -180,7 +_,7 @@ } } -- if (neighbourSources >= 2 && this.canConvertToSource(level)) { -+ if (neighbourSources >= 2) { - BlockState belowState = level.getBlockState(mutablePos.setWithOffset(pos, Direction.DOWN)); - FluidState belowFluid = belowState.getFluidState(); - if (belowState.isSolid() || this.isSourceBlockOfThisType(belowFluid)) { -@@ -263,6 +_,15 @@ +- if (j >= 2 && this.canConvertToSource(level)) { ++ if (j >= 2) { + BlockState blockstate1 = level.getBlockState(blockpos$mutableblockpos.setWithOffset(pos, Direction.DOWN)); + FluidState fluidstate1 = blockstate1.getFluidState(); + if (blockstate1.isSolid() || this.isSourceBlockOfThisType(fluidstate1)) { +@@ -265,6 +_,15 @@ return this.getSource().defaultFluidState().setValue(FALLING, falling); } 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 63a2dcba5e..bb5082301f 100644 --- a/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/world/level/material/LavaFluid.java +++ b/net/minecraft/world/level/material/LavaFluid.java @@ -93,7 +_,7 @@ - BlockState blockState = level.getBlockState(testPos); - if (blockState.isAir()) { - if (this.hasFlammableNeighbours(level, testPos)) { -- level.setBlockAndUpdate(testPos, BaseFireBlock.getState(level, testPos)); -+ level.setBlockAndUpdate(testPos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, testPos, pos, Blocks.FIRE.defaultBlockState())); + BlockState blockstate = level.getBlockState(blockpos); + if (blockstate.isAir()) { + if (this.hasFlammableNeighbours(level, blockpos)) { +- level.setBlockAndUpdate(blockpos, BaseFireBlock.getState(level, blockpos)); ++ level.setBlockAndUpdate(blockpos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, blockpos, pos, Blocks.FIRE.defaultBlockState())); return; } - } else if (blockState.blocksMotion()) { + } else if (blockstate.blocksMotion()) { @@ -107,8 +_,8 @@ return; } -- if (level.isEmptyBlock(testPos.above()) && this.isFlammable(level, testPos)) { -- level.setBlockAndUpdate(testPos.above(), BaseFireBlock.getState(level, testPos)); -+ if (level.isEmptyBlock(testPos.above()) && this.isFlammable(level, testPos, Direction.UP)) { -+ level.setBlockAndUpdate(testPos.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, testPos.above(), pos, Blocks.FIRE.defaultBlockState())); +- if (level.isEmptyBlock(blockpos1.above()) && this.isFlammable(level, blockpos1)) { +- level.setBlockAndUpdate(blockpos1.above(), BaseFireBlock.getState(level, blockpos1)); ++ if (level.isEmptyBlock(blockpos1.above()) && this.isFlammable(level, blockpos1, Direction.UP)) { ++ level.setBlockAndUpdate(blockpos1.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, blockpos1.above(), pos, Blocks.FIRE.defaultBlockState())); } } } @@ -47,12 +47,13 @@ @Override public @Nullable ParticleOptions getDripParticle() { return ParticleTypes.DRIPPING_LAVA; -@@ -206,7 +_,7 @@ - FluidState fluidState = level.getFluidState(pos); - if (this.is(FluidTags.LAVA) && fluidState.is(FluidTags.WATER)) { +@@ -206,7 +_,8 @@ + FluidState fluidstate = level.getFluidState(pos); + if (this.is(FluidTags.LAVA) && fluidstate.is(FluidTags.WATER)) { if (state.getBlock() instanceof LiquidBlock) { - level.setBlock(pos, Blocks.STONE.defaultBlockState(), 3); + level.setBlock(pos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, pos, pos, Blocks.STONE.defaultBlockState()), 3); ++ } this.fizz(level, pos); 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 48ec5af73f..9e983b6a82 100644 --- a/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java +++ b/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java -@@ -494,6 +_,16 @@ - for (int dz = -1; dz <= 1; dz++) { - if (dx != 0 || dz != 0) { - PathType pathType = context.getPathTypeFromState(x + dx, y + dy, z + dz); +@@ -484,6 +_,16 @@ + for (int k = -1; k <= 1; k++) { + if (i != 0 || k != 0) { + PathType pathtype = context.getPathTypeFromState(x + i, y + j, z + k); + -+ var pos = new BlockPos(x + dx, y + dy, z + dz); ++ var pos = new BlockPos(x + i, y + j, z + k); + var blockstate = context.level().getBlockState(pos); + + var adjacentBlockPathType = blockstate.getAdjacentBlockPathType(context.level(), pos, null, blockPathType); @@ -14,35 +14,35 @@ + var adjacentFluidPathType = blockstate.getFluidState().getAdjacentBlockPathType(context.level(), pos, null, blockPathType); + if (adjacentFluidPathType != null) return adjacentFluidPathType; + - if (pathType == PathType.DAMAGING) { + if (pathtype == PathType.DAMAGING) { return PathType.DAMAGING_IN_NEIGHBOR; } -@@ -520,6 +_,10 @@ +@@ -510,6 +_,10 @@ protected static PathType getPathTypeFromState(final BlockGetter level, final BlockPos pos) { - BlockState blockState = level.getBlockState(pos); - Block block = blockState.getBlock(); + BlockState blockstate = level.getBlockState(pos); + Block block = blockstate.getBlock(); + -+ var type = blockState.getBlockPathType(level, pos, null); ++ var type = blockstate.getBlockPathType(level, pos, null); + if (type != null) return type; + - if (blockState.isAir()) { + if (blockstate.isAir()) { return PathType.OPEN; - } -@@ -546,6 +_,8 @@ - - if (!blockState.is(Blocks.WITHER_ROSE) && !blockState.is(BlockTags.SPELEOTHEMS)) { - FluidState fluidState = blockState.getFluidState(); -+ var nonLoggableFluidPathType = fluidState.getBlockPathType(level, pos, null, false); + } else if (blockstate.is(BlockTags.TRAPDOORS) || blockstate.is(Blocks.LILY_PAD) || blockstate.is(Blocks.BIG_DRIPLEAF)) { +@@ -524,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(level, pos, null, false); + if (nonLoggableFluidPathType != null) return nonLoggableFluidPathType; - if (fluidState.is(FluidTags.LAVA)) { + if (fluidstate.is(FluidTags.LAVA)) { return PathType.LAVA; - } -@@ -558,6 +_,8 @@ - if (blockState.getValue(DoorBlock.OPEN)) { - return PathType.DOOR_OPEN; + } else if (isBurningBlock(blockstate)) { +@@ -544,6 +_,8 @@ + if (!blockstate.isPathfindable(PathComputationType.LAND)) { + return PathType.BLOCKED; } else { -+ var loggableFluidPathType = fluidState.getBlockPathType(level, pos, null, true); ++ var loggableFluidPathType = fluidstate.getBlockPathType(level, pos, null, true); + if (loggableFluidPathType != null) return loggableFluidPathType; - return door.type().canOpenByHand() ? PathType.DOOR_WOOD_CLOSED : PathType.DOOR_IRON_CLOSED; + return fluidstate.is(FluidTags.WATER) ? PathType.WATER : PathType.OPEN; } } else { 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 48ba3f73e7..a9aadca86b 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/storage/LevelStorageSource.java +++ b/net/minecraft/world/level/storage/LevelStorageSource.java -@@ -566,6 +_,11 @@ - return unfixedDataTag; +@@ -571,6 +_,11 @@ + return dynamic; } + public CompoundTag getDataTagRaw(final boolean useFallback) throws IOException { @@ -11,16 +11,16 @@ + public Dynamic getUnfixedDataTag(final boolean useFallback) throws IOException { this.checkLock(); - Path dataFile = this.getDataFile(useFallback); -@@ -585,6 +_,7 @@ - CompoundTag dataTag = levelData.createTag(singleplayerUUID); - CompoundTag root = new CompoundTag(); - root.put("Data", dataTag); -+ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(levelData, root); - this.saveLevelData(root); + Path path = this.getDataFile(useFallback); +@@ -590,6 +_,7 @@ + CompoundTag compoundtag = levelData.createTag(singleplayerUUID); + CompoundTag compoundtag1 = new CompoundTag(); + compoundtag1.put("Data", compoundtag); ++ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(levelData, compoundtag1); + this.saveLevelData(compoundtag1); } -@@ -611,6 +_,10 @@ +@@ -616,6 +_,10 @@ public Optional getIconFile() { return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile()); 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 981ea03650..c636bf9385 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/storage/LevelSummary.java +++ b/net/minecraft/world/level/storage/LevelSummary.java -@@ -14,7 +_,7 @@ +@@ -15,7 +_,7 @@ import org.apache.commons.lang3.StringUtils; import org.jspecify.annotations.Nullable; 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 f2d7fc24aa..c8b6ac29ae 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/storage/PlayerDataStorage.java +++ b/net/minecraft/world/level/storage/PlayerDataStorage.java @@ -41,6 +_,7 @@ - Path realFile = playerDirPath.resolve(player.getStringUUID() + ".dat"); - Path oldFile = playerDirPath.resolve(player.getStringUUID() + ".dat_old"); - Util.safeReplaceFile(realFile, tmpFile, oldFile); + Path path2 = path.resolve(player.getStringUUID() + ".dat"); + Path path3 = path.resolve(player.getStringUUID() + ".dat_old"); + Util.safeReplaceFile(path2, path1, path3); + net.minecraftforge.event.ForgeEventFactory.firePlayerSavingEvent(player, playerDir, player.getStringUUID()); - } catch (Exception ignored) { + } catch (Exception exception) { LOGGER.warn("Failed to save player data for {}", player.getPlainTextName()); } @@ -83,5 +_,9 @@ - int version = NbtUtils.getDataVersion(tag); - return DataFixTypes.PLAYER.updateToCurrentVersion(this.fixerUpper, tag, version); + int i = NbtUtils.getDataVersion(tag); + return DataFixTypes.PLAYER.updateToCurrentVersion(this.fixerUpper, tag, i); }); + } + 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 c9d019189c..a4a91e9342 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/PrimaryLevelData.java.patch @@ -26,7 +26,7 @@ } public static void writeLastPlayed(final CompoundTag tag) { -@@ -327,6 +_,16 @@ +@@ -322,6 +_,16 @@ public LevelSettings getLevelSettings() { return this.settings.copy(); } @@ -42,4 +42,4 @@ + @Deprecated - public enum SpecialWorldProperty { + public static enum SpecialWorldProperty { diff --git a/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch b/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch index d24788744b..809dbcc9dd 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch @@ -1,12 +1,13 @@ --- a/net/minecraft/world/level/storage/SavedDataStorage.java +++ b/net/minecraft/world/level/storage/SavedDataStorage.java -@@ -121,6 +_,9 @@ +@@ -122,6 +_,10 @@ } - int version = NbtUtils.getDataVersion(tag, 1343); + 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 (type == null) -+ return tag; - return type.update(this.fixerUpper, tag, version, newVersion); ++ compoundtag1 = compoundtag; ++ else + compoundtag1 = type.update(this.fixerUpper, compoundtag, i, newVersion); } - } + 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 7a75d879de..d64b673fbb 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 @@ -45,7 +45,7 @@ + return this.queriedLootTableId == null ? net.minecraftforge.common.loot.LootTableIdCondition.UNKNOWN_LOOT_TABLE : this.queriedLootTableId; + } + - public enum BlockEntityTarget implements StringRepresentable, LootContextArg.SimpleGetter { + public static enum BlockEntityTarget implements StringRepresentable, LootContextArg.SimpleGetter { BLOCK_ENTITY("block_entity", LootContextParams.BLOCK_ENTITY); @@ -113,11 +_,18 @@ @@ -79,12 +79,12 @@ public ServerLevel getLevel() { return this.params.getLevel(); } -@@ -139,7 +_,7 @@ - ServerLevel level = this.getLevel(); - MinecraftServer server = level.getServer(); - RandomSource random = Optional.ofNullable(this.random).or(() -> randomSequenceKey.map(server::getRandomSequence)).orElseGet(level::getRandom); -- return new LootContext(this.params, random, server.reloadableRegistries().lookup()); -+ return new LootContext(this.params, random, server.reloadableRegistries().lookup(), queriedLootTableId); +@@ -141,7 +_,7 @@ + RandomSource randomsource = Optional.ofNullable(this.random) + .or(() -> randomSequenceKey.map(minecraftserver::getRandomSequence)) + .orElseGet(serverlevel::getRandom); +- return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup()); ++ return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup(), queriedLootTableId); } } 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 0a2c7fd3e0..71222d49dc 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 @@ -18,8 +18,8 @@ } @@ -92,6 +_,10 @@ public LootParams create(final ContextKeySet contextKeySet) { - ContextMap keySet = this.params.create(contextKeySet); - return new LootParams(this.level, keySet, this.dynamicDrops, this.luck); + ContextMap contextmap = this.params.create(contextKeySet); + return new LootParams(this.level, contextmap, this.dynamicDrops, this.luck); + } + + public LootParams create() { 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 f0e1a9f4d9..a1116b8098 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 @@ -4,8 +4,8 @@ LootItemCondition.DIRECT_CODEC.listOf().optionalFieldOf("conditions", List.of()).forGetter(p -> p.conditions), LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(p -> p.functions), NumberProviders.CODEC.fieldOf("rolls").forGetter(p -> p.rolls), -- NumberProviders.CODEC.optionalFieldOf("bonus_rolls", ConstantValue.exactly(0.0F)).forGetter(p -> p.bonusRolls) -+ NumberProviders.CODEC.optionalFieldOf("bonus_rolls", ConstantValue.exactly(0.0F)).forGetter(p -> p.bonusRolls), +- NumberProviders.CODEC.fieldOf("bonus_rolls").orElse(ConstantValue.exactly(0.0F)).forGetter(p -> p.bonusRolls) ++ NumberProviders.CODEC.fieldOf("bonus_rolls").orElse(ConstantValue.exactly(0.0F)).forGetter(p -> p.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) ) @@ -88,7 +88,7 @@ public LootPool.Builder setRolls(final NumberProvider rolls) { this.rolls = rolls; -@@ -162,8 +_,18 @@ +@@ -154,8 +_,18 @@ return this; } 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 7f9008ce24..3a4b7e54c1 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,6 +1,6 @@ --- a/net/minecraft/world/level/storage/loot/LootTable.java +++ b/net/minecraft/world/level/storage/loot/LootTable.java -@@ -39,7 +_,7 @@ +@@ -40,7 +_,7 @@ i -> i.group( LootContextParamSets.CODEC.lenientOptionalFieldOf("type", DEFAULT_PARAM_SET).forGetter(t -> t.paramSet), Identifier.CODEC.optionalFieldOf("random_sequence").forGetter(t -> t.randomSequence), @@ -9,7 +9,7 @@ LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(t -> t.functions) ) .apply(i, LootTable::new) -@@ -58,7 +_,7 @@ +@@ -59,7 +_,7 @@ ) { this.paramSet = paramSet; this.randomSequence = randomSequence; @@ -18,7 +18,7 @@ this.functions = functions; this.compositeFunction = LootItemFunctions.compose(functions); } -@@ -81,10 +_,12 @@ +@@ -82,10 +_,12 @@ }; } @@ -29,9 +29,9 @@ + @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied public void getRandomItemsRaw(final LootContext context, final Consumer output) { - LootContext.VisitedEntry breadcrumb = LootContext.createVisitedEntry(this); - if (context.pushVisitedElement(breadcrumb)) { -@@ -101,18 +_,19 @@ + LootContext.VisitedEntry visitedentry = LootContext.createVisitedEntry(this); + if (context.pushVisitedElement(visitedentry)) { +@@ -102,18 +_,19 @@ } public void getRandomItems(final LootParams params, final long optionalLootTableSeed, final Consumer output) { @@ -55,17 +55,17 @@ } public ObjectArrayList getRandomItems(final LootParams params, final RandomSource randomSource) { -@@ -129,7 +_,8 @@ +@@ -130,7 +_,8 @@ private ObjectArrayList getRandomItems(final LootContext context) { - ObjectArrayList result = new ObjectArrayList<>(); -- this.getRandomItems(context, result::add); -+ this.getRandomItemsRaw(context, createStackSplitter(context.getLevel(), result::add)); -+ result = net.minecraftforge.common.ForgeHooks.modifyLoot(this, result, context); - return result; + ObjectArrayList objectarraylist = new ObjectArrayList<>(); +- this.getRandomItems(context, objectarraylist::add); ++ this.getRandomItemsRaw(context, createStackSplitter(context.getLevel(), objectarraylist::add)); ++ objectarraylist = net.minecraftforge.common.ForgeHooks.modifyLoot(this, objectarraylist, context); + return objectarraylist; } -@@ -214,6 +_,68 @@ +@@ -215,6 +_,68 @@ public static LootTable.Builder lootTable() { return new LootTable.Builder(); diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch index 86b37b2817..754a85516f 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java +++ b/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java -@@ -72,8 +_,12 @@ +@@ -73,8 +_,12 @@ @Override public ItemStack run(final ItemStack itemStack, final LootContext context) { - Entity killer = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); -- if (killer instanceof LivingEntity entity) { -- int level = EnchantmentHelper.getEnchantmentLevel(this.enchantment, entity); -+ int level = 0; + Entity entity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); +- if (entity instanceof LivingEntity livingentity) { +- int i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); ++ int i = 0; + if (this.enchantment.is(Enchantments.LOOTING)) -+ level = context.getLootingModifier(); -+ else if (killer instanceof LivingEntity livingentity) -+ level = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); ++ i = context.getLootingModifier(); ++ else if (entity instanceof LivingEntity livingentity) ++ i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); + - if (level == 0) { + if (i == 0) { return itemStack; } -@@ -83,7 +_,6 @@ +@@ -84,7 +_,6 @@ if (this.hasLimit()) { itemStack.limitSize(this.limit); } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch index c85a4d3836..ff80c549ac 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java +++ b/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java -@@ -40,7 +_,11 @@ +@@ -41,7 +_,11 @@ public boolean test(final LootContext context) { - Entity killerEntity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); -- int enchantmentLevel = killerEntity instanceof LivingEntity livingKiller ? EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingKiller) : 0; -+ int enchantmentLevel = 0; + Entity entity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); +- int i = entity instanceof LivingEntity livingentity ? EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity) : 0; ++ int i = 0; + if (this.enchantment.is(Enchantments.LOOTING)) -+ enchantmentLevel = context.getLootingModifier(); -+ else if (killerEntity instanceof LivingEntity livingentity) -+ enchantmentLevel = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); - float chance = enchantmentLevel > 0 ? this.enchantedChance.calculate(enchantmentLevel) : this.unenchantedChance; - return context.getRandom().nextFloat() < chance; ++ i = context.getLootingModifier(); ++ else if (entity instanceof LivingEntity livingentity) ++ i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); + float f = i > 0 ? this.enchantedChance.calculate(i) : this.unenchantedChance; + return context.getRandom().nextFloat() < f; } diff --git a/settings.gradle b/settings.gradle index 66b94fb4cd..631180f095 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,26 +1,18 @@ -import groovy.transform.Field - pluginManagement { - private static final @Field String FORGEDEV_VERSION = '7.0.0-beta.51' - - if (new File('forgedev/settings.gradle').exists()) { - includeBuild 'forgedev' - } else { - resolutionStrategy.eachPlugin { - // TODO [ForgeDev] Consolidate these entry-points - switch (requested.id.id) { - case 'net.minecraftforge.forgedev': - case 'net.minecraftforge.forge.build.convention': - useVersion(FORGEDEV_VERSION) - break - } - } - } - repositories { gradlePluginPortal() - maven { url = 'https://maven.minecraftforge.net/' } //mavenLocal() + maven { url = 'https://maven.minecraftforge.net/' } + } +} + +buildscript { + dependencies { + classpath('com.google.code.gson:gson') { + version { + strictly '2.11.0' + } + } } } @@ -28,7 +20,100 @@ plugins { id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' } -rootProject.name = 'forge' +dependencyResolutionManagement { + versionCatalogs { + libs { + plugin('apt', 'com.diffplug.eclipse.apt').version('4.2.0') + + library('forgespi', 'net.minecraftforge:forgespi:8.0.0') // Needs modlauncher + library('modlauncher', 'net.minecraftforge:modlauncher:10.2.4') // Needs securemodules + library('securemodules', 'net.minecraftforge:securemodules:2.2.24') // Needs unsafe + library('unsafe', 'net.minecraftforge:unsafe:0.9.2') + library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.2') + library('coremods-api', 'net.minecraftforge:coremods-api:5.3.0') + version('eventbus', '7.0.1') + library('eventbus', 'net.minecraftforge', 'eventbus').versionRef('eventbus') + library('eventbus-validator', 'net.minecraftforge', 'eventbus-validator').versionRef('eventbus') + library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0') + + library('roimfs', 'net.minecraftforge:roimfs:1.0.0') // ReadOnlyInMemoryFileSystem - Used for JarInJar extraction at runtime + library('mixin', 'org.spongepowered:mixin:0.8.7') + version('mixinextras', '0.5.3') + library('mixinextras-forge', 'io.github.llamalad7', 'mixinextras-forge').versionRef('mixinextras') + library('mixinextras-common', 'io.github.llamalad7', 'mixinextras-common').versionRef('mixinextras') + library('jetbrains-annotations', 'org.jetbrains:annotations:24.1.0') // for ApiStatus annotations + library('jspecify', 'org.jspecify:jspecify:1.0.0') // for nullability annotations + library('slf4j-api', 'org.slf4j:slf4j-api:2.0.7') + library('maven-artifact', 'org.apache.maven:maven-artifact:3.8.8') + + // Google's InMemory File System. Used by ForgeDev Tests for now, but could be useful for a lot of things. + library('jimfs', 'com.google.jimfs:jimfs:1.3.0') + bundle('jimfs', ['guava', 'failureaccess']) + + version('bootstrap', '2.1.8') + library('bootstrap', 'net.minecraftforge', 'bootstrap' ).versionRef('bootstrap') // Needs modlauncher + library('bootstrap-api', 'net.minecraftforge', 'bootstrap-api' ).versionRef('bootstrap') + library('bootstrap-dev', 'net.minecraftforge', 'bootstrap-dev' ).versionRef('bootstrap') + library('bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim').versionRef('bootstrap') + + // ASM it's used for so many of our hacks + version('asm', '9.9.1') + 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') + library('asm-commons', 'org.ow2.asm', 'asm-commons' ).versionRef('asm') + library('asm-analysis', 'org.ow2.asm', 'asm-analysis').versionRef('asm') + bundle('asm', ['asm', 'asm-tree', 'asm-util', 'asm-commons', 'asm-analysis']) + + // Terminal Console Appender.. essentually make pretty colors in the console, but it's been a PITA + library('terminalconsoleappender', 'net.minecrell:terminalconsoleappender:1.2.0') + version('jline', '3.25.1') + library('jline-reader', 'org.jline', 'jline-reader' ).versionRef('jline') + library('jline-terminal', 'org.jline', 'jline-terminal' ).versionRef('jline') + library('jline-terminal-jna', 'org.jline', 'jline-terminal-jna').versionRef('jline') // Colors and tab completeion + bundle('terminalconsoleappender', ['terminalconsoleappender', 'jline-reader', 'jline-terminal', 'jline-terminal-jna']) + + // The core of our configuration system, it has many flaws, but it works for the most part + version('night-config', '3.7.4') + library('night-config-toml', 'com.electronwill.night-config', 'toml').versionRef('night-config') + library('night-config-core', 'com.electronwill.night-config', 'core').versionRef('night-config') + bundle('night-config', ['night-config-toml', 'night-config-core']) + + // Jar in Jar FileSystem + version('jarjar', '0.4.2') + library('jarjar-fs', 'net.minecraftforge', 'JarJarFileSystems').versionRef('jarjar') + library('jarjar-meta', 'net.minecraftforge', 'JarJarMetadata' ).versionRef('jarjar') + library('jarjar-selector', 'net.minecraftforge', 'JarJarSelector' ).versionRef('jarjar') + bundle('jarjar', ['jarjar-fs', 'jarjar-selector', 'jarjar-meta']) + + // These are libraries shipped by the MC launcher, try and keep them in sync with the manifest + // but honestly if we don't it just means we ship them as normal libraries by adding them to the installer config in the forge project + library('gson', 'com.google.code.gson:gson:2.11.0') + library('guava', 'com.google.guava:guava:33.5.0-jre') + library('failureaccess', 'com.google.guava:failureaccess:1.0.3') + + version('log4j', '2.24.3') + library('log4j-api', 'org.apache.logging.log4j', 'log4j-api' ).versionRef('log4j') + library('log4j-core', 'org.apache.logging.log4j', 'log4j-core').versionRef('log4j') + bundle('log4j', ['log4j-api', 'log4j-core']) + + library('apache-commons', 'org.apache.commons:commons-lang3:3.17.0') + library('mojang-logging', 'com.mojang:logging:1.5.10') + library('jopt-simple', 'net.sf.jopt-simple:jopt-simple:5.0.4') + library('commons-io', 'commons-io:commons-io:2.17.0') + + version('lwjgl', '3.4.1') + 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') + library('lwjgl-stb', 'org.lwjgl', 'lwjgl-stb' ).versionRef('lwjgl') + library('lwjgl-tinyfd', 'org.lwjgl', 'lwjgl-tinyfd').versionRef('lwjgl') + bundle('lwjgl', ['lwjgl', 'lwjgl-glfw', 'lwjgl-opengl', 'lwjgl-stb', 'lwjgl-tinyfd']) + } + } +} + +rootProject.name = 'ForgeRoot' include 'fmlloader' include 'fmlcore' @@ -38,175 +123,15 @@ include 'lowcodelanguage' include 'fmlearlydisplay' include 'forge-transformers' -enableFeaturePreview 'TYPESAFE_PROJECT_ACCESSORS' +include ':mcp' +project(":mcp").projectDir = file("projects/mcp") -gradle.beforeProject { Project project -> - project.pluginManager.withPlugin('net.minecraftforge.forge.build.convention') { - // NOTE: We are defining these variables in here so that the projects can stay isolated, increasing build time. - // See minecraft.versions.toml for the versions where you can change these values. - //@formatter:off - project.ext.javaVersion = project.gradleutils.unpack(project.bootLibs.versions.java) - project.ext.minecraftVersion = project.gradleutils.unpack(project.bootLibs.versions.minecraft) - project.version = project.gitversion.getMCTagOffsetBranch(project.ext.minecraftVersion) - project.ext.forgeVersion = project.version.substring(project.ext.minecraftVersion.length() + 1) - project.ext.minecraftNextVersion = project.gradleutils.unpack(project.bootLibs.versions.minecraft.next) - project.ext.mcpVersion = project.gradleutils.unpack(project.bootLibs.versions.mcp) - project.ext.changelogBase = project.gradleutils.unpack(project.bootLibs.versions.changelog.base) - //@formatter:on - } +include ':forge' +project(":forge").projectDir = file("projects/forge") +project(':forge').buildFileName = '../../build_forge.gradle' - // NOTE: We are adding dependencies to projects instead of through settings, so we don't have to apply forgedev in settings. - // Applying forgedev in settings will break IDE linting support, which makes it very hard to work with. - // We can reconsider this if/when switching to Kotlin DSL, or if JetBrains gets their shit together. - project.repositories { - // Libraries has to be before maven central because Mojang hosts a classifer that central doesn't (org.lwjgl:lwjgl-freetype:3.3.3:natives-macos-patch) - maven { url = 'https://libraries.minecraft.net/' } - mavenCentral() - - project.pluginManager.withPlugin('net.minecraftforge.gradleutils') { - maven project.gradleutils.forgeMaven - } - - project.pluginManager.withPlugin('net.minecraftforge.forgedev') { - maven project.forgedev.mavenizer - } - - mavenLocal() - } -} - -dependencyResolutionManagement.versionCatalogs { - register('bootLibs') { - description = 'Important version numbers that are externally declared for easy modification.' - - // Contains Java, Minecraft, and MCP versions - from(files('minecraft.versions.toml')) - } - - register('buildLibs') { - description = 'Libraries used solely during the build and publish process.' - - library 'binarypatcher', 'net.minecraftforge', 'binarypatcher' version '1.3.4' - library 'installer', 'net.minecraftforge', 'installer' version '2.2.+' - library 'installertools', 'net.minecraftforge', 'installertools' version '1.4.5' - library 'srg2source', 'net.minecraftforge', 'Srg2Source' version '8.2.0' - } - - //@formatter:off - register('libs') { - description = 'Libraries used by Forge and its subprojects.' - - plugin 'licenser', 'net.minecraftforge.licenser' version '1.2.0' - plugin 'versions', 'com.github.ben-manes.versions' version '0.54.0' - plugin 'gradleutils', 'net.minecraftforge.gradleutils' version '3.4.5' - plugin 'gitversion', 'net.minecraftforge.gitversion' version '3.1.7' - plugin 'changelog', 'net.minecraftforge.changelog' version '3.2.2' - plugin 'download', 'de.undercouch.download' version '5.6.0' - plugin 'jarsigner', 'net.minecraftforge.gradlejarsigner' version '1.2.1' - plugin 'apt', 'com.diffplug.eclipse.apt' version '4.4.1' - - // TODO [Forge][Buildscript We should not be needing to manually add transitive dependencies - // If we need to make strict versions for dependencies, we should do so using dependency constraints - library 'forgespi', 'net.minecraftforge', 'forgespi' version '8.0.0' // Needs modlauncher - library 'modlauncher', 'net.minecraftforge', 'modlauncher' version '10.2.6' // Needs securemodules - library 'securemodules', 'net.minecraftforge', 'securemodules' version '2.2.24' // Needs unsafe - library 'unsafe', 'net.minecraftforge', 'unsafe' version '0.9.2' - library 'accesstransformers', 'net.minecraftforge', 'accesstransformers' version '8.2.17' - library 'coremods-api', 'net.minecraftforge', 'coremods-api' version '5.3.1' - version 'eventbus', '7.0.5' - library 'eventbus', 'net.minecraftforge', 'eventbus' versionRef 'eventbus' - library 'eventbus-validator', 'net.minecraftforge', 'eventbus-validator' versionRef 'eventbus' - library 'mergetool-api', 'net.minecraftforge', 'mergetool-api' version '1.0' - - library 'roimfs', 'net.minecraftforge', 'roimfs' version '1.0.0' // ReadOnlyInMemoryFileSystem - Used for JarInJar extraction at runtime - library 'mixin', 'org.spongepowered', 'mixin' version '0.8.7' - version 'mixinextras', '0.5.4' - library 'mixinextras-forge', 'io.github.llamalad7', 'mixinextras-forge' versionRef 'mixinextras' - library 'mixinextras-common', 'io.github.llamalad7', 'mixinextras-common' versionRef 'mixinextras' - library 'jetbrains-annotations', 'org.jetbrains', 'annotations' version '24.0.1' // for ApiStatus annotations - library 'jspecify', 'org.jspecify', 'jspecify' version '1.0.0' // for nullability annotations - library 'slf4j-api', 'org.slf4j', 'slf4j-api' version '2.0.17' - library 'maven-artifact', 'org.apache.maven', 'maven-artifact' version '3.8.8' - - // Google's InMemory File System. Used by ForgeDev Tests for now, but could be useful for a lot of things. - library 'jimfs', 'com.google.jimfs:jimfs:1.3.0' - bundle 'jimfs', ['guava', 'failureaccess'] - - version 'bootstrap', '2.1.8' - library 'bootstrap', 'net.minecraftforge', 'bootstrap' versionRef 'bootstrap' // Needs modlauncher - library 'bootstrap-api', 'net.minecraftforge', 'bootstrap-api' versionRef 'bootstrap' - library 'bootstrap-dev', 'net.minecraftforge', 'bootstrap-dev' versionRef 'bootstrap' - library 'bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim' versionRef 'bootstrap' - - // ASM it's used for so many of our hacks - version 'asm', '9.10.1' - 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' - library 'asm-commons', 'org.ow2.asm', 'asm-commons' versionRef 'asm' - library 'asm-analysis', 'org.ow2.asm', 'asm-analysis' versionRef 'asm' - bundle 'asm', ['asm', 'asm-tree', 'asm-util', 'asm-commons', 'asm-analysis'] - - // Terminal Console Appender. essentially make pretty colors in the console, but it's been a PITA - library 'terminalconsoleappender', 'net.minecrell', 'terminalconsoleappender' version '1.2.0' - version 'jline', '3.25.1' - library 'jline-reader', 'org.jline', 'jline-reader' versionRef 'jline' - library 'jline-terminal', 'org.jline', 'jline-terminal' versionRef 'jline' - library 'jline-terminal-jna', 'org.jline', 'jline-terminal-jna' versionRef 'jline' // Colors and tab completeion - bundle 'terminalconsoleappender', ['terminalconsoleappender', 'jline-reader', 'jline-terminal', 'jline-terminal-jna'] - - // The core of our configuration system, it has many flaws, but it works for the most part - version 'night-config', '3.7.4' - library 'night-config-toml', 'com.electronwill.night-config', 'toml' versionRef 'night-config' - library 'night-config-core', 'com.electronwill.night-config', 'core' versionRef 'night-config' - bundle 'night-config', ['night-config-toml', 'night-config-core'] - - // Jar in Jar FileSystem - version 'jarjar', '0.4.2' - library 'jarjar-fs', 'net.minecraftforge', 'JarJarFileSystems' versionRef 'jarjar' - library 'jarjar-meta', 'net.minecraftforge', 'JarJarMetadata' versionRef 'jarjar' - library 'jarjar-selector', 'net.minecraftforge', 'JarJarSelector' versionRef 'jarjar' - bundle 'jarjar', ['jarjar-fs', 'jarjar-selector', 'jarjar-meta'] - - // These are libraries shipped by the MC launcher, try and keep them in sync with the manifest - // but honestly if we don't it just means we ship them as normal libraries by adding them to the installer config in the forge project - library 'gson', 'com.google.code.gson', 'gson' version '2.14.0' - library 'guava', 'com.google.guava', 'guava' version '33.6.0-jre' - library 'failureaccess', 'com.google.guava', 'failureaccess' version '1.0.3' - - version 'log4j', '2.26.0' - library 'log4j-api', 'org.apache.logging.log4j', 'log4j-api' versionRef 'log4j' - library 'log4j-core', 'org.apache.logging.log4j', 'log4j-core' versionRef 'log4j' - bundle 'log4j', ['log4j-api', 'log4j-core'] - - library 'apache-commons', 'org.apache.commons', 'commons-lang3' version '3.20.0' - library 'mojang-logging', 'com.mojang', 'logging' version '1.7.12' - library 'jopt-simple', 'net.sf.jopt-simple', 'jopt-simple' version '5.0.4' - library 'commons-io', 'commons-io', 'commons-io' version '2.20.0' - - version 'lwjgl', '3.4.1' - 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' - library 'lwjgl-stb', 'org.lwjgl', 'lwjgl-stb' versionRef 'lwjgl' - library 'lwjgl-tinyfd', 'org.lwjgl', 'lwjgl-tinyfd' versionRef 'lwjgl' - bundle 'lwjgl', ['lwjgl', 'lwjgl-glfw', 'lwjgl-opengl', 'lwjgl-stb', 'lwjgl-tinyfd'] - } - - register('earlyDisplayLibs') { - version 'slf4j', '2.0.17' - library 'slf4j-api', 'org.slf4j', 'slf4j-api' versionRef 'slf4j' - library 'slf4j-jdk14', 'org.slf4j', 'slf4j-jdk14' versionRef 'slf4j' - } - - register('earlyDisplayTestLibs') { - library 'powermock-core', 'org.powermock', 'powermock-core' version '2.0.9' - - library 'lwjgl', 'org.lwjgl', 'lwjgl' withoutVersion() - library 'lwjgl-glfw', 'org.lwjgl', 'lwjgl-glfw' withoutVersion() - library 'lwjgl-opengl', 'org.lwjgl', 'lwjgl-opengl' withoutVersion() - library 'lwjgl-stb', 'org.lwjgl', 'lwjgl-stb' withoutVersion() - bundle 'lwjgl', ['lwjgl', 'lwjgl-glfw', 'lwjgl-opengl', 'lwjgl-stb'] - } - //@formatter:on +if (false && !System.env.TEAMCITY_VERSION) { + include ':clean' + project(':clean').projectDir = file('projects/clean') + project(':clean').buildFileName = '../../build_clean.gradle' } diff --git a/src/main/generated/assets/minecraft/atlases/items.json b/src/main/generated/assets/minecraft/atlases/items.json deleted file mode 100644 index 6dd66854ab..0000000000 --- a/src/main/generated/assets/minecraft/atlases/items.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "sources": [ - { - "type": "minecraft:single", - "resource": "minecraft:block/lava_still", - "sprite": "minecraft:item/lava_still" - }, - { - "type": "minecraft:single", - "resource": "minecraft:block/water_still", - "sprite": "minecraft:item/water_still" - } - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/bars.json b/src/main/generated/data/c/tags/block/bars.json deleted file mode 100644 index 4f62bc5ffc..0000000000 --- a/src/main/generated/data/c/tags/block/bars.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "values": [ - "#c:bars/copper", - "#c:bars/iron", - "#minecraft:bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/bars/copper.json b/src/main/generated/data/c/tags/block/bars/copper.json deleted file mode 100644 index f11b169128..0000000000 --- a/src/main/generated/data/c/tags/block/bars/copper.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "values": [ - "minecraft:copper_bars", - "minecraft:exposed_copper_bars", - "minecraft:weathered_copper_bars", - "minecraft:oxidized_copper_bars", - "minecraft:waxed_copper_bars", - "minecraft:waxed_exposed_copper_bars", - "minecraft:waxed_weathered_copper_bars", - "minecraft:waxed_oxidized_copper_bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/bars/iron.json b/src/main/generated/data/c/tags/block/bars/iron.json deleted file mode 100644 index ba12ec6f5a..0000000000 --- a/src/main/generated/data/c/tags/block/bars/iron.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "minecraft:iron_bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/chains.json b/src/main/generated/data/c/tags/block/chains.json index daba291fc0..58c2b30a5a 100644 --- a/src/main/generated/data/c/tags/block/chains.json +++ b/src/main/generated/data/c/tags/block/chains.json @@ -2,12 +2,12 @@ "values": [ "minecraft:iron_chain", "minecraft:copper_chain", - "minecraft:exposed_copper_chain", - "minecraft:weathered_copper_chain", - "minecraft:oxidized_copper_chain", "minecraft:waxed_copper_chain", + "minecraft:exposed_copper_chain", "minecraft:waxed_exposed_copper_chain", + "minecraft:weathered_copper_chain", "minecraft:waxed_weathered_copper_chain", + "minecraft:oxidized_copper_chain", "minecraft:waxed_oxidized_copper_chain" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/chests.json b/src/main/generated/data/c/tags/block/chests.json index 192ace8c7f..16ea314685 100644 --- a/src/main/generated/data/c/tags/block/chests.json +++ b/src/main/generated/data/c/tags/block/chests.json @@ -1,13 +1,6 @@ { "values": [ "minecraft:copper_chest", - "minecraft:exposed_copper_chest", - "minecraft:weathered_copper_chest", - "minecraft:oxidized_copper_chest", - "minecraft:waxed_copper_chest", - "minecraft:waxed_exposed_copper_chest", - "minecraft:waxed_weathered_copper_chest", - "minecraft:waxed_oxidized_copper_chest", "#c:chests/ender", "#c:chests/trapped", "#c:chests/wooden" diff --git a/src/main/generated/data/c/tags/block/flowers/tall.json b/src/main/generated/data/c/tags/block/flowers/tall.json index 144eb89e0a..1944a475be 100644 --- a/src/main/generated/data/c/tags/block/flowers/tall.json +++ b/src/main/generated/data/c/tags/block/flowers/tall.json @@ -4,6 +4,10 @@ "minecraft:lilac", "minecraft:peony", "minecraft:rose_bush", - "minecraft:pitcher_plant" + "minecraft:pitcher_plant", + { + "id": "minecraft:tall_flowers", + "required": false + } ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/skulls.json b/src/main/generated/data/c/tags/block/skulls.json index 063402cdbf..a9820b074f 100644 --- a/src/main/generated/data/c/tags/block/skulls.json +++ b/src/main/generated/data/c/tags/block/skulls.json @@ -1,18 +1,18 @@ { "values": [ "minecraft:skeleton_skull", - "minecraft:wither_skeleton_skull", - "minecraft:player_head", - "minecraft:zombie_head", - "minecraft:creeper_head", - "minecraft:piglin_head", - "minecraft:dragon_head", "minecraft:skeleton_wall_skull", + "minecraft:wither_skeleton_skull", "minecraft:wither_skeleton_wall_skull", + "minecraft:player_head", "minecraft:player_wall_head", + "minecraft:zombie_head", "minecraft:zombie_wall_head", + "minecraft:creeper_head", "minecraft:creeper_wall_head", + "minecraft:piglin_head", "minecraft:piglin_wall_head", + "minecraft:dragon_head", "minecraft:dragon_wall_head" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/storage_blocks/copper.json b/src/main/generated/data/c/tags/block/storage_blocks/copper.json index 538486501f..015bec70c3 100644 --- a/src/main/generated/data/c/tags/block/storage_blocks/copper.json +++ b/src/main/generated/data/c/tags/block/storage_blocks/copper.json @@ -1,12 +1,5 @@ { "values": [ - "minecraft:copper_block", - "minecraft:exposed_copper", - "minecraft:weathered_copper", - "minecraft:oxidized_copper", - "minecraft:waxed_copper_block", - "minecraft:waxed_exposed_copper", - "minecraft:waxed_weathered_copper", - "minecraft:waxed_oxidized_copper" + "minecraft:copper_block" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/villager_job_sites.json b/src/main/generated/data/c/tags/block/villager_job_sites.json index 714e373cca..859c128fce 100644 --- a/src/main/generated/data/c/tags/block/villager_job_sites.json +++ b/src/main/generated/data/c/tags/block/villager_job_sites.json @@ -5,6 +5,9 @@ "minecraft:brewing_stand", "minecraft:cartography_table", "minecraft:cauldron", + "minecraft:water_cauldron", + "minecraft:lava_cauldron", + "minecraft:powder_snow_cauldron", "minecraft:composter", "minecraft:fletching_table", "minecraft:grindstone", @@ -12,9 +15,6 @@ "minecraft:loom", "minecraft:smithing_table", "minecraft:smoker", - "minecraft:stonecutter", - "minecraft:water_cauldron", - "minecraft:lava_cauldron", - "minecraft:powder_snow_cauldron" + "minecraft:stonecutter" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/bars.json b/src/main/generated/data/c/tags/item/bars.json deleted file mode 100644 index 4f62bc5ffc..0000000000 --- a/src/main/generated/data/c/tags/item/bars.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "values": [ - "#c:bars/copper", - "#c:bars/iron", - "#minecraft:bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/bars/copper.json b/src/main/generated/data/c/tags/item/bars/copper.json deleted file mode 100644 index f11b169128..0000000000 --- a/src/main/generated/data/c/tags/item/bars/copper.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "values": [ - "minecraft:copper_bars", - "minecraft:exposed_copper_bars", - "minecraft:weathered_copper_bars", - "minecraft:oxidized_copper_bars", - "minecraft:waxed_copper_bars", - "minecraft:waxed_exposed_copper_bars", - "minecraft:waxed_weathered_copper_bars", - "minecraft:waxed_oxidized_copper_bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/bars/iron.json b/src/main/generated/data/c/tags/item/bars/iron.json deleted file mode 100644 index ba12ec6f5a..0000000000 --- a/src/main/generated/data/c/tags/item/bars/iron.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "minecraft:iron_bars" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/chains.json b/src/main/generated/data/c/tags/item/chains.json index daba291fc0..58c2b30a5a 100644 --- a/src/main/generated/data/c/tags/item/chains.json +++ b/src/main/generated/data/c/tags/item/chains.json @@ -2,12 +2,12 @@ "values": [ "minecraft:iron_chain", "minecraft:copper_chain", - "minecraft:exposed_copper_chain", - "minecraft:weathered_copper_chain", - "minecraft:oxidized_copper_chain", "minecraft:waxed_copper_chain", + "minecraft:exposed_copper_chain", "minecraft:waxed_exposed_copper_chain", + "minecraft:weathered_copper_chain", "minecraft:waxed_weathered_copper_chain", + "minecraft:oxidized_copper_chain", "minecraft:waxed_oxidized_copper_chain" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/chests.json b/src/main/generated/data/c/tags/item/chests.json index 192ace8c7f..16ea314685 100644 --- a/src/main/generated/data/c/tags/item/chests.json +++ b/src/main/generated/data/c/tags/item/chests.json @@ -1,13 +1,6 @@ { "values": [ "minecraft:copper_chest", - "minecraft:exposed_copper_chest", - "minecraft:weathered_copper_chest", - "minecraft:oxidized_copper_chest", - "minecraft:waxed_copper_chest", - "minecraft:waxed_exposed_copper_chest", - "minecraft:waxed_weathered_copper_chest", - "minecraft:waxed_oxidized_copper_chest", "#c:chests/ender", "#c:chests/trapped", "#c:chests/wooden" diff --git a/src/main/generated/data/c/tags/item/drink_containing/bottle.json b/src/main/generated/data/c/tags/item/drink_containing/bottle.json deleted file mode 100644 index 068ca91291..0000000000 --- a/src/main/generated/data/c/tags/item/drink_containing/bottle.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "values": [ - "minecraft:potion", - "minecraft:honey_bottle", - "minecraft:ominous_bottle" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/drink_containing/bucket.json b/src/main/generated/data/c/tags/item/drink_containing/bucket.json deleted file mode 100644 index 899451cb24..0000000000 --- a/src/main/generated/data/c/tags/item/drink_containing/bucket.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "minecraft:milk_bucket" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/foods/dough.json b/src/main/generated/data/c/tags/item/foods/dough.json deleted file mode 100644 index f72d209df7..0000000000 --- a/src/main/generated/data/c/tags/item/foods/dough.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "values": [] -} \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/foods/vegetable.json b/src/main/generated/data/c/tags/item/foods/vegetable.json index d48dd4228c..17ecdb1ca6 100644 --- a/src/main/generated/data/c/tags/item/foods/vegetable.json +++ b/src/main/generated/data/c/tags/item/foods/vegetable.json @@ -1,8 +1,8 @@ { "values": [ - "minecraft:golden_carrot", - "minecraft:beetroot", "minecraft:carrot", - "minecraft:potato" + "minecraft:golden_carrot", + "minecraft:potato", + "minecraft:beetroot" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/storage_blocks/copper.json b/src/main/generated/data/c/tags/item/storage_blocks/copper.json index 538486501f..015bec70c3 100644 --- a/src/main/generated/data/c/tags/item/storage_blocks/copper.json +++ b/src/main/generated/data/c/tags/item/storage_blocks/copper.json @@ -1,12 +1,5 @@ { "values": [ - "minecraft:copper_block", - "minecraft:exposed_copper", - "minecraft:weathered_copper", - "minecraft:oxidized_copper", - "minecraft:waxed_copper_block", - "minecraft:waxed_exposed_copper", - "minecraft:waxed_weathered_copper", - "minecraft:waxed_oxidized_copper" + "minecraft:copper_block" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/tools.json b/src/main/generated/data/c/tags/item/tools.json index 8099500241..093ece2873 100644 --- a/src/main/generated/data/c/tags/item/tools.json +++ b/src/main/generated/data/c/tags/item/tools.json @@ -12,7 +12,7 @@ "#c:tools/shear", "#c:tools/igniter", "#c:tools/shield", - "#c:tools/trident", + "#c:tools/spear", "#c:tools/mace", "#c:tools/mining_tool", "#c:tools/melee_weapon", diff --git a/src/main/generated/data/c/tags/item/tools/melee_weapon.json b/src/main/generated/data/c/tags/item/tools/melee_weapon.json index 0f91924b7d..2bb3c599d0 100644 --- a/src/main/generated/data/c/tags/item/tools/melee_weapon.json +++ b/src/main/generated/data/c/tags/item/tools/melee_weapon.json @@ -15,13 +15,6 @@ "minecraft:golden_axe", "minecraft:iron_axe", "minecraft:diamond_axe", - "minecraft:netherite_axe", - "minecraft:wooden_spear", - "minecraft:stone_spear", - "minecraft:copper_spear", - "minecraft:iron_spear", - "minecraft:golden_spear", - "minecraft:diamond_spear", - "minecraft:netherite_spear" + "minecraft:netherite_axe" ] } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/item/tools/trident.json b/src/main/generated/data/c/tags/item/tools/spear.json similarity index 100% rename from src/main/generated/data/c/tags/item/tools/trident.json rename to src/main/generated/data/c/tags/item/tools/spear.json diff --git a/src/main/generated/data/minecraft/loot_table/blocks/acacia_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/acacia_leaves.json index 76b0651a2d..6b168e6299 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/acacia_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/acacia_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/azalea_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/azalea_leaves.json index e2688d9d93..728ca83253 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/azalea_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/azalea_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/birch_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/birch_leaves.json index d785dae910..bc635e84ac 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/birch_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/birch_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/bush.json b/src/main/generated/data/minecraft/loot_table/blocks/bush.json index ec187ebbd4..f339200a8c 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/bush.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/bush.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:any_of", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/cherry_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/cherry_leaves.json index 2b06aae023..c5ffbbd7b3 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/cherry_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/cherry_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/cobweb.json b/src/main/generated/data/minecraft/loot_table/blocks/cobweb.json index dccc612281..0fc81358f5 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/cobweb.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/cobweb.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/dark_oak_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/dark_oak_leaves.json index 835b4f54ba..c866e9aa27 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/dark_oak_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/dark_oak_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, @@ -125,6 +128,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/dead_bush.json b/src/main/generated/data/minecraft/loot_table/blocks/dead_bush.json index fa44726bc4..1f9d8b5378 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/dead_bush.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/dead_bush.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -20,6 +21,7 @@ "type": "minecraft:item", "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/fern.json b/src/main/generated/data/minecraft/loot_table/blocks/fern.json index de279d9d4e..e89145df53 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/fern.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/fern.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/flowering_azalea_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/flowering_azalea_leaves.json index d284eafbc5..db47a087d9 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/flowering_azalea_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/flowering_azalea_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/glow_lichen.json b/src/main/generated/data/minecraft/loot_table/blocks/glow_lichen.json index 56563b3457..5415d24862 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/glow_lichen.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/glow_lichen.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:item", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/hanging_roots.json b/src/main/generated/data/minecraft/loot_table/blocks/hanging_roots.json index da9a870588..6e84cafd44 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/hanging_roots.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/hanging_roots.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/jungle_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/jungle_leaves.json index 2901f7814f..d56cdc0697 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/jungle_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/jungle_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -62,6 +63,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -109,6 +111,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/large_fern.json b/src/main/generated/data/minecraft/loot_table/blocks/large_fern.json index 4dbcfcfd5f..22b7513724 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/large_fern.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/large_fern.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "block": "minecraft:large_fern", @@ -37,6 +38,7 @@ ], "functions": [ { + "add": false, "count": 2.0, "function": "minecraft:set_count" } @@ -62,6 +64,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "block": "minecraft:large_fern", @@ -97,6 +100,7 @@ ], "functions": [ { + "add": false, "count": 2.0, "function": "minecraft:set_count" } diff --git a/src/main/generated/data/minecraft/loot_table/blocks/mangrove_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/mangrove_leaves.json index ab53c93864..4601627c2a 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/mangrove_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/mangrove_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -53,6 +54,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/nether_sprouts.json b/src/main/generated/data/minecraft/loot_table/blocks/nether_sprouts.json index 67258724b2..d0aee8945e 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/nether_sprouts.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/nether_sprouts.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/oak_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/oak_leaves.json index 69933a1855..59c4a3c458 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/oak_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/oak_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, @@ -125,6 +128,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/pale_hanging_moss.json b/src/main/generated/data/minecraft/loot_table/blocks/pale_hanging_moss.json index ddaef52c33..a186e96ba4 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/pale_hanging_moss.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/pale_hanging_moss.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:any_of", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/pale_oak_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/pale_oak_leaves.json index 7e9ae46ff0..8e75c5a242 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/pale_oak_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/pale_oak_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/seagrass.json b/src/main/generated/data/minecraft/loot_table/blocks/seagrass.json index c806404eaa..383923d251 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/seagrass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/seagrass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/short_dry_grass.json b/src/main/generated/data/minecraft/loot_table/blocks/short_dry_grass.json index 073531704f..84f1103b9b 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/short_dry_grass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/short_dry_grass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:any_of", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/short_grass.json b/src/main/generated/data/minecraft/loot_table/blocks/short_grass.json index 6c1b1492fb..c75f40d2fe 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/short_grass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/short_grass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/small_dripleaf.json b/src/main/generated/data/minecraft/loot_table/blocks/small_dripleaf.json index c7aa5e9724..e7bb2ff6d1 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/small_dripleaf.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/small_dripleaf.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/spruce_leaves.json b/src/main/generated/data/minecraft/loot_table/blocks/spruce_leaves.json index 40d83f352e..70115ff27f 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/spruce_leaves.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/spruce_leaves.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", @@ -61,6 +62,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:inverted", @@ -108,6 +110,7 @@ ], "functions": [ { + "add": false, "count": { "type": "minecraft:uniform", "max": 2.0, diff --git a/src/main/generated/data/minecraft/loot_table/blocks/tall_dry_grass.json b/src/main/generated/data/minecraft/loot_table/blocks/tall_dry_grass.json index cfc332693c..0bf2a9912d 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/tall_dry_grass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/tall_dry_grass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:any_of", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/tall_grass.json b/src/main/generated/data/minecraft/loot_table/blocks/tall_grass.json index d0c7d31e68..4391e321ef 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/tall_grass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/tall_grass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "block": "minecraft:tall_grass", @@ -37,6 +38,7 @@ ], "functions": [ { + "add": false, "count": 2.0, "function": "minecraft:set_count" } @@ -62,6 +64,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "conditions": [ { "block": "minecraft:tall_grass", @@ -97,6 +100,7 @@ ], "functions": [ { + "add": false, "count": 2.0, "function": "minecraft:set_count" } diff --git a/src/main/generated/data/minecraft/loot_table/blocks/tall_seagrass.json b/src/main/generated/data/minecraft/loot_table/blocks/tall_seagrass.json index 452880c35b..fa8d199f02 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/tall_seagrass.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/tall_seagrass.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", @@ -13,6 +14,7 @@ "type": "minecraft:item", "functions": [ { + "add": false, "count": 2.0, "function": "minecraft:set_count" } diff --git a/src/main/generated/data/minecraft/loot_table/blocks/twisting_vines.json b/src/main/generated/data/minecraft/loot_table/blocks/twisting_vines.json index 543c463516..add7780f43 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/twisting_vines.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/twisting_vines.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/vine.json b/src/main/generated/data/minecraft/loot_table/blocks/vine.json index 5fc89d2081..94c46af2c1 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/vine.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/vine.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "action": "shears_dig", diff --git a/src/main/generated/data/minecraft/loot_table/blocks/weeping_vines.json b/src/main/generated/data/minecraft/loot_table/blocks/weeping_vines.json index ab00aeccc5..d782c26b41 100644 --- a/src/main/generated/data/minecraft/loot_table/blocks/weeping_vines.json +++ b/src/main/generated/data/minecraft/loot_table/blocks/weeping_vines.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:alternatives", diff --git a/src/main/generated/data/minecraft/recipe/acacia_chest_boat.json b/src/main/generated/data/minecraft/recipe/acacia_chest_boat.json index eb2e6f98f0..ccdd3c5ead 100644 --- a/src/main/generated/data/minecraft/recipe/acacia_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/acacia_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/acacia_fence.json b/src/main/generated/data/minecraft/recipe/acacia_fence.json index 6c6a000970..abc4d37cba 100644 --- a/src/main/generated/data/minecraft/recipe/acacia_fence.json +++ b/src/main/generated/data/minecraft/recipe/acacia_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/acacia_sign.json b/src/main/generated/data/minecraft/recipe/acacia_sign.json index 8a03c68de4..3232b1b89a 100644 --- a/src/main/generated/data/minecraft/recipe/acacia_sign.json +++ b/src/main/generated/data/minecraft/recipe/acacia_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:acacia_planks", diff --git a/src/main/generated/data/minecraft/recipe/activator_rail.json b/src/main/generated/data/minecraft/recipe/activator_rail.json index 4fa1b01904..555bb300db 100644 --- a/src/main/generated/data/minecraft/recipe/activator_rail.json +++ b/src/main/generated/data/minecraft/recipe/activator_rail.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "minecraft:redstone_torch", "S": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/anvil.json b/src/main/generated/data/minecraft/recipe/anvil.json index fc40541868..b6bbfbf821 100644 --- a/src/main/generated/data/minecraft/recipe/anvil.json +++ b/src/main/generated/data/minecraft/recipe/anvil.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "I": "minecraft:iron_block", "i": "#c:ingots/iron" diff --git a/src/main/generated/data/minecraft/recipe/armor_stand.json b/src/main/generated/data/minecraft/recipe/armor_stand.json index 09aaff0756..938c8d80c4 100644 --- a/src/main/generated/data/minecraft/recipe/armor_stand.json +++ b/src/main/generated/data/minecraft/recipe/armor_stand.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "/": "#c:rods/wooden", "_": "minecraft:smooth_stone_slab" diff --git a/src/main/generated/data/minecraft/recipe/bamboo_chest_raft.json b/src/main/generated/data/minecraft/recipe/bamboo_chest_raft.json index bcaa8136ee..eb6bf0e6c7 100644 --- a/src/main/generated/data/minecraft/recipe/bamboo_chest_raft.json +++ b/src/main/generated/data/minecraft/recipe/bamboo_chest_raft.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/bamboo_fence.json b/src/main/generated/data/minecraft/recipe/bamboo_fence.json index 9730b110af..d36413016a 100644 --- a/src/main/generated/data/minecraft/recipe/bamboo_fence.json +++ b/src/main/generated/data/minecraft/recipe/bamboo_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/bamboo_sign.json b/src/main/generated/data/minecraft/recipe/bamboo_sign.json index ae6b9c61e8..79d256d984 100644 --- a/src/main/generated/data/minecraft/recipe/bamboo_sign.json +++ b/src/main/generated/data/minecraft/recipe/bamboo_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:bamboo_planks", diff --git a/src/main/generated/data/minecraft/recipe/birch_chest_boat.json b/src/main/generated/data/minecraft/recipe/birch_chest_boat.json index f887571b42..fb964e091f 100644 --- a/src/main/generated/data/minecraft/recipe/birch_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/birch_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/birch_fence.json b/src/main/generated/data/minecraft/recipe/birch_fence.json index ecf986d15e..f340e905c3 100644 --- a/src/main/generated/data/minecraft/recipe/birch_fence.json +++ b/src/main/generated/data/minecraft/recipe/birch_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/birch_sign.json b/src/main/generated/data/minecraft/recipe/birch_sign.json index f74bb206c3..94b286ed75 100644 --- a/src/main/generated/data/minecraft/recipe/birch_sign.json +++ b/src/main/generated/data/minecraft/recipe/birch_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:birch_planks", diff --git a/src/main/generated/data/minecraft/recipe/black_banner.json b/src/main/generated/data/minecraft/recipe/black_banner.json index bbc855b37f..20fa2d9737 100644 --- a/src/main/generated/data/minecraft/recipe/black_banner.json +++ b/src/main/generated/data/minecraft/recipe/black_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:black_wool", diff --git a/src/main/generated/data/minecraft/recipe/blast_furnace.json b/src/main/generated/data/minecraft/recipe/blast_furnace.json index 6aca85ac79..e6d456e1d3 100644 --- a/src/main/generated/data/minecraft/recipe/blast_furnace.json +++ b/src/main/generated/data/minecraft/recipe/blast_furnace.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "minecraft:smooth_stone", "I": "#c:ingots/iron", diff --git a/src/main/generated/data/minecraft/recipe/blue_banner.json b/src/main/generated/data/minecraft/recipe/blue_banner.json index e529c7eb88..ef898a8586 100644 --- a/src/main/generated/data/minecraft/recipe/blue_banner.json +++ b/src/main/generated/data/minecraft/recipe/blue_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:blue_wool", diff --git a/src/main/generated/data/minecraft/recipe/bolt_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/bolt_armor_trim_smithing_template.json index 628de82168..e5db16797d 100644 --- a/src/main/generated/data/minecraft/recipe/bolt_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/bolt_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": [ diff --git a/src/main/generated/data/minecraft/recipe/brown_banner.json b/src/main/generated/data/minecraft/recipe/brown_banner.json index ff3b670602..4fe52af768 100644 --- a/src/main/generated/data/minecraft/recipe/brown_banner.json +++ b/src/main/generated/data/minecraft/recipe/brown_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:brown_wool", diff --git a/src/main/generated/data/minecraft/recipe/bucket.json b/src/main/generated/data/minecraft/recipe/bucket.json index 447b848ac1..98599240ce 100644 --- a/src/main/generated/data/minecraft/recipe/bucket.json +++ b/src/main/generated/data/minecraft/recipe/bucket.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/iron" }, diff --git a/src/main/generated/data/minecraft/recipe/campfire.json b/src/main/generated/data/minecraft/recipe/campfire.json index 10da3b72d2..93372c24ec 100644 --- a/src/main/generated/data/minecraft/recipe/campfire.json +++ b/src/main/generated/data/minecraft/recipe/campfire.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "C": "#minecraft:coals", "L": "#minecraft:logs", diff --git a/src/main/generated/data/minecraft/recipe/candle.json b/src/main/generated/data/minecraft/recipe/candle.json index 9e9b03ea16..953a680359 100644 --- a/src/main/generated/data/minecraft/recipe/candle.json +++ b/src/main/generated/data/minecraft/recipe/candle.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "H": "minecraft:honeycomb", "S": "#c:strings" diff --git a/src/main/generated/data/minecraft/recipe/cauldron.json b/src/main/generated/data/minecraft/recipe/cauldron.json index e4f76c54fb..936cc35ecb 100644 --- a/src/main/generated/data/minecraft/recipe/cauldron.json +++ b/src/main/generated/data/minecraft/recipe/cauldron.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/iron" }, diff --git a/src/main/generated/data/minecraft/recipe/cherry_chest_boat.json b/src/main/generated/data/minecraft/recipe/cherry_chest_boat.json index ab5750cbd1..841e525c6b 100644 --- a/src/main/generated/data/minecraft/recipe/cherry_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/cherry_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/cherry_fence.json b/src/main/generated/data/minecraft/recipe/cherry_fence.json index b1d0626d72..9866480fe0 100644 --- a/src/main/generated/data/minecraft/recipe/cherry_fence.json +++ b/src/main/generated/data/minecraft/recipe/cherry_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/cherry_sign.json b/src/main/generated/data/minecraft/recipe/cherry_sign.json index febe767664..000659bd4a 100644 --- a/src/main/generated/data/minecraft/recipe/cherry_sign.json +++ b/src/main/generated/data/minecraft/recipe/cherry_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:cherry_planks", diff --git a/src/main/generated/data/minecraft/recipe/chest_minecart.json b/src/main/generated/data/minecraft/recipe/chest_minecart.json index adbeb2d5cb..53958c8406 100644 --- a/src/main/generated/data/minecraft/recipe/chest_minecart.json +++ b/src/main/generated/data/minecraft/recipe/chest_minecart.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "#c:chests/wooden", "minecraft:minecart" diff --git a/src/main/generated/data/minecraft/recipe/coast_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/coast_armor_trim_smithing_template.json index 680d59584f..91af5fbabf 100644 --- a/src/main/generated/data/minecraft/recipe/coast_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/coast_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "#c:cobblestones/normal", diff --git a/src/main/generated/data/minecraft/recipe/copper_bars.json b/src/main/generated/data/minecraft/recipe/copper_bars.json index 20d2045949..57c1a88ba8 100644 --- a/src/main/generated/data/minecraft/recipe/copper_bars.json +++ b/src/main/generated/data/minecraft/recipe/copper_bars.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/copper" }, diff --git a/src/main/generated/data/minecraft/recipe/copper_chain.json b/src/main/generated/data/minecraft/recipe/copper_chain.json index 4abf563b44..51909893cd 100644 --- a/src/main/generated/data/minecraft/recipe/copper_chain.json +++ b/src/main/generated/data/minecraft/recipe/copper_chain.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "I": "#c:ingots/copper", "N": "minecraft:copper_nugget" diff --git a/src/main/generated/data/minecraft/recipe/copper_chest.json b/src/main/generated/data/minecraft/recipe/copper_chest.json index 440f5201a8..786c2104a4 100644 --- a/src/main/generated/data/minecraft/recipe/copper_chest.json +++ b/src/main/generated/data/minecraft/recipe/copper_chest.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/copper", "X": "#c:chests/wooden" diff --git a/src/main/generated/data/minecraft/recipe/copper_nugget.json b/src/main/generated/data/minecraft/recipe/copper_nugget.json index 43f2d8b76e..6309a958a8 100644 --- a/src/main/generated/data/minecraft/recipe/copper_nugget.json +++ b/src/main/generated/data/minecraft/recipe/copper_nugget.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "#c:ingots/copper" ], diff --git a/src/main/generated/data/minecraft/recipe/copper_torch.json b/src/main/generated/data/minecraft/recipe/copper_torch.json index a6d835a1c5..4bde6043d5 100644 --- a/src/main/generated/data/minecraft/recipe/copper_torch.json +++ b/src/main/generated/data/minecraft/recipe/copper_torch.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "C": "minecraft:copper_nugget", diff --git a/src/main/generated/data/minecraft/recipe/crimson_fence.json b/src/main/generated/data/minecraft/recipe/crimson_fence.json index 1bef1ecd26..20e9d8a6e3 100644 --- a/src/main/generated/data/minecraft/recipe/crimson_fence.json +++ b/src/main/generated/data/minecraft/recipe/crimson_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/crimson_sign.json b/src/main/generated/data/minecraft/recipe/crimson_sign.json index d89fbe0ad2..b175242019 100644 --- a/src/main/generated/data/minecraft/recipe/crimson_sign.json +++ b/src/main/generated/data/minecraft/recipe/crimson_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:crimson_planks", diff --git a/src/main/generated/data/minecraft/recipe/cyan_banner.json b/src/main/generated/data/minecraft/recipe/cyan_banner.json index b6c3fcb7b0..39eab34e3e 100644 --- a/src/main/generated/data/minecraft/recipe/cyan_banner.json +++ b/src/main/generated/data/minecraft/recipe/cyan_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:cyan_wool", diff --git a/src/main/generated/data/minecraft/recipe/dark_oak_chest_boat.json b/src/main/generated/data/minecraft/recipe/dark_oak_chest_boat.json index cda05e602b..0cb611b14e 100644 --- a/src/main/generated/data/minecraft/recipe/dark_oak_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/dark_oak_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/dark_oak_fence.json b/src/main/generated/data/minecraft/recipe/dark_oak_fence.json index 0104840445..d5c3933be8 100644 --- a/src/main/generated/data/minecraft/recipe/dark_oak_fence.json +++ b/src/main/generated/data/minecraft/recipe/dark_oak_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/dark_oak_sign.json b/src/main/generated/data/minecraft/recipe/dark_oak_sign.json index 0905d76807..aeb6ace8bf 100644 --- a/src/main/generated/data/minecraft/recipe/dark_oak_sign.json +++ b/src/main/generated/data/minecraft/recipe/dark_oak_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:dark_oak_planks", diff --git a/src/main/generated/data/minecraft/recipe/detector_rail.json b/src/main/generated/data/minecraft/recipe/detector_rail.json index b7fc13cdcd..aa0d8b1f83 100644 --- a/src/main/generated/data/minecraft/recipe/detector_rail.json +++ b/src/main/generated/data/minecraft/recipe/detector_rail.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "minecraft:stone_pressure_plate", "R": "minecraft:redstone", diff --git a/src/main/generated/data/minecraft/recipe/dune_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/dune_armor_trim_smithing_template.json index f1a0c7f59c..a732119fe5 100644 --- a/src/main/generated/data/minecraft/recipe/dune_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/dune_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:sandstone", diff --git a/src/main/generated/data/minecraft/recipe/enchanting_table.json b/src/main/generated/data/minecraft/recipe/enchanting_table.json index 55908f490a..bfe6ac2770 100644 --- a/src/main/generated/data/minecraft/recipe/enchanting_table.json +++ b/src/main/generated/data/minecraft/recipe/enchanting_table.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "minecraft:obsidian", "B": "minecraft:book", diff --git a/src/main/generated/data/minecraft/recipe/eye_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/eye_armor_trim_smithing_template.json index 30e1a0feb8..24c0e2e4ad 100644 --- a/src/main/generated/data/minecraft/recipe/eye_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/eye_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:end_stone", diff --git a/src/main/generated/data/minecraft/recipe/flow_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/flow_armor_trim_smithing_template.json index c625dfd37c..958fdf6b4c 100644 --- a/src/main/generated/data/minecraft/recipe/flow_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/flow_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:breeze_rod", diff --git a/src/main/generated/data/minecraft/recipe/golden_apple.json b/src/main/generated/data/minecraft/recipe/golden_apple.json index b7446f43e0..bc73ddf140 100644 --- a/src/main/generated/data/minecraft/recipe/golden_apple.json +++ b/src/main/generated/data/minecraft/recipe/golden_apple.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/gold", "X": "minecraft:apple" diff --git a/src/main/generated/data/minecraft/recipe/gray_banner.json b/src/main/generated/data/minecraft/recipe/gray_banner.json index a257155230..5b383dfe15 100644 --- a/src/main/generated/data/minecraft/recipe/gray_banner.json +++ b/src/main/generated/data/minecraft/recipe/gray_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:gray_wool", diff --git a/src/main/generated/data/minecraft/recipe/green_banner.json b/src/main/generated/data/minecraft/recipe/green_banner.json index 05a5f5d812..b39debf52e 100644 --- a/src/main/generated/data/minecraft/recipe/green_banner.json +++ b/src/main/generated/data/minecraft/recipe/green_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:green_wool", diff --git a/src/main/generated/data/minecraft/recipe/grindstone.json b/src/main/generated/data/minecraft/recipe/grindstone.json index 92c80c562b..7bfe1abe16 100644 --- a/src/main/generated/data/minecraft/recipe/grindstone.json +++ b/src/main/generated/data/minecraft/recipe/grindstone.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#minecraft:planks", "-": "minecraft:stone_slab", diff --git a/src/main/generated/data/minecraft/recipe/host_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/host_armor_trim_smithing_template.json index f6c673ad85..ae84d48cc6 100644 --- a/src/main/generated/data/minecraft/recipe/host_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/host_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:terracotta", diff --git a/src/main/generated/data/minecraft/recipe/iron_bars.json b/src/main/generated/data/minecraft/recipe/iron_bars.json index 9ff84ac625..e33ecdcc4f 100644 --- a/src/main/generated/data/minecraft/recipe/iron_bars.json +++ b/src/main/generated/data/minecraft/recipe/iron_bars.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/iron" }, diff --git a/src/main/generated/data/minecraft/recipe/iron_chain.json b/src/main/generated/data/minecraft/recipe/iron_chain.json index cc7b7e3449..6ca1a0bda5 100644 --- a/src/main/generated/data/minecraft/recipe/iron_chain.json +++ b/src/main/generated/data/minecraft/recipe/iron_chain.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "I": "#c:ingots/iron", "N": "minecraft:iron_nugget" diff --git a/src/main/generated/data/minecraft/recipe/item_frame.json b/src/main/generated/data/minecraft/recipe/item_frame.json index e553296ccd..3cbb9b2183 100644 --- a/src/main/generated/data/minecraft/recipe/item_frame.json +++ b/src/main/generated/data/minecraft/recipe/item_frame.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "X": "minecraft:leather" diff --git a/src/main/generated/data/minecraft/recipe/jukebox.json b/src/main/generated/data/minecraft/recipe/jukebox.json index eb3d291fdd..389ac126c8 100644 --- a/src/main/generated/data/minecraft/recipe/jukebox.json +++ b/src/main/generated/data/minecraft/recipe/jukebox.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#minecraft:planks", "X": "#c:gems/diamond" diff --git a/src/main/generated/data/minecraft/recipe/jungle_chest_boat.json b/src/main/generated/data/minecraft/recipe/jungle_chest_boat.json index 5478d47d17..70883bace5 100644 --- a/src/main/generated/data/minecraft/recipe/jungle_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/jungle_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/jungle_fence.json b/src/main/generated/data/minecraft/recipe/jungle_fence.json index b8b91627bd..dc919dea44 100644 --- a/src/main/generated/data/minecraft/recipe/jungle_fence.json +++ b/src/main/generated/data/minecraft/recipe/jungle_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/jungle_sign.json b/src/main/generated/data/minecraft/recipe/jungle_sign.json index 9033e56d3b..9c22e2bcd1 100644 --- a/src/main/generated/data/minecraft/recipe/jungle_sign.json +++ b/src/main/generated/data/minecraft/recipe/jungle_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:jungle_planks", diff --git a/src/main/generated/data/minecraft/recipe/ladder.json b/src/main/generated/data/minecraft/recipe/ladder.json index ffd1098465..0aefdd0268 100644 --- a/src/main/generated/data/minecraft/recipe/ladder.json +++ b/src/main/generated/data/minecraft/recipe/ladder.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden" }, diff --git a/src/main/generated/data/minecraft/recipe/light_blue_banner.json b/src/main/generated/data/minecraft/recipe/light_blue_banner.json index 166356a244..94fa7b212c 100644 --- a/src/main/generated/data/minecraft/recipe/light_blue_banner.json +++ b/src/main/generated/data/minecraft/recipe/light_blue_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:light_blue_wool", diff --git a/src/main/generated/data/minecraft/recipe/light_gray_banner.json b/src/main/generated/data/minecraft/recipe/light_gray_banner.json index 711327e1a9..e1a2400e0b 100644 --- a/src/main/generated/data/minecraft/recipe/light_gray_banner.json +++ b/src/main/generated/data/minecraft/recipe/light_gray_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:light_gray_wool", diff --git a/src/main/generated/data/minecraft/recipe/lime_banner.json b/src/main/generated/data/minecraft/recipe/lime_banner.json index 19685f6245..828ccfcb50 100644 --- a/src/main/generated/data/minecraft/recipe/lime_banner.json +++ b/src/main/generated/data/minecraft/recipe/lime_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:lime_wool", diff --git a/src/main/generated/data/minecraft/recipe/lodestone.json b/src/main/generated/data/minecraft/recipe/lodestone.json index d2a7d4a61c..8b353b4504 100644 --- a/src/main/generated/data/minecraft/recipe/lodestone.json +++ b/src/main/generated/data/minecraft/recipe/lodestone.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/iron", "S": "minecraft:chiseled_stone_bricks" diff --git a/src/main/generated/data/minecraft/recipe/loom.json b/src/main/generated/data/minecraft/recipe/loom.json index f4e54b62d5..21b2fa928a 100644 --- a/src/main/generated/data/minecraft/recipe/loom.json +++ b/src/main/generated/data/minecraft/recipe/loom.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#minecraft:planks", "@": "#c:strings" diff --git a/src/main/generated/data/minecraft/recipe/magenta_banner.json b/src/main/generated/data/minecraft/recipe/magenta_banner.json index 5eb547b59a..b0fee202d5 100644 --- a/src/main/generated/data/minecraft/recipe/magenta_banner.json +++ b/src/main/generated/data/minecraft/recipe/magenta_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:magenta_wool", diff --git a/src/main/generated/data/minecraft/recipe/mangrove_chest_boat.json b/src/main/generated/data/minecraft/recipe/mangrove_chest_boat.json index 219b9e30e5..47eab0678b 100644 --- a/src/main/generated/data/minecraft/recipe/mangrove_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/mangrove_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/mangrove_fence.json b/src/main/generated/data/minecraft/recipe/mangrove_fence.json index efda31e05f..f939810940 100644 --- a/src/main/generated/data/minecraft/recipe/mangrove_fence.json +++ b/src/main/generated/data/minecraft/recipe/mangrove_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/mangrove_sign.json b/src/main/generated/data/minecraft/recipe/mangrove_sign.json index d232b6519e..2c1eeab8a2 100644 --- a/src/main/generated/data/minecraft/recipe/mangrove_sign.json +++ b/src/main/generated/data/minecraft/recipe/mangrove_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:mangrove_planks", diff --git a/src/main/generated/data/minecraft/recipe/minecart.json b/src/main/generated/data/minecraft/recipe/minecart.json index 5bd1dcdeac..1ba7653387 100644 --- a/src/main/generated/data/minecraft/recipe/minecart.json +++ b/src/main/generated/data/minecraft/recipe/minecart.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:ingots/iron" }, diff --git a/src/main/generated/data/minecraft/recipe/netherite_ingot.json b/src/main/generated/data/minecraft/recipe/netherite_ingot.json index 1d8fba0d64..b99430fe50 100644 --- a/src/main/generated/data/minecraft/recipe/netherite_ingot.json +++ b/src/main/generated/data/minecraft/recipe/netherite_ingot.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "netherite_ingot", "ingredients": [ "minecraft:netherite_scrap", diff --git a/src/main/generated/data/minecraft/recipe/netherite_upgrade_smithing_template.json b/src/main/generated/data/minecraft/recipe/netherite_upgrade_smithing_template.json index 1527cf530b..aa03072c28 100644 --- a/src/main/generated/data/minecraft/recipe/netherite_upgrade_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/netherite_upgrade_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:netherrack", diff --git a/src/main/generated/data/minecraft/recipe/oak_chest_boat.json b/src/main/generated/data/minecraft/recipe/oak_chest_boat.json index 35eaedd589..135b0d1cb7 100644 --- a/src/main/generated/data/minecraft/recipe/oak_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/oak_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/oak_fence.json b/src/main/generated/data/minecraft/recipe/oak_fence.json index 841737af50..b3684fd871 100644 --- a/src/main/generated/data/minecraft/recipe/oak_fence.json +++ b/src/main/generated/data/minecraft/recipe/oak_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/oak_sign.json b/src/main/generated/data/minecraft/recipe/oak_sign.json index 37d025c615..1692e49e39 100644 --- a/src/main/generated/data/minecraft/recipe/oak_sign.json +++ b/src/main/generated/data/minecraft/recipe/oak_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:oak_planks", diff --git a/src/main/generated/data/minecraft/recipe/orange_banner.json b/src/main/generated/data/minecraft/recipe/orange_banner.json index 46a0917e02..22de227ea5 100644 --- a/src/main/generated/data/minecraft/recipe/orange_banner.json +++ b/src/main/generated/data/minecraft/recipe/orange_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:orange_wool", diff --git a/src/main/generated/data/minecraft/recipe/painting.json b/src/main/generated/data/minecraft/recipe/painting.json index 6f64524c95..b8497c2de4 100644 --- a/src/main/generated/data/minecraft/recipe/painting.json +++ b/src/main/generated/data/minecraft/recipe/painting.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "X": "#minecraft:wool" diff --git a/src/main/generated/data/minecraft/recipe/pale_oak_chest_boat.json b/src/main/generated/data/minecraft/recipe/pale_oak_chest_boat.json index ab238d2548..b75a6247d3 100644 --- a/src/main/generated/data/minecraft/recipe/pale_oak_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/pale_oak_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/pale_oak_fence.json b/src/main/generated/data/minecraft/recipe/pale_oak_fence.json index a45cc02b9d..c4a34ad537 100644 --- a/src/main/generated/data/minecraft/recipe/pale_oak_fence.json +++ b/src/main/generated/data/minecraft/recipe/pale_oak_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/pale_oak_sign.json b/src/main/generated/data/minecraft/recipe/pale_oak_sign.json index dfa9f8e208..ac471218f3 100644 --- a/src/main/generated/data/minecraft/recipe/pale_oak_sign.json +++ b/src/main/generated/data/minecraft/recipe/pale_oak_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:pale_oak_planks", diff --git a/src/main/generated/data/minecraft/recipe/pink_banner.json b/src/main/generated/data/minecraft/recipe/pink_banner.json index 1ec35a93c2..b0640cb8ef 100644 --- a/src/main/generated/data/minecraft/recipe/pink_banner.json +++ b/src/main/generated/data/minecraft/recipe/pink_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:pink_wool", diff --git a/src/main/generated/data/minecraft/recipe/powered_rail.json b/src/main/generated/data/minecraft/recipe/powered_rail.json index 98d2889b68..40d834f692 100644 --- a/src/main/generated/data/minecraft/recipe/powered_rail.json +++ b/src/main/generated/data/minecraft/recipe/powered_rail.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "R": "minecraft:redstone", diff --git a/src/main/generated/data/minecraft/recipe/purple_banner.json b/src/main/generated/data/minecraft/recipe/purple_banner.json index 21aae0f5ea..8f1b072de3 100644 --- a/src/main/generated/data/minecraft/recipe/purple_banner.json +++ b/src/main/generated/data/minecraft/recipe/purple_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:purple_wool", diff --git a/src/main/generated/data/minecraft/recipe/rail.json b/src/main/generated/data/minecraft/recipe/rail.json index 0a3e60e760..b9ed74f2f2 100644 --- a/src/main/generated/data/minecraft/recipe/rail.json +++ b/src/main/generated/data/minecraft/recipe/rail.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "X": "#c:ingots/iron" diff --git a/src/main/generated/data/minecraft/recipe/raiser_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/raiser_armor_trim_smithing_template.json index 4fb9ee682a..f49dd8b54a 100644 --- a/src/main/generated/data/minecraft/recipe/raiser_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/raiser_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:terracotta", diff --git a/src/main/generated/data/minecraft/recipe/red_banner.json b/src/main/generated/data/minecraft/recipe/red_banner.json index d1a839d900..16e01ce497 100644 --- a/src/main/generated/data/minecraft/recipe/red_banner.json +++ b/src/main/generated/data/minecraft/recipe/red_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:red_wool", diff --git a/src/main/generated/data/minecraft/recipe/rib_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/rib_armor_trim_smithing_template.json index 98a267e64d..f99a49c84f 100644 --- a/src/main/generated/data/minecraft/recipe/rib_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/rib_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:netherrack", diff --git a/src/main/generated/data/minecraft/recipe/scaffolding.json b/src/main/generated/data/minecraft/recipe/scaffolding.json index 6ca014d1bc..1393f3b416 100644 --- a/src/main/generated/data/minecraft/recipe/scaffolding.json +++ b/src/main/generated/data/minecraft/recipe/scaffolding.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "I": "minecraft:bamboo", "~": "#c:strings" diff --git a/src/main/generated/data/minecraft/recipe/sentry_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/sentry_armor_trim_smithing_template.json index a0307a6d17..e0a1a2a451 100644 --- a/src/main/generated/data/minecraft/recipe/sentry_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/sentry_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "#c:cobblestones/normal", diff --git a/src/main/generated/data/minecraft/recipe/shaper_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/shaper_armor_trim_smithing_template.json index db0aa56270..e1f08a5ca1 100644 --- a/src/main/generated/data/minecraft/recipe/shaper_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/shaper_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:terracotta", diff --git a/src/main/generated/data/minecraft/recipe/shulker_box.json b/src/main/generated/data/minecraft/recipe/shulker_box.json index fa88e88e2c..7b35303f6e 100644 --- a/src/main/generated/data/minecraft/recipe/shulker_box.json +++ b/src/main/generated/data/minecraft/recipe/shulker_box.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:chests/wooden", "-": "minecraft:shulker_shell" diff --git a/src/main/generated/data/minecraft/recipe/silence_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/silence_armor_trim_smithing_template.json index 20a9278cf3..364cdd75a6 100644 --- a/src/main/generated/data/minecraft/recipe/silence_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/silence_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "#c:cobblestones/deepslate", diff --git a/src/main/generated/data/minecraft/recipe/smithing_table.json b/src/main/generated/data/minecraft/recipe/smithing_table.json index d745c68519..4642066634 100644 --- a/src/main/generated/data/minecraft/recipe/smithing_table.json +++ b/src/main/generated/data/minecraft/recipe/smithing_table.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#minecraft:planks", "@": "#c:ingots/iron" diff --git a/src/main/generated/data/minecraft/recipe/snout_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/snout_armor_trim_smithing_template.json index f99ecffc0f..8f24674fdd 100644 --- a/src/main/generated/data/minecraft/recipe/snout_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/snout_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:blackstone", diff --git a/src/main/generated/data/minecraft/recipe/soul_campfire.json b/src/main/generated/data/minecraft/recipe/soul_campfire.json index d683caea06..a5630fbfe5 100644 --- a/src/main/generated/data/minecraft/recipe/soul_campfire.json +++ b/src/main/generated/data/minecraft/recipe/soul_campfire.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#minecraft:soul_fire_base_blocks", "L": "#minecraft:logs", diff --git a/src/main/generated/data/minecraft/recipe/soul_torch.json b/src/main/generated/data/minecraft/recipe/soul_torch.json index 9c373bb794..89fba8cfe0 100644 --- a/src/main/generated/data/minecraft/recipe/soul_torch.json +++ b/src/main/generated/data/minecraft/recipe/soul_torch.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "S": "#minecraft:soul_fire_base_blocks", diff --git a/src/main/generated/data/minecraft/recipe/spire_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/spire_armor_trim_smithing_template.json index 76ac8903bd..a4f55cc155 100644 --- a/src/main/generated/data/minecraft/recipe/spire_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/spire_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:purpur_block", diff --git a/src/main/generated/data/minecraft/recipe/spruce_chest_boat.json b/src/main/generated/data/minecraft/recipe/spruce_chest_boat.json index 49c8cf18c8..80f4e6e72b 100644 --- a/src/main/generated/data/minecraft/recipe/spruce_chest_boat.json +++ b/src/main/generated/data/minecraft/recipe/spruce_chest_boat.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shapeless", + "category": "misc", "group": "chest_boat", "ingredients": [ "#c:chests/wooden", diff --git a/src/main/generated/data/minecraft/recipe/spruce_fence.json b/src/main/generated/data/minecraft/recipe/spruce_fence.json index 804b3b538a..f84b63a72b 100644 --- a/src/main/generated/data/minecraft/recipe/spruce_fence.json +++ b/src/main/generated/data/minecraft/recipe/spruce_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/spruce_sign.json b/src/main/generated/data/minecraft/recipe/spruce_sign.json index 9a020a7592..58046b4828 100644 --- a/src/main/generated/data/minecraft/recipe/spruce_sign.json +++ b/src/main/generated/data/minecraft/recipe/spruce_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:spruce_planks", diff --git a/src/main/generated/data/minecraft/recipe/stonecutter.json b/src/main/generated/data/minecraft/recipe/stonecutter.json index 596ee798c0..1d1c6a2e34 100644 --- a/src/main/generated/data/minecraft/recipe/stonecutter.json +++ b/src/main/generated/data/minecraft/recipe/stonecutter.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "minecraft:stone", "I": "#c:ingots/iron" diff --git a/src/main/generated/data/minecraft/recipe/tide_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/tide_armor_trim_smithing_template.json index 802def7aad..4f4f0feec4 100644 --- a/src/main/generated/data/minecraft/recipe/tide_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/tide_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:prismarine", diff --git a/src/main/generated/data/minecraft/recipe/torch.json b/src/main/generated/data/minecraft/recipe/torch.json index 9ed89552aa..442a61780e 100644 --- a/src/main/generated/data/minecraft/recipe/torch.json +++ b/src/main/generated/data/minecraft/recipe/torch.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:rods/wooden", "X": [ diff --git a/src/main/generated/data/minecraft/recipe/vex_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/vex_armor_trim_smithing_template.json index 0717a4ef69..33b599c546 100644 --- a/src/main/generated/data/minecraft/recipe/vex_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/vex_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "#c:cobblestones/normal", diff --git a/src/main/generated/data/minecraft/recipe/ward_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/ward_armor_trim_smithing_template.json index 78cbdb841a..9a4b94b40f 100644 --- a/src/main/generated/data/minecraft/recipe/ward_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/ward_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "#c:cobblestones/deepslate", diff --git a/src/main/generated/data/minecraft/recipe/warped_fence.json b/src/main/generated/data/minecraft/recipe/warped_fence.json index cbc3eb97e5..54684ffb50 100644 --- a/src/main/generated/data/minecraft/recipe/warped_fence.json +++ b/src/main/generated/data/minecraft/recipe/warped_fence.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_fence", "key": { "#": "#c:rods/wooden", diff --git a/src/main/generated/data/minecraft/recipe/warped_sign.json b/src/main/generated/data/minecraft/recipe/warped_sign.json index b9cc43590e..fd63852c3b 100644 --- a/src/main/generated/data/minecraft/recipe/warped_sign.json +++ b/src/main/generated/data/minecraft/recipe/warped_sign.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "wooden_sign", "key": { "#": "minecraft:warped_planks", diff --git a/src/main/generated/data/minecraft/recipe/wayfinder_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/wayfinder_armor_trim_smithing_template.json index b21c78e691..3c93a650a0 100644 --- a/src/main/generated/data/minecraft/recipe/wayfinder_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/wayfinder_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:terracotta", diff --git a/src/main/generated/data/minecraft/recipe/white_banner.json b/src/main/generated/data/minecraft/recipe/white_banner.json index d4061a1300..fcae720d40 100644 --- a/src/main/generated/data/minecraft/recipe/white_banner.json +++ b/src/main/generated/data/minecraft/recipe/white_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:white_wool", diff --git a/src/main/generated/data/minecraft/recipe/wild_armor_trim_smithing_template.json b/src/main/generated/data/minecraft/recipe/wild_armor_trim_smithing_template.json index 7a7d4dd58f..0048eb4531 100644 --- a/src/main/generated/data/minecraft/recipe/wild_armor_trim_smithing_template.json +++ b/src/main/generated/data/minecraft/recipe/wild_armor_trim_smithing_template.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "#": "#c:gems/diamond", "C": "minecraft:mossy_cobblestone", diff --git a/src/main/generated/data/minecraft/recipe/yellow_banner.json b/src/main/generated/data/minecraft/recipe/yellow_banner.json index f33512542b..6b72a8f64a 100644 --- a/src/main/generated/data/minecraft/recipe/yellow_banner.json +++ b/src/main/generated/data/minecraft/recipe/yellow_banner.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "group": "banner", "key": { "#": "minecraft:yellow_wool", diff --git a/src/main/generated/pack.mcmeta b/src/main/generated/pack.mcmeta index ed943be2fb..8161ff9d70 100644 --- a/src/main/generated/pack.mcmeta +++ b/src/main/generated/pack.mcmeta @@ -3,9 +3,9 @@ "description": { "translate": "pack.forge.description" }, - "max_format": 107, + "max_format": 101, "min_format": [ - 107, + 101, 1 ] } diff --git a/src/main/java/net/minecraftforge/client/ClientCommandHandler.java b/src/main/java/net/minecraftforge/client/ClientCommandHandler.java index 0c606ea277..e758aa8aed 100644 --- a/src/main/java/net/minecraftforge/client/ClientCommandHandler.java +++ b/src/main/java/net/minecraftforge/client/ClientCommandHandler.java @@ -16,6 +16,7 @@ import com.mojang.brigadier.tree.RootCommandNode; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.ClientSuggestionProvider; import net.minecraft.client.player.LocalPlayer; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSource; @@ -25,6 +26,7 @@ import net.minecraft.commands.synchronization.SuggestionProviders; import net.minecraft.network.chat.*; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.client.event.RegisterClientCommandsEvent; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.server.command.CommandHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -69,12 +71,12 @@ public class ClientCommandHandler { copy(serverCommandsRoot, newServerCommands.getRoot()); // Copies the client side commands into the server side commands to be used for suggestions - CommandHelper.mergeCommandNode(commands.getRoot(), newServerCommands.getRoot(), new IdentityHashMap<>(), getSource(), (_) -> 0, (suggestions) -> { + CommandHelper.mergeCommandNode(commands.getRoot(), newServerCommands.getRoot(), new IdentityHashMap<>(), getSource(), (context) -> 0, (suggestions) -> { @SuppressWarnings("unchecked") var shared = (SuggestionProvider)(SuggestionProvider)suggestions; var suggestionProvider = shared; //SuggestionProviders.safelySwap(shared); if (suggestionProvider == SuggestionProviders.ASK_SERVER) { - suggestionProvider = (context, _) -> { + suggestionProvider = (context, builder) -> { ClientCommandSourceStack source = getSource(); StringReader reader = new StringReader(context.getInput()); if (reader.canRead() && reader.peek() == '/') @@ -107,7 +109,7 @@ public class ClientCommandHandler { new CommandSource() { @Override public void sendSystemMessage(Component message) { - mc.gui.hud.getChat().addClientSystemMessage(message); + mc.gui.getChat().addClientSystemMessage(message); } @Override @@ -186,7 +188,7 @@ public class ClientCommandHandler { // in case of unknown command, let the server try and handle it return false; } - mc.gui.hud.getChat().addClientSystemMessage( + mc.gui.getChat().addClientSystemMessage( Component.literal("").append(ComponentUtils.fromMessage(syntax.getRawMessage())).withStyle(ChatFormatting.RED) ); if (syntax.getInput() != null && syntax.getCursor() >= 0) { @@ -203,11 +205,11 @@ public class ClientCommandHandler { details.append(Component.literal(syntax.getInput().substring(position)).withStyle(ChatFormatting.RED, ChatFormatting.UNDERLINE)); details.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC)); - mc.gui.hud.getChat().addClientSystemMessage(Component.literal("").append(details).withStyle(ChatFormatting.RED)); + mc.gui.getChat().addClientSystemMessage(Component.literal("").append(details).withStyle(ChatFormatting.RED)); } } catch (Exception generic) { // Probably thrown by the command{ MutableComponent message = Component.literal(generic.getMessage() == null ? generic.getClass().getName() : generic.getMessage()); - mc.gui.hud.getChat().addClientSystemMessage( + mc.gui.getChat().addClientSystemMessage( Component.translatable("command.failed") .withStyle(ChatFormatting.RED) .withStyle(style -> style.withHoverEvent(new HoverEvent.ShowText(message))) diff --git a/src/main/java/net/minecraftforge/client/ClientCommandSourceStack.java b/src/main/java/net/minecraftforge/client/ClientCommandSourceStack.java index 3affac5f77..88cd02a06c 100644 --- a/src/main/java/net/minecraftforge/client/ClientCommandSourceStack.java +++ b/src/main/java/net/minecraftforge/client/ClientCommandSourceStack.java @@ -41,7 +41,7 @@ public class ClientCommandSourceStack extends CommandSourceStack { @SuppressWarnings("resource") @Override public void sendSuccess(Supplier message, boolean sendToAdmins) { - Minecraft.getInstance().gui.hud.getChat().addClientSystemMessage(message.get()); + Minecraft.getInstance().gui.getChat().addClientSystemMessage(message.get()); } /** diff --git a/src/main/java/net/minecraftforge/client/ClientForgeMod.java b/src/main/java/net/minecraftforge/client/ClientForgeMod.java index 265c4b9fa1..2ffd2a691f 100644 --- a/src/main/java/net/minecraftforge/client/ClientForgeMod.java +++ b/src/main/java/net/minecraftforge/client/ClientForgeMod.java @@ -21,7 +21,7 @@ import net.minecraftforge.fml.common.Mod; public class ClientForgeMod { @SubscribeEvent public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register(forgeRL("empty"), (_, _) -> UnbakedGeometry.EMPTY); + event.register(forgeRL("empty"), (json, ctx) -> UnbakedGeometry.EMPTY); event.register(forgeRL("obj"), ObjLoader.INSTANCE); event.register(forgeRL("fluid_container"), DynamicFluidContainerModel.Loader.INSTANCE); } diff --git a/src/main/java/net/minecraftforge/client/ConfigScreenHandler.java b/src/main/java/net/minecraftforge/client/ConfigScreenHandler.java index 16f12a6b74..385b519cc5 100644 --- a/src/main/java/net/minecraftforge/client/ConfigScreenHandler.java +++ b/src/main/java/net/minecraftforge/client/ConfigScreenHandler.java @@ -33,7 +33,7 @@ public class ConfigScreenHandler * instance.

*/ public ConfigScreenFactory(Function screenFunction) { - this((_, modsScreen) -> screenFunction.apply(modsScreen)); + this((mcClient, modsScreen) -> screenFunction.apply(modsScreen)); } } diff --git a/src/main/java/net/minecraftforge/client/CreativeModeTabSearchRegistry.java b/src/main/java/net/minecraftforge/client/CreativeModeTabSearchRegistry.java index da7b16605a..e244336b89 100644 --- a/src/main/java/net/minecraftforge/client/CreativeModeTabSearchRegistry.java +++ b/src/main/java/net/minecraftforge/client/CreativeModeTabSearchRegistry.java @@ -53,7 +53,7 @@ public class CreativeModeTabSearchRegistry { if (!tab.hasSearchBar()) return null; - return NAME_SEARCH_KEYS.computeIfAbsent(tab, _ -> new SessionSearchTrees.Key()); + return NAME_SEARCH_KEYS.computeIfAbsent(tab, k -> new SessionSearchTrees.Key()); } @Nullable @@ -64,6 +64,6 @@ public class CreativeModeTabSearchRegistry { if (!tab.hasSearchBar()) return null; - return TAG_SEARCH_KEYS.computeIfAbsent(tab, _ -> new SessionSearchTrees.Key()); + return TAG_SEARCH_KEYS.computeIfAbsent(tab, k -> new SessionSearchTrees.Key()); } } diff --git a/src/main/java/net/minecraftforge/client/ForgeAtlasProvider.java b/src/main/java/net/minecraftforge/client/ForgeAtlasProvider.java deleted file mode 100644 index 0824241177..0000000000 --- a/src/main/java/net/minecraftforge/client/ForgeAtlasProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.client; - -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -import net.minecraft.client.data.AtlasProvider; -import net.minecraft.client.renderer.texture.atlas.SpriteSource; -import net.minecraft.client.renderer.texture.atlas.sources.SingleFile; -import net.minecraft.data.AtlasIds; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.Identifier; - -public class ForgeAtlasProvider extends AtlasProvider { - public ForgeAtlasProvider(PackOutput output) { - super(output); - } - - @Override - public CompletableFuture run(final CachedOutput cache) { - return CompletableFuture.allOf( - this.storeAtlas(cache, AtlasIds.BLOCKS, List.of( - single("white") - )), - this.storeAtlas(cache, AtlasIds.ITEMS, List.of( - fromBlock("block/lava_still"), - fromBlock("block/water_still") - )) - ); - } - - private static SpriteSource single(String path) { - return new SingleFile(Identifier.fromNamespaceAndPath("forge", path)); - } - - private static SpriteSource fromBlock(String name) { - var resource = Identifier.withDefaultNamespace(name); - var id = resource; - if (resource.getPath().startsWith("block/")) - id = resource.withPath(path -> "item/" + path.substring(6)); - return new SingleFile(resource, Optional.of(id)); - } -} diff --git a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java index ac6ecec55c..65ae1fe6eb 100644 --- a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java +++ b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java @@ -27,6 +27,7 @@ import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.components.ChatComponent; import net.minecraft.client.gui.components.LerpingBossEvent; import net.minecraft.client.gui.render.pip.PictureInPictureRenderer; +import net.minecraft.client.gui.screens.ConfirmScreen; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; @@ -41,27 +42,41 @@ import net.minecraft.client.model.geom.builders.LayerDefinition; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.particle.ParticleEngine; +import net.minecraft.client.particle.ParticleRenderType; import net.minecraft.client.particle.ParticleResources; import net.minecraft.client.player.ClientInput; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderPipelines; import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.block.BlockAndTintGetter; import net.minecraft.client.renderer.block.FluidModel; +import net.minecraft.client.renderer.block.dispatch.BlockStateModel; +import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.client.renderer.entity.state.EntityRenderState; import net.minecraft.client.renderer.entity.state.HumanoidRenderState; -import net.minecraft.client.renderer.extract.LevelExtractor; import net.minecraft.client.renderer.fog.FogData; import net.minecraft.client.renderer.state.gui.pip.PictureInPictureRenderState; +import net.minecraft.client.renderer.state.level.CameraRenderState; import net.minecraft.client.renderer.state.level.LevelRenderState; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.metadata.animation.FrameSize; +import net.minecraft.client.resources.model.ModelBaker; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelManager; +import net.minecraft.client.resources.model.ResolvedModel; import net.minecraft.client.resources.model.geometry.UnbakedGeometry; import net.minecraft.client.resources.model.sprite.MaterialBaker; 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.data.AtlasIds; import net.minecraft.locale.Language; import net.minecraft.network.Connection; import net.minecraft.network.chat.ChatType; @@ -74,8 +89,10 @@ import net.minecraft.resources.Identifier; import net.minecraft.server.packs.metadata.MetadataSectionType; import net.minecraft.server.packs.resources.ReloadableResourceManager; import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceMetadata; import net.minecraft.util.GsonHelper; import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.Entity; @@ -114,6 +131,7 @@ import net.minecraftforge.client.event.RenderBlockScreenEffectEvent; import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.client.event.RenderHighlightEvent; import net.minecraftforge.client.event.RenderTooltipEvent; +import net.minecraftforge.client.event.ScreenEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.client.event.ViewportEvent; import net.minecraftforge.client.event.sound.PlaySoundEvent; @@ -123,6 +141,7 @@ import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions; import net.minecraftforge.client.gui.ClientTooltipComponentManager; import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen; import net.minecraftforge.client.model.ForgeBlockModelData; +import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.geometry.GeometryLoaderManager; import net.minecraftforge.client.textures.ForgeTextureMetadata; import net.minecraftforge.client.textures.TextureAtlasSpriteLoaderManager; @@ -130,6 +149,7 @@ import net.minecraftforge.common.ForgeI18n; import net.minecraftforge.common.ForgeMod; import net.minecraftforge.fml.IExtensionPoint; import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.ModLoader; import net.minecraftforge.network.NetworkContext; import net.minecraftforge.network.NetworkInitialization; import net.minecraftforge.network.NetworkRegistry; @@ -146,15 +166,19 @@ import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; import org.joml.Vector4f; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.Stack; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; @@ -169,6 +193,53 @@ public class ForgeHooksClient { //private static final Identifier ITEM_GLINT = new Identifier("textures/misc/enchanted_item_glint.png"); + /** + * Contains the *extra* GUI layers. + * The current top layer stays in Minecraft#currentScreen, and the rest serve as a background for it. + */ + private static final Stack guiLayers = new Stack<>(); + + public static void resizeGuiLayers(Minecraft minecraft, int width, int height) { + guiLayers.forEach(screen -> screen.resize(width, height)); + } + + public static void clearGuiLayers(Minecraft minecraft) { + while (!guiLayers.isEmpty()) + popGuiLayerInternal(minecraft); + } + + private static void popGuiLayerInternal(Minecraft minecraft) { + if (minecraft.screen != null) + minecraft.screen.removed(); + minecraft.screen = guiLayers.pop(); + } + + public static void pushGuiLayer(Minecraft minecraft, Screen screen) { + if (minecraft.screen != null) + guiLayers.push(minecraft.screen); + minecraft.screen = Objects.requireNonNull(screen); + screen.init(minecraft.getWindow().getGuiScaledWidth(), minecraft.getWindow().getGuiScaledHeight()); + minecraft.getNarrator().saySystemNow(screen.getNarrationMessage()); + } + + public static void popGuiLayer(Minecraft minecraft) { + if (guiLayers.isEmpty()) { + minecraft.setScreen(null); + return; + } + + popGuiLayerInternal(minecraft); + if (minecraft.screen != null) + minecraft.getNarrator().saySystemNow(minecraft.screen.getNarrationMessage()); + } + + public static float getGuiFarPlane() { + // 11000 units for the overlay background, + // and 10000 units for each layered Screen, + + return 11000.0F + 10000.0F * (1 + guiLayers.size()); + } + public static boolean onClientPauseChangePre(boolean pause) { return ClientPauseChangeEvent.Pre.BUS.post(new ClientPauseChangeEvent.Pre(pause)); } @@ -184,9 +255,9 @@ public class ForgeHooksClient { } */ - private static final RenderHighlightEvent.Callback NOOP_HIGHLIGHTER = (_, _, _) -> { }; + private static final RenderHighlightEvent.Callback NOOP_HIGHLIGHTER = (source, stack, translucent, state) -> { }; - public static RenderHighlightEvent.Callback onExtractBlockOutline(LevelExtractor context, Camera camera, LevelRenderState state, HitResult target) { + public static RenderHighlightEvent.Callback onExtractBlockOutline(LevelRenderer context, Camera camera, LevelRenderState state, HitResult target) { if (target instanceof BlockHitResult blockTarget) { var event = new RenderHighlightEvent.Block(context, camera, state, blockTarget); if (RenderHighlightEvent.Block.BUS.post(event)) @@ -256,6 +327,23 @@ public class ForgeHooksClient { return PlaySoundEvent.BUS.fire(new PlaySoundEvent(manager, sound)).getSound(); } + public static void drawScreen(Screen screen, GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) { + guiGraphics.pose().pushMatrix(); + for (Screen layer : guiLayers) { + // Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted. + drawScreenInternal(layer, guiGraphics, Integer.MAX_VALUE, Integer.MAX_VALUE, partialTick); + //guiGraphics.pose().translate(0, 0, 10000); + } + drawScreenInternal(screen, guiGraphics, mouseX, mouseY, partialTick); + guiGraphics.pose().popMatrix(); + } + + private static void drawScreenInternal(Screen screen, GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) { + if (!ScreenEvent.Render.Pre.BUS.post(new ScreenEvent.Render.Pre(screen, guiGraphics, mouseX, mouseY, partialTick))) + screen.extractRenderStateWithTooltipAndSubtitles(guiGraphics, mouseX, mouseY, partialTick); + ScreenEvent.Render.Post.BUS.post(new ScreenEvent.Render.Post(screen, guiGraphics, mouseX, mouseY, partialTick)); + } + public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) { // Modify fog color depending on the fluid FluidState state = level.getFluidState(camera.blockPosition()); @@ -368,14 +456,14 @@ public class ForgeHooksClient { InputEvent.Key.BUS.post(new InputEvent.Key(info, action)); } - public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance, double nameTagDistance) { + public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) { if (entity instanceof LivingEntity living) { var attribute = living.getAttribute(ForgeMod.NAMETAG_DISTANCE.getHolder().get()); if (attribute != null) { return !(squareDistance > (attribute.getValue() * attribute.getValue())); } } - return !(squareDistance > Mth.square(nameTagDistance)); + return !(squareDistance > 4096.0f); } public static boolean shouldRenderEffect(MobEffectInstance effectInstance) { @@ -541,8 +629,9 @@ public class ForgeHooksClient { } public static void onRegisterPictureInPictureRenderers(List> renderers, + MultiBufferSource.BufferSource bufferSource, ImmutableMap.Builder, PictureInPictureRenderer> builder) { - RegisterPictureInPictureRendererEvent.BUS.post(new RegisterPictureInPictureRendererEvent(renderers, builder)); + RegisterPictureInPictureRendererEvent.BUS.post(new RegisterPictureInPictureRendererEvent(renderers, bufferSource, builder)); } @Nullable @@ -600,7 +689,7 @@ public class ForgeHooksClient { // text wrapping int tooltipTextWidth = event.getTooltipElements().stream() - .mapToInt(either -> either.map(font::width, _ -> 0)) + .mapToInt(either -> either.map(font::width, component -> 0)) .max() .orElse(0); @@ -646,6 +735,22 @@ public class ForgeHooksClient { return font.split(text, maxWidth).stream().map(ClientTooltipComponent::create); } + public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad) { + Component title = Component.translatable("selectWorld.backupQuestion.experimental"); + Component msg = Component.translatable("selectWorld.backupWarning.experimental") + .append("\n\n") + .append(Component.translatable("forge.selectWorld.backupWarning.experimental.additional")); + + Screen screen = new ConfirmScreen(confirmed -> { + if (confirmed) + doConfirmedWorldLoad.run(); + else + Minecraft.getInstance().setScreen(null); + }, title, msg, CommonComponents.GUI_PROCEED, CommonComponents.GUI_CANCEL); + + Minecraft.getInstance().setScreen(screen); + } + public static boolean renderFireOverlay(Player player, PoseStack mat) { return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.FIRE, Blocks.FIRE.defaultBlockState(), player.blockPosition()); } @@ -700,7 +805,7 @@ public class ForgeHooksClient { var mismatch = NetworkContext.get(connection).getMismatchs(); if (mismatch == null) return false; - mc.gui.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch)); + mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch)); return true; } diff --git a/src/main/java/net/minecraftforge/client/ForgeRenderTypes.java b/src/main/java/net/minecraftforge/client/ForgeRenderTypes.java index 159035b79d..42a8e1d283 100644 --- a/src/main/java/net/minecraftforge/client/ForgeRenderTypes.java +++ b/src/main/java/net/minecraftforge/client/ForgeRenderTypes.java @@ -5,15 +5,16 @@ package net.minecraftforge.client; -import com.mojang.blaze3d.GpuFormat; import com.mojang.blaze3d.pipeline.BlendFunction; import com.mojang.blaze3d.pipeline.ColorTargetState; import com.mojang.blaze3d.pipeline.RenderPipeline; -import com.mojang.blaze3d.platform.BlendFactor; +import com.mojang.blaze3d.platform.DestFactor; +import com.mojang.blaze3d.platform.SourceFactor; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.textures.AddressMode; import com.mojang.blaze3d.textures.FilterMode; import com.mojang.blaze3d.textures.GpuSampler; +import com.mojang.blaze3d.textures.TextureFormat; import net.minecraft.util.Util; import net.minecraft.client.renderer.RenderPipelines; @@ -104,8 +105,8 @@ public enum ForgeRenderTypes { * * @return Replacement of {@link RenderType#textIntensity(Identifier)}, but with optional linear texture filtering. */ - public static RenderType getTextGrayscale(Identifier locationIn) { - return Internal.TEXT_GRAYSCALE.apply(locationIn); + public static RenderType getTextIntensity(Identifier locationIn) { + return Internal.TEXT_INTENSITY.apply(locationIn); } /** @@ -122,8 +123,8 @@ public enum ForgeRenderTypes { * * @return Replacement of {@link RenderType#textIntensityPolygonOffset(Identifier)}, but with optional linear texture filtering. */ - public static RenderType getTextGrayscalePolygonOffset(Identifier locationIn) { - return Internal.TEXT_GRAYSCALE_POLYGON_OFFSET.apply(locationIn); + public static RenderType getTextIntensityPolygonOffset(Identifier locationIn) { + return Internal.TEXT_INTENSITY_POLYGON_OFFSET.apply(locationIn); } /** @@ -140,8 +141,8 @@ public enum ForgeRenderTypes { * * @return Replacement of {@link RenderType#textIntensitySeeThrough(Identifier)}, but with optional linear texture filtering. */ - public static RenderType getTextGrayscaleSeeThrough(Identifier locationIn) { - return Internal.TEXT_GRAYSCALE_SEE_THROUGH.apply(locationIn); + public static RenderType getTextIntensitySeeThrough(Identifier locationIn) { + return Internal.TEXT_INTENSITY_SEE_THROUGH.apply(locationIn); } /** @@ -178,7 +179,9 @@ public enum ForgeRenderTypes { private static RenderType unsortedTranslucent(Identifier texture) { return RenderType.create("forge_unsorted_translucent", RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .withTexture("Sampler0", texture) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .affectsCrumbling() .useLightmap() .useOverlay() @@ -191,6 +194,7 @@ public enum ForgeRenderTypes { private static RenderType unlitTranslucentSorted(Identifier texture) { return RenderType.create("forge_unlit_translucent_sorted", RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .affectsCrumbling() .sortOnUpload() .withTexture("Sampler0", texture) @@ -204,6 +208,7 @@ public enum ForgeRenderTypes { private static RenderType unlitTranslucentUnsorted(Identifier texture) { return RenderType.create("forge_unlit_translucent_sorted", RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .affectsCrumbling() .withTexture("Sampler0", texture) .useOverlay() @@ -216,6 +221,7 @@ public enum ForgeRenderTypes { private static RenderType layeredItemSolid(Identifier texture) { return RenderType.create("forge_layered_item_soild", RenderSetup.builder(RenderPipelines.ENTITY_SOLID) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .affectsCrumbling() .withTexture("Sampler0", texture) .useLightmap() @@ -229,6 +235,7 @@ public enum ForgeRenderTypes { private static RenderType layeredItemCutout(Identifier texture) { return RenderType.create("forge_layered_item_cutout", RenderSetup.builder(RenderPipelines.ENTITY_CUTOUT) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .affectsCrumbling() .withTexture("Sampler0", texture) .useLightmap() @@ -245,15 +252,17 @@ public enum ForgeRenderTypes { RenderSetup.builder(RenderPipelines.TEXT) .withTexture("Sampler0", texture) .useLightmap() + .bufferSize(RenderType.SMALL_BUFFER_SIZE) .sortOnUpload() // This is what is different from RenderTypes.TEXT .createRenderSetup() ); } - public static Function TEXT_GRAYSCALE = Util.memoize(Internal::getTextGrayscale); - private static RenderType getTextGrayscale(Identifier texture) { - return RenderType.create("forge_text_grayscale", - RenderSetup.builder(RenderPipelines.TEXT_GRAYSCALE) + public static Function TEXT_INTENSITY = Util.memoize(Internal::getTextIntensity); + private static RenderType getTextIntensity(Identifier texture) { + return RenderType.create("forge_text_intensity", + RenderSetup.builder(RenderPipelines.TEXT_INTENSITY) + .bufferSize(RenderType.SMALL_BUFFER_SIZE) .withTexture("Sampler0", texture) .useLightmap() .useOverlay() @@ -265,6 +274,7 @@ public enum ForgeRenderTypes { private static RenderType getTextPolygonOffset(Identifier texture) { return RenderType.create("forge_text_polygon_offset", RenderSetup.builder(RenderPipelines.TEXT_POLYGON_OFFSET) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .sortOnUpload() .withTexture("Sampler0", texture) .useLightmap() @@ -272,10 +282,11 @@ public enum ForgeRenderTypes { ); } - public static Function TEXT_GRAYSCALE_POLYGON_OFFSET = Util.memoize(Internal::getTextGrayscalePolygonOffset); - private static RenderType getTextGrayscalePolygonOffset(Identifier texture) { - return RenderType.create("forge_text_grayscale_polygon_offset", - RenderSetup.builder(RenderPipelines.TEXT_GRAYSCALE) + public static Function TEXT_INTENSITY_POLYGON_OFFSET = Util.memoize(Internal::getTextIntensityPolygonOffset); + private static RenderType getTextIntensityPolygonOffset(Identifier texture) { + return RenderType.create("forge_text_intensity_polygon_offset", + RenderSetup.builder(RenderPipelines.TEXT_INTENSITY) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .sortOnUpload() .withTexture("Sampler0", texture) .useLightmap() @@ -287,16 +298,18 @@ public enum ForgeRenderTypes { private static RenderType getTextSeeThrough(Identifier texture) { return RenderType.create("forge_text_see_through", RenderSetup.builder(RenderPipelines.TEXT_SEE_THROUGH) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .withTexture("Sampler0", texture) .useLightmap() .createRenderSetup() ); } - public static Function TEXT_GRAYSCALE_SEE_THROUGH = Util.memoize(Internal::getTextIntensitySeeThrough); + public static Function TEXT_INTENSITY_SEE_THROUGH = Util.memoize(Internal::getTextIntensitySeeThrough); private static RenderType getTextIntensitySeeThrough(Identifier texture) { - return RenderType.create("forge_text_grayscale_see_through", - RenderSetup.builder(RenderPipelines.TEXT_GRAYSCALE_SEE_THROUGH) + return RenderType.create("forge_text_intensity_see_through", + RenderSetup.builder(RenderPipelines.TEXT_INTENSITY_SEE_THROUGH) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) .sortOnUpload() .withTexture("Sampler0", texture) .useLightmap() @@ -306,7 +319,7 @@ public enum ForgeRenderTypes { private static final RenderPipeline LOADING_PIPELINE = RenderPipeline.builder(RenderPipelines.GUI_TEXTURED_SNIPPET) .withLocation("pipeline/forge/loading_overlay") - .withColorTargetState(new ColorTargetState(new BlendFunction(BlendFactor.SRC_ALPHA, BlendFactor.ONE))) + .withColorTargetState(new ColorTargetState(new BlendFunction(SourceFactor.SRC_ALPHA, DestFactor.ONE))) .build(); private static final GpuSampler LOADING_SAMPLER = RenderSystem.getSamplerCache().getSampler(AddressMode.REPEAT, AddressMode.REPEAT, FilterMode.NEAREST, FilterMode.NEAREST, false); @@ -314,14 +327,15 @@ public enum ForgeRenderTypes { public static RenderType getLoadingOverlay(DisplayWindow window) { var gpu = RenderSystem.getDevice(); - var texture = gpu.createTexture(LOADING_TEXTURE.toString(), 5, GpuFormat.RGBA8_UNORM, + var texture = gpu.createTexture(LOADING_TEXTURE.toString(), 5, TextureFormat.RGBA8, window.context().width(), window.context().height(), 1, window.getFramebufferTextureId()); var textureView = gpu.createTextureView(texture); return RenderType.create("forge_loading_overlay", RenderSetup.builder(LOADING_PIPELINE) - .withTexture("Sampler0", LOADING_TEXTURE, () -> LOADING_SAMPLER) + .bufferSize(RenderType.TRANSIENT_BUFFER_SIZE) + .withTexture("Sampler0", textureView, LOADING_SAMPLER) .createRenderSetup() ); } diff --git a/src/main/java/net/minecraftforge/client/FramePassManager.java b/src/main/java/net/minecraftforge/client/FramePassManager.java index 2029d2cc16..626c47336b 100644 --- a/src/main/java/net/minecraftforge/client/FramePassManager.java +++ b/src/main/java/net/minecraftforge/client/FramePassManager.java @@ -7,14 +7,10 @@ package net.minecraftforge.client; import com.mojang.blaze3d.framegraph.FrameGraphBuilder; import com.mojang.blaze3d.framegraph.FramePass; -import net.minecraft.client.DeltaTracker; import net.minecraft.client.renderer.LevelTargetBundle; import net.minecraft.client.renderer.state.level.LevelRenderState; import net.minecraft.resources.Identifier; import org.jetbrains.annotations.ApiStatus; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - import java.util.ArrayList; import java.util.List; @@ -31,75 +27,25 @@ public class FramePassManager { // Note: Pass order is determined automatically within FrameGraphBuilder. It's unclear what must be done to guarantee ordering. @ApiStatus.Internal - public static void insertForgePasses(FrameGraphBuilder graphBuilder, LevelTargetBundle bundle, LevelRenderState state, DeltaTracker deltaTracker) { + public static void insertForgePasses(FrameGraphBuilder graphBuilder, LevelTargetBundle bundle, LevelRenderState state) { for (PassInfo info : addedPasses) { FramePass pass = graphBuilder.addPass(info.name); PassDefinition forgePass = info.pass; - forgePass.extracts(bundle, pass, deltaTracker); + forgePass.extracts(bundle, pass); pass.executes(() -> forgePass.executes(state)); } } - - - /// ### A PassDefinition must satisfy 3 things. - /// - /// 1. The rendering order for the purpose of translucency sorting. Read further for specific details. - /// 2. A render state definition supplier; "what" will be rendered. - /// 3. A render state definition consumer; "how" it will be rendered. - /// - /// - /// To satisfy #1, all FramePasses (and thus PassDefinitions) must bind against at least one target. - /// The list of targets can be found in {@linkplain LevelTargetBundle}. - /// HOWEVER!!! Only {@linkplain LevelTargetBundle#main} is used if the graphics mode is not set to Fabulous! - /// So at minimum, all passes must guarantee a fallback binding to the main target, like the below. - /// ``` - /// @Override - /// void extracts(LevelTargetBundle bundle, FramePass pass, DeltaTracker deltaTracker) { - /// if (bundle.clouds != null) { // Perhaps we want to bind to clouds if Fabulous! is on. - /// bundle.clouds = pass.readsAndWrites(bundle.clouds); - /// } - /// // An else clause could be used, but is not mandatory. It is fine to bind to more than one target. - /// bundle.main = pass.readsAndWrites(bundle.main); - /// } - /// ``` - /// - /// - /// It is up to the user to decide how their pass should bind to targets, but it must always bind to at least one. - /// Failure to satisfy this requirement will result in {@linkplain FrameGraphBuilder#resolvePassOrder} exploding. - /// Custom render targets are possible but not documented, see the implementation of {@linkplain LevelTargetBundle} - /// if you want to take a crack at it. - /// - /// Satisfying #2 is simple. Any state information you need to extract - /// should be done during {@linkplain PassDefinition#extracts(LevelTargetBundle, FramePass, DeltaTracker)}. - /// No actual rendering should be done at this time. This can happen before or after binding to a target. - /// The specific implementation of your render state is up to you, it can even be done with some instance variables. - /// - /// Satisfying #3 is also simple, this is the actual rendering that will consume the state created - /// during the extracts phase. - @NullMarked public interface PassDefinition { - /** - * @deprecated Prefer {@linkplain PassDefinition#extracts(LevelTargetBundle, FramePass, DeltaTracker)} + * Use to define which targets your pass will bind against, see {@link FramePass#reads} and {@link FramePass#readsAndWrites} + * A FramePass must bind to at least ONE target. Otherwise, you get freaky issues with >1 modded passes. + * Additionally, this method should be used for extracting render states into instance variables if desired. */ - @Deprecated(forRemoval = true, since="26.2") - default void extracts(LevelTargetBundle bundle, FramePass pass) {}; + void extracts(LevelTargetBundle bundle, FramePass pass); /** - * This method exists to do render state extraction. Your instance of a PassDefinition should have - * locals or some filled record instance that represents the render state created. - * The resulting render state should be consumed by {@linkplain PassDefinition#executes(LevelRenderState)} - * You must also use this to define which targets your pass will bind against. See PassDefinition javadocs for details. - */ - - default void extracts(LevelTargetBundle bundle, FramePass pass, DeltaTracker deltaTracker) { - extracts(bundle, pass); - }; - - /** - * Use to define what your pass does during the render stage. This should consume the render state created - * during the extracts phase. + * Use to define what your pass does during the render stage. */ void executes(LevelRenderState state); } diff --git a/src/main/java/net/minecraftforge/client/event/AddFramePassEvent.java b/src/main/java/net/minecraftforge/client/event/AddFramePassEvent.java index c8e9ad9a94..3031c9e835 100644 --- a/src/main/java/net/minecraftforge/client/event/AddFramePassEvent.java +++ b/src/main/java/net/minecraftforge/client/event/AddFramePassEvent.java @@ -13,7 +13,7 @@ import net.minecraftforge.eventbus.api.event.RecordEvent; import org.jspecify.annotations.NullMarked; /** - * Fired during the construction of {@linkplain net.minecraft.client.renderer.LevelRenderer}. + * Fired after all vanilla frame passes are added into the pass list. * *

This event is fired on the {@linkplain net.minecraftforge.common.MinecraftForge#EVENT_BUS main Forge event bus}, * only on the {@linkplain net.minecraftforge.fml.LogicalSide#CLIENT logical client}. @@ -24,9 +24,8 @@ public record AddFramePassEvent() implements RecordEvent { /** * Adds a frame pass to pass list. * Create a new {@linkplain FramePassManager.PassDefinition} to handle render targets and render code. - * See javadocs for details on what creating a PassDefinition entails. * - * @param rl Identifier for frame pass name. Use RLs to avoid duplicate names. + * @param rl Resource location for frame pass name. Use RLs to avoid duplicate names. * @param definition see usages of {@linkplain com.mojang.blaze3d.framegraph.FramePass} in {@linkplain net.minecraft.client.renderer.LevelRenderer} * @throws IllegalArgumentException If the name is a duplicate. */ diff --git a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java index 5283c7c8ec..36a920b3cd 100644 --- a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java +++ b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java @@ -49,10 +49,12 @@ import net.minecraft.client.renderer.entity.state.AvatarRenderState; import net.minecraft.client.renderer.entity.state.EntityRenderState; import net.minecraft.client.renderer.entity.state.ItemFrameRenderState; import net.minecraft.client.renderer.entity.state.LivingEntityRenderState; +import net.minecraft.client.renderer.special.SpecialModelRenderer; import net.minecraft.client.renderer.state.level.CameraRenderState; 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.world.InteractionHand; import net.minecraft.world.entity.Avatar; import net.minecraft.world.entity.EntityType; @@ -60,6 +62,7 @@ import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.PlayerModelType; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SkullBlock.Type; import net.minecraftforge.client.event.sound.PlaySoundSourceEvent; import net.minecraftforge.client.event.sound.PlayStreamingSourceEvent; diff --git a/src/main/java/net/minecraftforge/client/event/RegisterItemDecorationsEvent.java b/src/main/java/net/minecraftforge/client/event/RegisterItemDecorationsEvent.java index 2c26b95749..4c69fadb63 100644 --- a/src/main/java/net/minecraftforge/client/event/RegisterItemDecorationsEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RegisterItemDecorationsEvent.java @@ -40,7 +40,7 @@ public final class RegisterItemDecorationsEvent extends MutableEvent implements * Register an ItemDecorator to an Item */ public void register(ItemLike itemLike, IItemDecorator decorator) { - List itemDecoratorList = decorators.computeIfAbsent(itemLike.asItem(), _ -> new ArrayList<>()); + List itemDecoratorList = decorators.computeIfAbsent(itemLike.asItem(), item -> new ArrayList<>()); itemDecoratorList.add(decorator); } } diff --git a/src/main/java/net/minecraftforge/client/event/RegisterPictureInPictureRendererEvent.java b/src/main/java/net/minecraftforge/client/event/RegisterPictureInPictureRendererEvent.java index 57f9f752fa..a41610388b 100644 --- a/src/main/java/net/minecraftforge/client/event/RegisterPictureInPictureRendererEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RegisterPictureInPictureRendererEvent.java @@ -7,6 +7,7 @@ package net.minecraftforge.client.event; import com.google.common.collect.ImmutableMap; import net.minecraft.client.gui.render.pip.PictureInPictureRenderer; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.state.gui.pip.PictureInPictureRenderState; import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.event.MutableEvent; @@ -28,14 +29,20 @@ public final class RegisterPictureInPictureRendererEvent extends MutableEvent im public static final EventBus BUS = EventBus.create(RegisterPictureInPictureRendererEvent.class); private final List> renderers; + private final MultiBufferSource.BufferSource bufferSource; private final ImmutableMap.Builder, PictureInPictureRenderer> builder; @ApiStatus.Internal - public RegisterPictureInPictureRendererEvent(List> renderers, ImmutableMap.Builder, PictureInPictureRenderer> builder) { + public RegisterPictureInPictureRendererEvent(List> renderers, MultiBufferSource.BufferSource bufferSource, ImmutableMap.Builder, PictureInPictureRenderer> builder) { this.renderers = renderers; + this.bufferSource = bufferSource; this.builder = builder; } + public MultiBufferSource.BufferSource getBufferSource() { + return bufferSource; + } + public void register(PictureInPictureRenderer renderer) { var seen = HashSet.newHashSet(renderers.size()); for (var r : renderers) diff --git a/src/main/java/net/minecraftforge/client/event/RenderHighlightEvent.java b/src/main/java/net/minecraftforge/client/event/RenderHighlightEvent.java index 2c925c98a1..55e811413a 100644 --- a/src/main/java/net/minecraftforge/client/event/RenderHighlightEvent.java +++ b/src/main/java/net/minecraftforge/client/event/RenderHighlightEvent.java @@ -7,8 +7,8 @@ package net.minecraftforge.client.event; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Camera; -import net.minecraft.client.renderer.SubmitNodeCollector; -import net.minecraft.client.renderer.extract.LevelExtractor; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.MultiBufferSource.BufferSource; import net.minecraft.client.renderer.state.level.LevelRenderState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; @@ -33,13 +33,13 @@ import org.jetbrains.annotations.Nullable; public sealed abstract class RenderHighlightEvent extends MutableEvent implements Cancellable, InheritableEvent permits RenderHighlightEvent.Block, RenderHighlightEvent.Entity { CancellableEventBus BUS = CancellableEventBus.create(RenderHighlightEvent.class); - private final LevelExtractor levelExtractor; + private final LevelRenderer levelRenderer; private final Camera camera; private final LevelRenderState levelRenderState; private Callback customRenderer; - private RenderHighlightEvent(LevelExtractor levelExtractor, Camera camera, LevelRenderState levelRenderState) { - this.levelExtractor = levelExtractor; + private RenderHighlightEvent(LevelRenderer levelRenderer, Camera camera, LevelRenderState levelRenderState) { + this.levelRenderer = levelRenderer; this.camera = camera; this.levelRenderState = levelRenderState; } @@ -47,8 +47,8 @@ public sealed abstract class RenderHighlightEvent extends MutableEvent implement /** * {@return the level renderer} */ - public LevelExtractor getLevelExtractor() { - return this.levelExtractor; + public LevelRenderer getLevelRenderer() { + return this.levelRenderer; } /** @@ -101,8 +101,8 @@ public sealed abstract class RenderHighlightEvent extends MutableEvent implement private final BlockHitResult target; @ApiStatus.Internal - public Block(LevelExtractor levelExtrctor, Camera camera, LevelRenderState levelRenderState, BlockHitResult target) { - super(levelExtrctor, camera, levelRenderState); + public Block(LevelRenderer levelRenderer, Camera camera, LevelRenderState levelRenderState, BlockHitResult target) { + super(levelRenderer, camera, levelRenderState); this.target = target; } @@ -127,8 +127,8 @@ public sealed abstract class RenderHighlightEvent extends MutableEvent implement private final EntityHitResult target; @ApiStatus.Internal - public Entity(LevelExtractor levelExtractor, Camera camera, LevelRenderState levelRenderState, EntityHitResult target) { - super(levelExtractor, camera, levelRenderState); + public Entity(LevelRenderer levelRenderer, Camera camera, LevelRenderState levelRenderState, EntityHitResult target) { + super(levelRenderer, camera, levelRenderState); this.target = target; } @@ -142,6 +142,6 @@ public sealed abstract class RenderHighlightEvent extends MutableEvent implement } public interface Callback { - void render(SubmitNodeCollector submitNodeCollector, PoseStack stack, LevelRenderState state); + void render(BufferSource source, PoseStack stack, boolean translucent, LevelRenderState state); } } diff --git a/src/main/java/net/minecraftforge/client/event/sound/SoundEvent.java b/src/main/java/net/minecraftforge/client/event/sound/SoundEvent.java index 62bd1479aa..16ab583530 100644 --- a/src/main/java/net/minecraftforge/client/event/sound/SoundEvent.java +++ b/src/main/java/net/minecraftforge/client/event/sound/SoundEvent.java @@ -11,7 +11,9 @@ import com.mojang.blaze3d.audio.Channel; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.event.InheritableEvent; +import net.minecraftforge.eventbus.api.event.MutableEvent; import net.minecraftforge.fml.LogicalSide; +import org.jetbrains.annotations.ApiStatus; /** * Superclass for sound related events. diff --git a/src/main/java/net/minecraftforge/client/extensions/IForgeMinecraft.java b/src/main/java/net/minecraftforge/client/extensions/IForgeMinecraft.java index ea8bf45f33..a0d4b4f665 100644 --- a/src/main/java/net/minecraftforge/client/extensions/IForgeMinecraft.java +++ b/src/main/java/net/minecraftforge/client/extensions/IForgeMinecraft.java @@ -6,21 +6,45 @@ package net.minecraftforge.client.extensions; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraftforge.client.ForgeHooksClient; + import java.util.Locale; /** - * Extension interface for {@link Minecraft}. + * Extension interface for {@link IForgeMinecraft}. */ -public interface IForgeMinecraft { - private Minecraft self() { - return (Minecraft)this; +public interface IForgeMinecraft +{ + private Minecraft self() + { + return (Minecraft) this; + } + + /** + * Pushes a screen as a new GUI layer. + * + * @param screen the new GUI layer + */ + default void pushGuiLayer(Screen screen) + { + ForgeHooksClient.pushGuiLayer(self(), screen); + } + + /** + * Pops a GUI layer from the screen. + */ + default void popGuiLayer() + { + ForgeHooksClient.popGuiLayer(self()); } /** * Retrieves the {@link Locale} set by the player. * Useful for creating string and number formatters. */ - default Locale getLocale() { + default Locale getLocale() + { return self().getLanguageManager().getJavaLocale(); } } diff --git a/src/main/java/net/minecraftforge/client/extensions/common/IClientFluidTypeExtensions.java b/src/main/java/net/minecraftforge/client/extensions/common/IClientFluidTypeExtensions.java index b49d6286db..f8b0b1c149 100644 --- a/src/main/java/net/minecraftforge/client/extensions/common/IClientFluidTypeExtensions.java +++ b/src/main/java/net/minecraftforge/client/extensions/common/IClientFluidTypeExtensions.java @@ -10,8 +10,8 @@ import java.util.function.Consumer; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.ScreenEffectRenderer; -import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.block.BlockAndTintGetter; import net.minecraft.client.renderer.block.FluidModel; import net.minecraft.client.renderer.block.FluidRenderer; @@ -138,7 +138,7 @@ public interface IClientFluidTypeExtensions { * @param mc the client instance * @param poseStack the transformations representing the current rendering position */ - default void renderOverlay(Minecraft mc, PoseStack poseStack, SubmitNodeCollector buffer) { + default void renderOverlay(Minecraft mc, PoseStack poseStack, MultiBufferSource buffer) { Identifier texture = this.getRenderOverlayTexture(mc); if (texture != null) ScreenEffectRenderer.renderFluid(mc, poseStack, buffer, texture); 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 856e72ff45..8ebe973a29 100644 --- a/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java +++ b/src/main/java/net/minecraftforge/client/extensions/common/IClientMobEffectExtensions.java @@ -5,8 +5,8 @@ package net.minecraftforge.client.extensions.common; +import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphicsExtractor; -import net.minecraft.client.gui.Hud; import net.minecraft.client.gui.screens.inventory.EffectsInInventory; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; @@ -51,6 +51,12 @@ public interface IClientMobEffectExtensions { /** * Renders the text and icon of the specified effect in the player's inventory. * + * @param instance The effect instance + * @param effects The effect-rendering screen + * @param graphics The gui graphics + * @param x The x coordinate + * @param y The y coordinate + * @param blitOffset The blit offset * @return true to prevent default rendering, false otherwise */ default boolean extractInventory(MobEffectInstance instance, EffectsInInventory effects, GuiGraphicsExtractor graphics, int x, int y, int blitOffset) { @@ -61,10 +67,16 @@ public interface IClientMobEffectExtensions { * Renders the icon of the specified effect on the player's HUD. * This can be used to render icons from your own texture sheet. * + * @param instance The effect instance + * @param gui The gui + * @param graphics The gui graphics + * @param x The x coordinate + * @param y The y coordinate + * @param z The z depth * @param alpha The alpha value. Blinks when the effect is about to run out * @return true to prevent default rendering, false otherwise */ - default boolean extractGuiIcon(MobEffectInstance instance, Hud hud, GuiGraphicsExtractor graphics, int x, int y, float z, float alpha) { + default boolean extractGuiIcon(MobEffectInstance instance, Gui gui, GuiGraphicsExtractor graphics, int x, int y, float z, float alpha) { return false; } } diff --git a/src/main/java/net/minecraftforge/client/gui/LoadingErrorScreen.java b/src/main/java/net/minecraftforge/client/gui/LoadingErrorScreen.java index fd0f42538a..6c70a2f3eb 100644 --- a/src/main/java/net/minecraftforge/client/gui/LoadingErrorScreen.java +++ b/src/main/java/net/minecraftforge/client/gui/LoadingErrorScreen.java @@ -53,15 +53,15 @@ public class LoadingErrorScreen extends ErrorScreen { this.clearWidgets(); this.errorHeader = Component.literal(ChatFormatting.RED + ForgeI18n.parseMessage("fml.loadingerrorscreen.errorheader", this.modLoadErrors.size()) + ChatFormatting.RESET); - this.warningHeader = Component.literal(ChatFormatting.YELLOW + ForgeI18n.parseMessage("fml.loadingerrorscreen.warningheader", this.modLoadWarnings.size()) + ChatFormatting.RESET); + this.warningHeader = Component.literal(ChatFormatting.YELLOW + ForgeI18n.parseMessage("fml.loadingerrorscreen.warningheader", this.modLoadErrors.size()) + ChatFormatting.RESET); int yOffset = 46; - this.addRenderableWidget(new ExtendedButton(50, this.height - yOffset, this.width / 2 - 55, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.mods.folder")), _ -> Util.getPlatform().openFile(modsDir.toFile()))); - this.addRenderableWidget(new ExtendedButton(this.width / 2 + 5, this.height - yOffset, this.width / 2 - 55, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName())), _ -> Util.getPlatform().openFile(logFile.toFile()))); + this.addRenderableWidget(new ExtendedButton(50, this.height - yOffset, this.width / 2 - 55, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.mods.folder")), b -> Util.getPlatform().openFile(modsDir.toFile()))); + this.addRenderableWidget(new ExtendedButton(this.width / 2 + 5, this.height - yOffset, this.width / 2 - 55, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName())), b -> Util.getPlatform().openFile(logFile.toFile()))); if (this.modLoadErrors.isEmpty()) - this.addRenderableWidget(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, Component.literal(ForgeI18n.parseMessage("fml.button.continue.launch")), _ -> this.minecraft.gui.setScreen(null))); + this.addRenderableWidget(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, Component.literal(ForgeI18n.parseMessage("fml.button.continue.launch")), b -> this.minecraft.setScreen(null))); else - this.addRenderableWidget(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.file", dumpedLocation.getFileName())), _ -> Util.getPlatform().openFile(dumpedLocation.toFile()))); + this.addRenderableWidget(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, Component.literal(ForgeI18n.parseMessage("fml.button.open.file", dumpedLocation.getFileName())), b -> Util.getPlatform().openFile(dumpedLocation.toFile()))); this.entryList = new LoadingEntryList(this, this.modLoadErrors, this.modLoadWarnings); this.addWidget(this.entryList); @@ -70,6 +70,7 @@ public class LoadingErrorScreen extends ErrorScreen { @Override public void extractRenderState(GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) { + this.extractRenderState(guiGraphics, mouseX, mouseY, partialTick); this.entryList.extractRenderState(guiGraphics, mouseX, mouseY, partialTick); drawMultiLineCenteredString(guiGraphics, font, this.modLoadErrors.isEmpty() ? warningHeader : errorHeader, this.width / 2, 10); this.renderables.forEach(button -> button.extractRenderState(guiGraphics, mouseX, mouseY, partialTick)); diff --git a/src/main/java/net/minecraftforge/client/gui/ModListScreen.java b/src/main/java/net/minecraftforge/client/gui/ModListScreen.java index 5c8f9f3ca4..303aeaaa50 100644 --- a/src/main/java/net/minecraftforge/client/gui/ModListScreen.java +++ b/src/main/java/net/minecraftforge/client/gui/ModListScreen.java @@ -23,7 +23,6 @@ import net.minecraftforge.client.gui.widget.ModListWidget; import net.minecraftforge.client.gui.widget.ScrollPanel; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import org.apache.maven.artifact.versioning.ComparableVersion; -import org.jspecify.annotations.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ActiveTextCollector; @@ -228,16 +227,16 @@ public class ModListScreen extends Screen { final int doneButtonWidth = Math.min(modInfoWidth, 200); int y = this.height - BUTTON_HEIGHT - PADDING; - doneButton = Button.builder(Component.translatable("gui.done"), _ -> ModListScreen.this.onClose()) + doneButton = Button.builder(Component.translatable("gui.done"), b -> ModListScreen.this.onClose()) .bounds(((listWidth + PADDING + this.width - doneButtonWidth) / 2), y, doneButtonWidth, BUTTON_HEIGHT) .build(); - openModsFolderButton = Button.builder(Component.translatable("fml.menu.mods.openmodsfolder"), _ -> Util.getPlatform().openFile(FMLPaths.MODSDIR.get().toFile())) + openModsFolderButton = Button.builder(Component.translatable("fml.menu.mods.openmodsfolder"), b -> Util.getPlatform().openFile(FMLPaths.MODSDIR.get().toFile())) .bounds(6, y, this.listWidth, BUTTON_HEIGHT) .build(); y -= BUTTON_HEIGHT + PADDING; - configButton = Button.builder(Component.translatable("fml.menu.mods.config"), _ -> ModListScreen.this.displayModConfig()) + configButton = Button.builder(Component.translatable("fml.menu.mods.config"), b -> ModListScreen.this.displayModConfig()) .bounds(6, y, this.listWidth, BUTTON_HEIGHT) .build(); @@ -267,17 +266,17 @@ public class ModListScreen extends Screen { width = listWidth / NUM_BUTTONS; int x = PADDING; - addRenderableWidget(SortType.NORMAL.button = Button.builder(SortType.NORMAL.getButtonText(), _ -> resortMods(SortType.NORMAL)) + addRenderableWidget(SortType.NORMAL.button = Button.builder(SortType.NORMAL.getButtonText(), b -> resortMods(SortType.NORMAL)) .bounds(x, PADDING, width - BUTTON_MARGIN, BUTTON_HEIGHT) .build()); x += width + BUTTON_MARGIN; - addRenderableWidget(SortType.A_TO_Z.button = Button.builder(SortType.A_TO_Z.getButtonText(), _ -> resortMods(SortType.A_TO_Z)) + addRenderableWidget(SortType.A_TO_Z.button = Button.builder(SortType.A_TO_Z.getButtonText(), b -> resortMods(SortType.A_TO_Z)) .bounds(x, PADDING, width - BUTTON_MARGIN, BUTTON_HEIGHT) .build()); x += width + BUTTON_MARGIN; - addRenderableWidget(SortType.Z_TO_A.button = Button.builder(SortType.Z_TO_A.getButtonText(), _ -> resortMods(SortType.Z_TO_A)) + addRenderableWidget(SortType.Z_TO_A.button = Button.builder(SortType.Z_TO_A.getButtonText(), b -> resortMods(SortType.Z_TO_A)) .bounds(x, PADDING, width - BUTTON_MARGIN, BUTTON_HEIGHT) .build()); @@ -292,7 +291,7 @@ public class ModListScreen extends Screen { try { ConfigScreenHandler.getScreenFactoryFor(selected.getInfo()) .map(f -> f.apply(this.minecraft, this)) - .ifPresent(newScreen -> this.minecraft.gui.setScreen(newScreen)); + .ifPresent(newScreen -> this.minecraft.setScreen(newScreen)); } catch (final Exception e) { LOGGER.error("There was a critical issue trying to build the config GUI for {}", selected.getInfo().getModId(), e); } @@ -300,6 +299,8 @@ public class ModListScreen extends Screen { @Override public void tick() { + modList.setSelected(selected); + if (!search.getValue().equals(lastFilterText)) { reloadMods(); sorted = false; @@ -310,11 +311,11 @@ public class ModListScreen extends Screen { mods.sort(sortType); modList.refreshList(); if (selected != null) { - final var newSelected = modList.children().stream() + selected = modList.children().stream() .filter(e -> e.getInfo() == selected.getInfo()) .findFirst() .orElse(null); - this.modList.setSelected(newSelected); + updateCache(); } sorted = true; } @@ -364,14 +365,8 @@ public class ModListScreen extends Screen { } public void setSelected(ModListWidget.ModEntry entry) { - if (this.selected != entry) { - this.selected = entry; - updateCache(); - } - } - - public ModListWidget.@Nullable ModEntry getSelected() { - return this.selected; + this.selected = entry == this.selected ? null : entry; + updateCache(); } record Logo(Identifier texture, Size2i size) {} @@ -478,6 +473,7 @@ public class ModListScreen extends Screen { ModListWidget.ModEntry selected = this.selected; this.init(width, height); this.search.setValue(s); + this.selected = selected; if (!this.search.getValue().isEmpty()) reloadMods(); @@ -485,11 +481,11 @@ public class ModListScreen extends Screen { if (sort != SortType.NORMAL) resortMods(sort); - this.modList.setSelected(selected); + updateCache(); } @Override public void onClose() { - this.minecraft.gui.setScreen(this.parentScreen); + this.minecraft.setScreen(this.parentScreen); } } diff --git a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java index 5f4215ec3b..5c05861988 100644 --- a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java +++ b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java @@ -86,13 +86,13 @@ public class ModMismatchDisconnectedScreen extends Screen { this.addRenderableWidget(new MismatchInfoPanel(minecraft, listWidth, listHeight, (this.height - this.listHeight) / 2, listLeft)); int buttonWidth = Math.min(210, this.width / 2 - 20); - this.addRenderableWidget(Button.builder(Component.literal(ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName())), _ -> Util.getPlatform().openFile(logFile.toFile())) + this.addRenderableWidget(Button.builder(Component.literal(ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName())), button -> Util.getPlatform().openFile(logFile.toFile())) .bounds(Math.max(this.width / 4 - buttonWidth / 2, listLeft), upperButtonHeight, buttonWidth, 20) .build()); - this.addRenderableWidget(Button.builder(Component.literal(ForgeI18n.parseMessage("fml.button.open.mods.folder")), _ -> Util.getPlatform().openFile(modsDir.toFile())) + this.addRenderableWidget(Button.builder(Component.literal(ForgeI18n.parseMessage("fml.button.open.mods.folder")), button -> Util.getPlatform().openFile(modsDir.toFile())) .bounds(Math.min(this.width * 3 / 4 - buttonWidth / 2, listLeft + listWidth - buttonWidth), upperButtonHeight, buttonWidth, 20) .build()); - this.addRenderableWidget(Button.builder(Component.translatable("gui.toMenu"), _ -> this.minecraft.gui.setScreen(this.parent)) + this.addRenderableWidget(Button.builder(Component.translatable("gui.toMenu"), button -> this.minecraft.setScreen(this.parent)) .bounds((this.width - buttonWidth) / 2, lowerButtonHeight, buttonWidth, 20) .build()); } @@ -284,7 +284,7 @@ public class ModMismatchDisconnectedScreen extends Screen { int slotIndex = (int)(relativeY + (border / 2)) / 12; if (slotIndex < contentSize) { //The relative x needs to take the potentially missing indent of the row into account. It does that by checking if the line has a version associated to it - //double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent); + double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent); //if (relativeX >= 0) // return font.getSplitter().componentStyleAtWidth(lineTable.get(slotIndex).getLeft(), (int)relativeX); } diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayerInstance.java b/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayerInstance.java deleted file mode 100644 index 35b3a11255..0000000000 --- a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayerInstance.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.client.gui.overlay; - -import java.util.Objects; -import java.util.Stack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphicsExtractor; -import net.minecraft.client.gui.screens.Screen; -import net.minecraftforge.client.event.ScreenEvent; - -import org.jetbrains.annotations.ApiStatus; - -// This should be accessed via Gui -public abstract class ForgeLayerInstance { - public void pushLayer(Screen screen) { - if (screen() != null) - guiLayers.push(screen()); - setScreenInternal(Objects.requireNonNull(screen)); - screen.init(minecraft.getWindow().getGuiScaledWidth(), minecraft.getWindow().getGuiScaledHeight()); - minecraft.getNarrator().saySystemNow(screen.getNarrationMessage()); - } - - public void popLayer() { - if (guiLayers.isEmpty()) { - minecraft.gui.setScreen(null); - return; - } - - popLayerInternal(); - if (screen() != null) - minecraft.getNarrator().saySystemNow(screen().getNarrationMessage()); - } - - // Below here is private implementation details - - /** - * Contains the *extra* GUI layers. - * The current top layer stays in Minecraft#currentScreen, and the rest serve as a background for it. - */ - private final Stack guiLayers = new Stack<>(); - private final Minecraft minecraft; - - @ApiStatus.Internal - protected ForgeLayerInstance(Minecraft minecraft) { - this.minecraft = minecraft; - } - - @ApiStatus.Internal - protected abstract Screen screen(); - @ApiStatus.Internal - protected abstract void setScreenInternal(Screen value); - - @ApiStatus.Internal - public void resizeLayers(int width, int height) { - guiLayers.forEach(screen -> screen.resize(width, height)); - } - - @ApiStatus.Internal - protected void clearLayers() { - while (!guiLayers.isEmpty()) - popLayerInternal(); - } - - @ApiStatus.Internal - private void popLayerInternal() { - if (screen() != null) - screen().removed(); - setScreenInternal(guiLayers.pop()); - } - - @ApiStatus.Internal - protected void drawScreen(GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) { - guiGraphics.pose().pushMatrix(); - for (Screen layer : guiLayers) { - // Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted. - drawScreenInternal(layer, guiGraphics, Integer.MAX_VALUE, Integer.MAX_VALUE, partialTick); - //guiGraphics.pose().translate(0, 0, 10000); - } - drawScreenInternal(screen(), guiGraphics, mouseX, mouseY, partialTick); - guiGraphics.pose().popMatrix(); - } - - @ApiStatus.Internal - private static void drawScreenInternal(Screen screen, GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) { - if (!ScreenEvent.Render.Pre.BUS.post(new ScreenEvent.Render.Pre(screen, guiGraphics, mouseX, mouseY, partialTick))) - screen.extractRenderStateWithTooltipAndSubtitles(guiGraphics, mouseX, mouseY, partialTick); - ScreenEvent.Render.Post.BUS.post(new ScreenEvent.Render.Post(screen, guiGraphics, mouseX, mouseY, partialTick)); - } -} diff --git a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayeredDraw.java b/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayeredDraw.java index f25c9804c1..932f7a96f8 100644 --- a/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayeredDraw.java +++ b/src/main/java/net/minecraftforge/client/gui/overlay/ForgeLayeredDraw.java @@ -8,9 +8,8 @@ package net.minecraftforge.client.gui.overlay; import com.mojang.logging.LogUtils; import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphicsExtractor; -import net.minecraft.client.gui.Hud; -import net.minecraft.client.gui.contextualbar.ContextualBar; import net.minecraft.resources.Identifier; import net.minecraftforge.client.event.ForgeEventFactoryClient; import net.minecraftforge.client.event.AddGuiOverlayLayersEvent; @@ -39,27 +38,14 @@ public final class ForgeLayeredDraw implements ForgeLayer { private final List bakedLayers = new ArrayList<>(); private final Identifier name; - // Begin pre-sleep overlay public static final Identifier PRE_SLEEP_STACK = Identifier.withDefaultNamespace("pre_sleep_phase"); public static final Identifier CAMERA_OVERLAY = Identifier.withDefaultNamespace("camera_overlay"); public static final Identifier CROSSHAIR = Identifier.withDefaultNamespace("crosshair"); public static final Identifier CHANGE_STRATUM = Identifier.withDefaultNamespace("stratum_change"); - // Begin hotbar public static final Identifier HOTBAR_AND_DECOS = Identifier.withDefaultNamespace("hotbar"); - public static final Identifier ITEM_HOTBAR = Identifier.withDefaultNamespace("item_hotbar"); - public static final Identifier SPECTATOR_HOTBAR = Identifier.withDefaultNamespace("spectator_hotbar"); - public static final Identifier HEALTH_BAR = Identifier.withDefaultNamespace("health_bar"); - public static final Identifier VEHICLE_HEALTH = Identifier.withDefaultNamespace("vehicle_health"); - public static final Identifier BACKGROUND = Identifier.withDefaultNamespace("background"); // Any layer needing contextual info should order at some point after this layer. - public static final Identifier EXPERIENCE_LEVEL = Identifier.withDefaultNamespace("experience_level"); - public static final Identifier CONTEXTUAL_INFO = Identifier.withDefaultNamespace("contextual_info"); - public static final Identifier SELECTED_ITEM_NAME = Identifier.withDefaultNamespace("selected_item_name"); - public static final Identifier SPECTATOR_ACTION = Identifier.withDefaultNamespace("spectator_action"); - // End hotbar public static final Identifier POTION_EFFECTS = Identifier.withDefaultNamespace("potion_effects"); public static final Identifier BOSS_OVERLAY = Identifier.withDefaultNamespace("boss_overlay"); - // End pre-sleep overlay - // Begin post-sleep overlay + public static final Identifier POST_SLEEP_STACK = Identifier.withDefaultNamespace("post_sleep_phase"); public static final Identifier DEMO_OVERLAY = Identifier.withDefaultNamespace("demo"); public static final Identifier DEBUG_OVERLAY = Identifier.withDefaultNamespace("debug"); @@ -69,7 +55,6 @@ public final class ForgeLayeredDraw implements ForgeLayer { public static final Identifier CHAT_OVERLAY = Identifier.withDefaultNamespace("chat_overlay"); public static final Identifier TAB_LIST = Identifier.withDefaultNamespace("tab_list"); public static final Identifier SUBTITLE_OVERLAY = Identifier.withDefaultNamespace("subtitle"); - // End post-sleep overlay public static final Identifier VANILLA_ROOT = Identifier.withDefaultNamespace("vanilla_root"); public static final Identifier SLEEP_OVERLAY = Identifier.withDefaultNamespace("sleep_overlay"); @@ -102,22 +87,11 @@ public final class ForgeLayeredDraw implements ForgeLayer { return this; } - /** - * Adds a full draw stack and assumes condition is always true. - * Use {@linkplain ForgeLayeredDraw#putAbove} and {@linkplain ForgeLayeredDraw#putBelow} for fine location adjustment. - * @param name RL of the name to identify this stack with. - * @param layeredDraw the draw stack - * @return this - */ - public ForgeLayeredDraw add(Identifier name, ForgeLayeredDraw layeredDraw) { - return add(name, layeredDraw, () -> true); - } - /** * Add a layer to the layer list. This layer will be at the end of the list, which means * it will be rendered last (on top) of already added layers. * @param name RL for other mods to order against. - * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Hud} + * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui} * @return this */ public ForgeLayeredDraw add(Identifier targetStack, Identifier name, ForgeLayer layer) { @@ -130,7 +104,7 @@ public final class ForgeLayeredDraw implements ForgeLayer { * Use any of the non-deprecated add methods if you want a specific instance, * or call {@linkplain ForgeLayeredDraw#locateStack(Identifier)} to get a reference to an instance. * @param name RL of layer to add - * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Hud} + * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui} * @return this */ public ForgeLayeredDraw add(Identifier name, ForgeLayer layer) { @@ -198,7 +172,7 @@ public final class ForgeLayeredDraw implements ForgeLayer { * If the current stack does not contain otherLayer, no changes will be made. * @param newLayer name of the layer to be added * @param otherLayer name of the layer being ordered against - * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Hud} + * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui} * @return this */ public ForgeLayeredDraw addAbove(Identifier expectedStack, Identifier newLayer, Identifier otherLayer, ForgeLayer layer) { @@ -225,7 +199,7 @@ public final class ForgeLayeredDraw implements ForgeLayer { * If the current stack does not contain otherLayer, no changes will be made. * @param newLayer name of the layer to be added * @param otherLayer name of the layer being ordered against - * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Hud} + * @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui} * @return this */ public ForgeLayeredDraw addBelow(Identifier expectedStack, Identifier newLayer, Identifier otherLayer, ForgeLayer layer) { @@ -294,7 +268,7 @@ public final class ForgeLayeredDraw implements ForgeLayer { */ public ForgeLayeredDraw addConditionTo(Identifier targetLayer, BooleanSupplier condition) { var result = namedLayers.computeIfPresent(targetLayer, - (_, layer) -> (guiGraphics, deltaTracker) -> { + (name, layer) -> (guiGraphics, deltaTracker) -> { if (condition.getAsBoolean()) { layer.extract(guiGraphics, deltaTracker); } @@ -305,28 +279,6 @@ public final class ForgeLayeredDraw implements ForgeLayer { return this; } - /** - * Replaces the renderer of a single layer and logs whodunnit, this is not recommended for obvious reasons. - * Will not work if target is a ForgeLayeredDraw - * Prefer {@linkplain ForgeLayeredDraw#addConditionTo} - * @param expectedLocation Layer stack where the target should be. - * @param targetLayer Target whose renderer should be replaced. - * @param replacementRenderer Renderer to use instead. - * @return this - */ - public ForgeLayeredDraw replace(Identifier expectedLocation, Identifier targetLayer, ForgeLayer replacementRenderer) { - locateStack(expectedLocation).ifPresentOrElse((stack) -> { - if (stack.namedLayers.get(targetLayer) != null) { - stack.namedLayers.put(targetLayer, replacementRenderer); - LogUtils.getLogger().debug("ForgeLayer {} in {} was replaced by {}.", targetLayer, expectedLocation, replacementRenderer); - } else { - LogUtils.getLogger().debug("ForgeLayer {} in {} was attempted to be replaced by {}, but it did not exist.", targetLayer, expectedLocation, replacementRenderer); - } - }, () -> stackNotPresentWarning(expectedLocation)); - - return this; - } - /** * Propagate the layer order down to the inner render list after providing modders an opportunity to alter the list as they wish. * @apiNote Modders should NEVER be calling this method. @@ -428,23 +380,12 @@ public final class ForgeLayeredDraw implements ForgeLayer { } @ApiStatus.Internal - public static void init(Hud gui, Minecraft minecraft) { - BooleanSupplier spectator = () -> minecraft.gameMode.isSpectator(); - var hotbarCluster = new ForgeLayeredDraw(HOTBAR_AND_DECOS) - .addWithCondition(SPECTATOR_HOTBAR, (gg, _) -> gui.getSpectatorGui().extractHotbar(gg), spectator) - .addWithCondition(ITEM_HOTBAR, gui::extractItemHotbar, () -> !spectator.getAsBoolean()) - .addWithCondition(HEALTH_BAR, (gg, _) -> gui.extractPlayerHealth(gg), () -> minecraft.gameMode.canHurtPlayer()) - .add(VEHICLE_HEALTH, (gg, _) -> gui.extractVehicleHealth(gg)) - .add(BACKGROUND, gui::updateContextualInfo) - .addWithCondition(EXPERIENCE_LEVEL, (gg, _) -> ContextualBar.extractExperienceLevel(gg, minecraft.font, minecraft.player.experienceLevel), () -> minecraft.gameMode.hasExperience() && minecraft.player.experienceLevel > 0) - .add(CONTEXTUAL_INFO, gui::extractContextualInfoState) - .addWithCondition(SELECTED_ITEM_NAME, (gg, _) -> gui.extractSelectedItemName(gg), () -> !spectator.getAsBoolean()) - .addWithCondition(SPECTATOR_ACTION, (gg, _) -> gui.getSpectatorGui().extractAction(gg), spectator); + public static void init(Gui gui, Minecraft minecraft) { var preSleepDraw = new ForgeLayeredDraw(PRE_SLEEP_STACK) .add(CAMERA_OVERLAY, gui::extractCameraOverlays) .add(CROSSHAIR, gui::extractCrosshair) - .add(CHANGE_STRATUM, (gg, _) -> gg.nextStratum()) - .add(HOTBAR_AND_DECOS, hotbarCluster) + .add(CHANGE_STRATUM, (gg, dt) -> gg.nextStratum()) + .add(HOTBAR_AND_DECOS, gui::extractHotbarAndDecorations) .add(POTION_EFFECTS, gui::extractEffects) .add(BOSS_OVERLAY, gui::extractBossOverlay); var postSleepDraw = new ForgeLayeredDraw(POST_SLEEP_STACK) @@ -454,13 +395,13 @@ public final class ForgeLayeredDraw implements ForgeLayer { .add(TITLE_OVERLAY, gui::extractTitle) .add(CHAT_OVERLAY, gui::extractChat) .add(TAB_LIST, gui::extractTabList) - .add(SUBTITLE_OVERLAY, (gfx, _) -> gui.extractSubtitleOverlay(gfx, minecraft.gui.screen() != null && minecraft.gui.screen().isInGameUi())); + .add(SUBTITLE_OVERLAY, (gfx, delta) -> gui.extractSubtitleOverlay(gfx, minecraft.screen != null && minecraft.screen.isInGameUi())); instance - .add(PRE_SLEEP_STACK, preSleepDraw, () -> !gui.isHidden()) + .add(PRE_SLEEP_STACK, preSleepDraw, () -> !minecraft.options.hideGui) .add(SLEEP_OVERLAY, gui::extractSleepOverlay) - .add(POST_SLEEP_STACK, postSleepDraw, () -> !gui.isHidden()) - .add(SUBTITLE_OVERLAY, (gfx, _) -> { - if (!gui.isHidden() && minecraft.gui.screen() != null && minecraft.gui.screen().isInGameUi()) + .add(POST_SLEEP_STACK, postSleepDraw, () -> !minecraft.options.hideGui) + .add(SUBTITLE_OVERLAY, (gfx, delta) -> { + if (minecraft.options.hideGui && minecraft.screen != null && minecraft.screen.isInGameUi()) gui.extractSubtitleOverlay(gfx, true); }); instance.resolveLayers(); diff --git a/src/main/java/net/minecraftforge/client/gui/widget/ModListWidget.java b/src/main/java/net/minecraftforge/client/gui/widget/ModListWidget.java index a55edd14cf..062af04bbe 100644 --- a/src/main/java/net/minecraftforge/client/gui/widget/ModListWidget.java +++ b/src/main/java/net/minecraftforge/client/gui/widget/ModListWidget.java @@ -5,8 +5,6 @@ package net.minecraftforge.client.gui.widget; -import org.jspecify.annotations.Nullable; - import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.components.ObjectSelectionList; @@ -62,12 +60,6 @@ public class ModListWidget extends ObjectSelectionList { parent.buildModList(this::addEntry, mod->new ModEntry(mod, this.parent)); } - @Override - public void setSelected(final @Nullable ModEntry selected) { - parent.setSelected(selected); - super.setSelected(selected); - } - public class ModEntry extends ObjectSelectionList.Entry { private final IModInfo modInfo; private final ModListScreen parent; @@ -100,15 +92,14 @@ public class ModListWidget extends ObjectSelectionList { guiGraphics.pose().pushMatrix(); guiGraphics.blit(RenderPipelines.GUI_TEXTURED, VERSION_CHECK_ICONS, getX() + width - 12 - barOffset, top + entryHeight / 4, vercheck.status().getSheetOffset() * 8, (vercheck.status().isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16); guiGraphics.pose().popMatrix(); + } } @Override public boolean mouseClicked(MouseButtonEvent info, boolean recent) { - if (this.parent.getSelected() == this) - ModListWidget.this.setSelected(null); - else - ModListWidget.this.setSelected(this); + parent.setSelected(this); + ModListWidget.this.setSelected(this); return false; } diff --git a/src/main/java/net/minecraftforge/client/loading/ClientModLoader.java b/src/main/java/net/minecraftforge/client/loading/ClientModLoader.java index 88a633898e..cbd4e5e76c 100644 --- a/src/main/java/net/minecraftforge/client/loading/ClientModLoader.java +++ b/src/main/java/net/minecraftforge/client/loading/ClientModLoader.java @@ -114,7 +114,7 @@ public final class ClientModLoader { if (error != null || !warnings.isEmpty()) { BusGroup.DEFAULT.shutdown(); - mc.gui.setScreen(new LoadingErrorScreen(error, warnings, dumpedLocation)); + mc.setScreen(new LoadingErrorScreen(error, warnings, dumpedLocation)); return true; } diff --git a/src/main/java/net/minecraftforge/client/model/DynamicFluidContainerModel.java b/src/main/java/net/minecraftforge/client/model/DynamicFluidContainerModel.java index 263c3b71d8..c2f18abdcf 100644 --- a/src/main/java/net/minecraftforge/client/model/DynamicFluidContainerModel.java +++ b/src/main/java/net/minecraftforge/client/model/DynamicFluidContainerModel.java @@ -8,6 +8,7 @@ package net.minecraftforge.client.model; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.mojang.math.Transformation; + import net.minecraft.client.renderer.block.dispatch.ModelState; import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.client.resources.model.ModelBaker; @@ -30,7 +31,6 @@ import net.minecraftforge.client.model.geometry.IGeometryLoader; import net.minecraftforge.client.model.geometry.StandaloneGeometryBakingContext; import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper; import net.minecraftforge.registries.ForgeRegistries; - import org.joml.Quaternionf; import org.joml.Vector3f; @@ -81,26 +81,17 @@ public class DynamicFluidContainerModel implements UnbakedGeometry { @Override public QuadCollection bake(TextureSlots textures, ModelBaker baker, ModelState state, ModelDebugName name, IGeometryBakingContext context) { Material fluidMaskLocation = textures.getMaterial("fluid"); - Material coverLocation = textures.getMaterial("cover"); Material stillMaterial = null; if (fluid != Fluids.EMPTY) { var stillTexture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); - if (stillTexture != null) { - // Models can no longer have textures across atlases, so redirect to the item model of the same name. - // Modders may need to make clones of their textures in the item atlas, or provide a custom atlas alias - if (stillTexture.getPath().startsWith("block/")) - stillTexture = stillTexture.withPath(path -> "item/" + path.substring(6)); - stillMaterial = new Material(stillTexture); - } + stillMaterial = new Material(stillTexture); } - var materials = baker.materials(); var baseMaterial = materials.resolveSlot(textures, "base", name); var fluidMaterial = stillMaterial == null ? null : materials.get(stillMaterial, name); - var coverMaterial = coverLocation == null ? null : materials.get(coverLocation, name); - + var coverMaterial = materials.resolveSlot(textures, "cover", name); /* var particleSprite = sprites.resolveSlot(textures, "particle", name); @@ -113,10 +104,8 @@ public class DynamicFluidContainerModel implements UnbakedGeometry { // TODO: [Forge][Rendering] See if we can get rid of SimpleModelState and wrap transforms completely // If the fluid is lighter than air, rotate 180deg to turn it upside down - if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir()) { + if (flipGas && fluid != Fluids.EMPTY && fluid.getFluidType().isLighterThanAir()) transformation = transformation.compose(new Transformation(null, new Quaternionf(0, 0, 1, 0), null, null)); - state = new SimpleModelState(transformation); - } var buf = new QuadCollection.Builder(); @@ -128,7 +117,7 @@ public class DynamicFluidContainerModel implements UnbakedGeometry { var templateMaterial = materials.get(fluidMaskLocation, name); if (templateMaterial != null) { var transformedState = new SimpleModelState(transformation.compose(FLUID_TRANSFORM)); - UnbakedGeometryHelper.bakeMaskedSprite(buf, baker.interner(), transformedState, info(baker, fluidMaterial, 1), info(baker, templateMaterial, 1)); + UnbakedGeometryHelper.bakeMaskedSprite(buf, baker.interner(), transformedState, info(baker, templateMaterial, 1), info(baker, fluidMaterial, 1)); } } diff --git a/src/main/java/net/minecraftforge/client/model/data/ModelDataManager.java b/src/main/java/net/minecraftforge/client/model/data/ModelDataManager.java index 7feac00250..65ccf9fa46 100644 --- a/src/main/java/net/minecraftforge/client/model/data/ModelDataManager.java +++ b/src/main/java/net/minecraftforge/client/model/data/ModelDataManager.java @@ -44,7 +44,7 @@ public class ModelDataManager { public void requestRefresh(@NotNull BlockEntity blockEntity) { Preconditions.checkNotNull(blockEntity, "Block entity must not be null"); - needModelDataRefresh.computeIfAbsent(ChunkPos.containing(blockEntity.getBlockPos()), _ -> Collections.synchronizedSet(new HashSet<>())) + needModelDataRefresh.computeIfAbsent(ChunkPos.containing(blockEntity.getBlockPos()), $ -> Collections.synchronizedSet(new HashSet<>())) .add(blockEntity.getBlockPos()); } @@ -52,7 +52,7 @@ public class ModelDataManager { Set needUpdate = needModelDataRefresh.remove(chunk); if (needUpdate != null) { - Map data = modelDataCache.computeIfAbsent(chunk, _ -> new ConcurrentHashMap<>()); + Map data = modelDataCache.computeIfAbsent(chunk, $ -> new ConcurrentHashMap<>()); for (BlockPos pos : needUpdate) { BlockEntity toUpdate = level.getBlockEntity(pos); if (toUpdate != null && !toUpdate.isRemoved()) diff --git a/src/main/java/net/minecraftforge/client/model/geometry/StandaloneGeometryBakingContext.java b/src/main/java/net/minecraftforge/client/model/geometry/StandaloneGeometryBakingContext.java index 9dd4bcedf8..751f0215e8 100644 --- a/src/main/java/net/minecraftforge/client/model/geometry/StandaloneGeometryBakingContext.java +++ b/src/main/java/net/minecraftforge/client/model/geometry/StandaloneGeometryBakingContext.java @@ -120,7 +120,7 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext { private Identifier renderTypeHint; @Nullable private Identifier renderTypeFastHint; - private BiPredicate visibilityTest = (_, def) -> def; + private BiPredicate visibilityTest = (c, def) -> def; private Builder() { } diff --git a/src/main/java/net/minecraftforge/client/model/geometry/UnbakedGeometryHelper.java b/src/main/java/net/minecraftforge/client/model/geometry/UnbakedGeometryHelper.java index 4cb1468bb8..bd80bcb1aa 100644 --- a/src/main/java/net/minecraftforge/client/model/geometry/UnbakedGeometryHelper.java +++ b/src/main/java/net/minecraftforge/client/model/geometry/UnbakedGeometryHelper.java @@ -11,7 +11,6 @@ import net.minecraft.client.renderer.block.dispatch.ModelState; import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.resources.model.ModelBaker; -import net.minecraft.client.resources.model.cuboid.CuboidFace; import net.minecraft.client.resources.model.cuboid.FaceBakery; import net.minecraft.client.resources.model.cuboid.ItemModelGenerator; import net.minecraft.client.resources.model.geometry.BakedQuad; @@ -92,16 +91,15 @@ public class UnbakedGeometryHelper { final BakedQuad.MaterialInfo texture, final BakedQuad.MaterialInfo template ) { - var sprite = template.sprite().contents(); - int width = sprite.width(); - int height = sprite.height(); + var spriteContents = template.sprite().contents(); + int width = spriteContents.width(), height = spriteContents.height(); var bits = new BitSet(width * height); // For every frame in the texture, mark all the opaque pixels (this is what vanilla does too) - sprite.getUniqueFrames().forEach(frame -> { + spriteContents.getUniqueFrames().forEach(frame -> { for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) - if (!sprite.isTransparent(frame, x, y)) + if (!spriteContents.isTransparent(frame, x, y)) bits.set(x + y * width); }); @@ -134,10 +132,8 @@ public class UnbakedGeometryHelper { var to = new Vector3f(16 * x / (float) width, 16 - 16 * y / (float) height, 8.5F); // Create element - var southUvs = new CuboidFace.UVs(from.x, from.y, to.x, to.y); - var northUvs = new CuboidFace.UVs(to.x, from.y, from.x, to.y); - builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, southUvs, Quadrant.R0, texture, Direction.SOUTH, state, null)); - builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, northUvs, Quadrant.R0, texture, Direction.NORTH, state, null)); + builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, ItemModelGenerator.SOUTH_FACE_UVS, Quadrant.R0, texture, Direction.SOUTH, state, null)); + builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, ItemModelGenerator.NORTH_FACE_UVS, Quadrant.R0, texture, Direction.NORTH, state, null)); // Reset xStart xStart = -1; diff --git a/src/main/java/net/minecraftforge/client/model/obj/ObjLoader.java b/src/main/java/net/minecraftforge/client/model/obj/ObjLoader.java index 6e53e5f904..9a8bc7b1ee 100644 --- a/src/main/java/net/minecraftforge/client/model/obj/ObjLoader.java +++ b/src/main/java/net/minecraftforge/client/model/obj/ObjLoader.java @@ -64,7 +64,7 @@ public class ObjLoader implements IGeometryLoader, ResourceManagerReloadListener } public ObjModel loadModel(ObjModel.ModelSettings settings) { - return modelCache.computeIfAbsent(settings, (_) -> { + return modelCache.computeIfAbsent(settings, (data) -> { Resource resource = manager.getResource(settings.modelLocation()).orElseThrow(); try (ObjTokenizer tokenizer = new ObjTokenizer(resource.open())) { return ObjModel.parse(tokenizer, settings); 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 6625068cdb..16a68f25c3 100644 --- a/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java +++ b/src/main/java/net/minecraftforge/client/model/obj/ObjMaterialLibrary.java @@ -6,6 +6,7 @@ package net.minecraftforge.client.model.obj; import com.google.common.collect.Maps; +import net.minecraft.client.resources.model.ModelDebugName; import org.joml.Vector4f; import java.io.IOException; diff --git a/src/main/java/net/minecraftforge/client/model/obj/ObjTokenizer.java b/src/main/java/net/minecraftforge/client/model/obj/ObjTokenizer.java index c3d675da33..747ca6a389 100644 --- a/src/main/java/net/minecraftforge/client/model/obj/ObjTokenizer.java +++ b/src/main/java/net/minecraftforge/client/model/obj/ObjTokenizer.java @@ -5,34 +5,38 @@ package net.minecraftforge.client.model.obj; +import com.google.common.base.Charsets; +import joptsimple.internal.Strings; import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; -import java.util.regex.Pattern; /** * A tokenizer for OBJ and MTL files. *

* Joins split lines and ignores comments. */ -public class ObjTokenizer implements AutoCloseable { - private static final Pattern TABS = Pattern.compile("[\t ]+"); +public class ObjTokenizer implements AutoCloseable +{ private final BufferedReader lineReader; - public ObjTokenizer(InputStream inputStream) { - this.lineReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + public ObjTokenizer(InputStream inputStream) + { + this.lineReader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8)); } @Nullable - public String[] readAndSplitLine(boolean ignoreEmptyLines) throws IOException { + public String[] readAndSplitLine(boolean ignoreEmptyLines) throws IOException + { //noinspection LoopConditionNotUpdatedInsideLoop - do { + do + { String currentLine = lineReader.readLine(); if (currentLine == null) return null; @@ -42,19 +46,19 @@ public class ObjTokenizer implements AutoCloseable { if (currentLine.startsWith("#")) currentLine = ""; - if (!currentLine.isEmpty()) { + if (!currentLine.isEmpty()) + { boolean hasContinuation; - do { + do + { hasContinuation = currentLine.endsWith("\\"); String tmp = hasContinuation ? currentLine.substring(0, currentLine.length() - 1) : currentLine; - for (var part : TABS.split(tmp)) { - if (part != null && !part.isEmpty()) - lineParts.add(part); - } + Arrays.stream(tmp.split("[\t ]+")).filter(s -> !Strings.isNullOrEmpty(s)).forEach(lineParts::add); - if (hasContinuation) { + if (hasContinuation) + { currentLine = lineReader.readLine(); if (currentLine == null) break; @@ -74,7 +78,8 @@ public class ObjTokenizer implements AutoCloseable { } @Override - public void close() throws IOException { + public void close() throws IOException + { lineReader.close(); } } diff --git a/src/main/java/net/minecraftforge/client/model/renderable/BakedModelRenderable.java b/src/main/java/net/minecraftforge/client/model/renderable/BakedModelRenderable.java index 321b508f1c..9150aa121a 100644 --- a/src/main/java/net/minecraftforge/client/model/renderable/BakedModelRenderable.java +++ b/src/main/java/net/minecraftforge/client/model/renderable/BakedModelRenderable.java @@ -3,13 +3,13 @@ * SPDX-License-Identifier: LGPL-2.1-only */ -/* package net.minecraftforge.client.model.renderable; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.QuadInstance; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.dispatch.BlockStateModel; import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; import net.minecraft.client.renderer.texture.TextureAtlas; @@ -31,21 +31,21 @@ import java.util.Arrays; * a {@link ModelData} instance, and a {@link Vector4f tint}. * * @see Context - * / + */ public class BakedModelRenderable implements IRenderable { /** * Constructs a {@link BakedModelRenderable} from the given model location. * The model is expected to have been baked ahead of time. * * @see net.minecraftforge.client.event.ModelEvent.RegisterModelStateDefinitions - * / + */ public static BakedModelRenderable of(BlockState state) { return of(Minecraft.getInstance().getModelManager().getBlockStateModelSet().get(state)); } /** * Constructs a {@link BakedModelRenderable} from the given baked model. - * / + */ public static BakedModelRenderable of(BlockStateModel model) { return new BakedModelRenderable(model); } @@ -57,7 +57,7 @@ public class BakedModelRenderable implements IRenderable withModelDataContext() { - return (poseStack, textureRenderTypeLookup, lightmap, overlay, partialTick, context) -> - render(poseStack, textureRenderTypeLookup, lightmap, overlay, partialTick, new Context(context)); + return (poseStack, bufferSource, textureRenderTypeLookup, lightmap, overlay, partialTick, context) -> + render(poseStack, bufferSource, textureRenderTypeLookup, lightmap, overlay, partialTick, new Context(context)); } public record Context(@Nullable BlockState state, Direction[] faces, RandomSource randomSource, long seed, ModelData data, Vector4f tint) { @@ -100,4 +100,3 @@ public class BakedModelRenderable implements IRenderable { * @param partialTick The current time expressed in the fraction of a tick elapsed since the last client tick * @param context The context used for rendering */ - void render(PoseStack poseStack, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, float partialTick, T context); + void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay, float partialTick, T context); /** * Wraps the current renderable along with a context. @@ -36,7 +37,7 @@ public interface IRenderable { * @return A renderable that accepts {@link Unit#INSTANCE} as context, but uses the provided {@code context} instead */ default IRenderable withContext(T context) { - return (poseStack, textureRenderTypeLookup, lightmap, overlay, partialTick, _) -> - this.render(poseStack, textureRenderTypeLookup, lightmap, overlay, partialTick, context); + return (poseStack, bufferSource, textureRenderTypeLookup, lightmap, overlay, partialTick, unused) -> + this.render(poseStack, bufferSource, textureRenderTypeLookup, lightmap, overlay, partialTick, context); } } diff --git a/src/main/java/net/minecraftforge/client/settings/KeyConflictContext.java b/src/main/java/net/minecraftforge/client/settings/KeyConflictContext.java index 67cc790aa8..53d492a367 100644 --- a/src/main/java/net/minecraftforge/client/settings/KeyConflictContext.java +++ b/src/main/java/net/minecraftforge/client/settings/KeyConflictContext.java @@ -29,9 +29,10 @@ public enum KeyConflictContext implements IKeyConflictContext { * Gui key bindings are only used when a {@link Screen} is open. */ GUI { + @SuppressWarnings("resource") @Override public boolean isActive() { - return Minecraft.getInstance().gui.screen() != null; + return Minecraft.getInstance().screen != null; } @Override diff --git a/src/main/java/net/minecraftforge/client/settings/KeyMappingLookup.java b/src/main/java/net/minecraftforge/client/settings/KeyMappingLookup.java index 0400caa236..b17144259e 100644 --- a/src/main/java/net/minecraftforge/client/settings/KeyMappingLookup.java +++ b/src/main/java/net/minecraftforge/client/settings/KeyMappingLookup.java @@ -7,6 +7,8 @@ package net.minecraftforge.client.settings; import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyMapping; +import org.jetbrains.annotations.Nullable; + import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; @@ -58,7 +60,7 @@ public class KeyMappingLookup { public void put(InputConstants.Key keyCode, KeyMapping keyBinding) { var bindingsMap = map.get(keyBinding.getKeyModifier()); - var bindingsForKey = bindingsMap.computeIfAbsent(keyCode, _ -> new ArrayList()); + var bindingsForKey = bindingsMap.computeIfAbsent(keyCode, k -> new ArrayList()); bindingsForKey.add(keyBinding); } diff --git a/src/main/java/net/minecraftforge/common/CreativeModeTabRegistry.java b/src/main/java/net/minecraftforge/common/CreativeModeTabRegistry.java index 6ab9124cd7..bc9af0186e 100644 --- a/src/main/java/net/minecraftforge/common/CreativeModeTabRegistry.java +++ b/src/main/java/net/minecraftforge/common/CreativeModeTabRegistry.java @@ -160,7 +160,7 @@ public final class CreativeModeTabRegistry { } private static void setCreativeModeTabOrder(List tierList) { - runInServerThreadIfPossible(_ -> { + runInServerThreadIfPossible(hasServer -> { SORTED_TABS.clear(); SORTED_TABS.addAll(tierList); }); diff --git a/src/main/java/net/minecraftforge/common/DungeonHooks.java b/src/main/java/net/minecraftforge/common/DungeonHooks.java index 38680af611..9696286e3e 100644 --- a/src/main/java/net/minecraftforge/common/DungeonHooks.java +++ b/src/main/java/net/minecraftforge/common/DungeonHooks.java @@ -10,13 +10,12 @@ import java.util.ArrayList; import net.minecraft.util.RandomSource; import net.minecraft.util.random.WeightedList; import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.EntityTypes; public class DungeonHooks { private static WeightedList> dungeonMobs = WeightedList.>builder() - .add(EntityTypes.SKELETON, 100) - .add(EntityTypes.ZOMBIE, 200) - .add(EntityTypes.SPIDER, 100) + .add(EntityType.SKELETON, 100) + .add(EntityType.ZOMBIE, 200) + .add(EntityType.SPIDER, 100) .build(); /** diff --git a/src/main/java/net/minecraftforge/common/FarmlandWaterManager.java b/src/main/java/net/minecraftforge/common/FarmlandWaterManager.java index 1348e75a95..b7373a5aa2 100644 --- a/src/main/java/net/minecraftforge/common/FarmlandWaterManager.java +++ b/src/main/java/net/minecraftforge/common/FarmlandWaterManager.java @@ -45,7 +45,7 @@ public class FarmlandWaterManager { @SuppressWarnings("unchecked") public static> T addCustomTicket(Level level, T ticket, ChunkPos masterChunk, ChunkPos... additionalChunks) { Preconditions.checkArgument(!level.isClientSide(), "Water region is only determined server-side"); - Map> ticketMap = customWaterHandler.computeIfAbsent(level, _ -> new MapMaker().weakValues().makeMap()); + Map> ticketMap = customWaterHandler.computeIfAbsent(level, id -> new MapMaker().weakValues().makeMap()); ChunkTicketManager[] additionalTickets = new ChunkTicketManager[additionalChunks.length]; for (int i = 0; i < additionalChunks.length; i++) additionalTickets[i] = ticketMap.computeIfAbsent(additionalChunks[i], ChunkTicketManager::new); diff --git a/src/main/java/net/minecraftforge/common/ForgeConfigSpec.java b/src/main/java/net/minecraftforge/common/ForgeConfigSpec.java index 5ab0f771e6..c109a9bed1 100644 --- a/src/main/java/net/minecraftforge/common/ForgeConfigSpec.java +++ b/src/main/java/net/minecraftforge/common/ForgeConfigSpec.java @@ -82,9 +82,9 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper + (action, path, incorrectValue, correctedValue) -> LOGGER.warn(Logging.CORE, "Incorrect key {} was corrected from {} to its default, {}. {}", DOT_JOINER.join( path ), incorrectValue, correctedValue, incorrectValue == correctedValue ? "This seems to be an error." : ""), - (_, path, _, _) -> + (action, path, incorrectValue, correctedValue) -> LOGGER.debug(Logging.CORE, "The comment on key {} does not match the spec. This may create a backup.", DOT_JOINER.join( path ))); if (config instanceof FileConfig fileConfig) { @@ -140,12 +140,12 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper parentPath = new LinkedList<>(); - return correct(this.config, config, parentPath, Collections.unmodifiableList( parentPath ), (_, _, _, _) -> {}, null, true) == 0; + return correct(this.config, config, parentPath, Collections.unmodifiableList( parentPath ), (a, b, c, d) -> {}, null, true) == 0; } @Override public int correct(CommentedConfig config) { - return correct(config, (_, _, _, _) -> {}, null); + return correct(config, (action, path, incorrectValue, correctedValue) -> {}, null); } public synchronized int correct(CommentedConfig config, CorrectionListener listener) { diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index b6bb7bee81..fa78b156d0 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -15,7 +15,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; @@ -32,6 +31,7 @@ import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.Decoder; +import com.mojang.serialization.Dynamic; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.JsonOps; import com.mojang.serialization.Lifecycle; @@ -40,6 +40,7 @@ import io.netty.handler.codec.DecoderException; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.commands.arguments.selector.EntitySelectorParser; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder.Reference; @@ -49,11 +50,11 @@ import net.minecraft.core.HolderSet; import net.minecraft.core.HolderSet.Named; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.Connection; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.PacketListener; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.VarInt; import net.minecraft.network.chat.ClickEvent; @@ -107,7 +108,6 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.PacketFlow; -import net.minecraft.network.protocol.PacketType; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.network.syncher.EntityDataSerializer; @@ -158,9 +158,11 @@ import net.minecraftforge.event.level.NoteBlockEvent; import net.minecraftforge.event.level.ChunkEvent; import net.minecraftforge.event.network.CustomPayloadEvent; import net.minecraftforge.fluids.FluidType; +import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoader; import net.minecraftforge.fml.config.ConfigTracker; +import net.minecraftforge.fml.util.thread.EffectiveSide; import net.minecraftforge.network.ConnectionType; import net.minecraftforge.network.ForgePayload; import net.minecraftforge.network.NetworkContext; @@ -1013,13 +1015,11 @@ public final class ForgeHooks { @SuppressWarnings("deprecation") public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) { // Check things that vanilla considers to be air - these will cause the air supply to be increased. - // This is only called when the server level is already checked - var level = (ServerLevel)entity.level(); var eyeFluid = entity.getEyeInFluidType(); - boolean isAir = eyeFluid.isAir() || level.getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN); + boolean isAir = eyeFluid == null || 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(eyeFluid) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player player && player.getAbilities().invulnerable); - var breatheEvent = ForgeEventFactory.onLivingBreathe(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir || MobEffectUtil.shouldEffectsRefillAirsupply(entity)); + var breatheEvent = ForgeEventFactory.onLivingBreathe(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir); if (breatheEvent.canBreathe()) { if (breatheEvent.canRefillAir()) { entity.setAirSupply(Math.min(entity.getAirSupply() + breatheEvent.getRefillAirAmount(), entity.getMaxAirSupply())); @@ -1028,17 +1028,25 @@ public final class ForgeHooks { entity.setAirSupply(entity.getAirSupply() - breatheEvent.getConsumeAirAmount()); if (entity.getAirSupply() <= -20) { - var drownEvent = new LivingDrownEvent(entity, true, 2.0F, 8); + var drownEvent = new LivingDrownEvent(entity, entity.getAirSupply() <= -20, 2.0F, 8); if (!LivingDrownEvent.BUS.post(drownEvent) && drownEvent.isDrowning()) { entity.setAirSupply(0); - level.broadcastEntityEvent(entity, (byte)67); + Vec3 vec3 = entity.getDeltaMovement(); + + for (int i = 0; i < drownEvent.getBubbleCount(); ++i) { + double d2 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); + double d3 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); + double d4 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble(); + 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.hurtServer(level, entity.damageSources().drown(), drownEvent.getDamageAmount()); + entity.hurt(entity.damageSources().drown(), drownEvent.getDamageAmount()); } } } - if (!isAir && 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(); } } @@ -1050,7 +1058,7 @@ public final class ForgeHooks { } final var entries = new MutableHashedLinkedMap(ItemStackLinkedSet.TYPE_AND_TAG, - (_, _, _) -> { + (key, left, right) -> { //throw new IllegalStateException("Accidentally adding the same item stack twice " + key.getDisplayName().getString() + " to a Creative Mode Tab: " + tab.getDisplayName().getString()); // Vanilla adds enchanting books twice in both visibilities. // This is just code cleanliness for them. For us lets just increase the visibility and merge the entries. @@ -1318,32 +1326,4 @@ public final class ForgeHooks { return Optional.of(ret); } - - // This is similar to PacketUtils.ensureRunningOnSameThread, we can't use the normal LogicalSidedProvider.WORKQUEUE because it is processed after packets. - // So any vanilla packets that are received after this packet, will be processed before our enqueued packet. - public static void enqueuePacket(BiConsumer handler, MSG packet, CustomPayloadEvent.Context context) { - var processor = LogicalSidedProvider.PACKETS.get(context.isClientSide()); - if (!processor.isSameThread()) - processor.scheduleIfPossible(context.getConnection().getPacketListener(), new DummyPacket<>(handler, packet, context)); - else - handler.accept(packet, context); - } - - private static final record DummyPacket( - BiConsumer handler, - MSG packet, - CustomPayloadEvent.Context context - ) implements Packet { - private static final PacketType> TYPE = new PacketType<>(PacketFlow.CLIENTBOUND, Identifier.fromNamespaceAndPath("forge", "dummy_for_schedualing")); - - @Override - public PacketType> type() { - return TYPE; - } - - @Override - public void handle(PacketListener listener) { - handler.accept(packet, context); - } - } } \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/common/ForgeI18n.java b/src/main/java/net/minecraftforge/common/ForgeI18n.java index 27ab8def28..163a94a067 100644 --- a/src/main/java/net/minecraftforge/common/ForgeI18n.java +++ b/src/main/java/net/minecraftforge/common/ForgeI18n.java @@ -40,21 +40,21 @@ public class ForgeI18n { static { customFactories = new HashMap<>(); // {0,modinfo,id} -> modid from ModInfo object; {0,modinfo,name} -> displayname from ModInfo object - customFactories.put("modinfo", (_, formatString, _) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseModInfo(formatString, stringBuffer, objectToParse))); + customFactories.put("modinfo", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseModInfo(formatString, stringBuffer, objectToParse))); // {0,lower} -> lowercase supplied string - customFactories.put("lower", (_, _, _) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toLowerCase(String.valueOf(objectToParse))))); + customFactories.put("lower", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toLowerCase(String.valueOf(objectToParse))))); // {0,upper> -> uppercase supplied string - customFactories.put("upper", (_, _, _) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toUpperCase(String.valueOf(objectToParse))))); + customFactories.put("upper", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toUpperCase(String.valueOf(objectToParse))))); // {0,exc,cls} -> class of exception; {0,exc,msg} -> message from exception - customFactories.put("exc", (_, formatString, _) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseException(formatString, stringBuffer, objectToParse))); + customFactories.put("exc", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseException(formatString, stringBuffer, objectToParse))); // {0,vr} -> transform VersionRange into cleartext string using fml.messages.version.restriction.* strings - customFactories.put("vr", (_, _, _) -> new CustomReadOnlyFormat(MavenVersionStringHelper::parseVersionRange)); + customFactories.put("vr", (name, formatString, locale) -> new CustomReadOnlyFormat(MavenVersionStringHelper::parseVersionRange)); // {0,featurebound} -> transform feature bound to cleartext string - customFactories.put("featurebound", (_, _, _) -> new CustomReadOnlyFormat(MavenVersionStringHelper::parseFeatureBoundValue)); + customFactories.put("featurebound", (name, formatString, locale) -> new CustomReadOnlyFormat(MavenVersionStringHelper::parseFeatureBoundValue)); // {0,i18n,fml.message} -> pass object to i18n string 'fml.message' - customFactories.put("i18n", (_, formatString, _) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(ForgeI18n.parseMessage(formatString, o)))); + customFactories.put("i18n", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(ForgeI18n.parseMessage(formatString, o)))); // {0,ornull,fml.absent} -> append String value of o, or i18n string 'fml.absent' (message format transforms nulls into the string literal "null") - customFactories.put("ornull", ((_, formatString, _) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(Objects.equals(String.valueOf(o),"null") ? ForgeI18n.parseMessage(formatString) : String.valueOf(o))))); + customFactories.put("ornull", ((name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(Objects.equals(String.valueOf(o),"null") ? ForgeI18n.parseMessage(formatString) : String.valueOf(o))))); } private static void parseException(final String formatString, final StringBuffer stringBuffer, final Object objectToParse) { diff --git a/src/main/java/net/minecraftforge/common/ForgeMod.java b/src/main/java/net/minecraftforge/common/ForgeMod.java index cf0b5a8dd0..6888b9102b 100644 --- a/src/main/java/net/minecraftforge/common/ForgeMod.java +++ b/src/main/java/net/minecraftforge/common/ForgeMod.java @@ -37,8 +37,6 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.ForgeAtlasProvider; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.common.data.ForgeBiomeTagsProvider; @@ -49,6 +47,7 @@ import net.minecraftforge.common.data.ForgeFluidTagsProvider; import net.minecraftforge.common.data.ForgeItemTagsProvider; import net.minecraftforge.common.data.ForgeLootTableProvider; import net.minecraftforge.common.data.ForgeRecipeProvider; +import net.minecraftforge.common.data.ForgeSpriteSourceProvider; import net.minecraftforge.common.data.ForgeStructureTagsProvider; import net.minecraftforge.common.data.VanillaSoundDefinitionsProvider; import net.minecraftforge.common.loot.CanToolPerformAction; @@ -70,7 +69,6 @@ import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.config.ModConfigEvent; import net.minecraftforge.fml.event.lifecycle.*; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.registries.*; import net.minecraftforge.registries.holdersets.AndHolderSet; import net.minecraftforge.registries.holdersets.AnyHolderSet; @@ -446,11 +444,8 @@ public class ForgeMod { gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper)); gen.addProvider(event.includeServer(), new ForgeStructureTagsProvider(packOutput, lookupProvider, existingFileHelper)); + gen.addProvider(event.includeClient(), new ForgeSpriteSourceProvider(packOutput, existingFileHelper)); gen.addProvider(event.includeClient(), new VanillaSoundDefinitionsProvider(packOutput, existingFileHelper)); - // The provider uses Client only classes, so put a side guard on it. - if (FMLLoader.getDist() == Dist.CLIENT) { - gen.addProvider(event.includeClient(), new ForgeAtlasProvider(packOutput)); - } } // done in an event instead of deferred to only enable if a mod requests it @@ -511,7 +506,7 @@ public class ForgeMod { } public static final PermissionNode USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors", - PermissionTypes.BOOLEAN, (player, _, _) -> player != null && Commands.LEVEL_GAMEMASTERS.check(player.permissions())); + PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && Commands.LEVEL_GAMEMASTERS.check(player.permissions())); /** * TODO: Remove when {@link ForgeRegistry#addAlias(Identifier, Identifier)} is elevated to {@link IForgeRegistry}. diff --git a/src/main/java/net/minecraftforge/common/IForgeShearable.java b/src/main/java/net/minecraftforge/common/IForgeShearable.java new file mode 100644 index 0000000000..8e671d63db --- /dev/null +++ b/src/main/java/net/minecraftforge/common/IForgeShearable.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common; + +import java.util.Collections; +import java.util.List; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * + * This allows for mods to create there own Shear-like items + * and have them interact with Blocks/Entities without extra work. + * Also, if your block/entity supports the Shears, this allows you + * to support mod-shears as well. + * + */ +public interface IForgeShearable { + /** + * Checks if the object is currently shearable + * Example: Sheep return false when they have no wool + * + * @param item The ItemStack that is being used, may be empty. + * @param level The current level. + * @param pos Block's position in level. + * @return If this is shearable, and onSheared should be called. + */ + default boolean isShearable(@NotNull ItemStack item, Level level, BlockPos pos) { + return true; + } + + /** + * Performs the shear function on this object. + * This is called for both client, and server. + * The object should perform all actions related to being sheared, + * except for dropping of the items, and removal of the block. + * As those are handled by ItemShears itself. + * + * Returns a list of items that resulted from the shearing process. + * + * For entities, they should trust there internal location information + * over the values passed into this function. + * + * @param item The ItemStack that is being used, may be empty. + * @param level The current level. + * @param pos If this is a block, the block's position in level. + * @param fortune The fortune level of the shears being used. + * @return A List containing all items from this shearing. May be empty. + */ + @NotNull + default List onSheared(@Nullable Player player, @NotNull ItemStack item, Level level, BlockPos pos, int fortune) { + return Collections.emptyList(); + } +} diff --git a/src/main/java/net/minecraftforge/common/LenientUnboundedMapCodec.java b/src/main/java/net/minecraftforge/common/LenientUnboundedMapCodec.java index 6139b6674d..e620898253 100644 --- a/src/main/java/net/minecraftforge/common/LenientUnboundedMapCodec.java +++ b/src/main/java/net/minecraftforge/common/LenientUnboundedMapCodec.java @@ -52,17 +52,17 @@ public class LenientUnboundedMapCodec implements BaseMapCodec, Codec final DataResult v = elementCodec().parse(ops, pair.getSecond()); final DataResult> entry = k.apply2stable(Pair::of, v); - entry.error().ifPresent(_ -> failed.add(pair)); + entry.error().ifPresent(e -> failed.add(pair)); entry.result().ifPresent(e -> read.put(e.getFirst(), e.getSecond())); // FORGE: This line moved outside the below apply2stable condition - return r.apply2stable((u, _) -> u, entry); + return r.apply2stable((u, p) -> u, entry); }, - (r1, r2) -> r1.apply2stable((u1, _) -> u1, r2) + (r1, r2) -> r1.apply2stable((u1, u2) -> u1, r2) ); final Map elements = read.build(); final T errors = ops.createMap(failed.build().stream()); - return result.map(_ -> elements).setPartial(elements).mapError(e -> e + " missed input: " + errors); + return result.map(unit -> elements).setPartial(elements).mapError(e -> e + " missed input: " + errors); } @Override diff --git a/src/main/java/net/minecraftforge/common/MinecraftForge.java b/src/main/java/net/minecraftforge/common/MinecraftForge.java index 2a6093a3ca..efc38caa0e 100644 --- a/src/main/java/net/minecraftforge/common/MinecraftForge.java +++ b/src/main/java/net/minecraftforge/common/MinecraftForge.java @@ -67,7 +67,7 @@ public class MinecraftForge { * @see ModLoadingContext#registerConfig(ModConfig.Type, IConfigSpec) */ public static void registerConfigScreen(Function screenFunction) { - registerConfigScreen((_, modsScreen) -> screenFunction.apply(modsScreen)); + registerConfigScreen((mcClient, modsScreen) -> screenFunction.apply(modsScreen)); } /** diff --git a/src/main/java/net/minecraftforge/common/TagConventionMappings.java b/src/main/java/net/minecraftforge/common/TagConventionMappings.java index 1e65dec2bf..9266376fac 100644 --- a/src/main/java/net/minecraftforge/common/TagConventionMappings.java +++ b/src/main/java/net/minecraftforge/common/TagConventionMappings.java @@ -238,7 +238,7 @@ public final class TagConventionMappings { legacyToCommon(Registries.ITEM, forgeRl("tools/bows"), Tags.Items.TOOLS_BOW), legacyToCommon(Registries.ITEM, forgeRl("tools/crossbows"), Tags.Items.TOOLS_CROSSBOW), legacyToCommon(Registries.ITEM, forgeRl("tools/fishing_rods"), Tags.Items.TOOLS_FISHING_ROD), - legacyToCommon(Registries.ITEM, forgeRl("tools/tridents"), Tags.Items.TOOLS_TRIDENT), + legacyToCommon(Registries.ITEM, forgeRl("tools/tridents"), Tags.Items.TOOLS_SPEAR), legacyToCommon(Registries.ITEM, forgeRl("tools/shears"), Tags.Items.TOOLS_SHEAR), legacyToCommon(Registries.ITEM, forgeRl("armors"), Tags.Items.ARMORS), diff --git a/src/main/java/net/minecraftforge/common/Tags.java b/src/main/java/net/minecraftforge/common/Tags.java index 7977a14959..028f811a06 100644 --- a/src/main/java/net/minecraftforge/common/Tags.java +++ b/src/main/java/net/minecraftforge/common/Tags.java @@ -8,18 +8,15 @@ package net.minecraftforge.common; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.resources.Identifier; -import net.minecraft.tags.BlockItemTagId; import net.minecraft.tags.BlockTags; import net.minecraft.tags.FluidTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; -import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.monster.EnderMan; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemUseAnimation; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; @@ -32,7 +29,6 @@ import net.minecraftforge.fluids.capability.wrappers.FluidBucketWrapper; public class Tags { public static void init() { - BlockItems.init(); Blocks.init(); EntityTypes.init(); Items.init(); @@ -42,223 +38,6 @@ public class Tags { Structures.init(); } - public static class BlockItems { - private static void init() {} - //region forge specific tags - public static final BlockItemTagId STORAGE_BLOCKS_AMETHYST = forgeTag("storage_blocks/amethyst"); - public static final BlockItemTagId STORAGE_BLOCKS_QUARTZ = forgeTag("storage_blocks/quartz"); - //endregion - - - //region `c` tags for common conventions - // Note: Other loaders have additional `c` tags that are exclusive to their loader. - // Forge only adopts `c` tags that are common across all loaders. - public static final BlockItemTagId BARRELS = cTag("barrels"); - public static final BlockItemTagId BARRELS_WOODEN = cTag("barrels/wooden"); - /** - * Equivalent to the "minecraft:bars" block tag. - */ - public static final BlockItemTagId BARS = cTag("bars"); - public static final BlockItemTagId BARS_COPPER = cTag("bars/copper"); - public static final BlockItemTagId BARS_IRON = cTag("bars/iron"); - public static final BlockItemTagId BOOKSHELVES = cTag("bookshelves"); - /** - * For blocks that are similar to amethyst where their budding block produces buds and cluster blocks - */ - public static final BlockItemTagId BUDDING_BLOCKS = cTag("budding_blocks"); - /** - * For blocks that are similar to amethyst where they have buddings forming from budding blocks - */ - public static final BlockItemTagId BUDS = cTag("buds"); - public static final BlockItemTagId CHAINS = cTag("chains"); - public static final BlockItemTagId CHESTS = cTag("chests"); - public static final BlockItemTagId CHESTS_ENDER = cTag("chests/ender"); - public static final BlockItemTagId CHESTS_TRAPPED = cTag("chests/trapped"); - public static final BlockItemTagId CHESTS_WOODEN = cTag("chests/wooden"); - /** - * For blocks that are similar to amethyst where they have clusters forming from budding blocks - */ - public static final BlockItemTagId CLUSTERS = cTag("clusters"); - public static final BlockItemTagId COBBLESTONES = cTag("cobblestones"); - public static final BlockItemTagId COBBLESTONES_DEEPSLATE = cTag("cobblestones/deepslate"); - public static final BlockItemTagId COBBLESTONES_INFESTED = cTag("cobblestones/infested"); - public static final BlockItemTagId COBBLESTONES_MOSSY = cTag("cobblestones/mossy"); - public static final BlockItemTagId COBBLESTONES_NORMAL = cTag("cobblestones/normal"); - public static final BlockItemTagId CONCRETES = cTag("concretes"); - - public static final BlockItemTagId END_STONES = cTag("end_stones"); - - public static final BlockItemTagId FENCE_GATES = cTag("fence_gates"); - public static final BlockItemTagId FENCE_GATES_WOODEN = cTag("fence_gates/wooden"); - - public static final BlockItemTagId FENCES = cTag("fences"); - public static final BlockItemTagId FENCES_NETHER_BRICK = cTag("fences/nether_brick"); - public static final BlockItemTagId FENCES_WOODEN = cTag("fences/wooden"); - - /** - * Contains living ground-based flowers that are 1 block tall such as Dandelions or Poppy. - * Equivalent to the {@code minecraft:small_flowers} block tag. - * This is NOT aliased with {@link BlockTags#SMALL_FLOWERS} because the vanilla tag is used to make the block weak to swords. - */ - public static final BlockItemTagId FLOWERS_SMALL = cTag("flowers/small"); - /** - * Contains living ground-based flowers that are 2 block tall such as Rose Bush or Peony. - * Equivalent to the {@code minecraft:tall_flowers} block tag in past Minecraft versions. - */ - public static final BlockItemTagId FLOWERS_TALL = cTag("flowers/tall"); - /** - * Contains any living plant block that contains flowers or is a flower itself. - * Equivalent to the {@code minecraft:flowers} block tag. - * Aliased with {@link BlockTags#FLOWERS}. - */ - public static final BlockItemTagId FLOWERS = cTag("flowers"); - - public static final BlockItemTagId GRAVELS = cTag("gravels"); - - public static final BlockItemTagId GLASS_BLOCKS = cTag("glass_blocks"); - public static final BlockItemTagId GLASS_BLOCKS_COLORLESS = cTag("glass_blocks/colorless"); - /** - * Glass which is made from cheap resources like sand and only minor additional ingredients like dyes - */ - public static final BlockItemTagId GLASS_BLOCKS_CHEAP = cTag("glass_blocks/cheap"); - public static final BlockItemTagId GLASS_BLOCKS_TINTED = cTag("glass_blocks/tinted"); - - public static final BlockItemTagId GLASS_PANES = cTag("glass_panes"); - public static final BlockItemTagId GLASS_PANES_COLORLESS = cTag("glass_panes/colorless"); - public static final BlockItemTagId GLAZED_TERRACOTTAS = cTag("glazed_terracottas"); - - public static final BlockItemTagId NATURAL_LOGS = cTag("natural_logs"); - public static final BlockItemTagId NATURAL_LOGS_NETHER = cTag("natural_logs/nether"); - public static final BlockItemTagId NATURAL_LOGS_OVERWORLD = cTag("natural_logs/overworld"); - - public static final BlockItemTagId NATURAL_WOODS = cTag("natural_woods"); - - public static final BlockItemTagId NETHERRACKS = cTag("netherracks"); - - public static final BlockItemTagId OBSIDIANS = cTag("obsidians"); - /** - * For common obsidian that has no special quirks or behaviours - ideal for recipe use. - * Crying Obsidian, for example, is a light block and harder to obtain. So it gets its own tag instead of being under normal tag. - */ - public static final BlockItemTagId OBSIDIANS_NORMAL = cTag("obsidians/normal"); - public static final BlockItemTagId OBSIDIANS_CRYING = cTag("obsidians/crying"); - /** - * Blocks which are often replaced by deepslate ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_DEEPSLATE}, during world generation - */ - public static final BlockItemTagId ORE_BEARING_GROUND_DEEPSLATE = cTag("ore_bearing_ground/deepslate"); - /** - * Blocks which are often replaced by netherrack ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_NETHERRACK}, during world generation - */ - public static final BlockItemTagId ORE_BEARING_GROUND_NETHERRACK = cTag("ore_bearing_ground/netherrack"); - /** - * Blocks which are often replaced by stone ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_STONE}, during world generation - */ - public static final BlockItemTagId ORE_BEARING_GROUND_STONE = cTag("ore_bearing_ground/stone"); - /** - * Ores which on average result in more than one resource worth of materials - */ - public static final BlockItemTagId ORE_RATES_DENSE = cTag("ore_rates/dense"); - /** - * Ores which on average result in one resource worth of materials - */ - public static final BlockItemTagId ORE_RATES_SINGULAR = cTag("ore_rates/singular"); - /** - * Ores which on average result in less than one resource worth of materials - */ - public static final BlockItemTagId ORE_RATES_SPARSE = cTag("ore_rates/sparse"); - public static final BlockItemTagId ORES = cTag("ores"); - public static final BlockItemTagId ORES_NETHERITE_SCRAP = cTag("ores/netherite_scrap"); - public static final BlockItemTagId ORES_QUARTZ = cTag("ores/quartz"); - public static final BlockItemTagId ORES_COAL = cTag("ores/coal"); - public static final BlockItemTagId ORES_COPPER = cTag("ores/copper"); - public static final BlockItemTagId ORES_DIAMOND = cTag("ores/diamond"); - public static final BlockItemTagId ORES_EMERALD = cTag("ores/emerald"); - public static final BlockItemTagId ORES_GOLD = cTag("ores/gold"); - public static final BlockItemTagId ORES_IRON = cTag("ores/iron"); - public static final BlockItemTagId ORES_LAPIS = cTag("ores/lapis"); - public static final BlockItemTagId ORES_REDSTONE = cTag("ores/redstone"); - /** - * Ores in deepslate (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_DEEPSLATE}) which could logically use deepslate as recipe input or output - */ - public static final BlockItemTagId ORES_IN_GROUND_DEEPSLATE = cTag("ores_in_ground/deepslate"); - /** - * Ores in netherrack (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_NETHERRACK}) which could logically use netherrack as recipe input or output - */ - public static final BlockItemTagId ORES_IN_GROUND_NETHERRACK = cTag("ores_in_ground/netherrack"); - /** - * Ores in stone (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_STONE}) which could logically use stone as recipe input or output - */ - public static final BlockItemTagId ORES_IN_GROUND_STONE = cTag("ores_in_ground/stone"); - public static final BlockItemTagId PLAYER_WORKSTATIONS_CRAFTING_TABLES = cTag("player_workstations/crafting_tables"); - public static final BlockItemTagId PLAYER_WORKSTATIONS_FURNACES = cTag("player_workstations/furnaces"); - public static final BlockItemTagId PUMPKINS = cTag("pumpkins"); - /** For pumpkins that are not carved. */ - public static final BlockItemTagId PUMPKINS_NORMAL = cTag("pumpkins/normal"); - /** For pumpkins that are already carved but not a light source. */ - public static final BlockItemTagId PUMPKINS_CARVED = cTag("pumpkins/carved"); - /** For pumpkins that are already carved and a light source. */ - public static final BlockItemTagId PUMPKINS_JACK_O_LANTERNS = cTag("pumpkins/jack_o_lanterns"); - public static final BlockItemTagId ROPES = cTag("ropes"); - - public static final BlockItemTagId SANDS = cTag("sands"); - public static final BlockItemTagId SANDS_COLORLESS = cTag("sands/colorless"); - public static final BlockItemTagId SANDS_RED = cTag("sands/red"); - - public static final BlockItemTagId SANDSTONE_BLOCKS = cTag("sandstone/blocks"); - public static final BlockItemTagId SANDSTONE_SLABS = cTag("sandstone/slabs"); - public static final BlockItemTagId SANDSTONE_STAIRS = cTag("sandstone/stairs"); - public static final BlockItemTagId SANDSTONE_RED_BLOCKS = cTag("sandstone/red_blocks"); - public static final BlockItemTagId SANDSTONE_RED_SLABS = cTag("sandstone/red_slabs"); - public static final BlockItemTagId SANDSTONE_RED_STAIRS = cTag("sandstone/red_stairs"); - public static final BlockItemTagId SANDSTONE_UNCOLORED_BLOCKS = cTag("sandstone/uncolored_blocks"); - public static final BlockItemTagId SANDSTONE_UNCOLORED_SLABS = cTag("sandstone/uncolored_slabs"); - public static final BlockItemTagId SANDSTONE_UNCOLORED_STAIRS = cTag("sandstone/uncolored_stairs"); - /** - * Natural stone-like blocks that can be used as a base ingredient in recipes that takes stone. - */ - public static final BlockItemTagId STONES = cTag("stones"); - /** - * A storage block is generally a block that has a recipe to craft a bulk of 1 kind of resource to a block - * and has a mirror recipe to reverse the crafting with no loss in resources. - *

- * Honey Block is special in that the reversing recipe is not a perfect mirror of the crafting recipe - * and so, it is considered a special case and not given a storage block tag. - */ - public static final BlockItemTagId STORAGE_BLOCKS = cTag("storage_blocks"); - public static final BlockItemTagId STORAGE_BLOCKS_BONE_MEAL = cTag("storage_blocks/bone_meal"); - public static final BlockItemTagId STORAGE_BLOCKS_COAL = cTag("storage_blocks/coal"); - public static final BlockItemTagId STORAGE_BLOCKS_COPPER = cTag("storage_blocks/copper"); - public static final BlockItemTagId STORAGE_BLOCKS_DIAMOND = cTag("storage_blocks/diamond"); - public static final BlockItemTagId STORAGE_BLOCKS_DRIED_KELP = cTag("storage_blocks/dried_kelp"); - public static final BlockItemTagId STORAGE_BLOCKS_EMERALD = cTag("storage_blocks/emerald"); - public static final BlockItemTagId STORAGE_BLOCKS_GOLD = cTag("storage_blocks/gold"); - public static final BlockItemTagId STORAGE_BLOCKS_IRON = cTag("storage_blocks/iron"); - public static final BlockItemTagId STORAGE_BLOCKS_LAPIS = cTag("storage_blocks/lapis"); - public static final BlockItemTagId STORAGE_BLOCKS_NETHERITE = cTag("storage_blocks/netherite"); - public static final BlockItemTagId STORAGE_BLOCKS_RAW_COPPER = cTag("storage_blocks/raw_copper"); - public static final BlockItemTagId STORAGE_BLOCKS_RAW_GOLD = cTag("storage_blocks/raw_gold"); - public static final BlockItemTagId STORAGE_BLOCKS_RAW_IRON = cTag("storage_blocks/raw_iron"); - public static final BlockItemTagId STORAGE_BLOCKS_REDSTONE = cTag("storage_blocks/redstone"); - public static final BlockItemTagId STORAGE_BLOCKS_RESIN = cTag("storage_blocks/resin"); - public static final BlockItemTagId STORAGE_BLOCKS_SLIME = cTag("storage_blocks/slime"); - public static final BlockItemTagId STORAGE_BLOCKS_WHEAT = cTag("storage_blocks/wheat"); - public static final BlockItemTagId STRIPPED_LOGS = cTag("stripped_logs"); - public static final BlockItemTagId STRIPPED_WOODS = cTag("stripped_woods"); - //endregion - - private static BlockItemTagId cTag(String name) { - return create(Identifier.fromNamespaceAndPath("c", name)); - } - - private static BlockItemTagId forgeTag(String name) { - return create(Identifier.fromNamespaceAndPath("forge", name)); - } - - private static BlockItemTagId create(Identifier id) { - return BlockItemTagId.create(id, id); - } - } - public static class Blocks { private static void init() {} @@ -272,45 +51,39 @@ public class Tags { public static final TagKey NEEDS_WOOD_TOOL = forgeTag("needs_wood_tool"); public static final TagKey NEEDS_GOLD_TOOL = forgeTag("needs_gold_tool"); public static final TagKey NEEDS_NETHERITE_TOOL = forgeTag("needs_netherite_tool"); - public static final TagKey STORAGE_BLOCKS_AMETHYST = BlockItems.STORAGE_BLOCKS_AMETHYST.block(); - public static final TagKey STORAGE_BLOCKS_QUARTZ = BlockItems.STORAGE_BLOCKS_QUARTZ.block(); + public static final TagKey STORAGE_BLOCKS_AMETHYST = forgeTag("storage_blocks/amethyst"); + public static final TagKey STORAGE_BLOCKS_QUARTZ = forgeTag("storage_blocks/quartz"); //endregion //region `c` tags for common conventions // Note: Other loaders have additional `c` tags that are exclusive to their loader. // Forge only adopts `c` tags that are common across all loaders. - public static final TagKey BARRELS = BlockItems.BARRELS.block(); - public static final TagKey BARRELS_WOODEN = BlockItems.BARRELS_WOODEN.block(); - /** - * Equivalent to the "minecraft:bars" block tag. - */ - public static final TagKey BARS = BlockItems.BARS.block(); - public static final TagKey BARS_COPPER = BlockItems.BARS_COPPER.block(); - public static final TagKey BARS_IRON = BlockItems.BARS_IRON.block(); - public static final TagKey BOOKSHELVES = BlockItems.BOOKSHELVES.block(); + public static final TagKey BARRELS = cTag("barrels"); + public static final TagKey BARRELS_WOODEN = cTag("barrels/wooden"); + public static final TagKey BOOKSHELVES = cTag("bookshelves"); /** * For blocks that are similar to amethyst where their budding block produces buds and cluster blocks */ - public static final TagKey BUDDING_BLOCKS = BlockItems.BUDDING_BLOCKS.block(); + public static final TagKey BUDDING_BLOCKS = cTag("budding_blocks"); /** * For blocks that are similar to amethyst where they have buddings forming from budding blocks */ - public static final TagKey BUDS = BlockItems.BUDS.block(); - public static final TagKey CHAINS = BlockItems.CHAINS.block(); - public static final TagKey CHESTS = BlockItems.CHESTS.block(); - public static final TagKey CHESTS_ENDER = BlockItems.CHESTS_ENDER.block(); - public static final TagKey CHESTS_TRAPPED = BlockItems.CHESTS_TRAPPED.block(); - public static final TagKey CHESTS_WOODEN = BlockItems.CHESTS_WOODEN.block(); + public static final TagKey BUDS = cTag("buds"); + public static final TagKey CHAINS = cTag("chains"); + public static final TagKey CHESTS = cTag("chests"); + public static final TagKey CHESTS_ENDER = cTag("chests/ender"); + public static final TagKey CHESTS_TRAPPED = cTag("chests/trapped"); + public static final TagKey CHESTS_WOODEN = cTag("chests/wooden"); /** * For blocks that are similar to amethyst where they have clusters forming from budding blocks */ - public static final TagKey CLUSTERS = BlockItems.CLUSTERS.block(); - public static final TagKey COBBLESTONES = BlockItems.COBBLESTONES.block(); - public static final TagKey COBBLESTONES_DEEPSLATE = BlockItems.COBBLESTONES_DEEPSLATE.block(); - public static final TagKey COBBLESTONES_INFESTED = BlockItems.COBBLESTONES_INFESTED.block(); - public static final TagKey COBBLESTONES_MOSSY = BlockItems.COBBLESTONES_MOSSY.block(); - public static final TagKey COBBLESTONES_NORMAL = BlockItems.COBBLESTONES_NORMAL.block(); - public static final TagKey CONCRETES = BlockItems.CONCRETES.block(); + public static final TagKey CLUSTERS = cTag("clusters"); + public static final TagKey COBBLESTONES = cTag("cobblestones"); + public static final TagKey COBBLESTONES_DEEPSLATE = cTag("cobblestones/deepslate"); + public static final TagKey COBBLESTONES_INFESTED = cTag("cobblestones/infested"); + public static final TagKey COBBLESTONES_MOSSY = cTag("cobblestones/mossy"); + public static final TagKey COBBLESTONES_NORMAL = cTag("cobblestones/normal"); + public static final TagKey CONCRETES = cTag("concretes"); /** * Tag that holds all blocks that can be dyed a specific color. @@ -334,46 +107,46 @@ public class Tags { public static final TagKey DYED_WHITE = cTag("dyed/white"); public static final TagKey DYED_YELLOW = cTag("dyed/yellow"); - public static final TagKey END_STONES = BlockItems.END_STONES.block(); + public static final TagKey END_STONES = cTag("end_stones"); - public static final TagKey FENCE_GATES = BlockItems.FENCE_GATES.block(); - public static final TagKey FENCE_GATES_WOODEN = BlockItems.FENCE_GATES_WOODEN.block(); + public static final TagKey FENCE_GATES = cTag("fence_gates"); + public static final TagKey FENCE_GATES_WOODEN = cTag("fence_gates/wooden"); - public static final TagKey FENCES = BlockItems.FENCES.block(); - public static final TagKey FENCES_NETHER_BRICK = BlockItems.FENCES_NETHER_BRICK.block(); - public static final TagKey FENCES_WOODEN = BlockItems.FENCES_WOODEN.block(); + public static final TagKey FENCES = cTag("fences"); + public static final TagKey FENCES_NETHER_BRICK = cTag("fences/nether_brick"); + public static final TagKey FENCES_WOODEN = cTag("fences/wooden"); /** * Contains living ground-based flowers that are 1 block tall such as Dandelions or Poppy. * Equivalent to the {@code minecraft:small_flowers} block tag. * This is NOT aliased with {@link BlockTags#SMALL_FLOWERS} because the vanilla tag is used to make the block weak to swords. */ - public static final TagKey FLOWERS_SMALL = BlockItems.FLOWERS_SMALL.block(); + public static final TagKey FLOWERS_SMALL = cTag("flowers/small"); /** * Contains living ground-based flowers that are 2 block tall such as Rose Bush or Peony. * Equivalent to the {@code minecraft:tall_flowers} block tag in past Minecraft versions. */ - public static final TagKey FLOWERS_TALL = BlockItems.FLOWERS_TALL.block(); + public static final TagKey FLOWERS_TALL = cTag("flowers/tall"); /** * Contains any living plant block that contains flowers or is a flower itself. * Equivalent to the {@code minecraft:flowers} block tag. * Aliased with {@link BlockTags#FLOWERS}. */ - public static final TagKey FLOWERS = BlockItems.FLOWERS.block(); + public static final TagKey FLOWERS = cTag("flowers"); - public static final TagKey GRAVELS = BlockItems.GRAVELS.block(); + public static final TagKey GRAVELS = cTag("gravels"); - public static final TagKey GLASS_BLOCKS = BlockItems.GLASS_BLOCKS.block(); - public static final TagKey GLASS_BLOCKS_COLORLESS = BlockItems.GLASS_BLOCKS_COLORLESS.block(); + public static final TagKey GLASS_BLOCKS = cTag("glass_blocks"); + public static final TagKey GLASS_BLOCKS_COLORLESS = cTag("glass_blocks/colorless"); /** * Glass which is made from cheap resources like sand and only minor additional ingredients like dyes */ - public static final TagKey GLASS_BLOCKS_CHEAP = BlockItems.GLASS_BLOCKS_CHEAP.block(); - public static final TagKey GLASS_BLOCKS_TINTED = BlockItems.GLASS_BLOCKS_TINTED.block(); + public static final TagKey GLASS_BLOCKS_CHEAP = cTag("glass_blocks/cheap"); + public static final TagKey GLASS_BLOCKS_TINTED = cTag("glass_blocks/tinted"); - public static final TagKey GLASS_PANES = BlockItems.GLASS_PANES.block(); - public static final TagKey GLASS_PANES_COLORLESS = BlockItems.GLASS_PANES_COLORLESS.block(); - public static final TagKey GLAZED_TERRACOTTAS = BlockItems.GLAZED_TERRACOTTAS.block(); + public static final TagKey GLASS_PANES = cTag("glass_panes"); + public static final TagKey GLASS_PANES_COLORLESS = cTag("glass_panes/colorless"); + public static final TagKey GLAZED_TERRACOTTAS = cTag("glazed_terracottas"); /** * Tag that holds all blocks that recipe viewers should not show to users. @@ -381,77 +154,77 @@ public class Tags { */ public static final TagKey HIDDEN_FROM_RECIPE_VIEWERS = cTag("hidden_from_recipe_viewers"); - public static final TagKey NATURAL_LOGS = BlockItems.NATURAL_LOGS.block(); - public static final TagKey NATURAL_LOGS_NETHER = BlockItems.NATURAL_LOGS_NETHER.block(); - public static final TagKey NATURAL_LOGS_OVERWORLD = BlockItems.NATURAL_LOGS_OVERWORLD.block(); + public static final TagKey NATURAL_LOGS = cTag("natural_logs"); + public static final TagKey NATURAL_LOGS_NETHER = cTag("natural_logs/nether"); + public static final TagKey NATURAL_LOGS_OVERWORLD = cTag("natural_logs/overworld"); - public static final TagKey NATURAL_WOODS = BlockItems.NATURAL_WOODS.block(); + public static final TagKey NATURAL_WOODS = cTag("natural_woods"); - public static final TagKey NETHERRACKS = BlockItems.NETHERRACKS.block(); + public static final TagKey NETHERRACKS = cTag("netherracks"); - public static final TagKey OBSIDIANS = BlockItems.OBSIDIANS.block(); + public static final TagKey OBSIDIANS = cTag("obsidians"); /** * For common obsidian that has no special quirks or behaviours - ideal for recipe use. * Crying Obsidian, for example, is a light block and harder to obtain. So it gets its own tag instead of being under normal tag. */ - public static final TagKey OBSIDIANS_NORMAL = BlockItems.OBSIDIANS_NORMAL.block(); - public static final TagKey OBSIDIANS_CRYING = BlockItems.OBSIDIANS_CRYING.block(); + public static final TagKey OBSIDIANS_NORMAL = cTag("obsidians/normal"); + public static final TagKey OBSIDIANS_CRYING = cTag("obsidians/crying"); /** * Blocks which are often replaced by deepslate ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_DEEPSLATE}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_DEEPSLATE = BlockItems.ORE_BEARING_GROUND_DEEPSLATE.block(); + public static final TagKey ORE_BEARING_GROUND_DEEPSLATE = cTag("ore_bearing_ground/deepslate"); /** * Blocks which are often replaced by netherrack ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_NETHERRACK}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_NETHERRACK = BlockItems.ORE_BEARING_GROUND_NETHERRACK.block(); + public static final TagKey ORE_BEARING_GROUND_NETHERRACK = cTag("ore_bearing_ground/netherrack"); /** * Blocks which are often replaced by stone ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_STONE}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_STONE = BlockItems.ORE_BEARING_GROUND_STONE.block(); + public static final TagKey ORE_BEARING_GROUND_STONE = cTag("ore_bearing_ground/stone"); /** * Ores which on average result in more than one resource worth of materials */ - public static final TagKey ORE_RATES_DENSE = BlockItems.ORE_RATES_DENSE.block(); + public static final TagKey ORE_RATES_DENSE = cTag("ore_rates/dense"); /** * Ores which on average result in one resource worth of materials */ - public static final TagKey ORE_RATES_SINGULAR = BlockItems.ORE_RATES_SINGULAR.block(); + public static final TagKey ORE_RATES_SINGULAR = cTag("ore_rates/singular"); /** * Ores which on average result in less than one resource worth of materials */ - public static final TagKey ORE_RATES_SPARSE = BlockItems.ORE_RATES_SPARSE.block(); - public static final TagKey ORES = BlockItems.ORES.block(); - public static final TagKey ORES_NETHERITE_SCRAP = BlockItems.ORES_NETHERITE_SCRAP.block(); - public static final TagKey ORES_QUARTZ = BlockItems.ORES_QUARTZ.block(); - public static final TagKey ORES_COAL = BlockItems.ORES_COAL.block(); - public static final TagKey ORES_COPPER = BlockItems.ORES_COPPER.block(); - public static final TagKey ORES_DIAMOND = BlockItems.ORES_DIAMOND.block(); - public static final TagKey ORES_EMERALD = BlockItems.ORES_EMERALD.block(); - public static final TagKey ORES_GOLD = BlockItems.ORES_GOLD.block(); - public static final TagKey ORES_IRON = BlockItems.ORES_IRON.block(); - public static final TagKey ORES_LAPIS = BlockItems.ORES_LAPIS.block(); - public static final TagKey ORES_REDSTONE = BlockItems.ORES_REDSTONE.block(); + public static final TagKey ORE_RATES_SPARSE = cTag("ore_rates/sparse"); + public static final TagKey ORES = cTag("ores"); + public static final TagKey ORES_NETHERITE_SCRAP = cTag("ores/netherite_scrap"); + public static final TagKey ORES_QUARTZ = cTag("ores/quartz"); + public static final TagKey ORES_COAL = cTag("ores/coal"); + public static final TagKey ORES_COPPER = cTag("ores/copper"); + public static final TagKey ORES_DIAMOND = cTag("ores/diamond"); + public static final TagKey ORES_EMERALD = cTag("ores/emerald"); + public static final TagKey ORES_GOLD = cTag("ores/gold"); + public static final TagKey ORES_IRON = cTag("ores/iron"); + public static final TagKey ORES_LAPIS = cTag("ores/lapis"); + public static final TagKey ORES_REDSTONE = cTag("ores/redstone"); /** * Ores in deepslate (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_DEEPSLATE}) which could logically use deepslate as recipe input or output */ - public static final TagKey ORES_IN_GROUND_DEEPSLATE = BlockItems.ORES_IN_GROUND_DEEPSLATE.block(); + public static final TagKey ORES_IN_GROUND_DEEPSLATE = cTag("ores_in_ground/deepslate"); /** * Ores in netherrack (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_NETHERRACK}) which could logically use netherrack as recipe input or output */ - public static final TagKey ORES_IN_GROUND_NETHERRACK = BlockItems.ORES_IN_GROUND_NETHERRACK.block(); + public static final TagKey ORES_IN_GROUND_NETHERRACK = cTag("ores_in_ground/netherrack"); /** * Ores in stone (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_STONE}) which could logically use stone as recipe input or output */ - public static final TagKey ORES_IN_GROUND_STONE = BlockItems.ORES_IN_GROUND_STONE.block(); - public static final TagKey PLAYER_WORKSTATIONS_CRAFTING_TABLES = BlockItems.PLAYER_WORKSTATIONS_CRAFTING_TABLES.block(); - public static final TagKey PLAYER_WORKSTATIONS_FURNACES = BlockItems.PLAYER_WORKSTATIONS_FURNACES.block(); - public static final TagKey PUMPKINS = BlockItems.PUMPKINS.block(); + public static final TagKey ORES_IN_GROUND_STONE = cTag("ores_in_ground/stone"); + public static final TagKey PLAYER_WORKSTATIONS_CRAFTING_TABLES = cTag("player_workstations/crafting_tables"); + public static final TagKey PLAYER_WORKSTATIONS_FURNACES = cTag("player_workstations/furnaces"); + public static final TagKey PUMPKINS = cTag("pumpkins"); /** For pumpkins that are not carved. */ - public static final TagKey PUMPKINS_NORMAL = BlockItems.PUMPKINS_NORMAL.block(); + public static final TagKey PUMPKINS_NORMAL = cTag("pumpkins/normal"); /** For pumpkins that are already carved but not a light source. */ - public static final TagKey PUMPKINS_CARVED = BlockItems.PUMPKINS_CARVED.block(); + public static final TagKey PUMPKINS_CARVED = cTag("pumpkins/carved"); /** For pumpkins that are already carved and a light source. */ - public static final TagKey PUMPKINS_JACK_O_LANTERNS = BlockItems.PUMPKINS_JACK_O_LANTERNS.block(); + public static final TagKey PUMPKINS_JACK_O_LANTERNS = cTag("pumpkins/jack_o_lanterns"); /** * Blocks should be included in this tag if their movement/relocation can cause serious issues such * as world corruption upon being moved or for balance reason where the block should not be able to be relocated. @@ -459,21 +232,21 @@ public class Tags { * {@link BlockBehaviour.BlockStateBase#getPistonPushReaction}. */ public static final TagKey RELOCATION_NOT_SUPPORTED = cTag("relocation_not_supported"); - public static final TagKey ROPES = BlockItems.ROPES.block(); + public static final TagKey ROPES = cTag("ropes"); - public static final TagKey SANDS = BlockItems.SANDS.block(); - public static final TagKey SANDS_COLORLESS = BlockItems.SANDS_COLORLESS.block(); - public static final TagKey SANDS_RED = BlockItems.SANDS_RED.block(); + public static final TagKey SANDS = cTag("sands"); + public static final TagKey SANDS_COLORLESS = cTag("sands/colorless"); + public static final TagKey SANDS_RED = cTag("sands/red"); - public static final TagKey SANDSTONE_BLOCKS = BlockItems.SANDSTONE_BLOCKS.block(); - public static final TagKey SANDSTONE_SLABS = BlockItems.SANDSTONE_SLABS.block(); - public static final TagKey SANDSTONE_STAIRS = BlockItems.SANDSTONE_STAIRS.block(); - public static final TagKey SANDSTONE_RED_BLOCKS = BlockItems.SANDSTONE_RED_BLOCKS.block(); - public static final TagKey SANDSTONE_RED_SLABS = BlockItems.SANDSTONE_RED_SLABS.block(); - public static final TagKey SANDSTONE_RED_STAIRS = BlockItems.SANDSTONE_RED_STAIRS.block(); - public static final TagKey SANDSTONE_UNCOLORED_BLOCKS = BlockItems.SANDSTONE_UNCOLORED_BLOCKS.block(); - public static final TagKey SANDSTONE_UNCOLORED_SLABS = BlockItems.SANDSTONE_UNCOLORED_SLABS.block(); - public static final TagKey SANDSTONE_UNCOLORED_STAIRS = BlockItems.SANDSTONE_UNCOLORED_STAIRS.block(); + public static final TagKey SANDSTONE_BLOCKS = cTag("sandstone/blocks"); + public static final TagKey SANDSTONE_SLABS = cTag("sandstone/slabs"); + public static final TagKey SANDSTONE_STAIRS = cTag("sandstone/stairs"); + public static final TagKey SANDSTONE_RED_BLOCKS = cTag("sandstone/red_blocks"); + public static final TagKey SANDSTONE_RED_SLABS = cTag("sandstone/red_slabs"); + public static final TagKey SANDSTONE_RED_STAIRS = cTag("sandstone/red_stairs"); + public static final TagKey SANDSTONE_UNCOLORED_BLOCKS = cTag("sandstone/uncolored_blocks"); + public static final TagKey SANDSTONE_UNCOLORED_SLABS = cTag("sandstone/uncolored_slabs"); + public static final TagKey SANDSTONE_UNCOLORED_STAIRS = cTag("sandstone/uncolored_stairs"); /** * Tag that holds all head based blocks such as Skeleton Skull or Player Head. (Named skulls to match minecraft:skulls item tag) */ @@ -481,7 +254,7 @@ public class Tags { /** * Natural stone-like blocks that can be used as a base ingredient in recipes that takes stone. */ - public static final TagKey STONES = BlockItems.STONES.block(); + public static final TagKey STONES = cTag("stones"); /** * A storage block is generally a block that has a recipe to craft a bulk of 1 kind of resource to a block * and has a mirror recipe to reverse the crafting with no loss in resources. @@ -489,26 +262,26 @@ public class Tags { * Honey Block is special in that the reversing recipe is not a perfect mirror of the crafting recipe * and so, it is considered a special case and not given a storage block tag. */ - public static final TagKey STORAGE_BLOCKS = BlockItems.STORAGE_BLOCKS.block(); - public static final TagKey STORAGE_BLOCKS_BONE_MEAL = BlockItems.STORAGE_BLOCKS_BONE_MEAL.block(); - public static final TagKey STORAGE_BLOCKS_COAL = BlockItems.STORAGE_BLOCKS_COAL.block(); - public static final TagKey STORAGE_BLOCKS_COPPER = BlockItems.STORAGE_BLOCKS_COPPER.block(); - public static final TagKey STORAGE_BLOCKS_DIAMOND = BlockItems.STORAGE_BLOCKS_DIAMOND.block(); - public static final TagKey STORAGE_BLOCKS_DRIED_KELP = BlockItems.STORAGE_BLOCKS_DRIED_KELP.block(); - public static final TagKey STORAGE_BLOCKS_EMERALD = BlockItems.STORAGE_BLOCKS_EMERALD.block(); - public static final TagKey STORAGE_BLOCKS_GOLD = BlockItems.STORAGE_BLOCKS_GOLD.block(); - public static final TagKey STORAGE_BLOCKS_IRON = BlockItems.STORAGE_BLOCKS_IRON.block(); - public static final TagKey STORAGE_BLOCKS_LAPIS = BlockItems.STORAGE_BLOCKS_LAPIS.block(); - public static final TagKey STORAGE_BLOCKS_NETHERITE = BlockItems.STORAGE_BLOCKS_NETHERITE.block(); - public static final TagKey STORAGE_BLOCKS_RAW_COPPER = BlockItems.STORAGE_BLOCKS_RAW_COPPER.block(); - public static final TagKey STORAGE_BLOCKS_RAW_GOLD = BlockItems.STORAGE_BLOCKS_RAW_GOLD.block(); - public static final TagKey STORAGE_BLOCKS_RAW_IRON = BlockItems.STORAGE_BLOCKS_RAW_IRON.block(); - public static final TagKey STORAGE_BLOCKS_REDSTONE = BlockItems.STORAGE_BLOCKS_REDSTONE.block(); - public static final TagKey STORAGE_BLOCKS_RESIN = BlockItems.STORAGE_BLOCKS_RESIN.block(); - public static final TagKey STORAGE_BLOCKS_SLIME = BlockItems.STORAGE_BLOCKS_SLIME.block(); - public static final TagKey STORAGE_BLOCKS_WHEAT = BlockItems.STORAGE_BLOCKS_WHEAT.block(); - public static final TagKey STRIPPED_LOGS = BlockItems.STRIPPED_LOGS.block(); - public static final TagKey STRIPPED_WOODS = BlockItems.STRIPPED_WOODS.block(); + public static final TagKey STORAGE_BLOCKS = cTag("storage_blocks"); + public static final TagKey STORAGE_BLOCKS_BONE_MEAL = cTag("storage_blocks/bone_meal"); + public static final TagKey STORAGE_BLOCKS_COAL = cTag("storage_blocks/coal"); + public static final TagKey STORAGE_BLOCKS_COPPER = cTag("storage_blocks/copper"); + public static final TagKey STORAGE_BLOCKS_DIAMOND = cTag("storage_blocks/diamond"); + public static final TagKey STORAGE_BLOCKS_DRIED_KELP = cTag("storage_blocks/dried_kelp"); + public static final TagKey STORAGE_BLOCKS_EMERALD = cTag("storage_blocks/emerald"); + public static final TagKey STORAGE_BLOCKS_GOLD = cTag("storage_blocks/gold"); + public static final TagKey STORAGE_BLOCKS_IRON = cTag("storage_blocks/iron"); + public static final TagKey STORAGE_BLOCKS_LAPIS = cTag("storage_blocks/lapis"); + public static final TagKey STORAGE_BLOCKS_NETHERITE = cTag("storage_blocks/netherite"); + public static final TagKey STORAGE_BLOCKS_RAW_COPPER = cTag("storage_blocks/raw_copper"); + public static final TagKey STORAGE_BLOCKS_RAW_GOLD = cTag("storage_blocks/raw_gold"); + public static final TagKey STORAGE_BLOCKS_RAW_IRON = cTag("storage_blocks/raw_iron"); + public static final TagKey STORAGE_BLOCKS_REDSTONE = cTag("storage_blocks/redstone"); + public static final TagKey STORAGE_BLOCKS_RESIN = cTag("storage_blocks/resin"); + public static final TagKey STORAGE_BLOCKS_SLIME = cTag("storage_blocks/slime"); + public static final TagKey STORAGE_BLOCKS_WHEAT = cTag("storage_blocks/wheat"); + public static final TagKey STRIPPED_LOGS = cTag("stripped_logs"); + public static final TagKey STRIPPED_WOODS = cTag("stripped_woods"); public static final TagKey VILLAGER_JOB_SITES = cTag("villager_job_sites"); //endregion @@ -565,23 +338,17 @@ public class Tags { */ public static final TagKey ENCHANTING_FUELS = forgeTag("enchanting_fuels"); - public static final TagKey STORAGE_BLOCKS_AMETHYST = BlockItems.STORAGE_BLOCKS_AMETHYST.item(); - public static final TagKey STORAGE_BLOCKS_QUARTZ = BlockItems.STORAGE_BLOCKS_QUARTZ.item(); + public static final TagKey STORAGE_BLOCKS_AMETHYST = forgeTag("storage_blocks/amethyst"); + public static final TagKey STORAGE_BLOCKS_QUARTZ = forgeTag("storage_blocks/quartz"); //endregion //region `c` tags for common conventions // Note: Other loaders have additional `c` tags that are exclusive to their loader. // Forge only adopts `c` tags that are common across all loaders. - public static final TagKey BARRELS = BlockItems.BARRELS.item(); - public static final TagKey BARRELS_WOODEN = BlockItems.BARRELS_WOODEN.item(); - /** - * Equivalent to the "minecraft:bars" item tag. - */ - public static final TagKey BARS = BlockItems.BARS.item(); - public static final TagKey BARS_COPPER = BlockItems.BARS_COPPER.item(); - public static final TagKey BARS_IRON = BlockItems.BARS_IRON.item(); + public static final TagKey BARRELS = cTag("barrels"); + public static final TagKey BARRELS_WOODEN = cTag("barrels/wooden"); public static final TagKey BONES = cTag("bones"); - public static final TagKey BOOKSHELVES = BlockItems.BOOKSHELVES.item(); + public static final TagKey BOOKSHELVES = cTag("bookshelves"); public static final TagKey BRICKS = cTag("bricks"); public static final TagKey BRICKS_NORMAL = cTag("bricks/normal"); public static final TagKey BRICKS_NETHER = cTag("bricks/nether"); @@ -603,22 +370,22 @@ public class Tags { /** * For blocks that are similar to amethyst where their budding block produces buds and cluster blocks */ - public static final TagKey BUDDING_BLOCKS = BlockItems.BUDDING_BLOCKS.item(); + public static final TagKey BUDDING_BLOCKS = cTag("budding_blocks"); /** * For blocks that are similar to amethyst where they have buddings forming from budding blocks */ - public static final TagKey BUDS = BlockItems.BUDS.item(); - public static final TagKey CHAINS = BlockItems.CHAINS.item(); - public static final TagKey CHESTS = BlockItems.CHESTS.item(); - public static final TagKey CHESTS_WOODEN = BlockItems.CHESTS_WOODEN.item(); - public static final TagKey CHESTS_ENDER = BlockItems.CHESTS_ENDER.item(); - public static final TagKey CHESTS_TRAPPED = BlockItems.CHESTS_TRAPPED.item(); - public static final TagKey COBBLESTONES = BlockItems.COBBLESTONES.item(); - public static final TagKey COBBLESTONES_NORMAL = BlockItems.COBBLESTONES_NORMAL.item(); - public static final TagKey COBBLESTONES_INFESTED = BlockItems.COBBLESTONES_INFESTED.item(); - public static final TagKey COBBLESTONES_MOSSY = BlockItems.COBBLESTONES_MOSSY.item(); - public static final TagKey COBBLESTONES_DEEPSLATE = BlockItems.COBBLESTONES_DEEPSLATE.item(); - public static final TagKey CONCRETES = BlockItems.CONCRETES.item(); + public static final TagKey BUDS = cTag("buds"); + public static final TagKey CHAINS = cTag("chains"); + public static final TagKey CHESTS = cTag("chests"); + public static final TagKey CHESTS_WOODEN = cTag("chests/wooden"); + public static final TagKey CHESTS_ENDER = cTag("chests/ender"); + public static final TagKey CHESTS_TRAPPED = cTag("chests/trapped"); + public static final TagKey COBBLESTONES = cTag("cobblestones"); + public static final TagKey COBBLESTONES_NORMAL = cTag("cobblestones/normal"); + public static final TagKey COBBLESTONES_INFESTED = cTag("cobblestones/infested"); + public static final TagKey COBBLESTONES_MOSSY = cTag("cobblestones/mossy"); + public static final TagKey COBBLESTONES_DEEPSLATE = cTag("cobblestones/deepslate"); + public static final TagKey CONCRETES = cTag("concretes"); /** * Block tag equivalent is {@link BlockTags#CONCRETE_POWDER} */ @@ -626,7 +393,7 @@ public class Tags { /** * For blocks that are similar to amethyst where they have clusters forming from budding blocks */ - public static final TagKey CLUSTERS = BlockItems.CLUSTERS.item(); + public static final TagKey CLUSTERS = cTag("clusters"); public static final TagKey CLUMPS = cTag("clumps"); public static final TagKey CLUMPS_RESIN = cTag("clumps/resin"); /** @@ -648,49 +415,15 @@ public class Tags { public static final TagKey DUSTS_REDSTONE = cTag("dusts/redstone"); public static final TagKey DUSTS_GLOWSTONE = cTag("dusts/glowstone"); - /** - * Drinks are defined as (1) consumable items that (2) use the - * {@linkplain ItemUseAnimation#DRINK drink item use animation}, (3) can be consumed regardless of the - * player's current hunger. - * - *

Drinks may provide nutrition and saturation, but are not required to do so. - * - *

More specific types of drinks, such as Water, Milk, or Juice should be placed in a sub-tag, such as - * {@code #c:drinks/water}, {@code #c:drinks/milk}, and {@code #c:drinks/juice}. - */ public static final TagKey DRINKS = cTag("drinks"); public static final TagKey DRINKS_HONEY = cTag("drinks/honey"); - /** - * Plant based fruit and vegetable juices belong in this tag, for example apple juice and carrot juice. - * - *

If tags for specific types of juices are desired, they may go in a sub-tag, using their regular name such as - * {@code #c:drinks/apple_juice}. - */ public static final TagKey DRINKS_JUICE = cTag("drinks/juice"); public static final TagKey DRINKS_MAGIC = cTag("drinks/magic"); public static final TagKey DRINKS_MILK = cTag("drinks/milk"); - /** - * For drinks that always grant the {@linkplain MobEffects#BAD_OMEN Bad Omen} effect. - */ public static final TagKey DRINKS_OMINOUS = cTag("drinks/ominous"); - /** - * For consumable drinks that contain only water. - */ public static final TagKey DRINKS_WATER = cTag("drinks/water"); - /** - * For consumable drinks that are generally watery (such as potions). - */ public static final TagKey DRINKS_WATERY = cTag("drinks/watery"); - /** - * For non-empty bottles that are {@linkplain #DRINKS drinkable}. - */ - public static final TagKey DRINK_CONTAINING_BOTTLE = cTag("drink_containing/bottle"); - /** - * For non-empty buckets that are {@linkplain #DRINKS drinkable}. - */ - public static final TagKey DRINK_CONTAINING_BUCKET = cTag("drink_containing/bucket"); - /** * Tag that holds all blocks and items that can be dyed a specific color. * (Does not include color blending items like leather armor @@ -733,15 +466,15 @@ public class Tags { public static final TagKey DYES_WHITE = DyeColor.WHITE.getTag(); public static final TagKey EGGS = cTag("eggs"); - public static final TagKey END_STONES = BlockItems.END_STONES.item(); + public static final TagKey END_STONES = cTag("end_stones"); public static final TagKey ENDER_PEARLS = cTag("ender_pearls"); public static final TagKey FEATHERS = cTag("feathers"); - public static final TagKey FENCE_GATES = BlockItems.FENCE_GATES.item(); - public static final TagKey FENCE_GATES_WOODEN = BlockItems.FENCE_GATES_WOODEN.item(); - public static final TagKey FENCES = BlockItems.FENCES.item(); - public static final TagKey FENCES_NETHER_BRICK = BlockItems.FENCES_NETHER_BRICK.item(); - public static final TagKey FENCES_WOODEN = BlockItems.FENCES_WOODEN.item(); + public static final TagKey FENCE_GATES = cTag("fence_gates"); + public static final TagKey FENCE_GATES_WOODEN = cTag("fence_gates/wooden"); + public static final TagKey FENCES = cTag("fences"); + public static final TagKey FENCES_NETHER_BRICK = cTag("fences/nether_brick"); + public static final TagKey FENCES_WOODEN = cTag("fences/wooden"); /** * For bonemeal-like items that can grow plants. */ @@ -751,17 +484,17 @@ public class Tags { * Equivalent to the {@code minecraft:small_flowers} item tag. * Aliased with {@link ItemTags#SMALL_FLOWERS}. */ - public static final TagKey FLOWERS_SMALL = BlockItems.FLOWERS_SMALL.item(); + public static final TagKey FLOWERS_SMALL = cTag("flowers/small"); /** * Contains living ground-based flowers that are 2 block tall such as Rose Bush or Peony. * Equivalent to the {@code minecraft:tall_flowers} item tag in past Minecraft versions. */ - public static final TagKey FLOWERS_TALL = BlockItems.FLOWERS_TALL.item(); + public static final TagKey FLOWERS_TALL = cTag("flowers/tall"); /** * Contains any living plant block that contains flowers or is a flower itself. * Equivalent to the {@code minecraft:flowers} item tag in past Minecraft versions. */ - public static final TagKey FLOWERS = BlockItems.FLOWERS.item(); + public static final TagKey FLOWERS = cTag("flowers"); public static final TagKey FOODS = cTag("foods"); /** * Apples and other foods that are considered fruits in the culinary field belong in this tag. @@ -779,20 +512,6 @@ public class Tags { public static final TagKey FOODS_BERRY = cTag("foods/berry"); public static final TagKey FOODS_BREAD = cTag("foods/bread"); public static final TagKey FOODS_COOKIE = cTag("foods/cookie"); - /** - * For all doughs regardless of type, specific types of dough should fall under their respective sub-tag.
- * For example:
- * - Wheat dough (which generally results in bread) would go in "#c:foods/dough/wheat"
- * - Rye dough (which has rye as it's main ingredient) would go in "#c:foods/dough/rye"
- * - Sub-tags should also be added to this tag, for example: "#c:foods/dough/wheat" should be added to "#c:foods/dough"
- *
- * There are some important assumptions that should be kept in mind.
- * - It is assumed that "1 dough = result", which in the case of wheat dough would be "1 dough = 1 bread"
- * - It is assumed that this dough can be baked into another item
- * - It is *not* assumed that all doughs result in bread, there can be doughs in this tag that result in things like pizza, etc. - * This means that this tag should *not* be used for furnace recipes, mods should add their own dough to result recipes for their respective items. - */ - public static final TagKey FOODS_DOUGH = cTag("foods/dough"); public static final TagKey FOODS_RAW_MEAT = cTag("foods/raw_meat"); public static final TagKey FOODS_COOKED_MEAT = cTag("foods/cooked_meat"); public static final TagKey FOODS_RAW_FISH = cTag("foods/raw_fish"); @@ -835,79 +554,76 @@ public class Tags { public static final TagKey GEMS_PRISMARINE = cTag("gems/prismarine"); public static final TagKey GEMS_QUARTZ = cTag("gems/quartz"); - public static final TagKey GLASS_BLOCKS = BlockItems.GLASS_BLOCKS.item(); - public static final TagKey GLASS_BLOCKS_COLORLESS = BlockItems.GLASS_BLOCKS_COLORLESS.item(); + public static final TagKey GLASS_BLOCKS = cTag("glass_blocks"); + public static final TagKey GLASS_BLOCKS_COLORLESS = cTag("glass_blocks/colorless"); /** * Glass which is made from cheap resources like sand and only minor additional ingredients like dyes */ - public static final TagKey GLASS_BLOCKS_CHEAP = BlockItems.GLASS_BLOCKS_CHEAP.item(); - public static final TagKey GLASS_BLOCKS_TINTED = BlockItems.GLASS_BLOCKS_TINTED.item(); + public static final TagKey GLASS_BLOCKS_CHEAP = cTag("glass_blocks/cheap"); + public static final TagKey GLASS_BLOCKS_TINTED = cTag("glass_blocks/tinted"); - public static final TagKey GLASS_PANES = BlockItems.GLASS_PANES.item(); - public static final TagKey GLASS_PANES_COLORLESS = BlockItems.GLASS_PANES_COLORLESS.item(); - public static final TagKey GLAZED_TERRACOTTAS = BlockItems.GLAZED_TERRACOTTAS.item(); + public static final TagKey GLASS_PANES = cTag("glass_panes"); + public static final TagKey GLASS_PANES_COLORLESS = cTag("glass_panes/colorless"); + public static final TagKey GLAZED_TERRACOTTAS = cTag("glazed_terracottas"); - public static final TagKey GRAVELS = BlockItems.GRAVELS.item(); + public static final TagKey GRAVELS = cTag("gravels"); public static final TagKey GUNPOWDERS = cTag("gunpowders"); /** * Tag that holds all items that recipe viewers should not show to users. */ public static final TagKey HIDDEN_FROM_RECIPE_VIEWERS = cTag("hidden_from_recipe_viewers"); - public static final TagKey OBSIDIANS = BlockItems.OBSIDIANS.item(); + public static final TagKey OBSIDIANS = cTag("obsidians"); /** * For common obsidian that has no special quirks or behaviours - ideal for recipe use. * Crying Obsidian, for example, is a light block and harder to obtain. So it gets its own tag instead of being under normal tag. */ - public static final TagKey OBSIDIANS_NORMAL = BlockItems.OBSIDIANS_NORMAL.item(); - public static final TagKey OBSIDIANS_CRYING = BlockItems.OBSIDIANS_CRYING.item(); + public static final TagKey OBSIDIANS_NORMAL = cTag("obsidians/normal"); + public static final TagKey OBSIDIANS_CRYING = cTag("obsidians/crying"); /** * Blocks which are often replaced by deepslate ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_DEEPSLATE}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_DEEPSLATE = BlockItems.ORE_BEARING_GROUND_DEEPSLATE.item(); + public static final TagKey ORE_BEARING_GROUND_DEEPSLATE = cTag("ore_bearing_ground/deepslate"); /** * Blocks which are often replaced by netherrack ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_NETHERRACK}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_NETHERRACK = BlockItems.ORE_BEARING_GROUND_NETHERRACK.item(); + public static final TagKey ORE_BEARING_GROUND_NETHERRACK = cTag("ore_bearing_ground/netherrack"); /** * Blocks which are often replaced by stone ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_STONE}, during world generation */ - public static final TagKey ORE_BEARING_GROUND_STONE = BlockItems.ORE_BEARING_GROUND_STONE.item(); + public static final TagKey ORE_BEARING_GROUND_STONE = cTag("ore_bearing_ground/stone"); /** * Ores which on average result in more than one resource worth of materials */ - public static final TagKey ORE_RATES_DENSE = BlockItems.ORE_RATES_DENSE.item(); + public static final TagKey ORE_RATES_DENSE = cTag("ore_rates/dense"); /** * Ores which on average result in one resource worth of materials */ - public static final TagKey ORE_RATES_SINGULAR = BlockItems.ORE_RATES_SINGULAR.item(); + public static final TagKey ORE_RATES_SINGULAR = cTag("ore_rates/singular"); /** * Ores which on average result in less than one resource worth of materials */ - public static final TagKey ORE_RATES_SPARSE = BlockItems.ORE_RATES_SPARSE.item(); - public static final TagKey ORES = BlockItems.ORES.item(); - public static final TagKey ORES_COAL = BlockItems.ORES_COAL.item(); - public static final TagKey ORES_COPPER = BlockItems.ORES_COPPER.item(); - public static final TagKey ORES_DIAMOND = BlockItems.ORES_DIAMOND.item(); - public static final TagKey ORES_EMERALD = BlockItems.ORES_EMERALD.item(); - public static final TagKey ORES_GOLD = BlockItems.ORES_GOLD.item(); - public static final TagKey ORES_IRON = BlockItems.ORES_IRON.item(); - public static final TagKey ORES_LAPIS = BlockItems.ORES_LAPIS.item(); - public static final TagKey ORES_NETHERITE_SCRAP = BlockItems.ORES_NETHERITE_SCRAP.item(); - public static final TagKey ORES_QUARTZ = BlockItems.ORES_QUARTZ.item(); - public static final TagKey ORES_REDSTONE = BlockItems.ORES_REDSTONE.item(); + public static final TagKey ORE_RATES_SPARSE = cTag("ore_rates/sparse"); + public static final TagKey ORES_COAL = cTag("ores/coal"); + public static final TagKey ORES_COPPER = cTag("ores/copper"); + public static final TagKey ORES_DIAMOND = cTag("ores/diamond"); + public static final TagKey ORES_EMERALD = cTag("ores/emerald"); + public static final TagKey ORES_GOLD = cTag("ores/gold"); + public static final TagKey ORES_IRON = cTag("ores/iron"); + public static final TagKey ORES_LAPIS = cTag("ores/lapis"); + public static final TagKey ORES_REDSTONE = cTag("ores/redstone"); /** * Ores in deepslate (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_DEEPSLATE}) which could logically use deepslate as recipe input or output */ - public static final TagKey ORES_IN_GROUND_DEEPSLATE = BlockItems.ORES_IN_GROUND_DEEPSLATE.item(); + public static final TagKey ORES_IN_GROUND_DEEPSLATE = cTag("ores_in_ground/deepslate"); /** * Ores in netherrack (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_NETHERRACK}) which could logically use netherrack as recipe input or output */ - public static final TagKey ORES_IN_GROUND_NETHERRACK = BlockItems.ORES_IN_GROUND_NETHERRACK.item(); + public static final TagKey ORES_IN_GROUND_NETHERRACK = cTag("ores_in_ground/netherrack"); /** * Ores in stone (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_STONE}) which could logically use stone as recipe input or output */ - public static final TagKey ORES_IN_GROUND_STONE = BlockItems.ORES_IN_GROUND_STONE.item(); + public static final TagKey ORES_IN_GROUND_STONE = cTag("ores_in_ground/stone"); public static final TagKey INGOTS = cTag("ingots"); public static final TagKey INGOTS_COPPER = cTag("ingots/copper"); public static final TagKey INGOTS_GOLD = cTag("ingots/gold"); @@ -920,27 +636,30 @@ public class Tags { * A pancake with a JUKEBOX_PLAYABLE component attached to play in Jukeboxes as an Easter Egg is not a music disc and would not go in this tag. */ public static final TagKey MUSIC_DISCS = cTag("music_discs"); - public static final TagKey NATURAL_LOGS = BlockItems.NATURAL_LOGS.item(); - public static final TagKey NATURAL_LOGS_NETHER = BlockItems.NATURAL_LOGS_NETHER.item(); - public static final TagKey NATURAL_LOGS_OVERWORLD = BlockItems.NATURAL_LOGS_OVERWORLD.item(); - public static final TagKey NATURAL_WOODS = BlockItems.NATURAL_WOODS.item(); + public static final TagKey NATURAL_LOGS = cTag("natural_logs"); + public static final TagKey NATURAL_LOGS_NETHER = cTag("natural_logs/nether"); + public static final TagKey NATURAL_LOGS_OVERWORLD = cTag("natural_logs/overworld"); + public static final TagKey NATURAL_WOODS = cTag("natural_woods"); public static final TagKey NETHER_STARS = cTag("nether_stars"); - public static final TagKey NETHERRACKS = BlockItems.NETHERRACKS.item(); + public static final TagKey NETHERRACKS = cTag("netherracks"); public static final TagKey NUGGETS = cTag("nuggets"); public static final TagKey NUGGETS_COPPER = cTag("nuggets/copper"); public static final TagKey NUGGETS_GOLD = cTag("nuggets/gold"); public static final TagKey NUGGETS_IRON = cTag("nuggets/iron"); + public static final TagKey ORES = cTag("ores"); + public static final TagKey ORES_NETHERITE_SCRAP = cTag("ores/netherite_scrap"); + public static final TagKey ORES_QUARTZ = cTag("ores/quartz"); public static final TagKey POTIONS = cTag("potions"); public static final TagKey POTIONS_BOTTLE = cTag("potions/bottle"); - public static final TagKey PLAYER_WORKSTATIONS_CRAFTING_TABLES = BlockItems.PLAYER_WORKSTATIONS_CRAFTING_TABLES.item(); - public static final TagKey PLAYER_WORKSTATIONS_FURNACES = BlockItems.PLAYER_WORKSTATIONS_FURNACES.item(); - public static final TagKey PUMPKINS = BlockItems.PUMPKINS.item(); + public static final TagKey PLAYER_WORKSTATIONS_CRAFTING_TABLES = cTag("player_workstations/crafting_tables"); + public static final TagKey PLAYER_WORKSTATIONS_FURNACES = cTag("player_workstations/furnaces"); + public static final TagKey PUMPKINS = cTag("pumpkins"); /** For pumpkins that are not carved. */ - public static final TagKey PUMPKINS_NORMAL = BlockItems.PUMPKINS_NORMAL.item(); + public static final TagKey PUMPKINS_NORMAL = cTag("pumpkins/normal"); /** For pumpkins that are already carved but not a light source. */ - public static final TagKey PUMPKINS_CARVED = BlockItems.PUMPKINS_CARVED.item(); + public static final TagKey PUMPKINS_CARVED = cTag("pumpkins/carved"); /** For pumpkins that are already carved and a light source. */ - public static final TagKey PUMPKINS_JACK_O_LANTERNS = BlockItems.PUMPKINS_JACK_O_LANTERNS.item(); + public static final TagKey PUMPKINS_JACK_O_LANTERNS = cTag("pumpkins/jack_o_lanterns"); public static final TagKey RAW_MATERIALS = cTag("raw_materials"); public static final TagKey RAW_MATERIALS_COPPER = cTag("raw_materials/copper"); public static final TagKey RAW_MATERIALS_GOLD = cTag("raw_materials/gold"); @@ -956,11 +675,11 @@ public class Tags { * One example is a mod adds stick variants such as Spruce Sticks but would like stick recipes to be able to use it. */ public static final TagKey RODS_WOODEN = cTag("rods/wooden"); - public static final TagKey ROPES = BlockItems.ROPES.item(); + public static final TagKey ROPES = cTag("ropes"); - public static final TagKey SANDS = BlockItems.SANDS.item(); - public static final TagKey SANDS_COLORLESS = BlockItems.SANDS_COLORLESS.item(); - public static final TagKey SANDS_RED = BlockItems.SANDS_RED.item(); + public static final TagKey SANDS = cTag("sands"); + public static final TagKey SANDS_COLORLESS = cTag("sands/colorless"); + public static final TagKey SANDS_RED = cTag("sands/red"); public static final TagKey SEEDS = cTag("seeds"); public static final TagKey SEEDS_BEETROOT = cTag("seeds/beetroot"); @@ -970,15 +689,15 @@ public class Tags { public static final TagKey SEEDS_TORCHFLOWER = cTag("seeds/torchflower"); public static final TagKey SEEDS_WHEAT = cTag("seeds/wheat"); - public static final TagKey SANDSTONE_BLOCKS = BlockItems.SANDSTONE_BLOCKS.item(); - public static final TagKey SANDSTONE_SLABS = BlockItems.SANDSTONE_SLABS.item(); - public static final TagKey SANDSTONE_STAIRS = BlockItems.SANDSTONE_STAIRS.item(); - public static final TagKey SANDSTONE_RED_BLOCKS = BlockItems.SANDSTONE_RED_BLOCKS.item(); - public static final TagKey SANDSTONE_RED_SLABS = BlockItems.SANDSTONE_RED_SLABS.item(); - public static final TagKey SANDSTONE_RED_STAIRS = BlockItems.SANDSTONE_RED_STAIRS.item(); - public static final TagKey SANDSTONE_UNCOLORED_BLOCKS = BlockItems.SANDSTONE_UNCOLORED_BLOCKS.item(); - public static final TagKey SANDSTONE_UNCOLORED_SLABS = BlockItems.SANDSTONE_UNCOLORED_SLABS.item(); - public static final TagKey SANDSTONE_UNCOLORED_STAIRS = BlockItems.SANDSTONE_UNCOLORED_STAIRS.item(); + public static final TagKey SANDSTONE_BLOCKS = cTag("sandstone/blocks"); + public static final TagKey SANDSTONE_SLABS = cTag("sandstone/slabs"); + public static final TagKey SANDSTONE_STAIRS = cTag("sandstone/stairs"); + public static final TagKey SANDSTONE_RED_BLOCKS = cTag("sandstone/red_blocks"); + public static final TagKey SANDSTONE_RED_SLABS = cTag("sandstone/red_slabs"); + public static final TagKey SANDSTONE_RED_STAIRS = cTag("sandstone/red_stairs"); + public static final TagKey SANDSTONE_UNCOLORED_BLOCKS = cTag("sandstone/uncolored_blocks"); + public static final TagKey SANDSTONE_UNCOLORED_SLABS = cTag("sandstone/uncolored_slabs"); + public static final TagKey SANDSTONE_UNCOLORED_STAIRS = cTag("sandstone/uncolored_stairs"); /** * Block tag equivalent is {@link BlockTags#SHULKER_BOXES} @@ -988,7 +707,7 @@ public class Tags { /** * Natural stone-like blocks that can be used as a base ingredient in recipes that takes stone. */ - public static final TagKey STONES = BlockItems.STONES.item(); + public static final TagKey STONES = cTag("stones"); /** * A storage block is generally a block that has a recipe to craft a bulk of 1 kind of resource to a block * and has a mirror recipe to reverse the crafting with no loss in resources. @@ -996,27 +715,27 @@ public class Tags { * Honey Block is special in that the reversing recipe is not a perfect mirror of the crafting recipe * and so, it is considered a special case and not given a storage block tag. */ - public static final TagKey STORAGE_BLOCKS = BlockItems.STORAGE_BLOCKS.item(); - public static final TagKey STORAGE_BLOCKS_BONE_MEAL = BlockItems.STORAGE_BLOCKS_BONE_MEAL.item(); - public static final TagKey STORAGE_BLOCKS_COAL = BlockItems.STORAGE_BLOCKS_COAL.item(); - public static final TagKey STORAGE_BLOCKS_COPPER = BlockItems.STORAGE_BLOCKS_COPPER.item(); - public static final TagKey STORAGE_BLOCKS_DIAMOND = BlockItems.STORAGE_BLOCKS_DIAMOND.item(); - public static final TagKey STORAGE_BLOCKS_DRIED_KELP = BlockItems.STORAGE_BLOCKS_DRIED_KELP.item(); - public static final TagKey STORAGE_BLOCKS_EMERALD = BlockItems.STORAGE_BLOCKS_EMERALD.item(); - public static final TagKey STORAGE_BLOCKS_GOLD = BlockItems.STORAGE_BLOCKS_GOLD.item(); - public static final TagKey STORAGE_BLOCKS_IRON = BlockItems.STORAGE_BLOCKS_IRON.item(); - public static final TagKey STORAGE_BLOCKS_LAPIS = BlockItems.STORAGE_BLOCKS_LAPIS.item(); - public static final TagKey STORAGE_BLOCKS_NETHERITE = BlockItems.STORAGE_BLOCKS_NETHERITE.item(); - public static final TagKey STORAGE_BLOCKS_RAW_COPPER = BlockItems.STORAGE_BLOCKS_RAW_COPPER.item(); - public static final TagKey STORAGE_BLOCKS_RAW_GOLD = BlockItems.STORAGE_BLOCKS_RAW_GOLD.item(); - public static final TagKey STORAGE_BLOCKS_RAW_IRON = BlockItems.STORAGE_BLOCKS_RAW_IRON.item(); - public static final TagKey STORAGE_BLOCKS_REDSTONE = BlockItems.STORAGE_BLOCKS_REDSTONE.item(); - public static final TagKey STORAGE_BLOCKS_RESIN = BlockItems.STORAGE_BLOCKS_RESIN.item(); - public static final TagKey STORAGE_BLOCKS_SLIME = BlockItems.STORAGE_BLOCKS_SLIME.item(); - public static final TagKey STORAGE_BLOCKS_WHEAT = BlockItems.STORAGE_BLOCKS_WHEAT.item(); + public static final TagKey STORAGE_BLOCKS = cTag("storage_blocks"); + public static final TagKey STORAGE_BLOCKS_BONE_MEAL = cTag("storage_blocks/bone_meal"); + public static final TagKey STORAGE_BLOCKS_COAL = cTag("storage_blocks/coal"); + public static final TagKey STORAGE_BLOCKS_COPPER = cTag("storage_blocks/copper"); + public static final TagKey STORAGE_BLOCKS_DIAMOND = cTag("storage_blocks/diamond"); + public static final TagKey STORAGE_BLOCKS_DRIED_KELP = cTag("storage_blocks/dried_kelp"); + public static final TagKey STORAGE_BLOCKS_EMERALD = cTag("storage_blocks/emerald"); + public static final TagKey STORAGE_BLOCKS_GOLD = cTag("storage_blocks/gold"); + public static final TagKey STORAGE_BLOCKS_IRON = cTag("storage_blocks/iron"); + public static final TagKey STORAGE_BLOCKS_LAPIS = cTag("storage_blocks/lapis"); + public static final TagKey STORAGE_BLOCKS_NETHERITE = cTag("storage_blocks/netherite"); + public static final TagKey STORAGE_BLOCKS_RAW_COPPER = cTag("storage_blocks/raw_copper"); + public static final TagKey STORAGE_BLOCKS_RAW_GOLD = cTag("storage_blocks/raw_gold"); + public static final TagKey STORAGE_BLOCKS_RAW_IRON = cTag("storage_blocks/raw_iron"); + public static final TagKey STORAGE_BLOCKS_REDSTONE = cTag("storage_blocks/redstone"); + public static final TagKey STORAGE_BLOCKS_RESIN = cTag("storage_blocks/resin"); + public static final TagKey STORAGE_BLOCKS_SLIME = cTag("storage_blocks/slime"); + public static final TagKey STORAGE_BLOCKS_WHEAT = cTag("storage_blocks/wheat"); public static final TagKey STRINGS = cTag("strings"); - public static final TagKey STRIPPED_LOGS = BlockItems.STRIPPED_LOGS.item(); - public static final TagKey STRIPPED_WOODS = BlockItems.STRIPPED_WOODS.item(); + public static final TagKey STRIPPED_LOGS = cTag("stripped_logs"); + public static final TagKey STRIPPED_WOODS = cTag("stripped_woods"); public static final TagKey VILLAGER_JOB_SITES = cTag("villager_job_sites"); // Tools and Armors @@ -1061,16 +780,15 @@ public class Tags { */ public static final TagKey TOOLS_FISHING_ROD = cTag("tools/fishing_rod"); /** - * A tag containing all existing throwable stick-like weapons like tridents. - * Other tools such as throwing knives or boomerangs should not be put into - * this tag and should be put into their own tool tags. + * A tag containing all existing spears. Other tools such as throwing knives or boomerangs + * should not be put into this tag and should be put into their own tool tags. * Do not use this tag for determining a tool's behavior. * Please use {@link ToolActions} instead for what action a tool can do. * * @see ToolAction * @see ToolActions */ - public static final TagKey TOOLS_TRIDENT = cTag("tools/trident"); + public static final TagKey TOOLS_SPEAR = cTag("tools/spear"); /** * A tag containing all existing shears. Do not use this tag for determining a tool's behavior. * Please use {@link ToolActions} instead for what action a tool can do. diff --git a/src/main/java/net/minecraftforge/common/UsernameCache.java b/src/main/java/net/minecraftforge/common/UsernameCache.java index d328ed15ad..41a4219976 100644 --- a/src/main/java/net/minecraftforge/common/UsernameCache.java +++ b/src/main/java/net/minecraftforge/common/UsernameCache.java @@ -16,6 +16,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import com.google.common.base.Charsets; import net.minecraftforge.fml.loading.FMLLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -38,6 +39,7 @@ import org.jetbrains.annotations.Nullable; * the caches underlying map. */ public final class UsernameCache { + private static Map map = new HashMap<>(); private static final Path saveFile = FMLLoader.getGamePath().resolve("usernamecache.json"); @@ -56,7 +58,8 @@ public final class UsernameCache { * @param username * the player's username */ - protected static void setUsername(UUID uuid, String username) { + protected static void setUsername(UUID uuid, String username) + { Objects.requireNonNull(uuid); Objects.requireNonNull(username); @@ -73,10 +76,12 @@ public final class UsernameCache { * the player's {@link java.util.UUID UUID} * @return if the cache contained the user */ - protected static boolean removeUsername(UUID uuid) { + protected static boolean removeUsername(UUID uuid) + { Objects.requireNonNull(uuid); - if (map.remove(uuid) != null) { + if (map.remove(uuid) != null) + { save(); return true; } @@ -95,7 +100,8 @@ public final class UsernameCache { * cache doesn't have a record of the last username */ @Nullable - public static String getLastKnownUsername(UUID uuid) { + public static String getLastKnownUsername(UUID uuid) + { Objects.requireNonNull(uuid); return map.get(uuid); } @@ -107,7 +113,8 @@ public final class UsernameCache { * the player's {@link java.util.UUID UUID} * @return if the cache contains a username for the given player */ - public static boolean containsUUID(UUID uuid) { + public static boolean containsUUID(UUID uuid) + { Objects.requireNonNull(uuid); return map.containsKey(uuid); } @@ -117,37 +124,51 @@ public final class UsernameCache { * * @return the map */ - public static Map getMap() { + public static Map getMap() + { return ImmutableMap.copyOf(map); } /** * Save the cache to file */ - protected static void save() { + protected static void save() + { new SaveThread(gson.toJson(map)).start(); } /** * Load the cache from file */ - protected static void load() { + protected static void load() + { if (!Files.exists(saveFile)) return; - try (final BufferedReader reader = Files.newBufferedReader(saveFile, StandardCharsets.UTF_8)) { + try (final BufferedReader reader = Files.newBufferedReader(saveFile, Charsets.UTF_8)) + { + @SuppressWarnings("serial") Type type = new TypeToken>(){}.getType(); map = gson.fromJson(reader, type); - } catch (JsonSyntaxException | IOException e) { + } + catch (JsonSyntaxException | IOException e) + { LOGGER.error(USRCACHE,"Could not parse username cache file as valid json, deleting file {}", saveFile, e); - try { + try + { Files.delete(saveFile); - } catch (IOException e1) { + } + catch (IOException e1) + { LOGGER.error(USRCACHE,"Could not delete file {}", saveFile.toString()); } - } finally { + } + finally + { // Can sometimes occur when the json file is malformed if (map == null) + { map = new HashMap<>(); + } } } @@ -160,18 +181,24 @@ public final class UsernameCache { /** The data that will be saved to disk */ private final String data; - public SaveThread(String data) { + public SaveThread(String data) + { this.data = data; } @Override - public void run() { - try { + public void run() + { + try + { // Make sure we don't save when another thread is still saving - synchronized (saveFile) { + synchronized (saveFile) + { Files.write(saveFile, data.getBytes(StandardCharsets.UTF_8)); } - } catch (IOException e) { + } + catch (IOException e) + { LOGGER.error(USRCACHE, "Failed to save username cache to file!", e); } } diff --git a/src/main/java/net/minecraftforge/common/capabilities/CapabilityManager.java b/src/main/java/net/minecraftforge/common/capabilities/CapabilityManager.java index 89fbe670d0..ac45196c25 100644 --- a/src/main/java/net/minecraftforge/common/capabilities/CapabilityManager.java +++ b/src/main/java/net/minecraftforge/common/capabilities/CapabilityManager.java @@ -51,14 +51,14 @@ public final class CapabilityManager { Capability cap; synchronized (providers) { - final var parent = (Capability)providers.computeIfAbsent(new Key(type, null), _ -> new Capability<>(type.intern())); + final var parent = (Capability)providers.computeIfAbsent(new Key(type, null), k -> new Capability<>(type.intern())); if (name == null) { cap = parent; } else { // A Named child - cap = (Capability)providers.computeIfAbsent(new Key(type, name), _ -> { + cap = (Capability)providers.computeIfAbsent(new Key(type, name), k -> { var ret = new Capability<>((parent.getName() + '#' + name.toString()).intern()); - parent.addListener(_ -> ret.onRegister()); + parent.addListener(p -> ret.onRegister()); return ret; }); } diff --git a/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java b/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java index 20cedb7996..57cc4862e5 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java +++ b/src/main/java/net/minecraftforge/common/crafting/ConditionalRecipe.java @@ -286,8 +286,8 @@ public class ConditionalRecipe { public static final RecipeSerializer> SERIALZIER = new RecipeSerializer>(CODEC, StreamCodec.of( - (_, _) -> new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network"), - _ -> { throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network"); } + (o, v) -> new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network"), + i -> { throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network"); } ) ); 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 a32cc96c85..b3829f7d7b 100644 --- a/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java +++ b/src/main/java/net/minecraftforge/common/crafting/conditions/ConditionCodec.java @@ -45,7 +45,7 @@ public class ConditionCodec { public DataResult> decode(DynamicOps ops, T input) { var ret = normal.decode(ops, input); if (!ret.result().isPresent() || !ret.result().get().getFirst().isPresent()) - return ret.map(p -> p.mapFirst(_ -> _default.get())); + return ret.map(p -> p.mapFirst(e -> _default.get())); return ret.map(p -> p.mapFirst(Optional::get)); } } 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 6ce9566780..91cd54af38 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/CompoundIngredient.java @@ -93,12 +93,12 @@ public class CompoundIngredient extends AbstractIngredient { @Override public void write(RegistryFriendlyByteBuf buffer, CompoundIngredient value) { - buffer.writeCollection(value.children, (_, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); + buffer.writeCollection(value.children, (buf, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); } @Override public CompoundIngredient read(RegistryFriendlyByteBuf buffer) { - var children = buffer.readCollection(ArrayList::new, _ -> Ingredient.CONTENTS_STREAM_CODEC.decode(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/IntersectionIngredient.java b/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java index 98fec62695..1d40e180ae 100644 --- a/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java +++ b/src/main/java/net/minecraftforge/common/crafting/ingredients/IntersectionIngredient.java @@ -108,13 +108,13 @@ public class IntersectionIngredient extends AbstractIngredient { @Override public IntersectionIngredient read(RegistryFriendlyByteBuf buffer) { - var children = buffer.readCollection(ArrayList::new, _ -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer)); + var children = buffer.readCollection(ArrayList::new, buf -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer)); return new IntersectionIngredient(children); } @Override public void write(RegistryFriendlyByteBuf buffer, IntersectionIngredient value) { - buffer.writeCollection(value.children, (_, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); + buffer.writeCollection(value.children, (b, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child)); } }; } diff --git a/src/main/java/net/minecraftforge/common/data/BlockTagsProvider.java b/src/main/java/net/minecraftforge/common/data/BlockTagsProvider.java new file mode 100644 index 0000000000..e5800223ec --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/BlockTagsProvider.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common.data; + +import java.util.concurrent.CompletableFuture; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.PackOutput; +import net.minecraft.data.tags.IntrinsicHolderTagsProvider; +import net.minecraft.world.level.block.Block; +import org.jetbrains.annotations.Nullable; + +public abstract class BlockTagsProvider extends IntrinsicHolderTagsProvider { + @SuppressWarnings("deprecation") + public BlockTagsProvider(PackOutput output, CompletableFuture lookupProvider, String modId, @Nullable ExistingFileHelper existingFileHelper) { + super(output, Registries.BLOCK, lookupProvider, block -> block.builtInRegistryHolder().key(), modId, existingFileHelper); + } +} diff --git a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java index c82cf63278..9960dc169b 100644 --- a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java +++ b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java @@ -106,7 +106,7 @@ public class ExistingFileHelper { candidateServerResources.add(ServerPacksSource.createVanillaPackSource()); var symlinks = new ArrayList(); - var folder = new FolderRepositorySource.FolderPackDetector(new DirectoryValidator(_ -> true)); + var folder = new FolderRepositorySource.FolderPackDetector(new DirectoryValidator(p -> true)); for (Path existing : existingPacks) { try { diff --git a/src/main/java/net/minecraftforge/common/data/ForgeBiomeTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeBiomeTagsProvider.java index 868099b1ea..2414204102 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeBiomeTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeBiomeTagsProvider.java @@ -8,8 +8,13 @@ package net.minecraftforge.common.data; import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; import net.minecraft.data.tags.BiomeTagsProvider; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.Identifier; import net.minecraft.tags.BiomeTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; +import net.minecraftforge.common.Tags; import org.jetbrains.annotations.ApiStatus; import java.util.concurrent.CompletableFuture; @@ -22,7 +27,6 @@ public final class ForgeBiomeTagsProvider extends BiomeTagsProvider { super(output, lookupProvider, "forge", existingFileHelper); } - @SuppressWarnings("unchecked") @Override protected void addTags(HolderLookup.Provider lookupProvider) { tag(NO_DEFAULT_MONSTERS).add(Biomes.MUSHROOM_FIELDS).add(Biomes.DEEP_DARK); @@ -283,6 +287,17 @@ public final class ForgeBiomeTagsProvider extends BiomeTagsProvider { tag(IS_OUTER_END_ISLAND).add(Biomes.END_HIGHLANDS).add(Biomes.END_MIDLANDS).add(Biomes.END_BARRENS); } + @SafeVarargs + private void tag(ResourceKey biome, TagKey... tags) { + for (TagKey key : tags) { + tag(key).add(biome); + } + } + + private static TagKey forgeTagKey(String path) { + return BiomeTags.create(Identifier.fromNamespaceAndPath("forge", path)); + } + @Override public String getName() { return "Forge Biome Tags"; diff --git a/src/main/java/net/minecraftforge/common/data/ForgeBlockItemTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeBlockItemTagsProvider.java index ccf86f1f03..d64ccb56d7 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeBlockItemTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeBlockItemTagsProvider.java @@ -5,476 +5,644 @@ package net.minecraftforge.common.data; -import java.util.function.Function; +import java.util.Locale; +import java.util.function.Consumer; + import net.minecraft.data.tags.BlockItemTagsProvider; -import net.minecraft.references.BlockItemIds; -import net.minecraft.tags.BlockItemTagId; -import net.minecraft.tags.BlockItemTags; +import net.minecraft.data.tags.TagAppender; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import net.minecraftforge.common.Tags; -import static net.minecraftforge.common.Tags.BlockItems.*; -import static net.minecraft.references.BlockItemIds.*; - -public class ForgeBlockItemTagsProvider extends BlockItemTagsProvider { - @SuppressWarnings("unchecked") - protected ForgeBlockItemTagsProvider(final Function tagSupplier) { - super((Function)tagSupplier); - } - - @Override - protected WrappedCombinedAppender tag(final BlockItemTagId tag) { - return (WrappedCombinedAppender)super.tag(tag); - } +import net.minecraftforge.registries.ForgeRegistries; +public abstract class ForgeBlockItemTagsProvider extends BlockItemTagsProvider { @Override + @SuppressWarnings({ "unchecked", "removal" }) protected void run() { - tag(BARRELS) - .addTag(BARRELS_WOODEN); - tag(BARRELS_WOODEN) - .add(BARREL); - tag(BARS_COPPER) - .addAll(COPPER_BARS.asList()); - tag(BARS_IRON) - .add(IRON_BARS); - tag(BARS) - .add(BARS_COPPER, BARS_IRON, BlockItemTags.BARS); - tag(BOOKSHELVES) - .add(BOOKSHELF); - tag(BUDDING_BLOCKS) - .add(BUDDING_AMETHYST); - tag(BUDS) - .add(SMALL_AMETHYST_BUD) - .add(MEDIUM_AMETHYST_BUD) - .add(LARGE_AMETHYST_BUD); - tag(CHAINS) - .add(IRON_CHAIN) - .addAll(COPPER_CHAIN.asList()); - tag(CHESTS_ENDER) - .add(ENDER_CHEST); - tag(CHESTS_TRAPPED) - .add(TRAPPED_CHEST); - tag(CHESTS_WOODEN) - .add(CHEST, TRAPPED_CHEST); - tag(CHESTS) - .addAll(COPPER_CHEST.asList()) - .add( - CHESTS_ENDER, - CHESTS_TRAPPED, - CHESTS_WOODEN + tag(Tags.Blocks.BARRELS, Tags.Items.BARRELS) + .addTag(Tags.Blocks.BARRELS_WOODEN); + tag(Tags.Blocks.BARRELS_WOODEN, Tags.Items.BARRELS_WOODEN) + .add(Blocks.BARREL); + tag(Tags.Blocks.BOOKSHELVES, Tags.Items.BOOKSHELVES) + .add(Blocks.BOOKSHELF); + tag(Tags.Blocks.BUDDING_BLOCKS, Tags.Items.BUDDING_BLOCKS) + .add(Blocks.BUDDING_AMETHYST); + tag(Tags.Blocks.BUDS, Tags.Items.BUDS) + .add(Blocks.SMALL_AMETHYST_BUD) + .add(Blocks.MEDIUM_AMETHYST_BUD) + .add(Blocks.LARGE_AMETHYST_BUD); + tag(Tags.Blocks.CHAINS, Tags.Items.CHAINS) + .add(Blocks.IRON_CHAIN) + .addAll(Blocks.COPPER_CHAIN.asList()); + tag(Tags.Blocks.CHESTS_ENDER, Tags.Items.CHESTS_ENDER) + .add(Blocks.ENDER_CHEST); + tag(Tags.Blocks.CHESTS_TRAPPED, Tags.Items.CHESTS_TRAPPED) + .add(Blocks.TRAPPED_CHEST); + tag(Tags.Blocks.CHESTS_WOODEN, Tags.Items.CHESTS_WOODEN) + .add(Blocks.CHEST, Blocks.TRAPPED_CHEST); + tag(Tags.Blocks.CHESTS, Tags.Items.CHESTS) + .add(Blocks.COPPER_CHEST) + .addTags( + Tags.Blocks.CHESTS_ENDER, + Tags.Blocks.CHESTS_TRAPPED, + Tags.Blocks.CHESTS_WOODEN ); - tag(CLUSTERS) - .add(AMETHYST_CLUSTER); - tag(COBBLESTONES_NORMAL) - .add(COBBLESTONE); - tag(COBBLESTONES_INFESTED) - .add(INFESTED_COBBLESTONE); - tag(COBBLESTONES_MOSSY) - .add(MOSSY_COBBLESTONE); - tag(COBBLESTONES_DEEPSLATE) - .add(COBBLED_DEEPSLATE); - tag(COBBLESTONES) - .add( - COBBLESTONES_NORMAL, - COBBLESTONES_INFESTED, - COBBLESTONES_MOSSY, - COBBLESTONES_DEEPSLATE + tag(Tags.Blocks.CLUSTERS, Tags.Items.CLUSTERS) + .add(Blocks.AMETHYST_CLUSTER); + tag(Tags.Blocks.COBBLESTONES_NORMAL, Tags.Items.COBBLESTONES_NORMAL) + .add(Blocks.COBBLESTONE); + tag(Tags.Blocks.COBBLESTONES_INFESTED, Tags.Items.COBBLESTONES_INFESTED) + .add(Blocks.INFESTED_COBBLESTONE); + tag(Tags.Blocks.COBBLESTONES_MOSSY, Tags.Items.COBBLESTONES_MOSSY) + .add(Blocks.MOSSY_COBBLESTONE); + tag(Tags.Blocks.COBBLESTONES_DEEPSLATE, Tags.Items.COBBLESTONES_DEEPSLATE) + .add(Blocks.COBBLED_DEEPSLATE); + tag(Tags.Blocks.COBBLESTONES, Tags.Items.COBBLESTONES) + .addTags( + Tags.Blocks.COBBLESTONES_NORMAL, + Tags.Blocks.COBBLESTONES_INFESTED, + Tags.Blocks.COBBLESTONES_MOSSY, + Tags.Blocks.COBBLESTONES_DEEPSLATE ); - tag(CONCRETES) - .addAll(CONCRETE.asList()); - tag(END_STONES) - .add(END_STONE); - tag(FENCE_GATES) - .add(FENCE_GATES_WOODEN); - tag(FENCE_GATES_WOODEN) + tag(Tags.Blocks.CONCRETES, Tags.Items.CONCRETES) .add( - OAK_FENCE_GATE, - SPRUCE_FENCE_GATE, - BIRCH_FENCE_GATE, - JUNGLE_FENCE_GATE, - ACACIA_FENCE_GATE, - DARK_OAK_FENCE_GATE, - CRIMSON_FENCE_GATE, - WARPED_FENCE_GATE, - MANGROVE_FENCE_GATE, - BAMBOO_FENCE_GATE, - CHERRY_FENCE_GATE + Blocks.WHITE_CONCRETE, + Blocks.ORANGE_CONCRETE, + Blocks.MAGENTA_CONCRETE, + Blocks.LIGHT_BLUE_CONCRETE, + Blocks.YELLOW_CONCRETE, + Blocks.LIME_CONCRETE, + Blocks.PINK_CONCRETE, + Blocks.GRAY_CONCRETE, + Blocks.LIGHT_GRAY_CONCRETE, + Blocks.CYAN_CONCRETE, + Blocks.PURPLE_CONCRETE, + Blocks.BLUE_CONCRETE, + Blocks.BROWN_CONCRETE, + Blocks.GREEN_CONCRETE, + Blocks.RED_CONCRETE, + Blocks.BLACK_CONCRETE ); - tag(FENCES_NETHER_BRICK) - .add(NETHER_BRICK_FENCE); - tag(FENCES_WOODEN) - .addTag(BlockItemTags.WOODEN_FENCES); - tag(FENCES) + tag(Tags.Blocks.END_STONES, Tags.Items.END_STONES) + .add(Blocks.END_STONE); + tag(Tags.Blocks.FENCE_GATES, Tags.Items.FENCE_GATES) + .addTags(Tags.Blocks.FENCE_GATES_WOODEN); + tag(Tags.Blocks.FENCE_GATES_WOODEN, Tags.Items.FENCE_GATES_WOODEN) .add( - FENCES_NETHER_BRICK, - FENCES_WOODEN + Blocks.OAK_FENCE_GATE, + Blocks.SPRUCE_FENCE_GATE, + Blocks.BIRCH_FENCE_GATE, + Blocks.JUNGLE_FENCE_GATE, + Blocks.ACACIA_FENCE_GATE, + Blocks.DARK_OAK_FENCE_GATE, + Blocks.CRIMSON_FENCE_GATE, + Blocks.WARPED_FENCE_GATE, + Blocks.MANGROVE_FENCE_GATE, + Blocks.BAMBOO_FENCE_GATE, + Blocks.CHERRY_FENCE_GATE ); - tag(FLOWERS_SMALL) - .add( - DANDELION, - POPPY, - BLUE_ORCHID, - ALLIUM, - AZURE_BLUET, - RED_TULIP, - ORANGE_TULIP, - WHITE_TULIP, - PINK_TULIP, - OXEYE_DAISY, - CORNFLOWER, - LILY_OF_THE_VALLEY, - WITHER_ROSE, - TORCHFLOWER, - OPEN_EYEBLOSSOM, - CLOSED_EYEBLOSSOM + tag(Tags.Blocks.FENCES_NETHER_BRICK, Tags.Items.FENCES_NETHER_BRICK) + .add(Blocks.NETHER_BRICK_FENCE); + tag(Tags.Blocks.FENCES_WOODEN, Tags.Items.FENCES_WOODEN) + .addTag(BlockTags.WOODEN_FENCES); + tag(Tags.Blocks.FENCES, Tags.Items.FENCES) + .addTags( + Tags.Blocks.FENCES_NETHER_BRICK, + Tags.Blocks.FENCES_WOODEN ); - tag(FLOWERS_TALL) + tag(Tags.Blocks.FLOWERS_SMALL, Tags.Items.FLOWERS_SMALL) .add( - SUNFLOWER, - LILAC, - PEONY, - ROSE_BUSH, - PITCHER_PLANT + Blocks.DANDELION, + Blocks.POPPY, + Blocks.BLUE_ORCHID, + Blocks.ALLIUM, + Blocks.AZURE_BLUET, + Blocks.RED_TULIP, + Blocks.ORANGE_TULIP, + Blocks.WHITE_TULIP, + Blocks.PINK_TULIP, + Blocks.OXEYE_DAISY, + Blocks.CORNFLOWER, + Blocks.LILY_OF_THE_VALLEY, + Blocks.WITHER_ROSE, + Blocks.TORCHFLOWER, + Blocks.OPEN_EYEBLOSSOM, + Blocks.CLOSED_EYEBLOSSOM ); - tag(FLOWERS) + tag(Tags.Blocks.FLOWERS_TALL, Tags.Items.FLOWERS_TALL) .add( - FLOWERING_AZALEA_LEAVES, - FLOWERING_AZALEA, - MANGROVE_PROPAGULE, - PINK_PETALS, - CHORUS_FLOWER, - SPORE_BLOSSOM + Blocks.SUNFLOWER, + Blocks.LILAC, + Blocks.PEONY, + Blocks.ROSE_BUSH, + Blocks.PITCHER_PLANT + ); + tag(Tags.Blocks.FLOWERS, Tags.Items.FLOWERS) + .add( + Blocks.FLOWERING_AZALEA_LEAVES, + Blocks.FLOWERING_AZALEA, + Blocks.MANGROVE_PROPAGULE, + Blocks.PINK_PETALS, + Blocks.CHORUS_FLOWER, + Blocks.SPORE_BLOSSOM ) - .add( - FLOWERS_SMALL, - FLOWERS_TALL + .addTags( + Tags.Blocks.FLOWERS_SMALL, + Tags.Blocks.FLOWERS_TALL ) - .addOptional(BlockItemTags.FLOWERS); - tag(GLASS_BLOCKS) - .add( - GLASS_BLOCKS_COLORLESS, - GLASS_BLOCKS_CHEAP, - GLASS_BLOCKS_TINTED + .addOptionalTag(BlockTags.FLOWERS); + tag(Tags.Blocks.GLASS_BLOCKS, Tags.Items.GLASS_BLOCKS) + .addTags( + Tags.Blocks.GLASS_BLOCKS_COLORLESS, + Tags.Blocks.GLASS_BLOCKS_CHEAP, + Tags.Blocks.GLASS_BLOCKS_TINTED ); - tag(GLASS_BLOCKS_COLORLESS) - .add(GLASS); - tag(GLASS_BLOCKS_TINTED) - .add(TINTED_GLASS); - tag(GLASS_BLOCKS_CHEAP) - .add(GLASS) - .addAll(STAINED_GLASS.asList()); - tag(GLASS_PANES) - .add(GLASS_PANES_COLORLESS) - .addAll(STAINED_GLASS_PANE.asList()); - tag(GLASS_PANES_COLORLESS) - .add(GLASS_PANE); - tag(GLAZED_TERRACOTTAS) - .addAll(GLAZED_TERRACOTTA.asList()); - tag(GRAVELS) - .add(GRAVEL); - tag(NATURAL_LOGS_NETHER) - .add(CRIMSON_STEM, WARPED_STEM); - tag(NATURAL_LOGS_OVERWORLD) + tag(Tags.Blocks.GLASS_BLOCKS_COLORLESS, Tags.Items.GLASS_BLOCKS_COLORLESS) + .add(Blocks.GLASS); + tag(Tags.Blocks.GLASS_BLOCKS_TINTED, Tags.Items.GLASS_BLOCKS_TINTED) + .add(Blocks.TINTED_GLASS); + + tag(Tags.Blocks.GLASS_BLOCKS_CHEAP, Tags.Items.GLASS_BLOCKS_CHEAP) .add( - ACACIA_LOG, - BIRCH_LOG, - CHERRY_LOG, - DARK_OAK_LOG, - JUNGLE_LOG, - MANGROVE_LOG, - OAK_LOG, - PALE_OAK_LOG, - SPRUCE_LOG + Blocks.GLASS, + Blocks.WHITE_STAINED_GLASS, + Blocks.ORANGE_STAINED_GLASS, + Blocks.MAGENTA_STAINED_GLASS, + Blocks.LIGHT_BLUE_STAINED_GLASS, + Blocks.YELLOW_STAINED_GLASS, + Blocks.LIME_STAINED_GLASS, + Blocks.PINK_STAINED_GLASS, + Blocks.GRAY_STAINED_GLASS, + Blocks.LIGHT_GRAY_STAINED_GLASS, + Blocks.CYAN_STAINED_GLASS, + Blocks.PURPLE_STAINED_GLASS, + Blocks.BLUE_STAINED_GLASS, + Blocks.BROWN_STAINED_GLASS, + Blocks.GREEN_STAINED_GLASS, + Blocks.RED_STAINED_GLASS, + Blocks.BLACK_STAINED_GLASS ); - tag(NATURAL_LOGS) - .add(NATURAL_LOGS_NETHER, NATURAL_LOGS_OVERWORLD); - tag(NATURAL_WOODS) + tag(Tags.Blocks.GLASS_PANES, Tags.Items.GLASS_PANES) + .addTags(Tags.Blocks.GLASS_PANES_COLORLESS) .add( - ACACIA_WOOD, - BIRCH_WOOD, - CHERRY_WOOD, - CRIMSON_HYPHAE, - DARK_OAK_WOOD, - JUNGLE_WOOD, - MANGROVE_WOOD, - OAK_WOOD, - PALE_OAK_WOOD, - SPRUCE_WOOD, - WARPED_HYPHAE + Blocks.WHITE_STAINED_GLASS_PANE, + Blocks.ORANGE_STAINED_GLASS_PANE, + Blocks.MAGENTA_STAINED_GLASS_PANE, + Blocks.LIGHT_BLUE_STAINED_GLASS_PANE, + Blocks.YELLOW_STAINED_GLASS_PANE, + Blocks.LIME_STAINED_GLASS_PANE, + Blocks.PINK_STAINED_GLASS_PANE, + Blocks.GRAY_STAINED_GLASS_PANE, + Blocks.LIGHT_GRAY_STAINED_GLASS_PANE, + Blocks.CYAN_STAINED_GLASS_PANE, + Blocks.PURPLE_STAINED_GLASS_PANE, + Blocks.BLUE_STAINED_GLASS_PANE, + Blocks.BROWN_STAINED_GLASS_PANE, + Blocks.GREEN_STAINED_GLASS_PANE, + Blocks.RED_STAINED_GLASS_PANE, + Blocks.BLACK_STAINED_GLASS_PANE ); - tag(NETHERRACKS) - .add(NETHERRACK); - tag(OBSIDIANS) + tag(Tags.Blocks.GLASS_PANES_COLORLESS, Tags.Items.GLASS_PANES_COLORLESS) + .add(Blocks.GLASS_PANE); + tag(Tags.Blocks.GLAZED_TERRACOTTAS, Tags.Items.GLAZED_TERRACOTTAS) .add( - OBSIDIANS_NORMAL, - OBSIDIANS_CRYING + Blocks.WHITE_GLAZED_TERRACOTTA, + Blocks.ORANGE_GLAZED_TERRACOTTA, + Blocks.MAGENTA_GLAZED_TERRACOTTA, + Blocks.LIGHT_BLUE_GLAZED_TERRACOTTA, + Blocks.YELLOW_GLAZED_TERRACOTTA, + Blocks.LIME_GLAZED_TERRACOTTA, + Blocks.PINK_GLAZED_TERRACOTTA, + Blocks.GRAY_GLAZED_TERRACOTTA, + Blocks.LIGHT_GRAY_GLAZED_TERRACOTTA, + Blocks.CYAN_GLAZED_TERRACOTTA, + Blocks.PURPLE_GLAZED_TERRACOTTA, + Blocks.BLUE_GLAZED_TERRACOTTA, + Blocks.BROWN_GLAZED_TERRACOTTA, + Blocks.GREEN_GLAZED_TERRACOTTA, + Blocks.RED_GLAZED_TERRACOTTA, + Blocks.BLACK_GLAZED_TERRACOTTA ); - tag(OBSIDIANS_NORMAL) - .add(OBSIDIAN); - tag(OBSIDIANS_CRYING) - .add(CRYING_OBSIDIAN); - tag(ORE_BEARING_GROUND_DEEPSLATE) - .add(DEEPSLATE); - tag(ORE_BEARING_GROUND_NETHERRACK) - .add(NETHERRACK); - tag(ORE_BEARING_GROUND_STONE) - .add(STONE); - tag(ORE_RATES_DENSE) + tag(Tags.Blocks.GRAVELS, Tags.Items.GRAVELS) + .add(Blocks.GRAVEL); + tag(Tags.Blocks.NATURAL_LOGS_NETHER, Tags.Items.NATURAL_LOGS_NETHER) + .add(Blocks.CRIMSON_STEM, Blocks.WARPED_STEM); + tag(Tags.Blocks.NATURAL_LOGS_OVERWORLD, Tags.Items.NATURAL_LOGS_OVERWORLD) .add( - COPPER_ORE, - DEEPSLATE_COPPER_ORE, - DEEPSLATE_LAPIS_ORE, - DEEPSLATE_REDSTONE_ORE, - LAPIS_ORE, - REDSTONE_ORE + Blocks.ACACIA_LOG, + Blocks.BIRCH_LOG, + Blocks.CHERRY_LOG, + Blocks.DARK_OAK_LOG, + Blocks.JUNGLE_LOG, + Blocks.MANGROVE_LOG, + Blocks.OAK_LOG, + Blocks.PALE_OAK_LOG, + Blocks.SPRUCE_LOG ); - tag(ORE_RATES_SINGULAR) + tag(Tags.Blocks.NATURAL_LOGS, Tags.Items.NATURAL_LOGS) + .addTags(Tags.Blocks.NATURAL_LOGS_NETHER, Tags.Blocks.NATURAL_LOGS_OVERWORLD); + tag(Tags.Blocks.NATURAL_WOODS, Tags.Items.NATURAL_WOODS) .add( - ANCIENT_DEBRIS, - COAL_ORE, - DEEPSLATE_COAL_ORE, - DEEPSLATE_DIAMOND_ORE, - DEEPSLATE_EMERALD_ORE, - DEEPSLATE_GOLD_ORE, - DEEPSLATE_IRON_ORE, - DIAMOND_ORE, - EMERALD_ORE, - GOLD_ORE, - IRON_ORE, - NETHER_QUARTZ_ORE + Blocks.ACACIA_WOOD, + Blocks.BIRCH_WOOD, + Blocks.CHERRY_WOOD, + Blocks.CRIMSON_HYPHAE, + Blocks.DARK_OAK_WOOD, + Blocks.JUNGLE_WOOD, + Blocks.MANGROVE_WOOD, + Blocks.OAK_WOOD, + Blocks.PALE_OAK_WOOD, + Blocks.SPRUCE_WOOD, + Blocks.WARPED_HYPHAE ); - tag(ORE_RATES_SPARSE) - .add(NETHER_GOLD_ORE); - tag(ORES_COAL) - .add(BlockItemTags.COAL_ORES); - tag(ORES_COPPER) - .add(BlockItemTags.COPPER_ORES); - tag(ORES_DIAMOND) - .add(BlockItemTags.DIAMOND_ORES); - tag(ORES_EMERALD) - .add(BlockItemTags.EMERALD_ORES); - tag(ORES_GOLD) - .add(BlockItemTags.GOLD_ORES); - tag(ORES_IRON) - .add(BlockItemTags.IRON_ORES); - tag(ORES_LAPIS) - .add(BlockItemTags.LAPIS_ORES); - tag(ORES_QUARTZ) - .add(NETHER_QUARTZ_ORE); - tag(ORES_REDSTONE) - .addTag(BlockItemTags.REDSTONE_ORES); - tag(ORES_NETHERITE_SCRAP) - .add(ANCIENT_DEBRIS); - tag(ORES) + tag(Tags.Blocks.NETHERRACKS, Tags.Items.NETHERRACKS) + .add(Blocks.NETHERRACK); + tag(Tags.Blocks.OBSIDIANS, Tags.Items.OBSIDIANS) + .addTags( + Tags.Blocks.OBSIDIANS_NORMAL, + Tags.Blocks.OBSIDIANS_CRYING + ); + tag(Tags.Blocks.OBSIDIANS_NORMAL, Tags.Items.OBSIDIANS_NORMAL) + .add(Blocks.OBSIDIAN); + tag(Tags.Blocks.OBSIDIANS_CRYING, Tags.Items.OBSIDIANS_CRYING) + .add(Blocks.CRYING_OBSIDIAN); + tag(Tags.Blocks.ORE_BEARING_GROUND_DEEPSLATE, Tags.Items.ORE_BEARING_GROUND_DEEPSLATE) + .add(Blocks.DEEPSLATE); + tag(Tags.Blocks.ORE_BEARING_GROUND_NETHERRACK, Tags.Items.ORE_BEARING_GROUND_NETHERRACK) + .add(Blocks.NETHERRACK); + tag(Tags.Blocks.ORE_BEARING_GROUND_STONE, Tags.Items.ORE_BEARING_GROUND_STONE) + .add(Blocks.STONE); + tag(Tags.Blocks.ORE_RATES_DENSE, Tags.Items.ORE_RATES_DENSE) .add( - ORES_COAL, - ORES_COPPER, - ORES_DIAMOND, - ORES_EMERALD, - ORES_GOLD, - ORES_IRON, - ORES_LAPIS, - ORES_NETHERITE_SCRAP, - ORES_REDSTONE, - ORES_QUARTZ + Blocks.COPPER_ORE, + Blocks.DEEPSLATE_COPPER_ORE, + Blocks.DEEPSLATE_LAPIS_ORE, + Blocks.DEEPSLATE_REDSTONE_ORE, + Blocks.LAPIS_ORE, + Blocks.REDSTONE_ORE ); - tag(ORES_IN_GROUND_DEEPSLATE) + tag(Tags.Blocks.ORE_RATES_SINGULAR, Tags.Items.ORE_RATES_SINGULAR) .add( - DEEPSLATE_COAL_ORE, - DEEPSLATE_COPPER_ORE, - DEEPSLATE_DIAMOND_ORE, - DEEPSLATE_EMERALD_ORE, - DEEPSLATE_GOLD_ORE, - DEEPSLATE_IRON_ORE, - DEEPSLATE_LAPIS_ORE, - DEEPSLATE_REDSTONE_ORE + Blocks.ANCIENT_DEBRIS, + Blocks.COAL_ORE, + Blocks.DEEPSLATE_COAL_ORE, + Blocks.DEEPSLATE_DIAMOND_ORE, + Blocks.DEEPSLATE_EMERALD_ORE, + Blocks.DEEPSLATE_GOLD_ORE, + Blocks.DEEPSLATE_IRON_ORE, + Blocks.DIAMOND_ORE, + Blocks.EMERALD_ORE, + Blocks.GOLD_ORE, + Blocks.IRON_ORE, + Blocks.NETHER_QUARTZ_ORE ); - tag(ORES_IN_GROUND_NETHERRACK) + tag(Tags.Blocks.ORE_RATES_SPARSE, Tags.Items.ORE_RATES_SPARSE) + .add(Blocks.NETHER_GOLD_ORE); + tag(Tags.Blocks.ORES_COAL, Tags.Items.ORES_COAL) + .addTag(BlockTags.COAL_ORES); + tag(Tags.Blocks.ORES_COPPER, Tags.Items.ORES_COPPER) + .addTag(BlockTags.COPPER_ORES); + tag(Tags.Blocks.ORES_DIAMOND, Tags.Items.ORES_DIAMOND) + .addTag(BlockTags.DIAMOND_ORES); + tag(Tags.Blocks.ORES_EMERALD, Tags.Items.ORES_EMERALD) + .addTag(BlockTags.EMERALD_ORES); + tag(Tags.Blocks.ORES_GOLD, Tags.Items.ORES_GOLD) + .addTag(BlockTags.GOLD_ORES); + tag(Tags.Blocks.ORES_IRON, Tags.Items.ORES_IRON) + .addTag(BlockTags.IRON_ORES); + tag(Tags.Blocks.ORES_LAPIS, Tags.Items.ORES_LAPIS) + .addTag(BlockTags.LAPIS_ORES); + tag(Tags.Blocks.ORES_QUARTZ, Tags.Items.ORES_QUARTZ) + .add(Blocks.NETHER_QUARTZ_ORE); + tag(Tags.Blocks.ORES_REDSTONE, Tags.Items.ORES_REDSTONE) + .addTag(BlockTags.REDSTONE_ORES); + tag(Tags.Blocks.ORES_NETHERITE_SCRAP, Tags.Items.ORES_NETHERITE_SCRAP) + .add(Blocks.ANCIENT_DEBRIS); + tag(Tags.Blocks.ORES, Tags.Items.ORES) + .addTags( + Tags.Blocks.ORES_COAL, + Tags.Blocks.ORES_COPPER, + Tags.Blocks.ORES_DIAMOND, + Tags.Blocks.ORES_EMERALD, + Tags.Blocks.ORES_GOLD, + Tags.Blocks.ORES_IRON, + Tags.Blocks.ORES_LAPIS, + Tags.Blocks.ORES_NETHERITE_SCRAP, + Tags.Blocks.ORES_REDSTONE, + Tags.Blocks.ORES_QUARTZ + ); + tag(Tags.Blocks.ORES_IN_GROUND_DEEPSLATE, Tags.Items.ORES_IN_GROUND_DEEPSLATE) .add( - NETHER_GOLD_ORE, - NETHER_QUARTZ_ORE + Blocks.DEEPSLATE_COAL_ORE, + Blocks.DEEPSLATE_COPPER_ORE, + Blocks.DEEPSLATE_DIAMOND_ORE, + Blocks.DEEPSLATE_EMERALD_ORE, + Blocks.DEEPSLATE_GOLD_ORE, + Blocks.DEEPSLATE_IRON_ORE, + Blocks.DEEPSLATE_LAPIS_ORE, + Blocks.DEEPSLATE_REDSTONE_ORE ); - tag(ORES_IN_GROUND_STONE) + tag(Tags.Blocks.ORES_IN_GROUND_NETHERRACK, Tags.Items.ORES_IN_GROUND_NETHERRACK) .add( - COAL_ORE, - COPPER_ORE, - DIAMOND_ORE, - EMERALD_ORE, - GOLD_ORE, - IRON_ORE, - LAPIS_ORE, - REDSTONE_ORE + Blocks.NETHER_GOLD_ORE, + Blocks.NETHER_QUARTZ_ORE ); - tag(PLAYER_WORKSTATIONS_CRAFTING_TABLES) - .add(CRAFTING_TABLE); - tag(PLAYER_WORKSTATIONS_FURNACES) - .add(FURNACE); - tag(PUMPKINS) + tag(Tags.Blocks.ORES_IN_GROUND_STONE, Tags.Items.ORES_IN_GROUND_STONE) .add( - PUMPKINS_NORMAL, - PUMPKINS_CARVED, - PUMPKINS_JACK_O_LANTERNS + Blocks.COAL_ORE, + Blocks.COPPER_ORE, + Blocks.DIAMOND_ORE, + Blocks.EMERALD_ORE, + Blocks.GOLD_ORE, + Blocks.IRON_ORE, + Blocks.LAPIS_ORE, + Blocks.REDSTONE_ORE ); - tag(PUMPKINS_NORMAL) - .add(PUMPKIN); - tag(PUMPKINS_CARVED) - .add(CARVED_PUMPKIN); - tag(PUMPKINS_JACK_O_LANTERNS) - .add(JACK_O_LANTERN); - tag(ROPES); - tag(SANDS) + tag(Tags.Blocks.PLAYER_WORKSTATIONS_CRAFTING_TABLES, Tags.Items.PLAYER_WORKSTATIONS_CRAFTING_TABLES) + .add(Blocks.CRAFTING_TABLE); + tag(Tags.Blocks.PLAYER_WORKSTATIONS_FURNACES, Tags.Items.PLAYER_WORKSTATIONS_FURNACES) + .add(Blocks.FURNACE); + tag(Tags.Blocks.PUMPKINS, Tags.Items.PUMPKINS) + .addTags( + Tags.Blocks.PUMPKINS_NORMAL, + Tags.Blocks.PUMPKINS_CARVED, + Tags.Blocks.PUMPKINS_JACK_O_LANTERNS + ); + tag(Tags.Blocks.PUMPKINS_NORMAL, Tags.Items.PUMPKINS_NORMAL) + .add(Blocks.PUMPKIN); + tag(Tags.Blocks.PUMPKINS_CARVED, Tags.Items.PUMPKINS_CARVED) + .add(Blocks.CARVED_PUMPKIN); + tag(Tags.Blocks.PUMPKINS_JACK_O_LANTERNS, Tags.Items.PUMPKINS_JACK_O_LANTERNS) + .add(Blocks.JACK_O_LANTERN); + tag(Tags.Blocks.ROPES, Tags.Items.ROPES); + tag(Tags.Blocks.SANDS, Tags.Items.SANDS) + .addTags( + Tags.Blocks.SANDS_COLORLESS, + Tags.Blocks.SANDS_RED + ); + tag(Tags.Blocks.SANDS_COLORLESS, Tags.Items.SANDS_COLORLESS) + .add(Blocks.SAND); + tag(Tags.Blocks.SANDS_RED, Tags.Items.SANDS_RED) + .add(Blocks.RED_SAND); + tag(Tags.Blocks.SANDSTONE_BLOCKS, Tags.Items.SANDSTONE_BLOCKS) + .addTags( + Tags.Blocks.SANDSTONE_RED_BLOCKS, + Tags.Blocks.SANDSTONE_UNCOLORED_BLOCKS + ); + tag(Tags.Blocks.SANDSTONE_SLABS, Tags.Items.SANDSTONE_SLABS) + .addTags( + Tags.Blocks.SANDSTONE_RED_SLABS, + Tags.Blocks.SANDSTONE_UNCOLORED_SLABS + ); + tag(Tags.Blocks.SANDSTONE_STAIRS, Tags.Items.SANDSTONE_STAIRS) + .addTags( + Tags.Blocks.SANDSTONE_RED_STAIRS, + Tags.Blocks.SANDSTONE_UNCOLORED_STAIRS + ); + tag(Tags.Blocks.SANDSTONE_RED_BLOCKS, Tags.Items.SANDSTONE_RED_BLOCKS) .add( - SANDS_COLORLESS, - SANDS_RED + Blocks.RED_SANDSTONE, + Blocks.CUT_RED_SANDSTONE, + Blocks.CHISELED_RED_SANDSTONE, + Blocks.SMOOTH_RED_SANDSTONE ); - tag(SANDS_COLORLESS) - .add(SAND); - tag(SANDS_RED) - .add(RED_SAND); - tag(SANDSTONE_BLOCKS) + tag(Tags.Blocks.SANDSTONE_RED_SLABS, Tags.Items.SANDSTONE_RED_SLABS) .add( - SANDSTONE_RED_BLOCKS, - SANDSTONE_UNCOLORED_BLOCKS + Blocks.RED_SANDSTONE_SLAB, + Blocks.CUT_RED_SANDSTONE_SLAB, + Blocks.SMOOTH_RED_SANDSTONE_SLAB ); - tag(SANDSTONE_SLABS) + tag(Tags.Blocks.SANDSTONE_RED_STAIRS, Tags.Items.SANDSTONE_RED_STAIRS) .add( - SANDSTONE_RED_SLABS, - SANDSTONE_UNCOLORED_SLABS + Blocks.RED_SANDSTONE_STAIRS, + Blocks.SMOOTH_RED_SANDSTONE_STAIRS ); - tag(Tags.BlockItems.SANDSTONE_STAIRS) + tag(Tags.Blocks.SANDSTONE_UNCOLORED_BLOCKS, Tags.Items.SANDSTONE_UNCOLORED_BLOCKS) .add( - SANDSTONE_RED_STAIRS, - SANDSTONE_UNCOLORED_STAIRS + Blocks.SANDSTONE, + Blocks.CUT_SANDSTONE, + Blocks.CHISELED_SANDSTONE, + Blocks.SMOOTH_SANDSTONE ); - tag(SANDSTONE_RED_BLOCKS) + tag(Tags.Blocks.SANDSTONE_UNCOLORED_SLABS, Tags.Items.SANDSTONE_UNCOLORED_SLABS) .add( - RED_SANDSTONE, - CUT_RED_SANDSTONE, - CHISELED_RED_SANDSTONE, - SMOOTH_RED_SANDSTONE + Blocks.SANDSTONE_SLAB, + Blocks.CUT_SANDSTONE_SLAB, + Blocks.SMOOTH_SANDSTONE_SLAB ); - tag(SANDSTONE_RED_SLABS) + tag(Tags.Blocks.SANDSTONE_UNCOLORED_STAIRS, Tags.Items.SANDSTONE_UNCOLORED_STAIRS) .add( - RED_SANDSTONE_SLAB, - CUT_RED_SANDSTONE_SLAB, - SMOOTH_RED_SANDSTONE_SLAB + Blocks.SANDSTONE_STAIRS, + Blocks.SMOOTH_SANDSTONE_STAIRS ); - tag(SANDSTONE_RED_STAIRS) + tag(Tags.Blocks.STONES, Tags.Items.STONES) .add( - RED_SANDSTONE_STAIRS, - SMOOTH_RED_SANDSTONE_STAIRS + Blocks.ANDESITE, + Blocks.DIORITE, + Blocks.GRANITE, + Blocks.STONE, + Blocks.DEEPSLATE, + Blocks.TUFF ); - tag(SANDSTONE_UNCOLORED_BLOCKS) + tag(Tags.Blocks.STORAGE_BLOCKS, Tags.Items.STORAGE_BLOCKS) + .addTags( + Tags.Blocks.STORAGE_BLOCKS_BONE_MEAL, + Tags.Blocks.STORAGE_BLOCKS_COAL, + Tags.Blocks.STORAGE_BLOCKS_COPPER, + Tags.Blocks.STORAGE_BLOCKS_DIAMOND, + Tags.Blocks.STORAGE_BLOCKS_DRIED_KELP, + Tags.Blocks.STORAGE_BLOCKS_EMERALD, + Tags.Blocks.STORAGE_BLOCKS_GOLD, + Tags.Blocks.STORAGE_BLOCKS_IRON, + Tags.Blocks.STORAGE_BLOCKS_LAPIS, + Tags.Blocks.STORAGE_BLOCKS_NETHERITE, + Tags.Blocks.STORAGE_BLOCKS_RAW_COPPER, + Tags.Blocks.STORAGE_BLOCKS_RAW_GOLD, + Tags.Blocks.STORAGE_BLOCKS_RAW_IRON, + Tags.Blocks.STORAGE_BLOCKS_REDSTONE, + Tags.Blocks.STORAGE_BLOCKS_SLIME, + Tags.Blocks.STORAGE_BLOCKS_WHEAT, + Tags.Blocks.STORAGE_BLOCKS_RESIN + ); + tag(Tags.Blocks.STORAGE_BLOCKS_AMETHYST, Tags.Items.STORAGE_BLOCKS_AMETHYST) + .add(Blocks.AMETHYST_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_BONE_MEAL, Tags.Items.STORAGE_BLOCKS_BONE_MEAL) + .add(Blocks.BONE_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_COAL, Tags.Items.STORAGE_BLOCKS_COAL) + .add(Blocks.COAL_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_COPPER, Tags.Items.STORAGE_BLOCKS_COPPER) + .add(Blocks.COPPER_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_DIAMOND, Tags.Items.STORAGE_BLOCKS_DIAMOND) + .add(Blocks.DIAMOND_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_DRIED_KELP, Tags.Items.STORAGE_BLOCKS_DRIED_KELP) + .add(Blocks.DRIED_KELP_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_EMERALD, Tags.Items.STORAGE_BLOCKS_EMERALD) + .add(Blocks.EMERALD_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_GOLD, Tags.Items.STORAGE_BLOCKS_GOLD) + .add(Blocks.GOLD_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_IRON, Tags.Items.STORAGE_BLOCKS_IRON) + .add(Blocks.IRON_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_LAPIS, Tags.Items.STORAGE_BLOCKS_LAPIS) + .add(Blocks.LAPIS_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_NETHERITE, Tags.Items.STORAGE_BLOCKS_NETHERITE) + .add(Blocks.NETHERITE_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_QUARTZ, Tags.Items.STORAGE_BLOCKS_QUARTZ) + .add(Blocks.QUARTZ_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_RAW_COPPER, Tags.Items.STORAGE_BLOCKS_RAW_COPPER) + .add(Blocks.RAW_COPPER_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_RAW_GOLD, Tags.Items.STORAGE_BLOCKS_RAW_GOLD) + .add(Blocks.RAW_GOLD_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_RAW_IRON, Tags.Items.STORAGE_BLOCKS_RAW_IRON) + .add(Blocks.RAW_IRON_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_RESIN, Tags.Items.STORAGE_BLOCKS_RESIN) + .add(Blocks.RESIN_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_REDSTONE, Tags.Items.STORAGE_BLOCKS_REDSTONE) + .add(Blocks.REDSTONE_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_SLIME, Tags.Items.STORAGE_BLOCKS_SLIME) + .add(Blocks.SLIME_BLOCK); + tag(Tags.Blocks.STORAGE_BLOCKS_WHEAT, Tags.Items.STORAGE_BLOCKS_WHEAT) + .add(Blocks.HAY_BLOCK); + tag(Tags.Blocks.STRIPPED_LOGS, Tags.Items.STRIPPED_LOGS) .add( - SANDSTONE, - CUT_SANDSTONE, - CHISELED_SANDSTONE, - SMOOTH_SANDSTONE + Blocks.STRIPPED_ACACIA_LOG, + Blocks.STRIPPED_BAMBOO_BLOCK, + Blocks.STRIPPED_BIRCH_LOG, + Blocks.STRIPPED_CHERRY_LOG, + Blocks.STRIPPED_CRIMSON_STEM, + Blocks.STRIPPED_DARK_OAK_LOG, + Blocks.STRIPPED_JUNGLE_LOG, + Blocks.STRIPPED_MANGROVE_LOG, + Blocks.STRIPPED_OAK_LOG, + Blocks.STRIPPED_PALE_OAK_LOG, + Blocks.STRIPPED_SPRUCE_LOG, + Blocks.STRIPPED_WARPED_STEM ); - tag(SANDSTONE_UNCOLORED_SLABS) + tag(Tags.Blocks.STRIPPED_WOODS, Tags.Items.STRIPPED_WOODS) .add( - SANDSTONE_SLAB, - CUT_SANDSTONE_SLAB, - SMOOTH_SANDSTONE_SLAB - ); - tag(SANDSTONE_UNCOLORED_STAIRS) - .add( - BlockItemIds.SANDSTONE_STAIRS, - SMOOTH_SANDSTONE_STAIRS - ); - tag(STONES) - .add( - ANDESITE, - DIORITE, - GRANITE, - STONE, - DEEPSLATE, - TUFF - ); - tag(STORAGE_BLOCKS) - .add( - STORAGE_BLOCKS_BONE_MEAL, - STORAGE_BLOCKS_COAL, - STORAGE_BLOCKS_COPPER, - STORAGE_BLOCKS_DIAMOND, - STORAGE_BLOCKS_DRIED_KELP, - STORAGE_BLOCKS_EMERALD, - STORAGE_BLOCKS_GOLD, - STORAGE_BLOCKS_IRON, - STORAGE_BLOCKS_LAPIS, - STORAGE_BLOCKS_NETHERITE, - STORAGE_BLOCKS_RAW_COPPER, - STORAGE_BLOCKS_RAW_GOLD, - STORAGE_BLOCKS_RAW_IRON, - STORAGE_BLOCKS_REDSTONE, - STORAGE_BLOCKS_SLIME, - STORAGE_BLOCKS_WHEAT, - STORAGE_BLOCKS_RESIN - ); - tag(STORAGE_BLOCKS_AMETHYST) - .add(AMETHYST_BLOCK); - tag(STORAGE_BLOCKS_BONE_MEAL) - .add(BONE_BLOCK); - tag(STORAGE_BLOCKS_COAL) - .add(COAL_BLOCK); - tag(STORAGE_BLOCKS_COPPER) - .addAll(COPPER_BLOCK.asList()); - tag(STORAGE_BLOCKS_DIAMOND) - .add(DIAMOND_BLOCK); - tag(STORAGE_BLOCKS_DRIED_KELP) - .add(DRIED_KELP_BLOCK); - tag(STORAGE_BLOCKS_EMERALD) - .add(EMERALD_BLOCK); - tag(STORAGE_BLOCKS_GOLD) - .add(GOLD_BLOCK); - tag(STORAGE_BLOCKS_IRON) - .add(IRON_BLOCK); - tag(STORAGE_BLOCKS_LAPIS) - .add(LAPIS_BLOCK); - tag(STORAGE_BLOCKS_NETHERITE) - .add(NETHERITE_BLOCK); - tag(STORAGE_BLOCKS_QUARTZ) - .add(QUARTZ_BLOCK); - tag(STORAGE_BLOCKS_RAW_COPPER) - .add(RAW_COPPER_BLOCK); - tag(STORAGE_BLOCKS_RAW_GOLD) - .add(RAW_GOLD_BLOCK); - tag(STORAGE_BLOCKS_RAW_IRON) - .add(RAW_IRON_BLOCK); - tag(STORAGE_BLOCKS_RESIN) - .add(RESIN_BLOCK); - tag(STORAGE_BLOCKS_REDSTONE) - .add(REDSTONE_BLOCK); - tag(STORAGE_BLOCKS_SLIME) - .add(SLIME_BLOCK); - tag(STORAGE_BLOCKS_WHEAT) - .add(HAY_BLOCK); - tag(STRIPPED_LOGS) - .add( - STRIPPED_ACACIA_LOG, - STRIPPED_BAMBOO_BLOCK, - STRIPPED_BIRCH_LOG, - STRIPPED_CHERRY_LOG, - STRIPPED_CRIMSON_STEM, - STRIPPED_DARK_OAK_LOG, - STRIPPED_JUNGLE_LOG, - STRIPPED_MANGROVE_LOG, - STRIPPED_OAK_LOG, - STRIPPED_PALE_OAK_LOG, - STRIPPED_SPRUCE_LOG, - STRIPPED_WARPED_STEM - ); - tag(STRIPPED_WOODS) - .add( - STRIPPED_ACACIA_WOOD, - STRIPPED_BIRCH_WOOD, - STRIPPED_CHERRY_WOOD, - STRIPPED_CRIMSON_HYPHAE, - STRIPPED_DARK_OAK_WOOD, - STRIPPED_JUNGLE_WOOD, - STRIPPED_MANGROVE_WOOD, - STRIPPED_OAK_WOOD, - STRIPPED_PALE_OAK_WOOD, - STRIPPED_SPRUCE_WOOD, - STRIPPED_WARPED_HYPHAE + Blocks.STRIPPED_ACACIA_WOOD, + Blocks.STRIPPED_BIRCH_WOOD, + Blocks.STRIPPED_CHERRY_WOOD, + Blocks.STRIPPED_CRIMSON_HYPHAE, + Blocks.STRIPPED_DARK_OAK_WOOD, + Blocks.STRIPPED_JUNGLE_WOOD, + Blocks.STRIPPED_MANGROVE_WOOD, + Blocks.STRIPPED_OAK_WOOD, + Blocks.STRIPPED_PALE_OAK_WOOD, + Blocks.STRIPPED_SPRUCE_WOOD, + Blocks.STRIPPED_WARPED_HYPHAE ); } + + private static TagKey forgeTagKey(String path) { + return BlockTags.create(Identifier.fromNamespaceAndPath("forge", path)); + } + + private static TagKey tagKey(String name) { + return BlockTags.create(Identifier.withDefaultNamespace(name)); + } + + private void addColored(Consumer consumer, TagKey group, String pattern) { + String prefix = group.location().getPath().toUpperCase(Locale.ENGLISH) + '_'; + for (DyeColor color : DyeColor.values()) { + Identifier key = Identifier.fromNamespaceAndPath("minecraft", pattern.replace("{color}", color.getName())); + TagKey blockTag = getForgeTag(Tags.Blocks.class, prefix + color.getName()); + TagKey itemTag = getForgeTag(Tags.Items.class, prefix + color.getName()); + Block block = ForgeRegistries.BLOCKS.getValue(key); + if (block == null || block == Blocks.AIR) + throw new IllegalStateException("Unknown vanilla block: " + key.toString()); + tag(blockTag, itemTag).add(block); + consumer.accept(block); + } + } + + @SuppressWarnings("unchecked") + private static TagKey getForgeTag(Class cls, String name) { + try { + name = name.toUpperCase(Locale.ENGLISH); + return (TagKey)cls.getDeclaredField(name).get(null); + } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { + throw new IllegalStateException(cls.getName() + " is missing tag name: " + name); + } + } + + private static Identifier forgeRl(String path) { + return Identifier.fromNamespaceAndPath("forge", path); + } + + private TagAppender tag(TagKey block, TagKey item, TagKey oldBlock, TagKey oldItem) { + var tag = tag(block, item); + var old = tag(oldBlock, oldItem); + return wrap(tag, old, oldBlock); + } + + private static TagAppender wrap(TagAppender tag, TagAppender old, TagKey oldBlock) { + return new TagAppender() { + @Override + public TagAppender add(Block value) { + tag.add(value); + old.add(value); + return this; + } + + @Override + public TagAppender addOptional(Block value) { + tag.addOptional(value); + old.addOptional(value); + return this; + } + + @Override + public TagAppender addTag(TagKey value) { + tag.addTag(value); + old.addTag(value); + return this; + } + + @Override + public TagAppender addOptionalTag(TagKey value) { + tag.addOptionalTag(value); + if (value != oldBlock) + old.addOptionalTag(value); + return this; + } + + @Override + public TagAppender replace(boolean value) { + tag.replace(value); + old.replace(value); + return this; + } + + @Override + public TagAppender remove(Identifier value) { + tag.remove(value); + old.remove(value); + return this; + } + + @Override + public TagAppender remove(TagKey value) { + tag.remove(value); + old.remove(value); + return this; + } + + @Override + public TagAppender remove(Block value) { + tag.remove(value); + old.remove(value); + return this; + } + + @Override + public String getSourceName() { + return tag.getSourceName(); + } + }; + } } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeBlockTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeBlockTagsProvider.java index 989af417d3..6f52809ecc 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeBlockTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeBlockTagsProvider.java @@ -6,14 +6,14 @@ package net.minecraftforge.common.data; import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; +import net.minecraft.data.tags.TagAppender; import net.minecraft.data.tags.VanillaBlockTagsProvider; import net.minecraft.resources.Identifier; -import net.minecraft.resources.ResourceKey; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraftforge.common.Tags; @@ -25,8 +25,7 @@ import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; -import static net.minecraft.references.BlockIds.*; -import static net.minecraft.references.BlockItemIds.*; +// We typically don't do static imports as S2S can't remap them {as they are not qualified}, however this conflicts with vanilla and our tag class names, and our tags don't get obfed so its one line of warning. import static net.minecraftforge.common.Tags.Blocks.*; @ApiStatus.Internal @@ -36,8 +35,13 @@ public final class ForgeBlockTagsProvider extends VanillaBlockTagsProvider { } @Override - public void addTags(HolderLookup.Provider p_256380_) { - new ForgeBlockItemTagsProvider(tagId -> WrappedCombinedAppender.block(this.tag(tagId.block()))).run(); + public void addTags(HolderLookup.Provider p_256380_) { + (new ForgeBlockItemTagsProvider() { + @Override + protected TagAppender tag(TagKey p_406922_, TagKey p_408417_) { + return ForgeBlockTagsProvider.this.tag(p_406922_); + } + }).run(); addColored(DYED, "{color}_banner"); addColored(DYED, "{color}_bed"); addColored(DYED, "{color}_candle"); @@ -53,60 +57,25 @@ public final class ForgeBlockTagsProvider extends VanillaBlockTagsProvider { addColored(DYED, "{color}_wool"); addColoredTags(tag(DYED)::addTag, DYED); tag(ENDERMAN_PLACE_ON_BLACKLIST); // forge:enderman_place_on_blacklist - tag(SKULLS) - .add( // Has Items - SKELETON_SKULL, - WITHER_SKELETON_SKULL, - PLAYER_HEAD, - ZOMBIE_HEAD, - CREEPER_HEAD, - PIGLIN_HEAD, - DRAGON_HEAD - ) - .add( // Doesn't have items - SKELETON_WALL_SKULL, - WITHER_SKELETON_WALL_SKULL, - PLAYER_WALL_HEAD, - ZOMBIE_WALL_HEAD, - CREEPER_WALL_HEAD, - PIGLIN_WALL_HEAD, - DRAGON_WALL_HEAD - ); + tag(SKULLS).add(Blocks.SKELETON_SKULL, Blocks.SKELETON_WALL_SKULL, Blocks.WITHER_SKELETON_SKULL, Blocks.WITHER_SKELETON_WALL_SKULL, Blocks.PLAYER_HEAD, Blocks.PLAYER_WALL_HEAD, Blocks.ZOMBIE_HEAD, Blocks.ZOMBIE_WALL_HEAD, Blocks.CREEPER_HEAD, Blocks.CREEPER_WALL_HEAD, Blocks.PIGLIN_HEAD, Blocks.PIGLIN_WALL_HEAD, Blocks.DRAGON_HEAD, Blocks.DRAGON_WALL_HEAD); tag(HIDDEN_FROM_RECIPE_VIEWERS); tag(RELOCATION_NOT_SUPPORTED); - tag(VILLAGER_JOB_SITES) - .add( // Has items - BARREL, - BLAST_FURNACE, - BREWING_STAND, - CARTOGRAPHY_TABLE, - CAULDRON, - COMPOSTER, - FLETCHING_TABLE, - GRINDSTONE, - LECTERN, - LOOM, - SMITHING_TABLE, - SMOKER, - STONECUTTER - ) - .add( // Doesn't have items - WATER_CAULDRON, - LAVA_CAULDRON, - POWDER_SNOW_CAULDRON - ); + tag(VILLAGER_JOB_SITES).add( + Blocks.BARREL, Blocks.BLAST_FURNACE, Blocks.BREWING_STAND, Blocks.CARTOGRAPHY_TABLE, + Blocks.CAULDRON, Blocks.WATER_CAULDRON, Blocks.LAVA_CAULDRON, Blocks.POWDER_SNOW_CAULDRON, + Blocks.COMPOSTER, Blocks.FLETCHING_TABLE, Blocks.GRINDSTONE, Blocks.LECTERN, + Blocks.LOOM, Blocks.SMITHING_TABLE, Blocks.SMOKER, Blocks.STONECUTTER); } private void addColored(TagKey group, String pattern) { String prefix = group.location().getPath().toUpperCase(Locale.ENGLISH) + '_'; for (var color : DyeColor.values()) { - var key = Identifier.withDefaultNamespace(pattern.replace("{color}", color.getName())); + var key = Identifier.fromNamespaceAndPath("minecraft", pattern.replace("{color}", color.getName())); TagKey tag = getTag(prefix + color.getName()); var block = ForgeRegistries.BLOCKS.getValue(key); if (block == null || block == Blocks.AIR) throw new IllegalStateException("Unknown vanilla block: " + key); - tag(tag) - .add(ResourceKey.create(Registries.BLOCK, key)); + tag(tag).add(block); } } @@ -122,13 +91,12 @@ public final class ForgeBlockTagsProvider extends VanillaBlockTagsProvider { private static TagKey getTag(String name) { try { name = name.toUpperCase(Locale.ENGLISH); - return (TagKey)Tags.Blocks.class.getDeclaredField(name).get(null); + return (TagKey) Tags.Blocks.class.getDeclaredField(name).get(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { throw new IllegalStateException(Tags.Blocks.class.getName() + " is missing tag name: " + name); } } - @SuppressWarnings("unused") private static TagKey forgeTagKey(String path) { return BlockTags.create(Identifier.fromNamespaceAndPath("forge", path)); } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeEntityTypeTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeEntityTypeTagsProvider.java index 53a4b33232..a936c23bbb 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeEntityTypeTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeEntityTypeTagsProvider.java @@ -12,7 +12,6 @@ import net.minecraft.resources.Identifier; import net.minecraft.tags.EntityTypeTags; import net.minecraft.tags.TagKey; import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.EntityTypeIds; import org.jetbrains.annotations.ApiStatus; import java.util.concurrent.CompletableFuture; @@ -25,48 +24,46 @@ public final class ForgeEntityTypeTagsProvider extends EntityTypeTagsProvider { super(output, lookupProvider, "forge", existingFileHelper); } - @SuppressWarnings("unchecked") @Override public void addTags(HolderLookup.Provider lookupProvider) { tag(BOSSES) - .add(EntityTypeIds.ENDER_DRAGON, EntityTypeIds.WITHER); + .add(EntityType.ENDER_DRAGON, EntityType.WITHER); tag(MINECARTS).add( - EntityTypeIds.MINECART, - EntityTypeIds.CHEST_MINECART, - EntityTypeIds.FURNACE_MINECART, - EntityTypeIds.HOPPER_MINECART, - EntityTypeIds.SPAWNER_MINECART, - EntityTypeIds.TNT_MINECART, - EntityTypeIds.COMMAND_BLOCK_MINECART + EntityType.MINECART, + EntityType.CHEST_MINECART, + EntityType.FURNACE_MINECART, + EntityType.HOPPER_MINECART, + EntityType.SPAWNER_MINECART, + EntityType.TNT_MINECART, + EntityType.COMMAND_BLOCK_MINECART ); tag(BOATS).add( - EntityTypeIds.ACACIA_BOAT, - EntityTypeIds.ACACIA_CHEST_BOAT, - EntityTypeIds.BAMBOO_CHEST_RAFT, - EntityTypeIds.BAMBOO_RAFT, - EntityTypeIds.BIRCH_BOAT, - EntityTypeIds.BIRCH_CHEST_BOAT, - EntityTypeIds.CHERRY_BOAT, - EntityTypeIds.CHERRY_CHEST_BOAT, - EntityTypeIds.DARK_OAK_BOAT, - EntityTypeIds.DARK_OAK_CHEST_BOAT, - EntityTypeIds.JUNGLE_BOAT, - EntityTypeIds.JUNGLE_CHEST_BOAT, - EntityTypeIds.MANGROVE_BOAT, - EntityTypeIds.MANGROVE_CHEST_BOAT, - EntityTypeIds.OAK_BOAT, - EntityTypeIds.OAK_CHEST_BOAT, - EntityTypeIds.PALE_OAK_BOAT, - EntityTypeIds.PALE_OAK_CHEST_BOAT, - EntityTypeIds.SPRUCE_BOAT, - EntityTypeIds.SPRUCE_CHEST_BOAT + EntityType.ACACIA_BOAT, + EntityType.ACACIA_CHEST_BOAT, + EntityType.BAMBOO_CHEST_RAFT, + EntityType.BAMBOO_RAFT, + EntityType.BIRCH_BOAT, + EntityType.BIRCH_CHEST_BOAT, + EntityType.CHERRY_BOAT, + EntityType.CHERRY_CHEST_BOAT, + EntityType.DARK_OAK_BOAT, + EntityType.DARK_OAK_CHEST_BOAT, + EntityType.JUNGLE_BOAT, + EntityType.JUNGLE_CHEST_BOAT, + EntityType.MANGROVE_BOAT, + EntityType.MANGROVE_CHEST_BOAT, + EntityType.OAK_BOAT, + EntityType.OAK_CHEST_BOAT, + EntityType.PALE_OAK_BOAT, + EntityType.PALE_OAK_CHEST_BOAT, + EntityType.SPRUCE_BOAT, + EntityType.SPRUCE_CHEST_BOAT ); - tag(ITEM_FRAMES).add(EntityTypeIds.ITEM_FRAME, EntityTypeIds.GLOW_ITEM_FRAME); + tag(ITEM_FRAMES).add(EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME); tag(CAPTURING_NOT_SUPPORTED); tag(TELEPORTING_NOT_SUPPORTED); } - @SuppressWarnings("unused") private static TagKey> forgeTagKey(String path) { return EntityTypeTags.create(Identifier.fromNamespaceAndPath("forge", path)); } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeFluidTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeFluidTagsProvider.java index b63f67cdb9..af7df178c0 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeFluidTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeFluidTagsProvider.java @@ -8,7 +8,10 @@ package net.minecraftforge.common.data; import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; import net.minecraft.data.tags.FluidTagsProvider; -import net.minecraft.world.level.material.FluidIds; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.FluidTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.material.Fluid; import net.minecraftforge.common.ForgeMod; import org.jetbrains.annotations.ApiStatus; @@ -21,19 +24,10 @@ public final class ForgeFluidTagsProvider extends FluidTagsProvider { super(output, lookupProvider, "forge", existingFileHelper); } - @SuppressWarnings("unchecked") @Override public void addTags(HolderLookup.Provider lookupProvider) { - tag(WATER) - .add( - FluidIds.WATER, - FluidIds.FLOWING_WATER - ); - tag(LAVA) - .add( - FluidIds.LAVA, - FluidIds.FLOWING_LAVA - ); + tag(WATER).add(net.minecraft.world.level.material.Fluids.WATER).add(net.minecraft.world.level.material.Fluids.FLOWING_WATER); + tag(LAVA).add(net.minecraft.world.level.material.Fluids.LAVA).add(net.minecraft.world.level.material.Fluids.FLOWING_LAVA); tag(MILK) .addOptional(ForgeMod.MILK.getKey().identifier()) .addOptional(ForgeMod.FLOWING_MILK.getKey().identifier()); @@ -48,6 +42,10 @@ public final class ForgeFluidTagsProvider extends FluidTagsProvider { tag(EXPERIENCE); } + private static TagKey forgeTagKey(String path) { + return FluidTags.create(Identifier.fromNamespaceAndPath("forge", path)); + } + @Override public String getName() { return "Forge Fluid Tags"; diff --git a/src/main/java/net/minecraftforge/common/data/ForgeItemTagsProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeItemTagsProvider.java index e692ba0599..05b5cb375b 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeItemTagsProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeItemTagsProvider.java @@ -7,18 +7,16 @@ package net.minecraftforge.common.data; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; +import net.minecraft.data.tags.TagAppender; import net.minecraft.data.tags.VanillaItemTagsProvider; -import net.minecraft.references.BlockItemId; -import net.minecraft.references.BlockItemIds; import net.minecraft.resources.Identifier; -import net.minecraft.resources.ResourceKey; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; import net.minecraftforge.common.Tags; import net.minecraftforge.registries.ForgeRegistries; import org.jetbrains.annotations.ApiStatus; @@ -27,10 +25,6 @@ import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; -import static net.minecraft.references.ItemIds.*; -import static net.minecraft.references.BlockItemIds.*; -import static net.minecraftforge.common.Tags.Items.*; - @ApiStatus.Internal public final class ForgeItemTagsProvider extends VanillaItemTagsProvider { public ForgeItemTagsProvider(PackOutput output, CompletableFuture lookupProvider, ExistingFileHelper existingFileHelper) { @@ -40,523 +34,266 @@ public final class ForgeItemTagsProvider extends VanillaItemTagsProvider { @SuppressWarnings({ "unchecked", "removal" }) @Override public void addTags(HolderLookup.Provider lookupProvider) { - new ForgeBlockItemTagsProvider(tagId -> WrappedCombinedAppender.item(this.tag(tagId.item()))).run(); - tag(BONES).add(BONE); - tag(Tags.Items.BRICKS) - .addTags( - BRICKS_NORMAL, - BRICKS_NETHER, - BRICKS_RESIN - ); - tag(BRICKS_NORMAL).add(BRICK); - tag(BRICKS_NETHER).add(NETHER_BRICK); - tag(BRICKS_RESIN).add(RESIN_BRICK); - tag(BUCKETS_EMPTY).add(BUCKET); - tag(BUCKETS_WATER).add(WATER_BUCKET); - tag(BUCKETS_LAVA).add(LAVA_BUCKET); - tag(BUCKETS_MILK).add(MILK_BUCKET); - tag(BUCKETS_POWDER_SNOW).add(POWDER_SNOW); - tag(BUCKETS_ENTITY_WATER) - .add( - AXOLOTL_BUCKET, - COD_BUCKET, - PUFFERFISH_BUCKET, - TADPOLE_BUCKET, - TROPICAL_FISH_BUCKET, - SALMON_BUCKET - ); - tag(BUCKETS) - .addTags( - BUCKETS_EMPTY, - BUCKETS_WATER, - BUCKETS_LAVA, - BUCKETS_MILK, - BUCKETS_POWDER_SNOW, - BUCKETS_ENTITY_WATER - ); - tag(CLUMPS) - .addTag(CLUMPS_RESIN); - tag(CLUMPS_RESIN) - .add(RESIN_CLUMP); - tag(CONCRETE_POWDERS) - .addAll(BlockItemIds.CONCRETE_POWDER.map(BlockItemId::item).asList()); - tag(CROPS) - .addTags( - CROPS_BEETROOT, - CROPS_CACTUS, - CROPS_CARROT, - CROPS_COCOA_BEAN, - CROPS_MELON, - CROPS_NETHER_WART, - CROPS_POTATO, - CROPS_PUMPKIN, - CROPS_SUGAR_CANE, - CROPS_WHEAT - ); - tag(CROPS_BEETROOT).add(BEETROOT); - tag(CROPS_CACTUS).add(CACTUS); - tag(CROPS_CARROT).add(CARROT_CROP); - tag(CROPS_COCOA_BEAN).add(COCOA_CROP); - tag(CROPS_MELON).add(MELON); - tag(CROPS_NETHER_WART).add(NETHER_WART); - tag(CROPS_POTATO).add(POTATO_CROP); - tag(CROPS_PUMPKIN).add(PUMPKIN); - tag(CROPS_SUGAR_CANE).add(SUGAR_CANE); - tag(CROPS_WHEAT).add(WHEAT); - tag(DRINK_CONTAINING_BOTTLE) - .add( - POTION, - HONEY_BOTTLE, - OMINOUS_BOTTLE - ); - tag(DRINK_CONTAINING_BUCKET).add(MILK_BUCKET); - tag(DRINKS) - .addTags( - DRINKS_HONEY, - DRINKS_JUICE, - DRINKS_MAGIC, - DRINKS_MILK, - DRINKS_OMINOUS, - DRINKS_WATER, - DRINKS_WATERY - ); - tag(DRINKS_HONEY).add(HONEY_BOTTLE); - tag(DRINKS_JUICE); - tag(DRINKS_MAGIC) - .add( - OMINOUS_BOTTLE, - POTION - ); - tag(DRINKS_MILK).add(MILK_BUCKET); - tag(DRINKS_OMINOUS).add(OMINOUS_BOTTLE); - tag(DRINKS_WATER); - tag(DRINKS_WATERY).add(POTION); - addColored(DYED, "{color}_banner"); - addColored(DYED, "{color}_bed"); - addColored(DYED, "{color}_candle"); - addColored(DYED, "{color}_carpet"); - addColored(DYED, "{color}_concrete"); - addColored(DYED, "{color}_concrete_powder"); - addColored(DYED, "{color}_glazed_terracotta"); - addColored(DYED, "{color}_shulker_box"); - addColored(DYED, "{color}_stained_glass"); - addColored(DYED, "{color}_stained_glass_pane"); - addColored(DYED, "{color}_terracotta"); - addColored(DYED, "{color}_wool"); - addColoredTags(tag(DYED)::addTags, DYED); - tag(DUSTS) - .addTags( - DUSTS_GLOWSTONE, - DUSTS_REDSTONE - ); - tag(DUSTS_GLOWSTONE).add(GLOWSTONE_DUST); - tag(DUSTS_REDSTONE).add(REDSTONE_DUST); - addColored(DYES, "{color}_dye"); - addColoredTags(tag(DYES)::addTags, DYES); - tag(EGGS) - .add( - EGG, - BLUE_EGG, - BROWN_EGG - ); - tag(ENCHANTING_FUELS).addTag(GEMS_LAPIS); // forge:enchanting_fuels - tag(ENDER_PEARLS).add(ENDER_PEARL); - tag(FEATHERS).add(FEATHER); - tag(FERTILIZERS).add(BONE_MEAL); - tag(FOODS_FRUIT) - .add( - APPLE, - GOLDEN_APPLE, - ENCHANTED_GOLDEN_APPLE, - CHORUS_FRUIT, - MELON_SLICE - ); - tag(FOODS_VEGETABLE) - .add( - GOLDEN_CARROT, - BEETROOT - ) - .add( - CARROT_CROP, - POTATO_CROP - ); - tag(FOODS_BERRY) - .add( - SWEET_BERRY_CROP, - GLOW_BERRY_CROP - ); - tag(FOODS_BREAD).add(BREAD); - tag(FOODS_COOKIE).add(COOKIE); - tag(FOODS_DOUGH); - tag(FOODS_RAW_MEAT) - .add( - BEEF, - PORKCHOP, - CHICKEN, - RABBIT, - MUTTON - ); - tag(FOODS_RAW_FISH) - .add( - COD, - SALMON, - TROPICAL_FISH, - PUFFERFISH - ); - tag(FOODS_COOKED_MEAT) - .add( - COOKED_BEEF, - COOKED_PORKCHOP, - COOKED_CHICKEN, - COOKED_RABBIT, - COOKED_MUTTON - ); - tag(FOODS_COOKED_FISH) - .add( - COOKED_COD, - COOKED_SALMON - ); - tag(FOODS_SOUP) - .add( - BEETROOT_SOUP, - MUSHROOM_STEW, - RABBIT_STEW, - SUSPICIOUS_STEW - ); - tag(FOODS_CANDY); - tag(FOODS_PIE).add(PUMPKIN_PIE); - tag(FOODS_EDIBLE_WHEN_PLACED).add(CAKE); - tag(FOODS_FOOD_POISONING) - .add( - POISONOUS_POTATO, - PUFFERFISH, - SPIDER_EYE, - CHICKEN, - ROTTEN_FLESH - ); - tag(FOODS_GOLDEN) - .add( - GOLDEN_APPLE, - ENCHANTED_GOLDEN_APPLE, - GOLDEN_CARROT - ); - tag(FOODS) - .add( - BAKED_POTATO, - HONEY_BOTTLE, - OMINOUS_BOTTLE, - DRIED_KELP - ) - .addTags( - FOODS_FRUIT, - FOODS_VEGETABLE, - FOODS_BERRY, - FOODS_BREAD, - FOODS_COOKIE, - FOODS_RAW_MEAT, - FOODS_RAW_FISH, - FOODS_COOKED_MEAT, - FOODS_COOKED_FISH, - FOODS_SOUP, - FOODS_CANDY, - FOODS_PIE, - FOODS_GOLDEN, - FOODS_EDIBLE_WHEN_PLACED, - FOODS_FOOD_POISONING - ); - tag(ANIMAL_FOODS) - .addTags( - ItemTags.ARMADILLO_FOOD, - ItemTags.AXOLOTL_FOOD, - ItemTags.BEE_FOOD, - ItemTags.CAMEL_FOOD, - ItemTags.CAT_FOOD, - ItemTags.CHICKEN_FOOD, - ItemTags.COW_FOOD, - ItemTags.FOX_FOOD, - ItemTags.FROG_FOOD, - ItemTags.GOAT_FOOD, - ItemTags.HOGLIN_FOOD, - ItemTags.HORSE_FOOD, - ItemTags.LLAMA_FOOD, - ItemTags.OCELOT_FOOD, - ItemTags.PANDA_FOOD, - ItemTags.PARROT_FOOD, - ItemTags.PIG_FOOD, - ItemTags.PIGLIN_FOOD, - ItemTags.RABBIT_FOOD, - ItemTags.SHEEP_FOOD, - ItemTags.SNIFFER_FOOD, - ItemTags.STRIDER_FOOD, - ItemTags.TURTLE_FOOD, - ItemTags.WOLF_FOOD - ); - tag(GEMS) - .addTags( - GEMS_AMETHYST, - GEMS_DIAMOND, - GEMS_EMERALD, - GEMS_LAPIS, - GEMS_PRISMARINE, - GEMS_QUARTZ - ); - tag(GEMS_AMETHYST).add(AMETHYST_SHARD); - tag(GEMS_DIAMOND).add(DIAMOND); - tag(GEMS_EMERALD).add(EMERALD); - tag(GEMS_LAPIS).add(LAPIS_LAZULI); - tag(GEMS_PRISMARINE).add(PRISMARINE_CRYSTALS); - tag(GEMS_QUARTZ).add(QUARTZ); - tag(GUNPOWDERS).add(GUNPOWDER); - tag(HIDDEN_FROM_RECIPE_VIEWERS); - tag(INGOTS) - .addTags( - INGOTS_COPPER, - INGOTS_GOLD, - INGOTS_IRON, - INGOTS_NETHERITE - ); - tag(INGOTS_COPPER).add(COPPER_INGOT); - tag(INGOTS_GOLD).add(GOLD_INGOT); - tag(INGOTS_IRON).add(IRON_INGOT); - tag(INGOTS_NETHERITE).add(NETHERITE_INGOT); - tag(LEATHERS).add(LEATHER); - tag(MUSHROOMS) - .add( - BROWN_MUSHROOM, - RED_MUSHROOM - ); - tag(MUSIC_DISCS) - .add( - MUSIC_DISC_13, - MUSIC_DISC_CAT, - MUSIC_DISC_BLOCKS, - MUSIC_DISC_CHIRP, - MUSIC_DISC_FAR, - MUSIC_DISC_MALL, - MUSIC_DISC_MELLOHI, - MUSIC_DISC_STAL, - MUSIC_DISC_STRAD, - MUSIC_DISC_WARD, - MUSIC_DISC_11, - MUSIC_DISC_WAIT, - MUSIC_DISC_OTHERSIDE, - MUSIC_DISC_5, - MUSIC_DISC_PIGSTEP, - MUSIC_DISC_RELIC, - MUSIC_DISC_CREATOR, - MUSIC_DISC_CREATOR_MUSIC_BOX, - MUSIC_DISC_PRECIPICE, - MUSIC_DISC_LAVA_CHICKEN, - MUSIC_DISC_TEARS - ); - tag(NETHER_STARS).add(NETHER_STAR); - tag(NUGGETS) - .addTags( - NUGGETS_GOLD, - NUGGETS_IRON, - NUGGETS_COPPER - ); - tag(NUGGETS_COPPER).add(COPPER_NUGGET); - tag(NUGGETS_IRON).add(IRON_NUGGET); - tag(NUGGETS_GOLD).add(GOLD_NUGGET); - tag(POTIONS_BOTTLE) - .add( - POTION, - SPLASH_POTION, - LINGERING_POTION - ); - tag(POTIONS).addTags(POTIONS_BOTTLE); - tag(RAW_MATERIALS) - .addTags( - RAW_MATERIALS_COPPER, - RAW_MATERIALS_GOLD, - RAW_MATERIALS_IRON - ); - tag(RAW_MATERIALS_COPPER).add(RAW_COPPER); - tag(RAW_MATERIALS_GOLD).add(RAW_GOLD); - tag(RAW_MATERIALS_IRON).add(RAW_IRON); - tag(RODS) - .addTags( - RODS_WOODEN, - RODS_BLAZE, - RODS_BREEZE - ); - tag(RODS_BLAZE).add(BLAZE_ROD); - tag(RODS_BREEZE).add(BREEZE_ROD); - tag(RODS_WOODEN).add(STICK); - tag(SEEDS) - .addTags( - SEEDS_BEETROOT, - SEEDS_MELON, - SEEDS_PUMPKIN, - SEEDS_WHEAT - ); - tag(SEEDS_BEETROOT).add(BEETROOT_CROP); - tag(SEEDS_MELON).add(MELON_CROP); - tag(SEEDS_PUMPKIN).add(PUMPKIN_CROP); - tag(SEEDS_WHEAT).add(WHEAT_CROP); - tag(SLIME_BALLS).add(SLIME_BALL); - tag(SHULKER_BOXES) - .add( - SHULKER_BOX - ) - .addAll(BlockItemIds.DYED_SHULKER_BOX.map(BlockItemId::item).asList()); - tag(STRINGS).add(TRIPWIRE); - tag(VILLAGER_JOB_SITES) - .add( - BARREL, - BLAST_FURNACE, - BREWING_STAND, - CARTOGRAPHY_TABLE, - CAULDRON, - COMPOSTER, - FLETCHING_TABLE, - GRINDSTONE, - LECTERN, - LOOM, - SMITHING_TABLE, - SMOKER, - STONECUTTER - ); + (new ForgeBlockItemTagsProvider() { + @Override + protected TagAppender tag(TagKey p_409856_, TagKey p_406371_) { + return new VanillaItemTagsProvider.BlockToItemConverter(ForgeItemTagsProvider.this.tag(p_406371_)); + } + }).run(); + tag(Tags.Items.BONES).add(Items.BONE); + tag(Tags.Items.BRICKS).addTags(Tags.Items.BRICKS_NORMAL, Tags.Items.BRICKS_NETHER, Tags.Items.BRICKS_RESIN); + tag(Tags.Items.BRICKS_NORMAL).add(Items.BRICK); + tag(Tags.Items.BRICKS_NETHER).add(Items.NETHER_BRICK); + tag(Tags.Items.BRICKS_RESIN).add(Items.RESIN_BRICK); + tag(Tags.Items.BUCKETS_EMPTY).add(Items.BUCKET); + tag(Tags.Items.BUCKETS_WATER).add(Items.WATER_BUCKET); + tag(Tags.Items.BUCKETS_LAVA).add(Items.LAVA_BUCKET); + tag(Tags.Items.BUCKETS_MILK).add(Items.MILK_BUCKET); + tag(Tags.Items.BUCKETS_POWDER_SNOW).add(Items.POWDER_SNOW_BUCKET); + tag(Tags.Items.BUCKETS_ENTITY_WATER).add(Items.AXOLOTL_BUCKET, Items.COD_BUCKET, Items.PUFFERFISH_BUCKET, Items.TADPOLE_BUCKET, Items.TROPICAL_FISH_BUCKET, Items.SALMON_BUCKET); + tag(Tags.Items.BUCKETS).addTags(Tags.Items.BUCKETS_EMPTY, Tags.Items.BUCKETS_WATER, Tags.Items.BUCKETS_LAVA, Tags.Items.BUCKETS_MILK, Tags.Items.BUCKETS_POWDER_SNOW, Tags.Items.BUCKETS_ENTITY_WATER); + tag(Tags.Items.CLUMPS) + .addTag(Tags.Items.CLUMPS_RESIN); + tag(Tags.Items.CLUMPS_RESIN) + .add(Items.RESIN_CLUMP); + tag(Tags.Items.CONCRETE_POWDERS) + .add(Items.WHITE_CONCRETE_POWDER, Items.ORANGE_CONCRETE_POWDER, Items.MAGENTA_CONCRETE_POWDER, + Items.LIGHT_BLUE_CONCRETE_POWDER, Items.YELLOW_CONCRETE_POWDER, Items.LIME_CONCRETE_POWDER, + Items.PINK_CONCRETE_POWDER, Items.GRAY_CONCRETE_POWDER, Items.LIGHT_GRAY_CONCRETE_POWDER, + Items.CYAN_CONCRETE_POWDER, Items.PURPLE_CONCRETE_POWDER, Items.BLUE_CONCRETE_POWDER, + Items.BROWN_CONCRETE_POWDER, Items.GREEN_CONCRETE_POWDER, Items.RED_CONCRETE_POWDER, + Items.BLACK_CONCRETE_POWDER); + tag(Tags.Items.CROPS).addTags( + Tags.Items.CROPS_BEETROOT, Tags.Items.CROPS_CACTUS, Tags.Items.CROPS_CARROT, + Tags.Items.CROPS_COCOA_BEAN, Tags.Items.CROPS_MELON, Tags.Items.CROPS_NETHER_WART, + Tags.Items.CROPS_POTATO, Tags.Items.CROPS_PUMPKIN, Tags.Items.CROPS_SUGAR_CANE, + Tags.Items.CROPS_WHEAT + ); + tag(Tags.Items.CROPS_BEETROOT) + .add(Items.BEETROOT); + tag(Tags.Items.CROPS_CACTUS).add(Items.CACTUS); + tag(Tags.Items.CROPS_CARROT) + .add(Items.CARROT); + tag(Tags.Items.CROPS_COCOA_BEAN).add(Items.COCOA_BEANS); + tag(Tags.Items.CROPS_MELON).add(Items.MELON); + tag(Tags.Items.CROPS_NETHER_WART) + .add(Items.NETHER_WART); + tag(Tags.Items.CROPS_POTATO) + .add(Items.POTATO); + tag(Tags.Items.CROPS_PUMPKIN).add(Items.PUMPKIN); + tag(Tags.Items.CROPS_SUGAR_CANE).add(Items.SUGAR_CANE); + tag(Tags.Items.CROPS_WHEAT) + .add(Items.WHEAT); + tag(Tags.Items.DRINKS) + .addTags(Tags.Items.DRINKS_HONEY, Tags.Items.DRINKS_JUICE, Tags.Items.DRINKS_MAGIC, Tags.Items.DRINKS_MILK, + Tags.Items.DRINKS_OMINOUS, Tags.Items.DRINKS_WATER, Tags.Items.DRINKS_WATERY); + tag(Tags.Items.DRINKS_HONEY) + .add(Items.HONEY_BOTTLE); + tag(Tags.Items.DRINKS_JUICE); + tag(Tags.Items.DRINKS_MAGIC) + .add(Items.OMINOUS_BOTTLE, Items.POTION); + tag(Tags.Items.DRINKS_MILK) + .add(Items.MILK_BUCKET); + tag(Tags.Items.DRINKS_OMINOUS) + .add(Items.OMINOUS_BOTTLE); + tag(Tags.Items.DRINKS_WATER); + tag(Tags.Items.DRINKS_WATERY) + .add(Items.POTION); + addColored(Tags.Items.DYED, "{color}_banner"); + addColored(Tags.Items.DYED, "{color}_bed"); + addColored(Tags.Items.DYED, "{color}_candle"); + addColored(Tags.Items.DYED, "{color}_carpet"); + addColored(Tags.Items.DYED, "{color}_concrete"); + addColored(Tags.Items.DYED, "{color}_concrete_powder"); + addColored(Tags.Items.DYED, "{color}_glazed_terracotta"); + addColored(Tags.Items.DYED, "{color}_shulker_box"); + addColored(Tags.Items.DYED, "{color}_stained_glass"); + addColored(Tags.Items.DYED, "{color}_stained_glass_pane"); + addColored(Tags.Items.DYED, "{color}_terracotta"); + addColored(Tags.Items.DYED, "{color}_wool"); + addColoredTags(tag(Tags.Items.DYED)::addTags, Tags.Items.DYED); + tag(Tags.Items.DUSTS).addTags(Tags.Items.DUSTS_GLOWSTONE, Tags.Items.DUSTS_REDSTONE); + tag(Tags.Items.DUSTS_GLOWSTONE) + .add(Items.GLOWSTONE_DUST); + tag(Tags.Items.DUSTS_REDSTONE) + .add(Items.REDSTONE); + addColored(Tags.Items.DYES, "{color}_dye"); + addColoredTags(tag(Tags.Items.DYES)::addTags, Tags.Items.DYES); + tag(Tags.Items.EGGS).add(Items.EGG, Items.BLUE_EGG, Items.BROWN_EGG); + tag(Tags.Items.ENCHANTING_FUELS).addTag(Tags.Items.GEMS_LAPIS); // forge:enchanting_fuels + tag(Tags.Items.ENDER_PEARLS) + .add(Items.ENDER_PEARL); + tag(Tags.Items.FEATHERS) + .add(Items.FEATHER); + tag(Tags.Items.FERTILIZERS).add(Items.BONE_MEAL); + tag(Tags.Items.FOODS_FRUIT).add(Items.APPLE, Items.GOLDEN_APPLE, Items.ENCHANTED_GOLDEN_APPLE, Items.CHORUS_FRUIT, Items.MELON_SLICE); + tag(Tags.Items.FOODS_VEGETABLE).add(Items.CARROT, Items.GOLDEN_CARROT, Items.POTATO, Items.BEETROOT); + tag(Tags.Items.FOODS_BERRY).add(Items.SWEET_BERRIES, Items.GLOW_BERRIES); + tag(Tags.Items.FOODS_BREAD).add(Items.BREAD); + tag(Tags.Items.FOODS_COOKIE).add(Items.COOKIE); + tag(Tags.Items.FOODS_RAW_MEAT).add(Items.BEEF, Items.PORKCHOP, Items.CHICKEN, Items.RABBIT, Items.MUTTON); + tag(Tags.Items.FOODS_RAW_FISH).add(Items.COD, Items.SALMON, Items.TROPICAL_FISH, Items.PUFFERFISH); + tag(Tags.Items.FOODS_COOKED_MEAT).add(Items.COOKED_BEEF, Items.COOKED_PORKCHOP, Items.COOKED_CHICKEN, Items.COOKED_RABBIT, Items.COOKED_MUTTON); + tag(Tags.Items.FOODS_COOKED_FISH).add(Items.COOKED_COD, Items.COOKED_SALMON); + tag(Tags.Items.FOODS_SOUP).add(Items.BEETROOT_SOUP, Items.MUSHROOM_STEW, Items.RABBIT_STEW, Items.SUSPICIOUS_STEW); + tag(Tags.Items.FOODS_CANDY); + tag(Tags.Items.FOODS_PIE).add(Items.PUMPKIN_PIE); + tag(Tags.Items.FOODS_EDIBLE_WHEN_PLACED).add(Items.CAKE); + tag(Tags.Items.FOODS_FOOD_POISONING).add(Items.POISONOUS_POTATO, Items.PUFFERFISH, Items.SPIDER_EYE, Items.CHICKEN, Items.ROTTEN_FLESH); + tag(Tags.Items.FOODS_GOLDEN).add(Items.GOLDEN_APPLE, Items.ENCHANTED_GOLDEN_APPLE, Items.GOLDEN_CARROT); + tag(Tags.Items.FOODS) + .add(Items.BAKED_POTATO, Items.HONEY_BOTTLE, Items.OMINOUS_BOTTLE, Items.DRIED_KELP) + .addTags(Tags.Items.FOODS_FRUIT, Tags.Items.FOODS_VEGETABLE, Tags.Items.FOODS_BERRY, Tags.Items.FOODS_BREAD, Tags.Items.FOODS_COOKIE, + Tags.Items.FOODS_RAW_MEAT, Tags.Items.FOODS_RAW_FISH, Tags.Items.FOODS_COOKED_MEAT, Tags.Items.FOODS_COOKED_FISH, + Tags.Items.FOODS_SOUP, Tags.Items.FOODS_CANDY, Tags.Items.FOODS_PIE, Tags.Items.FOODS_GOLDEN, + Tags.Items.FOODS_EDIBLE_WHEN_PLACED, Tags.Items.FOODS_FOOD_POISONING); + tag(Tags.Items.ANIMAL_FOODS) + .addTags(ItemTags.ARMADILLO_FOOD, ItemTags.AXOLOTL_FOOD, ItemTags.BEE_FOOD, ItemTags.CAMEL_FOOD, + ItemTags.CAT_FOOD, ItemTags.CHICKEN_FOOD, ItemTags.COW_FOOD, ItemTags.FOX_FOOD, ItemTags.FROG_FOOD, + ItemTags.GOAT_FOOD, ItemTags.HOGLIN_FOOD, ItemTags.HORSE_FOOD, ItemTags.LLAMA_FOOD, ItemTags.OCELOT_FOOD, + ItemTags.PANDA_FOOD, ItemTags.PARROT_FOOD, ItemTags.PIG_FOOD, ItemTags.PIGLIN_FOOD, ItemTags.RABBIT_FOOD, + ItemTags.SHEEP_FOOD, ItemTags.SNIFFER_FOOD, ItemTags.STRIDER_FOOD, ItemTags.TURTLE_FOOD, ItemTags.WOLF_FOOD); + tag(Tags.Items.GEMS) + .addTags(Tags.Items.GEMS_AMETHYST, Tags.Items.GEMS_DIAMOND, Tags.Items.GEMS_EMERALD, Tags.Items.GEMS_LAPIS, Tags.Items.GEMS_PRISMARINE, Tags.Items.GEMS_QUARTZ); + tag(Tags.Items.GEMS_AMETHYST) + .add(Items.AMETHYST_SHARD); + tag(Tags.Items.GEMS_DIAMOND) + .add(Items.DIAMOND); + tag(Tags.Items.GEMS_EMERALD) + .add(Items.EMERALD); + tag(Tags.Items.GEMS_LAPIS) + .add(Items.LAPIS_LAZULI); + tag(Tags.Items.GEMS_PRISMARINE) + .add(Items.PRISMARINE_CRYSTALS); + tag(Tags.Items.GEMS_QUARTZ) + .add(Items.QUARTZ); + tag(Tags.Items.GUNPOWDERS).add(Items.GUNPOWDER); + tag(Tags.Items.HIDDEN_FROM_RECIPE_VIEWERS); + tag(Tags.Items.INGOTS) + .addTags(Tags.Items.INGOTS_COPPER, Tags.Items.INGOTS_GOLD, Tags.Items.INGOTS_IRON, Tags.Items.INGOTS_NETHERITE); + tag(Tags.Items.INGOTS_COPPER) + .add(Items.COPPER_INGOT); + tag(Tags.Items.INGOTS_GOLD) + .add(Items.GOLD_INGOT); + tag(Tags.Items.INGOTS_IRON) + .add(Items.IRON_INGOT); + tag(Tags.Items.INGOTS_NETHERITE) + .add(Items.NETHERITE_INGOT); + tag(Tags.Items.LEATHERS) + .add(Items.LEATHER); + tag(Tags.Items.MUSHROOMS) + .add(Items.BROWN_MUSHROOM, Items.RED_MUSHROOM); + tag(Tags.Items.MUSIC_DISCS).add(Items.MUSIC_DISC_13, Items.MUSIC_DISC_CAT, Items.MUSIC_DISC_BLOCKS, Items.MUSIC_DISC_CHIRP, + Items.MUSIC_DISC_FAR, Items.MUSIC_DISC_MALL, Items.MUSIC_DISC_MELLOHI, Items.MUSIC_DISC_STAL, Items.MUSIC_DISC_STRAD, + Items.MUSIC_DISC_WARD, Items.MUSIC_DISC_11, Items.MUSIC_DISC_WAIT, Items.MUSIC_DISC_OTHERSIDE, Items.MUSIC_DISC_5, + Items.MUSIC_DISC_PIGSTEP, Items.MUSIC_DISC_RELIC, Items.MUSIC_DISC_CREATOR, Items.MUSIC_DISC_CREATOR_MUSIC_BOX, + Items.MUSIC_DISC_PRECIPICE, Items.MUSIC_DISC_LAVA_CHICKEN, Items.MUSIC_DISC_TEARS); + tag(Tags.Items.NETHER_STARS) + .add(Items.NETHER_STAR); + tag(Tags.Items.NUGGETS) + .addTags(Tags.Items.NUGGETS_GOLD, Tags.Items.NUGGETS_IRON, Tags.Items.NUGGETS_COPPER); + tag(Tags.Items.NUGGETS_COPPER) + .add(Items.COPPER_NUGGET); + tag(Tags.Items.NUGGETS_IRON) + .add(Items.IRON_NUGGET); + tag(Tags.Items.NUGGETS_GOLD) + .add(Items.GOLD_NUGGET); + tag(Tags.Items.POTIONS_BOTTLE).add(Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION); + tag(Tags.Items.POTIONS).addTags(Tags.Items.POTIONS_BOTTLE); + tag(Tags.Items.RAW_MATERIALS) + .addTags(Tags.Items.RAW_MATERIALS_COPPER, Tags.Items.RAW_MATERIALS_GOLD, Tags.Items.RAW_MATERIALS_IRON); + tag(Tags.Items.RAW_MATERIALS_COPPER) + .add(Items.RAW_COPPER); + tag(Tags.Items.RAW_MATERIALS_GOLD) + .add(Items.RAW_GOLD); + tag(Tags.Items.RAW_MATERIALS_IRON) + .add(Items.RAW_IRON); + tag(Tags.Items.RODS) + .addTags(Tags.Items.RODS_WOODEN, Tags.Items.RODS_BLAZE, Tags.Items.RODS_BREEZE); + tag(Tags.Items.RODS_BLAZE) + .add(Items.BLAZE_ROD); + tag(Tags.Items.RODS_BREEZE).add(Items.BREEZE_ROD); + tag(Tags.Items.RODS_WOODEN) + .add(Items.STICK); + tag(Tags.Items.SEEDS).addTags(Tags.Items.SEEDS_BEETROOT, Tags.Items.SEEDS_MELON, Tags.Items.SEEDS_PUMPKIN, Tags.Items.SEEDS_WHEAT); + tag(Tags.Items.SEEDS_BEETROOT).add(Items.BEETROOT_SEEDS); + tag(Tags.Items.SEEDS_MELON).add(Items.MELON_SEEDS); + tag(Tags.Items.SEEDS_PUMPKIN).add(Items.PUMPKIN_SEEDS); + tag(Tags.Items.SEEDS_WHEAT).add(Items.WHEAT_SEEDS); + tag(Tags.Items.SLIME_BALLS) + .add(Items.SLIME_BALL); + tag(Tags.Items.SHULKER_BOXES) + .add(Items.SHULKER_BOX, Items.WHITE_SHULKER_BOX, Items.ORANGE_SHULKER_BOX, + Items.MAGENTA_SHULKER_BOX, Items.LIGHT_BLUE_SHULKER_BOX, Items.YELLOW_SHULKER_BOX, + Items.LIME_SHULKER_BOX, Items.PINK_SHULKER_BOX, Items.GRAY_SHULKER_BOX, + Items.LIGHT_GRAY_SHULKER_BOX, Items.CYAN_SHULKER_BOX, Items.PURPLE_SHULKER_BOX, + Items.BLUE_SHULKER_BOX, Items.BROWN_SHULKER_BOX, Items.GREEN_SHULKER_BOX, + Items.RED_SHULKER_BOX, Items.BLACK_SHULKER_BOX); + tag(Tags.Items.STRINGS) + .add(Items.STRING); + tag(Tags.Items.VILLAGER_JOB_SITES).add( + Items.BARREL, Items.BLAST_FURNACE, Items.BREWING_STAND, Items.CARTOGRAPHY_TABLE, + Items.CAULDRON, Items.COMPOSTER, Items.FLETCHING_TABLE, Items.GRINDSTONE, + Items.LECTERN, Items.LOOM, Items.SMITHING_TABLE, Items.SMOKER, Items.STONECUTTER); // Tools and Armors - tag(TOOLS_SHIELD).add(SHIELD); - tag(TOOLS_BOW).add(BOW); - tag(TOOLS_BRUSH).add(BRUSH); - tag(TOOLS_CROSSBOW).add(CROSSBOW); - tag(TOOLS_FISHING_ROD).add(FISHING_ROD); - tag(TOOLS_SHEAR).add(SHEARS); - tag(TOOLS_TRIDENT).add(TRIDENT); - tag(TOOLS_MACE).add(MACE); - tag(TOOLS_IGNITER).add(FLINT_AND_STEEL); - tag(MINING_TOOL_TOOLS) - .add( - WOODEN_PICKAXE, - STONE_PICKAXE, - COPPER_PICKAXE, - IRON_PICKAXE, - GOLDEN_PICKAXE, - DIAMOND_PICKAXE, - NETHERITE_PICKAXE - ); - tag(MELEE_WEAPON_TOOLS) - .add( - MACE, - TRIDENT, - WOODEN_SWORD, - STONE_SWORD, - COPPER_SWORD, - GOLDEN_SWORD, - IRON_SWORD, - DIAMOND_SWORD, - NETHERITE_SWORD, - WOODEN_AXE, - STONE_AXE, - COPPER_AXE, - GOLDEN_AXE, - IRON_AXE, - DIAMOND_AXE, - NETHERITE_AXE, - WOODEN_SPEAR, - STONE_SPEAR, - COPPER_SPEAR, - IRON_SPEAR, - GOLDEN_SPEAR, - DIAMOND_SPEAR, - NETHERITE_SPEAR - ); - tag(RANGED_WEAPON_TOOLS) - .add( - BOW, - CROSSBOW, - TRIDENT - ); - tag(TOOLS_WRENCH); - tag(TOOLS) - .addTags( - ItemTags.AXES, - ItemTags.HOES, - ItemTags.PICKAXES, - ItemTags.SHOVELS, - ItemTags.SWORDS - ) - .addTags( - TOOLS_BOW, - TOOLS_BRUSH, - TOOLS_CROSSBOW, - TOOLS_FISHING_ROD, - TOOLS_SHEAR, - TOOLS_IGNITER, - TOOLS_SHIELD, - TOOLS_TRIDENT, - TOOLS_MACE, - MINING_TOOL_TOOLS, - MELEE_WEAPON_TOOLS, - RANGED_WEAPON_TOOLS, - TOOLS_WRENCH - ); - tag(ARMORS_HORSE) - .add( - COPPER_HORSE_ARMOR, - DIAMOND_HORSE_ARMOR, - GOLDEN_HORSE_ARMOR, - IRON_HORSE_ARMOR, - LEATHER_HORSE_ARMOR, - NETHERITE_HORSE_ARMOR - ); - tag(ARMORS_NAUTILUS) - .add( - COPPER_NAUTILUS_ARMOR, - DIAMOND_NAUTILUS_ARMOR, - GOLDEN_NAUTILUS_ARMOR, - IRON_NAUTILUS_ARMOR, - NETHERITE_NAUTILUS_ARMOR - ); - tag(ARMORS_HUMANOID) - .add( - CHAINMAIL_BOOTS, - CHAINMAIL_CHESTPLATE, - CHAINMAIL_HELMET, - CHAINMAIL_LEGGINGS, - COPPER_BOOTS, - COPPER_CHESTPLATE, - COPPER_HELMET, - COPPER_LEGGINGS, - DIAMOND_BOOTS, - DIAMOND_CHESTPLATE, - DIAMOND_HELMET, - DIAMOND_LEGGINGS, - GOLDEN_BOOTS, - GOLDEN_CHESTPLATE, - GOLDEN_HELMET, - GOLDEN_LEGGINGS, - IRON_BOOTS, - IRON_CHESTPLATE, - IRON_HELMET, - IRON_LEGGINGS, - LEATHER_BOOTS, - LEATHER_CHESTPLATE, - LEATHER_HELMET, - LEATHER_LEGGINGS, - NETHERITE_BOOTS, - NETHERITE_CHESTPLATE, - NETHERITE_HELMET, - NETHERITE_LEGGINGS, - TURTLE_HELMET - ); - tag(ARMORS_WOLF).add(WOLF_ARMOR); - tag(ARMORS) - .addTags( - ItemTags.HEAD_ARMOR, - ItemTags.CHEST_ARMOR, - ItemTags.LEG_ARMOR, - ItemTags.FOOT_ARMOR, - ARMORS_HORSE, - ARMORS_NAUTILUS, - ARMORS_WOLF, - ARMORS_HUMANOID - ); - tag(ENCHANTABLES) + tag(Tags.Items.TOOLS_SHIELD) + .add(Items.SHIELD); + tag(Tags.Items.TOOLS_BOW) + .add(Items.BOW); + tag(Tags.Items.TOOLS_BRUSH).add(Items.BRUSH); + tag(Tags.Items.TOOLS_CROSSBOW) + .add(Items.CROSSBOW); + tag(Tags.Items.TOOLS_FISHING_ROD) + .add(Items.FISHING_ROD); + tag(Tags.Items.TOOLS_SHEAR) + .add(Items.SHEARS); + tag(Tags.Items.TOOLS_SPEAR).add(Items.TRIDENT); + tag(Tags.Items.TOOLS_MACE).add(Items.MACE); + tag(Tags.Items.TOOLS_IGNITER).add(Items.FLINT_AND_STEEL); + tag(Tags.Items.MINING_TOOL_TOOLS).add(Items.WOODEN_PICKAXE, Items.STONE_PICKAXE, Items.COPPER_PICKAXE, Items.IRON_PICKAXE, Items.GOLDEN_PICKAXE, Items.DIAMOND_PICKAXE, Items.NETHERITE_PICKAXE); + tag(Tags.Items.MELEE_WEAPON_TOOLS).add( + Items.MACE, Items.TRIDENT, + Items.WOODEN_SWORD, Items.STONE_SWORD, Items.COPPER_SWORD, Items.GOLDEN_SWORD, Items.IRON_SWORD, Items.DIAMOND_SWORD, Items.NETHERITE_SWORD, + Items.WOODEN_AXE, Items.STONE_AXE, Items.COPPER_AXE, Items.GOLDEN_AXE, Items.IRON_AXE, Items.DIAMOND_AXE, Items.NETHERITE_AXE + ); + tag(Tags.Items.RANGED_WEAPON_TOOLS).add(Items.BOW, Items.CROSSBOW, Items.TRIDENT); + tag(Tags.Items.TOOLS_WRENCH); + tag(Tags.Items.TOOLS) + .addTags(ItemTags.AXES, ItemTags.HOES, ItemTags.PICKAXES, ItemTags.SHOVELS, ItemTags.SWORDS) + .addTags(Tags.Items.TOOLS_BOW, Tags.Items.TOOLS_BRUSH, Tags.Items.TOOLS_CROSSBOW, Tags.Items.TOOLS_FISHING_ROD, Tags.Items.TOOLS_SHEAR, Tags.Items.TOOLS_IGNITER, Tags.Items.TOOLS_SHIELD, Tags.Items.TOOLS_SPEAR, Tags.Items.TOOLS_MACE, Tags.Items.MINING_TOOL_TOOLS, Tags.Items.MELEE_WEAPON_TOOLS, Tags.Items.RANGED_WEAPON_TOOLS, Tags.Items.TOOLS_WRENCH); + tag(Tags.Items.ARMORS_HORSE) + .add( + Items.COPPER_HORSE_ARMOR, + Items.DIAMOND_HORSE_ARMOR, + Items.GOLDEN_HORSE_ARMOR, + Items.IRON_HORSE_ARMOR, + Items.LEATHER_HORSE_ARMOR, + Items.NETHERITE_HORSE_ARMOR + ); + tag(Tags.Items.ARMORS_NAUTILUS) + .add( + Items.COPPER_NAUTILUS_ARMOR, + Items.DIAMOND_NAUTILUS_ARMOR, + Items.GOLDEN_NAUTILUS_ARMOR, + Items.IRON_NAUTILUS_ARMOR, + Items.NETHERITE_NAUTILUS_ARMOR + ); + tag(Tags.Items.ARMORS_HUMANOID) + .add(Items.CHAINMAIL_BOOTS, Items.CHAINMAIL_CHESTPLATE, Items.CHAINMAIL_HELMET, Items.CHAINMAIL_LEGGINGS, + Items.COPPER_BOOTS, Items.COPPER_CHESTPLATE, Items.COPPER_HELMET, Items.COPPER_LEGGINGS, + Items.DIAMOND_BOOTS, Items.DIAMOND_CHESTPLATE, Items.DIAMOND_HELMET, Items.DIAMOND_LEGGINGS, + Items.GOLDEN_BOOTS, Items.GOLDEN_CHESTPLATE, Items.GOLDEN_HELMET, Items.GOLDEN_LEGGINGS, + Items.IRON_BOOTS, Items.IRON_CHESTPLATE, Items.IRON_HELMET, Items.IRON_LEGGINGS, + Items.LEATHER_BOOTS, Items.LEATHER_CHESTPLATE, Items.LEATHER_HELMET, Items.LEATHER_LEGGINGS, + Items.NETHERITE_BOOTS, Items.NETHERITE_CHESTPLATE, Items.NETHERITE_HELMET, Items.NETHERITE_LEGGINGS, + Items.TURTLE_HELMET); + tag(Tags.Items.ARMORS_WOLF) + .add(Items.WOLF_ARMOR); + tag(Tags.Items.ARMORS) + .addTags(ItemTags.HEAD_ARMOR, ItemTags.CHEST_ARMOR, ItemTags.LEG_ARMOR, ItemTags.FOOT_ARMOR, + Tags.Items.ARMORS_HORSE, Tags.Items.ARMORS_NAUTILUS, Tags.Items.ARMORS_WOLF, Tags.Items.ARMORS_HUMANOID); + tag(Tags.Items.ENCHANTABLES) .addTags( ItemTags.ARMOR_ENCHANTABLE, ItemTags.EQUIPPABLE_ENCHANTABLE, @@ -573,22 +310,18 @@ public final class ForgeItemTagsProvider extends VanillaItemTagsProvider { ItemTags.DURABILITY_ENCHANTABLE, ItemTags.VANISHING_ENCHANTABLE ); - tag(SEEDS) - .addTags( - SEEDS_BEETROOT, - SEEDS_MELON, - SEEDS_PUMPKIN, - SEEDS_WHEAT, - SEEDS_PITCHER_PLANT, - SEEDS_TORCHFLOWER - ); - tag(SEEDS_BEETROOT).add(BEETROOT_CROP); - tag(SEEDS_MELON).add(MELON_CROP); - tag(SEEDS_PUMPKIN).add(PUMPKIN_CROP); - tag(SEEDS_WHEAT).add(WHEAT_CROP); - tag(SEEDS_PITCHER_PLANT).add(PITCHER_CROP); - tag(SEEDS_TORCHFLOWER).add(TORCHFLOWER_CROP); - tag(BONES).add(BONE); + tag(Tags.Items.SEEDS) + .addTags( + Tags.Items.SEEDS_BEETROOT, Tags.Items.SEEDS_MELON, Tags.Items.SEEDS_PUMPKIN, + Tags.Items.SEEDS_WHEAT, Tags.Items.SEEDS_PITCHER_PLANT, Tags.Items.SEEDS_TORCHFLOWER); + tag(Tags.Items.SEEDS_BEETROOT).add(Items.BEETROOT_SEEDS); + tag(Tags.Items.SEEDS_MELON).add(Items.MELON_SEEDS); + tag(Tags.Items.SEEDS_PUMPKIN).add(Items.PUMPKIN_SEEDS); + tag(Tags.Items.SEEDS_WHEAT).add(Items.WHEAT_SEEDS); + tag(Tags.Items.SEEDS_PITCHER_PLANT).add(Items.PITCHER_POD); + tag(Tags.Items.SEEDS_TORCHFLOWER).add(Items.TORCHFLOWER_SEEDS); + + tag(Tags.Items.BONES).add(Items.BONE); // Backwards compat definitions for pre-1.21 legacy `forge:` tags. // TODO: Remove backwards compat tag entries in 1.22 addColored(tag(forgeItemTagKey("dyes"))::addTags, forgeItemTagKey("dyes"), "{color}_dye"); @@ -602,8 +335,7 @@ public final class ForgeItemTagsProvider extends VanillaItemTagsProvider { Item item = BuiltInRegistries.ITEM.getValue(key); if (item == null || item == Items.AIR) throw new IllegalStateException("Unknown vanilla item: " + key); - tag(tag) - .add(ResourceKey.create(Registries.ITEM, key)); + tag(tag).add(item); } } @@ -615,8 +347,7 @@ public final class ForgeItemTagsProvider extends VanillaItemTagsProvider { Item item = ForgeRegistries.ITEMS.getValue(key); if (item == null || item == Items.AIR) throw new IllegalStateException("Unknown vanilla item: " + key); - tag(tag) - .add(ResourceKey.create(Registries.ITEM, key)); + tag(tag).add(item); consumer.accept(tag); } } diff --git a/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java index 13d6ff36c7..2e8fe381cd 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeLootTableProvider.java @@ -5,7 +5,7 @@ package net.minecraftforge.common.data; -import net.minecraft.advancements.predicates.ItemPredicate; +import net.minecraft.advancements.criterion.ItemPredicate; import net.minecraft.core.HolderLookup; import net.minecraft.core.Registry; import net.minecraft.data.PackOutput; diff --git a/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java index e35675b7bd..d5f8b1113d 100644 --- a/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java +++ b/src/main/java/net/minecraftforge/common/data/ForgeRecipeProvider.java @@ -22,7 +22,6 @@ import net.minecraft.data.recipes.packs.VanillaRecipeProvider; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; -import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; @@ -90,7 +89,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { replace(Blocks.COBBLED_DEEPSLATE, Tags.Items.COBBLESTONES_DEEPSLATE); replace(Items.STRING, Tags.Items.STRINGS); - exclude(getConversionRecipeName(Blocks.WOOL.pick(DyeColor.WHITE), Items.STRING)); + exclude(getConversionRecipeName(Blocks.WHITE_WOOL, Items.STRING)); exclude(Blocks.GOLD_BLOCK); exclude(Items.GOLD_NUGGET); @@ -99,7 +98,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider { exclude(Blocks.DIAMOND_BLOCK); exclude(Blocks.EMERALD_BLOCK); exclude(Blocks.NETHERITE_BLOCK); - Blocks.COPPER_BLOCK.forEach(this::exclude); + exclude(Blocks.COPPER_BLOCK); exclude(Blocks.AMETHYST_BLOCK); exclude(Blocks.COBBLESTONE_STAIRS); diff --git a/src/main/java/net/minecraftforge/common/data/ForgeSpriteSourceProvider.java b/src/main/java/net/minecraftforge/common/data/ForgeSpriteSourceProvider.java new file mode 100644 index 0000000000..15a5fa84b1 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/ForgeSpriteSourceProvider.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common.data; + +import net.minecraft.client.renderer.texture.atlas.sources.SingleFile; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.Identifier; + +import java.util.Optional; + +public class ForgeSpriteSourceProvider extends SpriteSourceProvider +{ + public ForgeSpriteSourceProvider(PackOutput output, ExistingFileHelper fileHelper) + { + super(output, fileHelper, "forge"); + } + + @Override + protected void addSources() + { + atlas(SpriteSourceProvider.BLOCKS_ATLAS).addSource(new SingleFile(Identifier.parse("forge:white"), Optional.empty())); + } +} diff --git a/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java b/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java index d4395ca4aa..3ee39c34a7 100644 --- a/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java +++ b/src/main/java/net/minecraftforge/common/data/JsonCodecProvider.java @@ -7,6 +7,7 @@ package net.minecraftforge.common.data; import com.google.common.collect.ImmutableList; import com.google.gson.JsonElement; +import com.mojang.logging.LogUtils; import com.mojang.serialization.Codec; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.JsonOps; @@ -24,6 +25,7 @@ import net.minecraft.resources.Identifier; import net.minecraft.server.packs.PackType; import net.minecraftforge.common.crafting.conditions.ICondition; import net.minecraftforge.common.data.ExistingFileHelper.ResourceType; +import org.slf4j.Logger; /** *

Dataprovider for using a Codec to generate jsons. @@ -34,7 +36,9 @@ import net.minecraftforge.common.data.ExistingFileHelper.ResourceType; * * @param the type of thing being generated. */ -public class JsonCodecProvider implements DataProvider { +public class JsonCodecProvider implements DataProvider +{ + private static final Logger LOGGER = LogUtils.getLogger(); protected final PackOutput output; protected final ExistingFileHelper existingFileHelper; protected final String modid; @@ -54,11 +58,14 @@ public class JsonCodecProvider implements DataProvider { * @param entries Map of named entries to serialize to jsons. Paths for values are derived from the Identifier's entryid:entrypath as specified above. */ public JsonCodecProvider(PackOutput output, ExistingFileHelper existingFileHelper, String modid, DynamicOps dynamicOps, PackType packType, - String directory, Codec codec, Map entries) { + String directory, Codec codec, Map entries) + { // Track generated data so other dataproviders can validate if needed. final ResourceType resourceType = new ResourceType(packType, ".json", directory); for (Identifier id : entries.keySet()) + { existingFileHelper.trackGenerated(id, resourceType); + } this.output = output; this.existingFileHelper = existingFileHelper; this.modid = modid; @@ -70,7 +77,8 @@ public class JsonCodecProvider implements DataProvider { } @Override - public CompletableFuture run(final CachedOutput cache) { + public CompletableFuture run(final CachedOutput cache) + { final Path outputFolder = this.output.getOutputFolder(this.packType == PackType.CLIENT_RESOURCES ? PackOutput.Target.RESOURCE_PACK : PackOutput.Target.DATA_PACK); @@ -100,12 +108,14 @@ public class JsonCodecProvider implements DataProvider { return CompletableFuture.allOf(futuresBuilder.build().toArray(CompletableFuture[]::new)); } - protected void gather(BiConsumer consumer) { + protected void gather(BiConsumer consumer) + { this.entries.forEach(consumer); } @Override - public String getName() { + public String getName() + { return String.format("%s generator for %s", this.directory, this.modid); } @@ -115,7 +125,8 @@ public class JsonCodecProvider implements DataProvider { * Null or empty arrays will not be written, and if the top-level json type is not JsonObject, attempting to add conditions will error. * @param conditions The name->condition map to apply. */ - public JsonCodecProvider setConditions(Map conditions) { + public JsonCodecProvider setConditions(Map conditions) + { this.conditions = conditions; return this; } diff --git a/src/main/java/net/minecraftforge/common/data/SpriteSourceProvider.java b/src/main/java/net/minecraftforge/common/data/SpriteSourceProvider.java new file mode 100644 index 0000000000..9d3cbc21e5 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/SpriteSourceProvider.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) Forge Development LLC and contributors + * SPDX-License-Identifier: LGPL-2.1-only + */ + +package net.minecraftforge.common.data; + +import com.mojang.serialization.JsonOps; +import net.minecraft.client.renderer.texture.atlas.SpriteSource; +import net.minecraft.client.renderer.texture.atlas.SpriteSources; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.PackType; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + *

Data provider for atlas configuration files.
+ * An atlas configuration is bound to a specific texture atlas such as the {@code minecraft:blocks} atlas and + * allows adding additional textures to the atlas by adding {@link SpriteSource}s to the configuration.

+ *

See {@link SpriteSources} for the available sources and the constants in this class for the + * atlases used in vanilla Minecraft

+ */ +public abstract class SpriteSourceProvider extends JsonCodecProvider> +{ + protected static final Identifier BLOCKS_ATLAS = Identifier.withDefaultNamespace("blocks"); + protected static final Identifier BANNER_PATTERNS_ATLAS = Identifier.withDefaultNamespace("banner_patterns"); + protected static final Identifier BEDS_ATLAS = Identifier.withDefaultNamespace("beds"); + protected static final Identifier CHESTS_ATLAS = Identifier.withDefaultNamespace("chests"); + protected static final Identifier SHIELD_PATTERNS_ATLAS = Identifier.withDefaultNamespace("shield_patterns"); + protected static final Identifier SHULKER_BOXES_ATLAS = Identifier.withDefaultNamespace("shulker_boxes"); + protected static final Identifier SIGNS_ATLAS = Identifier.withDefaultNamespace("signs"); + protected static final Identifier MOB_EFFECTS_ATLAS = Identifier.withDefaultNamespace("mob_effects"); + protected static final Identifier PAINTINGS_ATLAS = Identifier.withDefaultNamespace("paintings"); + protected static final Identifier PARTICLES_ATLAS = Identifier.withDefaultNamespace("particles"); + + private final Map atlases = new HashMap<>(); + + public SpriteSourceProvider(PackOutput output, ExistingFileHelper fileHelper, String modid) + { + super(output, fileHelper, modid, JsonOps.INSTANCE, PackType.CLIENT_RESOURCES, "atlases", SpriteSources.FILE_CODEC, Map.of()); + } + + @Override + protected final void gather(BiConsumer> consumer) + { + addSources(); + for (var entry : atlases.entrySet()) { + Identifier atlas = entry.getKey(); + SourceList srcList = entry.getValue(); + consumer.accept(atlas, srcList.sources); + } + } + + protected abstract void addSources(); + + /** + * Get or create a {@link SourceList} for the given atlas + * @param atlas The texture atlas the sources should be added to, see constants at the top for the format + * and the vanilla atlases + * @return an existing {@code SourceList} for the given atlas or a new one if not present yet + */ + protected final SourceList atlas(Identifier atlas) + { + return atlases.computeIfAbsent(atlas, $ -> new SourceList()); + } + + protected static final class SourceList + { + private final List sources = new ArrayList<>(); + + /** + * Add the given {@link SpriteSource} to this atlas configuration + * @param source The {@code SpriteSource} to be added + */ + public SourceList addSource(SpriteSource source) + { + sources.add(source); + return this; + } + } +} diff --git a/src/main/java/net/minecraftforge/common/data/WrappedCombinedAppender.java b/src/main/java/net/minecraftforge/common/data/WrappedCombinedAppender.java deleted file mode 100644 index d8f35f59ab..0000000000 --- a/src/main/java/net/minecraftforge/common/data/WrappedCombinedAppender.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.common.data; - -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Function; -import java.util.stream.Stream; - -import net.minecraft.data.tags.BlockItemTagsProvider.CombinedAppender; -import net.minecraft.data.tags.TagAppender; -import net.minecraft.references.BlockItemId; -import net.minecraft.resources.ResourceKey; -import net.minecraft.tags.BlockItemTagId; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; - -public class WrappedCombinedAppender implements CombinedAppender { - private final Function> mapper; - private final Function> tagMapper; - private final TagAppender appender; - - public static WrappedCombinedAppender item(TagAppender appender) { - return new WrappedCombinedAppender(appender, BlockItemId::item, BlockItemTagId::item); - } - public static WrappedCombinedAppender block(TagAppender appender) { - return new WrappedCombinedAppender(appender, BlockItemId::block, BlockItemTagId::block); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected WrappedCombinedAppender( - TagAppender appender, - Function> mapper, - Function> tagMapper - ) { - this.appender = (TagAppender)appender; - this.mapper = (Function>)(Function)mapper; - this.tagMapper = (Function>)(Function)tagMapper; - } - - @Override - public WrappedCombinedAppender add(final BlockItemId... ids) { - return this.addAll(Arrays.stream(ids)); - } - - @Override - public WrappedCombinedAppender add(final BlockItemTagId... ids) { - for (var id : ids) - addTag(id); - return this; - } - - @Override - public WrappedCombinedAppender addAll(final Collection ids) { - return this.addAll(ids.stream()); - } - - @Override - public WrappedCombinedAppender addAll(Stream ids) { - appender.addAll(ids.map(mapper)); - return this; - } - - @Override - public WrappedCombinedAppender addTag(BlockItemTagId id) { - appender.addTag(tagMapper.apply(id)); - return this; - } - - public WrappedCombinedAppender addOptional(BlockItemId... ids) { - for (var id : ids) - appender.addOptional(mapper.apply(id)); - return this; - } - - public WrappedCombinedAppender addOptional(BlockItemTagId... ids) { - for (var id : ids) - appender.addOptionalTag(tagMapper.apply(id)); - return this; - } - -} diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeAbstractMinecart.java b/src/main/java/net/minecraftforge/common/extensions/IForgeAbstractMinecart.java index 95fe90bacd..9705384ea1 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeAbstractMinecart.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeAbstractMinecart.java @@ -13,7 +13,7 @@ import net.minecraft.util.Mth; public interface IForgeAbstractMinecart { public static float DEFAULT_MAX_SPEED_AIR_LATERAL = 0.4f; public static float DEFAULT_MAX_SPEED_AIR_VERTICAL = -1.0f; - public static float DEFAULT_AIR_DRAG = 0.95f; + public static double DEFAULT_AIR_DRAG = 0.95f; private AbstractMinecart self() { return (AbstractMinecart)this; @@ -72,7 +72,8 @@ public interface IForgeAbstractMinecart { void setMaxSpeedAirLateral(float value); float getMaxSpeedAirVertical(); void setMaxSpeedAirVertical(float value); - void setAirDrag(float value); + double getDragAir(); + void setDragAir(double value); /** * Called from Detector Rails to retrieve a redstone power level for comparators. diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java index 2647f0d75b..6139cae4e3 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeBlockEntity.java @@ -6,6 +6,7 @@ package net.minecraftforge.common.extensions; import net.minecraft.network.Connection; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java b/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java index 20f444e0a7..e342d011f7 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeEntity.java @@ -9,6 +9,7 @@ import java.util.Collection; import java.util.function.BiPredicate; import net.minecraft.sounds.SoundEvent; +import net.minecraft.tags.TagKey; import net.minecraft.util.ProblemReporter; import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.entity.player.Player; @@ -22,6 +23,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; +import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.storage.TagValueInput; import net.minecraft.world.level.storage.TagValueOutput; diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java b/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java index ebe3958717..05227969b7 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeGameTestHelper.java @@ -18,7 +18,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.util.Util; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.state.BlockState; @@ -151,17 +151,17 @@ public interface IForgeGameTestHelper { * Create a mock server player in creative mode */ default ServerPlayer makeMockServerPlayer() { - return makeMockServerPlayerFull(GameType.CREATIVE); + return makeMockServerPlayer(GameType.CREATIVE); } /** * Create a mock server player in creative mode */ default ServerPlayer makeMockServerPlayer(boolean creative) { - return makeMockServerPlayerFull(creative ? GameType.CREATIVE : GameType.SURVIVAL); + return makeMockServerPlayer(creative ? GameType.CREATIVE : GameType.SURVIVAL); } - default ServerPlayer makeMockServerPlayerFull(GameType type) { + default ServerPlayer makeMockServerPlayer(GameType type) { var level = self().getLevel(); var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"), false); var player = new ServerPlayer(level.getServer(), level, cookie.gameProfile(), cookie.clientInformation()); @@ -182,7 +182,7 @@ public interface IForgeGameTestHelper { */ default void addEventListener(EventBus bus, Consumer consumer) { var key = bus.addListener(consumer); - self().addCleanup(_ -> bus.removeListener(key)); + self().addCleanup(success -> bus.removeListener(key)); } /** @@ -190,7 +190,7 @@ public interface IForgeGameTestHelper { */ default void addMutableListener(EventBus bus, Consumer consumer) { var key = bus.addListener(consumer); - self().addCleanup(_ -> bus.removeListener(key)); + self().addCleanup(success -> bus.removeListener(key)); } /** @@ -198,7 +198,7 @@ public interface IForgeGameTestHelper { */ default void addRecordListener(EventBus bus, Consumer consumer) { var key = bus.addListener(consumer); - self().addCleanup(_ -> bus.removeListener(key)); + self().addCleanup(success -> bus.removeListener(key)); } /** @@ -206,7 +206,7 @@ public interface IForgeGameTestHelper { */ default void registerEventListener(Object handler) { var keys = MinecraftForge.EVENT_BUS.register(handler); - self().addCleanup(_ -> MinecraftForge.EVENT_BUS.unregister(keys)); + self().addCleanup(success -> MinecraftForge.EVENT_BUS.unregister(keys)); } /** @@ -276,7 +276,7 @@ public interface IForgeGameTestHelper { default void removeAllItemEntitiesInRange(BlockPos pos, double range) { BlockPos blockpos = this.self().absolutePos(pos); - for (ItemEntity itemEntity : this.self().getLevel().getEntities(EntityTypes.ITEM, new AABB(blockpos).inflate(range), Entity::isAlive)) { + for (ItemEntity itemEntity : this.self().getLevel().getEntities(EntityType.ITEM, new AABB(blockpos).inflate(range), Entity::isAlive)) { itemEntity.remove(Entity.RemovalReason.DISCARDED); } } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java b/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java index 9180ca134f..15e3dbd64e 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeHolderSet.java @@ -32,13 +32,13 @@ public interface IForgeHolderSet { return this instanceof ListBacked listBacked ? listBacked.unwrap().map( // serializes as tag name if this holderset is named - _ -> SerializationType.STRING, + 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 ? 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, - _ -> SerializationType.OBJECT) + value -> SerializationType.OBJECT) : SerializationType.LIST) : SerializationType.UNKNOWN; // unsupported holderset impl, could be anything } diff --git a/src/main/java/net/minecraftforge/common/extensions/IForgeTagAppender.java b/src/main/java/net/minecraftforge/common/extensions/IForgeTagAppender.java index 411783fb40..f8754549bf 100644 --- a/src/main/java/net/minecraftforge/common/extensions/IForgeTagAppender.java +++ b/src/main/java/net/minecraftforge/common/extensions/IForgeTagAppender.java @@ -11,9 +11,9 @@ import net.minecraft.resources.Identifier; import net.minecraft.tags.TagBuilder; import net.minecraft.tags.TagKey; -public interface IForgeTagAppender { - private TagAppender self() { - return (TagAppender)this; +public interface IForgeTagAppender { + private TagAppender self() { + return (TagAppender)this; } /** @@ -28,8 +28,33 @@ public interface IForgeTagAppender { return "unknown"; } + /** + * Adds a registry entry to the tag json's remove list. Callable during datageneration. + * + * @param entry The entry to remove + * @return The builder for chaining + */ + default TagAppender remove(final E entry) { + throw new UnsupportedOperationException("TagAppender.remove is not implemented in class: " + this.getClass()); + } + + /** + * Adds multiple registry entries to the tag json's remove list. Callable during datageneration. + * + * @param entries The entries to remove + * @return The builder for chaining + */ @SuppressWarnings("unchecked") - default TagAppender addTags(TagKey... values) { + default TagAppender remove(final E first, final E...entries) { + this.remove(first); + for (E entry : entries) + this.remove(entry); + return self(); + } + + + @SuppressWarnings("unchecked") + default TagAppender addTags(TagKey... values) { var builder = self(); for (TagKey value : values) { builder.addTag(value); @@ -37,24 +62,24 @@ public interface IForgeTagAppender { return builder; } - default TagAppender addOptional(Identifier location) { + default TagAppender addOptional(Identifier location) { self().getInternalBuilder().addOptionalElement(location); return self(); } @SuppressWarnings("unchecked") - default TagAppender addOptionalTags(TagKey... values) { + default TagAppenderaddOptionalTags(TagKey... values) { var builder = self(); for (var value : values) builder.addOptionalTag(value); return builder; } - default TagAppender replace() { + default TagAppender replace() { return replace(true); } - default TagAppender replace(boolean value) { + default TagAppender replace(boolean value) { self().getInternalBuilder().setReplace(value); return self(); } @@ -64,7 +89,7 @@ public interface IForgeTagAppender { * @param location The ID of the element to remove * @return The builder for chaining */ - default TagAppender remove(final Identifier location) { + default TagAppender remove(final Identifier location) { var builder = self(); builder.getInternalBuilder().removeElement(location, builder.getSourceName()); return builder; @@ -75,7 +100,7 @@ public interface IForgeTagAppender { * @param locations The IDs of the elements to remove * @return The builder for chaining */ - default TagAppender remove(final Identifier first, final Identifier... locations) { + default TagAppender remove(final Identifier first, final Identifier... locations) { this.remove(first); for (var location : locations) this.remove(location); @@ -88,7 +113,7 @@ public interface IForgeTagAppender { * @param resourceKey The resource key of the element to remove * @return The appender for chaining */ - default TagAppender remove(final ResourceKey resourceKey) { + default TagAppender remove(final ResourceKey resourceKey) { this.remove(resourceKey.identifier()); return self(); } @@ -98,7 +123,7 @@ public interface IForgeTagAppender { * @param tag The ID of the tag to remove * @return The builder for chaining */ - default TagAppender remove(TagKey tag) { + default TagAppender remove(TagKey tag) { var builder = self(); builder.getInternalBuilder().removeTag(tag.location(), builder.getSourceName()); return builder; @@ -110,7 +135,7 @@ public interface IForgeTagAppender { * @return The builder for chaining */ @SuppressWarnings("unchecked") - default TagAppender remove(TagKey first, TagKey...tags) { + default TagAppender remove(TagKey first, TagKey...tags) { this.remove(first); for (var tag : tags) this.remove(tag); diff --git a/src/main/java/net/minecraftforge/common/util/BrainBuilder.java b/src/main/java/net/minecraftforge/common/util/BrainBuilder.java index 096198c3f4..365d7d6fee 100644 --- a/src/main/java/net/minecraftforge/common/util/BrainBuilder.java +++ b/src/main/java/net/minecraftforge/common/util/BrainBuilder.java @@ -110,7 +110,7 @@ public class BrainBuilder { /** You may use this as a helper method for adding a behavior to an Activity by priority to an entity's brain. */ public void addBehaviorToActivityByPriority(Integer priority, Activity activity, BehaviorControl behaviorControl) { - this.availableBehaviorsByPriority.computeIfAbsent(priority, (_) -> Maps.newHashMap()).computeIfAbsent(activity, (_) -> Sets.newLinkedHashSet()).add(behaviorControl); + this.availableBehaviorsByPriority.computeIfAbsent(priority, (i) -> Maps.newHashMap()).computeIfAbsent(activity, (a) -> Sets.newLinkedHashSet()).add(behaviorControl); } /** You may use this as a helper method for adding memory requirements for an Activity to an entity's brain. */ @@ -129,12 +129,12 @@ public class BrainBuilder { @ApiStatus.Internal public void addAvailableBehaviorsByPriorityFrom(Map>>> addFrom) { - addFrom.forEach(((priority, activitySetMap) -> activitySetMap.forEach(((activity, behaviorControls) -> this.availableBehaviorsByPriority.computeIfAbsent(priority, (_) -> Maps.newHashMap()).computeIfAbsent(activity, (_) -> Sets.newLinkedHashSet()).addAll(behaviorControls))))); + addFrom.forEach(((priority, activitySetMap) -> activitySetMap.forEach(((activity, behaviorControls) -> this.availableBehaviorsByPriority.computeIfAbsent(priority, (p) -> Maps.newHashMap()).computeIfAbsent(activity, (a) -> Sets.newLinkedHashSet()).addAll(behaviorControls))))); } @ApiStatus.Internal public void addAvailableBehaviorsByPriorityTo(Map>>> addTo){ - this.availableBehaviorsByPriority.forEach(((priority, activitySetMap) -> activitySetMap.forEach(((activity, behaviorControls) -> addTo.computeIfAbsent(priority, (_) -> Maps.newHashMap()).computeIfAbsent(activity, (_) -> Sets.newLinkedHashSet()).addAll(behaviorControls))))); + this.availableBehaviorsByPriority.forEach(((priority, activitySetMap) -> activitySetMap.forEach(((activity, behaviorControls) -> addTo.computeIfAbsent(priority, (p) -> Maps.newHashMap()).computeIfAbsent(activity, (a) -> Sets.newLinkedHashSet()).addAll(behaviorControls))))); } @ApiStatus.Internal @@ -158,11 +158,11 @@ public class BrainBuilder { } private static void addMemoriesToEraseWhenActivityStoppedInternal(Map>> activityMemoriesToEraseWhenStopped, Activity activity, Collection> memories) { - activityMemoriesToEraseWhenStopped.computeIfAbsent(activity, (_) -> Sets.newHashSet()).addAll(memories); + activityMemoriesToEraseWhenStopped.computeIfAbsent(activity, (a) -> Sets.newHashSet()).addAll(memories); } private static void addRequirementsToActivityInternal(Map, MemoryStatus>>> activityRequirements, Activity activity, Collection, MemoryStatus>> requirements) { - activityRequirements.computeIfAbsent(activity, (_) -> Sets.newHashSet()).addAll(requirements); + activityRequirements.computeIfAbsent(activity, (a) -> Sets.newHashSet()).addAll(requirements); } @ApiStatus.Internal diff --git a/src/main/java/net/minecraftforge/common/util/JsonUtils.java b/src/main/java/net/minecraftforge/common/util/JsonUtils.java index 302e86d8e1..cbb5beabff 100644 --- a/src/main/java/net/minecraftforge/common/util/JsonUtils.java +++ b/src/main/java/net/minecraftforge/common/util/JsonUtils.java @@ -24,6 +24,7 @@ import com.google.gson.JsonSerializer; import com.google.gson.JsonSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.serialization.JsonOps; import net.minecraft.nbt.TagParser; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.GsonHelper; diff --git a/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java b/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java index 5d47c42ba8..8020174ac0 100644 --- a/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java +++ b/src/main/java/net/minecraftforge/common/util/LogicalSidedProvider.java @@ -6,7 +6,6 @@ package net.minecraftforge.common.util; import net.minecraft.client.Minecraft; -import net.minecraft.network.PacketProcessor; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; import net.minecraft.util.thread.BlockableEventLoop; @@ -21,8 +20,7 @@ import org.jetbrains.annotations.ApiStatus; public class LogicalSidedProvider { public static final LogicalSidedProvider> WORKQUEUE = new LogicalSidedProvider<>(Supplier::get, Supplier::get); - public static final LogicalSidedProvider> CLIENTWORLD = new LogicalSidedProvider<>((c)-> Optional.of(c.get().level), (_)->Optional.empty()); - public static final LogicalSidedProvider PACKETS = new LogicalSidedProvider<>(client -> client.get().packetProcessor(), server -> server.get().packetProcessor()); + public static final LogicalSidedProvider> CLIENTWORLD = new LogicalSidedProvider<>((c)-> Optional.of(c.get().level), (s)->Optional.empty()); public T get(LogicalSide side) { return side == LogicalSide.CLIENT ? clientSide.apply(client) : serverSide.apply(server); diff --git a/src/main/java/net/minecraftforge/common/util/MutableHashedLinkedMap.java b/src/main/java/net/minecraftforge/common/util/MutableHashedLinkedMap.java index fdc4d70e39..5cea000ae2 100644 --- a/src/main/java/net/minecraftforge/common/util/MutableHashedLinkedMap.java +++ b/src/main/java/net/minecraftforge/common/util/MutableHashedLinkedMap.java @@ -60,7 +60,7 @@ public class MutableHashedLinkedMap implements Iterable> */ public MutableHashedLinkedMap(Strategy strategy) { - this(strategy, (_, _, v2) -> v2); + this(strategy, (k, v1, v2) -> v2); } /** diff --git a/src/main/java/net/minecraftforge/common/world/StructureSettingsBuilder.java b/src/main/java/net/minecraftforge/common/world/StructureSettingsBuilder.java index 5e62fcc7d8..4356ef8353 100644 --- a/src/main/java/net/minecraftforge/common/world/StructureSettingsBuilder.java +++ b/src/main/java/net/minecraftforge/common/world/StructureSettingsBuilder.java @@ -76,7 +76,7 @@ public class StructureSettingsBuilder { * @param category Mob category */ public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category) { - return spawnOverrides.computeIfAbsent(category, _ -> new StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType.PIECE, Collections.emptyList())); + return spawnOverrides.computeIfAbsent(category, c -> new StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType.PIECE, Collections.emptyList())); } /** diff --git a/src/main/java/net/minecraftforge/data/event/GatherDataEvent.java b/src/main/java/net/minecraftforge/data/event/GatherDataEvent.java index f4ef0e774f..5f99a9daef 100644 --- a/src/main/java/net/minecraftforge/data/event/GatherDataEvent.java +++ b/src/main/java/net/minecraftforge/data/event/GatherDataEvent.java @@ -107,7 +107,7 @@ public final class GatherDataEvent implements IModBusEvent { paths.values().forEach(LamdbaExceptionUtils.rethrowConsumer(lst -> { DataGenerator parent = lst.get(0); for (int x = 1; x < lst.size(); x++) - lst.get(x).getProvidersView().forEach((_, provider) -> parent.addProvider(true, provider)); + lst.get(x).getProvidersView().forEach((name, provider) -> parent.addProvider(true, provider)); parent.run(); })); } diff --git a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java index e1cf718988..baee33a7b1 100644 --- a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java +++ b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java @@ -21,7 +21,6 @@ import net.minecraft.core.component.DataComponentMap; import net.minecraft.util.random.WeightedList; import net.minecraft.world.entity.*; import net.minecraft.world.item.Item; -import net.minecraft.world.item.component.TooltipDisplay; import net.minecraft.world.level.chunk.storage.SerializableChunkData; import net.minecraftforge.common.util.Result; import org.jetbrains.annotations.ApiStatus; @@ -355,8 +354,8 @@ public final class ForgeEventFactory { return BlockEvent.FluidPlaceBlockEvent.BUS.fire(new BlockEvent.FluidPlaceBlockEvent(level, pos, liquidPos, state)).getNewState(); } - public static ItemTooltipEvent onItemTooltip(ItemStack itemStack, @Nullable Player entityPlayer, List list, TooltipFlag flags, Item.TooltipContext context, TooltipDisplay display) { - return ItemTooltipEvent.BUS.fire(new ItemTooltipEvent(itemStack, entityPlayer, list, flags, context, display)); + public static ItemTooltipEvent onItemTooltip(ItemStack itemStack, @Nullable Player entityPlayer, List list, TooltipFlag flags) { + return ItemTooltipEvent.BUS.fire(new ItemTooltipEvent(itemStack, entityPlayer, list, flags)); } public static SummonAidEvent fireZombieSummonAid(Zombie zombie, Level level, int x, int y, int z, LivingEntity attacker, double summonChance) { diff --git a/src/main/java/net/minecraftforge/event/GatherComponentsEvent.java b/src/main/java/net/minecraftforge/event/GatherComponentsEvent.java index 54d8f1342a..1cb7823e49 100644 --- a/src/main/java/net/minecraftforge/event/GatherComponentsEvent.java +++ b/src/main/java/net/minecraftforge/event/GatherComponentsEvent.java @@ -7,6 +7,8 @@ package net.minecraftforge.event; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.Item; import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.event.InheritableEvent; import net.minecraftforge.eventbus.api.event.MutableEvent; diff --git a/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java b/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java index bb60c18578..bb18a9040e 100644 --- a/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/EntityAttributeModificationEvent.java @@ -41,7 +41,7 @@ public final class EntityAttributeModificationEvent extends MutableEvent { } public void add(EntityType entityType, Holder attribute, double value) { - var attributes = entityAttributes.computeIfAbsent(entityType, (_) -> new AttributeSupplier.Builder()); + var attributes = entityAttributes.computeIfAbsent(entityType, (type) -> new AttributeSupplier.Builder()); attributes.add(attribute, value); } diff --git a/src/main/java/net/minecraftforge/event/entity/EntityTeleportEvent.java b/src/main/java/net/minecraftforge/event/entity/EntityTeleportEvent.java index 205e9475e0..495b8fcb3b 100644 --- a/src/main/java/net/minecraftforge/event/entity/EntityTeleportEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/EntityTeleportEvent.java @@ -11,6 +11,7 @@ import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnder import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.bus.CancellableEventBus; import net.minecraftforge.eventbus.api.event.InheritableEvent; import net.minecraftforge.eventbus.api.event.characteristic.Cancellable; diff --git a/src/main/java/net/minecraftforge/event/entity/player/ItemTooltipEvent.java b/src/main/java/net/minecraftforge/event/entity/player/ItemTooltipEvent.java index faa36fba87..204d9cc808 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/ItemTooltipEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/ItemTooltipEvent.java @@ -8,15 +8,12 @@ package net.minecraftforge.event.entity.player; import java.util.List; import net.minecraft.client.Minecraft; -import net.minecraft.world.item.Item; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.network.chat.Component; -import net.minecraft.world.item.component.TooltipDisplay; import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.event.MutableEvent; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,40 +25,17 @@ public final class ItemTooltipEvent extends MutableEvent implements PlayerEvent @NotNull private final ItemStack itemStack; private final List toolTip; - private final Item.TooltipContext context; - private final TooltipDisplay display; /** - * - * This event is fired in {@link ItemStack#getTooltipLines(Item.TooltipContext, Player, TooltipFlag)}, which in turn is called from its respective GUIContainer. + * This event is fired in {@link ItemStack#getTooltipLines(Player, TooltipFlag)}, which in turn is called from its respective GUIContainer. * Tooltips are also gathered with a null player during startup by {@link Minecraft#createSearchTrees()}. */ - @ApiStatus.Internal - public ItemTooltipEvent(@NotNull ItemStack itemStack, @Nullable Player player, List list, TooltipFlag flags, Item.TooltipContext context, TooltipDisplay display) + public ItemTooltipEvent(@NotNull ItemStack itemStack, @Nullable Player player, List list, TooltipFlag flags) { this.player = player; this.itemStack = itemStack; this.toolTip = list; this.flags = flags; - this.context = context; - this.display = display; - } - - - /** - * The {@link net.minecraft.world.item.Item.TooltipContext} for this tooltip. - */ - public Item.TooltipContext getContext() - { - return context; - } - - /** - * The {@link net.minecraft.world.item.component.TooltipDisplay} for this tooltip. - */ - public TooltipDisplay getDisplay() - { - return display; } /** 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 a75afa4cd2..4eb6993cf5 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java @@ -7,6 +7,7 @@ package net.minecraftforge.event.entity.player; import com.google.common.base.Preconditions; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/net/minecraftforge/event/entity/player/SleepingTimeCheckEvent.java b/src/main/java/net/minecraftforge/event/entity/player/SleepingTimeCheckEvent.java index 60c941005e..bd990c7fda 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/SleepingTimeCheckEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/SleepingTimeCheckEvent.java @@ -7,6 +7,7 @@ package net.minecraftforge.event.entity.player; import net.minecraft.world.entity.player.Player; import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; import net.minecraftforge.common.util.HasResult; import net.minecraftforge.common.util.Result; import net.minecraftforge.eventbus.api.bus.EventBus; diff --git a/src/main/java/net/minecraftforge/fluids/DispenseFluidContainer.java b/src/main/java/net/minecraftforge/fluids/DispenseFluidContainer.java index 51f59dcc55..071068ad1b 100644 --- a/src/main/java/net/minecraftforge/fluids/DispenseFluidContainer.java +++ b/src/main/java/net/minecraftforge/fluids/DispenseFluidContainer.java @@ -9,6 +9,7 @@ import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.DispenserBlockEntity; import net.minecraft.core.Direction; import net.minecraft.world.InteractionHand; import net.minecraft.core.BlockPos; diff --git a/src/main/java/net/minecraftforge/fluids/FluidInteractionRegistry.java b/src/main/java/net/minecraftforge/fluids/FluidInteractionRegistry.java index 889182e6cc..ed23c0ce8c 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidInteractionRegistry.java +++ b/src/main/java/net/minecraftforge/fluids/FluidInteractionRegistry.java @@ -44,7 +44,7 @@ public final class FluidInteractionRegistry */ public static synchronized void addInteraction(FluidType source, InteractionInformation interaction) { - INTERACTIONS.computeIfAbsent(source, _ -> new ArrayList<>()).add(interaction); + INTERACTIONS.computeIfAbsent(source, s -> new ArrayList<>()).add(interaction); } /** @@ -86,7 +86,7 @@ public final class FluidInteractionRegistry // Lava + Soul Soil (Below) + Blue Ice = Basalt addInteraction(ForgeMod.LAVA_TYPE.get(), new InteractionInformation( - (level, currentPos, relativePos, _) -> level.getBlockState(currentPos.below()).is(Blocks.SOUL_SOIL) && level.getBlockState(relativePos).is(Blocks.BLUE_ICE), + (level, currentPos, relativePos, currentState) -> level.getBlockState(currentPos.below()).is(Blocks.SOUL_SOIL) && level.getBlockState(relativePos).is(Blocks.BLUE_ICE), Blocks.BASALT.defaultBlockState() )); } @@ -109,7 +109,7 @@ public final class FluidInteractionRegistry */ public InteractionInformation(FluidType type, BlockState state) { - this(type, _ -> state); + this(type, fluidState -> state); } /** @@ -120,7 +120,7 @@ public final class FluidInteractionRegistry */ public InteractionInformation(HasFluidInteraction predicate, BlockState state) { - this(predicate, _ -> state); + this(predicate, fluidState -> state); } /** @@ -132,7 +132,7 @@ public final class FluidInteractionRegistry */ public InteractionInformation(FluidType type, Function getState) { - this((level, _, relativePos, _) -> level.getFluidState(relativePos).getFluidType() == type, getState); + this((level, currentPos, relativePos, currentState) -> level.getFluidState(relativePos).getFluidType() == type, getState); } /** @@ -143,7 +143,7 @@ public final class FluidInteractionRegistry */ public InteractionInformation(HasFluidInteraction predicate, Function getState) { - this(predicate, (level, currentPos, _, currentState) -> + this(predicate, (level, currentPos, relativePos, currentState) -> { level.setBlockAndUpdate(currentPos, ForgeEventFactory.fireFluidPlaceBlockEvent(level, currentPos, currentPos, getState.apply(currentState))); level.levelEvent(1501, currentPos, 0); diff --git a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidTank.java b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidTank.java index 6691466196..ae4057b339 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/templates/FluidTank.java +++ b/src/main/java/net/minecraftforge/fluids/capability/templates/FluidTank.java @@ -25,7 +25,7 @@ public class FluidTank implements IFluidHandler, IFluidTank { protected int capacity; public FluidTank(int capacity) { - this(capacity, _ -> true); + this(capacity, e -> true); } public FluidTank(int capacity, Predicate validator) { diff --git a/src/main/java/net/minecraftforge/items/wrapper/SidedInvWrapper.java b/src/main/java/net/minecraftforge/items/wrapper/SidedInvWrapper.java index 7d9f873153..f6266850af 100644 --- a/src/main/java/net/minecraftforge/items/wrapper/SidedInvWrapper.java +++ b/src/main/java/net/minecraftforge/items/wrapper/SidedInvWrapper.java @@ -55,11 +55,11 @@ public class SidedInvWrapper implements IItemHandlerModifiable if (inv instanceof BrewingStandBlockEntity) this.slotLimit = wrapperSlot -> getSlot(inv, wrapperSlot, side) < 3 ? 1 : inv.getMaxStackSize(); else - this.slotLimit = _ -> inv.getMaxStackSize(); + this.slotLimit = wrapperSlot -> inv.getMaxStackSize(); if (inv instanceof AbstractFurnaceBlockEntity) this.newStackInsertLimit = (wrapperSlot, invSlot, stack) -> invSlot == 1 && stack.is(Items.BUCKET) ? 1 : Math.min(stack.getMaxStackSize(), getSlotLimit(wrapperSlot)); else - this.newStackInsertLimit = (wrapperSlot, _, stack) -> Math.min(stack.getMaxStackSize(), getSlotLimit(wrapperSlot)); + this.newStackInsertLimit = (wrapperSlot, invSlot, stack) -> Math.min(stack.getMaxStackSize(), getSlotLimit(wrapperSlot)); } public static int getSlot(WorldlyContainer inv, int slot, @Nullable Direction side) diff --git a/src/main/java/net/minecraftforge/logging/CrashReportExtender.java b/src/main/java/net/minecraftforge/logging/CrashReportExtender.java index 4f951fbbac..acea58bf7f 100644 --- a/src/main/java/net/minecraftforge/logging/CrashReportExtender.java +++ b/src/main/java/net/minecraftforge/logging/CrashReportExtender.java @@ -26,7 +26,7 @@ public class CrashReportExtender { public static void extendSystemReport(final SystemReport systemReport) { for (final ISystemReportExtender call : CrashReportCallables.allCrashCallables()) { if (call.isActive()) - systemReport.setDetail(call.getLabel(), call::get); + systemReport.setDetail(call.getLabel(), call); } } diff --git a/src/main/java/net/minecraftforge/network/Channel.java b/src/main/java/net/minecraftforge/network/Channel.java index 70b6a35da8..29d1894313 100644 --- a/src/main/java/net/minecraftforge/network/Channel.java +++ b/src/main/java/net/minecraftforge/network/Channel.java @@ -116,8 +116,8 @@ public abstract class Channel { @FunctionalInterface public static interface VersionTest { - public static final VersionTest ACCEPT_MISSING = (status, _) -> status == Status.MISSING; - public static final VersionTest ACCEPT_VANILLA = (status, _) -> status == Status.VANILLA; + public static final VersionTest ACCEPT_MISSING = (status, version) -> status == Status.MISSING; + public static final VersionTest ACCEPT_VANILLA = (status, version) -> status == Status.VANILLA; public static VersionTest exact(int version) { return (status, remoteVersion) -> status == Status.PRESENT && version == remoteVersion; } diff --git a/src/main/java/net/minecraftforge/network/ChannelBuilder.java b/src/main/java/net/minecraftforge/network/ChannelBuilder.java index ec9860d1ce..809f1cadb3 100644 --- a/src/main/java/net/minecraftforge/network/ChannelBuilder.java +++ b/src/main/java/net/minecraftforge/network/ChannelBuilder.java @@ -143,7 +143,7 @@ public class ChannelBuilder { * @param factory A factory that creates a new instance of the context data */ public ChannelBuilder attribute(AttributeKey key, Supplier factory) { - return this.attribute(key, _ -> factory.get()); + return this.attribute(key, con -> factory.get()); } /** diff --git a/src/main/java/net/minecraftforge/network/ServerStatusPing.java b/src/main/java/net/minecraftforge/network/ServerStatusPing.java index 65f50192e4..32c99337e5 100644 --- a/src/main/java/net/minecraftforge/network/ServerStatusPing.java +++ b/src/main/java/net/minecraftforge/network/ServerStatusPing.java @@ -87,8 +87,8 @@ public record ServerStatusPing( ServerStatusPing.BYTE_BUF_CODEC.optionalFieldOf("d").forGetter(ping -> Optional.of(ping.toBuf())), - ChannelData.CODEC.listOf().optionalFieldOf("channels").forGetter(_ -> Optional.of(List.of())), - ModInfo.CODEC.listOf().optionalFieldOf("mods").forGetter(_ -> Optional.of(List.of())), + ChannelData.CODEC.listOf().optionalFieldOf("channels").forGetter(ping -> Optional.of(List.of())), + ModInfo.CODEC.listOf().optionalFieldOf("mods").forGetter(ping -> Optional.of(List.of())), // legacy versions see truncated lists, modern versions ignore this truncated flag (binary data has its own) Codec.BOOL.optionalFieldOf("truncated").forGetter(ping -> Optional.of(ping.isTruncated())) diff --git a/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java b/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java index d1ac6c817a..a92b980ff0 100644 --- a/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java +++ b/src/main/java/net/minecraftforge/network/config/SimpleConfigurationTask.java @@ -23,7 +23,7 @@ public class SimpleConfigurationTask implements ConfigurationTask { } public SimpleConfigurationTask(Type type, Runnable task) { - this(type, _ -> task.run()); + this(type, c -> task.run()); } @Override diff --git a/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java b/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java index 91c39f5d06..a70e4959c3 100644 --- a/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java +++ b/src/main/java/net/minecraftforge/network/filters/NetworkFilters.java @@ -20,7 +20,7 @@ public class NetworkFilters { private static final Logger LOGGER = LogManager.getLogger(); private static final Map> instances = ImmutableMap.of( - "forge:vanilla_filter", _ -> new VanillaConnectionNetworkFilter()/*, + "forge:vanilla_filter", manager -> new VanillaConnectionNetworkFilter()/*, "forge:forge_fixes", ForgeConnectionNetworkFilter::new*/ ); diff --git a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java index ed8332e09c..f4aa4bd3ee 100644 --- a/src/main/java/net/minecraftforge/network/packets/OpenContainer.java +++ b/src/main/java/net/minecraftforge/network/packets/OpenContainer.java @@ -70,7 +70,7 @@ public class OpenContainer { var s = ((MenuScreens.ScreenConstructor)f).create(c, inv, msg.getName()); mc.player.containerMenu = s.getMenu(); - mc.gui.setScreen(s); + mc.setScreen(s); }); } finally { msg.getAdditionalData().release(); diff --git a/src/main/java/net/minecraftforge/network/packets/RegistryList.java b/src/main/java/net/minecraftforge/network/packets/RegistryList.java index 531c363e09..8b0109ca0f 100644 --- a/src/main/java/net/minecraftforge/network/packets/RegistryList.java +++ b/src/main/java/net/minecraftforge/network/packets/RegistryList.java @@ -28,7 +28,7 @@ public record RegistryList( public static RegistryList decode(FriendlyByteBuf buf) { var token = buf.readVarInt(); var normal = buf.readList(FriendlyByteBuf::readIdentifier); - List>> datapacks = buf.readList(_ -> ResourceKey.createRegistryKey(buf.readIdentifier())); + List>> datapacks = buf.readList(b -> ResourceKey.createRegistryKey(buf.readIdentifier())); return new RegistryList(token, normal, datapacks); } diff --git a/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java b/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java index c1906d1633..bd9f3a5b1e 100644 --- a/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java +++ b/src/main/java/net/minecraftforge/network/simple/SimpleFlow.java @@ -28,7 +28,7 @@ public interface SimpleFlow extends SimplePro */ default SimpleFlow addMain(Class type, StreamCodec codec, BiConsumer handler) { return add(type, codec, (msg, ctx) -> { - net.minecraftforge.common.ForgeHooks.enqueuePacket(handler, msg, ctx); + ctx.enqueueWork(() -> handler.accept(msg, ctx)); ctx.setPacketHandled(true); }); } diff --git a/src/main/java/net/minecraftforge/registries/DeferredRegisterData.java b/src/main/java/net/minecraftforge/registries/DeferredRegisterData.java index 3e4a2e2cf7..8555028689 100644 --- a/src/main/java/net/minecraftforge/registries/DeferredRegisterData.java +++ b/src/main/java/net/minecraftforge/registries/DeferredRegisterData.java @@ -155,7 +155,7 @@ public class DeferredRegisterData implements RegistryBootstrap { * @see #register(String, Supplier) */ public RegistryObject register(final String name, final Supplier factory) { - return register(name, _ -> factory.get()); + return register(name, ctx -> factory.get()); } /** diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java index 1be1a30af7..6c10c9b8cc 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java @@ -31,6 +31,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntRBTreeMap; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; +import net.minecraft.nbt.Tag; import net.minecraft.tags.TagKey; import net.minecraftforge.common.util.LogMessageAdapter; import net.minecraftforge.fml.ModLoadingContext; @@ -497,7 +498,7 @@ public class ForgeRegistry implements IForgeRegistryInternal, IForgeRegist } private Holder.Reference bindDelegate(ResourceKey rkey, V value) { - Holder.Reference delegate = delegatesByName.computeIfAbsent(rkey.identifier(), _ -> Holder.Reference.createStandAlone(this.getWrapperOrThrow(), rkey)); + Holder.Reference delegate = delegatesByName.computeIfAbsent(rkey.identifier(), k -> Holder.Reference.createStandAlone(this.getWrapperOrThrow(), rkey)); delegate.bindKey(rkey); delegate.bindValue(value); delegatesByValue.put(value, delegate); diff --git a/src/main/java/net/minecraftforge/registries/GameData.java b/src/main/java/net/minecraftforge/registries/GameData.java index 626daf0ebf..ea39ca668b 100644 --- a/src/main/java/net/minecraftforge/registries/GameData.java +++ b/src/main/java/net/minecraftforge/registries/GameData.java @@ -88,7 +88,7 @@ public class GameData { 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 = (_, reg) -> reg.slaves.values().stream().filter(o -> o instanceof ILockableRegistry).forEach(o -> ((ILockableRegistry)o).lock()); + private static final BiConsumer> LOCK_VANILLA = (name, reg) -> reg.slaves.values().stream().filter(o -> o instanceof ILockableRegistry).forEach(o -> ((ILockableRegistry)o).lock()); private static Set vanillaRegistryOrder = null; static { @@ -301,13 +301,13 @@ public class GameData { LOGGER.warn(REGISTRIES, "Can't revert to {} GameData state without a valid snapshot.", target.getName()); return; } - RegistryManager.ACTIVE.registries.forEach((_, reg) -> reg.resetDelegates()); + RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates()); LOGGER.debug(REGISTRIES, "Reverting to {} data state.", target.getName()); for (var r : RegistryManager.ACTIVE.registries.entrySet()) loadRegistry(r.getKey(), target, RegistryManager.ACTIVE, true); - RegistryManager.ACTIVE.registries.forEach((_, reg) -> reg.bake()); + RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.bake()); // the id mapping has reverted, fire remap events for those that care about id changes if (fireEvents) { fireRemapEvent(ImmutableMap.of(), true); @@ -570,12 +570,12 @@ public class GameData { LOGGER.info(REGISTRIES, "Injecting existing registry data into this {} instance", EffectiveSide.get()); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.validateContent(name)); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name)); - RegistryManager.ACTIVE.registries.forEach((_, reg) -> reg.resetDelegates()); + RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates()); // Update legacy names snapshot = snapshot.entrySet().stream() .sorted(Map.Entry.comparingByKey()) // FIXME Registries need dependency ordering, this makes sure blocks are done before items (for ItemCallbacks) but it's lazy as hell - .collect(Collectors.toMap(e -> RegistryManager.ACTIVE.updateLegacyName(e.getKey()), Map.Entry::getValue, (k1, _) -> k1, LinkedHashMap::new)); + .collect(Collectors.toMap(e -> RegistryManager.ACTIVE.updateLegacyName(e.getKey()), Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); if (isLocalWorld) { Identifier[] missingRegs = snapshot.keySet().stream().filter(name -> !RegistryManager.ACTIVE.registries.containsKey(name)).toArray(Identifier[]::new); @@ -667,7 +667,7 @@ public class GameData { if (injectFrozenData) { // If we're loading up the world from disk, we want to add in the new data that might have been provisioned by mods // So we load it from the frozen persistent registry - RegistryManager.ACTIVE.registries.forEach((name, _) -> { + RegistryManager.ACTIVE.registries.forEach((name, reg) -> { loadFrozenDataToStagingRegistry(STAGING, name, remaps.get(name)); }); } @@ -677,7 +677,7 @@ public class GameData { // Load the STAGING registry into the ACTIVE registry //for (Map.Entry>> r : RegistryManager.ACTIVE.registries.entrySet()) - RegistryManager.ACTIVE.registries.forEach((key, _) -> { + RegistryManager.ACTIVE.registries.forEach((key, value) -> { loadRegistry(key, STAGING, RegistryManager.ACTIVE, true); }); diff --git a/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java b/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java index 6b993e36d9..b17fd4d574 100644 --- a/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java +++ b/src/main/java/net/minecraftforge/registries/NamespacedWrapper.java @@ -250,7 +250,7 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr } protected Holder.Reference getOrCreateHolderOrThrow(ResourceKey key) { - return this.holdersByName.computeIfAbsent(key.identifier(), _ -> { + return this.holdersByName.computeIfAbsent(key.identifier(), k -> { if (this.isIntrusive()) { throw new IllegalStateException("This registry can't create new holders without value"); } else { @@ -526,7 +526,7 @@ class NamespacedWrapper extends MappedRegistry implements ILockableRegistr if (this.isIntrusive()) return this.intrusiveHolderCallback.apply(value); - return this.holdersByName.computeIfAbsent(key.identifier(), _ -> Holder.Reference.createStandAlone(this, key)); + return this.holdersByName.computeIfAbsent(key.identifier(), k -> Holder.Reference.createStandAlone(this, key)); } private List> getSortedHolders() { diff --git a/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java b/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java index 53da06fb0a..8af55397ba 100644 --- a/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java @@ -54,7 +54,7 @@ class ObjectHolderRegistry { static void applyObjectHolders() { try { LOGGER.debug(ForgeRegistry.REGISTRIES, "Applying holder lookups"); - applyObjectHolders(_ -> true); + applyObjectHolders(key -> true); LOGGER.debug(ForgeRegistry.REGISTRIES, "Holder lookups applied"); } catch (RuntimeException e) { // It is more important that the calling contexts continue without exception to prevent further cascading errors diff --git a/src/main/java/net/minecraftforge/registries/RegistryObject.java b/src/main/java/net/minecraftforge/registries/RegistryObject.java index 96fe8b5cac..9c49544727 100644 --- a/src/main/java/net/minecraftforge/registries/RegistryObject.java +++ b/src/main/java/net/minecraftforge/registries/RegistryObject.java @@ -481,8 +481,8 @@ public final class RegistryObject implements Supplier { @Override public boolean equals(Object obj) { if (this == obj) return true; - if (obj instanceof RegistryObject o) { - return o.key == key && Objects.equals(o.name, name); + if (obj instanceof RegistryObject o) { + return Objects.equals(o.name, name); } return false; } diff --git a/src/main/java/net/minecraftforge/registries/tags/ITag.java b/src/main/java/net/minecraftforge/registries/tags/ITag.java index cb5aa57e57..bf5675d83c 100644 --- a/src/main/java/net/minecraftforge/registries/tags/ITag.java +++ b/src/main/java/net/minecraftforge/registries/tags/ITag.java @@ -9,6 +9,7 @@ import net.minecraft.tags.TagKey; import net.minecraft.util.RandomSource; import java.util.Optional; +import java.util.Random; import java.util.stream.Stream; /** diff --git a/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java b/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java index 5f92b1bbe6..078f25eecb 100644 --- a/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java +++ b/src/main/java/net/minecraftforge/resource/DelegatingPackResources.java @@ -49,9 +49,9 @@ public class DelegatingPackResources extends AbstractPackResources { Map> map = new HashMap<>(); for (PackResources pack : packList) { for (String namespace : pack.getNamespaces(type)) - map.computeIfAbsent(namespace, _ -> new ArrayList<>()).add(pack); + map.computeIfAbsent(namespace, k -> new ArrayList<>()).add(pack); } - map.replaceAll((_, list) -> ImmutableList.copyOf(list)); + map.replaceAll((k, list) -> ImmutableList.copyOf(list)); return ImmutableMap.copyOf(map); } diff --git a/src/main/java/net/minecraftforge/server/LanguageHook.java b/src/main/java/net/minecraftforge/server/LanguageHook.java index 2bcaac981b..aef19ffb38 100644 --- a/src/main/java/net/minecraftforge/server/LanguageHook.java +++ b/src/main/java/net/minecraftforge/server/LanguageHook.java @@ -73,7 +73,7 @@ public class LanguageHook { } for (var namespace : pack.getNamespaces(PackType.CLIENT_RESOURCES)) { - byNamespace.computeIfAbsent(namespace, _ -> new ArrayList<>()).add(pack); + byNamespace.computeIfAbsent(namespace, k -> new ArrayList<>()).add(pack); } } diff --git a/src/main/java/net/minecraftforge/server/command/DimensionsCommand.java b/src/main/java/net/minecraftforge/server/command/DimensionsCommand.java index dd46e3e2fb..8b39580af9 100644 --- a/src/main/java/net/minecraftforge/server/command/DimensionsCommand.java +++ b/src/main/java/net/minecraftforge/server/command/DimensionsCommand.java @@ -32,7 +32,7 @@ class DimensionsCommand { Map> types = new HashMap<>(); for (ServerLevel dim : ctx.getSource().getServer().getAllLevels()) { - types.computeIfAbsent(reg.getKey(dim.dimensionType()), _ -> new ArrayList<>()).add(dim.dimension().identifier()); + types.computeIfAbsent(reg.getKey(dim.dimensionType()), k -> new ArrayList<>()).add(dim.dimension().identifier()); } types.keySet().stream().sorted().forEach(key -> { diff --git a/src/main/java/net/minecraftforge/server/command/EntityCommand.java b/src/main/java/net/minecraftforge/server/command/EntityCommand.java index e1cce7ad99..7ae07c2557 100644 --- a/src/main/java/net/minecraftforge/server/command/EntityCommand.java +++ b/src/main/java/net/minecraftforge/server/command/EntityCommand.java @@ -52,7 +52,7 @@ class EntityCommand return Commands.literal("list") .requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)) .then(Commands.argument("filter", StringArgumentType.string()) - .suggests((_, builder) -> SharedSuggestionProvider.suggest(ForgeRegistries.ENTITY_TYPES.getKeys().stream().map(Identifier::toString).map(StringArgumentType::escapeIfRequired), builder)) + .suggests((ctx, builder) -> SharedSuggestionProvider.suggest(ForgeRegistries.ENTITY_TYPES.getKeys().stream().map(Identifier::toString).map(StringArgumentType::escapeIfRequired), builder)) .then(Commands.argument("dim", DimensionArgument.dimension()) .executes(ctx -> execute(ctx.getSource(), StringArgumentType.getString(ctx, "filter"), DimensionArgument.getDimension(ctx, "dim").dimension())) ) @@ -76,7 +76,7 @@ class EntityCommand Map>> list = Maps.newHashMap(); level.getEntities().getAll().forEach(e -> { - MutablePair> info = list.computeIfAbsent(ForgeRegistries.ENTITY_TYPES.getKey(e.getType()), _ -> MutablePair.of(0, Maps.newHashMap())); + MutablePair> info = list.computeIfAbsent(ForgeRegistries.ENTITY_TYPES.getKey(e.getType()), k -> MutablePair.of(0, Maps.newHashMap())); ChunkPos chunk = ChunkPos.containing(e.blockPosition()); info.left++; info.right.put(chunk, info.right.getOrDefault(chunk, 0) + 1); diff --git a/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java b/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java index cca380e653..3488ff22e8 100644 --- a/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java +++ b/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java @@ -9,6 +9,7 @@ import net.minecraft.IdentifierException; import net.minecraft.resources.Identifier; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.common.ForgeConfig; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.server.ServerLifecycleHooks; import net.minecraftforge.server.permission.events.PermissionGatherEvent; import net.minecraftforge.server.permission.exceptions.UnregisteredPermissionException; diff --git a/src/main/java/net/minecraftforge/server/permission/handler/IPermissionHandler.java b/src/main/java/net/minecraftforge/server/permission/handler/IPermissionHandler.java index bc1f62b19c..8a218a0fef 100644 --- a/src/main/java/net/minecraftforge/server/permission/handler/IPermissionHandler.java +++ b/src/main/java/net/minecraftforge/server/permission/handler/IPermissionHandler.java @@ -7,6 +7,7 @@ package net.minecraftforge.server.permission.handler; import net.minecraft.resources.Identifier; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.StringRepresentable; import net.minecraftforge.server.permission.PermissionAPI; import net.minecraftforge.server.permission.events.PermissionGatherEvent; import net.minecraftforge.server.permission.nodes.PermissionDynamicContext; diff --git a/src/main/java/net/minecraftforge/server/timings/TimeTracker.java b/src/main/java/net/minecraftforge/server/timings/TimeTracker.java index 2499b92952..1a3c322aa6 100644 --- a/src/main/java/net/minecraftforge/server/timings/TimeTracker.java +++ b/src/main/java/net/minecraftforge/server/timings/TimeTracker.java @@ -108,7 +108,7 @@ public class TimeTracker currentlyTracking = null; return; } - int[] timings = this.timings.computeIfAbsent(object, _ -> new int[101]); + int[] timings = this.timings.computeIfAbsent(object, k -> new int[101]); int idx = timings[100] = (timings[100] + 1) % 100; timings[idx] = (int) (nanoTime - timing); } diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index e8e53a3ff5..581a13239b 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,24 +1,9 @@ -public net.minecraft.advancements.triggers.CriteriaTriggers register(Ljava/lang/String;Lnet/minecraft/advancements/triggers/CriterionTrigger;)Lnet/minecraft/advancements/triggers/CriterionTrigger; +public net.minecraft.advancements.CriteriaTriggers register(Ljava/lang/String;Lnet/minecraft/advancements/CriterionTrigger;)Lnet/minecraft/advancements/CriterionTrigger; default net.minecraft.client.KeyMapping isDown public net.minecraft.client.Minecraft textureManager public-f net.minecraft.client.Options keyMappings public net.minecraft.client.Options$FieldAccess public net.minecraft.client.color.item.ItemTintSources ID_MAPPER -#group protected net.minecraft.client.data.AtlasProvider *() -protected net.minecraft.client.data.AtlasProvider armorTrims()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider bannerPatterns()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider blocksList()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider extractAllMaterialAssets()Ljava/util/stream/Stream; -protected net.minecraft.client.data.AtlasProvider forMapper(Lnet/minecraft/client/renderer/SpriteMapper;)Lnet/minecraft/client/renderer/texture/atlas/SpriteSource; -protected net.minecraft.client.data.AtlasProvider forMaterial(Lnet/minecraft/client/resources/model/sprite/SpriteId;)Lnet/minecraft/client/renderer/texture/atlas/SpriteSource; -protected net.minecraft.client.data.AtlasProvider guiSprites()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider itemsList()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider noPrefixMapper(Ljava/lang/String;)Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider patternTextures()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider shieldPatterns()Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider simpleMapper(Lnet/minecraft/client/renderer/SpriteMapper;)Ljava/util/List; -protected net.minecraft.client.data.AtlasProvider storeAtlas(Lnet/minecraft/data/CachedOutput;Lnet/minecraft/resources/Identifier;Ljava/util/List;)Ljava/util/concurrent/CompletableFuture; -#endgroup #group protected net.minecraft.client.data.models.BlockModelGenerators *() protected net.minecraft.client.data.models.BlockModelGenerators addBookSlotModel(Lnet/minecraft/client/data/models/blockstates/MultiPartGenerator;Lnet/minecraft/client/renderer/block/dispatch/multipart/Condition;Lnet/minecraft/client/renderer/block/dispatch/VariantMutator;Lnet/minecraft/world/level/block/state/properties/BooleanProperty;Lnet/minecraft/client/data/models/model/ModelTemplate;Z)V protected net.minecraft.client.data.models.BlockModelGenerators addShelfPart(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/model/TextureMapping;Lnet/minecraft/client/data/models/blockstates/MultiPartGenerator;Lnet/minecraft/client/data/models/model/ModelTemplate;Ljava/lang/Boolean;Lnet/minecraft/world/level/block/state/properties/SideChainPart;)V @@ -44,13 +29,14 @@ protected net.minecraft.client.data.models.BlockModelGenerators createAxisAligne protected net.minecraft.client.data.models.BlockModelGenerators createAzalea(Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createBamboo()V protected net.minecraft.client.data.models.BlockModelGenerators createBambooModels(I)Lnet/minecraft/client/data/models/MultiVariant; -protected net.minecraft.client.data.models.BlockModelGenerators createBanner(Lnet/minecraft/world/item/DyeColor;)V +protected net.minecraft.client.data.models.BlockModelGenerators createBanner(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/item/DyeColor;)V +protected net.minecraft.client.data.models.BlockModelGenerators createBanners()V protected net.minecraft.client.data.models.BlockModelGenerators createBarrel()V protected net.minecraft.client.data.models.BlockModelGenerators createBars(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/resources/Identifier;Lnet/minecraft/resources/Identifier;Lnet/minecraft/resources/Identifier;Lnet/minecraft/resources/Identifier;Lnet/minecraft/resources/Identifier;Lnet/minecraft/resources/Identifier;)V protected net.minecraft.client.data.models.BlockModelGenerators createBarsAndItem(Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createBarsAndItem(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;)V -protected net.minecraft.client.data.models.BlockModelGenerators createBed(Lnet/minecraft/world/item/DyeColor;)V -protected net.minecraft.client.data.models.BlockModelGenerators createBed(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; +protected net.minecraft.client.data.models.BlockModelGenerators createBed(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/item/DyeColor;)V +protected net.minecraft.client.data.models.BlockModelGenerators createBeds()V protected net.minecraft.client.data.models.BlockModelGenerators createBeeNest(Lnet/minecraft/world/level/block/Block;Ljava/util/function/Function;)V protected net.minecraft.client.data.models.BlockModelGenerators createBell()V protected net.minecraft.client.data.models.BlockModelGenerators createBigDripLeafBlock()V @@ -73,8 +59,8 @@ protected net.minecraft.client.data.models.BlockModelGenerators createChiseledBo protected net.minecraft.client.data.models.BlockModelGenerators createChorusFlower()V protected net.minecraft.client.data.models.BlockModelGenerators createChorusPlant()V protected net.minecraft.client.data.models.BlockModelGenerators createCocoa()V -protected net.minecraft.client.data.models.BlockModelGenerators createColoredBlockWithRandomRotations(Lnet/minecraft/client/data/models/model/TexturedModel$Provider;Ljava/util/List;)V -protected net.minecraft.client.data.models.BlockModelGenerators createColoredBlockWithStateRotations(Lnet/minecraft/client/data/models/model/TexturedModel$Provider;Ljava/util/List;)V +protected net.minecraft.client.data.models.BlockModelGenerators createColoredBlockWithRandomRotations(Lnet/minecraft/client/data/models/model/TexturedModel$Provider;[Lnet/minecraft/world/level/block/Block;)V +protected net.minecraft.client.data.models.BlockModelGenerators createColoredBlockWithStateRotations(Lnet/minecraft/client/data/models/model/TexturedModel$Provider;[Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createCommandBlock(Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createComparator()V protected net.minecraft.client.data.models.BlockModelGenerators createComposter()V @@ -130,7 +116,6 @@ protected net.minecraft.client.data.models.BlockModelGenerators createGrassLikeB protected net.minecraft.client.data.models.BlockModelGenerators createGrindstone()V protected net.minecraft.client.data.models.BlockModelGenerators createGrowingPlant(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/BlockModelGenerators$PlantType;)V protected net.minecraft.client.data.models.BlockModelGenerators createHangingMoss(Lnet/minecraft/world/level/block/Block;)V -protected net.minecraft.client.data.models.BlockModelGenerators createHangingSign(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createHead(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/SkullBlock$Type;Lnet/minecraft/resources/Identifier;)V protected net.minecraft.client.data.models.BlockModelGenerators createHeads()V protected net.minecraft.client.data.models.BlockModelGenerators createHopper()V @@ -179,6 +164,8 @@ protected net.minecraft.client.data.models.BlockModelGenerators createPitcherCro protected net.minecraft.client.data.models.BlockModelGenerators createPitcherPlant()V protected net.minecraft.client.data.models.BlockModelGenerators createPlant(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/BlockModelGenerators$PlantType;)V protected net.minecraft.client.data.models.BlockModelGenerators createPlantWithDefaultItem(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/BlockModelGenerators$PlantType;)V +protected net.minecraft.client.data.models.BlockModelGenerators createPointedDripstone()V +protected net.minecraft.client.data.models.BlockModelGenerators createPointedDripstoneVariant(Lnet/minecraft/core/Direction;Lnet/minecraft/world/level/block/state/properties/DripstoneThickness;)Lnet/minecraft/client/data/models/MultiVariant; protected net.minecraft.client.data.models.BlockModelGenerators createPottedAzalea(Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createPressurePlate(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createPumpkinVariant(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/model/TextureMapping;)V @@ -205,7 +192,6 @@ protected net.minecraft.client.data.models.BlockModelGenerators createSegmentedB protected net.minecraft.client.data.models.BlockModelGenerators createShelf(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createShulkerBox(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/item/DyeColor;)V protected net.minecraft.client.data.models.BlockModelGenerators createSideFireModels(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/client/data/models/MultiVariant; -protected net.minecraft.client.data.models.BlockModelGenerators createSign(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createSimpleBlock(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/MultiVariantGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createSlab(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createSmallDripleaf()V @@ -214,8 +200,6 @@ protected net.minecraft.client.data.models.BlockModelGenerators createSmoothSton protected net.minecraft.client.data.models.BlockModelGenerators createSnifferEgg()V protected net.minecraft.client.data.models.BlockModelGenerators createSnowBlocks()V protected net.minecraft.client.data.models.BlockModelGenerators createSoulFire()V -protected net.minecraft.client.data.models.BlockModelGenerators createSpeleothem(Lnet/minecraft/world/level/block/Block;)V -protected net.minecraft.client.data.models.BlockModelGenerators createSpeleothemVariant(Lnet/minecraft/core/Direction;Lnet/minecraft/world/level/block/state/properties/SpeleothemThickness;Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/client/data/models/MultiVariant; protected net.minecraft.client.data.models.BlockModelGenerators createStairs(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;Lnet/minecraft/client/data/models/MultiVariant;)Lnet/minecraft/client/data/models/blockstates/BlockModelDefinitionGenerator; protected net.minecraft.client.data.models.BlockModelGenerators createStems(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.client.data.models.BlockModelGenerators createStonecutter()V @@ -268,8 +252,6 @@ public net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider door(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/client/data/models/BlockModelGenerators$BlockFamilyProvider; protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider fullBlockVariant(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/client/data/models/BlockModelGenerators$BlockFamilyProvider; protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider getOrCreateModel(Lnet/minecraft/client/data/models/model/ModelTemplate;Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/resources/Identifier; -protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider hangingSign(Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/data/BlockFamily$Variant;)Lnet/minecraft/client/data/models/BlockModelGenerators$BlockFamilyProvider; -protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider pillar(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/client/data/models/BlockModelGenerators$BlockFamilyProvider; protected net.minecraft.client.data.models.BlockModelGenerators$BlockFamilyProvider trapdoor(Lnet/minecraft/world/level/block/Block;)V #endgroup public net.minecraft.client.data.models.BlockModelGenerators$PlantType @@ -320,53 +302,53 @@ public net.minecraft.client.data.models.ModelProvider$ItemInfoCollector public net.minecraft.client.data.models.ModelProvider$ItemInfoCollector ()V public net.minecraft.client.data.models.ModelProvider$SimpleModelCollector public net.minecraft.client.data.models.ModelProvider$SimpleModelCollector ()V -public net.minecraft.client.gui.GuiGraphicsExtractor componentHoverEffect(Lnet/minecraft/client/gui/Font;Lnet/minecraft/network/chat/Style;II)V -#group public net.minecraft.client.gui.Hud *() -public net.minecraft.client.gui.Hud canRenderCrosshairForSpectator(Lnet/minecraft/world/phys/HitResult;)Z -public net.minecraft.client.gui.Hud displayScoreboardSidebar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/scores/Objective;)V -public net.minecraft.client.gui.Hud extractAirBubbles(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;III)V -public net.minecraft.client.gui.Hud extractArmor(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;IIII)V -public net.minecraft.client.gui.Hud extractBossOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractCameraOverlays(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractChat(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractConfusionOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V -public net.minecraft.client.gui.Hud extractCrosshair(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractDemoOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractEffects(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractFood(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;II)V -public net.minecraft.client.gui.Hud extractHeart(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/gui/Hud$HeartType;IIZZZ)V -public net.minecraft.client.gui.Hud extractHearts(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;IIIIFIIIZ)V -public net.minecraft.client.gui.Hud extractHotbarAndDecorations(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractItemHotbar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractOverlayMessage(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractPlayerHealth(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V -public net.minecraft.client.gui.Hud extractPortalOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V -public net.minecraft.client.gui.Hud extractScoreboardSidebar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractSelectedItemName(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V -public net.minecraft.client.gui.Hud extractSleepOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractSlot(Lnet/minecraft/client/gui/GuiGraphicsExtractor;IILnet/minecraft/client/DeltaTracker;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/item/ItemStack;I)V -public net.minecraft.client.gui.Hud extractSpyglassOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V -public net.minecraft.client.gui.Hud extractSubtitleOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Z)V -public net.minecraft.client.gui.Hud extractTabList(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractTextureOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/resources/Identifier;F)V -public net.minecraft.client.gui.Hud extractTitle(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V -public net.minecraft.client.gui.Hud extractVehicleHealth(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V -public net.minecraft.client.gui.Hud extractVignette(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/Entity;)V -public net.minecraft.client.gui.Hud getAirBubbleYLine(II)I -public net.minecraft.client.gui.Hud getCameraPlayer()Lnet/minecraft/world/entity/player/Player; -public net.minecraft.client.gui.Hud getCurrentAirSupplyBubble(III)I -public net.minecraft.client.gui.Hud getEmptyBubbleDelayDuration(IZ)I -public net.minecraft.client.gui.Hud getPlayerVehicleWithHealth()Lnet/minecraft/world/entity/LivingEntity; -public net.minecraft.client.gui.Hud getVehicleMaxHearts(Lnet/minecraft/world/entity/LivingEntity;)I -public net.minecraft.client.gui.Hud getVisibleVehicleHeartRows(I)I -public net.minecraft.client.gui.Hud nextContextualInfoState()Lnet/minecraft/client/gui/Hud$ContextualInfo; -public net.minecraft.client.gui.Hud playAirBubblePoppedSound(ILnet/minecraft/world/entity/player/Player;I)V -public net.minecraft.client.gui.Hud tick()V -public net.minecraft.client.gui.Hud tickAutosaveIndicator()V -public net.minecraft.client.gui.Hud updateVignetteBrightness(Lnet/minecraft/world/entity/Entity;)V -public net.minecraft.client.gui.Hud willPrioritizeExperienceInfo()Z -public net.minecraft.client.gui.Hud willPrioritizeJumpInfo()Z +#group public net.minecraft.client.gui.Gui *() +public net.minecraft.client.gui.Gui canRenderCrosshairForSpectator(Lnet/minecraft/world/phys/HitResult;)Z +public net.minecraft.client.gui.Gui displayScoreboardSidebar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/scores/Objective;)V +public net.minecraft.client.gui.Gui extractAirBubbles(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;III)V +public net.minecraft.client.gui.Gui extractArmor(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;IIII)V +public net.minecraft.client.gui.Gui extractBossOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractCameraOverlays(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractChat(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractConfusionOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V +public net.minecraft.client.gui.Gui extractCrosshair(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractDemoOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractEffects(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractFood(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;II)V +public net.minecraft.client.gui.Gui extractHeart(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/gui/Gui$HeartType;IIZZZ)V +public net.minecraft.client.gui.Gui extractHearts(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/player/Player;IIIIFIIIZ)V +public net.minecraft.client.gui.Gui extractHotbarAndDecorations(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractItemHotbar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractOverlayMessage(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractPlayerHealth(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V +public net.minecraft.client.gui.Gui extractPortalOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V +public net.minecraft.client.gui.Gui extractScoreboardSidebar(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractSelectedItemName(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V +public net.minecraft.client.gui.Gui extractSleepOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractSlot(Lnet/minecraft/client/gui/GuiGraphicsExtractor;IILnet/minecraft/client/DeltaTracker;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/item/ItemStack;I)V +public net.minecraft.client.gui.Gui extractSpyglassOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;F)V +public net.minecraft.client.gui.Gui extractSubtitleOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Z)V +public net.minecraft.client.gui.Gui extractTabList(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractTextureOverlay(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/resources/Identifier;F)V +public net.minecraft.client.gui.Gui extractTitle(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/client/DeltaTracker;)V +public net.minecraft.client.gui.Gui extractVehicleHealth(Lnet/minecraft/client/gui/GuiGraphicsExtractor;)V +public net.minecraft.client.gui.Gui extractVignette(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Lnet/minecraft/world/entity/Entity;)V +public net.minecraft.client.gui.Gui getAirBubbleYLine(II)I +public net.minecraft.client.gui.Gui getCameraPlayer()Lnet/minecraft/world/entity/player/Player; +public net.minecraft.client.gui.Gui getCurrentAirSupplyBubble(III)I +public net.minecraft.client.gui.Gui getEmptyBubbleDelayDuration(IZ)I +public net.minecraft.client.gui.Gui getPlayerVehicleWithHealth()Lnet/minecraft/world/entity/LivingEntity; +public net.minecraft.client.gui.Gui getVehicleMaxHearts(Lnet/minecraft/world/entity/LivingEntity;)I +public net.minecraft.client.gui.Gui getVisibleVehicleHeartRows(I)I +public net.minecraft.client.gui.Gui nextContextualInfoState()Lnet/minecraft/client/gui/Gui$ContextualInfo; +public net.minecraft.client.gui.Gui playAirBubblePoppedSound(ILnet/minecraft/world/entity/player/Player;I)V +public net.minecraft.client.gui.Gui tick()V +public net.minecraft.client.gui.Gui tickAutosaveIndicator()V +public net.minecraft.client.gui.Gui updateVignetteBrightness(Lnet/minecraft/world/entity/Entity;)V +public net.minecraft.client.gui.Gui willPrioritizeExperienceInfo()Z +public net.minecraft.client.gui.Gui willPrioritizeJumpInfo()Z #endgroup +public net.minecraft.client.gui.GuiGraphicsExtractor componentHoverEffect(Lnet/minecraft/client/gui/Font;Lnet/minecraft/network/chat/Style;II)V protected net.minecraft.client.gui.components.AbstractButton SPRITES protected net.minecraft.client.gui.components.AbstractSelectionList$Entry list protected net.minecraft.client.gui.components.AbstractSliderButton getHandleSprite()Lnet/minecraft/resources/Identifier; @@ -390,10 +372,9 @@ public net.minecraft.client.particle.ParticleResources register(Lnet/minecraft/c public net.minecraft.client.particle.ParticleResources register(Lnet/minecraft/core/particles/ParticleType;Lnet/minecraft/client/particle/ParticleResources$SpriteParticleRegistration;)V public net.minecraft.client.particle.ParticleResources$SpriteParticleRegistration public net.minecraft.client.player.ClientInput moveVector +public net.minecraft.client.renderer.LevelRenderer shouldShowEntityOutlines()Z private-f net.minecraft.client.renderer.LevelRenderer weatherEffectRenderer #group public net.minecraft.client.renderer.RenderPipelines * -public net.minecraft.client.renderer.RenderPipelines ALPHA_CUTOUT_THRESHOLD_CUTOUT_TERRAIN -public net.minecraft.client.renderer.RenderPipelines ALPHA_CUTOUT_THRESHOLD_DEFAULT public net.minecraft.client.renderer.RenderPipelines BEACON_BEAM_SNIPPET public net.minecraft.client.renderer.RenderPipelines BLOCK_SNIPPET public net.minecraft.client.renderer.RenderPipelines CLOUDS_SNIPPET @@ -401,6 +382,7 @@ public net.minecraft.client.renderer.RenderPipelines DEBUG_FILLED_SNIPPET public net.minecraft.client.renderer.RenderPipelines END_PORTAL_SNIPPET public net.minecraft.client.renderer.RenderPipelines ENTITY_EMISSIVE_SNIPPET public net.minecraft.client.renderer.RenderPipelines ENTITY_SNIPPET +public net.minecraft.client.renderer.RenderPipelines FOG_SNIPPET public net.minecraft.client.renderer.RenderPipelines GENERIC_BLOCKS_SNIPPET public net.minecraft.client.renderer.RenderPipelines GLOBALS_SNIPPET public net.minecraft.client.renderer.RenderPipelines GUI_SNIPPET @@ -410,13 +392,13 @@ public net.minecraft.client.renderer.RenderPipelines ITEM_SNIPPET public net.minecraft.client.renderer.RenderPipelines LINES_SNIPPET public net.minecraft.client.renderer.RenderPipelines MATRICES_FOG_LIGHT_DIR_SNIPPET public net.minecraft.client.renderer.RenderPipelines MATRICES_FOG_SNIPPET +public net.minecraft.client.renderer.RenderPipelines MATRICES_PROJECTION_SNIPPET public net.minecraft.client.renderer.RenderPipelines OUTLINE_SNIPPET public net.minecraft.client.renderer.RenderPipelines PARTICLE_SNIPPET public net.minecraft.client.renderer.RenderPipelines PIPELINES_BY_LOCATION public net.minecraft.client.renderer.RenderPipelines TERRAIN_SNIPPET public net.minecraft.client.renderer.RenderPipelines TEXT_SNIPPET public net.minecraft.client.renderer.RenderPipelines WEATHER_SNIPPET -public net.minecraft.client.renderer.RenderPipelines WORLD_TEXT_SNIPPET #endgroup public net.minecraft.client.renderer.blockentity.BlockEntityRenderers register(Lnet/minecraft/world/level/block/entity/BlockEntityType;Lnet/minecraft/client/renderer/blockentity/BlockEntityRendererProvider;)V protected net.minecraft.client.renderer.blockentity.ChestRenderer getChestMaterial(Lnet/minecraft/world/level/block/entity/BlockEntity;Z)Lnet/minecraft/client/renderer/blockentity/state/ChestRenderState$ChestMaterialType; @@ -469,17 +451,14 @@ protected net.minecraft.data.recipes.RecipeProvider cutBuilder(Lnet/minecraft/da protected net.minecraft.data.recipes.RecipeProvider fenceBuilder(Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; protected net.minecraft.data.recipes.RecipeProvider fenceGateBuilder(Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; protected net.minecraft.data.recipes.RecipeProvider generateCraftingRecipe(Lnet/minecraft/data/BlockFamily;Lnet/minecraft/data/BlockFamily$Variant;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/ItemLike;)V -protected net.minecraft.data.recipes.RecipeProvider generateSmeltingRecipe(Lnet/minecraft/data/BlockFamily$Variant;Lnet/minecraft/world/level/block/Block;Lnet/minecraft/world/level/ItemLike;)V protected net.minecraft.data.recipes.RecipeProvider generateStonecutterRecipe(Lnet/minecraft/data/BlockFamily;Lnet/minecraft/data/BlockFamily$Variant;Lnet/minecraft/world/level/block/Block;)V protected net.minecraft.data.recipes.RecipeProvider getBaseBlockForCrafting(Lnet/minecraft/data/BlockFamily;Lnet/minecraft/data/BlockFamily$Variant;)Lnet/minecraft/world/level/block/Block; -protected net.minecraft.data.recipes.RecipeProvider getCraftingCriterionName(Lnet/minecraft/data/BlockFamily;Lnet/minecraft/data/BlockFamily$Variant;Lnet/minecraft/world/level/ItemLike;)Ljava/lang/String; -protected net.minecraft.data.recipes.RecipeProvider has(Lnet/minecraft/advancements/predicates/MinMaxBounds$Ints;Lnet/minecraft/world/level/ItemLike;)Lnet/minecraft/advancements/triggers/Criterion; -protected net.minecraft.data.recipes.RecipeProvider insideOf(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/advancements/triggers/Criterion; -protected net.minecraft.data.recipes.RecipeProvider inventoryTrigger([Lnet/minecraft/advancements/predicates/ItemPredicate$Builder;)Lnet/minecraft/advancements/triggers/Criterion; -protected net.minecraft.data.recipes.RecipeProvider inventoryTrigger([Lnet/minecraft/advancements/predicates/ItemPredicate;)Lnet/minecraft/advancements/triggers/Criterion; +protected net.minecraft.data.recipes.RecipeProvider has(Lnet/minecraft/advancements/criterion/MinMaxBounds$Ints;Lnet/minecraft/world/level/ItemLike;)Lnet/minecraft/advancements/Criterion; +protected net.minecraft.data.recipes.RecipeProvider insideOf(Lnet/minecraft/world/level/block/Block;)Lnet/minecraft/advancements/Criterion; +protected net.minecraft.data.recipes.RecipeProvider inventoryTrigger([Lnet/minecraft/advancements/criterion/ItemPredicate$Builder;)Lnet/minecraft/advancements/Criterion; +protected net.minecraft.data.recipes.RecipeProvider inventoryTrigger([Lnet/minecraft/advancements/criterion/ItemPredicate;)Lnet/minecraft/advancements/Criterion; protected net.minecraft.data.recipes.RecipeProvider nineBlockStorageRecipes(Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/level/ItemLike;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V protected net.minecraft.data.recipes.RecipeProvider oreCooking(Lnet/minecraft/world/item/crafting/AbstractCookingRecipe$Factory;Ljava/util/List;Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/item/crafting/CookingBookCategory;Lnet/minecraft/world/level/ItemLike;FILjava/lang/String;Ljava/lang/String;)V -protected net.minecraft.data.recipes.RecipeProvider pillarBuilder(Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; protected net.minecraft.data.recipes.RecipeProvider polishedBuilder(Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; protected net.minecraft.data.recipes.RecipeProvider pressurePlateBuilder(Lnet/minecraft/data/recipes/RecipeCategory;Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; protected net.minecraft.data.recipes.RecipeProvider signBuilder(Lnet/minecraft/world/level/ItemLike;Lnet/minecraft/world/item/crafting/Ingredient;)Lnet/minecraft/data/recipes/RecipeBuilder; @@ -500,6 +479,7 @@ public net.minecraft.data.recipes.packs.VanillaRecipeProvider REDSTONE_SMELTABLE public-f net.minecraft.data.registries.RegistriesDatapackGenerator getName()Ljava/lang/String; protected net.minecraft.data.tags.TagsProvider builders public-f net.minecraft.data.tags.TagsProvider getName()Ljava/lang/String; +public net.minecraft.data.tags.VanillaItemTagsProvider$BlockToItemConverter public net.minecraft.resources.Identifier validNamespaceChar(C)Z public net.minecraft.resources.RegistryDataLoader$RegistryData (Lnet/minecraft/resources/ResourceKey;Lcom/mojang/serialization/Codec;)V protected net.minecraft.server.MinecraftServer nextTickTimeNanos @@ -522,6 +502,7 @@ public net.minecraft.util.thread.BlockableEventLoop submitAsync(Ljava/lang/Runna #group public net.minecraft.world.damagesource.DamageSource *() #All methods public, most are already public net.minecraft.world.damagesource.DamageSource (Lnet/minecraft/core/Holder;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/phys/Vec3;)V #endgroup +protected net.minecraft.world.entity.Entity ENTITY_COUNTER public net.minecraft.world.entity.Entity LOGGER public net.minecraft.world.entity.Entity getEncodeId()Ljava/lang/String; public net.minecraft.world.entity.Mob goalSelector diff --git a/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_table/blocks/test.json b/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_table/blocks/test.json index e31ac7bd9e..b94b56867e 100644 --- a/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_table/blocks/test.json +++ b/src/test/generated/conditional_loot_test/data/conditional_loot_test/loot_table/blocks/test.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:item", @@ -14,6 +15,7 @@ "rolls": 1.0 }, { + "bonus_rolls": 0.0, "entries": [ { "type": "minecraft:item", diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_doesnt_load_empty.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_doesnt_load_empty.json index 28864758b4..7691fc96a8 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_doesnt_load_empty.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_doesnt_load_empty.json @@ -7,6 +7,7 @@ { "recipe": { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "minecraft:dirt" ], diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_recipe_choice.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_recipe_choice.json index 3555d79245..e850d76310 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_recipe_choice.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/conditional_recipe_choice.json @@ -7,6 +7,7 @@ }, "recipe": { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": "minecraft:dirt" }, @@ -26,6 +27,7 @@ }, "recipe": { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": "minecraft:oak_log" }, diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_false_conditions.json index 20abbe0ff3..21ad90f7a1 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_false_conditions.json @@ -7,6 +7,8 @@ { "recipe": { "type": "minecraft:smelting", + "category": "misc", + "cookingtime": 200, "experience": 0.1, "ingredient": "minecraft:dirt", "result": { diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_true_conditions.json index 2cba199ad6..e0bed48e3d 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/cooking_true_conditions.json @@ -7,6 +7,8 @@ { "recipe": { "type": "minecraft:smelting", + "category": "misc", + "cookingtime": 200, "experience": 0.1, "ingredient": "minecraft:bee_nest", "result": { diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_false_conditions.json index f5ab62d51d..45f9b7db70 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_false_conditions.json @@ -7,6 +7,7 @@ { "recipe": { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": "minecraft:dirt" }, diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_true_conditions.json index bafc16fe6a..87e16af726 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shaped_true_conditions.json @@ -7,6 +7,7 @@ { "recipe": { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": "minecraft:oak_log" }, diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_false_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_false_conditions.json index dfd27c1f91..5cff1ede06 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_false_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_false_conditions.json @@ -7,6 +7,7 @@ { "recipe": { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "minecraft:redstone_ore", "minecraft:redstone_ore", diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_true_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_true_conditions.json index e2b9cc1e38..6b9cfe24bb 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_true_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/shapeless_true_conditions.json @@ -7,6 +7,7 @@ { "recipe": { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "minecraft:redstone_ore", "minecraft:redstone_ore", diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_doesnt_load.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_doesnt_load.json index aed90aac7d..f1097b17ab 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_doesnt_load.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_doesnt_load.json @@ -8,6 +8,7 @@ { "recipe": { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "minecraft:iron_ore", "minecraft:iron_ore", diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_loads.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_loads.json index fc6f8db17a..a44c94be44 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_loads.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/tag_empty_condition_loads.json @@ -8,6 +8,7 @@ { "recipe": { "type": "minecraft:crafting_shapeless", + "category": "misc", "ingredients": [ "minecraft:gold_ore", "minecraft:gold_ore", diff --git a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/test_encode_all_conditions.json b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/test_encode_all_conditions.json index 159452af28..72939248d3 100644 --- a/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/test_encode_all_conditions.json +++ b/src/test/generated/conditional_recipe/data/conditional_recipe/recipe/test_encode_all_conditions.json @@ -35,6 +35,7 @@ { "recipe": { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": "minecraft:dirt" }, diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/compound_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/compound_ingredient.json index 8c38c4c5f2..2033323d40 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/compound_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/compound_ingredient.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:compound", diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/difference_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/difference_ingredient.json index b4d51b4867..e31647aef7 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/difference_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/difference_ingredient.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:difference", diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/intersection_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/intersection_ingredient.json index 67d91348ce..1a9e18fe0c 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/intersection_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/intersection_ingredient.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:intersection", diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_damage_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_damage_only.json index 005938a3fd..fcc8a2a829 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_damage_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_damage_only.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:nbt", diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_name_only.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_name_only.json index 95e0518b01..43438d9249 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_name_only.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/partial_nbt_name_only.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:nbt", diff --git a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/strict_nbt_ingredient.json b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/strict_nbt_ingredient.json index 38bf02b628..58c92c3e6e 100644 --- a/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/strict_nbt_ingredient.json +++ b/src/test/generated/custom_ingredients/data/custom_ingredients/recipe/strict_nbt_ingredient.json @@ -1,5 +1,6 @@ { "type": "minecraft:crafting_shaped", + "category": "misc", "key": { "X": { "type": "forge:nbt", diff --git a/src/test/generated/global_loot_test/data/global_loot_test/loot_table/blocks/test.json b/src/test/generated/global_loot_test/data/global_loot_test/loot_table/blocks/test.json index 8004016926..9a0c146055 100644 --- a/src/test/generated/global_loot_test/data/global_loot_test/loot_table/blocks/test.json +++ b/src/test/generated/global_loot_test/data/global_loot_test/loot_table/blocks/test.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:survives_explosion" diff --git a/src/test/generated/loot_events/data/loot_events/loot_table/blocks/test.json b/src/test/generated/loot_events/data/loot_events/loot_table/blocks/test.json index 95deedae5d..252f3538fc 100644 --- a/src/test/generated/loot_events/data/loot_events/loot_table/blocks/test.json +++ b/src/test/generated/loot_events/data/loot_events/loot_table/blocks/test.json @@ -2,6 +2,7 @@ "type": "minecraft:block", "pools": [ { + "bonus_rolls": 0.0, "conditions": [ { "condition": "minecraft:survives_explosion" diff --git a/src/test/generated/mdk_datagen/pack.mcmeta b/src/test/generated/mdk_datagen/pack.mcmeta index e0bd3459be..2af8be3823 100644 --- a/src/test/generated/mdk_datagen/pack.mcmeta +++ b/src/test/generated/mdk_datagen/pack.mcmeta @@ -1,9 +1,9 @@ { "pack": { "description": "${mod_id} resources", - "max_format": 107, + "max_format": 101, "min_format": [ - 107, + 101, 1 ] } diff --git a/src/test/generated/modify_overlay_test/data/forge/test_instance/modify_overlay_test/replace_renderer.json b/src/test/generated/modify_overlay_test/data/forge/test_instance/modify_overlay_test/replace_renderer.json deleted file mode 100644 index f018811795..0000000000 --- a/src/test/generated/modify_overlay_test/data/forge/test_instance/modify_overlay_test/replace_renderer.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:modify_overlay_test/replace_renderer", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ No newline at end of file diff --git a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_bogged.json b/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_bogged.json deleted file mode 100644 index 524b689a40..0000000000 --- a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_bogged.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:shears_behavior/custom_shears_shear_bogged", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ No newline at end of file diff --git a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_mooshroom.json b/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_mooshroom.json deleted file mode 100644 index a3feb9f485..0000000000 --- a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_mooshroom.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:shears_behavior/custom_shears_shear_mooshroom", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ No newline at end of file diff --git a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sheep.json b/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sheep.json deleted file mode 100644 index 233ee31e38..0000000000 --- a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sheep.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:shears_behavior/custom_shears_shear_sheep", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ No newline at end of file diff --git a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_snowgolem.json b/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_snowgolem.json deleted file mode 100644 index a064501d08..0000000000 --- a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_snowgolem.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:shears_behavior/custom_shears_shear_snowgolem", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ No newline at end of file diff --git a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sulfur_cube_block.json b/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sulfur_cube_block.json deleted file mode 100644 index c7d041cc68..0000000000 --- a/src/test/generated/shears_behavior/data/forge/test_instance/shears_behavior/custom_shears_shear_sulfur_cube_block.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "minecraft:function", - "environment": "minecraft:default", - "function": "forge:shears_behavior/custom_shears_shear_sulfur_cube_block", - "max_ticks": 100, - "structure": "forge:empty3x3x3" -} \ 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 46d7c8bc4e..d8608adf1e 100644 --- a/src/test/generated/test_helper_mod/pack.mcmeta +++ b/src/test/generated/test_helper_mod/pack.mcmeta @@ -1,9 +1,9 @@ { "pack": { "description": "Forge tests resource pack", - "max_format": 107, + "max_format": 101, "min_format": [ - 107, + 101, 1 ] } diff --git a/src/test/java/com/example/examplemod/ExampleMod.java b/src/test/java/com/example/examplemod/ExampleMod.java index 86a8af6ba1..3b914dbdfb 100644 --- a/src/test/java/com/example/examplemod/ExampleMod.java +++ b/src/test/java/com/example/examplemod/ExampleMod.java @@ -68,7 +68,7 @@ public final class ExampleMod { public static final RegistryObject EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder() .withTabsBefore(CreativeModeTabs.COMBAT) .icon(() -> EXAMPLE_ITEM.get().getDefaultInstance()) - .displayItems((_, output) -> { + .displayItems((parameters, output) -> { output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event }).build()); diff --git a/src/test/java/net/minecraftforge/debug/chunk/LightingEventTest.java b/src/test/java/net/minecraftforge/debug/chunk/LightingEventTest.java index 220d8eb750..6603ac65d1 100644 --- a/src/test/java/net/minecraftforge/debug/chunk/LightingEventTest.java +++ b/src/test/java/net/minecraftforge/debug/chunk/LightingEventTest.java @@ -35,7 +35,7 @@ public class LightingEventTest extends BaseTestMod { @GameTest public static void testLightingEventFires(GameTestHelper helper) { var eventFired = helper.boolFlag("eventFired"); - helper.addEventListener(ChunkEvent.LightingCalculated.BUS, _ -> eventFired.set(true)); + helper.addEventListener(ChunkEvent.LightingCalculated.BUS, event -> eventFired.set(true)); var random = RandomSource.create(); var level = helper.getLevel(); diff --git a/src/test/java/net/minecraftforge/debug/client/AdditionalModelTest.java b/src/test/java/net/minecraftforge/debug/client/AdditionalModelTest.java index 6ace81ca45..e9ad288f81 100644 --- a/src/test/java/net/minecraftforge/debug/client/AdditionalModelTest.java +++ b/src/test/java/net/minecraftforge/debug/client/AdditionalModelTest.java @@ -16,6 +16,7 @@ import net.minecraft.client.model.animal.cow.CowModel; import net.minecraft.client.model.animal.pig.PigModel; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.block.MovingBlockRenderState; +import net.minecraft.client.renderer.block.model.BlockStateModelWrapper; import net.minecraft.client.renderer.entity.LivingEntityRenderer; import net.minecraft.client.renderer.entity.layers.RenderLayer; import net.minecraft.client.renderer.entity.state.LivingEntityRenderState; @@ -26,7 +27,7 @@ import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; import net.minecraft.gametest.framework.GameTestHelper; -import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.animal.cow.Cow; import net.minecraft.world.entity.animal.pig.Pig; import net.minecraft.world.item.Item; @@ -118,7 +119,7 @@ public class AdditionalModelTest extends BaseTestMod { // An example on how to render both the item and block model variants public void onAddLayers(EntityRenderersEvent.AddLayers event) { // Pigs get a block on their head, this is a test of going through the ItemModel loader - LivingEntityRenderer pig = event.getEntityRenderer(EntityTypes.PIG); + LivingEntityRenderer pig = event.getEntityRenderer(EntityType.PIG); pig.addLayer(new RenderLayer<>(pig) { @Override public void submit(PoseStack stack, SubmitNodeCollector source, int light, PigRenderState state, float xRot, float yRot) { @@ -142,7 +143,7 @@ public class AdditionalModelTest extends BaseTestMod { // Cows get a block on their head, this is a test of going through the BlockModel loader - LivingEntityRenderer cow = event.getEntityRenderer(EntityTypes.COW); + LivingEntityRenderer cow = event.getEntityRenderer(EntityType.COW); cow.addLayer(new RenderLayer<>(cow) { @Override public void submit(PoseStack stack, SubmitNodeCollector source, int light, LivingEntityRenderState cowState, float xRot, float yRot) { @@ -158,7 +159,7 @@ public class AdditionalModelTest extends BaseTestMod { var state = new MovingBlockRenderState(); state.blockState = COW_HEAD_STATE.any(); - source.submitMovingBlock(stack, state, 0); + source.submitMovingBlock(stack, state); stack.popPose(); } } diff --git a/src/test/java/net/minecraftforge/debug/client/CustomParticleTypeTest.java b/src/test/java/net/minecraftforge/debug/client/CustomParticleTypeTest.java index 20576bda84..e7805e2eec 100644 --- a/src/test/java/net/minecraftforge/debug/client/CustomParticleTypeTest.java +++ b/src/test/java/net/minecraftforge/debug/client/CustomParticleTypeTest.java @@ -25,9 +25,9 @@ import java.util.Map; @Mod(CustomParticleTypeTest.MOD_ID) public class CustomParticleTypeTest extends BaseTestMod { public static final String MOD_ID = "custom_particle_type_test"; - private static final ParticleRenderType CUSTOM_TYPE = new ParticleRenderType("GRP_ONE", "G1"); - private static final ParticleRenderType CUSTOM_TYPE_TWO = new ParticleRenderType("GRP_TWO", "G2"); - private static final ParticleRenderType CUSTOM_TYPE_DUP = new ParticleRenderType("GRP_DUP", "GD"); + private static final ParticleRenderType CUSTOM_TYPE = new ParticleRenderType("GRP_ONE"); + private static final ParticleRenderType CUSTOM_TYPE_TWO = new ParticleRenderType("GRP_TWO"); + private static final ParticleRenderType CUSTOM_TYPE_DUP = new ParticleRenderType("GRP_DUP"); public CustomParticleTypeTest(FMLJavaModLoadingContext context) { super(context, false, false); diff --git a/src/test/java/net/minecraftforge/debug/client/FluidBucketModelTest.java b/src/test/java/net/minecraftforge/debug/client/FluidBucketModelTest.java deleted file mode 100644 index c5e117e7eb..0000000000 --- a/src/test/java/net/minecraftforge/debug/client/FluidBucketModelTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) Forge Development LLC and contributors - * SPDX-License-Identifier: LGPL-2.1-only - */ - -package net.minecraftforge.debug.client; - -import java.util.function.Consumer; - -import net.minecraft.client.renderer.block.FluidModel; -import net.minecraft.client.resources.model.sprite.Material; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.item.BucketItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.LiquidBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.level.material.PushReaction; -import net.minecraftforge.client.event.ModelEvent.BakeFluidModels; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.common.SoundActions; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.ForgeFlowingFluid; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.gametest.GameTestNamespace; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; -import net.minecraftforge.test.BaseTestMod; - -@GameTestNamespace("forge") -@Mod(FluidBucketModelTest.MODID) -public class FluidBucketModelTest extends BaseTestMod { - public static final String MODID = "fluid_bucket_model"; - - private static final DeferredRegister BLOCKS = DeferredRegister.create(Registries.BLOCK, MODID); - private static final DeferredRegister ITEMS = DeferredRegister.create(Registries.ITEM, MODID); - private static final DeferredRegister FLUIDS = DeferredRegister.create(Registries.FLUID, MODID); - private static final DeferredRegister FLUID_TYPES = DeferredRegister.create(ForgeRegistries.FLUID_TYPES, MODID); - - - private static ForgeFlowingFluid.Properties FLUID_PROPERTIES; - private static final RegistryObject GAS_STILL = FLUIDS.register("gas", () -> new ForgeFlowingFluid.Source(FLUID_PROPERTIES)); - private static final RegistryObject GAS_FLOWING = FLUIDS.register("gas_flowing", () -> new ForgeFlowingFluid.Flowing(FLUID_PROPERTIES)); - - private static final FluidType.Properties GAS_PROPERTIES = FluidType.Properties.create() - .lightLevel(10) - .density(-1600) - .viscosity(100) - .sound(SoundActions.BUCKET_FILL, SoundEvents.BUCKET_FILL) - .sound(SoundActions.BUCKET_EMPTY, SoundEvents.BUCKET_EMPTY) - .sound(SoundActions.FLUID_VAPORIZE, SoundEvents.FIRE_EXTINGUISH); - - private static final Identifier GAS_STILL_TEXTURE = rl("minecraft", "block/water_still"); - private static final Identifier GAS_FLOWING_TEXTURE = rl("minecraft", "block/water_flow"); - - public static final RegistryObject GAS_TYPE = FLUID_TYPES.register("gas", () -> { - return new FluidType(GAS_PROPERTIES) { - @Override - public void initializeClient(final Consumer consumer) { - consumer.accept(new IClientFluidTypeExtensions() { - @Override - public Identifier getStillTexture() { - return GAS_STILL_TEXTURE; - } - @Override - public Identifier getFlowingTexture() { - return GAS_FLOWING_TEXTURE; - } - }); - } - }; - }); - - public static final RegistryObject GAS_BLOCK = BLOCKS.register("gas", () -> new LiquidBlock( - GAS_STILL, - Block.Properties.of() - .replaceable() - .noCollision() - .strength(100) - .pushReaction(PushReaction.DESTROY) - .noLootTable() - .liquid() - .sound(SoundType.EMPTY) - .setId(BLOCKS.key("gas")) - )); - - public static final RegistryObject GAS_BUCKET = ITEMS.register("gas_bucket", () -> new BucketItem(GAS_STILL, new Item.Properties().setId(ITEMS.key("gas_bucket")))); - - static { - FLUID_PROPERTIES = new ForgeFlowingFluid.Properties(GAS_TYPE, GAS_STILL, GAS_FLOWING).block(GAS_BLOCK).bucket(GAS_BUCKET); - } - - - public static final RegistryObject BUCKET = ITEMS.register("bucket", () -> new BucketItem(() -> Fluids.LAVA, new Item.Properties().setId(ITEMS.key("bucket")))); - - public FluidBucketModelTest(FMLJavaModLoadingContext context) { - super(context, false, true); - this.testItem(_ -> BUCKET.get().getDefaultInstance()); - BakeFluidModels.BUS.addListener(this::registerFluidModels); - } - - private void registerFluidModels(BakeFluidModels event) { - var gas_model = new FluidModel.Unbaked( - new Material(GAS_STILL_TEXTURE), - new Material(GAS_FLOWING_TEXTURE), - null, - null - ); - var gas_baked = gas_model.bake(event.materials(), () -> "Gas"); - event.register(GAS_STILL.get(), gas_baked); - event.register(GAS_FLOWING.get(), gas_baked); - } -} diff --git a/src/test/java/net/minecraftforge/debug/client/GuiLayeringTest.java b/src/test/java/net/minecraftforge/debug/client/GuiLayeringTest.java index cb11d6a649..73e70c7c91 100644 --- a/src/test/java/net/minecraftforge/debug/client/GuiLayeringTest.java +++ b/src/test/java/net/minecraftforge/debug/client/GuiLayeringTest.java @@ -35,11 +35,11 @@ public class GuiLayeringTest { public static void guiOpen(ScreenEvent.Init.Post event) { if (event.getScreen() instanceof AbstractContainerScreen && ENABLED) { event.addListener(Button.builder(Component.literal("Test Gui Layering"), btn -> { - Minecraft.getInstance().gui.pushLayer(new TestLayer(Component.literal("LayerScreen"))); + Minecraft.getInstance().pushGuiLayer(new TestLayer(Component.literal("LayerScreen"))); }).pos(2,2).size(150, 20).build()); event.addListener(Button.builder(Component.literal("Test Gui Normal"), btn -> { - Minecraft.getInstance().gui.setScreen(new TestLayer(Component.literal("LayerScreen"))); + Minecraft.getInstance().setScreen(new TestLayer(Component.literal("LayerScreen"))); }).pos(2, 25).size(150, 20).build()); } } @@ -78,15 +78,15 @@ public class GuiLayeringTest { } private void closeStack(Button button) { - this.minecraft.gui.setScreen(null); + this.minecraft.setScreen(null); } private void popLayerButton(Button button) { - this.minecraft.gui.popLayer(); + this.minecraft.popGuiLayer(); } private void pushLayerButton(Button button) { - this.minecraft.gui.pushLayer(new TestLayer(Component.literal("LayerScreen"))); + this.minecraft.pushGuiLayer(new TestLayer(Component.literal("LayerScreen"))); } } } diff --git a/src/test/java/net/minecraftforge/debug/client/ModifyOverlayTest.java b/src/test/java/net/minecraftforge/debug/client/ModifyOverlayTest.java index dfe6e7c623..4dd35eb55c 100644 --- a/src/test/java/net/minecraftforge/debug/client/ModifyOverlayTest.java +++ b/src/test/java/net/minecraftforge/debug/client/ModifyOverlayTest.java @@ -5,7 +5,6 @@ package net.minecraftforge.debug.client; -import net.minecraft.client.Minecraft; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.resources.Identifier; import net.minecraftforge.client.event.AddGuiOverlayLayersEvent; @@ -32,20 +31,14 @@ public class ModifyOverlayTest extends BaseTestMod { private static final Identifier myStackName = name("my_stack_name"); private static final ForgeLayeredDraw myLayerStack = new ForgeLayeredDraw(myStackName); - private static final ForgeLayer notAddedLayer = (_, _) -> {}; - private static final ForgeLayer layerA = (_,_) -> {}; + private static final ForgeLayer notAddedLayer = (gg, tr) -> {}; + private static final ForgeLayer layerA = (gg,tr) -> {}; private static final Identifier layerAName = name("layer_a"); - private static final ForgeLayer layerB = (_,_) -> {}; + private static final ForgeLayer layerB = (gg,tr) -> {}; private static final Identifier layerBName = name("layer_b"); - private static final ForgeLayer layerC = (_,_) -> {}; + private static final ForgeLayer layerC = (gg,tr) -> {}; private static final Identifier layerCName = name("layer_c"); - private static final IForgeGameTestHelper.BoolFlag detectReplaceFlag = new IForgeGameTestHelper.BoolFlag("det_replace_flag"); - // Wrapper renderer since we just need to change the callee location to test - private static final ForgeLayer replacementRenderer = (gg, tracker) -> { - Minecraft.getInstance().gui.hud.extractEffects(gg, tracker); - detectReplaceFlag.set(true); - }; private static final IForgeGameTestHelper.BoolFlag detectConditionFlag = new IForgeGameTestHelper.BoolFlag("det_cond_flag"); private static final IForgeGameTestHelper.BoolFlag detectConditionStackFlag = new IForgeGameTestHelper.BoolFlag("det_cond_stack_flag"); @@ -85,7 +78,6 @@ public class ModifyOverlayTest extends BaseTestMod { }); } - @SuppressWarnings("unchecked") @GameTest public static void ordered_layers(GameTestHelper helper) { // Test that layers are in the correct order. @@ -97,9 +89,9 @@ public class ModifyOverlayTest extends BaseTestMod { var field1 = cls.getDeclaredField("namedLayers"); field.setAccessible(true); field1.setAccessible(true); - var VROOT = ((Map>) field.get(drawStack)); - var PSS = ((ForgeLayeredDraw)VROOT.get(PRE_SLEEP_STACK).getKey()); - check = ((Map)field1.get(PSS)); + Map> VROOT = ((Map>) field.get(drawStack)); + var PSS = ((ForgeLayeredDraw) VROOT.get(PRE_SLEEP_STACK).getKey()); + check = ((Map) field1.get(PSS)); internalLayersList = getInternalLayersList(PSS); } catch (Exception e) { helper.fail("Threw a " + e.getMessage() + " when trying to get the inner layer list."); @@ -127,13 +119,6 @@ public class ModifyOverlayTest extends BaseTestMod { }); } - @GameTest - public static void replace_renderer(GameTestHelper helper) { - helper.assertTrue(detectReplaceFlag.getBool(), "Replace flag was not set."); - detectReplaceFlag.set(false); - helper.succeed(); - } - private void overlayTestListener(AddGuiOverlayLayersEvent event) { drawStack = event.getLayeredDraw(); var layeredDraw = event.getLayeredDraw(); @@ -143,7 +128,6 @@ public class ModifyOverlayTest extends BaseTestMod { // Layers have to be present to be ordered against, of course, but we tested for that already above. pEffects.addAbove(layerBName, POTION_EFFECTS, layerB); pEffects.addAbove(layerCName, layerBName, layerC); - layeredDraw.replace(PRE_SLEEP_STACK, POTION_EFFECTS, replacementRenderer); layeredDraw.addBelow(PRE_SLEEP_STACK, layerAName, layerBName, layerA); layeredDraw.addConditionTo(PRE_SLEEP_STACK, BOSS_OVERLAY, () -> { if (enableConditionFlag.getBool()) { @@ -155,7 +139,7 @@ public class ModifyOverlayTest extends BaseTestMod { } }); - myLayerStack.add(name("my_inner_layer_name"), (_, _) -> { + myLayerStack.add(name("my_inner_layer_name"), (gg, tr) -> { detectConditionStackFlag.set(true); }); // Demonstrates that entire stacks can have conditions attached diff --git a/src/test/java/net/minecraftforge/debug/client/PictureInPictureTest.java b/src/test/java/net/minecraftforge/debug/client/PictureInPictureTest.java index 30cf1ab57f..ac8e27618d 100644 --- a/src/test/java/net/minecraftforge/debug/client/PictureInPictureTest.java +++ b/src/test/java/net/minecraftforge/debug/client/PictureInPictureTest.java @@ -11,7 +11,7 @@ import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.navigation.ScreenPosition; import net.minecraft.client.gui.navigation.ScreenRectangle; import net.minecraft.client.gui.render.pip.PictureInPictureRenderer; -import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.state.gui.pip.PictureInPictureRenderState; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraftforge.client.event.RegisterPictureInPictureRendererEvent; @@ -80,17 +80,21 @@ public class PictureInPictureTest extends BaseTestMod { } private void registerTestPip(RegisterPictureInPictureRendererEvent event) { - event.register(new TestPipRenderer()); + event.register(new TestPipRenderer(event.getBufferSource())); } static class TestPipRenderer extends PictureInPictureRenderer { + protected TestPipRenderer(MultiBufferSource.BufferSource bufferSource) { + super(bufferSource); + } + @Override public Class getRenderStateClass() { return TestPipRendererState.class; } @Override - protected void renderToTexture(TestPipRendererState state, PoseStack poseStack, SubmitNodeCollector collector) { + protected void renderToTexture(TestPipRendererState state, PoseStack poseStack) { var graphics = state.graphics(); int red = Color.red.getRGB(); int x1 = state.x0 - 1; diff --git a/src/test/java/net/minecraftforge/debug/client/RenderFrameLayerTest.java b/src/test/java/net/minecraftforge/debug/client/RenderFrameLayerTest.java index 7289f76007..0394bb46dc 100644 --- a/src/test/java/net/minecraftforge/debug/client/RenderFrameLayerTest.java +++ b/src/test/java/net/minecraftforge/debug/client/RenderFrameLayerTest.java @@ -5,7 +5,6 @@ package net.minecraftforge.debug.client; -import net.minecraft.client.DeltaTracker; import net.minecraft.client.renderer.LevelTargetBundle; import net.minecraft.client.renderer.state.level.LevelRenderState; import net.minecraftforge.client.FramePassManager; @@ -24,8 +23,6 @@ import net.minecraft.world.phys.AABB; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.framegraph.FramePass; -import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NullMarked; @GameTestNamespace("forge") @Mod(RenderFrameLayerTest.MODID) @@ -51,11 +48,10 @@ public class RenderFrameLayerTest extends BaseTestMod { /** * If this is working, two white line box cubes will be rendered at ground level in a superflat world around (0,0) */ - @NullMarked public static void renderTest(AddFramePassEvent event) { FramePassManager.PassDefinition def = new FramePassManager.PassDefinition() { @Override - public void extracts(LevelTargetBundle bundle, FramePass pass, DeltaTracker dt) { + public void extracts(LevelTargetBundle bundle, FramePass pass) { bundle.main = pass.readsAndWrites(bundle.main); } @@ -76,7 +72,7 @@ public class RenderFrameLayerTest extends BaseTestMod { event.addPass(rl(MODID), def); FramePassManager.PassDefinition def2 = new FramePassManager.PassDefinition() { @Override - public void extracts(@NotNull LevelTargetBundle bundle, FramePass pass, DeltaTracker dt) { + public void extracts(LevelTargetBundle bundle, FramePass pass) { bundle.main = pass.readsAndWrites(bundle.main); } diff --git a/src/test/java/net/minecraftforge/debug/client/RenderTooltipTest.java b/src/test/java/net/minecraftforge/debug/client/RenderTooltipTest.java index e41c175078..d8faa016e0 100644 --- a/src/test/java/net/minecraftforge/debug/client/RenderTooltipTest.java +++ b/src/test/java/net/minecraftforge/debug/client/RenderTooltipTest.java @@ -61,10 +61,10 @@ public class RenderTooltipTest extends BaseTestMod { helper.addRecordListener(TickEvent.RenderTickEvent.Pre.BUS, (event) -> { if (shouldOpen == 1) { - Minecraft.getInstance().gui.setScreen(new InventoryScreen(Minecraft.getInstance().player)); + Minecraft.getInstance().setScreen(new InventoryScreen(Minecraft.getInstance().player)); shouldOpen = 2; } else if (shouldOpen == 2) { - Minecraft.getInstance().gui.setScreen(null); + Minecraft.getInstance().setScreen(null); shouldOpen = 0; } }); diff --git a/src/test/java/net/minecraftforge/debug/creativetabs/CreativeModeTabTest.java b/src/test/java/net/minecraftforge/debug/creativetabs/CreativeModeTabTest.java index 7a02eb32a9..8b7df7b3d6 100644 --- a/src/test/java/net/minecraftforge/debug/creativetabs/CreativeModeTabTest.java +++ b/src/test/java/net/minecraftforge/debug/creativetabs/CreativeModeTabTest.java @@ -53,7 +53,7 @@ public class CreativeModeTabTest { helper.register(LOGS, CreativeModeTab.builder().icon(() -> new ItemStack(Blocks.ACACIA_LOG)) .title(Component.literal("Logs")) .withLabelColor(0x00FF00) - .displayItems((_, output) -> { + .displayItems((params, output) -> { output.accept(new ItemStack(Blocks.ACACIA_LOG)); output.accept(new ItemStack(Blocks.BIRCH_LOG)); output.accept(new ItemStack(Blocks.DARK_OAK_LOG)); @@ -67,7 +67,7 @@ public class CreativeModeTabTest { .icon(() -> new ItemStack(Blocks.STONE)) .title(Component.literal("Stone")) .withLabelColor(0x0000FF) - .displayItems((_, output) -> { + .displayItems((params, output) -> { output.accept(new ItemStack(Blocks.STONE)); output.accept(new ItemStack(Blocks.GRANITE)); output.accept(new ItemStack(Blocks.DIORITE)); @@ -78,7 +78,7 @@ public class CreativeModeTabTest { helper.register(COLORS, CreativeModeTab.builder() .title(Component.literal("Colors")) - .displayItems((_, output) -> output.acceptAll(getDyes())) + .displayItems((params, output) -> output.acceptAll(getDyes())) .withTabFactory(CreativeModeColorTab::new) .withTabsBefore(STONE) .build() @@ -87,7 +87,7 @@ public class CreativeModeTabTest { helper.register(SEARCH, CreativeModeTab.builder() .title(Component.literal("Search")) .icon(() -> new ItemStack(Items.BOOKSHELF)) - .displayItems((_, output) -> output.acceptAll(getDyes())) + .displayItems((params, output) -> output.acceptAll(getDyes())) .withTabsBefore(COLORS) .withSearchBar() .build() @@ -99,7 +99,7 @@ public class CreativeModeTabTest { helper.register(Identifier.fromNamespaceAndPath(MOD_ID, "dummy" + i), CreativeModeTab.builder() .title(Component.literal("Dummy " + i)) .icon(() -> new ItemStack(block)) - .displayItems((_, output) -> output.accept(block)) + .displayItems((params, output) -> output.accept(block)) .build() ); } @@ -108,7 +108,7 @@ public class CreativeModeTabTest { helper.register(Identifier.fromNamespaceAndPath(MOD_ID, "with_tabs_image"), CreativeModeTab.builder() .title(Component.translatable("itemGroup.with_tabs_image")) .icon(() -> new ItemStack(Blocks.BRICKS)) - .displayItems((_, output) -> output.accept(Blocks.BRICKS)) + .displayItems((params, output) -> output.accept(Blocks.BRICKS)) //.withTabsImage(custom_tabs_image) .build()); }); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/block/ChorusBlockPlacementTest.java b/src/test/java/net/minecraftforge/debug/gameplay/block/ChorusBlockPlacementTest.java index dc64ab8251..b3f9aa54ac 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/block/ChorusBlockPlacementTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/block/ChorusBlockPlacementTest.java @@ -7,11 +7,11 @@ package net.minecraftforge.debug.gameplay.block; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; -import net.minecraft.data.tags.VanillaBlockTagsProvider; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraftforge.common.data.BlockTagsProvider; import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @@ -51,14 +51,14 @@ public class ChorusBlockPlacementTest extends BaseTestMod { event.getGenerator().addProvider(event.includeServer(), new BlockTagProvider(event)); } - private static final class BlockTagProvider extends VanillaBlockTagsProvider { + private static final class BlockTagProvider extends BlockTagsProvider { public BlockTagProvider(GatherDataEvent event) { super(event.getGenerator().getPackOutput(), event.getLookupProvider(), MOD_ID, event.getExistingFileHelper()); } @Override protected void addTags(HolderLookup.Provider provider) { - this.tag(BlockTags.SUPPORTS_CHORUS_PLANT).add(BLOCK.getKey()); + this.tag(BlockTags.SUPPORTS_CHORUS_PLANT).add(BLOCK.get()); } } } diff --git a/src/test/java/net/minecraftforge/debug/gameplay/block/PlantTypePlacementTest.java b/src/test/java/net/minecraftforge/debug/gameplay/block/PlantTypePlacementTest.java index b62099e71f..f1b4dd6e10 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/block/PlantTypePlacementTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/block/PlantTypePlacementTest.java @@ -45,9 +45,7 @@ public class PlantTypePlacementTest extends BaseTestMod { map.put(BlockTags.MOSS_BLOCKS, List.of(MOSS_BLOCK, PALE_MOSS_BLOCK)); map.put(BlockTags.GRASS_BLOCKS, List.of(GRASS_BLOCK, PODZOL, MYCELIUM)); map.put(BlockTags.SAND, List.of(SAND, RED_SAND, SUSPICIOUS_SAND)); - var terracotta = new ArrayList(Blocks.DYED_TERRACOTTA.asList()); - terracotta.add(TERRACOTTA); - map.put(BlockTags.TERRACOTTA, terracotta); + map.put(BlockTags.TERRACOTTA, List.of(TERRACOTTA, WHITE_TERRACOTTA, ORANGE_TERRACOTTA, MAGENTA_TERRACOTTA, LIGHT_BLUE_TERRACOTTA, YELLOW_TERRACOTTA, LIME_TERRACOTTA, PINK_TERRACOTTA, GRAY_TERRACOTTA, LIGHT_GRAY_TERRACOTTA, CYAN_TERRACOTTA, PURPLE_TERRACOTTA, BLUE_TERRACOTTA, BROWN_TERRACOTTA, GREEN_TERRACOTTA, RED_TERRACOTTA, BLACK_TERRACOTTA)); map.put(BlockTags.NYLIUM, List.of(CRIMSON_NYLIUM, WARPED_NYLIUM)); map.put(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT, List.of(MYCELIUM, PODZOL, CRIMSON_NYLIUM, WARPED_NYLIUM)); }); @@ -413,7 +411,7 @@ public class PlantTypePlacementTest extends BaseTestMod { } @SafeVarargs - private static Collection join(GameTestHelper helper, TagKey... tags) { + private static Collection join(GameTestHelper helper, @SuppressWarnings("unchecked") TagKey... tags) { var ret = new HashSet(); for (var tag : tags) ret.addAll(known(helper, tag)); 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 f6e849c1d7..05553d29eb 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/crafting/ConditionalRecipeTest.java @@ -18,10 +18,10 @@ import net.minecraft.data.recipes.SimpleCookingRecipeBuilder; import net.minecraft.data.recipes.SingleItemRecipeBuilder; import net.minecraft.data.tags.VanillaItemTagsProvider; import net.minecraft.gametest.framework.GameTestHelper; -import net.minecraft.references.ItemIds; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.CookingBookCategory; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; @@ -33,6 +33,7 @@ import net.minecraftforge.common.Tags; import net.minecraftforge.common.crafting.ConditionalRecipe; import net.minecraftforge.common.crafting.SimpleCraftingContainer; import net.minecraftforge.common.crafting.conditions.IConditionBuilder; +import net.minecraftforge.common.data.BlockTagsProvider; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.fml.common.Mod; @@ -54,6 +55,8 @@ public class ConditionalRecipeTest extends BaseTestMod { public void gatherData(GatherDataEvent event) { var gen = event.getGenerator(); gen.addProvider(event.includeServer(), new Recipes.Runner(gen.getPackOutput(), event.getLookupProvider())); + var testBlockTags = new TestBlockTags(gen.getPackOutput(), event.getLookupProvider(), event.getExistingFileHelper()); + gen.addProvider(event.includeServer(), testBlockTags); gen.addProvider(event.includeServer(), new TestItemTags(gen.getPackOutput(), event.getLookupProvider(), event.getExistingFileHelper())); } @@ -168,6 +171,17 @@ public class ConditionalRecipeTest extends BaseTestMod { ); } + public static class TestBlockTags extends BlockTagsProvider { + public TestBlockTags(PackOutput output, CompletableFuture lookupProvider, ExistingFileHelper existingFileHelper) { + super(output, lookupProvider, MODID, existingFileHelper); + } + + @Override + protected void addTags(HolderLookup.Provider registries) { + // No block tags needed; just need a block provider content-getter to supply to the item tags generator + } + } + public static class TestItemTags extends VanillaItemTagsProvider { public TestItemTags(PackOutput output, CompletableFuture lookupProvider, ExistingFileHelper existingFileHelper) { super(output, lookupProvider, MODID, existingFileHelper); @@ -176,7 +190,7 @@ public class ConditionalRecipeTest extends BaseTestMod { @Override protected void addTags(HolderLookup.Provider registries) { // Empty out the Forge eggs tag for purposes of testing the tag-empty recipe condition - this.tag(Tags.Items.EGGS).remove(ItemIds.EGG); + this.tag(Tags.Items.EGGS).remove(Items.EGG); } } 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 68bd6ae49a..e0afa34fe8 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/crafting/CustomIngredientsTest.java @@ -9,6 +9,8 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Function; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import org.jetbrains.annotations.Nullable; + import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderLookup.Provider; import net.minecraft.core.component.DataComponents; @@ -21,7 +23,6 @@ import net.minecraft.data.recipes.ShapedRecipeBuilder; import net.minecraft.data.tags.VanillaItemTagsProvider; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.nbt.CompoundTag; -import net.minecraft.references.BlockItemIds; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; @@ -37,6 +38,7 @@ import net.minecraft.world.level.ItemLike; import net.minecraftforge.common.crafting.SimpleCraftingContainer; import net.minecraftforge.common.crafting.conditions.IConditionBuilder; import net.minecraftforge.common.crafting.ingredients.IIngredientBuilder; +import net.minecraftforge.common.data.BlockTagsProvider; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.common.util.INBTBuilder; import net.minecraftforge.data.event.GatherDataEvent; @@ -67,7 +69,9 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { var look = event.getLookupProvider(); var exist = event.getExistingFileHelper(); - gen.addProvider(event.includeServer(), new ItemTagsGen(out, look, exist)); + 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.Runner(out, event.getLookupProvider())); } @@ -222,15 +226,25 @@ public class CustomIngredientsTest extends BaseTestMod implements INBTBuilder { assertRecipeMatch(helper, RecipeType.CRAFTING, container.apply(stack(Items.DIRT)), "difference_ingredient"); assertRecipeMiss(helper, RecipeType.CRAFTING, container.apply(stack(Items.STONE))); } + + private static class BlockTagsGen extends BlockTagsProvider { + public BlockTagsGen(PackOutput out, CompletableFuture look, @Nullable ExistingFileHelper exist) { + super(out, look, MODID, exist); + } + + @Override + public void addTags(HolderLookup.Provider lookup) { } + } + private static class ItemTagsGen extends VanillaItemTagsProvider { - public ItemTagsGen(PackOutput out, CompletableFuture lookup, ExistingFileHelper existing) { - super(out, lookup, MODID, existing); + public ItemTagsGen(PackOutput out, CompletableFuture lookup, BlockTagsProvider blocks, ExistingFileHelper existing) { + super(out, lookup, /*blocks.contentsGetter(),*/ MODID, existing); } @Override public void addTags(HolderLookup.Provider lookup) { - tag(LEFT).add(BlockItemIds.DIRT.item(), BlockItemIds.STONE.item()); - tag(RIGHT).add(BlockItemIds.STONE.item(), BlockItemIds.GRAVEL.item()); + tag(LEFT).add(Items.DIRT, Items.STONE); + tag(RIGHT).add(Items.STONE, Items.GRAVEL); } } 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 669a39095b..a7d239b1ce 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/criterion/BreakWithItemCriterion.java @@ -8,12 +8,11 @@ package net.minecraftforge.debug.gameplay.criterion; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import org.jspecify.annotations.NullMarked; - -import net.minecraft.advancements.predicates.BlockPredicate; -import net.minecraft.advancements.predicates.ContextAwarePredicate; -import net.minecraft.advancements.predicates.ItemPredicate; -import net.minecraft.advancements.triggers.Criterion; -import net.minecraft.advancements.triggers.SimpleCriterionTrigger; +import net.minecraft.advancements.Criterion; +import net.minecraft.advancements.criterion.BlockPredicate; +import net.minecraft.advancements.criterion.ContextAwarePredicate; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.criterion.SimpleCriterionTrigger; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; diff --git a/src/test/java/net/minecraftforge/debug/gameplay/criterion/CriterionTest.java b/src/test/java/net/minecraftforge/debug/gameplay/criterion/CriterionTest.java index e6f38e19cf..3b0e0452c5 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/criterion/CriterionTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/criterion/CriterionTest.java @@ -9,9 +9,9 @@ import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementRequirements; import net.minecraft.advancements.AdvancementType; -import net.minecraft.advancements.predicates.BlockPredicate; -import net.minecraft.advancements.predicates.ItemPredicate; -import net.minecraft.advancements.triggers.CriterionTrigger; +import net.minecraft.advancements.CriterionTrigger; +import net.minecraft.advancements.criterion.BlockPredicate; +import net.minecraft.advancements.criterion.ItemPredicate; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; @@ -19,7 +19,6 @@ import net.minecraft.core.registries.Registries; import net.minecraft.data.tags.VanillaItemTagsProvider; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.network.chat.Component; -import net.minecraft.references.ItemIds; import net.minecraft.resources.Identifier; import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.TagKey; @@ -108,12 +107,12 @@ public final class CriterionTest extends BaseTestMod { @Override protected void addTags(HolderLookup.Provider lookup) { this.tag(tag) - .add(ItemIds.COD) - .add(ItemIds.SALMON) - .add(ItemIds.TROPICAL_FISH) - .add(ItemIds.PUFFERFISH) - .add(ItemIds.COOKED_COD) - .add(ItemIds.COOKED_SALMON) + .add(Items.COD) + .add(Items.SALMON) + .add(Items.TROPICAL_FISH) + .add(Items.PUFFERFISH) + .add(Items.COOKED_COD) + .add(Items.COOKED_SALMON) ; } }); @@ -125,7 +124,7 @@ public final class CriterionTest extends BaseTestMod { event.getGenerator().getPackOutput(), event.getLookupProvider(), event.getExistingFileHelper(), - List.of(((registries, saver, _) -> { + List.of(((registries, saver, existingFileHelper) -> { var blocks = registries.lookup(Registries.BLOCK).get(); var items = registries.lookup(Registries.ITEM).get(); saver.accept(new Advancement.Builder() diff --git a/src/test/java/net/minecraftforge/debug/gameplay/item/PreventItemDamageTest.java b/src/test/java/net/minecraftforge/debug/gameplay/item/PreventItemDamageTest.java index 5c804f61b2..fea2567fb5 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/item/PreventItemDamageTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/item/PreventItemDamageTest.java @@ -17,7 +17,7 @@ import net.minecraft.tags.DamageTypeTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageTypes; -import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -50,7 +50,7 @@ public class PreventItemDamageTest extends BaseTestMod { public PreventItemDamageTest(FMLJavaModLoadingContext context) { super(context, false, true); - this.testItem(_ -> FAKE_SHIELD.get().getDefaultInstance()); + this.testItem(lookup -> FAKE_SHIELD.get().getDefaultInstance()); } @GameTest @@ -90,7 +90,7 @@ public class PreventItemDamageTest extends BaseTestMod { int initialDamage = shield.getDamageValue(); // setup enemy - var enemy = helper.spawnWithNoFreeWill(EntityTypes.HUSK, new BlockPos(2, 0, 2)); + var enemy = helper.spawnWithNoFreeWill(EntityType.HUSK, new BlockPos(2, 0, 2)); player.lookAt(EntityAnchorArgument.Anchor.EYES, enemy.position()); // hit the player @@ -117,7 +117,7 @@ public class PreventItemDamageTest extends BaseTestMod { helper.makeFloor(); // setup player - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); // setup shield var shield = FAKE_SHIELD.get().getDefaultInstance(); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/item/ShearsBehaviorTest.java b/src/test/java/net/minecraftforge/debug/gameplay/item/ShearsBehaviorTest.java index 77ac4ad264..e7b7276abb 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/item/ShearsBehaviorTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/item/ShearsBehaviorTest.java @@ -6,16 +6,11 @@ package net.minecraftforge.debug.gameplay.item; import net.minecraft.core.BlockPos; -import net.minecraft.core.component.DataComponents; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityTypes; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.animal.cow.MushroomCow; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.animal.golem.CopperGolem; import net.minecraft.world.entity.decoration.LeashFenceKnotEntity; -import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -49,16 +44,8 @@ public class ShearsBehaviorTest extends BaseTestMod { public ShearsBehaviorTest(FMLJavaModLoadingContext context) { super(context, false, true); - this.testItem(_ -> CUSTOM_SHEARS_ITEM.get().getDefaultInstance()); - this.testItem(_ -> CUSTOM_SHEARS_HARVEST_ITEM.get().getDefaultInstance()); - } - - private static void shear(GameTestHelper helper, Entity entity) { - var player = helper.makeMockServerPlayer(GameType.SURVIVAL); - var shears = CUSTOM_SHEARS_HARVEST_ITEM.get().getDefaultInstance(); - player.setItemInHand(InteractionHand.MAIN_HAND, shears); - var result = player.interactOn(entity, InteractionHand.MAIN_HAND, Vec3.ZERO); - helper.assertTrue(result.consumesAction(), "Using entity should result in consume action"); + this.testItem(lookup -> CUSTOM_SHEARS_ITEM.get().getDefaultInstance()); + this.testItem(lookup -> CUSTOM_SHEARS_HARVEST_ITEM.get().getDefaultInstance()); } @GameTest @@ -69,14 +56,19 @@ public class ShearsBehaviorTest extends BaseTestMod { var fencePos = new BlockPos(1, 1, 1); var cowPos = new BlockPos(0, 1, 1); helper.setBlock(fencePos, Blocks.OAK_FENCE); - var cow = helper.spawnWithNoFreeWill(EntityTypes.COW, cowPos); + var cow = helper.spawnWithNoFreeWill(EntityType.COW, cowPos); var knot = LeashFenceKnotEntity.getOrCreateKnot(helper.getLevel(), helper.absolutePos(fencePos)); cow.setLeashedTo(knot, true); helper.assertTrue(cow.isLeashed(), "Cow should start leashed"); - shear(helper, cow); + // act: interact with cow using custom shears + var player = helper.makeMockPlayer(GameType.SURVIVAL); + var shears = CUSTOM_SHEARS_HARVEST_ITEM.get().getDefaultInstance(); + player.setItemInHand(InteractionHand.MAIN_HAND, shears); + var result = player.interactOn(cow, InteractionHand.MAIN_HAND, Vec3.ZERO); // assert + helper.assertTrue(result.consumesAction(), "Using custom shears on leashed cow should result in consume action"); helper.assertTrue(!cow.isLeashed(), "Cow should be unleashed by custom shears"); helper.assertItemEntityPresent(Items.LEAD); @@ -92,14 +84,19 @@ public class ShearsBehaviorTest extends BaseTestMod { var fencePos = new BlockPos(1, 1, 1); var cowPos = new BlockPos(0, 1, 1); helper.setBlock(fencePos, Blocks.OAK_FENCE); - var cow = helper.spawnWithNoFreeWill(EntityTypes.COW, cowPos); + var cow = helper.spawnWithNoFreeWill(EntityType.COW, cowPos); var knot = LeashFenceKnotEntity.getOrCreateKnot(helper.getLevel(), helper.absolutePos(fencePos)); cow.setLeashedTo(knot, true); helper.assertTrue(cow.isLeashed(), "Cow should start leashed"); - shear(helper, knot); + // act: interact with knot using custom shears + var player = helper.makeMockPlayer(GameType.SURVIVAL); + var shears = CUSTOM_SHEARS_HARVEST_ITEM.get().getDefaultInstance(); + player.setItemInHand(InteractionHand.MAIN_HAND, shears); + var result = player.interactOn(knot, InteractionHand.MAIN_HAND, Vec3.ZERO); // assert + helper.assertTrue(result.consumesAction(), "Using custom shears on leash knot should result in consume action"); helper.assertTrue(!cow.isLeashed(), "Cow should be unleashed by sheared knot"); helper.assertItemEntityPresent(Items.LEAD); @@ -112,114 +109,24 @@ public class ShearsBehaviorTest extends BaseTestMod { // setup: copper golem with poppy var golemPos = new BlockPos(1, 1, 1); - var golem = helper.spawnWithNoFreeWill(EntityTypes.COPPER_GOLEM, golemPos); + var golem = helper.spawnWithNoFreeWill(EntityType.COPPER_GOLEM, golemPos); golem.setItemSlot(CopperGolem.EQUIPMENT_SLOT_ANTENNA, new ItemStack(Items.POPPY)); helper.assertTrue(golem.readyForShearing(), "Golem should start shearable (has poppy)"); - shear(helper, golem); + // act: interact with copper golem using custom shears + var player = helper.makeMockPlayer(GameType.SURVIVAL); + var shears = CUSTOM_SHEARS_ITEM.get().getDefaultInstance(); + player.setItemInHand(InteractionHand.MAIN_HAND, shears); + var result = player.interactOn(golem, InteractionHand.MAIN_HAND, Vec3.ZERO); // assert + helper.assertTrue(result.consumesAction(), "Using custom shears on copper golem should result in consume action"); helper.assertTrue(golem.getItemBySlot(CopperGolem.EQUIPMENT_SLOT_ANTENNA).isEmpty(), "Copper golem poppy should be sheared off with custom shears"); helper.assertItemEntityPresent(Items.POPPY); helper.succeed(); } - @GameTest - public static void custom_shears_shear_sulfur_cube_block(GameTestHelper helper) { - helper.makeFloor(); - - // setup: sulfur cube with block - var pos = new BlockPos(1, 1, 1); - var sulfurCube = helper.spawnWithNoFreeWill(EntityTypes.SULFUR_CUBE, pos); - sulfurCube.setItemSlot(EquipmentSlot.BODY, new ItemStack(Items.DIRT)); - helper.assertTrue(sulfurCube.readyForShearing(), "Sulfur cube should start shearable (has dirt block)"); - - shear(helper, sulfurCube); - - // assert - helper.assertTrue(sulfurCube.getItemBySlot(EquipmentSlot.BODY).isEmpty(), "Sulfur cube block should be sheared off with custom shears"); - helper.assertItemEntityPresent(Items.DIRT); - - helper.succeed(); - } - - @GameTest - public static void custom_shears_shear_bogged(GameTestHelper helper) { - helper.makeFloor(); - - var pos = new BlockPos(1, 1, 1); - var entity = helper.spawnWithNoFreeWill(EntityTypes.BOGGED, pos); - helper.assertTrue(entity.readyForShearing(), "Bogged start shearable"); - - shear(helper, entity); - - // assert - helper.assertTrue(!entity.readyForShearing(), "Bogged should no longer be shearable"); - int found = 0; - for (var item : helper.getEntities(EntityTypes.ITEM, BlockPos.ZERO, 3)) { - if (item.isAlive() && (item.getItem().is(Items.BROWN_MUSHROOM) || item.getItem().is(Items.RED_MUSHROOM))) - found += item.getItem().count(); - } - helper.assertValueEqual(found, 2, "Mushroom loot not found"); - - helper.succeed(); - } - - @GameTest - public static void custom_shears_shear_mooshroom(GameTestHelper helper) { - helper.makeFloor(); - - var pos = new BlockPos(1, 1, 1); - var entity = helper.spawnWithNoFreeWill(EntityTypes.MOOSHROOM, pos); - entity.setComponent(DataComponents.MOOSHROOM_VARIANT, MushroomCow.Variant.RED); - helper.assertTrue(entity.readyForShearing(), "Mooshroom start shearable"); - - shear(helper, entity); - - // assert - helper.assertTrue(!entity.isAlive(), "Mooshroom should no longer be alive"); - helper.assertEntityPresent(EntityTypes.COW); - helper.assertItemEntityPresent(Items.RED_MUSHROOM); - - helper.succeed(); - } - - @GameTest - public static void custom_shears_shear_sheep(GameTestHelper helper) { - helper.makeFloor(); - - var pos = new BlockPos(1, 1, 1); - var entity = helper.spawnWithNoFreeWill(EntityTypes.SHEEP, pos); - entity.setColor(DyeColor.WHITE); - helper.assertTrue(entity.readyForShearing(), "Sheep should start shearable"); - - shear(helper, entity); - - // assert - helper.assertTrue(!entity.readyForShearing(), "Sheep should no longer be shearable"); - helper.assertItemEntityPresent(Items.WOOL.white()); - - helper.succeed(); - } - - @GameTest - public static void custom_shears_shear_snowgolem(GameTestHelper helper) { - helper.makeFloor(); - - var pos = new BlockPos(1, 1, 1); - var entity = helper.spawnWithNoFreeWill(EntityTypes.SNOW_GOLEM, pos); - helper.assertTrue(entity.readyForShearing(), "Snow golem should start shearable"); - - shear(helper, entity); - - // assert - helper.assertTrue(!entity.readyForShearing(), "Snow golem should no longer be shearable"); - helper.assertItemEntityPresent(Items.CARVED_PUMPKIN); - - helper.succeed(); - } - private static final class ShearsHarvestItem extends Item { ShearsHarvestItem(Item.Properties properties) { super(properties); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/item/ShieldDisablingTest.java b/src/test/java/net/minecraftforge/debug/gameplay/item/ShieldDisablingTest.java index 6a26db4c71..cc9f1c2f8d 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/item/ShieldDisablingTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/item/ShieldDisablingTest.java @@ -13,7 +13,7 @@ import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageTypes; -import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -39,14 +39,14 @@ public final class ShieldDisablingTest extends BaseTestMod { @GameTest public static void player_shield_disabled_by_axe(GameTestHelper helper) { player_shield_disabled_common(helper, h -> Util.make( - h.spawnWithNoFreeWill(EntityTypes.HUSK, new BlockPos(2, 0, 2)), + h.spawnWithNoFreeWill(EntityType.HUSK, new BlockPos(2, 0, 2)), enemy -> enemy.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.IRON_AXE)) )); } @GameTest public static void player_shield_disabled_by_warden(GameTestHelper helper) { - player_shield_disabled_common(helper, h -> h.spawnWithNoFreeWill(EntityTypes.WARDEN, new BlockPos(2, 0, 2))); + player_shield_disabled_common(helper, h -> h.spawnWithNoFreeWill(EntityType.WARDEN, new BlockPos(2, 0, 2))); } private static void player_shield_disabled_common(GameTestHelper helper, Function enemyGetter) { diff --git a/src/test/java/net/minecraftforge/debug/gameplay/level/TrySleepTest.java b/src/test/java/net/minecraftforge/debug/gameplay/level/TrySleepTest.java index 6010a38474..4252c3c7db 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/level/TrySleepTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/level/TrySleepTest.java @@ -11,13 +11,12 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.clock.ClockTimeMarker; import net.minecraft.world.clock.ClockTimeMarkers; import net.minecraft.world.clock.WorldClocks; -import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.BedBlock; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.properties.BedPart; -import net.minecraft.world.phys.Vec3; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.gametest.GameTest; @@ -35,7 +34,7 @@ public class TrySleepTest extends BaseTestMod { @GameTest public static void sleep_obstructed(GameTestHelper helper) { - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var bed = putBed(helper); helper.setAndAssertBlock(bed.above(), Blocks.STONE); @@ -44,22 +43,22 @@ public class TrySleepTest extends BaseTestMod { @GameTest public static void sleep_daytime(GameTestHelper helper) { - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var bed = putBed(helper); setTimeAndTest(helper, ClockTimeMarkers.DAY, bed, player, false, "Player was able to sleep during daytime."); } @GameTest public static void sleep_unsafe(GameTestHelper helper) { - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var bed = putBed(helper); - helper.spawn(EntityTypes.ZOMBIE, bed.east()); + helper.spawn(EntityType.ZOMBIE, bed.east()); setTimeAndTest(helper, ClockTimeMarkers.NIGHT, bed, player, false, "Player was able to sleep in an unsafe bed."); } @GameTest public static void sleep_normally(GameTestHelper helper) { - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var bed = putBed(helper); setTimeAndTest(helper, ClockTimeMarkers.NIGHT, bed, player, true, "Player was not able to sleep. There might be a slime or something causing this to fail."); } @@ -67,8 +66,8 @@ public class TrySleepTest extends BaseTestMod { private static BlockPos putBed(GameTestHelper helper) { var mid = new BlockPos(0,0,0); var south = mid.south(); - helper.setAndAssertBlock(south, Blocks.BED.black().defaultBlockState()); - helper.setAndAssertBlock(mid, Blocks.BED.black().defaultBlockState().setValue(BedBlock.PART, BedPart.HEAD)); + helper.setAndAssertBlock(south, Blocks.BLACK_BED.defaultBlockState()); + helper.setAndAssertBlock(mid, Blocks.BLACK_BED.defaultBlockState().setValue(BedBlock.PART, BedPart.HEAD)); return mid; } @@ -77,7 +76,7 @@ public class TrySleepTest extends BaseTestMod { var overworld = helper.getLevel().registryAccess().getOrThrow(WorldClocks.OVERWORLD); var origTime = manager.getTotalTicks(overworld); - player.setPos(Vec3.atBottomCenterOf(helper.absolutePos(bed))); + player.setPos(helper.absolutePos(bed).getCenter()); manager.moveToTimeMarker(overworld, time); helper.getLevel().tick(() -> true); helper.useBlock(bed, player); 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 257ada2f9b..160e3a5529 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/ConditionalLootPools.java @@ -60,7 +60,7 @@ public class ConditionalLootPools extends BaseTestMod { helper.setBlock(center, TEST_BLOCK.get()); helper.assertBlock(center, block -> block == TEST_BLOCK.get(), block -> Component.literal("Failed to set block, was " + block.getDescriptionId())); - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); player.gameMode.destroyBlock(helper.absolutePos(center)); helper.assertItemEntityPresent(Items.GOLDEN_APPLE, center, 1.0); 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 eedf7503d1..3d8449d36d 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/GlobalLootModifiersTest.java @@ -10,10 +10,10 @@ 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.predicates.DataComponentMatchers; -import net.minecraft.advancements.predicates.EnchantmentPredicate; -import net.minecraft.advancements.predicates.ItemPredicate; -import net.minecraft.advancements.predicates.MinMaxBounds; +import net.minecraft.advancements.criterion.DataComponentMatchers; +import net.minecraft.advancements.criterion.EnchantmentPredicate; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.criterion.MinMaxBounds; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistrySetBuilder; @@ -138,7 +138,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { // Tests the Enchantment condition, as well as the ability to completely override the returned values. @GameTest public static void smellting(GameTestHelper helper) { - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var center = new BlockPos(1, 1, 1); var enchants = helper.getLevel().holderLookup(Registries.ENCHANTMENT); var smelt = getSmelterAxe(enchants, true); @@ -166,7 +166,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { @GameTest public static void condition_table_name(GameTestHelper helper) { var center = new BlockPos(1, 1, 1); - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); // Should be doubled helper.setBlock(center, TEST_BLOCK.get()); @@ -185,7 +185,7 @@ public class GlobalLootModifiersTest extends BaseTestMod { @GameTest public static void silk_reentrant(GameTestHelper helper) { var center = new BlockPos(1, 1, 1); - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); var bamboo = new ItemStack(Items.BAMBOO); var normal = new ItemStack(Items.IRON_AXE); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/loot/LootEventsTest.java b/src/test/java/net/minecraftforge/debug/gameplay/loot/LootEventsTest.java index feecc983ff..a9f5438953 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/LootEventsTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/LootEventsTest.java @@ -69,7 +69,7 @@ public class LootEventsTest extends BaseTestMod { helper.setBlock(center, TEST_BLOCK.get()); helper.assertBlock(center, block -> block == TEST_BLOCK.get(), block -> Component.literal("Failed to set block, was " + block.getDescriptionId())); - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); player.gameMode.destroyBlock(helper.absolutePos(center)); helper.assertItemEntityPresent(Items.GOLDEN_APPLE, center, 1.0); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/loot/ShearsLootTests.java b/src/test/java/net/minecraftforge/debug/gameplay/loot/ShearsLootTests.java index 15ccc31886..8a163dac86 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/loot/ShearsLootTests.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/loot/ShearsLootTests.java @@ -44,7 +44,7 @@ public class ShearsLootTests extends BaseTestMod { public ShearsLootTests(FMLJavaModLoadingContext context) { super(context, false, true); - this.testItem(_ -> MODDED_SHEARS.get().getDefaultInstance()); + this.testItem(lookup -> MODDED_SHEARS.get().getDefaultInstance()); } @GameTest @@ -86,7 +86,7 @@ public class ShearsLootTests extends BaseTestMod { }; helper.makeFloor(); // Seagrass makes water - var player = helper.makeMockServerPlayerFull(GameType.SURVIVAL); // Plants prevent loot for creative players + var player = helper.makeMockServerPlayer(GameType.SURVIVAL); // Plants prevent loot for creative players var center = new BlockPos(1, 1, 1); player.setItemSlot(EquipmentSlot.MAINHAND, new ItemStack(MODDED_SHEARS.get())); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/redstone/UpdateOrder.java b/src/test/java/net/minecraftforge/debug/gameplay/redstone/UpdateOrder.java index 6fb46d29b9..04d06b8a82 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/redstone/UpdateOrder.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/redstone/UpdateOrder.java @@ -44,7 +44,7 @@ public class UpdateOrder extends BaseTestMod { helper.runAfterDelay(PISTON_DELAY, () -> { var expectedPos = new BlockPos(2, 1, 3); - helper.assertBlockPresent(Blocks.WOOL.white(), expectedPos); + helper.assertBlockPresent(Blocks.WHITE_WOOL, expectedPos); helper.succeed(); }); } @@ -58,7 +58,7 @@ public class UpdateOrder extends BaseTestMod { helper.runAfterDelay(PISTON_DELAY, () -> { var expectedPos = new BlockPos(2, 1, 3); - helper.assertBlockPresent(Blocks.WOOL.white(), expectedPos); + helper.assertBlockPresent(Blocks.WHITE_WOOL, expectedPos); helper.succeed(); }); } @@ -72,7 +72,7 @@ public class UpdateOrder extends BaseTestMod { helper.runAfterDelay(4, () -> { var expectedPos = new BlockPos(3, 1, 2); - helper.assertBlockPresent(Blocks.WOOL.white(), expectedPos); + helper.assertBlockPresent(Blocks.WHITE_WOOL, expectedPos); helper.succeed(); }); } @@ -86,7 +86,7 @@ public class UpdateOrder extends BaseTestMod { helper.runAfterDelay(PISTON_DELAY, () -> { var expectedPos = new BlockPos(2, 1, 3); - helper.assertBlockPresent(Blocks.WOOL.white(), expectedPos); + helper.assertBlockPresent(Blocks.WHITE_WOOL, expectedPos); helper.succeed(); }); } @@ -103,8 +103,8 @@ public class UpdateOrder extends BaseTestMod { barrel.setItem(0, new ItemStack(Items.DIRT)); helper.runAfterDelay(10, () -> { // There are a lot of things happening, give it a few ticks - helper.assertBlockNotPresent(Blocks.WOOL.white(), unexpectedPos); - helper.assertBlockPresent(Blocks.WOOL.white(), expectedPos); + helper.assertBlockNotPresent(Blocks.WHITE_WOOL, unexpectedPos); + helper.assertBlockPresent(Blocks.WHITE_WOOL, expectedPos); helper.succeed(); }); } diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/blockstates/gas.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/blockstates/gas.json deleted file mode 100644 index d86665fb61..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/blockstates/gas.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "fluid_bucket_model:block/gas" - } - } -} \ No newline at end of file diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/bucket.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/bucket.json deleted file mode 100644 index cec24c2bd1..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/bucket.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "fluid_bucket_model:item/bucket" - } -} \ No newline at end of file diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/gas_bucket.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/gas_bucket.json deleted file mode 100644 index b29c97b6af..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/items/gas_bucket.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "fluid_bucket_model:item/gas_bucket" - } -} \ No newline at end of file diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/block/gas.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/block/gas.json deleted file mode 100644 index 67032282f0..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/block/gas.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "minecraft:block/water_still" - } -} \ No newline at end of file diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/bucket.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/bucket.json deleted file mode 100644 index 5c42dc3a2d..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/bucket.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "parent": "forge:item/bucket", - "flip_gas": true, - "fluid": "minecraft:lava", - "loader": "forge:fluid_container", - "textures": { - "particle": "minecraft:block/lava_still" - } -} \ No newline at end of file diff --git a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/gas_bucket.json b/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/gas_bucket.json deleted file mode 100644 index bf90e7b06e..0000000000 --- a/src/test/resources/fluid_bucket_model/assets/fluid_bucket_model/models/item/gas_bucket.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "parent": "forge:item/bucket", - "flip_gas": true, - "fluid": "fluid_bucket_model:gas", - "loader": "forge:fluid_container", - "textures": { - "particle": "minecraft:block/water_still" - } -} \ No newline at end of file