Compare commits

..
39 Commits
Author SHA1 Message Date
LexManos 16dde4d551 1.20.6 RB 1
https://forums.minecraftforge.net/topic/149458-forge-501-minecraft-1206/
2024-06-03 13:15:55 -07:00
Paint_Ninja 60661350c6 Fix minor typo in MDK build.gradle 2024-06-03 20:53:10 +01:00
LexManos 7ee4a44c75 Fire EntityInteractSpecific on server side. Closes #9984 2024-06-03 12:33:53 -07:00
LexManos f22894cf70 Unlock wrapped registries when firing register events. 2024-06-03 12:31:59 -07:00
Paint_Ninja a3fce36942 Update Bootstrap to improve the Java version check error message (#9990) 2024-05-30 23:51:44 +01:00
Paint_Ninja 549dbe7df4 Minor cleanup to ModListScreen and VersionChecker (#9988) 2024-05-30 23:51:25 +01:00
Daniel Norris 5505e472aa Prevent the @OnlyIn being misused on @EventBusSubscriber and @Mod annotated classes (#9891) 2024-05-30 23:51:09 +01:00
Mysticdrew c2c7f9b656 Fix CustomizeGuiOverlayEvent.DebugText and CustomizeGuiOverlayEvent.Chat not being fired. (#9982) 2024-05-24 08:33:52 -07:00
LexManos fd8a0f9c8b Actually fix creative tab count, IDE didn't save the file before regenning patches. 2024-05-23 09:08:51 -07:00
LexManos 0ac873e296 Move Creative Inventory page count to fix issue with partially transparent tooltips. Closes #9983 2024-05-22 12:14:38 -07:00
LexManos 38b5b678cb Make OpenContainer and SpawnEntity packets process on main game thread. 2024-05-21 11:02:44 -07:00
LexManos 9a2bc1e7c2 Add File.exists check to ConfigFileTypeHandler. Closes #9976 2024-05-21 11:02:43 -07:00
RealMangoRage 95b49bedbc Fix crash when reloading a world that uses custom placed features. Closes #9979 2024-05-20 23:23:45 -07:00
LexManos 7c36115e3d Fix NPE in HurtByTargetGoal when mods set targets to null. Closes #7853 2024-05-20 16:21:17 -07:00
R0b0Li0n c037e6aca1 Fix RenderHandEvent firing with incorrect hand and item for offhand items. (#9977) 2024-05-20 11:50:09 -07:00
Mysticdrew e8f1b7ed6d Fix screen layering and re-add the test. (#9978) 2024-05-20 11:49:41 -07:00
RealMangoRage 5da16e6719 Add GatherComponentsEvent (#9944) 2024-05-14 23:02:58 -07:00
LexManos f0a82d79a6 Fix powered rails not propogating correctly. 2024-05-14 22:43:27 -07:00
LexManos 2b3a4137e1 Remove ICustomPacket and add PayloadChannel. (#9972)
New PayloadChannel that uses the vanilla payload Type for packet distinction
Implement the minecraft:register/unregister channels using the new PayloadChannel
New generic channel builder function allowing people to implement channels however they want.
2024-05-14 08:36:42 -07:00
LexManos 640c206117 Implement entity aware armor model and texture hooks. Closes #9960 2024-05-12 17:07:45 -07:00
LexManos 59a7bbdb57 Fix finalizeSpawn's return value not being used correctly. Closes #9964 2024-05-12 13:48:20 -07:00
LexManos be7ad14b4b Fix Biome patch change that caused our field redirect coremod to not function correctly. 2024-05-12 11:21:49 -07:00
LexManos c700b4ea9d Make RegistryObject.getHolder lazy, Should help cases where vanilla registries use holders from other vanilla registries. Closes #9961 2024-05-12 10:53:10 -07:00
LexManos dffa3dd4c9 Ignore jar files in the mods folder that are not Forge mods. Closes #9968 2024-05-12 03:36:22 -07:00
LexManos 4b934809c4 Fix canceling MobSpawnEvent.FinalizeSpawn causing a NPE closes #9971 2024-05-11 23:05:19 -07:00
LexManos ddf76db9b3 Fix potion brewing having arguments reversed. Closes #9970 2024-05-10 14:55:38 -07:00
LexManos 64d6b4f76a Fix Melons/Pumpkins not growing correctly. 2024-05-10 10:39:13 -07:00
Paint_Ninja 58012bfb17 Some patch cleanup (#9951) 2024-05-09 18:07:41 +01:00
LexManos 0cad6b14d9 Filter paths discovered by ServiceProvider in ClasspathLocator. Closes #9899 2024-05-09 09:39:25 -07:00
8848294210 Update SimpleChannel to make StreamCodecs easier (#9959)
Rework networking so that RegistryFriendlyByteBuf is useable for modders
Simple support for StreamCodec in SimpleChannel
Codecify all Forge packets
Make simpler builder pattern for SimpleChannel. Will eventually deprecate the old MessageBuilder as it's verbose and poorly written.

Co-authored-by: MrCrayfish <[email protected]>
Co-authored-by: Paint_Ninja <[email protected]>
2024-05-07 22:53:14 -07:00
LexManos 0e28336fc0 Fix shields not working correctly. Fixes #9966 2024-05-06 18:56:20 -07:00
LexManos 968fa9eeb5 Fix RenderTarget stencil patch location. Fixes #9965 2024-05-06 09:33:27 -07:00
EnZaXD 43768ea328 Add ModelLayers patch back (#9962) 2024-05-05 09:15:05 -07:00
LexManos 0e829630da Fix canApplyAtEnchantingTable null pointer, Closes #9956
Bump SecureModules for package info and multi-release jar fixes.
2024-05-03 14:10:17 -07:00
Paint_Ninja 0467d71466 Remove zombie chance config options (#9950) 2024-05-01 22:27:28 +01:00
Paint_Ninja 115eb5e4c8 Remove deprecated compressLanIPv6Addresses config option (#9949)
LAN IPv6 addresses are always compressed these days, so this config option is redundant
2024-05-01 22:27:16 +01:00
LexManos a7345372fd Fix custom payloads not being handled on the server in the game state. Closes #9948
Fix villagers not opening trade guis. Closes #9946
2024-05-01 13:16:41 -07:00
LexManos bd714b2f76 Fix MDK by bumping FG and disabling reobf tasks
Fix LAN server IPs being duplicated
Fix connecting to vanilla servers due to misapplied patch.
2024-05-01 11:28:43 -07:00
7b782e5b05 1.20.6 Initial Update
New Decompiler
Runtime Official mappings
ItemStacks arnt Capability providers anymore, use Vanilla's system.

Co-authored-by: RealMangoRage <[email protected]>
Co-authored-by: Paint_Ninja <[email protected]>
2024-04-30 11:42:52 -07:00
1252 changed files with 27627 additions and 31716 deletions

No files matched your search

-28
View File
@@ -1,28 +0,0 @@
name: Publish
on:
push:
branches: [ '1.20.4' ]
permissions:
contents: read
jobs:
build:
uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main
with:
java: 17
gradle_setup: './gradlew setup'
gradle_tasks: 'build publish'
artifact_name: 'forge'
secrets:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
PROMOTE_ARTIFACT_WEBHOOK: ${{ secrets.PROMOTE_ARTIFACT_WEBHOOK }}
PROMOTE_ARTIFACT_USERNAME: ${{ secrets.PROMOTE_ARTIFACT_USERNAME }}
PROMOTE_ARTIFACT_PASSWORD: ${{ secrets.PROMOTE_ARTIFACT_PASSWORD }}
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
SIGN_KEY_ALIAS: ${{ secrets.SIGN_KEY_ALIAS }}
SIGN_KEY_PASSWORD: ${{ secrets.SIGN_KEY_PASSWORD }}
SIGN_KEYSTORE_PASSWORD: ${{ secrets.SIGN_KEYSTORE_PASSWORD }}
SIGN_KEYSTORE_DATA: ${{ secrets.SIGN_KEYSTORE_DATA }}
+104
View File
@@ -0,0 +1,104 @@
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<name>MinecraftForge_Forge Config DSL Script</name>
<groupId>MinecraftForge_Forge</groupId>
<artifactId>MinecraftForge_Forge_dsl</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jetbrains-all</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>teamcity-server</id>
<url>https://teamcity.minecraftforge.net/app/dsl-plugins-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>JetBrains</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>${basedir}</sourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration/>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>teamcity-configs-maven-plugin</artifactId>
<version>${teamcity.dsl.version}</version>
<configuration>
<format>kotlin</format>
<dstDir>target/generated-configs</dstDir>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin</artifactId>
<version>${teamcity.dsl.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-plugins</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-runtime</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
+193
View File
@@ -0,0 +1,193 @@
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.projectFeatures.githubIssues
import jetbrains.buildServer.configs.kotlin.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2021.2"
project {
buildType(Build)
buildType(BuildSecondaryBranches)
buildType(PullRequests)
buildType(PullRequestChecks)
buildType(PullRequestCompatibility)
params {
text("docker_jdk_version", "21", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_gradle_version", "8.7", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_main_branch", "1.20.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_branch_spec", """
+:refs/heads/(main*)
+:refs/heads/(master*)
+:refs/heads/(develop|release|staging|main|master)
+:refs/heads/(1.*)
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
text("github_repository_name", "MinecraftForge", label = "The github repository name. Used to connect to it in VCS Roots.", description = "This is the repository slug on github. So for example `MinecraftForge` or `MinecraftForge`. It is interpolated into the global VCS Roots.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("env.PUBLISHED_JAVA_ARTIFACT_ID", "forge", label = "Published artifact id", description = "The maven coordinate artifact id that has been published by this build. Can not be empty.", allowEmpty = false)
text("env.PUBLISHED_JAVA_GROUP", "net.minecraftforge", label = "Published group", description = "The maven coordinate group that has been published by this build. Can not be empty.", allowEmpty = false)
//These are references and not actually keys
password("env.CROWDIN_KEY", "credentialsJSON:a3102dbe-805d-4177-9f54-3d2c2eb08fd5", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_URL", "credentialsJSON:a7ae1c82-8058-4061-8d12-7f6bc2618d2e", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_PASSWORD", "credentialsJSON:d7b964e3-a1fd-47a8-b892-6f601fe47479", display = ParameterDisplay.HIDDEN)
text("additional_publishing_gradle_parameters", "-PcrowdinKey=%env.CROWDIN_KEY% -PkeystoreKeyPass=%env.KEYSTORE_PASSWORD% -PkeystoreStorePass=%env.KEYSTORE_PASSWORD% -Pkeystore=%env.KEYSTORE_URL%", label = "Additional gradle parameters for publish", description = "Contains the additional gradle parameters used during publishing.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
checkbox("should_execute_build", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
checkbox("should_execute_test", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
}
features {
githubIssues {
id = "MinecraftForge_MinecraftForge__IssueTracker"
displayName = "MinecraftForge/MinecraftForge"
repositoryURL = "https://github.com/MinecraftForge/MinecraftForge"
}
}
}
object Build : BuildType({
templates(AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"), AbsoluteId("MinecraftForge_PublishProjectUsingGradle"), AbsoluteId("MinecraftForge_TriggersStaticFilesWebpageGenerator"))
id("MinecraftForge_MinecraftForge__Build")
name = "Build"
description = "Builds and Publishes the main branches of the project."
})
object BuildSecondaryBranches : BuildType({
templates(AbsoluteId("MinecraftForge_ExcludesBuildingDefaultBranch"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__BuildSecondaryBranches")
name = "Build - Secondary Branches"
description = "Builds and Publishes the secondary branches of the project."
params {
text("git_branch_spec", """
+:refs/heads/(*)
-:refs/heads/noci*
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequests : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequests")
name = "Pull Requests"
description = "Builds pull requests for the project"
params {
checkbox("should_execute_build", "true", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
text(
"gradle_build_task",
"assemble",
label = "Gradle build task to execute during build",
description = "Determines the build task that is executed to build the project.",
display = ParameterDisplay.HIDDEN,
allowEmpty = false
)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestChecks : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestChecks")
name = "Pull Requests (Checks)"
description = "Checks pull requests for the project"
steps {
gradle {
name = "Check"
id = "RUNNER_10_Check"
tasks = "checkAll"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestCompatibility : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestCompatibility")
name = "Pull Requests (Compatibility)"
description = "Validates binary compatibility for pull requests made to the project"
steps {
gradle {
name = "Validate"
id = "RUNNER_10_Compatibility"
tasks = "checkJarCompatibility"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
+2 -2
View File
@@ -7,8 +7,8 @@ plugins {
id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)'
id 'eclipse'
id 'de.undercouch.download' version '5.4.0'
id 'net.minecraftforge.gradle.patcher' version '[6.0.16,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.16,6.2)' apply false
id 'net.minecraftforge.gradle.patcher' version '[6.0.22,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.22,6.2)' apply false
id 'net.minecraftforge.gradlejarsigner' version '1.0.4'
id 'org.barfuin.gradle.taskinfo' version '2.1.0'
}
+3 -3
View File
@@ -4,9 +4,9 @@ repositories {
}
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 'org.ow2.asm:asm:9.7'
implementation 'org.ow2.asm:asm-tree:9.7'
implementation 'net.minecraftforge:srgutils:0.5.10'
implementation 'commons-io:commons-io:2.13.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r'
@@ -10,17 +10,17 @@ import java.util.zip.ZipFile
abstract class BundleList extends DefaultTask {
@InputFiles abstract ConfigurableFileCollection getConfig()
@InputFiles abstract ConfigurableFileCollection getConfigExtra()
@InputFile abstract RegularFileProperty getServerBundle()
@OutputFile abstract RegularFileProperty getOutput()
BundleList() {
config.setFrom(project.configurations.installer)
configExtra.setFrom(project.configurations.installerextra)
output.convention(project.layout.buildDirectory.file("$name/output.list"))
configure {
dependsOn(project.tasks.universalJar)
inputs.file(project.tasks.universalJar.archiveFile)
dependsOn(project.tasks.applyServerBinPatches)
inputs.file(project.tasks.applyServerBinPatches.output)
}
}
@@ -34,6 +34,13 @@ abstract class BundleList extends DefaultTask {
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
}
resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts
for (def dep : resolved) {
def info = Util.getMavenInfoFromDep(dep)
//println("$dep.file.sha1\t$info.name\t$info.path")
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
}
var packed = (AbstractArchiveTask) project.tasks.universalJar
var info = Util.getMavenInfoFromTask(packed)
def file = packed.archiveFile.get().asFile
@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
@Internal
@Override
protected Object getData() {
return matches.toSorted(Comparator.<String>naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
return matches.toSorted(Comparator.naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
}
}
@@ -24,6 +24,7 @@ abstract class LauncherJson extends DefaultTask {
dependsOn(project.tasks.universalJar)
input.from(project.tasks.universalJar.archiveFile)
input.from(project.configurations.installer)
input.from(project.configurations.installerextra)
configure {
def mc = project.rootProject.ext.MC_VERSION
def forge = project.rootProject.ext.FORGE_VERSION
@@ -88,6 +89,7 @@ abstract class LauncherJson extends DefaultTask {
]
])
json.libraries.addAll(getArtifacts(project.configurations.installerextra).values())
json.libraries.addAll(getArtifacts(project.configurations.installer).values())
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
}
@@ -140,7 +140,7 @@ abstract class CheckPatches extends CheckTask {
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", false)
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)
}
}
+9
View File
@@ -61,4 +61,13 @@ eclipse.classpath.file.whenMerged {
def src = entries.find { it.path == 'src/main/java' }
if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
src.entryAttributes['ignore_optional_problems'] = 'true'
}
tasks.named('genPatches').configure {
onlyIf { false }
}
tasks.named('extractRangeMap').configure {
onlyIf { false }
tool = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
}
+103 -102
View File
@@ -12,9 +12,9 @@ import net.minecraftforge.gradle.common.tasks.ApplyBinPatches
import net.minecraftforge.gradle.common.tasks.CheckJarCompatibility
import net.minecraftforge.gradle.common.tasks.DownloadMavenArtifact
import net.minecraftforge.gradle.common.tasks.ExtractInheritance
import net.minecraftforge.gradle.patcher.tasks.FilterNewJar
import net.minecraftforge.gradle.patcher.tasks.GeneratePatches
import net.minecraftforge.gradle.userdev.tasks.RenameJar
import net.minecraftforge.gradleutils.PomUtils
import org.apache.tools.ant.filters.ReplaceTokens
import org.objectweb.asm.Opcodes
@@ -46,6 +46,7 @@ jarSigner.autoDetect('forge')
applyPatches {
level 'WARNING'
failOnError = UPDATING != 'true'
}
sourceSets {
@@ -88,16 +89,21 @@ ext {
final String MAVEN_PATH = ext.MAVEN_PATH
final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.0'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.3'
final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6'
final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
configurations {
// Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
bootstrap { transitive = false }
bootstrap { transitive = false }
installer {
extendsFrom(bootstrap)
transitive = false
}
installerextra {
extendsFrom(bootstrap)
transitive = false
}
api.extendsFrom(installer)
}
@@ -111,10 +117,11 @@ dependencies {
bootstrap(libs.unsafe) // Needed by securemodules
bootstrap(libs.bundles.asm) // Needed by securemodules
implementation(libs.jopt.simple) { version { strictly '5.0.4' } }
installer(libs.bootstrap)
installer(libs.bootstrap.api) // Needed by securemodules
installer(libs.accesstransformers)
installer(libs.antlr.runtime) // Dep of AccessTransformer
installer(libs.eventbus)
installer(libs.typetools) // Dep of EventBus
installer(libs.forgespi)
@@ -135,10 +142,16 @@ dependencies {
installer(project(':lowcodelanguage'))
installer(project(':mclanguage'))
installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off")
runtimeOnly(libs.bootstrap)
runtimeOnly(libs.bootstrap.dev)
}
tasks.named('extractRangeMap').configure {
tool = S2S_TOOL
}
patcher {
excs.from file("$rootDir/src/main/resources/forge.exc")
parent = project(':mcp')
@@ -167,6 +180,7 @@ patcher {
forge_client_test {
parent runs.forge_client
source sourceSets.test
}
forge_server {
@@ -175,6 +189,7 @@ patcher {
forge_server_test {
parent runs.forge_server
source sourceSets.test
}
forge_server_gametest {
@@ -183,6 +198,7 @@ patcher {
forge_server_gametest_test {
parent runs.forge_server_gametest
source sourceSets.test
}
forge_data {
@@ -198,6 +214,7 @@ patcher {
}
forge_data_test {
source sourceSets.test
args '--launchTarget', 'forge_dev_data',
'--mod', '.+',
'--all',
@@ -208,7 +225,6 @@ patcher {
'--assetsDir', downloadAssets.output,
'--assetIndex', "{asset_index}"
}
}
}
@@ -362,33 +378,15 @@ tasks.register('extractInheritance', ExtractInheritance) {
Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).toList()
}
}
tasks.register("findFieldInstanceChecks", FieldCompareFinder) {
jar = createJoinedSRG.output
output = rootProject.file('src/main/resources/coremods/field_to_instanceof.json')
fields {
/* 1.17 changed most things to use Tags. So this isn't nessasary anymore so just make an empty list
bows {
cls = 'net/minecraft/world/item/Items'
name = 'f_42411_'
replacement = 'net/minecraft/world/item/BowItem'
}
crossbows {
cls = 'net/minecraft/world/item/Items'
name = 'f_42717_'
replacement = 'net/minecraft/world/item/CrossbowItem'
}
*/
}
}
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
jar = createJoinedSRG.output
output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json')
predicate = {
parent, node, insn ->
'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
&& insn.getOpcode() === Opcodes.INVOKEVIRTUAL
return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
&& insn.getOpcode().equals(Opcodes.INVOKEVIRTUAL)
&& insn.name == 'm_6518_'
&& insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;'
&& insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;';
}
}
tasks.register('validateDeprecations', ValidateDeprecations) {
@@ -428,43 +426,34 @@ tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks.
args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath]
outputs.file(output)
}
tasks.register('mergeClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
ext.output = file('build/client_mappings_merged.tsrg')
tool = INSTALLER_TOOLS + ':fatjar'
args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadClientMappings.output.absolutePath, '--output', output.absolutePath]
outputs.file(output)
}
tasks.register('mergeServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
ext.output = file('build/server_mappings_merged.tsrg')
tool = INSTALLER_TOOLS + ':fatjar'
args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadServerMappings.output.absolutePath, '--output', output.absolutePath]
outputs.file(output)
}
tasks.register("createJoinedSRG", DownloadMavenArtifact) {
artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
}
tasks.register("createClientSRG", RenameJar) {
tasks.register("createClientOfficial", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
mappings = createMcp2Srg.srg
dependsOn(downloadClientRaw)
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadClientMappings.output
dependsOn(downloadClientRaw, downloadClientMappings)
input = downloadClientRaw.dest
output = file("build/createClientSRG/output.jar")
output = file("build/createClientOfficial/output.jar")
}
tasks.register("createServerSRG", RenameJar) {
tasks.register("createServerOfficial", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
mappings = createMcp2Srg.srg
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadServerMappings.output
dependsOn(downloadServerMappings)
input = extractServer.output
output = file("build/createServerSRG/output.jar")
output = file("build/createServerOfficial/output.jar")
}
tasks.named('genClientBinPatches').configure {
tool = BINPATCH_TOOL
cleanJar = createClientSRG.output
cleanJar = createClientOfficial.output
dirtyJar = jar.archiveFile
}
tasks.named('genServerBinPatches').configure {
tool = BINPATCH_TOOL
cleanJar = createServerSRG.output
cleanJar = createServerOfficial.output
dirtyJar = jar.archiveFile
}
tasks.named('genJoinedBinPatches').configure {
tool = BINPATCH_TOOL
@@ -472,13 +461,13 @@ tasks.named('genJoinedBinPatches').configure {
}
tasks.register('applyClientBinPatches', ApplyBinPatches) {
tool = BINPATCH_TOOL
clean = createClientSRG.output
clean = createClientOfficial.output
patch = genClientBinPatches.output
args.addAll(['--data', '--unpatched'])
}
tasks.register('applyServerBinPatches', ApplyBinPatches) {
tool = BINPATCH_TOOL
clean = createServerSRG.output
clean = createServerOfficial.output
patch = genServerBinPatches.output
args.addAll(['--data', '--unpatched'])
}
@@ -494,10 +483,10 @@ tasks.register('createServerShimClasspath', BundleList) {
tasks.register('createServerShimConfig') {
ext.output = file('build/libs/bootstrap-shim.properties')
doLast {
def cfg = new CleanProperties()
cfg."Main-Class" = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg."Java-Version" = '17'
cfg."Arguments" = "--launchTarget forge_server"
var cfg = new CleanProperties()
cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg['Java-Version'] = '21'
cfg['Arguments'] = '--launchTarget forge_server'
cfg.store(output)
}
}
@@ -523,7 +512,7 @@ tasks.register('checkAll') {
group = 'checks'
}
tasks.register('checkAllAndFix') {
dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses'
dependsOn 'findFinalizeSpawnTargets', 'checkLicenses'
group = 'checks'
}
@@ -637,15 +626,12 @@ tasks.register('installerJson', InstallerJson) {
// Download Official Mappings
dependsOn(downloadClientMappings, downloadServerMappings)
input.from(downloadClientMappings.output, downloadServerMappings.output)
// Merge MCP and Official Mappings
dependsOn(mergeClientMappings, mergeServerMappings)
input.from(mergeClientMappings.output, mergeServerMappings.output)
// Get 'base' MC jar, Client is straight download, server is extracted from the bundle
dependsOn(downloadClientRaw, extractServer)
input.from(downloadClientRaw.dest, extractServer.output)
// Rename MC Jar
dependsOn(createClientSRG, createServerSRG)
input.from(createClientSRG.output, createServerSRG.output)
dependsOn(createClientOfficial, createServerOfficial)
input.from(createClientOfficial.output, createServerOfficial.output)
// Apply Binary patches to vanilla jar
dependsOn(applyClientBinPatches, applyServerBinPatches)
input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar)
@@ -672,21 +658,13 @@ tasks.register('installerJson', InstallerJson) {
server: "'${extractMCPConfigMappings.output.sha1}'"
],
MOJMAPS: [
client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]",
server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]"
client: "[net.minecraft:client:${MC_VERSION}:mappings@tsrg]",
server: "[net.minecraft:server:${MC_VERSION}:mappings@tsrg]"
],
MOJMAPS_SHA: [
client: "'${downloadClientMappings.output.sha1}'",
server: "'${downloadServerMappings.output.sha1}'"
],
MERGED_MAPPINGS: [
client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]",
server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]"
],
MERGED_MAPPINGS_SHA: [
client: "'${mergeClientMappings.output.sha1}'",
server: "'${mergeServerMappings.output.sha1}'"
],
MC_UNPACKED: [
client: "[net.minecraft:client:${MC_VERSION}]",
server: "[net.minecraft:server:${MC_VERSION}:unpacked]"
@@ -695,13 +673,13 @@ tasks.register('installerJson', InstallerJson) {
client: "'${downloadClientRaw.dest.sha1}'",
server: "'${extractServer.output.get().asFile.sha1}'"
],
MC_SRG: [
client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]",
server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]"
MC_OFF: [
client: "[net.minecraft:client:${MC_VERSION}:official]",
server: "[net.minecraft:server:${MC_VERSION}:official]"
],
MC_SRG_SHA: [
client: "'${createClientSRG.output.get().asFile.sha1}'",
server: "'${createServerSRG.output.get().asFile.sha1}'"
MC_OFF_SHA: [
client: "'${createClientOfficial.output.get().asFile.sha1}'",
server: "'${createServerOfficial.output.get().asFile.sha1}'"
],
BINPATCH: [
client: '/data/client.lzma',
@@ -793,31 +771,18 @@ tasks.register('installerJson', InstallerJson) {
outputs: [
'{MOJMAPS}': '{MOJMAPS_SHA}'
]
], [
jar: INSTALLER_TOOLS,
classpath: INSTALLER_TOOLS_CLASSPATH,
args: [
'--task', 'MERGE_MAPPING',
'--left', '{MAPPINGS}',
'--right', '{MOJMAPS}',
'--output', '{MERGED_MAPPINGS}',
'--classes', '--reverse-right'
],
outputs: [
'{MERGED_MAPPINGS}': '{MERGED_MAPPINGS_SHA}'
]
], [
sides: ['server'],
jar: FART,
classpath: getClasspath(project, libs, FART),
args: [
'--input', '{MC_UNPACKED}',
'--output', '{MC_SRG}',
'--names', '{MERGED_MAPPINGS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
'--output', '{MC_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
],
outputs: [
'{MC_SRG}': '{MC_SRG_SHA}'
'{MC_OFF}': '{MC_OFF_SHA}'
]
], [
sides: ['client'],
@@ -825,18 +790,18 @@ tasks.register('installerJson', InstallerJson) {
classpath: getClasspath(project, libs, FART),
args: [
'--input', '{MINECRAFT_JAR}',
'--output', '{MC_SRG}',
'--names', '{MERGED_MAPPINGS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
'--output', '{MC_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
],
outputs: [
'{MC_SRG}': '{MC_SRG_SHA}'
'{MC_OFF}': '{MC_OFF_SHA}'
]
], [
jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar
classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
args: [
'--clean', '{MC_SRG}',
'--clean', '{MC_OFF}',
'--output', '{PATCHED}',
'--apply', '{BINPATCH}',
'--data', '--unpatched'
@@ -851,6 +816,27 @@ tasks.register('installerJson', InstallerJson) {
}
}
tasks.register('officialClassesOnly', Zip).configure {
dependsOn(jar)
destinationDirectory = file('build/libs')
archiveClassifier = 'official-classes'
from zipTree(jar.archiveFile).matching {
include '**/*.class'
exclude 'mcp/**'
}
}
tasks.named('filterJarNew').configure {
dependsOn('officialClassesOnly')
input = officialClassesOnly.archiveFile
}
tasks.register('filterJarNewSRG', FilterNewJar).configure {
input = reobfJar.output
srg = filterJarNew.srg
blacklist = filterJarNew.blacklist
}
tasks.named('universalJar').configure {
dependsOn downloadCrowdin
from zipTree(downloadCrowdin.dest).matching {
@@ -882,6 +868,20 @@ tasks.named('universalJar').configure {
jarSigner.sign(it)
}
tasks.register('universalJarSrg', Jar).configure {
from zipTree(filterJarNewSRG.output)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from zipTree(universalJar.archiveFile)
destinationDirectory = file('build/libs')
archiveClassifier = 'universal-srg'
manifest.from(universalJar.manifest)
jarSigner.sign(it)
}
tasks.named('userdevConfig').configure {
universal = "$project.group:$project.name:$project.version:universal-srg@jar"
}
tasks.register('installerJar', InstallerJar) {
fat = !System.env.TEAMCITY_VERSION
//offline = true
@@ -1068,6 +1068,7 @@ tasks.named('javadoc', Javadoc).configure {
publishing {
publications.register('mavenJava', MavenPublication).configure {
artifact universalJar
artifact universalJarSrg
artifact installerJar
artifact mdkZip
artifact userdevJar
@@ -1079,8 +1080,8 @@ publishing {
name = project.name
description = 'Modifactions to Minecraft to enable mod developers.'
url = 'https://github.com/MinecraftForge/MinecraftForge'
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
license PomUtils.Licenses.LGPLv2_1
gradleutils.pom.setGitHubDetails(pom, 'MinecraftForge')
license gradleutils.pom.Licenses.LGPLv2_1
}
}
@@ -1090,5 +1091,5 @@ publishing {
}
// Make sure we run bin compat checking during local testing.
if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
if ((!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) && CHECK_COMPATIBILITY == "true")
tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') }
-8
View File
@@ -74,11 +74,3 @@ eclipse {
// 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
}
}
+6 -25
View File
@@ -2,15 +2,16 @@
MinecraftForge
=============
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.20.4-&query=$.promos["1.20.4-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=1.20.4-&query=$.promos["1.20.4-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.20.6-&query=$.promos["1.20.6-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=1.20.6-&query=$.promos["1.20.6-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!
| Version | Support |
|--------------|-----------------------------|
| All versions | [Supported][Support-Policy] |
| Version | Support |
|---------| ------------- |
| 1.20.x | Active |
| 1.19.x | Legacy |
* [Download]
* [Forum]
@@ -30,19 +31,6 @@ You can download the installer for the *Recommended Build* or the
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
## Required Java Versions
We require the version of Java that Minecraft requires, which is currently:
| Minecraft | Java |
|---------------|-------------------|
| 1.20.6+ | [21][Adoptium-21] |
| 1.18 - 1.20.4 | [17][Adoptium-17] |
| 1.17.1 | [16][Adoptium-16] |
| 1.16.5- | [8][Adoptium-8] |
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
# Creating Mods
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
@@ -75,15 +63,8 @@ Please ensure you have a valid email address associated with your GitHub account
[Download]: https://files.minecraftforge.net/
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
[Adoptium-8]: https://adoptium.net/temurin/releases/?version=8
[Jarfix]: https://johann.loefflmann.net/en/software/jarfix/index.html
[Forum]: https://forums.minecraftforge.net/
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
[Support-Policy]: https://forums.minecraftforge.net/topic/144690-new-tiered-support-policy
[Discord]: https://discord.minecraftforge.net/
@@ -9,35 +9,41 @@ import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.loading.FMLLoader;
import java.util.ArrayList;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.function.Supplier;
/**
* Used to allow access to certain things from the game layer
*/
public class Bindings {
private Bindings() {}
private static final Bindings INSTANCE = new Bindings();
/**
* The provider of the bindings
* @implNote May also throw a {@link ServiceConfigurationError}
*/
private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
private final IBindingsProvider provider;
private Bindings() {
var providers = new ArrayList<IBindingsProvider>(1);
for (var itr = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class).iterator(); itr.hasNext(); ) {
try {
providers.add(itr.next());
} catch (ServiceConfigurationError sce) {
sce.printStackTrace();
}
}
if (providers.size() != 1)
throw new IllegalStateException("Could not find bindings provider: " + providers);
this.provider = providers.get(0);
}
/**
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
*/
public static Supplier<IEventBus> getForgeBus() {
return PROVIDER.getForgeBusSupplier();
return INSTANCE.provider.getForgeBusSupplier();
}
public static Supplier<I18NParser> getMessageParser() {
return PROVIDER.getMessageParser();
return INSTANCE.provider.getMessageParser();
}
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
return PROVIDER.getConfigConfiguration();
return INSTANCE.provider.getConfigConfiguration();
}
}
@@ -16,8 +16,7 @@ import net.minecraftforge.api.distmarker.Dist;
*
* @see Dist
*/
public enum LogicalSide
{
public enum LogicalSide {
/**
* The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
* viewpoint.
@@ -27,6 +26,7 @@ public enum LogicalSide
* @see Dist#CLIENT
*/
CLIENT,
/**
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
* on the level.
@@ -41,16 +41,14 @@ public enum LogicalSide
/**
* {@return if this logical side is the server}
*/
public boolean isServer()
{
public boolean isServer() {
return !isClient();
}
/**
* {@return if the logical side is the client}
*/
public boolean isClient()
{
public boolean isClient() {
return this == CLIENT;
}
}
@@ -8,7 +8,9 @@ package net.minecraftforge.fml;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.loading.FMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
@@ -17,45 +19,28 @@ public class ModLoadingContext
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
private ModContainer activeContainer;
private Object languageExtension;
private ModLoadingStage stage;
/**
* @deprecated Use the context provided by your language loader in your mod's constructor.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static ModLoadingContext get() {
return context.get();
}
/**
* @deprecated Going to be moved to ForgeHooks for internal use.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
private ModContainer activeContainer;
public void setActiveContainer(final ModContainer container) {
this.activeContainer = container;
this.languageExtension = container == null ? null : container.contextExtension.get();
}
/**
* Going to be moved to ForgeHooks for internal use.
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public ModContainer getActiveContainer() {
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
}
@Deprecated(forRemoval = true, since = "1.21.1")
public String getActiveNamespace() {
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
}
public ModContainer getContainer() {
return getActiveContainer();
}
/**
* Register an {@link IExtensionPoint} with the mod container.
* @param point The extension point to register
@@ -63,7 +48,7 @@ public class ModLoadingContext
* @param <T> The type signature of the extension operator
*/
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
getContainer().registerExtensionPoint(point, extension);
getActiveContainer().registerExtensionPoint(point, extension);
}
/**
@@ -72,7 +57,7 @@ public class ModLoadingContext
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
*/
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
getContainer().registerDisplayTest(() -> displayTest);
getActiveContainer().registerDisplayTest(() -> displayTest);
}
/**
@@ -81,7 +66,7 @@ public class ModLoadingContext
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
*/
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
getContainer().registerDisplayTest(displayTest);
getActiveContainer().registerDisplayTest(displayTest);
}
/**
@@ -91,7 +76,7 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
*/
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
/**
@@ -101,29 +86,29 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
*/
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getActiveContainer().getModId());
return;
}
getContainer().addConfig(new ModConfig(type, spec, getContainer()));
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer()));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getActiveContainer().getModId(), fileName);
return;
}
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName));
}
@@ -67,7 +67,9 @@ public class ConfigFileTypeHandler {
}
private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
Files.createDirectories(file.getParent());
if (!Files.isDirectory(file.getParent())) {
Files.createDirectories(file.getParent());
}
Path p = defaultConfigPath.resolve(modConfig.getFileName());
if (Files.exists(p)) {
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
@@ -13,10 +13,10 @@ import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
public class PerformanceInfo {
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
private final boolean showCPUUsage;
private final OperatingSystemMXBean osBean;
private final MemoryMXBean memoryBean;
private float memory;
private String text;
@@ -24,14 +24,15 @@ public class PerformanceInfo {
PerformanceInfo() {
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
memoryBean = ManagementFactory.getMemoryMXBean();
}
void update() {
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage();
memory = (float) heapusage.getUsed() / heapusage.getMax();
if (!showCPUUsage) {
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20);
return;
}
@@ -43,7 +44,7 @@ public class PerformanceInfo {
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
}
text = "Memory: %d/%dMB (%.1f%%) %s".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f, cpuText);
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB %s".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20, cpuText);
}
String text() {
+1 -1
View File
@@ -37,7 +37,7 @@ dependencies {
implementation(libs.jimfs)
implementation(libs.log4j.core)
annotationProcessor(libs.log4j.core)
annotationProcessor(libs.bundles.log4j)
testCompileOnly(libs.nulls)
testRuntimeOnly(libs.bootstrap)
@@ -36,9 +36,9 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
*/
public class CapabilityTokenSubclass implements ILaunchPluginService {
private static final String FUNC_NAME = "getType";
private static final String FUNC_DESC = "()Ljava/lang/String;";
private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
private final String FUNC_NAME = "getType";
private final String FUNC_DESC = "()Ljava/lang/String;";
private final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
@@ -51,14 +51,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
return isEmpty ? NAY : YAY;
}
@Override
@@ -82,7 +75,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9)
{
final Deque<String> stack = new ArrayDeque<>();
Deque<String> stack = new ArrayDeque<>();
@Override
public void visitClassType(final String name)
@@ -120,7 +113,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
}
}
private static final class Holder {
private static class Holder {
String value;
}
@@ -8,7 +8,6 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -36,11 +35,7 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
new VanillaObjectHolderData("net.minecraft.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toMap(VanillaObjectHolderData::holderClass, Function.identity()));
private static final Set<String> VANILLA_OBJECT_HOLDER_CLASSES = VANILLA_OBJECT_HOLDERS.keySet().stream()
.map(it -> it.replace('.', '/'))
.collect(Collectors.toUnmodifiableSet());
private static final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final int PUBLIC_STATIC_FINAL_FLAGS = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
@@ -51,29 +46,13 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
// Let's skip processing classes that definitely don't have object holders
String internalName = classType.getInternalName();
// Forge classes that aren't in the debug package (that package is used for tests)
if (internalName.startsWith("net/minecraftforge/") && !internalName.substring(18).contains("debug"))
return NAY;
// Vanilla classes that don't have object holders
if (internalName.startsWith("com/mojang/"))
return NAY;
// ...except specific ones we added to the VANILLA_OBJECT_HOLDERS map
if (internalName.startsWith("net/minecraft/") && !VANILLA_OBJECT_HOLDER_CLASSES.contains(internalName))
return NAY;
return YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
}
private boolean hasHolder(List<AnnotationNode> lst) {
private boolean hasHolder(List<AnnotationNode> lst)
{
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
@@ -97,9 +76,10 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
{
final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final
@@ -109,7 +89,7 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
if (VANILLA_OBJECT_HOLDERS.containsKey(classType.getClassName())) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L")).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL;
@@ -28,16 +28,15 @@ import org.slf4j.Logger;
public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Type STRING = Type.getType(String.class);
private static final Type ENUM = Type.getType(Enum.class);
private static final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private static final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private static final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private static final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
private static final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
private static final int FLAGS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
private final Type STRING = Type.getType(String.class);
private final Type ENUM = Type.getType(Enum.class);
private final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private final String NAME_DESC = Type.getMethodDescriptor(STRING);
private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
@Override
public String name() {
@@ -48,15 +47,9 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
}
@Override
@@ -65,24 +58,25 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return ComputeFlags.NO_REWRITE;
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE;
Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor();
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) {
return ComputeFlags.NO_REWRITE;
}
//Static methods named "create" with first argument as a string
List<MethodNode> candidates = classNode.methods.stream()
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
.toList();
.collect(Collectors.toList());
if (candidates.isEmpty()) {
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
}
for (var mtd : candidates)
candidates.forEach(mtd ->
{
Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING)) {
@@ -114,7 +108,8 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE;
System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
for (int x = 1; x < args.length; x++)
ctrArgs[1 + x] = args[x];
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
@@ -236,7 +231,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
ins.load(vars, classType);
ins.areturn(classType);
}
}
});
return ComputeFlags.COMPUTE_FRAMES;
}
@@ -39,7 +39,6 @@ public class FMLConfig
EARLY_WINDOW_SQUIR("earlyWindowSquir", Boolean.FALSE, "Squir?"),
EARLY_WINDOW_SHOW_CPU("earlyWindowShowCPU", Boolean.FALSE, "Whether to show CPU usage stats in early window"),
EARLY_WINDOW_LOG_HELP_MSG("earlyWindowLogHelpMessage", Boolean.TRUE, "Whether to log a help message on first attempt, to aid troubleshooting. This setting should automatically disable itself after a successful launch"),
DETECT_NON_FORGE_MODS_TOML("detectNonForgeModsToml", Boolean.TRUE, "Attempt to detect non-Forge mods from their mods.toml to show a friendlier error message. This is a best-effort feature - disable if it causes issues."),
;
private final String entry;
@@ -57,9 +57,6 @@ public class FMLLoader {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
// Allows us to communicate properties with other services through ModLauncher
setupBlackboardKeys();
checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
@@ -123,12 +120,6 @@ public class FMLLoader {
return providers.get(0);
}
private static void setupBlackboardKeys() {
LOGGER.debug(CORE, "Requesting CoreMods to not apply the fix for ASMAPI.findFirstInstructionBefore by default");
var blackboardKey = TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "coremods.use_old_findFirstInstructionBefore", Boolean.class);
Launcher.INSTANCE.blackboard().<Boolean>computeIfAbsent(blackboardKey, k -> true);
}
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
@@ -190,7 +181,7 @@ public class FMLLoader {
}
public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {} in {}", atPath, modName.getFilePath());
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
@@ -5,14 +5,12 @@
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import org.slf4j.Logger;
import java.net.URL;
import java.nio.file.Files;
@@ -32,7 +30,6 @@ import java.util.stream.Collectors;
*/
public class LoadingModList
{
private static final Logger LOGGER = LogUtils.getLogger();
private static LoadingModList INSTANCE;
private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList;
@@ -81,22 +78,9 @@ public class LoadingModList
public void addAccessTransformers()
{
var errors = new ArrayList<EarlyLoadingException.ExceptionData>();
for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile();
for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message);
} else {
FMLLoader.addAccessTransformer(at, mod);
}
}
}
if (!errors.isEmpty()) {
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
modFiles.stream()
.map(ModFileInfo::getFile)
.forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod)));
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler)
@@ -77,7 +77,7 @@ public class MCPNamingService implements INameMappingService {
}
private static void loadMappings(final String mappingFileName, BiConsumer<String, String> mapStore) {
URL path = ClassLoader.getSystemResource(mappingFileName); //We EXPLICITLY go through the SystemClassLoader here because this is dev-time only. And will be on the root classpath.
URL path = MCPNamingService.class.getClassLoader().getResource(mappingFileName);
if (path == null)
return;
@@ -34,7 +34,8 @@ import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public final class RuntimeDistCleaner implements ILaunchPluginService {
public class RuntimeDistCleaner implements ILaunchPluginService
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
private static String DIST;
@@ -56,11 +57,17 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST);
}
if (!FMLEnvironment.production && hasOnlyInWithModAnnotation(classNode.visibleAnnotations))
{
LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
throw new RuntimeException("Found @OnlyIn on @Mod class "+ classNode.name + " - this is not allowed as it causes crashes. Remove the OnlyIn and consider setting clientSideOnly=true in the root of your mods.toml instead");
}
if (classNode.interfaces != null )
{
unpack(classNode.visibleAnnotations).stream()
.filter(ann->Objects.equals(ann.desc, ONLYIN))
.filter(ann->ann.values.indexOf("_interface") != -1)
.filter(ann-> ann.values.contains("_interface"))
.filter(ann->!Objects.equals(((String[])ann.values.get(ann.values.indexOf("value") + 1))[1], DIST))
.map(ann -> ((Type)ann.values.get(ann.values.indexOf("_interface") + 1)).getInternalName())
.forEach(intf -> {
@@ -136,22 +143,78 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
}
@SuppressWarnings("unchecked")
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns) {
if (anns == null) return Collections.emptyList();
List<AnnotationNode> ret = anns.stream().filter(ann->Objects.equals(ann.desc, ONLYIN)).collect(Collectors.toList());
anns.stream().filter(ann->Objects.equals(ann.desc, ONLYINS) && ann.values != null)
.map( ann -> (List<AnnotationNode>)ann.values.get(ann.values.indexOf("value") + 1))
.filter(v -> v != null)
.forEach(v -> v.forEach(ret::add));
return ret;
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns)
{
if (anns == null)
{
return Collections.emptyList();
}
List<AnnotationNode> unpacked = new ArrayList<>();
for (var annotationNode : anns)
{
if (Objects.equals(annotationNode.desc, ONLYINS))
{
unpacked.add(annotationNode);
if (annotationNode.values != null)
{
List<AnnotationNode> subNodes = (List<AnnotationNode>) annotationNode.values.get(annotationNode.values.indexOf("value") + 1);
if (subNodes != null)
{
unpacked.addAll(subNodes);
}
}
}
}
return unpacked;
}
private static boolean remove(final List<AnnotationNode> anns, final String side)
private boolean remove(final List<AnnotationNode> anns, final String side)
{
return unpack(anns).stream().
filter(ann->Objects.equals(ann.desc, ONLYIN)).
filter(ann->ann.values.indexOf("_interface") == -1).
anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side));
var onlyIns = unpack(anns);
for (var onlyIn : onlyIns)
{
if (!Objects.equals(onlyIn.desc, ONLYINS) || onlyIn.values.contains("_interface"))
{
continue;
}
if (!Objects.equals(((String[])onlyIn.values.get(onlyIn.values.indexOf("value") + 1))[1], side))
{
return true;
}
}
return false;
}
private boolean hasOnlyInWithModAnnotation(final List<AnnotationNode> anns)
{
if (anns == null)
{
return false;
}
var foundModAnnotation = false;
var foundOnlyIn = false;
for (var ann : anns)
{
if (ann.desc.equals("Lnet/minecraftforge/fml/common/Mod;"))
{
foundModAnnotation = true;
} else if (Objects.equals(ann.desc, ONLYIN) || Objects.equals(ann.desc, ONLYINS))
{
foundOnlyIn = true;
}
}
return foundModAnnotation && foundOnlyIn;
}
@SuppressWarnings("unchecked")
@@ -168,19 +231,9 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/"))
return NAY;
// No Vanilla classes use @OnlyIn(Dist.SERVER), so we can skip them entirely when we're running on a client
if (FMLEnvironment.dist.isClient() && (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/")))
return NAY;
return YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
}
private static class LambdaGatherer extends MethodVisitor {
@@ -18,6 +18,7 @@ import net.minecraftforge.forgespi.locating.IModProvider;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
@@ -36,10 +37,11 @@ public abstract class AbstractModProvider implements IModProvider {
protected static final String MODS_TOML = "META-INF/mods.toml";
protected IModLocator.ModFileOrException createMod(Path path) {
return this.createMod(path, getDefaultJarModType());
return createMod(path, false);
}
protected IModLocator.ModFileOrException createMod(Path path, String defaultType) {
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown) {
var mjm = new ModJarMetadata();
var sj = SecureJar.from(
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
@@ -49,18 +51,20 @@ public abstract class AbstractModProvider implements IModProvider {
IModFile mod;
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
if (type == null)
type = defaultType;
type = getDefaultJarModType();
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
mod = new ModFile(sj, this, ModFileParser::modsTomlParser);
if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
if (mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
LOGGER.error(LogMarkers.SCAN, "Unable to load file \"{}\" because its mods.toml is requesting an invalid javafml loaderVersion (use \"*\" if you want to allow all versions) and is missing a forge modId dependency declaration (see the sample mods.toml in the MDK).", path);
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("File \"%s\" is not a Forge mod and cannot be loaded. Look for a Forge version of this mod or consider alternative mods.".formatted(mod.getFileName())));
}
} else if (type != null) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path);
mod = new ModFile(sj, this, this::manifestParser, type);
} else if (ignoreUnknown) {
return null;
} else
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
@@ -83,14 +83,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
final Path pathInFS = zipFS.getPath("/");
final IModFile.Type parentType = file.getType();
final String modType;
if (parentType == IModFile.Type.LIBRARY || parentType == IModFile.Type.LANGPROVIDER) {
modType = IModFile.Type.LIBRARY.name();
} else {
modType = IModFile.Type.GAMELIBRARY.name();
}
return Optional.of(createMod(pathInFS, modType).file());
return Optional.of(createMod(pathInFS).file());
} catch (Exception e) {
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
@@ -52,7 +52,6 @@ public class ModFile implements IModFile {
private CompletableFuture<ModFileScanData> futureScanResult;
private List<CoreModFile> coreMods;
private Path accessTransformer;
private List<Path> accessTransformers = Collections.emptyList();
static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
private SecureJar.Status securityStatus;
@@ -97,11 +96,7 @@ public class ModFile implements IModFile {
}
public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(accessTransformer);
}
public List<Path> getAccessTransformers() {
return accessTransformers;
return Optional.ofNullable(Files.exists(accessTransformer) ? accessTransformer : null);
}
public boolean identifyMods() {
@@ -110,28 +105,7 @@ public class ModFile implements IModFile {
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
this.coreMods = ModFileParser.getCoreMods(this);
this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath()));
List<String> cfg;
// Note: Some mods may have invalid tomls copied from other projects.
// Unfortunately we must protect against those landmines.
try {
cfg = this.modFileInfo.getConfig().<List<String>>getConfigElement("accessTransformers").orElse(null);
} catch (Exception e) {
cfg = null;
LOGGER.warn("{} contains an invalid 'accessTransformers' TOML entry. Should be e.g. accessTransformers = [\"META-INF/accesstransformer.cfg\", \"META-INF/extra_at.cfg\"] or accessTransformers = [] for no ATs. Falling back to default.", this.getFileName());
}
if (cfg == null) {
var path = findResource("META-INF", "accesstransformer.cfg");
if (Files.exists(path)) {
this.accessTransformer = path;
this.accessTransformers = List.of(path);
}
} else if (!cfg.isEmpty()) {
var paths = new ArrayList<Path>(cfg.size());
for (var path : cfg) {
paths.add(getSecureJar().getPath(path.replace("\\","/")));
}
this.accessTransformers = List.copyOf(paths);
}
this.accessTransformer = findResource("META-INF", "accesstransformer.cfg");
return true;
}
@@ -8,7 +8,6 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.base.Strings;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.forgespi.language.IConfigurable;
@@ -49,9 +48,6 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
@ApiStatus.Internal
public static final String NOT_A_FORGE_MOD_PROP = "__FORGE__not_a_forge_mod";
@ApiStatus.Internal
public static final boolean DETECT_NON_FORGE_MODS_TOML = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.DETECT_NON_FORGE_MODS_TOML);
private final IConfigurable config;
private final ModFile modFile;
private final URL issueURL;
@@ -79,8 +75,7 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
this.languageSpecs = new ArrayList<>(List.of(new LanguageSpec(modLoader, modLoaderVersion)));
// if true, this might not be a Forge mod
boolean maybeNotAForgeMod = DETECT_NON_FORGE_MODS_TOML
&& modLoader.equals(JAVAFML)
boolean maybeNotAForgeMod = modLoader.equals(JAVAFML)
&& modLoaderVersion.hasRestrictions() // if loaderVersion is not "*"
&& modLoaderVerStr.equals(MAYBE_NOT_JAVAFML_VER); // if loaderVersion is exactly "[2,)"
@@ -6,7 +6,6 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.logging.LogUtils;
@@ -14,7 +13,6 @@ 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;
@@ -33,7 +31,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());
@@ -44,15 +41,10 @@ public class ModFileParser {
}
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
try {
fileConfig.load();
fileConfig.close();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
} catch (ParsingException e) {
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.");
}
fileConfig.load();
fileConfig.close();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
}
protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
@@ -214,7 +214,7 @@ public class ModInfo implements IModInfo, IConfigurable {
this.owner = owner;
this.modId = config.<String>getConfigElement("modId")
.orElseThrow(()->new InvalidModFileException("Missing required field modid in dependency", getOwningFile()));
if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && this.modId.equals("forge")) {
if (this.modId.equals("forge")) {
var fileProps = owner.getOwningFile().getFileProperties();
// Checking containsKey to avoid a possible exception if the property is not present (due to Collections.emptyMap())
if (!fileProps.isEmpty() && fileProps.containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
@@ -226,7 +226,7 @@ public class ModInfo implements IModInfo, IConfigurable {
var mandatory = config.<Boolean>getConfigElement("mandatory");
if (mandatory.isPresent()) {
this.mandatory = mandatory.get();
} else if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
} else if (owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
this.mandatory = true;
} else {
throw new InvalidModFileException("Missing required field mandatory in dependency", getOwningFile());
@@ -16,6 +16,7 @@ import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
@@ -42,11 +43,21 @@ public class ModsFolderLocator extends AbstractModProvider implements IModLocato
public List<IModLocator.ModFileOrException> scanMods() {
LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder);
var excluded = ModDirTransformerDiscoverer.allExcluded();
try (var stream = Files.list(this.modFolder)) {
return stream.filter(path -> !excluded.contains(path) && path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(SUFFIX))
.sorted(Comparator.comparing(path -> path.getFileName().toString().toLowerCase(Locale.ROOT)))
.map(this::createMod)
.toList();
try {
var ret = new ArrayList<IModLocator.ModFileOrException>();
var files = Files.list(this.modFolder).toList();
for (var file : files) {
var name = file.getFileName().toString().toLowerCase(Locale.ROOT);
if (excluded.contains(file) || !name.endsWith(SUFFIX))
continue;
var mod = this.createMod(file, true);
if (mod == null) {
LOGGER.debug(LogMarkers.SCAN, "Found unknown jar file {} ignoring", file);
} else {
ret.add(mod);
}
}
return ret;
} catch (IOException e) {
return sneak(e);
}
@@ -48,7 +48,7 @@ class Scanner {
try (InputStream in = Files.newInputStream(path)){
ModClassVisitor mcv = new ModClassVisitor();
ClassReader cr = new ClassReader(in);
cr.accept(mcv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
cr.accept(mcv, 0);
mcv.buildData(result.getClasses(), result.getAnnotations());
} catch (IOException | IllegalArgumentException e) {
// mark path bad
@@ -15,7 +15,7 @@ abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
super(type, "forge_");
}
@Override public String getNaming() { return "srg"; }
@Override public String getNaming() { return "mcp"; }
@Override public boolean isProduction() { return true; }
public static class Client extends ForgeProdLaunchHandler {
+9 -4
View File
@@ -4,9 +4,14 @@ org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
org.gradle.parallel=true
JAVA_VERSION=17
MC_VERSION=1.20.4
JAVA_VERSION=21
MC_VERSION=1.20.6
MC_NEXT_VERSION=1.21
MCP_VERSION=20231207.112700
MCP_VERSION=20240429.135109
MAPPING_CHANNEL=official
MAPPING_VERSION=1.20.4
MAPPING_VERSION=1.20.6
// Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false
// Set to true to allow for fuzzy patching. Useful during updateing
UPDATING=false
Binary file not shown.
+1 -2
View File
@@ -1,7 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+9 -13
View File
@@ -83,8 +83,7 @@ done
# This is normally unused
# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -131,13 +130,10 @@ location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -145,7 +141,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -153,7 +149,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -202,11 +198,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * 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.
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.Mod;
@@ -19,19 +20,21 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Type;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Automatic eventbus subscriber - reads {@link EventBusSubscriber}
* annotations and passes the class instances to the {@link Bus}
* annotations and passes the class instances to the {@link nBus}
* defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/
public class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.class);
private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class);
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
if (scanData == null) return;
@@ -41,6 +44,11 @@ public class AutomaticEventSubscriber {
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
.toList();
var onlyIns = FMLEnvironment.production ? Collections.emptySet() : scanData.getAnnotations().stream()
.filter(data -> ONLY_IN_TYPE.equals(data.annotationType()))
.map(data -> data.clazz().getClassName())
.collect(Collectors.toSet());
var modids = scanData.getAnnotations().stream()
.filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
@@ -49,6 +57,10 @@ public class AutomaticEventSubscriber {
var defaultBus = new EnumData(null, "FORGE");
for (var data : targets) {
if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) {
throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead");
}
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId);
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
public class FMLJavaModLoadingContext extends ModLoadingContext
public class FMLJavaModLoadingContext
{
private final FMLModContainer container;
@@ -24,18 +24,11 @@ public class FMLJavaModLoadingContext extends ModLoadingContext
return container.getEventBus();
}
@Override
public FMLModContainer getContainer() {
return container;
}
/**
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
* @return The FMLJavaMod language specific extension from the ModLoadingContext
*
* @deprecated use {@link FMLJavaModLoadingContext} in your mod constructor
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static FMLJavaModLoadingContext get() {
return ModLoadingContext.get().extension();
}
@@ -21,7 +21,6 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Optional;
@@ -33,7 +32,6 @@ public class FMLModContainer extends ModContainer {
private final IEventBus eventBus;
private Object modInstance;
private final Class<?> modClass;
private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this);
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) {
super(info);
@@ -42,7 +40,9 @@ public class FMLModContainer extends ModContainer {
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
this.contextExtension = () -> context;
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this);
this.contextExtension = () -> contextExtension;
try {
var moduleName = info.getOwningFile().moduleName();
@@ -63,13 +63,7 @@ public class FMLModContainer extends ModContainer {
private void constructMod() {
try {
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
Constructor<?> constructor;
try {
constructor = modClass.getDeclaredConstructor(context.getClass());
} catch (NoSuchMethodException | SecurityException exception) {
constructor = modClass.getDeclaredConstructor();
}
this.modInstance = constructor.getParameterCount() == 0 ? constructor.newInstance() : constructor.newInstance(context);
this.modInstance = modClass.getDeclaredConstructor().newInstance();
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
} catch (Throwable e) {
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
+13 -19
View File
@@ -2,7 +2,7 @@ plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0.16,6.2)'
id 'net.minecraftforge.gradle' version '[6.0.24,6.2)'
}
version = mod_version
@@ -12,8 +12,8 @@ base {
archivesName = mod_id
}
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
// Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
minecraft {
@@ -31,6 +31,9 @@ minecraft {
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
// Tell FG to not automtically create the reobf tasks, as we now use Official mappings at runtime, If you don't use them at dev time then you'll have to fix your reobf yourself.
reobf = false
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
// In most cases, it is not necessary to enable.
@@ -124,11 +127,11 @@ dependencies {
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// Example mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}"
// runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}"
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
@@ -138,6 +141,9 @@ dependencies {
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
// Hack fix for now, force jopt-simple to be exactly 5.0.4 because Mojang ships that version, but some transitive dependencies request 6.0+
implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } }
}
// This block of code expands all declared replace properties in the specified resource targets.
@@ -171,16 +177,8 @@ tasks.named('jar', Jar).configure {
'Implementation-Vendor' : mod_authors
])
}
// This is the preferred method to reobfuscate your jar file
finalizedBy 'reobfJar'
}
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing:
// tasks.named('publish').configure {
// dependsOn 'reobfJar'
// }
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
@@ -199,10 +197,6 @@ tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IntelliJ no longer downloads javadocs and sources by default.
// This tells Gradle to force IDEA to do it.
idea.module { downloadJavadoc = downloadSources = true }
eclipse {
// Run everytime eclipse builds the code
//autoBuildTasks genEclipseRuns
@@ -18,6 +18,7 @@ import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
@@ -50,7 +51,7 @@ public class ExampleMod
// Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
.alwaysEat().nutrition(1).saturationMod(2f).build())));
.alwaysEdible().nutrition(1).saturationModifier(2f).build())));
// Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder()
@@ -60,9 +61,9 @@ public class ExampleMod
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());
public ExampleMod(FMLJavaModLoadingContext context)
public ExampleMod()
{
IEventBus modEventBus = context.getModEventBus();
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
@@ -81,7 +82,7 @@ public class ExampleMod
modEventBus.addListener(this::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
context.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);
}
private void commonSetup(final FMLCommonSetupEvent event)
@@ -41,13 +41,6 @@ authors="${mod_authors}" #optional
# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself.
#displayTest="MATCH_VERSION" # if nothing is specified, MATCH_VERSION is the default when clientSideOnly=false, otherwise IGNORE_ALL_VERSION when clientSideOnly=true (#optional)
# Access Transformers
# Optional, if not specified Forge will attempt to find the default META-INF/accesstransformer.cfg and silently continue if not found. May default to an empty list in a future MC.
# If you specify AT path strings in this list, Forge will attempt to load each of them and throw errors for any that aren't found.
# Specifying an empty list when your mod has no ATs is recommended to opt-out of the default for slightly better loading performance.
#accessTransformers = []
# The description text for the mod (multi line!) (#mandatory)
description='''${mod_description}'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
@@ -1,56 +1,55 @@
--- a/com/mojang/blaze3d/pipeline/RenderTarget.java
+++ b/com/mojang/blaze3d/pipeline/RenderTarget.java
@@ -113,7 +_,10 @@
GlStateManager._texParameter(3553, 34892, 0);
GlStateManager._texParameter(3553, 10242, 33071);
GlStateManager._texParameter(3553, 10243, 33071);
+ if (!stencilEnabled)
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, (IntBuffer)null);
+ else
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
}
@@ -106,7 +_,10 @@
GlStateManager._texParameter(3553, 34892, 0);
GlStateManager._texParameter(3553, 10242, 33071);
GlStateManager._texParameter(3553, 10243, 33071);
+ if (!stencilEnabled)
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, null);
+ else
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
}
this.setFilterMode(9728);
@@ -124,7 +_,14 @@
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
if (this.useDepth) {
+ if(!stencilEnabled)
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
+ else if(net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ } else {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ }
}
this.setFilterMode(9728, true);
@@ -116,8 +_,13 @@
GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, null);
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
- if (this.useDepth) {
+ if (this.useDepth && !stencilEnabled) {
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
+ } else if(this.useDepth && net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ } else if (this.useDepth) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
}
this.checkStatus();
@@ -292,4 +_,27 @@
public int getDepthTextureId() {
return this.depthBufferId;
}
this.checkStatus();
@@ -280,5 +_,26 @@
public int getDepthTextureId() {
return this.depthBufferId;
+ }
+
+ /*================================ FORGE START ================================================*/
+ private boolean stencilEnabled = false;
+ /**
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
+ * Modders must call this directly to set things up.
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
+ * <b>Make sure to call this on the main render thread!</b>
+ */
+ public void enableStencil() {
+ if(stencilEnabled) return;
+ stencilEnabled = true;
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
+ }
+ private boolean stencilEnabled = false;
+ /**
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
+ * Modders must call this directly to set things up.
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
+ * <b>Make sure to call this on the main render thread!</b>
+ */
+ public void enableStencil() {
+ if (stencilEnabled) return;
+ stencilEnabled = true;
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
+ }
+
+ /**
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
+ * If not, and a modder wishes it to be, they must call enableStencil.
+ */
+ public boolean isStencilEnabled() {
+ return this.stencilEnabled;
+ }
+ /*================================ FORGE END ================================================*/
+ /**
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
+ * If not, and a modder wishes it to be, they must call enableStencil.
+ */
+ public boolean isStencilEnabled() {
+ return this.stencilEnabled;
}
}
@@ -1,19 +1,20 @@
--- a/com/mojang/blaze3d/platform/GlStateManager.java
+++ b/com/mojang/blaze3d/platform/GlStateManager.java
@@ -501,9 +_,16 @@
@@ -493,9 +_,17 @@
}
}
}
+ /* Stores the last values sent into glMultiTexCoord2f */
+ public static float lastBrightnessX = 0.0f;
+ public static float lastBrightnessY = 0.0f;
+
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
RenderSystem.assertOnRenderThreadOrInit();
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
+ if (p_84161_ == GL13.GL_TEXTURE1) {
+ lastBrightnessX = p_84162_;
+ lastBrightnessY = p_84163_;
+ }
}
+ /* Stores the last values sent into glMultiTexCoord2f */
+ public static float lastBrightnessX = 0.0f;
+ public static float lastBrightnessY = 0.0f;
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
RenderSystem.assertOnRenderThreadOrInit();
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
+ if (p_84161_ == GL13.GL_TEXTURE1) {
+ lastBrightnessX = p_84162_;
+ lastBrightnessY = p_84163_;
+ }
}
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
@@ -1,28 +1,30 @@
--- a/com/mojang/blaze3d/platform/Window.java
+++ b/com/mojang/blaze3d/platform/Window.java
@@ -81,7 +_,8 @@
GLFW.glfwWindowHint(139267, 2);
GLFW.glfwWindowHint(139272, 204801);
GLFW.glfwWindowHint(139270, 1);
- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) {
if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
@@ -93,6 +_,7 @@
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
+ }
@@ -82,7 +_,8 @@
GLFW.glfwWindowHint(139267, 2);
GLFW.glfwWindowHint(139272, 204801);
GLFW.glfwWindowHint(139270, 1);
- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) {
if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
@@ -94,6 +_,7 @@
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
+ }
GLFW.glfwMakeContextCurrent(this.window);
GL.createCapabilities();
@@ -242,6 +_,7 @@
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth==0) net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w->this.framebufferWidth=w, h->this.framebufferHeight=h);
}
GLFW.glfwMakeContextCurrent(this.window);
GL.createCapabilities();
@@ -242,6 +_,9 @@
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) {
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w -> this.framebufferWidth = w, h -> this.framebufferHeight = h);
+ }
}
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
@@ -1,17 +1,18 @@
--- a/com/mojang/blaze3d/vertex/BufferBuilder.java
+++ b/com/mojang/blaze3d/vertex/BufferBuilder.java
@@ -477,4 +_,14 @@
this.sorting = p_277855_;
}
}
@@ -389,6 +_,15 @@
return MemoryUtil.memSlice(this.buffer, p_231170_, p_231171_ - p_231170_);
}
+ public void putBulkData(ByteBuffer buffer) {
+ ensureCapacity(buffer.limit() + this.format.getVertexSize());
+ this.buffer.position(this.nextElementByte);
+ this.buffer.put(buffer);
+ this.buffer.position(0);
+ this.vertices += buffer.limit() / this.format.getVertexSize();
+ this.nextElementByte += buffer.limit();
+ }
+
+ // Forge start
+ public void putBulkData(ByteBuffer buffer) {
+ ensureCapacity(buffer.limit() + this.format.getVertexSize());
+ this.buffer.position(this.nextElementByte);
+ this.buffer.put(buffer);
+ this.buffer.position(0);
+ this.vertices += buffer.limit() / this.format.getVertexSize();
+ this.nextElementByte += buffer.limit();
+ }
}
@OnlyIn(Dist.CLIENT)
public static record DrawState(
VertexFormat format, int vertexCount, int indexCount, VertexFormat.Mode mode, VertexFormat.IndexType indexType, boolean indexOnly, boolean sequentialIndex
@@ -1,11 +1,11 @@
--- a/com/mojang/blaze3d/vertex/PoseStack.java
+++ b/com/mojang/blaze3d/vertex/PoseStack.java
@@ -11,7 +_,7 @@
import org.joml.Quaternionf;
@@ -13,7 +_,7 @@
import org.joml.Vector3f;
@OnlyIn(Dist.CLIENT)
-public class PoseStack {
+public class PoseStack implements net.minecraftforge.client.extensions.IForgePoseStack {
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), (p_85848_) -> {
Matrix4f matrix4f = new Matrix4f();
Matrix3f matrix3f = new Matrix3f();
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), p_85848_ -> {
Matrix4f matrix4f = new Matrix4f();
Matrix3f matrix3f = new Matrix3f();
@@ -1,11 +1,11 @@
--- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
+++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
@@ -46,7 +_,7 @@
public void endVertex() {
Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz));
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F));
vector4f.rotateY((float)Math.PI);
vector4f.rotateX((-(float)Math.PI / 2F));
@@ -47,7 +_,7 @@
@Override
public void endVertex() {
Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz));
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F));
vector4f.rotateY((float) Math.PI);
vector4f.rotateX((float) (-Math.PI / 2));
@@ -1,38 +1,24 @@
--- a/com/mojang/blaze3d/vertex/VertexConsumer.java
+++ b/com/mojang/blaze3d/vertex/VertexConsumer.java
@@ -14,7 +_,7 @@
@@ -13,7 +_,7 @@
import org.lwjgl.system.MemoryStack;
@OnlyIn(Dist.CLIENT)
-public interface VertexConsumer {
+public interface VertexConsumer extends net.minecraftforge.client.extensions.IForgeVertexConsumer {
VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_);
VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_);
VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_);
@@ -64,6 +_,10 @@
}
VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_);
@@ -142,10 +_,11 @@
f5 = afloat[k] * p_85992_;
}
default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, int[] p_86002_, int p_86003_, boolean p_86004_) {
+ putBulkData(p_85996_, p_85997_, p_85998_, p_85999_, p_86000_, p_86001_, 1, p_86002_, p_86003_, p_86004_);
+ }
+
+ default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, float alpha, int[] p_86002_, int p_86003_, boolean p_86004_) {
float[] afloat = new float[]{p_85998_[0], p_85998_[1], p_85998_[2], p_85998_[3]};
int[] aint = new int[]{p_86002_[0], p_86002_[1], p_86002_[2], p_86002_[3]};
int[] aint1 = p_85997_.getVertices();
@@ -99,11 +_,13 @@
f5 = afloat[k] * p_86001_;
- int l = aint[k];
+ int l = applyBakedLighting(aint[k], bytebuffer);
float f9 = bytebuffer.getFloat(16);
float f10 = bytebuffer.getFloat(20);
Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F));
+ applyBakedNormals(vector3f, bytebuffer, p_85988_.normal());
this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, p_335371_, f9, f10, p_85993_, l, vector3f.x(), vector3f.y(), vector3f.z());
}
- int l = aint[k];
+ int l = applyBakedLighting(p_86002_[k], bytebuffer);
float f9 = bytebuffer.getFloat(16);
float f10 = bytebuffer.getFloat(20);
Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F));
- this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, 1.0F, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
+ applyBakedNormals(vector3f, bytebuffer, p_85996_.normal());
+ float vertexAlpha = p_86004_ ? alpha * (float) (bytebuffer.get(15) & 255) / 255.0F : alpha;
+ this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, vertexAlpha, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
}
}
}
@@ -1,14 +1,21 @@
--- a/com/mojang/blaze3d/vertex/VertexFormat.java
+++ b/com/mojang/blaze3d/vertex/VertexFormat.java
@@ -176,4 +_,11 @@
return i;
}
}
@@ -12,7 +_,7 @@
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
-public class VertexFormat {
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
private final ImmutableList<VertexFormatElement> elements;
private final ImmutableMap<String, VertexFormatElement> elementMapping;
private final IntList offsets = new IntArrayList();
@@ -113,6 +_,9 @@
return vertexbuffer;
}
+
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
+ public int getOffset(int index) { return offsets.getInt(index); }
+ public boolean hasPosition() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.POSITION); }
+ public boolean hasNormal() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.NORMAL); }
+ public boolean hasColor() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.COLOR); }
+ public boolean hasUV(int which) { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == which); }
}
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
+ public int getOffset(int index) { return offsets.getInt(index); }
@OnlyIn(Dist.CLIENT)
public static enum IndexType {
@@ -1,13 +0,0 @@
--- a/com/mojang/blaze3d/vertex/VertexFormatElement.java
+++ b/com/mojang/blaze3d/vertex/VertexFormatElement.java
@@ -90,6 +_,10 @@
this.usage.clearBufferState(this.index, p_166964_);
}
+ public int getElementCount() {
+ return count;
+ }
+
@OnlyIn(Dist.CLIENT)
public static enum Type {
FLOAT(4, "Float", 5126),
@@ -1,31 +1,31 @@
--- a/com/mojang/math/Transformation.java
+++ b/com/mojang/math/Transformation.java
@@ -13,7 +_,7 @@
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector3fc;
-public final class Transformation {
+public final class Transformation implements net.minecraftforge.common.extensions.IForgeTransformation {
private final Matrix4f matrix;
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create((p_269604_) -> {
return p_269604_.group(ExtraCodecs.VECTOR3F.fieldOf("translation").forGetter((p_269599_) -> {
@@ -156,6 +_,19 @@
public int hashCode() {
return Objects.hash(this.matrix);
}
private final Matrix4f matrix;
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create(
p_269604_ -> p_269604_.group(
@@ -169,5 +_,19 @@
vector3f1.lerp(p_175938_.getScale(), p_175939_);
quaternionf1.slerp(p_175938_.getRightRotation(), p_175939_);
return new Transformation(vector3f, quaternionf, vector3f1, quaternionf1);
+ }
+
+ private Matrix3f normalTransform = null;
+ public Matrix3f getNormalMatrix() {
+ checkNormalTransform();
+ return normalTransform;
+ }
+
+ private void checkNormalTransform() {
+ if (normalTransform == null) {
+ normalTransform = new Matrix3f(matrix);
+ normalTransform.invert();
+ normalTransform.transpose();
+ }
+ }
public Transformation slerp(Transformation p_175938_, float p_175939_) {
Vector3f vector3f = this.getTranslation();
}
}
@@ -1,10 +1,9 @@
--- a/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
+++ b/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
@@ -61,6 +_,15 @@
return Component.empty().append(this.lines.title).append(": ").append(this.lines.detail);
}
@@ -71,6 +_,15 @@
}
+ @Override
@Override
+ public boolean keyPressed(int key, int scanCode, int modifiers) {
+ if (key == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) {
+ minecraft.setScreen(this.nextScreen);
@@ -13,6 +12,7 @@
+ return super.keyPressed(key, scanCode, modifiers);
+ }
+
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
+ @Override
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
@@ -1,48 +1,48 @@
--- a/net/minecraft/CrashReport.java
+++ b/net/minecraft/CrashReport.java
@@ -59,14 +_,9 @@
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
- p_127520_.append("Stacktrace:\n");
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
- p_127520_.append("Stacktrace:\n");
-
- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
- p_127520_.append("\t").append("at ").append(stacktraceelement);
- p_127520_.append("\n");
- }
-
- for(StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
- p_127520_.append("\t").append("at ").append((Object)stacktraceelement);
- p_127520_.append("\n");
- }
-
- p_127520_.append("\n");
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
}
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
}
for(CrashReportCategory crashreportcategory : this.details) {
for (CrashReportCategory crashreportcategory : this.details) {
@@ -74,6 +_,7 @@
p_127520_.append("\n\n");
}
p_127520_.append("\n\n");
}
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
this.systemReport.appendToCrashReportString(p_127520_);
}
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
this.systemReport.appendToCrashReportString(p_127520_);
}
@@ -93,18 +_,7 @@
throwable.setStackTrace(this.exception.getStackTrace());
}
throwable.setStackTrace(this.exception.getStackTrace());
}
- String s;
- try {
- stringwriter = new StringWriter();
- printwriter = new PrintWriter(stringwriter);
- throwable.printStackTrace(printwriter);
- s = stringwriter.toString();
- } finally {
- IOUtils.closeQuietly((Writer)stringwriter);
- IOUtils.closeQuietly((Writer)printwriter);
- }
- String s;
- try {
- stringwriter = new StringWriter();
- printwriter = new PrintWriter(stringwriter);
- throwable.printStackTrace(printwriter);
- s = stringwriter.toString();
- } finally {
- IOUtils.closeQuietly((Writer)stringwriter);
- IOUtils.closeQuietly((Writer)printwriter);
- }
-
- return s;
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
}
- return s;
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
}
public String getFriendlyReport() {
public String getFriendlyReport() {
@@ -1,38 +1,37 @@
--- a/net/minecraft/CrashReportCategory.java
+++ b/net/minecraft/CrashReportCategory.java
@@ -102,8 +_,10 @@
if (astacktraceelement.length <= 0) {
return 0;
} else {
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
+ int len = astacktraceelement.length - 3 - p_128149_;
+ if (len <= 0) len = astacktraceelement.length;
+ this.stackTrace = new StackTraceElement[len];
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
return this.stackTrace.length;
}
}
@@ -147,17 +_,17 @@
@@ -112,8 +_,10 @@
if (astacktraceelement.length <= 0) {
return 0;
} else {
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
+ int len = astacktraceelement.length - 3 - p_128149_;
+ if (len <= 0) len = astacktraceelement.length;
+ this.stackTrace = new StackTraceElement[len];
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
return this.stackTrace.length;
}
}
@@ -160,16 +_,16 @@
if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:");
if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:");
-
- for(StackTraceElement stacktraceelement : this.stackTrace) {
- p_128169_.append("\n\tat ");
- p_128169_.append((Object)stacktraceelement);
- }
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
}
- for (StackTraceElement stacktraceelement : this.stackTrace) {
- p_128169_.append("\n\tat ");
- p_128169_.append(stacktraceelement);
- }
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
}
}
}
public StackTraceElement[] getStacktrace() {
return this.stackTrace;
+ }
public StackTraceElement[] getStacktrace() {
return this.stackTrace;
+ }
+
+ public void applyStackTrace(Throwable t) {
+ this.stackTrace = t.getStackTrace();
}
+ public void applyStackTrace(Throwable t) {
+ this.stackTrace = t.getStackTrace();
}
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
@@ -1,10 +1,10 @@
--- a/net/minecraft/SharedConstants.java
+++ b/net/minecraft/SharedConstants.java
@@ -215,6 +_,7 @@
}
@@ -181,6 +_,7 @@
}
static {
+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified
ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION);
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
static {
+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified
ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION);
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
@@ -1,23 +1,11 @@
--- a/net/minecraft/Util.java
+++ b/net/minecraft/Util.java
@@ -180,6 +_,11 @@
return 255;
}
+ // We add these inner classes to compensate for Mojang's missing inner classes and shift the anonymous class index.
+ // This allows us to obfuscate subsequent anonymous inner classes correctly.
+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT1 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } };
+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT2 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } };
+
public static ExecutorService backgroundExecutor() {
return BACKGROUND_EXECUTOR;
}
@@ -254,7 +_,7 @@
try {
type = DataFixers.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())).getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) {
- LOGGER.error("No data fixer registered for {}", (Object)p_137553_);
+ LOGGER.debug("No data fixer registered for {}", (Object)p_137553_);
if (SharedConstants.IS_RUNNING_IN_IDE) {
throw illegalargumentexception;
}
@@ -267,7 +_,7 @@
.getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion()))
.getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) {
- LOGGER.error("No data fixer registered for {}", p_137553_);
+ LOGGER.debug("No data fixer registered for {}", p_137553_);
if (SharedConstants.IS_RUNNING_IN_IDE) {
throw illegalargumentexception;
}
@@ -1,15 +1,15 @@
--- a/net/minecraft/advancements/Advancement.java
+++ b/net/minecraft/advancements/Advancement.java
@@ -171,7 +_,11 @@
}
@@ -214,7 +_,11 @@
}
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_));
+ return save(p_138390_, new ResourceLocation(p_138391_));
+ }
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_));
+ return save(p_138390_, new ResourceLocation(p_138391_));
+ }
+
+ public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, ResourceLocation id) {
+ AdvancementHolder advancementholder = this.build(id);
p_138390_.accept(advancementholder);
return advancementholder;
}
+ public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, ResourceLocation id) {
+ AdvancementHolder advancementholder = this.build(id);
p_138390_.accept(advancementholder);
return advancementholder;
}
@@ -1,11 +1,10 @@
--- a/net/minecraft/advancements/AdvancementRewards.java
+++ b/net/minecraft/advancements/AdvancementRewards.java
@@ -27,7 +_,7 @@
@@ -40,6 +_,7 @@
LootParams lootparams = new LootParams.Builder(p_9990_.serverLevel())
.withParameter(LootContextParams.THIS_ENTITY, p_9990_)
.withParameter(LootContextParams.ORIGIN, p_9990_.position())
+ .withLuck(p_9990_.getLuck())
.create(LootContextParamSets.ADVANCEMENT_REWARD);
boolean flag = false;
public void grant(ServerPlayer p_9990_) {
p_9990_.giveExperiencePoints(this.experience);
- LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).create(LootContextParamSets.ADVANCEMENT_REWARD);
+ LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).withLuck(p_9990_.getLuck()).create(LootContextParamSets.ADVANCEMENT_REWARD); // Forge: Add luck to LootContext
boolean flag = false;
for(ResourceLocation resourcelocation : this.loot) {
@@ -1,11 +0,0 @@
--- a/net/minecraft/advancements/critereon/ItemPredicate.java
+++ b/net/minecraft/advancements/critereon/ItemPredicate.java
@@ -45,7 +_,7 @@
return false;
} else {
if (!this.enchantments.isEmpty()) {
- Map<Enchantment, Integer> map = EnchantmentHelper.deserializeEnchantments(p_45050_.getEnchantmentTags());
+ Map<Enchantment, Integer> map = p_45050_.getAllEnchantments();
for(EnchantmentPredicate enchantmentpredicate : this.enchantments) {
if (!enchantmentpredicate.containedIn(map)) {
@@ -1,21 +1,21 @@
--- a/net/minecraft/client/Camera.java
+++ b/net/minecraft/client/Camera.java
@@ -212,6 +_,18 @@
return this.partialTickTime;
}
@@ -227,6 +_,18 @@
return this.partialTickTime;
}
+ public void setAnglesInternal(float yaw, float pitch) {
+ this.yRot = yaw;
+ this.xRot = pitch;
+ }
+ public void setAnglesInternal(float yaw, float pitch) {
+ this.yRot = yaw;
+ this.xRot = pitch;
+ }
+
+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() {
+ if (!this.initialized)
+ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
+ else
+ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position);
+ }
+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() {
+ if (!this.initialized)
+ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
+ else
+ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position);
+ }
+
@OnlyIn(Dist.CLIENT)
public static class NearPlane {
final Vec3 forward;
@OnlyIn(Dist.CLIENT)
public static class NearPlane {
final Vec3 forward;
@@ -2,9 +2,9 @@
+++ b/net/minecraft/client/ClientBrandRetriever.java
@@ -10,6 +_,6 @@
@DontObfuscate
public static String getClientModName() {
- return "vanilla";
+ return net.minecraftforge.internal.BrandingControl.getClientBranding();
}
@DontObfuscate
public static String getClientModName() {
- return "vanilla";
+ return net.minecraftforge.internal.BrandingControl.getClientBranding();
}
}
@@ -1,20 +1,20 @@
--- a/net/minecraft/client/ClientRecipeBook.java
+++ b/net/minecraft/client/ClientRecipeBook.java
@@ -56,7 +_,7 @@
Recipe<?> recipe = recipeholder.value();
if (!recipe.isSpecial() && !recipe.isIncomplete()) {
RecipeBookCategories recipebookcategories = getCategory(recipeholder);
- String s = recipe.getGroup();
+ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty.
if (s.isEmpty()) {
map.computeIfAbsent(recipebookcategories, (p_90645_) -> {
return Lists.newArrayList();
@@ -144,6 +_,8 @@
} else if (recipetype == RecipeType.SMITHING) {
return RecipeBookCategories.SMITHING;
} else {
+ RecipeBookCategories categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType) recipetype, p_299041_);
+ if (categories != null) return categories;
LOGGER.warn("Unknown recipe category: {}/{}", LogUtils.defer(() -> {
return BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType());
}), LogUtils.defer(p_299041_::id));
@@ -65,7 +_,7 @@
Recipe<?> recipe = recipeholder.value();
if (!recipe.isSpecial() && !recipe.isIncomplete()) {
RecipeBookCategories recipebookcategories = getCategory(recipeholder);
- String s = recipe.getGroup();
+ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty.
if (s.isEmpty()) {
map.computeIfAbsent(recipebookcategories, p_90645_ -> Lists.newArrayList()).add(ImmutableList.of(recipeholder));
} else {
@@ -125,6 +_,8 @@
} else if (recipetype == RecipeType.SMITHING) {
return RecipeBookCategories.SMITHING;
} else {
+ var categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType)recipetype, p_299041_);
+ if (categories != null) return categories;
LOGGER.warn(
"Unknown recipe category: {}/{}",
LogUtils.defer(() -> BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType())),
@@ -1,182 +1,183 @@
--- a/net/minecraft/client/KeyMapping.java
+++ b/net/minecraft/client/KeyMapping.java
@@ -13,9 +_,9 @@
@@ -14,9 +_,9 @@
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
-public class KeyMapping implements Comparable<KeyMapping> {
+public class KeyMapping implements Comparable<KeyMapping>, net.minecraftforge.client.extensions.IForgeKeyMapping {
private static final Map<String, KeyMapping> ALL = Maps.newHashMap();
- private static final Map<InputConstants.Key, KeyMapping> MAP = Maps.newHashMap();
+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup();
private static final Set<String> CATEGORIES = Sets.newHashSet();
public static final String CATEGORY_MOVEMENT = "key.categories.movement";
public static final String CATEGORY_MISC = "key.categories.misc";
@@ -41,7 +_,7 @@
private int clickCount;
private static final Map<String, KeyMapping> ALL = Maps.newHashMap();
- private static final Map<InputConstants.Key, KeyMapping> MAP = Maps.newHashMap();
+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup();
private static final Set<String> CATEGORIES = Sets.newHashSet();
public static final String CATEGORY_MOVEMENT = "key.categories.movement";
public static final String CATEGORY_MISC = "key.categories.misc";
@@ -42,14 +_,14 @@
private int clickCount;
public static void click(InputConstants.Key p_90836_) {
- KeyMapping keymapping = MAP.get(p_90836_);
+ for (KeyMapping keymapping : MAP.getAll(p_90836_))
if (keymapping != null) {
++keymapping.clickCount;
}
@@ -49,7 +_,7 @@
}
public static void click(InputConstants.Key p_90836_) {
- KeyMapping keymapping = MAP.get(p_90836_);
+ for (KeyMapping keymapping : MAP.getAll(p_90836_))
if (keymapping != null) {
keymapping.clickCount++;
}
}
public static void set(InputConstants.Key p_90838_, boolean p_90839_) {
- KeyMapping keymapping = MAP.get(p_90838_);
+ for (KeyMapping keymapping : MAP.getAll(p_90838_))
if (keymapping != null) {
keymapping.setDown(p_90839_);
}
@@ -105,7 +_,7 @@
}
public static void set(InputConstants.Key p_90838_, boolean p_90839_) {
- KeyMapping keymapping = MAP.get(p_90838_);
+ for (KeyMapping keymapping : MAP.getAll(p_90838_))
if (keymapping != null) {
keymapping.setDown(p_90839_);
}
@@ -100,7 +_,7 @@
}
public boolean isDown() {
- return this.isDown;
+ return this.isDown && isConflictContextAndModifierActive();
}
public boolean isDown() {
- return this.isDown;
+ return this.isDown && isConflictContextAndModifierActive();
}
public String getCategory() {
@@ -139,7 +_,13 @@
}
public String getCategory() {
@@ -136,7 +_,16 @@
public int compareTo(KeyMapping p_90841_) {
return this.category.equals(p_90841_.category)
? I18n.get(this.name).compareTo(I18n.get(p_90841_.name))
- : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category));
+ : compareSort(this.category, p_90841_.category);
+ }
+
+ private static int compareSort(String c1, String c2) {
+ Integer o1 = CATEGORY_SORT_ORDER.get(c1);
+ Integer o2 = CATEGORY_SORT_ORDER.get(c2);
+ if (o1 == null && o2 != null) return 1;
+ if (o1 != null && o2 == null) return -1;
+ if (o1 == null && o2 == null) return I18n.get(c1).compareTo(I18n.get(c2));
+ return o1.compareTo(o2);
}
public int compareTo(KeyMapping p_90841_) {
- return this.category.equals(p_90841_.category) ? I18n.get(this.name).compareTo(I18n.get(p_90841_.name)) : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category));
+ if (this.category.equals(p_90841_.category)) return I18n.get(this.name).compareTo(I18n.get(p_90841_.name));
+ Integer tCat = CATEGORY_SORT_ORDER.get(this.category);
+ Integer oCat = CATEGORY_SORT_ORDER.get(p_90841_.category);
+ if (tCat == null && oCat != null) return 1;
+ if (tCat != null && oCat == null) return -1;
+ if (tCat == null && oCat == null) return I18n.get(this.category).compareTo(I18n.get(p_90841_.category));
+ return tCat.compareTo(oCat);
}
public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -145,6 +_,20 @@
}
public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -150,6 +_,20 @@
}
public boolean same(KeyMapping p_90851_) {
+ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) {
+ net.minecraftforge.client.settings.KeyModifier keyModifier = getKeyModifier();
+ net.minecraftforge.client.settings.KeyModifier otherKeyModifier = p_90851_.getKeyModifier();
+ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) {
+ return true;
+ } else if (getKey().equals(p_90851_.getKey())) {
+ // IN_GAME key contexts have a conflict when at least one modifier is NONE.
+ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E.
+ // GUI and other key contexts do not have this limitation.
+ return keyModifier == otherKeyModifier ||
+ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) &&
+ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE));
public boolean same(KeyMapping p_90851_) {
+ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) {
+ var keyModifier = getKeyModifier();
+ var otherKeyModifier = p_90851_.getKeyModifier();
+ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) {
+ return true;
+ } else if (getKey().equals(p_90851_.getKey())) {
+ // IN_GAME key contexts have a conflict when at least one modifier is NONE.
+ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E.
+ // GUI and other key contexts do not have this limitation.
+ return keyModifier == otherKeyModifier ||
+ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) &&
+ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE));
+ }
+ }
+ }
return this.key.equals(p_90851_.key);
}
return this.key.equals(p_90851_.key);
}
@@ -170,11 +_,13 @@
}
@@ -163,11 +_,13 @@
}
public Component getTranslatedKeyMessage() {
+ return getKeyModifier().getCombinedName(key, () -> {
return this.key.getDisplayName();
+ });
}
public Component getTranslatedKeyMessage() {
+ return getKeyModifier().getCombinedName(key, () -> {
return this.key.getDisplayName();
+ });
}
public boolean isDefault() {
- return this.key.equals(this.defaultKey);
+ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier();
}
public boolean isDefault() {
- return this.key.equals(this.defaultKey);
+ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier();
}
public String saveString() {
@@ -183,5 +_,89 @@
public String saveString() {
@@ -176,5 +_,88 @@
public void setDown(boolean p_90846_) {
this.isDown = p_90846_;
+ }
public void setDown(boolean p_90846_) {
this.isDown = p_90846_;
+ }
+
+ /****************** Forge Start *****************************/
+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL;
+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL;
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category);
+ }
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) {
+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category);
+ }
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) {
+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) {
+ this.name = description;
+ this.key = keyCode;
+ this.defaultKey = keyCode;
+ this.category = category;
+ this.keyConflictContext = keyConflictContext;
+ this.keyModifier = keyModifier;
+ this.keyModifierDefault = keyModifier;
+ if (this.keyModifier.matches(keyCode))
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this);
+ MAP.put(keyCode, this);
+ CATEGORIES.add(category);
+ }
+
+ @Override
+ public InputConstants.Key getKey() {
+ return this.key;
+ }
+
+ @Override
+ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) {
+ this.keyConflictContext = keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() {
+ return keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() {
+ return keyModifierDefault;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() {
+ return keyModifier;
+ }
+
+ @Override
+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ MAP.remove(this);
+
+ if (keyModifier == null)
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key);
+ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) {
+ this.name = description;
+ this.key = keyCode;
+ this.defaultKey = keyCode;
+ this.category = category;
+ this.keyConflictContext = keyConflictContext;
+ this.keyModifier = keyModifier;
+
+ this.keyModifierDefault = keyModifier;
+ if (this.keyModifier.matches(keyCode))
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this);
+ MAP.put(keyCode, this);
}
+ CATEGORIES.add(category);
+ }
+
+ @Override
+ public InputConstants.Key getKey() {
+ return this.key;
+ }
+
+ @Override
+ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) {
+ this.keyConflictContext = keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() {
+ return keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() {
+ return keyModifierDefault;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() {
+ return keyModifier;
+ }
+
+ @Override
+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ MAP.remove(this);
+
+ if (keyModifier == null)
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key);
+ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+
+ this.key = keyCode;
+ this.keyModifier = keyModifier;
+
+ MAP.put(keyCode, this);
}
}
@@ -1,50 +1,39 @@
--- a/net/minecraft/client/KeyboardHandler.java
+++ b/net/minecraft/client/KeyboardHandler.java
@@ -397,11 +_,15 @@
Screen.wrapScreenError(() -> {
if (p_90897_ != 1 && p_90897_ != 2) {
if (p_90897_ == 0) {
- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPre(screen, p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPost(screen, p_90895_, p_90896_, p_90898_);
}
} else {
screen.afterKeyboardAction();
- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPre(screen, p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPost(screen, p_90895_, p_90896_, p_90898_);
}
}, "keyPressed event handler", screen.getClass().getCanonicalName());
@@ -478,21 +_,26 @@
@@ -410,9 +_,9 @@
Screen.wrapScreenError(() -> {
if (p_90897_ == 1 || p_90897_ == 2) {
screen.afterKeyboardAction();
- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(aboolean, screen, p_90895_, p_90896_, p_90898_);
} else if (p_90897_ == 0) {
- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(aboolean, screen, p_90895_, p_90896_, p_90898_);
}
}, "keyPressed event handler", screen.getClass().getCanonicalName());
if (aboolean[0]) {
@@ -481,20 +_,21 @@
}
}
}
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
}
}
}
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
}
}
private void charTyped(long p_90890_, int p_90891_, int p_90892_) {
if (p_90890_ == this.minecraft.getWindow().getWindow()) {
- GuiEventListener guieventlistener = this.minecraft.screen;
+ Screen guieventlistener = this.minecraft.screen;
if (guieventlistener != null && this.minecraft.getOverlay() == null) {
if (Character.charCount(p_90891_) == 1) {
Screen.wrapScreenError(() -> {
- guieventlistener.charTyped((char)p_90891_, p_90892_);
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, (char)p_90891_, p_90892_)) return;
+ if (guieventlistener.charTyped((char)p_90891_, p_90892_)) return;
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, (char)p_90891_, p_90892_);
}, "charTyped event handler", guieventlistener.getClass().getCanonicalName());
} else {
for(char c0 : Character.toChars(p_90891_)) {
Screen.wrapScreenError(() -> {
- guieventlistener.charTyped(c0, p_90892_);
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, c0, p_90892_)) return;
+ if (guieventlistener.charTyped(c0, p_90892_)) return;
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, c0, p_90892_);
}, "charTyped event handler", guieventlistener.getClass().getCanonicalName());
}
private void charTyped(long p_90890_, int p_90891_, int p_90892_) {
if (p_90890_ == this.minecraft.getWindow().getWindow()) {
- GuiEventListener guieventlistener = this.minecraft.screen;
+ Screen guieventlistener = this.minecraft.screen;
if (guieventlistener != null && this.minecraft.getOverlay() == null) {
if (Character.charCount(p_90891_) == 1) {
Screen.wrapScreenError(
- () -> guieventlistener.charTyped((char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()
+ () -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, (char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()
);
} else {
for (char c0 : Character.toChars(p_90891_)) {
- Screen.wrapScreenError(() -> guieventlistener.charTyped(c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName());
}
}
}
@@ -1,447 +1,452 @@
--- a/net/minecraft/client/Minecraft.java
+++ b/net/minecraft/client/Minecraft.java
@@ -254,7 +_,7 @@
@@ -259,7 +_,7 @@
import org.slf4j.Logger;
@OnlyIn(Dist.CLIENT)
-public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler {
+public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft {
static Minecraft instance;
private static final Logger LOGGER = LogUtils.getLogger();
public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX;
static Minecraft instance;
private static final Logger LOGGER = LogUtils.getLogger();
public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX;
@@ -438,7 +_,6 @@
}
}, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", (Object)this.user.getName());
- LOGGER.debug("(Session ID is {})", (Object)this.user.getSessionId());
this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat;
@@ -474,15 +_,15 @@
}
this.window.setFramerateLimit(this.options.framerateLimit().get());
+ // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window.getWindow());
this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window.getWindow());
RenderSystem.initRenderer(this.options.glDebugVerbosity, false);
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F);
this.mainRenderTarget.clear(ON_OSX);
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
+ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager);
this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode);
@@ -538,10 +_,13 @@
this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers);
this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener());
this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers);
+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent());
this.resourceManager.registerReloadListener(this.levelRenderer);
- this.createSearchTrees();
+ // Forge: We delay this to allow registration of modded creative mode tabs
+ // this.createSearchTrees();
this.resourceManager.registerReloadListener(this.searchRegistry);
this.particleEngine = new ParticleEngine(this.level, this.textureManager);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine);
this.resourceManager.registerReloadListener(this.particleEngine);
this.paintingTextures = new PaintingTextureManager(this.textureManager);
this.resourceManager.registerReloadListener(this.paintingTextures);
@@ -552,7 +_,10 @@
this.gpuWarnlistManager = new GpuWarnlistManager();
this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies);
- this.gui = new Gui(this, this.itemRenderer);
+ this.gui = new net.minecraftforge.client.gui.overlay.ForgeGui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
RealmsClient realmsclient = RealmsClient.create(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
@@ -572,6 +_,7 @@
TinyFileDialogs.tinyfd_messageBox("Minecraft", stringbuilder.toString(), "ok", "error", false);
}
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setDefaultErrorCallback();
@@ -592,7 +_,7 @@
ReloadInstance reloadinstance = this.resourceManager.createReload(Util.backgroundExecutor(), this, RESOURCE_RELOAD_INITIAL_TASK, list);
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
- this.setOverlay(new LoadingOverlay(this, reloadinstance, (p_296164_) -> {
+ this.setOverlay(net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay(() -> this, () -> reloadinstance, (p_296164_) -> {
Util.ifElse(p_296164_, (p_296162_) -> {
this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie);
}, () -> {
@@ -602,8 +_,10 @@
this.reloadStateTracker.finishReload();
this.onResourceLoadFinished(minecraft$gameloadcookie);
+ if (net.minecraftforge.client.loading.ClientModLoader.completeModLoading())
+ return; // Do not overwrite the error screen if there are errors
});
- }, false));
+ }, false).get());
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path());
}
@@ -701,7 +_,7 @@
private String createTitle() {
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) {
- stringbuilder.append("*");
+ stringbuilder.append('*').append(" Forge");
}
stringbuilder.append(" ");
@@ -725,6 +_,8 @@
}
private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) {
+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam.
+ return UserApiService.OFFLINE;
return p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
}
@@ -733,7 +_,7 @@
}
private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
- if (this.resourcePackRepository.getSelectedIds().size() > 1) {
+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any.
this.clearResourcePacksOnError(p_91240_, (Component)null, p_299515_);
} else {
Util.throwAsRuntime(p_91240_);
@@ -819,7 +_,10 @@
}
public void createSearchTrees() {
- this.searchRegistry.register(SearchRegistry.CREATIVE_NAMES, (p_231451_) -> {
+ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys();
+ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys();
+ for (var nameSearchKey : nameSearchKeys.values())
+ this.searchRegistry.register(nameSearchKey, (p_231451_) -> {
return new FullTextSearchTree<>((p_210797_) -> {
return p_210797_.getTooltipLines((Player)null, TooltipFlag.Default.NORMAL.asCreative()).stream().map((p_231455_) -> {
return ChatFormatting.stripFormatting(p_231455_.getString()).trim();
@@ -830,7 +_,8 @@
return Stream.of(BuiltInRegistries.ITEM.getKey(p_91317_.getItem()));
}, p_231451_);
});
- this.searchRegistry.register(SearchRegistry.CREATIVE_TAGS, (p_231430_) -> {
+ for (var tagSearchKey : tagSearchKeys.values())
+ this.searchRegistry.register(tagSearchKey, (p_231430_) -> {
return new IdSearchTree<>((p_231353_) -> {
return p_231353_.getTags().map(TagKey::location);
}, p_231430_);
@@ -850,9 +_,12 @@
});
}, p_301514_);
});
- CreativeModeTabs.searchTab().setSearchTreeBuilder((p_255439_) -> {
- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_);
- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_);
+ nameSearchKeys.forEach((tab, nameSearchKey) -> {
+ var tagSearchKey = tagSearchKeys.get(tab);
+ tab.setSearchTreeBuilder(contents -> {
+ this.populateSearchTree(nameSearchKey, contents);
+ this.populateSearchTree(tagSearchKey, contents);
+ });
});
}
@@ -1054,10 +_,6 @@
LOGGER.error("setScreen called from non-game thread");
}
- if (this.screen != null) {
- this.screen.removed();
- }
-
if (p_91153_ == null && this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
} else {
@@ -1071,6 +_,19 @@
}
}
}, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", this.user.getName());
- LOGGER.debug("(Session ID is {})", this.user.getSessionId());
this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat;
@@ -475,15 +_,15 @@
}
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.screen;
+ if (p_91153_ != null) {
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return;
+ p_91153_ = event;
+ }
+
+ if (old != null && p_91153_ != old) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.removed();
+ }
+
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1218,9 +_,12 @@
RenderSystem.enableCull();
this.profiler.pop();
if (!this.noRender) {
+ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick);
this.profiler.popPush("gameRenderer");
this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_);
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick);
}
this.window.setFramerateLimit(this.options.framerateLimit().get());
+ // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window.getWindow());
this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window.getWindow());
RenderSystem.initRenderer(this.options.glDebugVerbosity, false);
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F);
this.mainRenderTarget.clear(ON_OSX);
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
+ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager);
this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode);
@@ -542,6 +_,7 @@
this.entityRenderDispatcher = new EntityRenderDispatcher(this, this.textureManager, this.itemRenderer, this.blockRenderer, this.font, this.options, this.entityModels);
this.resourceManager.registerReloadListener(this.entityRenderDispatcher);
this.particleEngine = new ParticleEngine(this.level, this.textureManager);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine);
this.resourceManager.registerReloadListener(this.particleEngine);
this.paintingTextures = new PaintingTextureManager(this.textureManager);
this.resourceManager.registerReloadListener(this.paintingTextures);
@@ -554,13 +_,18 @@
this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers);
this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener());
this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers);
+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent());
this.resourceManager.registerReloadListener(this.levelRenderer);
- this.createSearchTrees();
+ // Forge: We delay this to allow registration of modded creative mode tabs
+ //this.createSearchTrees();
this.resourceManager.registerReloadListener(this.searchRegistry);
this.gpuWarnlistManager = new GpuWarnlistManager();
this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies);
this.gui = new Gui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
RealmsClient realmsclient = RealmsClient.create(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
@@ -584,6 +_,7 @@
this.options.fullscreen().set(this.window.isFullscreen());
}
if (this.fpsPieResults != null) {
@@ -1254,7 +_,8 @@
this.window.setErrorSection("Post render");
++this.frames;
boolean flag1 = this.hasSingleplayerServer() && (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen()) && !this.singleplayerServer.isPublished();
- if (this.pause != flag1) {
+ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) {
+
if (flag1) {
this.pausePartialTick = this.timer.partialTick;
} else {
@@ -1262,6 +_,7 @@
}
this.pause = flag1;
+ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1);
}
long l = Util.getNanos();
@@ -1341,10 +_,12 @@
this.window.setGuiScale((double)i);
if (this.screen != null) {
this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
}
RenderTarget rendertarget = this.getMainRenderTarget();
rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX);
+ if (this.gameRenderer != null)
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove();
}
@@ -1618,6 +_,7 @@
}
public void stop() {
+ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown();
this.running = false;
}
@@ -1647,10 +_,18 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.particleEngine.crack(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1679,6 +_,8 @@
return false;
} else {
boolean flag = false;
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!inputEvent.isCanceled())
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1686,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1699,8 +_,10 @@
}
this.player.resetAttackStrengthTicker();
+ net.minecraftforge.common.ForgeHooks.onEmptyLeftClick(this.player);
}
+ if (inputEvent.shouldSwingHand())
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
}
@@ -1716,6 +_,11 @@
}
for(InteractionHand interactionhand : InteractionHand.values()) {
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(1, this.options.keyUse, interactionhand);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand);
+ return;
+ }
ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return;
@@ -1736,7 +_,7 @@
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setDefaultErrorCallback();
@@ -604,16 +_,17 @@
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
this.setOverlay(
- new LoadingOverlay(
- this, reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay(
+ () -> this, () -> reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
if (SharedConstants.IS_RUNNING_IN_IDE) {
this.selfTest();
}
if (interactionresult.consumesAction()) {
- if (interactionresult.shouldSwing()) {
+ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
}
this.reloadStateTracker.finishReload();
this.onResourceLoadFinished(minecraft$gameloadcookie);
+ net.minecraftforge.client.loading.ClientModLoader.completeModLoading();
}), false
- )
+ ).get()
);
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path());
}
@@ -702,6 +_,7 @@
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) {
stringbuilder.append("*");
+ stringbuilder.append(" Forge");
}
@@ -1748,7 +_,7 @@
int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1.consumesAction()) {
- if (interactionresult1.shouldSwing()) {
+ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1764,6 +_,9 @@
}
}
stringbuilder.append(" ");
@@ -725,6 +_,8 @@
}
+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS))
+ net.minecraftforge.common.ForgeHooks.onEmptyClick(this.player, interactionhand);
+
if (!itemstack.isEmpty()) {
InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand);
if (interactionresult2.consumesAction()) {
@@ -1795,6 +_,8 @@
--this.rightClickDelay;
}
private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) {
+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam.
+ return UserApiService.OFFLINE;
return p_193587_.user.user.getType() != User.Type.MSA
? UserApiService.OFFLINE
: p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
@@ -735,7 +_,7 @@
}
+ net.minecraftforge.event.ForgeEventFactory.onPreClientTick();
+
this.profiler.push("gui");
this.chatListener.tick();
this.gui.tick(this.pause);
@@ -1887,6 +_,7 @@
private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
- if (this.resourcePackRepository.getSelectedIds().size() > 1) {
+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any.
this.clearResourcePacksOnError(p_91240_, null, p_299515_);
} else {
Util.throwAsRuntime(p_91240_);
@@ -817,9 +_,12 @@
}
this.tutorial.tick();
public void createSearchTrees() {
+ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys();
+ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys();
+ for (var nameSearchKey : nameSearchKeys.values())
this.searchRegistry
.register(
- SearchRegistry.CREATIVE_NAMES,
+ nameSearchKey,
p_231451_ -> new FullTextSearchTree<>(
p_325272_ -> p_325272_.getTooltipLines(Item.TooltipContext.EMPTY, null, TooltipFlag.Default.NORMAL.asCreative())
.stream()
@@ -829,8 +_,9 @@
p_231451_
)
);
+ for (var tagSearchKey : tagSearchKeys.values())
this.searchRegistry
- .register(SearchRegistry.CREATIVE_TAGS, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_));
+ .register(tagSearchKey, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_));
this.searchRegistry
.register(
SearchRegistry.RECIPE_COLLECTIONS,
@@ -854,9 +_,12 @@
p_301514_
)
);
- CreativeModeTabs.searchTab().setSearchTreeBuilder(p_255439_ -> {
- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_);
- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_);
+ nameSearchKeys.forEach((tab, nameSearchKey) -> {
+ var tagSearchKey = tagSearchKeys.get(tab);
+ tab.setSearchTreeBuilder(contents -> {
+ this.populateSearchTree(nameSearchKey, contents);
+ this.populateSearchTree(tagSearchKey, contents);
+ });
});
}
+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true);
try {
this.level.tick(() -> {
return true;
@@ -1902,6 +_,7 @@
@@ -1039,12 +_,6 @@
LOGGER.error("setScreen called from non-game thread");
}
throw new ReportedException(crashreport);
}
+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true);
}
this.profiler.popPush("animateTick");
@@ -1921,6 +_,8 @@
this.profiler.popPush("keyboard");
this.keyboardHandler.tick();
this.profiler.pop();
+
+ net.minecraftforge.event.ForgeEventFactory.onPostClientTick();
}
private boolean isMultiplayerServer() {
@@ -2112,6 +_,7 @@
}
public void setLevel(ClientLevel p_91157_) {
+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
ProgressScreen progressscreen = new ProgressScreen(true);
progressscreen.progressStartNoAbort(Component.translatable("connect.joining"));
this.updateScreenAndTick(progressscreen);
@@ -2146,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null;
this.gameRenderer.resetData();
+ net.minecraftforge.client.ForgeHooksClient.firePlayerLogout(this.gameMode, this.player);
this.gameMode = null;
this.narrator.clear();
this.clientLevelTeardownInProgress = true;
@@ -2153,6 +_,7 @@
try {
this.updateScreenAndTick(p_91321_);
if (this.level != null) {
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
if (integratedserver != null) {
this.profiler.push("waitForServer");
@@ -2165,6 +_,7 @@
this.gui.onDisconnected();
this.isLocalServer = false;
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
}
this.level = null;
@@ -2313,6 +_,7 @@
private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.ForgeHooksClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return;
boolean flag = this.player.getAbilities().instabuild;
BlockEntity blockentity = null;
HitResult.Type hitresult$type = this.hitResult.getType();
@@ -2325,10 +_,7 @@
- if (this.screen != null) {
- this.screen.removed();
- } else {
- this.setLastInputType(InputType.NONE);
- }
-
if (p_91153_ == null && this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
} else {
@@ -1058,6 +_,23 @@
}
}
Block block = blockstate.getBlock();
- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate);
- if (itemstack.isEmpty()) {
- return;
- }
+ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player);
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.screen;
+ if (p_91153_ != null) {
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return;
+ p_91153_ = event;
+ }
+
+ if (p_91153_ != old) {
+ if (old != null) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.removed();
+ } else {
+ this.setLastInputType(InputType.NONE);
+ }
+ }
+
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1204,9 +_,12 @@
this.mouseHandler.handleAccumulatedMovement();
this.profiler.pop();
if (!this.noRender) {
+ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick);
this.profiler.popPush("gameRenderer");
this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_);
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick);
}
if (flag && Screen.hasControlDown() && blockstate.hasBlockEntity()) {
blockentity = this.level.getBlockEntity(blockpos);
@@ -2339,7 +_,7 @@
if (this.fpsPieResults != null) {
@@ -1240,7 +_,7 @@
boolean flag1 = this.hasSingleplayerServer()
&& (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen())
&& !this.singleplayerServer.isPublished();
- if (this.pause != flag1) {
+ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) {
if (flag1) {
this.pausePartialTick = this.timer.partialTick;
} else {
@@ -1248,6 +_,7 @@
}
Entity entity = ((EntityHitResult)this.hitResult).getEntity();
- itemstack = entity.getPickResult();
+ itemstack = entity.getPickedResult(this.hitResult);
if (itemstack == null) {
return;
this.pause = flag1;
+ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1);
}
long l = Util.getNanos();
@@ -1340,10 +_,12 @@
this.window.setGuiScale((double)i);
if (this.screen != null) {
this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
}
RenderTarget rendertarget = this.getMainRenderTarget();
rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX);
+ if (this.gameRenderer != null)
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove();
}
@@ -1619,6 +_,7 @@
}
public void stop() {
+ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown();
this.running = false;
}
@@ -1647,10 +_,18 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.particleEngine.crack(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1678,6 +_,8 @@
return false;
} else {
boolean flag = false;
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!inputEvent.isCanceled())
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1685,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1698,8 +_,10 @@
}
this.player.resetAttackStrengthTicker();
+ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player);
}
+ if (inputEvent.shouldSwingHand())
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
}
@@ -2904,6 +_,19 @@
@@ -1715,6 +_,12 @@
}
public void updateMaxMipLevel(int p_91313_) {
this.modelManager.updateMaxMipLevel(p_91313_);
+ }
for (InteractionHand interactionhand : InteractionHand.values()) {
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(1, this.options.keyUse, interactionhand);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand);
+ return;
+ }
+
+ public ItemColors getItemColors() {
+ return this.itemColors;
+ }
+
+ public SearchRegistry getSearchTreeManager() {
+ return this.searchRegistry;
+ }
+
+ private float realPartialTick;
+ public float getPartialTick() {
+ return this.realPartialTick;
}
ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return;
@@ -1735,7 +_,7 @@
}
public EntityModelSet getEntityModels() {
if (interactionresult.consumesAction()) {
- if (interactionresult.shouldSwing()) {
+ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
}
@@ -1747,7 +_,7 @@
int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1.consumesAction()) {
- if (interactionresult1.shouldSwing()) {
+ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1763,6 +_,9 @@
}
}
+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS))
+ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, interactionhand);
+
if (!itemstack.isEmpty()) {
InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand);
if (interactionresult2.consumesAction()) {
@@ -1793,6 +_,8 @@
this.rightClickDelay--;
}
+ net.minecraftforge.event.ForgeEventFactory.onPreClientTick();
+
this.profiler.push("gui");
this.chatListener.tick();
this.gui.tick(this.pause);
@@ -1877,6 +_,7 @@
this.tutorial.tick();
+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true);
try {
this.level.tick(() -> true);
} catch (Throwable throwable) {
@@ -1890,6 +_,7 @@
throw new ReportedException(crashreport);
}
+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true);
}
this.profiler.popPush("animateTick");
@@ -1909,6 +_,7 @@
this.profiler.popPush("keyboard");
this.keyboardHandler.tick();
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onPostClientTick();
}
private boolean isMultiplayerServer() {
@@ -2105,6 +_,7 @@
}
public void setLevel(ClientLevel p_91157_, ReceivingLevelScreen.Reason p_335893_) {
+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
this.updateScreenAndTick(new ReceivingLevelScreen(() -> false, p_335893_));
this.level = p_91157_;
this.updateLevelInEngines(p_91157_);
@@ -2142,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null;
this.gameRenderer.resetData();
+ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogout(this.gameMode, this.player);
this.gameMode = null;
this.narrator.clear();
this.clientLevelTeardownInProgress = true;
@@ -2149,6 +_,7 @@
try {
this.updateScreenAndTick(p_335030_);
if (this.level != null) {
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
if (integratedserver != null) {
this.profiler.push("waitForServer");
@@ -2161,6 +_,7 @@
this.gui.onDisconnected();
this.isLocalServer = false;
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
}
this.level = null;
@@ -2307,6 +_,7 @@
private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return;
boolean flag = this.player.getAbilities().instabuild;
BlockEntity blockentity = null;
HitResult.Type hitresult$type = this.hitResult.getType();
@@ -2319,7 +_,7 @@
}
Block block = blockstate.getBlock();
- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate);
+ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player);
if (itemstack.isEmpty()) {
return;
}
@@ -2333,7 +_,7 @@
}
Entity entity = ((EntityHitResult)this.hitResult).getEntity();
- itemstack = entity.getPickResult();
+ itemstack = entity.getPickedResult(this.hitResult);
if (itemstack == null) {
return;
}
@@ -2931,6 +_,19 @@
@Nullable
public static String getLauncherBrand() {
return System.getProperty("minecraft.launcher.brand");
+ }
+
+ public ItemColors getItemColors() {
+ return this.itemColors;
+ }
+
+ public SearchRegistry getSearchTreeManager() {
+ return this.searchRegistry;
+ }
+
+ private float realPartialTick;
+ public float getPartialTick() {
+ return this.realPartialTick;
}
@OnlyIn(Dist.CLIENT)
@@ -1,86 +1,73 @@
--- a/net/minecraft/client/MouseHandler.java
+++ b/net/minecraft/client/MouseHandler.java
@@ -74,6 +_,7 @@
this.activeButton = -1;
}
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
boolean[] aboolean = new boolean[]{false};
if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) {
@@ -87,11 +_,19 @@
if (flag) {
screen.afterMouseAction();
Screen.wrapScreenError(() -> {
- aboolean[0] = screen.mouseClicked(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.minecraft.screen.mouseClicked(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseClicked event handler", screen.getClass().getCanonicalName());
} else {
Screen.wrapScreenError(() -> {
- aboolean[0] = screen.mouseReleased(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.minecraft.screen.mouseReleased(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseReleased event handler", screen.getClass().getCanonicalName());
}
}
@@ -116,6 +_,7 @@
}
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
}
@@ -129,8 +_,10 @@
if (this.minecraft.screen != null) {
double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2);
this.minecraft.screen.afterMouseAction();
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return;
+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2);
} else if (this.minecraft.player != null) {
if (this.accumulatedScrollX != 0.0D && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) {
this.accumulatedScrollX = 0.0D;
@@ -151,6 +_,7 @@
this.accumulatedScrollX -= (double)j;
this.accumulatedScrollY -= (double)i;
int k = i == 0 ? -j : i;
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return;
if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k);
@@ -219,7 +_,9 @@
double d2 = (p_91563_ - this.xpos) * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d3 = (p_91564_ - this.ypos) * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
Screen.wrapScreenError(() -> {
- screen.mouseDragged(d0, d1, this.activeButton, d2, d3);
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPre(screen, d0, d1, this.activeButton, d2, d3)) return;
+ if (screen.mouseDragged(d0, d1, this.activeButton, d2, d3)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPost(screen, d0, d1, this.activeButton, d2, d3);
}, "mouseDragged event handler", screen.getClass().getCanonicalName());
this.activeButton = -1;
}
@@ -302,6 +_,14 @@
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
boolean[] aboolean = new boolean[]{false};
if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) {
@@ -86,9 +_,9 @@
Screen screen = this.minecraft.screen;
if (flag) {
screen.afterMouseAction();
- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseClicked(d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(aboolean, screen, d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName());
} else {
- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseReleased(d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(aboolean, screen, d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName());
}
}
}
@@ -111,6 +_,7 @@
}
}
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
}
public double ypos() {
return this.ypos;
+ }
@@ -124,7 +_,9 @@
if (this.minecraft.screen != null) {
double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2);
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return;
+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2);
this.minecraft.screen.afterMouseAction();
} else if (this.minecraft.player != null) {
if (this.accumulatedScrollX != 0.0 && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) {
@@ -146,6 +_,7 @@
this.accumulatedScrollX -= (double)j;
this.accumulatedScrollY -= (double)i;
int k = i == 0 ? -j : i;
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return;
if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k);
@@ -216,7 +_,7 @@
if (this.activeButton != -1 && this.mousePressedTime > 0.0) {
double d4 = this.accumulatedDX * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d5 = this.accumulatedDY * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- Screen.wrapScreenError(() -> screen.mouseDragged(d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName());
}
screen.afterMouseMove();
@@ -283,6 +_,14 @@
public double ypos() {
return this.ypos;
+ }
+
+ public double getXVelocity() {
+ return this.accumulatedDX;
+ }
+ public double getXVelocity() {
+ return this.accumulatedDX;
+ }
+
+ public double getYVelocity() {
+ return this.accumulatedDY;
}
+ public double getYVelocity() {
+ return this.accumulatedDY;
}
public void setIgnoreFirstMove() {
public void setIgnoreFirstMove() {
@@ -1,95 +1,97 @@
--- a/net/minecraft/client/Options.java
+++ b/net/minecraft/client/Options.java
@@ -509,7 +_,8 @@
}, new OptionInstance.LazyEnum<>(() -> {
return Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList();
}, (p_232011_) -> {
- return Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_);
+ // FORGE: fix incorrect string comparison - PR #8767
+ return Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_);
}, Codec.STRING), "", (p_299350_) -> {
SoundManager soundmanager = Minecraft.getInstance().getSoundManager();
soundmanager.reload();
@@ -841,6 +_,7 @@
}
@@ -680,7 +_,8 @@
},
new OptionInstance.LazyEnum<>(
() -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(),
- p_232011_ -> Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_)
+ // FORGE: fix incorrect string comparison - PR #8767
+ p_232011_ -> Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_)
? Optional.empty()
: Optional.of(p_232011_),
Codec.STRING
@@ -1044,6 +_,7 @@
}
public Options(Minecraft p_92138_, File p_92139_) {
+ setForgeKeybindProperties();
this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = p_92138_.is64Bit();
@@ -964,11 +_,20 @@
p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra);
this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility);
public Options(Minecraft p_92138_, File p_92139_) {
+ setForgeKeybindProperties();
this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L;
@@ -1178,12 +_,22 @@
p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra);
this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility);
p_168428_.process("menuBackgroundBlurriness", this.menuBackgroundBlurriness);
+ processOptionsForge(p_168428_);
+ }
+ processOptionsForge(p_168428_);
+ }
+ // FORGE: split off to allow reloading options after mod loading is done
+ private void processOptionsForge(Options.FieldAccess p_168428_)
+ {
for(KeyMapping keymapping : this.keyMappings) {
- String s = keymapping.saveString();
+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : "");
String s1 = p_168428_.process("key_" + keymapping.getName(), s);
if (!s.equals(s1)) {
- keymapping.setKey(InputConstants.getKey(s1));
+ if (s1.indexOf(':') != -1) {
+ String[] pts = s1.split(":");
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0]));
+ } else
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1));
}
}
@@ -987,6 +_,9 @@
}
public void load() {
+ this.load(false);
+ }
+ public void load(boolean limited) {
try {
if (!this.optionsFile.exists()) {
return;
@@ -1015,7 +_,8 @@
+ // FORGE: split off to allow reloading options after mod loading is done
+ private void processOptionsForge(Options.FieldAccess p_168428_) {
for (KeyMapping keymapping : this.keyMappings) {
- String s = keymapping.saveString();
+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : "");
String s1 = p_168428_.process("key_" + keymapping.getName(), s);
if (!s.equals(s1)) {
keymapping.setKey(InputConstants.getKey(s1));
+ if (s1.indexOf(':') != -1) {
+ String[] pts = s1.split(":");
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0]));
+ } else {
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1));
+ }
}
}
}
- this.processOptions(new Options.FieldAccess() {
+ java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsForge : this::processOptions;
+ processor.accept(new Options.FieldAccess() {
@Nullable
private String getValueOrNull(String p_168459_) {
return compoundtag1.contains(p_168459_) ? compoundtag1.getString(p_168459_) : null;
@@ -1188,6 +_,7 @@
}
@@ -1201,6 +_,10 @@
}
public void broadcastOptions() {
+ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted.
if (this.minecraft.player != null) {
this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation()));
}
@@ -1246,6 +_,23 @@
}
p_92146_.setSelected(set);
+ }
public void load() {
+ load(false);
+ }
+
+ private void setForgeKeybindProperties() {
+ net.minecraftforge.client.settings.KeyConflictContext inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME;
+ keyUp.setKeyConflictContext(inGame);
+ keyLeft.setKeyConflictContext(inGame);
+ keyDown.setKeyConflictContext(inGame);
+ keyRight.setKeyConflictContext(inGame);
+ keyJump.setKeyConflictContext(inGame);
+ keyShift.setKeyConflictContext(inGame);
+ keySprint.setKeyConflictContext(inGame);
+ keyAttack.setKeyConflictContext(inGame);
+ keyChat.setKeyConflictContext(inGame);
+ keyPlayerList.setKeyConflictContext(inGame);
+ keyCommand.setKeyConflictContext(inGame);
+ keyTogglePerspective.setKeyConflictContext(inGame);
+ keySmoothCamera.setKeyConflictContext(inGame);
}
+ public void load(boolean limited) {
try {
if (!this.optionsFile.exists()) {
return;
@@ -1228,7 +_,8 @@
}
}
public CameraType getCameraType() {
- this.processOptions(
+ java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsForge : this::processOptions;
+ processor.accept(
new Options.FieldAccess() {
@Nullable
private String getValueOrNull(String p_168459_) {
@@ -1422,6 +_,7 @@
}
public void broadcastOptions() {
+ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted.
if (this.minecraft.player != null) {
this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation()));
}
@@ -1544,6 +_,23 @@
public static Component genericValueLabel(Component p_231901_, int p_231902_) {
return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_)));
+ }
+
+ private void setForgeKeybindProperties() {
+ var inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME;
+ keyUp.setKeyConflictContext(inGame);
+ keyLeft.setKeyConflictContext(inGame);
+ keyDown.setKeyConflictContext(inGame);
+ keyRight.setKeyConflictContext(inGame);
+ keyJump.setKeyConflictContext(inGame);
+ keyShift.setKeyConflictContext(inGame);
+ keySprint.setKeyConflictContext(inGame);
+ keyAttack.setKeyConflictContext(inGame);
+ keyChat.setKeyConflictContext(inGame);
+ keyPlayerList.setKeyConflictContext(inGame);
+ keyCommand.setKeyConflictContext(inGame);
+ keyTogglePerspective.setKeyConflictContext(inGame);
+ keySmoothCamera.setKeyConflictContext(inGame);
}
@OnlyIn(Dist.CLIENT)
@@ -6,34 +6,40 @@
@OnlyIn(Dist.CLIENT)
-public enum RecipeBookCategories {
+public enum RecipeBookCategories implements net.minecraftforge.common.IExtensibleEnum {
CRAFTING_SEARCH(new ItemStack(Items.COMPASS)),
CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)),
CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)),
@@ -36,7 +_,7 @@
public static final List<RecipeBookCategories> BLAST_FURNACE_CATEGORIES = ImmutableList.of(BLAST_FURNACE_SEARCH, BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC);
public static final List<RecipeBookCategories> FURNACE_CATEGORIES = ImmutableList.of(FURNACE_SEARCH, FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC);
public static final List<RecipeBookCategories> CRAFTING_CATEGORIES = ImmutableList.of(CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE);
- public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = ImmutableMap.of(CRAFTING_SEARCH, ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE), FURNACE_SEARCH, ImmutableList.of(FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC), BLAST_FURNACE_SEARCH, ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC), SMOKER_SEARCH, ImmutableList.of(SMOKER_FOOD));
+ public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories();
private final List<ItemStack> itemIcons;
CRAFTING_SEARCH(new ItemStack(Items.COMPASS)),
CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)),
CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)),
@@ -38,7 +_,7 @@
public static final List<RecipeBookCategories> CRAFTING_CATEGORIES = ImmutableList.of(
CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE
);
- public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = ImmutableMap.of(
+ public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories(ImmutableMap.of(
CRAFTING_SEARCH,
ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE),
FURNACE_SEARCH,
@@ -47,7 +_,7 @@
ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC),
SMOKER_SEARCH,
ImmutableList.of(SMOKER_FOOD)
- );
+ ));
private final List<ItemStack> itemIcons;
private RecipeBookCategories(ItemStack... p_92267_) {
@@ -59,7 +_,7 @@
list = SMOKER_CATEGORIES;
break;
default:
- throw new IncompatibleClassChangeError();
+ return net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_);
}
private RecipeBookCategories(final ItemStack... p_92267_) {
@@ -60,10 +_,15 @@
case FURNACE -> FURNACE_CATEGORIES;
case BLAST_FURNACE -> BLAST_FURNACE_CATEGORIES;
case SMOKER -> SMOKER_CATEGORIES;
+ default -> net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_);
};
}
return list;
@@ -67,5 +_,9 @@
public List<ItemStack> getIconItems() {
return this.itemIcons;
+ }
public List<ItemStack> getIconItems() {
return this.itemIcons;
+ }
+
+ public static RecipeBookCategories create(String name, ItemStack... icons) {
+ throw new IllegalStateException("Enum not extended");
}
+ public static RecipeBookCategories create(String name, ItemStack... icons) {
+ throw new IllegalStateException("Enum not extended");
}
}
@@ -1,29 +1,30 @@
--- a/net/minecraft/client/Screenshot.java
+++ b/net/minecraft/client/Screenshot.java
@@ -56,13 +_,23 @@
file2 = new File(file1, p_92307_);
}
@@ -54,14 +_,24 @@
file2 = new File(file1, p_92307_);
}
+ net.minecraftforge.client.event.ScreenshotEvent event = net.minecraftforge.client.ForgeHooksClient.onScreenshot(nativeimage, file2);
+ if (event.isCanceled()) {
+ p_92311_.accept(event.getCancelMessage());
+ return;
+ }
+ final File target = event.getScreenshotFile();
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenshot(nativeimage, file2);
+ if (event.isCanceled()) {
+ p_92311_.accept(event.getCancelMessage());
+ return;
+ }
+ final File target = event.getScreenshotFile();
+
Util.ioPool().execute(() -> {
try {
- nativeimage.writeToFile(file2);
+ nativeimage.writeToFile(target);
Component component = Component.literal(file2.getName()).withStyle(ChatFormatting.UNDERLINE).withStyle((p_168608_) -> {
- return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath()));
+ return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath()));
});
- p_92311_.accept(Component.translatable("screenshot.success", component));
+ if (event.getResultMessage() != null)
+ p_92311_.accept(event.getResultMessage());
+ else
+ p_92311_.accept(Component.translatable("screenshot.success", component));
} catch (Exception exception) {
LOGGER.warn("Couldn't save screenshot", (Throwable)exception);
p_92311_.accept(Component.translatable("screenshot.failure", exception.getMessage()));
Util.ioPool()
.execute(
() -> {
try {
- nativeimage.writeToFile(file2);
- Component component = Component.literal(file2.getName())
+ nativeimage.writeToFile(target);
+ Component component = Component.literal(target.getName())
.withStyle(ChatFormatting.UNDERLINE)
- .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath())));
+ .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath())));
+ if (event.getResultMessage() != null)
+ p_92311_.accept(event.getResultMessage());
+ else
p_92311_.accept(Component.translatable("screenshot.success", component));
} catch (Exception exception) {
LOGGER.warn("Couldn't save screenshot", (Throwable)exception);
@@ -1,19 +1,21 @@
--- a/net/minecraft/client/ToggleKeyMapping.java
+++ b/net/minecraft/client/ToggleKeyMapping.java
@@ -16,7 +_,7 @@
@@ -17,7 +_,7 @@
@Override
public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) {
- if (p_92534_) {
+ if (p_92534_ && isConflictContextAndModifierActive()) {
super.setDown(!this.isDown());
}
} else {
@@ -27,5 +_,9 @@
public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) {
- if (p_92534_) {
+ if (p_92534_ && isConflictContextAndModifierActive()) {
super.setDown(!this.isDown());
}
} else {
@@ -24,6 +_,7 @@
}
}
+ @Override public boolean isDown() { return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean()); }
protected void reset() {
super.setDown(false);
protected void reset() {
super.setDown(false);
+ }
+
+ @Override public boolean isDown() {
+ return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean());
}
}
@@ -1,44 +1,44 @@
--- a/net/minecraft/client/color/block/BlockColors.java
+++ b/net/minecraft/client/color/block/BlockColors.java
@@ -28,7 +_,8 @@
@@ -29,7 +_,8 @@
@OnlyIn(Dist.CLIENT)
public class BlockColors {
private static final int DEFAULT = -1;
- private final IdMapper<BlockColor> blockColors = new IdMapper<>(32);
+ // FORGE: Use registry delegate as non-Vanilla block ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Block>, BlockColor> blockColors = new java.util.HashMap<>();
private final Map<Block, Set<Property<?>>> coloringStates = Maps.newHashMap();
private static final int DEFAULT = -1;
- private final IdMapper<BlockColor> blockColors = new IdMapper<>(32);
+ // Forge: Use registry delegate as non-Vanilla block ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Block>, BlockColor> blockColors = new java.util.HashMap<>(32);
private final Map<Block, Set<Property<?>>> coloringStates = Maps.newHashMap();
public static BlockColors createDefault() {
@@ -80,11 +_,12 @@
blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> {
return p_92597_ != null && p_92598_ != null ? 2129968 : 7455580;
}, Blocks.LILY_PAD);
+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors);
return blockcolors;
}
public static BlockColors createDefault() {
@@ -91,11 +_,12 @@
}, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockcolors.addColoringState(StemBlock.AGE, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> p_92597_ != null && p_92598_ != null ? -14647248 : -9321636, Blocks.LILY_PAD);
+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors);
return blockcolors;
}
public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock()));
if (blockcolor != null) {
return blockcolor.getColor(p_92583_, (BlockAndTintGetter)null, (BlockPos)null, 0);
} else {
@@ -94,13 +_,15 @@
}
public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock()));
if (blockcolor != null) {
return blockcolor.getColor(p_92583_, null, null, 0);
} else {
@@ -105,13 +_,15 @@
}
public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock()));
return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_);
}
public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock()));
return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_);
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */
+ @Deprecated
public void register(BlockColor p_92590_, Block... p_92591_) {
for(Block block : p_92591_) {
- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block));
+ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_);
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */
+ @Deprecated
public void register(BlockColor p_92590_, Block... p_92591_) {
for (Block block : p_92591_) {
- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block));
+ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_);
}
}
}
@@ -1,35 +1,35 @@
--- a/net/minecraft/client/color/item/ItemColors.java
+++ b/net/minecraft/client/color/item/ItemColors.java
@@ -25,7 +_,8 @@
@@ -26,7 +_,8 @@
@OnlyIn(Dist.CLIENT)
public class ItemColors {
private static final int DEFAULT = -1;
- private final IdMapper<ItemColor> itemColors = new IdMapper<>(32);
+ // FORGE: Use registry delegate as non-Vanilla item ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Item>, ItemColor> itemColors = new java.util.HashMap<>();
private static final int DEFAULT = -1;
- private final IdMapper<ItemColor> itemColors = new IdMapper<>(32);
+ // Forge: Use registry delegate as non-Vanilla item ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Item>, ItemColor> itemColors = new java.util.HashMap<>(32);
public static ItemColors createDefault(BlockColors p_92684_) {
ItemColors itemcolors = new ItemColors();
@@ -88,17 +_,20 @@
itemcolors.register((p_232352_, p_232353_) -> {
return p_232353_ == 0 ? -1 : MapItem.getColor(p_232352_);
}, Items.FILLED_MAP);
+ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_);
return itemcolors;
}
public static ItemColors createDefault(BlockColors p_92684_) {
ItemColors itemcolors = new ItemColors();
@@ -105,17 +_,20 @@
: FastColor.ARGB32.opaque(p_325310_.getOrDefault(DataComponents.MAP_COLOR, MapItemColor.DEFAULT).rgb()),
Items.FILLED_MAP
);
+ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_);
return itemcolors;
}
public int getColor(ItemStack p_92677_, int p_92678_) {
- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem()));
+ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem()));
return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_);
}
public int getColor(ItemStack p_92677_, int p_92678_) {
- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem()));
+ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem()));
return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_);
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */
+ @Deprecated
public void register(ItemColor p_92690_, ItemLike... p_92691_) {
for(ItemLike itemlike : p_92691_) {
- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem()));
+ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_);
}
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */
+ @Deprecated
public void register(ItemColor p_92690_, ItemLike... p_92691_) {
for (ItemLike itemlike : p_92691_) {
- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem()));
+ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_);
}
}
}
@@ -6,15 +6,15 @@
@OnlyIn(Dist.CLIENT)
-public class Font {
+public class Font implements net.minecraftforge.client.extensions.IForgeFont {
private static final float EFFECT_DEPTH = 0.01F;
private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F);
public static final int ALPHA_CUTOFF = 8;
@@ -202,6 +_,8 @@
public StringSplitter getSplitter() {
return this.splitter;
}
private static final float EFFECT_DEPTH = 0.01F;
private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F);
public static final int ALPHA_CUTOFF = 8;
@@ -322,6 +_,8 @@
public StringSplitter getSplitter() {
return this.splitter;
}
+
+ @Override public Font self() { return this; }
+ @Override public Font self() { return this; }
@OnlyIn(Dist.CLIENT)
public static enum DisplayMode {
@OnlyIn(Dist.CLIENT)
public static enum DisplayMode {
@@ -1,77 +1,84 @@
--- a/net/minecraft/client/gui/Gui.java
+++ b/net/minecraft/client/gui/Gui.java
@@ -131,7 +_,7 @@
public float vignetteBrightness = 1.0F;
protected int toolHighlightTimer;
protected ItemStack lastToolHighlight = ItemStack.EMPTY;
- protected final DebugScreenOverlay debugOverlay;
+ protected DebugScreenOverlay debugOverlay;
protected final SubtitleOverlay subtitleOverlay;
protected final SpectatorGui spectatorGui;
protected final PlayerTabOverlay tabList;
@@ -454,6 +_,8 @@
public float vignetteBrightness = 1.0F;
private int toolHighlightTimer;
private ItemStack lastToolHighlight = ItemStack.EMPTY;
- private final DebugScreenOverlay debugOverlay;
+ protected DebugScreenOverlay debugOverlay;
private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList;
@@ -320,7 +_,7 @@
Window window = this.minecraft.getWindow();
int i = Mth.floor(this.minecraft.mouseHandler.xpos() * (double)window.getGuiScaledWidth() / (double)window.getScreenWidth());
int j = Mth.floor(this.minecraft.mouseHandler.ypos() * (double)window.getGuiScaledHeight() / (double)window.getScreenHeight());
- this.chat.render(p_329202_, this.tickCount, i, j, false);
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(p_329202_, this.chat, window, i, j, this.tickCount);
}
}
for(MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
MobEffect mobeffect = mobeffectinstance.getEffect();
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue;
if (mobeffectinstance.showIcon()) {
int i = this.screenWidth;
int j = 1;
@@ -482,6 +_,7 @@
}
}
@@ -444,6 +_,8 @@
+ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue;
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(mobeffect);
int i1 = j;
float f1 = f;
@@ -602,16 +_,21 @@
}
for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
Holder<MobEffect> holder = mobeffectinstance.getEffect();
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue;
if (mobeffectinstance.showIcon()) {
int i = p_282812_.guiWidth();
int j = 1;
@@ -473,6 +_,7 @@
}
}
public void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue;
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(holder);
int l1 = i;
int i1 = j;
@@ -635,6 +_,10 @@
}
private void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+
+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) {
this.minecraft.getProfiler().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
- MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color);
+ MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().getStyleModifier());
if (this.lastToolHighlight.hasCustomHoverName()) {
mutablecomponent.withStyle(ChatFormatting.ITALIC);
}
- int i = this.getFont().width(mutablecomponent);
+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent);
+ int i = this.getFont().width(highlightTip);
int j = (this.screenWidth - i) / 2;
- int k = this.screenHeight - 59;
+ int k = this.screenHeight - Math.max(yShift, 59);
if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14;
}
@@ -623,7 +_,13 @@
if (l > 0) {
p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0));
- p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24));
+ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME);
+ if (font == null) {
+ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24));
+ } else {
+ j = (this.screenWidth - font.width(highlightTip)) / 2;
+ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24));
+ }
}
}
@@ -1080,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelected();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
- } else if (!this.lastToolHighlight.isEmpty() && itemstack.is(this.lastToolHighlight.getItem()) && itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) {
+ } else if (!this.lastToolHighlight.isEmpty() && itemstack.getItem() == this.lastToolHighlight.getItem() && (itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) && itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName())))) {
if (this.toolHighlightTimer > 0) {
--this.toolHighlightTimer;
+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) {
this.minecraft.getProfiler().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color());
@@ -642,9 +_,10 @@
mutablecomponent.withStyle(ChatFormatting.ITALIC);
}
- int i = this.getFont().width(mutablecomponent);
+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent);
+ int i = this.getFont().width(highlightTip);
int j = (p_283501_.guiWidth() - i) / 2;
- int k = p_283501_.guiHeight() - 59;
+ int k = p_283501_.guiHeight() - Math.max(yShift, 59);
if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14;
}
@@ -657,6 +_,13 @@
if (l > 0) {
p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0));
p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24));
+ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME);
+ if (font == null) {
+ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24));
+ } else {
+ j = (p_283501_.guiWidth() - font.width(highlightTip)) / 2;
+ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24));
+ }
}
}
@@ -1155,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelected();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
- } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) {
+ } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) || !itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName()))) {
this.toolHighlightTimer = (int)(40.0 * this.minecraft.options.notificationDisplayTime().get());
} else if (this.toolHighlightTimer > 0) {
this.toolHighlightTimer--;
@@ -1,147 +1,138 @@
--- a/net/minecraft/client/gui/GuiGraphics.java
+++ b/net/minecraft/client/gui/GuiGraphics.java
@@ -55,7 +_,7 @@
@@ -56,7 +_,7 @@
import org.joml.Vector2ic;
@OnlyIn(Dist.CLIENT)
-public class GuiGraphics {
+public class GuiGraphics implements net.minecraftforge.client.extensions.IForgeGuiGraphics {
public static final float MAX_GUI_Z = 10000.0F;
public static final float MIN_GUI_Z = -10000.0F;
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
@@ -271,6 +_,11 @@
}
public static final float MAX_GUI_Z = 10000.0F;
public static final float MIN_GUI_Z = -10000.0F;
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
@@ -280,6 +_,11 @@
}
public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) {
+ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_);
+ }
public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) {
+ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_);
+ }
+
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) {
if (p_281896_ == null) {
return 0;
} else {
@@ -285,6 +_,11 @@
}
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) {
if (p_281896_ == null) {
return 0;
} else {
@@ -306,6 +_,11 @@
}
public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) {
+ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_);
+ }
public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) {
+ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_);
+ }
+
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) {
int i = p_282636_.drawInBatch(p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_, this.pose.last().pose(), this.bufferSource, Font.DisplayMode.NORMAL, 0, 15728880);
this.flushIfUnmanaged();
return i;
@@ -515,6 +_,7 @@
crashreportcategory.setDetail("Item Type", () -> {
return String.valueOf((Object)p_281675_.getItem());
});
+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem())));
crashreportcategory.setDetail("Item Damage", () -> {
return String.valueOf(p_281675_.getDamageValue());
});
@@ -562,18 +_,26 @@
}
this.pose.popPose();
+ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_);
}
}
+
+ private ItemStack tooltipStack = ItemStack.EMPTY;
public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) {
+ this.tooltipStack = p_282781_;
this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderTooltip(Font font, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, ItemStack stack, int mouseX, int mouseY) {
+ this.tooltipStack = stack;
+ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_283128_, List<Component> p_282716_, Optional<TooltipComponent> p_281682_, int p_283678_, int p_281696_) {
- List<ClientTooltipComponent> list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Collectors.toList());
- p_281682_.ifPresent((p_282969_) -> {
- list.add(1, ClientTooltipComponent.create(p_282969_));
- });
+ List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_);
this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE);
}
@@ -582,7 +_,22 @@
}
public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_);
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_);
+ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE);
+ }
+
+ public void renderComponentTooltip(Font font, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderComponentTooltipFromElements(Font font, List<com.mojang.datafixers.util.Either<FormattedText, TooltipComponent>> elements, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponentsFromElements(stack, elements, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_282192_, List<? extends FormattedCharSequence> p_282297_, int p_281680_, int p_283325_) {
@@ -595,11 +_,13 @@
private void renderTooltipInternal(Font p_282675_, List<ClientTooltipComponent> p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) {
if (!p_282615_.isEmpty()) {
+ net.minecraftforge.client.event.RenderTooltipEvent.Pre preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_);
+ if (preEvent.isCanceled()) return;
int i = 0;
int j = p_282615_.size() == 1 ? -2 : 0;
for(ClientTooltipComponent clienttooltipcomponent : p_282615_) {
- int k = clienttooltipcomponent.getWidth(p_282675_);
+ int k = clienttooltipcomponent.getWidth(preEvent.getFont());
if (k > i) {
i = k;
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) {
int i = p_282636_.drawInBatch(
p_281596_,
(float)p_281586_,
@@ -872,6 +_,7 @@
CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item");
CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered");
crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_281675_.getItem()));
+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem())));
crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_281675_.getComponents()));
crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_281675_.hasFoil()));
throw new ReportedException(crashreport);
@@ -912,16 +_,26 @@
}
@@ -609,20 +_,21 @@
int i2 = i;
int j2 = j;
- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2);
+ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2);
int l = vector2ic.x();
int i1 = vector2ic.y();
this.pose.pushPose();
int j1 = 400;
this.drawManaged(() -> {
- TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400);
+ net.minecraftforge.client.event.RenderTooltipEvent.Color colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd());
});
this.pose.translate(0.0F, 0.0F, 400.0F);
int k1 = i1;
this.pose.popPose();
+ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_);
}
}
+
+ private ItemStack tooltipStack = ItemStack.EMPTY;
for(int l1 = 0; l1 < p_282615_.size(); ++l1) {
ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1);
- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource);
+ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource);
k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0);
}
public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) {
+ this.tooltipStack = p_282781_;
this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderTooltip(Font font, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, ItemStack stack, int mouseX, int mouseY) {
+ this.tooltipStack = stack;
+ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY);
+ this.tooltipStack = ItemStack.EMPTY;
}
@@ -630,7 +_,7 @@
public void renderTooltip(Font p_283128_, List<Component> p_282716_, Optional<TooltipComponent> p_281682_, int p_283678_, int p_281696_) {
- List<ClientTooltipComponent> list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList());
- p_281682_.ifPresent(p_325321_ -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(p_325321_)));
+ List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_);
this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE);
}
for(int k2 = 0; k2 < p_282615_.size(); ++k2) {
ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2);
- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this);
+ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this);
k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0);
}
@@ -930,7 +_,15 @@
}
public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_);
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_);
+ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE);
+ }
+
+ public void renderComponentTooltip(Font font, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_282192_, List<? extends FormattedCharSequence> p_282297_, int p_281680_, int p_283325_) {
@@ -949,11 +_,13 @@
private void renderTooltipInternal(Font p_282675_, List<ClientTooltipComponent> p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) {
if (!p_282615_.isEmpty()) {
+ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_);
+ if (preEvent.isCanceled()) return;
int i = 0;
int j = p_282615_.size() == 1 ? -2 : 0;
for (ClientTooltipComponent clienttooltipcomponent : p_282615_) {
- int k = clienttooltipcomponent.getWidth(p_282675_);
+ int k = clienttooltipcomponent.getWidth(preEvent.getFont());
if (k > i) {
i = k;
}
@@ -963,18 +_,21 @@
int i2 = i;
int j2 = j;
- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2);
+ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2);
int l = vector2ic.x();
int i1 = vector2ic.y();
this.pose.pushPose();
int j1 = 400;
- this.drawManaged(() -> TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400));
+ this.drawManaged(() -> {
+ var colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd());
+ });
this.pose.translate(0.0F, 0.0F, 400.0F);
int k1 = i1;
for (int l1 = 0; l1 < p_282615_.size(); l1++) {
ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1);
- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource);
+ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource);
k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0);
}
@@ -982,7 +_,7 @@
for (int k2 = 0; k2 < p_282615_.size(); k2++) {
ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2);
- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this);
+ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this);
k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0);
}
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/components/AbstractButton.java
+++ b/net/minecraft/client/gui/components/AbstractButton.java
@@ -29,7 +_,7 @@
RenderSystem.enableDepthTest();
p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
- int i = this.active ? 16777215 : 10526880;
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24);
}
@@ -32,7 +_,7 @@
RenderSystem.enableDepthTest();
p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
- int i = this.active ? 16777215 : 10526880;
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24);
}
@@ -1,22 +1,28 @@
--- a/net/minecraft/client/gui/components/AbstractWidget.java
+++ b/net/minecraft/client/gui/components/AbstractWidget.java
@@ -233,6 +_,19 @@
this.focused = p_93693_;
}
@@ -255,6 +_,25 @@
this.focused = p_93693_;
}
+ public static final int UNSET_FG_COLOR = -1;
+ protected int packedFGColor = UNSET_FG_COLOR;
+ public int getFGColor() {
+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor;
+ return this.active ? 16777215 : 10526880; // White : Light Grey
+ }
+ public void setFGColor(int color) {
+ this.packedFGColor = color;
+ }
+ public void clearFGColor() {
+ this.packedFGColor = UNSET_FG_COLOR;
+ }
+ // Forge start
+ public static final int UNSET_FG_COLOR = -1;
+
public NarratableEntry.NarrationPriority narrationPriority() {
if (this.isFocused()) {
return NarratableEntry.NarrationPriority.FOCUSED;
+ protected int packedFGColor = UNSET_FG_COLOR;
+
+ public int getFGColor() {
+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor;
+ return this.active ? 16777215 : 10526880; // White : Light Grey
+ }
+
+ public void setFGColor(int color) {
+ this.packedFGColor = color;
+ }
+
+ public void clearFGColor() {
+ this.packedFGColor = UNSET_FG_COLOR;
+ }
+ // Forge end
+
@Override
public NarratableEntry.NarrationPriority narrationPriority() {
if (this.isFocused()) {
@@ -1,20 +1,20 @@
--- a/net/minecraft/client/gui/components/BossHealthOverlay.java
+++ b/net/minecraft/client/gui/components/BossHealthOverlay.java
@@ -36,13 +_,16 @@
@@ -63,13 +_,16 @@
for(LerpingBossEvent lerpingbossevent : this.events.values()) {
int k = i / 2 - 91;
+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight);
+ if (!event.isCanceled()) {
this.drawBar(p_283175_, k, j, lerpingbossevent);
Component component = lerpingbossevent.getName();
int l = this.minecraft.font.width(component);
int i1 = i / 2 - l / 2;
int j1 = j - 9;
p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215);
- j += 10 + 9;
+ }
+ j += event.getIncrement();
if (j >= p_283175_.guiHeight() / 3) {
break;
}
for (LerpingBossEvent lerpingbossevent : this.events.values()) {
int k = i / 2 - 91;
+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight);
+ if (!event.isCanceled()) {
this.drawBar(p_283175_, k, j, lerpingbossevent);
Component component = lerpingbossevent.getName();
int l = this.minecraft.font.width(component);
int i1 = i / 2 - l / 2;
int j1 = j - 9;
p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215);
- j += 10 + 9;
+ }
+ j += event.getIncrement();
if (j >= p_283175_.guiHeight() / 3) {
break;
}
@@ -1,29 +1,31 @@
--- a/net/minecraft/client/gui/components/Button.java
+++ b/net/minecraft/client/gui/components/Button.java
@@ -30,6 +_,11 @@
this.createNarration = p_259552_;
}
@@ -31,6 +_,12 @@
this.createNarration = p_259552_;
}
+ protected Button(Builder builder) {
+ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration);
+ setTooltip(builder.tooltip); // Forge: Make use of the Builder tooltip
+ }
+ // Forge (GH-9238)
+ protected Button(Builder builder) {
+ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration);
+ this.setTooltip(builder.tooltip);
+ }
+
public void onPress() {
this.onPress.onPress(this);
}
@@ -93,9 +_,11 @@
}
@Override
public void onPress() {
this.onPress.onPress(this);
@@ -95,9 +_,12 @@
}
public Button build() {
- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration);
- button.setTooltip(this.tooltip);
- return button;
+ return build(Button::new);
+ }
public Button build() {
- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration);
- button.setTooltip(this.tooltip);
- return button;
+ return build(Button::new);
+ }
+
+ public Button build(java.util.function.Function<Builder, Button> builder) {
+ return builder.apply(this);
}
}
+ // Forge (GH-9238)
+ public Button build(java.util.function.Function<Builder, Button> builder) {
+ return builder.apply(this);
}
}
@@ -1,92 +1,99 @@
--- a/net/minecraft/client/gui/components/DebugScreenOverlay.java
+++ b/net/minecraft/client/gui/components/DebugScreenOverlay.java
@@ -95,9 +_,9 @@
@Nullable
private CompletableFuture<LevelChunk> serverChunk;
private boolean renderDebug;
- private boolean renderProfilerChart;
- private boolean renderFpsCharts;
- private boolean renderNetworkCharts;
+ protected boolean renderProfilerChart;
+ protected boolean renderFpsCharts;
+ protected boolean renderNetworkCharts;
private final SampleLogger frameTimeLogger = new SampleLogger();
private final SampleLogger tickTimeLogger = new SampleLogger();
private final SampleLogger pingLogger = new SampleLogger();
@@ -124,14 +_,18 @@
this.clientChunk = null;
}
@@ -101,9 +_,9 @@
@Nullable
private CompletableFuture<LevelChunk> serverChunk;
private boolean renderDebug;
- private boolean renderProfilerChart;
- private boolean renderFpsCharts;
- private boolean renderNetworkCharts;
+ protected boolean renderProfilerChart;
+ protected boolean renderFpsCharts;
+ protected boolean renderNetworkCharts;
private final LocalSampleLogger frameTimeLogger = new LocalSampleLogger(1);
private final LocalSampleLogger tickTimeLogger = new LocalSampleLogger(TpsDebugDimensions.values().length);
private final LocalSampleLogger pingLogger = new LocalSampleLogger(1);
@@ -129,14 +_,18 @@
this.clientChunk = null;
}
- public void render(GuiGraphics p_281427_) {
- this.minecraft.getProfiler().push("debug");
+ protected void update() {
Entity entity = this.minecraft.getCameraEntity();
this.block = entity.pick(20.0D, 0.0F, false);
this.liquid = entity.pick(20.0D, 0.0F, true);
- p_281427_.drawManaged(() -> {
- this.drawGameInformation(p_281427_);
- this.drawSystemInformation(p_281427_);
+ }
- public void render(GuiGraphics p_281427_) {
- this.minecraft.getProfiler().push("debug");
+ protected void update() {
Entity entity = this.minecraft.getCameraEntity();
this.block = entity.pick(20.0, 0.0F, false);
this.liquid = entity.pick(20.0, 0.0F, true);
- p_281427_.drawManaged(() -> {
+ }
+
+ protected void drawText(GuiGraphics p_281427_) {
+ this.drawGameInformation(p_281427_);
+ this.drawSystemInformation(p_281427_);
+ }
+ protected void drawText(GuiGraphics p_281427_) {
this.drawGameInformation(p_281427_);
this.drawSystemInformation(p_281427_);
+ }
+
+ protected void drawFPSCharts(GuiGraphics p_281427_) {
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
int j = i / 2;
@@ -141,7 +_,9 @@
this.tpsChart.drawChart(p_281427_, i - k, k);
+ protected void drawFPSCharts(GuiGraphics p_281427_) {
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
int j = i / 2;
@@ -146,7 +_,9 @@
this.tpsChart.drawChart(p_281427_, i - k, k);
}
}
}
+ }
+ }
+ protected void drawNetworkCharts(GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -152,17 +_,32 @@
int j1 = this.pingChart.getWidth(i1);
this.pingChart.drawChart(p_281427_, l - j1, j1);
}
+ }
+ protected void drawNetworkCharts(GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -157,12 +_,21 @@
int j1 = this.pingChart.getWidth(i1);
this.pingChart.drawChart(p_281427_, l - j1, j1);
}
+ }
+
+ public void render(GuiGraphics p_281427_) {
+ this.minecraft.getProfiler().push("debug");
+ this.update();
+ p_281427_.drawManaged(() -> {
+ this.drawText(p_281427_);
+ this.drawFPSCharts(p_281427_);
+ this.drawNetworkCharts(p_281427_);
+ public void render(GuiGraphics p_281427_) {
+ this.minecraft.getProfiler().push("debug");
+ this.update();
+ p_281427_.drawManaged(() -> {
+ this.drawText(p_281427_);
+ this.drawFPSCharts(p_281427_);
+ this.drawNetworkCharts(p_281427_);
});
this.minecraft.getProfiler().pop();
}
});
this.minecraft.getProfiler().pop();
}
- protected void drawGameInformation(GuiGraphics p_281525_) {
- List<String> list = this.getGameInformation();
+ protected List<String> getOverlayHelp() {
+ List<String> list = Lists.newArrayList();
list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add("Debug charts: [F3+1] Profiler " + (this.renderProfilerChart ? "visible" : "hidden") + "; [F3+2] " + (flag ? "FPS + TPS " : "FPS ") + (this.renderFpsCharts ? "visible" : "hidden") + "; [F3+3] " + (!this.minecraft.isLocalServer() ? "Bandwidth + Ping" : "Ping") + (this.renderNetworkCharts ? " visible" : " hidden"));
list.add("For help: press F3 + Q");
+ return list;
+ }
+
- protected void drawGameInformation(GuiGraphics p_281525_) {
- List<String> list = this.getGameInformation();
+ protected List<String> getOverlayHelp() {
+ List<String> list = Lists.newArrayList();
list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add(
@@ -176,11 +_,18 @@
+ (this.renderNetworkCharts ? " visible" : " hidden")
);
list.add("For help: press F3 + Q");
- this.renderLines(p_281525_, list, true);
+ return list;
+ }
+ protected void drawGameInformation(GuiGraphics p_281525_) {
+ List<String> list = this.getGameInformation();
+ list.addAll(this.getOverlayHelp());
this.renderLines(p_281525_, list, true);
}
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281525_, minecraft.getWindow(), minecraft.getFrameTime(), list, true);
+ this.renderLines(p_281525_, list, true);
}
@@ -451,6 +_,7 @@
list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf((Object)BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
protected void drawSystemInformation(GuiGraphics p_281261_) {
List<String> list = this.getSystemInformation();
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281261_, minecraft.getWindow(), minecraft.getFrameTime(), list, false);
this.renderLines(p_281261_, list, false);
}
return list;
@@ -529,6 +_,7 @@
list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
return list;
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/components/toasts/ToastComponent.java
+++ b/net/minecraft/client/gui/components/toasts/ToastComponent.java
@@ -101,6 +_,7 @@
}
@@ -97,6 +_,7 @@
}
public void addToast(Toast p_94923_) {
+ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return;
this.queued.add(p_94923_);
}
public void addToast(Toast p_94923_) {
+ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return;
this.queued.add(p_94923_);
}
@@ -1,11 +1,10 @@
--- a/net/minecraft/client/gui/screens/ChatScreen.java
+++ b/net/minecraft/client/gui/screens/ChatScreen.java
@@ -225,7 +_,7 @@
this.minecraft.player.connection.sendChat(p_242400_);
}
- return true;
+ return minecraft.screen == this; // FORGE: Prevent closing the screen if another screen has been opened.
}
}
@@ -89,6 +_,7 @@
return true;
} else if (p_95591_ == 257 || p_95591_ == 335) {
this.handleChatInput(this.input.getValue(), true);
+ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened.
this.minecraft.setScreen(null);
return true;
} else if (p_95591_ == 265) {
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/screens/ConnectScreen.java
+++ b/net/minecraft/client/gui/screens/ConnectScreen.java
@@ -85,6 +_,8 @@
}
@@ -102,6 +_,8 @@
}
if (optional.isEmpty()) {
+ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost());
+ net.minecraftforge.network.DualStackUtils.logInitialPreferences();
p_251955_.execute(() -> {
p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE));
});
if (optional.isEmpty()) {
+ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost());
+ net.minecraftforge.network.DualStackUtils.logInitialPreferences();
p_251955_.execute(
() -> p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE))
);
@@ -1,18 +1,18 @@
--- a/net/minecraft/client/gui/screens/LoadingOverlay.java
+++ b/net/minecraft/client/gui/screens/LoadingOverlay.java
@@ -132,6 +_,7 @@
}
@@ -131,6 +_,7 @@
}
if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
+ this.fadeOutStart = Util.getMillis(); // Moved up to guard against inf loops caused by callback
try {
this.reload.checkExceptions();
this.onFinish.accept(Optional.empty());
@@ -139,7 +_,6 @@
this.onFinish.accept(Optional.of(throwable));
}
if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
+ this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback
try {
this.reload.checkExceptions();
this.onFinish.accept(Optional.empty());
@@ -138,7 +_,6 @@
this.onFinish.accept(Optional.of(throwable));
}
- this.fadeOutStart = Util.getMillis();
if (this.minecraft.screen != null) {
this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight());
}
- this.fadeOutStart = Util.getMillis();
if (this.minecraft.screen != null) {
this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight());
}
@@ -1,25 +1,20 @@
--- a/net/minecraft/client/gui/screens/MenuScreens.java
+++ b/net/minecraft/client/gui/screens/MenuScreens.java
@@ -41,6 +_,10 @@
private static final Map<MenuType<?>, MenuScreens.ScreenConstructor<?, ?>> SCREENS = Maps.newHashMap();
@@ -41,11 +_,16 @@
private static final Map<MenuType<?>, MenuScreens.ScreenConstructor<?, ?>> SCREENS = Maps.newHashMap();
public static <T extends AbstractContainerMenu> void create(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
+ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_));
+ }
public static <T extends AbstractContainerMenu> void create(MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
+ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_));
+ }
+
+ public static <T extends AbstractContainerMenu> java.util.Optional<ScreenConstructor<T, ?>> getScreenFactory(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
if (p_96202_ == null) {
LOGGER.warn("Trying to open invalid screen with name: {}", (Object)p_96205_.getString());
} else {
@@ -48,9 +_,10 @@
if (screenconstructor == null) {
LOGGER.warn("Failed to create screen for menu type: {}", (Object)BuiltInRegistries.MENU.getKey(p_96202_));
} else {
+ public static <T extends AbstractContainerMenu> java.util.Optional<ScreenConstructor<T, ?>> getScreenFactory(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
MenuScreens.ScreenConstructor<T, ?> screenconstructor = getConstructor(p_96202_);
if (screenconstructor == null) {
LOGGER.warn("Failed to create screen for menu type: {}", BuiltInRegistries.MENU.getKey(p_96202_));
+ return java.util.Optional.empty();
} else {
- screenconstructor.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_);
+ return java.util.Optional.of(screenconstructor);
}
}
+ return java.util.Optional.empty();
}
}
}
@Nullable
@@ -1,17 +0,0 @@
--- a/net/minecraft/client/gui/screens/OptionsScreen.java
+++ b/net/minecraft/client/gui/screens/OptionsScreen.java
@@ -150,6 +_,14 @@
p_283520_.drawCenteredString(this.font, this.title, this.width / 2, 15, 16777215);
}
+ @Override
+ public void onClose() {
+ // We need to consider 2 potential parent screens here:
+ // 1. From the main menu, in which case display the main menu
+ // 2. From the pause menu, in which case exit back to game
+ this.minecraft.setScreen(this.lastScreen instanceof PauseScreen ? null : this.lastScreen);
+ }
+
private Button openScreenButton(Component p_261565_, Supplier<Screen> p_262119_) {
return Button.builder(p_261565_, (p_280808_) -> {
this.minecraft.setScreen(p_262119_.get());
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -87,6 +_,7 @@
} else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, SocialInteractionsScreen::new));
}
+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2);
@@ -86,6 +_,7 @@
} else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this)));
}
+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2);
Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT;
this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, (p_280815_) -> {
Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT;
this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, p_280815_ -> {
@@ -1,74 +1,61 @@
--- a/net/minecraft/client/gui/screens/Screen.java
+++ b/net/minecraft/client/gui/screens/Screen.java
@@ -207,7 +_,7 @@
}
@@ -204,7 +_,7 @@
}
public void onClose() {
- this.minecraft.setScreen((Screen)null);
+ this.minecraft.popGuiLayer();
}
public void onClose() {
- this.minecraft.setScreen(null);
+ this.minecraft.popGuiLayer();
}
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -319,7 +_,10 @@
this.width = p_96608_;
this.height = p_96609_;
if (!this.initialized) {
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) {
this.init();
+ }
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
} else {
this.repositionElements();
}
@@ -332,7 +_,10 @@
protected void rebuildWidgets() {
this.clearWidgets();
this.clearFocus();
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) {
this.init();
+ }
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
}
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -320,8 +_,10 @@
this.width = p_96608_;
this.height = p_96609_;
if (!this.initialized) {
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget)))
this.init();
this.setInitialFocus();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
} else {
this.repositionElements();
}
@@ -334,8 +_,10 @@
protected void rebuildWidgets() {
this.clearWidgets();
this.clearFocus();
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget)))
this.init();
this.setInitialFocus();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
}
public List<? extends GuiEventListener> children() {
@@ -354,6 +_,7 @@
public void renderBackground(GuiGraphics p_283688_, int p_299421_, int p_298679_, float p_297268_) {
if (this.minecraft.level != null) {
this.renderTransparentBackground(p_283688_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_283688_));
} else {
this.renderDirtBackground(p_283688_);
}
@@ -369,6 +_,7 @@
int i = 32;
p_282281_.blit(BACKGROUND_LOCATION, 0, 0, 0, 0.0F, 0.0F, this.width, this.height, 32, 32);
p_282281_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_282281_));
}
@Override
@@ -362,6 +_,7 @@
public boolean isPauseScreen() {
@@ -462,6 +_,10 @@
public void onFilesDrop(List<Path> p_96591_) {
}
this.renderBlurredBackground(p_297268_);
this.renderMenuBackground(p_283688_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_);
}
+ public Minecraft getMinecraft() {
+ return this.minecraft;
+ }
protected void renderBlurredBackground(float p_336041_) {
@@ -492,6 +_,19 @@
}
public void onFilesDrop(List<Path> p_96591_) {
+ }
+
private void scheduleNarration(long p_169381_, boolean p_169382_) {
this.nextNarrationTime = Util.getMillis() + p_169381_;
if (p_169382_) {
@@ -632,5 +_,13 @@
this.index = p_169425_;
this.priority = p_169426_;
}
+ }
+ @Nullable
+ public Minecraft getMinecraft() {
+ return minecraft;
+ }
+
+ private void addEventWidget(GuiEventListener b) {
+ if (b instanceof Renderable r)
+ this.renderables.add(r);
+ if (b instanceof NarratableEntry ne)
+ this.narratables.add(ne);
+ children.add(b);
}
}
+ private void addEventWidget(GuiEventListener guiEventListener) {
+ if (guiEventListener instanceof Renderable r)
+ this.renderables.add(r);
+ if (guiEventListener instanceof NarratableEntry ne)
+ this.narratables.add(ne);
+ this.children.add(guiEventListener);
}
private void scheduleNarration(long p_169381_, boolean p_169382_) {
@@ -1,67 +1,64 @@
--- a/net/minecraft/client/gui/screens/TitleScreen.java
+++ b/net/minecraft/client/gui/screens/TitleScreen.java
@@ -63,6 +_,7 @@
@Nullable
private TitleScreen.WarningLabel warningLabel;
private final LogoRenderer logoRenderer;
+ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification;
@@ -61,6 +_,7 @@
@Nullable
private TitleScreen.WarningLabel warningLabel;
private final LogoRenderer logoRenderer;
+ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification;
public TitleScreen() {
this(false);
@@ -113,11 +_,15 @@
int j = this.width - i - 2;
int k = 24;
int l = this.height / 4 + 48;
+ Button modButton = null;
if (this.minecraft.isDemo()) {
this.createDemoMenuOptions(l, 24);
} else {
this.createNormalMenuOptions(l, 24);
+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this)))
+ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build());
}
+ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton);
public TitleScreen() {
this(false);
@@ -116,11 +_,15 @@
int j = this.width - i - 2;
int k = 24;
int l = this.height / 4 + 48;
+ Button modButton = null;
if (this.minecraft.isDemo()) {
this.createDemoMenuOptions(l, 24);
} else {
this.createNormalMenuOptions(l, 24);
+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this)))
+ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build());
}
+ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton);
SpriteIconButton spriteiconbutton = this.addRenderableWidget(CommonButtons.language(20, (p_280830_) -> {
this.minecraft.setScreen(new LanguageSelectScreen(this, this.minecraft.options, this.minecraft.getLanguageManager()));
@@ -163,7 +_,7 @@
}).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build())).active = flag;
(this.addRenderableWidget(Button.builder(Component.translatable("menu.online"), (p_210872_) -> {
this.realmsButtonClicked();
- }).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20).tooltip(tooltip).build())).active = flag;
+ }).bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20).tooltip(tooltip).build())).active = flag;
}
SpriteIconButton spriteiconbutton = this.addRenderableWidget(
CommonButtons.language(
@@ -171,7 +_,7 @@
}).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build()).active = flag;
this.addRenderableWidget(
Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this)))
- .bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20)
+ .bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20)
.tooltip(tooltip)
.build()
)
@@ -281,6 +_,7 @@
this.warningLabel.render(p_282860_, i);
}
@Nullable
@@ -243,6 +_,7 @@
this.warningLabel.render(p_282860_, i);
}
+ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i);
if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) {
this.splash.render(p_282860_, this.width, this.font, i);
}
@@ -296,11 +_,19 @@
s = s + I18n.get("menu.modded");
}
+ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i);
if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) {
this.splash.render(p_282860_, this.width, this.font, i);
}
@@ -258,7 +_,14 @@
s = s + I18n.get("menu.modded");
}
- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i);
+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) ->
+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i)
+ );
- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i);
+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) ->
+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i)
+ );
+
+ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) ->
+ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i)
+ );
+ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) ->
+ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i)
+ );
+
if (this.realmsNotificationsEnabled() && f >= 1.0F) {
RenderSystem.enableDepthTest();
this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
+ if (f >= 1.0f) this.modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
}
for(GuiEventListener guieventlistener : this.children()) {
if (guieventlistener instanceof AbstractWidget) {
@@ -271,6 +_,7 @@
RenderSystem.enableDepthTest();
this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
+ if (f1 >= 1.0f) modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
}
@@ -1,37 +1,37 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
@@ -37,6 +_,7 @@
private int maxY = Integer.MIN_VALUE;
private float fade;
private boolean centered;
+ private int page;
private int maxY = Integer.MIN_VALUE;
private float fade;
private boolean centered;
+ private int page;
public AdvancementTab(Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_) {
this.minecraft = p_97145_;
@@ -51,6 +_,15 @@
this.addWidget(this.root, p_297568_.holder());
}
public AdvancementTab(
Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_
@@ -53,6 +_,15 @@
this.addWidget(this.root, p_297568_.holder());
}
+ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) {
+ this(mc, screen, type, index, adv, info);
+ this.page = page;
+ }
+ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) {
+ this(mc, screen, type, index, adv, info);
+ this.page = page;
+ }
+
+ public int getPage() {
+ return page;
+ }
+ public int getPage() {
+ return this.page;
+ }
+
public AdvancementTabType getType() {
return this.type;
}
@@ -145,8 +_,8 @@
return null;
} else {
for(AdvancementTabType advancementtabtype : AdvancementTabType.values()) {
- if (p_97173_ < advancementtabtype.getMax()) {
- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get());
+ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) {
+ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get());
}
public AdvancementTabType getType() {
return this.type;
}
@@ -146,8 +_,8 @@
return null;
} else {
for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) {
- if (p_97173_ < advancementtabtype.getMax()) {
- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get());
+ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) {
+ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get());
}
p_97173_ -= advancementtabtype.getMax();
p_97173_ -= advancementtabtype.getMax();
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java
@@ -13,6 +_,7 @@
LEFT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top_selected"), new ResourceLocation("advancements/tab_left_middle_selected"), new ResourceLocation("advancements/tab_left_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top"), new ResourceLocation("advancements/tab_left_middle"), new ResourceLocation("advancements/tab_left_bottom")), 32, 28, 5),
RIGHT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top_selected"), new ResourceLocation("advancements/tab_right_middle_selected"), new ResourceLocation("advancements/tab_right_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top"), new ResourceLocation("advancements/tab_right_middle"), new ResourceLocation("advancements/tab_right_bottom")), 32, 28, 5);
@@ -69,6 +_,7 @@
5
);
+ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum();
private final AdvancementTabType.Sprites selectedSprites;
private final AdvancementTabType.Sprites unselectedSprites;
private final int width;
+ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum();
private final AdvancementTabType.Sprites selectedSprites;
private final AdvancementTabType.Sprites unselectedSprites;
private final int width;
@@ -1,74 +1,60 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
@@ -42,6 +_,7 @@
@Nullable
private AdvancementTab selectedTab;
private boolean isScrolling;
+ private static int tabPage, maxPages;
@@ -49,6 +_,7 @@
@Nullable
private AdvancementTab selectedTab;
private boolean isScrolling;
+ private static int tabPage, maxPages;
public AdvancementsScreen(ClientAdvancements p_97340_) {
super(GameNarrator.NO_TITLE);
@@ -58,7 +_,15 @@
} else {
this.advancements.setSelectedTab(this.selectedTab == null ? null : this.selectedTab.getRootNode().holder(), true);
}
-
+ if (this.tabs.size() > AdvancementTabType.MAX_TABS) {
+ int guiLeft = (this.width - 252) / 2;
+ int guiTop = (this.height - 140) / 2;
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> tabPage = Math.max(tabPage - 1, 0 ))
+ .pos(guiLeft, guiTop - 50).size(20, 20).build());
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> tabPage = Math.min(tabPage + 1, maxPages))
+ .pos(guiLeft + WINDOW_WIDTH - 20, guiTop - 50).size(20, 20).build());
+ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS;
+ }
}
public AdvancementsScreen(ClientAdvancements p_97340_) {
this(p_97340_, null);
@@ -62,6 +_,19 @@
public void removed() {
@@ -76,7 +_,7 @@
int j = (this.height - 140) / 2;
@Override
protected void init() {
+ if (this.tabs.size() > AdvancementTabType.MAX_TABS) {
+ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS;
+ var pageLayout = new net.minecraft.client.gui.layouts.GridLayout();
+ var text = new net.minecraft.client.gui.components.StringWidget(Component.literal(String.format("%d / %d", maxPages + 1, maxPages + 1)), this.font);
+ var update = (java.util.function.Consumer<Boolean>)back -> {
+ tabPage = back ? Math.max(tabPage - 1, 0) : Math.min(tabPage + 1, maxPages);
+ text.setMessage(Component.literal(String.format("%d / %d", 1, maxPages + 1)));
+ };
+ pageLayout.addChild(Button.builder(Component.literal("<"), b -> update.accept(true)).size(20, 20).build(), 0, 0, pageLayout.defaultCellSetting().alignHorizontallyLeft());
+ pageLayout.addChild(text, 0, 1, pageLayout.defaultCellSetting().alignHorizontallyCenter());
+ pageLayout.addChild(Button.builder(Component.literal(">"), b -> update.accept(false)).size(20, 20).build(), 0, 2, pageLayout.defaultCellSetting().alignHorizontallyRight());
+ this.layout.addToHeader(pageLayout);
+ }
this.layout.addTitleHeader(TITLE, this.font);
this.tabs.clear();
this.selectedTab = null;
@@ -106,7 +_,7 @@
int j = (this.height - 140) / 2;
for(AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break;
for (AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break;
}
@@ -180,10 +_,12 @@
p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140);
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab);
}
@@ -100,9 +_,15 @@
int i = (this.width - 252) / 2;
int j = (this.height - 140) / 2;
this.renderBackground(p_282589_, p_282255_, p_283354_, p_283123_);
+ if (maxPages != 0) {
+ net.minecraft.network.chat.Component page = Component.literal(String.format("%d / %d", tabPage + 1, maxPages + 1));
+ int width = this.font.width(page);
+ p_282589_.drawString(this.font, page.getVisualOrderText(), i + (252 / 2) - (width / 2), j - 44, -1);
+ }
this.renderInside(p_282589_, p_282255_, p_283354_, i, j);
this.renderWindow(p_282589_, i, j);
this.renderTooltips(p_282589_, p_282255_, p_283354_, i, j);
+ this.renderables.forEach(r -> r.render(p_282589_, p_282255_, p_283354_, p_283123_));
}
public boolean mouseDragged(double p_97347_, double p_97348_, int p_97349_, double p_97350_, double p_97351_) {
@@ -146,10 +_,12 @@
p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140);
if (this.tabs.size() > 1) {
for(AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab);
}
for(AdvancementTab advancementtab1 : this.tabs.values()) {
+ if (advancementtab1.getPage() == tabPage)
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
}
}
@@ -169,7 +_,7 @@
if (this.tabs.size() > 1) {
for(AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_);
for (AdvancementTab advancementtab1 : this.tabs.values()) {
+ if (advancementtab1.getPage() == tabPage)
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
}
}
}
@@ -203,6 +_,7 @@
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_);
}
@@ -1,44 +1,43 @@
--- a/net/minecraft/client/gui/screens/controls/KeyBindsList.java
+++ b/net/minecraft/client/gui/screens/controls/KeyBindsList.java
@@ -64,7 +_,7 @@
}
@@ -69,6 +_,11 @@
return 340;
}
protected int getScrollbarPosition() {
- return super.getScrollbarPosition() + 15;
+ return super.getScrollbarPosition() + 15 + 20;
}
public int getRowWidth() {
@@ -128,11 +_,13 @@
this.name = p_193917_;
this.changeButton = Button.builder(p_193917_, (p_269618_) -> {
KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_;
+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN);
KeyBindsList.this.resetMappingAndUpdateButtons();
- }).bounds(0, 0, 75, 20).createNarration((p_253311_) -> {
+ }).bounds(0, 0, 75 + 20 /* Forge: Add space */, 20).createNarration((p_253311_) -> {
return p_193916_.isUnbound() ? Component.translatable("narrator.controls.unbound", p_193917_) : Component.translatable("narrator.controls.bound", p_193917_, p_253311_.get());
}).build();
this.resetButton = Button.builder(Component.translatable("controls.reset"), (p_269616_) -> {
+ this.key.setToDefault();
KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey());
KeyBindsList.this.resetMappingAndUpdateButtons();
}).bounds(0, 0, 50, 20).createNarration((p_253313_) -> {
@@ -144,7 +_,7 @@
public void render(GuiGraphics p_281805_, int p_281298_, int p_282357_, int p_281373_, int p_283433_, int p_281932_, int p_282224_, int p_282053_, boolean p_282605_, float p_281432_) {
int k = p_281373_ + 90 - KeyBindsList.this.maxNameWidth;
p_281805_.drawString(KeyBindsList.this.minecraft.font, this.name, k, p_282357_ + p_281932_ / 2 - 9 / 2, 16777215, false);
- this.resetButton.setX(p_281373_ + 190);
+ this.resetButton.setX(p_281373_ + 190 + 20);
this.resetButton.setY(p_282357_);
this.resetButton.render(p_281805_, p_282224_, p_282053_, p_281432_);
this.changeButton.setX(p_281373_ + 105);
@@ -173,7 +_,7 @@
MutableComponent mutablecomponent = Component.empty();
if (!this.key.isUnbound()) {
for(KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) {
- if (keymapping != this.key && this.key.same(keymapping)) {
+ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G
if (this.hasCollision) {
mutablecomponent.append(", ");
}
+ @Override
+ protected int getScrollbarPosition() {
+ return super.getScrollbarPosition() + 20;
+ }
+
@OnlyIn(Dist.CLIENT)
public class CategoryEntry extends KeyBindsList.Entry {
final Component name;
@@ -153,9 +_,10 @@
this.name = p_193917_;
this.changeButton = Button.builder(p_193917_, p_269618_ -> {
KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_;
+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN);
KeyBindsList.this.resetMappingAndUpdateButtons();
})
- .bounds(0, 0, 75, 20)
+ .bounds(0, 0, 75 + 20 /* Forge: Add space */, 20)
.createNarration(
p_253311_ -> p_193916_.isUnbound()
? Component.translatable("narrator.controls.unbound", p_193917_)
@@ -163,6 +_,7 @@
)
.build();
this.resetButton = Button.builder(RESET_BUTTON_TITLE, p_325376_ -> {
+ this.key.setToDefault();
KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey());
KeyBindsList.this.resetMappingAndUpdateButtons();
}).bounds(0, 0, 50, 20).createNarration(p_253313_ -> Component.translatable("narrator.controls.reset", p_193917_)).build();
@@ -215,7 +_,7 @@
MutableComponent mutablecomponent = Component.empty();
if (!this.key.isUnbound()) {
for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) {
- if (keymapping != this.key && this.key.same(keymapping)) {
+ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G
if (this.hasCollision) {
mutablecomponent.append(", ");
}
@@ -1,46 +1,46 @@
--- a/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java
+++ b/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java
@@ -30,7 +_,7 @@
this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft));
this.resetButton = this.addRenderableWidget(Button.builder(Component.translatable("controls.resetAll"), (p_269619_) -> {
for(KeyMapping keymapping : this.options.keyMappings) {
- keymapping.setKey(keymapping.getDefaultKey());
+ keymapping.setToDefault();
}
@@ -33,7 +_,7 @@
this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft));
this.resetButton = Button.builder(Component.translatable("controls.resetAll"), p_269619_ -> {
for (KeyMapping keymapping : this.options.keyMappings) {
- keymapping.setKey(keymapping.getDefaultKey());
+ keymapping.setToDefault();
}
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -54,11 +_,13 @@
public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) {
if (this.selectedKey != null) {
if (p_193987_ == 256) {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN);
this.options.setKey(this.selectedKey, InputConstants.UNKNOWN);
} else {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_));
this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_));
}
-
+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey()))
this.selectedKey = null;
this.lastKeySelection = Util.getMillis();
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -66,6 +_,19 @@
} else {
return super.keyPressed(p_193987_, p_193988_, p_193989_);
}
+ }
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -70,11 +_,14 @@
public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) {
if (this.selectedKey != null) {
if (p_193987_ == 256) {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN);
this.options.setKey(this.selectedKey, InputConstants.UNKNOWN);
} else {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_));
this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_));
}
+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey()))
this.selectedKey = null;
this.lastKeySelection = Util.getMillis();
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -82,6 +_,19 @@
} else {
return super.keyPressed(p_193987_, p_193988_, p_193989_);
}
+ }
+
+ @Override
+ public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
+ // Forge: We wait for a second key above if the first press is a modifier
+ // but if they release the modifier then set it explicitly.
+ var key = InputConstants.getKey(keyCode, scanCode);
+ if (this.selectedKey != null && this.selectedKey.getKey() == key) {
+ this.selectedKey = null;
+ this.lastKeySelection = Util.getMillis();
+ this.keyBindsList.resetMappingAndUpdateButtons();
+ }
+ return super.keyReleased(keyCode, scanCode, modifiers);
}
+ @Override
+ public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
+ // Forge: We wait for a second key above if the first press is a modifier
+ // but if they release the modifier then set it explicitly.
+ var key = InputConstants.getKey(keyCode, scanCode);
+ if (this.selectedKey != null && this.selectedKey.getKey() == key) {
+ this.selectedKey = null;
+ this.lastKeySelection = Util.getMillis();
+ this.keyBindsList.resetMappingAndUpdateButtons();
+ }
+ return super.keyReleased(keyCode, scanCode, modifiers);
}
public void render(GuiGraphics p_282556_, int p_193992_, int p_193993_, float p_193994_) {
@Override
@@ -1,188 +1,153 @@
--- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
@@ -90,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
super.render(p_283479_, p_283661_, p_281248_, p_281886_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Background(this, p_283479_, p_283661_, p_281248_));
RenderSystem.disableDepthTest();
p_283479_.pose().pushPose();
p_283479_.pose().translate((float)i, (float)j, 0.0F);
@@ -106,12 +_,13 @@
int l = slot.x;
int i1 = slot.y;
if (this.hoveredSlot.isHighlightable()) {
- renderSlotHighlight(p_283479_, l, i1, 0);
+ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k));
@@ -92,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
super.render(p_283479_, p_283661_, p_281248_, p_281886_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderBackground(this, p_283479_, p_283661_, p_281248_);
RenderSystem.disableDepthTest();
p_283479_.pose().pushPose();
p_283479_.pose().translate((float)i, (float)j, 0.0F);
@@ -108,12 +_,13 @@
int l = slot.x;
int i1 = slot.y;
if (this.hoveredSlot.isHighlightable()) {
- renderSlotHighlight(p_283479_, l, i1, 0);
+ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k));
}
}
}
}
}
this.renderLabels(p_283479_, p_283661_, p_281248_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Foreground(this, p_283479_, p_283661_, p_281248_));
ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem;
if (!itemstack.isEmpty()) {
int l1 = 8;
@@ -153,13 +_,16 @@
}
this.renderLabels(p_283479_, p_283661_, p_281248_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderForeground(this, p_283479_, p_283661_, p_281248_);
ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem;
if (!itemstack.isEmpty()) {
int l1 = 8;
@@ -156,13 +_,17 @@
}
public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) {
- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_);
+ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433);
+ }
+ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) {
+ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_);
}
public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) {
- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_);
+ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433);
+ }
+
+ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) {
+ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_);
}
protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
ItemStack itemstack = this.hoveredSlot.getItem();
- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_);
+ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_);
}
protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
ItemStack itemstack = this.hoveredSlot.getItem();
- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_);
+ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_);
}
}
}
@@ -172,7 +_,8 @@
p_282567_.pose().pushPose();
p_282567_.pose().translate(0.0F, 0.0F, 232.0F);
p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
+ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT);
+ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
p_282567_.pose().popPose();
}
@@ -174,7 +_,8 @@
p_282567_.pose().pushPose();
p_282567_.pose().translate(0.0F, 0.0F, 232.0F);
p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
+ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT);
+ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
p_282567_.pose().popPose();
}
@@ -280,7 +_,8 @@
if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
return true;
} else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems();
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.findSlot(p_97748_, p_97749_);
long i = Util.getMillis();
this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -291,6 +_,7 @@
int j = this.leftPos;
int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int l = -1;
if (slot != null) {
l = slot.index;
@@ -316,7 +_,7 @@
}
} else if (!this.isQuickCrafting) {
if (this.menu.getCarried().isEmpty()) {
- if (flag) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, l, p_97750_, ClickType.CLONE);
} else {
boolean flag2 = l != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344));
@@ -340,7 +_,7 @@
this.quickCraftingType = 0;
} else if (p_97750_ == 1) {
this.quickCraftingType = 1;
- } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2;
}
}
@@ -409,10 +_,13 @@
}
public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) {
+ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons
Slot slot = this.findSlot(p_97812_, p_97813_);
int i = this.leftPos;
int j = this.topPos;
boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_);
int k = -1;
if (slot != null) {
k = slot.index;
@@ -426,7 +_,7 @@
if (hasShiftDown()) {
if (!this.lastQuickMoved.isEmpty()) {
for(Slot slot2 : this.menu.slots) {
- if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.container == slot.container && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
+ if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.isSameInventory(slot) && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE);
}
}
@@ -489,7 +_,7 @@
this.slotClicked((Slot)null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT);
} else if (!this.menu.getCarried().isEmpty()) {
- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
} else {
boolean flag1 = k != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344));
@@ -540,34 +_,39 @@
}
public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {
+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_);
if (super.keyPressed(p_97765_, p_97766_, p_97767_)) {
return true;
- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
this.onClose();
return true;
} else {
- this.checkHotbarKeyPressed(p_97765_, p_97766_);
+ boolean handled = this.checkHotbarKeyPressed(p_97765_, p_97766_);// Forge MC-146650: Needs to return true when the key is handled
if (this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
- if (this.minecraft.options.keyPickItem.matches(p_97765_, p_97766_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 0, ClickType.CLONE);
- } else if (this.minecraft.options.keyDrop.matches(p_97765_, p_97766_)) {
+ handled = true;
+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, hasControlDown() ? 1 : 0, ClickType.THROW);
+ handled = true;
}
+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) {
+ handled = true; // Forge MC-146650: Emulate MC bug, so we don't drop from hotbar when pressing drop without hovering over a item.
}
- return true;
+ return handled;
}
}
protected boolean checkHotbarKeyPressed(int p_97806_, int p_97807_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null) {
- if (this.minecraft.options.keySwapOffhand.matches(p_97806_, p_97807_)) {
+ if (this.minecraft.options.keySwapOffhand.isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 40, ClickType.SWAP);
@@ -282,7 +_,8 @@
if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
return true;
}
} else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems();
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.findSlot(p_97748_, p_97749_);
long i = Util.getMillis();
this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -293,6 +_,7 @@
int j = this.leftPos;
int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int l = -1;
if (slot != null) {
l = slot.index;
@@ -318,7 +_,7 @@
}
} else if (!this.isQuickCrafting) {
if (this.menu.getCarried().isEmpty()) {
- if (flag) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, l, p_97750_, ClickType.CLONE);
} else {
boolean flag2 = l != -999
@@ -346,7 +_,7 @@
this.quickCraftingType = 0;
} else if (p_97750_ == 1) {
this.quickCraftingType = 1;
- } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2;
}
}
@@ -425,10 +_,13 @@
for(int i = 0; i < 9; ++i) {
- if (this.minecraft.options.keyHotbarSlots[i].matches(p_97806_, p_97807_)) {
+ if (this.minecraft.options.keyHotbarSlots[i].isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, i, ClickType.SWAP);
return true;
}
@@ -602,6 +_,18 @@
@Override
public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) {
+ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons
Slot slot = this.findSlot(p_97812_, p_97813_);
int i = this.leftPos;
int j = this.topPos;
boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_);
int k = -1;
if (slot != null) {
k = slot.index;
@@ -445,7 +_,7 @@
if (slot2 != null
&& slot2.mayPickup(this.minecraft.player)
&& slot2.hasItem()
- && slot2.container == slot.container
+ && slot2.isSameInventory(slot)
&& AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE);
}
@@ -509,7 +_,7 @@
public T getMenu() {
return this.menu;
+ }
this.slotClicked(null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT);
} else if (!this.menu.getCarried().isEmpty()) {
- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
} else {
boolean flag1 = k != -999
@@ -568,9 +_,10 @@
@Override
public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {
+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_);
if (super.keyPressed(p_97765_, p_97766_, p_97767_)) {
return true;
- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
this.onClose();
return true;
} else {
@@ -639,5 +_,17 @@
public void onClose() {
this.minecraft.player.closeContainer();
super.onClose();
+ }
+
+ @org.jetbrains.annotations.Nullable
+ public Slot getSlotUnderMouse() { return this.hoveredSlot; }
+ public int getGuiLeft() { return leftPos; }
+ public int getGuiTop() { return topPos; }
+ public int getXSize() { return imageWidth; }
+ public int getYSize() { return imageHeight; }
+ @org.jetbrains.annotations.Nullable
+ public Slot getSlotUnderMouse() { return this.hoveredSlot; }
+ public int getGuiLeft() { return leftPos; }
+ public int getGuiTop() { return topPos; }
+ public int getXSize() { return imageWidth; }
+ public int getYSize() { return imageHeight; }
+
+ protected int slotColor = -2130706433;
+ public int getSlotColor(int index) {
+ return slotColor;
}
public void onClose() {
+ protected int slotColor = -2130706433;
+ public int getSlotColor(int index) {
+ return slotColor;
}
}
Loaded 100 of 1252 files, more files were not shown because too many files have changed in this diff. Show more