Compare commits

...
68 Commits
Author SHA1 Message Date
LexManos e1e23e9118 Add protection against large network channel lists 2026-10-12 19:07:53 -07:00
LexManos 126f4739e9 Add patch for new Eclipse Compiler 2026-10-12 15:06:55 -07:00
BonsUnleashed 3ccc463d02 Store object holder handlers per registry name (#10899) 2026-10-12 15:06:36 -07:00
Paint_NinjaandMartijn van den Brand 057fc3a309 Fix IForgeBlockStateModel.getModelData not being called correct for #getParticleIcon (#10818) (#10873)
Co-authored-by: Martijn van den Brand <[email protected]>
2026-08-15 00:41:29 -07:00
LexManos 813b53a9f6 Fix mod packets being processed after vanilla packets when received in the same tick. 2026-08-13 13:40:38 -07:00
Matt 62fa5b26a7 Split hotbar rendering into components, allow replacing renderers (#10869) 2026-07-26 10:46:12 -07:00
Matt 6efa0681b8 Add DeltaTracker (partialTick) context to PassDefinitions (#10850) 2026-07-21 11:39:06 -07:00
Paint_Ninja 5e3a3137c6 Add support for multiple access transformer configs (#10785)
Backport of #10760 to 1.21.10
Co-authored-by: LexManos <[email protected]>
Co-authored-by: Fealtous <[email protected]>
2026-07-11 10:55:28 +01:00
Matt b44728efa1 Toml parsing errors are now visible in the latest log (#10838) 2026-07-09 12:24:35 -07:00
Jonathing ac17d66868 Migrate the MDK to ForgeGradle 7
Backport of d29524b to 1.21.10.

Also bumped ASM to 9.9.1, EventBus to 7.0.1 (non-beta) and MixinExtras to 0.5.3
2026-03-17 21:48:25 +00:00
LexManos a953d2df3d Update SecureModules to address ZipPath bug with brackets. Closes #10755 2026-01-20 18:14:41 -08:00
MattandLexManos aadc515814 Optimize memory allocation for checking entity fluid collisions. Backport of #10745 (#10748)
Co-authored-by: LexManos <[email protected]>
2026-01-15 10:22:56 -08:00
LexManos 51af4b1f95 Make 1.21.10 branch 2025-12-09 18:23:36 -08:00
Matt 17e1002e86 Expose movevector field for usage with MovementInputUpdateEvent (#10732) 2025-12-06 10:42:49 -08:00
LexManos da1b8f4efa Mark applyServerBinpatches as a dependency of BundleList.
Fixes shim jar config
2025-12-03 08:56:24 -08:00
LexManos 42bbe44a34 Split setup and publish commands in actions 2025-12-02 13:58:34 -08:00
LexManos f095474adf Github Actions 2025-12-02 13:44:20 -08:00
Paint_Ninja 1b5ca64f20 Fix BusGroup.DEFAULT not being trimmed after mod loading completes, also trim mod BusGroups now too (#10721)
Saves some memory by trimming various backing collections of loaded EventBuses on the default BusGroup
2025-12-02 12:17:33 -08:00
LexManos b518c804fb 1.21.10 RB 2025-11-19 15:01:12 -08:00
Paint_Ninja e50a0ffc6c Add c:nuggets/copper item tag (#10716) 2025-11-19 09:12:27 -08:00
Matt 7ea0a41fe2 Fix ItemStack in RenderTooltipEvent always EMPTY, merges RenderTooltipEvent.Background into .Pre (#10655) (#10702) 2025-11-14 07:42:03 -08:00
Matt f3d16621c0 Provide LevelRenderState during frame pass construction Addresses #10867 (#10688) 2025-11-12 13:20:34 -08:00
Lemonnik6484 aa55a6a831 Make Mixin dev mode check a little looser (#10713) 2025-11-10 11:27:19 -08:00
cech12 3449217c65 Expand hooks for custom shears (#10704)
Fix shearing leads with custom shears (interacting with entity & leash knot)
Fix shearing poppy from copper golem for custom shears
2025-11-05 11:53:50 -08:00
JonathingandLexManos 41609a03d2 Introduce MixinExtras as an included, optional dependency (#10709)
Declare ME in userdev config as an effective compile transitive

Co-authored-by: LexManos <[email protected]>
2025-11-05 11:34:23 -08:00
LexManos 9b8e5c7109 Add workaround for Mixin bug. Closes #10710 2025-11-02 18:39:39 -08:00
LexManos f05ad3afd0 Fix ROIMFS not being on boot classloader for dedicated server. 2025-10-31 13:02:08 -07:00
LexManos 6a615f1a4b Add support for Forge shipping with JarInJar options. (#10683)
These are optional libraries that are only loaded when requested by mods.
Includes new ReadOnlyInMemoryFileSystem to improve performance of JarInJar parsing.
2025-10-30 14:48:46 -07:00
LexManos 4376cd6b85 Remove generic from AttachCapabilitiesEvent to help prevent modders from having unchecked casts. Closes #10707 2025-10-27 10:45:43 -07:00
LexManos d17a111dc0 Fix misaligned patch in DedicatedServer 2025-10-23 00:10:46 -07:00
Jonathing 1b99b2cea4 Revert "Remove runtime mods.toml string substitution (#10698)" (#10701)
This reverts commit fc80e30289, 17ce723edf, and 0e6341a23e.
2025-10-21 17:51:24 -07:00
Matt 4ef6695a30 Add support for custom particle groups (#10692) 2025-10-20 17:21:50 -07:00
Jonathing 0e6341a23e Fix Minecraft version being incorrectly included in Forge mods.toml (#10700) 2025-10-20 01:06:07 -07:00
Jonathing 17ce723edf Fix universal jar missing Forge version (#10699) 2025-10-20 00:41:21 +01:00
Paint_Ninja fc80e30289 Remove runtime mods.toml string substitution (#10698) 2025-10-19 21:45:17 +01:00
LexManos ecd1491f96 Fix Manually created RegistryObjects not being populated. Closes #10686
This partially reverts commit 1268d4c3a8acd9f780d2048d5a527206707f8e35.
But makes the classes package private so nobody can access.
2025-10-12 10:49:47 -07:00
Paint_Ninja 8f7fbc76e1 Simplify ModLoader#hasCompletedState, some more cleanup to FML internals 2025-10-11 13:43:14 +01:00
Paint_Ninja ec405958c9 Skip processing vanilla classes in RuntimeDistCleaner when running on a client (#10682) 2025-10-10 21:31:14 +01:00
Paint_Ninja e2ff990601 Require CapabilityToken subclasses to be anonymous (#10681) 2025-10-10 21:30:22 +01:00
Paint_Ninja 8443262e39 Improve event javadocs based on community feedback, apply jSpecify to more events 2025-10-10 14:57:38 +01:00
LexManos 8e09d47cd6 1.21.10 2025-10-07 10:20:47 -07:00
Paint_Ninja 0404d2d776 Bump EventBus for more javadocs 2025-10-06 20:14:28 +01:00
Paint_Ninja aea804cb6e Make BuildCreativeModeTabContentsEvent a record 2025-10-06 20:12:13 +01:00
LexManos 0bffcb83c5 Fix CustomizeGuiOverlayEvent mistakenly being a RecordEvent 2025-10-05 09:51:12 -07:00
Paint_Ninja 9a022d1451 Move more events away from the mod BusGroup (#10676)
Also adds more validation to strict mode. See the GitHub PR for further details.
2025-10-05 14:02:45 +01:00
LexManos 58aa3b276c Add the new vanilla info object to Keyboard and Mouse related events. 2025-10-02 12:09:01 -07:00
LexManosandPaint_Ninja b0ccf1a480 Minecraft 1.21.9 update.
There a lot of performance improvements related to events.
  No more InheritableEvent for abstract events that you shouldn't add listeners to anyway, like EntityEvent. Use their sub-events.
  Made a lot more events records and interfaces. Mostly just a binary break, but has better performance.
  Mod bus posting methods are now static, no more ModLoader.get() for those.

ObjectHolder was removed, use RegistryObject.
Changed RuntimeEnumExtender to only target Minecraft classes. If you want other modders to interact with your API, use an Interface instead of Enum.
Moved some abstract event methods to only the relevant sub-events now, e.g. can no longer check the side of a ClientTickEvent, because it'll always be client

Rendering has changed a lot, they now batch most things together so that the game will render faster.
RenderHighlightEvent changed a lot

See https://github.com/MinecraftForge/MinecraftForge-Experimental/tree/1.21.9-dev for unsquashed commits.

Co-authored-by: Paint_Ninja <[email protected]>
2025-10-01 13:05:12 -07:00
LexManos c1d703e395 Fix Crafters not inserting into IItemHandlers. Closes #10667 2025-09-23 13:42:29 -07:00
LexManos 728fd6ff24 Optimize ConcatenatedListView's Iterator and fix hidden CreativeTabs taking up page space. 2025-09-23 13:37:53 -07:00
Paint_Ninja 0a885a77e7 [1.21.8] Deprecate global IExtensibleEnum support (#10662)
This is intended for use with Minecraft classes only. Mod devs can support extending enums through other, more efficient means, such as converting their enum to a record and having static final fields of instances that correspond to each enum value.
2025-09-18 17:13:58 +01:00
Matt 15dbadaae6 Fix alpha channel of creative mode tab title color (#10661) 2025-09-18 08:56:02 -07:00
Jonathing 4c1c3aafdb Deprecate JS CoreMods, remove Forge's usages of them (#10659) 2025-09-16 20:13:30 +01:00
Joseph T. McQuigg f06727a205 Replace Blocks.FARMLAND checks with instanceof FarmBlock (#10647)
Signed-off-by: Joseph T. McQuigg <[email protected]>
2025-09-10 20:17:42 -07:00
LexManos ef0e7bc17f 1.21.8 RB 1 2025-08-27 12:17:25 -07:00
Matt ec7a098f81 Add event for adding framepasses (#10612) 2025-08-23 22:09:12 -07:00
Matt ff25961a05 Add ForgeLayeredDraw & AddGuiOverlayLayersEvent as API for gui overlay management. (#10579) (#10611) 2025-08-21 12:56:12 -07:00
LexManos c999a2d4eb Fix Inactivated activator rails, acting like inactivated powered rails. Closes #10643 2025-08-21 08:50:35 -07:00
LexManos ce79df9716 Fix Redstone power propagating between powered and activator rails. Fixed #10642 2025-08-20 12:20:11 -07:00
LexManos eae9b9145d Optimize VillagerTradingManager, avoid redundant work. Closes #10577 2025-08-12 18:02:33 -07:00
Paint_Ninja 7f56986027 Minor cleanup to FML, fix double parsing of mods.toml (#10597) 2025-08-04 12:50:39 -07:00
Jonathing c6874bce67 Update GradleUtils to 2.6.4 (#10600) 2025-08-02 21:21:24 -07:00
Paint_Ninja aa11175f41 Sync deps with MC (#10596) 2025-08-02 05:27:19 -07:00
Joseph T. McQuigg 2730559ff3 Allow command suggestions/autocomplete to search all modded paths at once without namespace provided (#10593) 2025-07-31 09:13:35 -07:00
Paint_Ninja e80c3402b7 Optimise WorldWorkerManager (#10578) 2025-07-23 18:37:02 +01:00
LexManos 837c259668 1.21.8 - Intel Graphic Fixes 2025-07-17 11:09:42 -07:00
LexManos 2e48910b4c Fix crash when clicking links in modlist without being in-world. 2025-07-16 10:21:55 -07:00
LexManos 70dd556db6 Use vanilla's entrypoint for GameTest servers 2025-07-01 23:56:59 -07:00
LexManos e44a558f37 Fix Forge error screen not rendering text correctly. Closes #10569 2025-07-01 23:41:08 -07:00
657 changed files with 9448 additions and 8471 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: Publish
on:
push:
branches: [ '1.21.10' ]
permissions:
contents: read
jobs:
build:
uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main
with:
java: 21
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 }}
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
name: Upload payload
runs-on: ubuntu-latest
steps:
- uses: actions/upload-artifact@v3 # Payload artifact is consumed in Actionable
- uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
with:
name: payload
path: ${{ github.event_path }}
@@ -7,7 +7,7 @@ jobs:
name: Upload payload
runs-on: ubuntu-latest
steps:
- uses: actions/upload-artifact@v3 # Payload artifact is consumed in Actionable
- uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
with:
name: payload
path: ${{ github.event_path }}
-104
View File
@@ -1,104 +0,0 @@
<?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
@@ -1,193 +0,0 @@
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.21.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()
}
})
-65
View File
@@ -1,65 +0,0 @@
Minecraft Forge: Credits/Thank You
Forge is a set of tools and modifications to the Minecraft base game code to assist
mod developers in creating new and exciting content. It has been in development for
several years now, but I would like to take this time thank a few people who have
helped it along its way.
First, the people who originally created the Forge projects way back in Minecraft
alpha. Eloraam of RedPower, and SpaceToad of Buildcraft, without their acceptiance
of me taking over the project, who knows what Minecraft modding would be today.
Secondly, someone who has worked with me, and developed some of the core features
that allow modding to be as functional, and as simple as it is, cpw. For developing
FML, which stabilized the client and server modding ecosystem. As well as the base
loading system that allows us to modify Minecraft's code as elegently as possible.
Mezz, who has stepped up as the issue and pull request manager. Helping to keep me
sane as well as guiding the community into creating better additions to Forge.
Searge, Bspks, Fesh0r, ProfMobious, and all the rest over on the MCP team {of which
I am a part}. For creating some of the core tools needed to make Minecraft modding
both possible, and as stable as can be.
On that note, here is some specific information of the MCP data we use:
* Minecraft Coder Pack (MCP) *
Forge Mod Loader and Minecraft Forge have permission to distribute and automatically
download components of MCP and distribute MCP data files. This permission is not
transitive and others wishing to redistribute the Minecraft Forge source independently
should seek permission of MCP or remove the MCP data files and request their users
to download MCP separately.
And lastly, the countless community members who have spent time submitting bug reports,
pull requests, and just helping out the community in general. Thank you.
--LexManos
=========================================================================
This is Forge Mod Loader.
You can find the source code at all times at https://github.com/MinecraftForge/MinecraftForge/tree/1.12.x/src/main/java/net/minecraftforge/fml
This minecraft mod is a clean open source implementation of a mod loader for minecraft servers
and minecraft clients.
The code is authored by cpw.
It began by partially implementing an API defined by the client side ModLoader, authored by Risugami.
https://www.minecraftforum.net/topic/75440-
This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader.
It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge.
https://minecraftforge.net/
Additionally, it contains an implementation of topological sort based on that
published at http://keithschwarz.com/interesting/code/?dir=topological-sort
It also contains code from the Maven project for performing versioned dependency
resolution. http://maven.apache.org/
It also contains a partial repackaging of the javaxdelta library from http://sourceforge.net/projects/javaxdelta/
with credit to it's authors.
Forge Mod Loader downloads components from the Minecraft Coder Pack
(http://mcp.ocean-labs.de/index.php/Main_Page) with kind permission from the MCP team.
+4 -5
View File
@@ -4,11 +4,11 @@ import net.minecraftforge.gradleutils.PomUtils
plugins {
id 'net.minecraftforge.licenser' version '1.0.1'
id 'com.github.ben-manes.versions' version '0.46.0'
id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)'
id 'net.minecraftforge.gradleutils' version '[2.6.4,2.7)'
id 'eclipse'
id 'de.undercouch.download' version '5.4.0'
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.gradle.patcher' version '[6.0.46,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.46,6.2)' apply false
id 'net.minecraftforge.gradlejarsigner' version '1.0.4'
id 'org.barfuin.gradle.taskinfo' version '2.1.0'
}
@@ -16,8 +16,7 @@ plugins {
Util.init() //Init all our extension methods!
ext {
GIT_INFO = gradleutils.gitInfo
VERSION = gradleutils.getFilteredMCTagOffsetBranchVersion(true, '[0-9]', MC_VERSION)
VERSION = gitversion.getMCTagOffsetBranch(MC_VERSION)
FORGE_VERSION = VERSION.substring(MC_VERSION.length() + 1)
}
+4 -3
View File
@@ -4,9 +4,10 @@ repositories {
}
dependencies {
implementation 'org.ow2.asm:asm:9.8'
implementation 'org.ow2.asm:asm-tree:9.8'
implementation 'net.minecraftforge:srgutils:0.5.10'
implementation 'org.ow2.asm:asm:9.9.1'
implementation 'org.ow2.asm:asm-tree:9.9.1'
implementation 'net.minecraftforge:srgutils:0.6.2'
implementation 'net.minecraftforge:JarJarMetadata:0.3.27'
implementation 'commons-io:commons-io:2.13.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.7.0.202309050840-r'
@@ -21,6 +21,8 @@ abstract class BundleList extends DefaultTask {
configure {
dependsOn(project.tasks.universalJar)
inputs.file(project.tasks.universalJar.archiveFile)
dependsOn(project.tasks.applyServerBinPatches)
inputs.file(project.tasks.applyServerBinPatches.output)
}
}
@@ -0,0 +1,415 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.forge.tasks;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier;
import net.minecraftforge.jarjar.metadata.ContainedJarMetadata;
import net.minecraftforge.jarjar.metadata.ContainedVersion;
import net.minecraftforge.jarjar.metadata.Metadata;
import net.minecraftforge.jarjar.metadata.MetadataIOHandler;
import net.minecraftforge.jarjar.metadata.json.ArtifactVersionSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedJarIdentifierSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedJarMetadataSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedVersionSerializer;
import net.minecraftforge.jarjar.metadata.json.MetadataSerializer;
import net.minecraftforge.jarjar.metadata.json.VersionRangeSerializer;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ExternalModuleDependency;
import org.gradle.api.artifacts.FileCollectionDependency;
import org.gradle.api.artifacts.MinimalExternalModuleDependency;
import org.gradle.api.artifacts.ModuleDependency;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.zip.ZipFile;
// TODO SUPER SUPER SUPER UGLY, CLEAN UP IN FORGEDEV 7
@Deprecated(forRemoval = true) // Will be moved to JarJar plugin in ForgeDev 7
public abstract class JarJarMetadataOptions extends DefaultTask {
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(VersionRange.class, new VersionRangeSerializer())
.registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionSerializer())
.registerTypeAdapter(DefaultArtifactVersion.class, new ArtifactVersionSerializer())
.registerTypeAdapter(ContainedJarIdentifier.class, new ContainedJarIdentifierSerializer())
.registerTypeAdapter(ContainedJarMetadata.class, new ContainedJarMetadataSerializer())
.registerTypeAdapter(ContainedVersion.class, new ContainedVersionSerializer())
.registerTypeAdapter(Metadata.class, new MetadataSerializer())
.setPrettyPrinting()
.create();
protected abstract @Input SetProperty<ResolvedDependencyInfoImpl> getResolvedDependencies();
protected abstract @OutputFile RegularFileProperty getMetadataFile();
protected abstract @Inject ProjectLayout getLayout();
// NOTE: I'm not adding a non-provider version. please just use the version catalog entries for now.
public void add(Provider<MinimalExternalModuleDependency> dependency, Action<? super ResolvedDependencyInfo> action) {
this.getResolvedDependencies().add(dependency.map(d -> {
var ret = ResolvedDependencyInfoImpl.from(this.getProject().getConfigurations(), d);
action.execute(ret);
return ret;
}));
}
@Inject
public JarJarMetadataOptions() {
this.getMetadataFile().convention(this.getLayout().getBuildDirectory().file(this.getName() + "/options.json"));
}
@TaskAction
protected void exec() {
record ForgeLocaterOptions(String resource, String layer, String id, List<ContainedJarMetadata> deps, ContainedJarMetadata meta, boolean nested) { }
var resolved = this.getResolvedDependencies().get();
var jars = new ArrayList<ForgeLocaterOptions>(resolved.size());
for (var dependency : resolved) {
var deps = new ArrayList<ContainedJarMetadata>();
try (var zip = new ZipFile(dependency.artifact)) {
var entry = zip.getEntry("META-INF/jarjar/metadata.json");
if (entry != null) {
try (var stream = zip.getInputStream(entry)) {
var meta = MetadataIOHandler.fromStream(stream).orElse(null);
if (meta == null)
throw new IllegalStateException("Corrupt metadata.json in " + dependency.artifact.getAbsolutePath());
for (var dep : meta.jars())
deps.add(new ContainedJarMetadata(dep.identifier(), dep.version(), "", dep.isObfuscated()));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
jars.add(new ForgeLocaterOptions(
dependency.resource,
dependency.layer,
dependency.identifier,
deps,
new ContainedJarMetadata(
new ContainedJarIdentifier(validateGroup(dependency), dependency.module.getName()),
new ContainedVersion(null, parseVersion(dependency)),
Objects.requireNonNull(dependency.path, "Dependency path is unspecified: " + dependency.asString),
false
),
dependency.nested
));
}
try {
record Meta(List<ForgeLocaterOptions> options){}
Files.writeString(
this.getMetadataFile().getAsFile().get().toPath(),
GSON.toJson(new Meta(jars), Meta.class)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String validateGroup(ResolvedDependencyInfoImpl dependency) {
try {
return Objects.requireNonNull(dependency.module.getGroup());
} catch (NullPointerException e) {
throw new IllegalArgumentException("Module dependency has no group: " + dependency.asString, e);
}
}
private ArtifactVersion parseVersion(ResolvedDependencyInfoImpl resolved) {
try {
return VersionRange.createFromVersionSpec(Objects.requireNonNull(resolved.version)).getRecommendedVersion();
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version is invalid for: " + resolved.asString, e);
} catch (NullPointerException e) {
throw new IllegalArgumentException("Version is unspecified for: " + resolved.asString, e);
}
}
private VersionRange parseVersionRange(ResolvedDependencyInfoImpl dependency) {
if (dependency.hasManuallySpecifiedRange) {
try {
return VersionRange.createFromVersionSpec(dependency.versionRange);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version is invalid for: " + dependency.asString, e);
}
} else {
try {
return VersionRange.createFromVersionSpec("[%s,)".formatted(Objects.requireNonNull(dependency.versionRange)));
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version range is invalid for: " + dependency.asString, e);
} catch (NullPointerException e) {
throw new IllegalArgumentException("Version is unspecified for: " + dependency.asString, e);
}
}
}
public interface ResolvedDependencyInfo {
void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action);
void setResource(String resource);
void setLayer(String layer);
void setId(String identifier);
void setNested(boolean nested);
interface ContainedJarMetadataInfo {
void setGroup(String group);
void setName(String name);
void setPath(String version);
}
}
static final class ResolvedDependencyInfoImpl implements ResolvedDependencyInfo, ResolvedDependencyInfo.ContainedJarMetadataInfo, Serializable {
private static final @Serial long serialVersionUID = -7577318115877822993L;
final MinimalModuleVersionIdentifier module;
final String version;
String versionRange;
boolean hasManuallySpecifiedRange;
boolean nested;
final File artifact;
String path;
String resource;
String layer;
String identifier;
final String asString;
public ResolvedDependencyInfoImpl(MinimalModuleVersionIdentifier module, String version, File artifact, String asString) {
this.module = module;
this.version = version;
this.artifact = artifact;
this.asString = asString;
}
@Override
public void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action) {
action.execute(this);
}
@Override
public void setGroup(String group) {
this.module.group = group;
}
@Override
public void setName(String name) {
this.module.name = name;
}
@Override
public void setPath(String path) {
this.path = path;
}
@Override
public void setResource(String resource) {
this.resource = resource;
}
@Override
public void setLayer(String layer) {
this.layer = layer;
}
@Override
public void setId(String identifier) {
this.identifier = identifier;
}
@Override
public void setNested(boolean nested) {
this.nested = nested;
}
static Set<File> getFiles(Set<ResolvedDependencyInfoImpl> resolvedDependencies) {
var ret = new HashSet<File>(resolvedDependencies.size());
for (var dependency : resolvedDependencies) {
ret.add(dependency.artifact);
}
return ret;
}
static ResolvedDependencyInfoImpl from(ConfigurationContainer configurations, Dependency dependency) {
var group = dependency.getGroup();
var name = dependency.getName();
var version = dependency.getVersion();
if (dependency instanceof FileCollectionDependency filesDependency) {
File artifact;
try {
artifact = filesDependency.getFiles().getSingleFile();
} catch (IllegalStateException e) {
// TODO fileCollectionDependencyIsNotSingleFile
throw e;
}
return new ResolvedDependencyInfoImpl(
new MinimalModuleVersionIdentifier(group, name, version),
version,
artifact,
filesDependency.toString()
);
} else if (dependency instanceof ModuleDependency moduleDependency) {
moduleDependency = moduleDependency.copy();
if (moduleDependency instanceof ExternalModuleDependency externalModuleDependency) {
externalModuleDependency.version(v -> v.strictly(version.toString()));
}
var detachedConfiguration = configurations.detachedConfiguration(moduleDependency);
detachedConfiguration.setTransitive(false);
ResolvedDependencyInfoImpl ret = null;
for (var artifact : detachedConfiguration.getResolvedConfiguration().getFirstLevelModuleDependencies().iterator().next().getModuleArtifacts()) {
var fileName = getFileName(artifact);
if (!fileName.endsWith(".jar"))
continue;
if (ret != null)
throw new IllegalArgumentException("Module dependency has too many Jar artifacts: " + moduleDependency);
ret = new ResolvedDependencyInfoImpl(
new MinimalModuleVersionIdentifier(group, name, artifact.getModuleVersion().getId().getVersion()),
version,
artifact.getFile(),
moduleDependency.toString()
);
}
if (ret == null)
throw new IllegalArgumentException("Module dependency has no Jar artifacts: " + moduleDependency);
return ret;
} else {
throw new IllegalArgumentException("Unsupported dependency type: " + dependency.getClass().getName() + " -- " + dependency);
}
}
private static String getFileName(ResolvedArtifact artifact) {
try {
return InvokerHelper.getProperty(artifact.getId(), "fileName").toString();
} catch (Throwable e) {
// NOTE: Why not just use this to begin with?
// ComponentArtifactIdentifier can have a getFileName() method, which doesn't necessarily resolve the file itself.
// This allows us to get the name of the file to be used without asking Gradle to download the file.
// So, if a file is not a JAR file, we can check the name without actually downloading it.
return artifact.getFile().getName();
}
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (ResolvedDependencyInfoImpl) obj;
return Objects.equals(this.module, that.module) &&
Objects.equals(this.version, that.version) &&
Objects.equals(this.versionRange, that.versionRange) &&
Objects.equals(this.artifact, that.artifact);
}
@Override
public int hashCode() {
return Objects.hash(module, version, versionRange, artifact);
}
@Override
public String toString() {
return "ResolvedDependencyInfo[" +
"module=" + module + ", " +
"fixedVersion=" + version + ", " +
"versionRange=" + versionRange + ", " +
"artifact=" + artifact + ']';
}
static final class MinimalModuleVersionIdentifier implements ModuleIdentifier, ModuleVersionIdentifier {
private static final @Serial long serialVersionUID = -955346236759069739L;
private String group;
private String name;
private final String version;
@Inject
public MinimalModuleVersionIdentifier(String group, String name, String version) {
this.group = group;
this.name = name;
this.version = version;
}
@Override
public ModuleIdentifier getModule() {
return this;
}
@Override
public String getGroup() {
return this.group;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getVersion() {
return this.version;
}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof MinimalModuleVersionIdentifier o
&& Objects.equals(this.group, o.group)
&& Objects.equals(this.name, o.name)
&& Objects.equals(this.version, o.version);
}
@Override
public int hashCode() {
return Objects.hash(group, name, version);
}
@Override
public String toString() {
return "MinimalModuleVersionIdentifier[" +
"group=" + group + ", " +
"name=" + name + ", " +
"version=" + version + ']';
}
}
}
}
+27 -10
View File
@@ -71,7 +71,7 @@ sourceSets {
}
}
final String SPEC_VERSION = gradleutils.gitInfo.tag
final String SPEC_VERSION = gitversion.info.tag
// The new versioning sceme is <MCVersion>-<ForgeMC>.<RB>.<CommitsSinceRB>
// ForgeMC is a unique identifier for every MC version we have supported.
@@ -79,7 +79,6 @@ final String SPEC_VERSION = gradleutils.gitInfo.tag
final def MCP_ARTIFACT = project(':mcp').mcp.config.get()
final List<File> EXTRA_TXTS = [
rootProject.file('CREDITS.txt'),
rootProject.file('LICENSE.txt'),
rootProject.tasks.createChangelog.outputFile
]
@@ -113,6 +112,7 @@ dependencies {
// And this is only needed because custom file systems are REQUIRED to be on the boot classloader.
// This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project.
bootstrap(libs.jarjar.fs) // JarInJar file system
bootstrap(libs.roimfs) // JarInJar File System - FileSystems need to be on boot loader.
bootstrap(libs.bundles.jimfs) // In memory file system used for ForgeDev launches
bootstrap(libs.securemodules) // Has Union file system in it
bootstrap(libs.unsafe) // Needed by securemodules
@@ -134,7 +134,9 @@ dependencies {
installer(libs.maven.artifact)
installer(libs.bundles.terminalconsoleappender)
installer(libs.mixin)
installer(libs.mixinextras.forge)
installer(libs.bundles.jarjar)
installer(libs.roimfs)
installer(project(':fmlcore'))
installer(project(':fmlloader'))
@@ -142,6 +144,7 @@ dependencies {
installer(project(':javafmllanguage'))
installer(project(':lowcodelanguage'))
installer(project(':mclanguage'))
installer(project(':forge-transformers'))
installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off")
@@ -298,6 +301,11 @@ tasks.userdevConfig.configure {
libraries.add(dep)
}
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
// so we don't gotta keep making exceptions for MixinExtras
addCompileDependency(libs.mixinextras.common)
addAnnotationProcessorDependency(libs.mixinextras.common)
inject = '' // We don't have a userdev sourceset anymore. Empty as a gradle workaround...
runs {
client {
@@ -414,7 +422,7 @@ tasks.register('extractInheritance', ExtractInheritance) {
}
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
jar = createClientOfficial.output
output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json')
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json')
predicate = {
parent, node, insn ->
return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
@@ -925,23 +933,31 @@ tasks.register('installerJar', InstallerJar) {
jarSigner.sign(it)
}
final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) {
gradleVersion = '9.3.1'
}
tasks.register('mdkZip', Zip) {
dependsOn mdkGradleWrapper
archiveBaseName = project.name
archiveClassifier = 'mdk'
archiveVersion = project.version
destinationDirectory = file('build/libs')
from rootProject.file('gradlew')
from rootProject.file('gradlew.bat')
from mdkGradleWrapper.map(Wrapper.&getScriptFile)
from mdkGradleWrapper.map(Wrapper.&getBatchScript)
from(EXTRA_TXTS)
from(rootProject.file('gradle/')){
into('gradle/')
into('gradle/wrapper/') {
from mdkGradleWrapper.map(Wrapper.&getJarFile)
from mdkGradleWrapper.map(Wrapper.&getPropertiesFile)
}
from(rootProject.file('mdk/')){
rootProject.file('mdk/gitignore.txt').eachLine{
rootProject.file('mdk/gitignore.txt').eachLine {
if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
exclude it
}
filter(ReplaceTokens, tokens: [
FORGE_VERSION: FORGE_VERSION,
FORGE_GROUP: project.group,
@@ -950,7 +966,8 @@ tasks.register('mdkZip', Zip) {
MAPPING_CHANNEL: MAPPING_CHANNEL,
MAPPING_VERSION: MAPPING_VERSION,
FORGE_SPEC_VERSION: SPEC_VERSION.split("\\.")[0],
MC_NEXT_VERSION: MC_NEXT_VERSION
MC_NEXT_VERSION: MC_NEXT_VERSION,
EVENTBUS_VERSION: libs.versions.eventbus.get()
])
rename 'gitignore\\.txt', '.gitignore'
rename 'gitattributes\\.txt', '.gitattributes'
@@ -997,7 +1014,7 @@ if (project.hasProperty('UPDATE_MAPPINGS')) {
tasks.named('javadoc', Javadoc).configure {
description 'Generates the combined javadocs for the FML projects and the main Forge project'
var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage' ]
var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage', ':forge-transformers' ]
source includedProjects.collect { project(it).sourceSets.main.allJava }
classpath = classpath + files(includedProjects.collect { project(it).sourceSets.main.compileClasspath })
+4
View File
@@ -38,6 +38,10 @@ tasks.register('generateResources') {
dependsOn('writeManifest')
}
tasks.named('processResources') {
dependsOn(generateResources)
}
// Make sure out manifests get written before compiling the code, IDEA calls this task if you tell it to use the gradle build.
tasks.withType(JavaCompile).configureEach {
dependsOn 'generateResources'
+2 -2
View File
@@ -2,8 +2,8 @@
MinecraftForge
=============
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.21.4-&query=$.promos["1.21.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.21.5-&query=$.promos["1.21.5-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.21.10-&query=$.promos["1.21.10-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.21.10-&query=$.promos["1.21.10-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!
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
for file in $(find repo | grep --invert-match -e md5 -e sha | grep -e .jar -e .zip); do
file_path=$(realpath $file)
file_name=$(basename $file)
echo "$file_name"
files=$(unzip -l $file | awk '{print $4}')
for f in $files; do
out="_actual/$file_name/$f"
parent=$(dirname "$out")
echo $out
if [ ! -d "$parent" ]; then
mkdir -p "$parent"
fi
if [[ $f == *.class ]]; then
javap -v -p jar:file://$file_path!/$f | tail -n +4 >$out.txt
elif [[ $f != */ && $f != "Name" && $f != "----" ]]; then
unzip -o -q $file $f -d _actual/$file_name
fi
done
done
@@ -5,6 +5,7 @@
package net.minecraftforge.fml;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.IModBusEvent;
@@ -157,6 +158,14 @@ public abstract class ModContainer {
*/
public abstract Object getMod();
/**
* @return the mod bus group for this specific mod, or null if there is none.
* Leave null if you use {@link BusGroup#DEFAULT} for your mod lifecycle events.
*/
public BusGroup getModBusGroup() {
return null;
}
/**
* Accept an arbitrary event for processing by the mod. Probably posted to an event bus in the lower level container.
* @param e Event to accept
@@ -41,14 +41,14 @@ public class ModList {
private List<ModContainer> sortedContainers;
private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
var modFileInfos = this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
this.sortedList = sortedList.stream().map(IModInfo.class::cast).toList();
var byId = new HashMap<String, IModFileInfo>();
for (var file : this.modFiles) {
for (var file : modFileInfos) {
for (var mod : file.getMods())
byId.put(mod.getModId(), mod.getOwningFile());
}
this.fileById = Collections.unmodifiableMap(byId);
this.fileById = Map.copyOf(byId);
CrashReportCallables.registerCrashCallable("Mod List", this::crashReport);
}
@@ -67,7 +67,7 @@ public class ModList {
}
private String crashReport() {
return "\n"+applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
return "\n" + applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
}
public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) {
@@ -126,10 +126,9 @@ public class ModList {
map(IModFileInfo::getFile).
distinct().
map(IModFile::getScanResult).
collect(Collectors.toList());
toList();
}
return modFileScanData;
}
public void forEachModFile(Consumer<IModFile> fileConsumer) {
@@ -6,6 +6,7 @@
package net.minecraftforge.fml;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.FMLLoader;
@@ -84,20 +85,20 @@ public class ModLoader {
private ModList modList;
private ModLoader() {
this.loadingModList = FMLLoader.getLoadingModList();
this.loadingExceptions = this.loadingModList.getErrors().stream()
var loadingModList = this.loadingModList = FMLLoader.getLoadingModList();
var loadingExceptions = this.loadingExceptions = loadingModList.getErrors().stream()
.flatMap(ModLoadingException::fromEarlyException)
.collect(Collectors.toList());
this.loadingWarnings = this.loadingModList.getBrokenFiles().stream()
this.loadingWarnings = loadingModList.getBrokenFiles().stream()
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
.collect(Collectors.toList());
if (this.loadingExceptions.isEmpty()) {
if (loadingExceptions.isEmpty()) {
this.erroredModInfos = Collections.emptySet();
} else {
this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
this.erroredModInfos.addAll(this.loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
this.erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
}
this.loadingModList.getModFiles().stream()
loadingModList.getModFiles().stream()
.filter(ModFileInfo::missingLicense)
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(this.erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
@@ -112,16 +113,16 @@ public class ModLoader {
private static String computeLanguageList() {
return "\n" + FMLLoader.getLanguageLoadingProvider()
.applyForEach(lp -> lp.name() + "@" + lp.getClass().getPackage().getImplementationVersion())
.applyForEach(lp -> lp.name() + '@' + lp.getClass().getPackage().getImplementationVersion())
.collect(Collectors.joining("\n\t\t", "\t\t", ""));
}
private static String computeModLauncherServiceList() {
final List<Map<String, String>> mods = FMLLoader.modLauncherModList();
return "\n"+mods.stream().map(mod->mod.getOrDefault("file","nofile")+
" "+mod.getOrDefault("name", "missing")+
" "+mod.getOrDefault("type","NOTYPE")+
" "+mod.getOrDefault("description", "")).
return "\n" + mods.stream().map(mod -> mod.getOrDefault("file","nofile") +
' ' + mod.getOrDefault("name", "missing") +
' ' + mod.getOrDefault("type","NOTYPE") +
' ' + mod.getOrDefault("description", "")).
collect(Collectors.joining("\n\t\t","\t\t",""));
}
@@ -232,7 +233,19 @@ public class ModLoader {
for (IModLoadingState mls : stateList) {
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
}
statusConsumer.accept(String.format("Mod loading complete - %d mods loaded", this.modList.size()));
var modBusGroups = Set.of(
modList.getLoadedMods().stream()
.map(ModContainer::getModBusGroup)
.filter(Objects::nonNull)
.toArray(BusGroup[]::new)
);
for (var modBusGroup : modBusGroups) {
parallelExecutor.execute(modBusGroup::trim);
}
parallelExecutor.execute(BusGroup.DEFAULT::trim);
statusConsumer.accept("Mod loading complete - %d mods loaded".formatted(this.modList.size()));
progress.complete();
}
@@ -254,7 +267,7 @@ public class ModLoader {
}
private void handleInlineTransition(final Consumer<ModList> transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
var pb = StartupMessageManager.addProgressBar("State transition " +state.name()+" running", 0);
var pb = StartupMessageManager.addProgressBar("State transition " + state.name() + " running", 0);
syncExecutor.drive(ticker);
transition.accept(this.modList);
syncExecutor.drive(ticker);
@@ -353,12 +366,18 @@ public class ModLoader {
return loadingStateValid;
}
/** @deprecated Use {@link #hasCompletedState(IModLoadingState)} instead */
@Deprecated(forRemoval = true)
public boolean hasCompletedState(final String stateName) {
IModLoadingState state = stateManager.findState(stateName);
return completedStates.contains(state);
}
public <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
public boolean hasCompletedState(IModLoadingState state) {
return completedStates.contains(state);
}
public static <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
return;
@@ -367,8 +386,7 @@ public class ModLoader {
mod.acceptEvent(generator.apply(mod));
}
public <T extends IModBusEvent> void postEvent(T e) {
var cls = e.getClass();
public static <T extends IModBusEvent> void postEvent(T e) {
if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return;
@@ -377,7 +395,7 @@ public class ModLoader {
mod.acceptEvent(e);
}
public <T extends IModBusEvent> T postEventWithReturn(T e) {
public static <T extends IModBusEvent> T postEventWithReturn(T e) {
if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return e;
@@ -388,14 +406,14 @@ public class ModLoader {
}
@SuppressWarnings("removal")
public <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
public static <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
postEventWithWrapInModOrder(event,
(mc, e) -> ModLoadingContext.get().setActiveContainer(mc),
(mc, e) -> ModLoadingContext.get().setActiveContainer(null)
);
}
public <T extends IModBusEvent> void postEventWithWrapInModOrder(T e, BiConsumer<ModContainer, T> pre, BiConsumer<ModContainer, T> post) {
public static <T extends IModBusEvent> void postEventWithWrapInModOrder(T e, BiConsumer<ModContainer, T> pre, BiConsumer<ModContainer, T> post) {
if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return;
@@ -19,7 +19,13 @@ public class ModLoadingContext {
private Object languageExtension;
/**
* @deprecated Use the context provided by your language loader in your mod's constructor
* @deprecated Use the context provided by your language loader in your mod's constructor. Example for Java mods: {@snippet :
* @Mod("examplemod")
* public final class ExampleMod {
* public ExampleMod(FMLJavaModLoadingContext context) {
* // Use context from the param instead of FMLJavaModLoadingContext.get() or ModLoadingContext.get()
* }
* }}
*/
@Deprecated(forRemoval = true, since="1.21.1")
public static ModLoadingContext get() {
@@ -7,6 +7,7 @@ package net.minecraftforge.fml;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -59,7 +60,7 @@ public record ModLoadingState(
*/
@Deprecated(since = "1.21.3", forRemoval = true)
public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) {
return of(name, phase).after(previous).empty();
return new ModLoadingState(name, previous, ml -> "", ml -> 0, phase, Optional.empty(), Optional.empty());
}
/**
@@ -120,6 +121,22 @@ public record ModLoadingState(
return new Builder(name, phase);
}
@Override
public boolean equals(Object o) {
return o instanceof ModLoadingState that
&& this.phase == that.phase
&& this.name.equals(that.name)
&& Objects.equals(this.previous, that.previous);
}
@Override
public int hashCode() {
int result = phase.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + Objects.hashCode(previous);
return result;
}
public static class Builder {
private final String name;
private final ModLoadingPhase phase;
@@ -41,11 +41,13 @@ public class ModStateManager {
}
public IModLoadingState findState(final String stateName) {
return stateMap.values()
var result = stateMap.values()
.stream()
.flatMap(List::stream)
.filter(mls -> mls.name().equals(stateName))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown IModLoadingState: " + stateName));
.orElse(null);
if (result != null) return result;
else throw new IllegalArgumentException("Unknown IModLoadingState: " + stateName);
}
}
@@ -8,16 +8,22 @@ package net.minecraftforge.fml.event;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.InheritableEvent;
import org.jspecify.annotations.NonNull;
/**
* Marker interface for events dispatched on the ModLifecycle event bus instead of the primary event bus
* Marker interface for mod lifecycle events dispatched on the
* {@linkplain net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup() mod BusGroup} instead
* of the {@linkplain BusGroup#DEFAULT default BusGroup}.
*
* @apiNote Each mod gets its own unique mod BusGroup instance, obtained from the mod loading context. Most events
* should go on the default BusGroup.
*/
public interface IModBusEvent extends InheritableEvent {
/**
* @param modEventBusGroup Obtained from {@link net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup()} or your language provider's equivalent.
* @param eventClass The event type you want to get the associated bus for.
*/
static <T extends IModBusEvent> EventBus<T> getBus(BusGroup modEventBusGroup, Class<T> eventClass) {
static <T extends IModBusEvent> @NonNull EventBus<@NonNull T> getBus(@NonNull BusGroup modEventBusGroup, @NonNull Class<T> eventClass) {
// Do not copy! Temporary solution until the FML rewrite is complete. May throw in future
// without prior notice.
//
+21
View File
@@ -36,6 +36,7 @@ dependencies {
implementation(libs.accesstransformers)
implementation(libs.terminalconsoleappender)
implementation(libs.jimfs)
implementation(libs.roimfs)
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
implementation(libs.log4j.core)
@@ -103,11 +104,31 @@ tasks.register('writeForgeVersionJson') {
}
}
tasks.register('jarJarOptionsJson', net.minecraftforge.forge.tasks.JarJarMetadataOptions) {
metadataFile = project.file('src/main/resources/jarjar_options.json')
// This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually...
//add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class')
add(libs.mixinextras.forge) {
containedJarMetadata {
path = ''
}
resource = 'com/llamalad7/mixinextras/platform/forge/MixinExtrasConfigPlugin.class'
layer = 'GAMELIBRARY'
id = 'mixinextras'
nested = true
}
}
tasks.named('generateResources').configure {
dependsOn('eclipseJdt')
dependsOn('eclipseJdtApt')
dependsOn('eclipseFactorypath')
dependsOn('writeForgeVersionJson')
dependsOn('jarJarOptionsJson')
}
tasks.named('sourcesJar') {
dependsOn('jarJarOptionsJson')
}
eclipse {
@@ -34,11 +34,10 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
* }</code>
* </pre>
*/
public class CapabilityTokenSubclass implements ILaunchPluginService {
public final 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 static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; // Don't directly reference this to prevent class loading.
@Override
public String name() {
@@ -56,8 +55,11 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY;
if (internalName.startsWith("net/minecraftforge/common/capabilities/"))
return YAY;
return YAY;
return internalName.contains("$") ? YAY : NAY; // Anonymous subclasses only
}
@Override
@@ -70,7 +72,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
}
return ComputeFlags.SIMPLE_REWRITE;
} else if (CAP_INJECT.equals(classNode.superName)) {
Holder cls = new Holder();
var cls = new Object() { String value = null; };
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9) {
@@ -106,8 +108,4 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
return ComputeFlags.NO_REWRITE;
}
}
private static final class Holder {
String value;
}
}
@@ -1,131 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
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;
import java.util.stream.Stream;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Removes the final modifier from fields with the @ObjectHolder annotation, prevents the JITer from in lining them so our runtime replacements can work.
* Will also de-finalize all fields in on class level annotations.
*/
public class ObjectHolderDefinalize implements ILaunchPluginService {
// Hardcoded map of vanilla classes that should have object holders for each field of the given registry type.
// IMPORTANT: Updates to this collection must be reflected in ObjectHolderRegistry. Duplicated cuz classloaders, yay!
// Classnames are validated in ObjectHolderRegistry.
private static final Map<String, VanillaObjectHolderData> VANILLA_OBJECT_HOLDERS = Stream.of(
new VanillaObjectHolderData("net.minecraft.world.level.block.Blocks", "block", "net.minecraft.world.level.block.Block"),
new VanillaObjectHolderData("net.minecraft.world.item.Items", "item", "net.minecraft.world.item.Item"),
new VanillaObjectHolderData("net.minecraft.world.item.enchantment.Enchantments", "enchantment", "net.minecraft.world.item.enchantment.Enchantment"),
new VanillaObjectHolderData("net.minecraft.world.effect.MobEffects", "mob_effect", "net.minecraft.world.effect.MobEffect"),
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.toUnmodifiableMap(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;
@Override
public String name() {
return "object_holder_definalize";
}
private static final EnumSet<Phase> YAY = EnumSet.of(Phase.AFTER);
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;
}
private static boolean hasHolder(List<AnnotationNode> lst) {
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
@SuppressWarnings("unused")
private String getValue(List<AnnotationNode> lst)
{
AnnotationNode ann = lst.stream().filter(n -> n.desc.equals(OBJECT_HOLDER)).findFirst().get();
if (ann.values != null)
{
for (int x = 0; x < ann.values.size() - 1; x += 2) {
if (ann.values.get(x).equals("value")) {
return (String)ann.values.get(x + 1);
}
}
}
return null;
}
@Override
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason)
{
final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects
//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 ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final
f.access |= Opcodes.ACC_SYNTHETIC; //Add Synthetic so we can check in runtime. ? Good idea?
changes.compareAndSet(false, prev != f.access);
});
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 ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL;
f.access |= Opcodes.ACC_SYNTHETIC;
/*if (!hasHolder(f.visibleAnnotations)) //Add field level annotation, doesn't do anything until after we figure out how ASMDataTable is gatherered
{
if (value == null)
f.visitAnnotation(OBJECT_HOLDER, true);
else
f.visitAnnotation(OBJECT_HOLDER, true).visit("value", value + ":" + f.name.toLowerCase());
}*/
changes.compareAndSet(false, prev != f.access);
});
}
return changes.get() ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE;
}
private record VanillaObjectHolderData(String holderClass, String registryName, String registryType) {}
}
@@ -7,9 +7,9 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.LoadingModList;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
@@ -47,16 +47,21 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final EnumSet<Phase> YAY = EnumSet.of(Phase.AFTER);
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
private static final class LazyInit {
private LazyInit() {}
private static final boolean ANY_MODS = LoadingModList.get().getMods().size() > 2; // 2: forge, minecraft
}
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
if (isEmpty || !LazyInit.ANY_MODS)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return NAY;
if (internalName.startsWith("net/minecraft/client/model") || internalName.startsWith("net/minecraft/world"))
return YAY;
return YAY;
return NAY;
}
@Override
@@ -146,9 +146,8 @@ public class FMLLoader {
}
public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) {
LOGGER.debug(SCAN,"Scanning for Mod Locators");
var modDiscoverer = new ModDiscoverer(arguments);
modValidator = modDiscoverer.discoverMods();
LOGGER.debug(SCAN, "Scanning for Mod Locators");
modValidator = ModDiscoverer.discoverMods(arguments);
var pluginResources = modValidator.getPluginResources();
return List.of(pluginResources);
}
@@ -174,7 +173,7 @@ public class FMLLoader {
}
public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
LOGGER.debug(SCAN, "Adding Access Transformer {} in {}", atPath, modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
@@ -5,11 +5,14 @@
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
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.nio.file.Files;
import java.nio.file.Path;
@@ -24,6 +27,7 @@ import java.util.stream.Collectors;
* loading package</em>
*/
public class LoadingModList {
private static final Logger LOGGER = LogUtils.getLogger();
private static LoadingModList INSTANCE;
private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList;
@@ -36,9 +40,7 @@ public class LoadingModList {
.map(ModFile::getModFileInfo)
.map(ModFileInfo.class::cast)
.toList();
this.sortedList = sortedList.stream()
.map(ModInfo.class::cast)
.toList();
this.sortedList = sortedList.stream().toList();
this.fileById = this.modFiles.stream()
.map(ModFileInfo::getMods)
.flatMap(Collection::stream)
@@ -67,13 +69,22 @@ public class LoadingModList {
}
public void addAccessTransformers() {
var errors = new ArrayList<ExceptionData>();
for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile();
var at = mod.getAccessTransformer().orElse(null);
if (at != null) {
FMLLoader.addAccessTransformer(at, mod);
for (var at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new ExceptionData(message));
LOGGER.error(message);
} else
FMLLoader.addAccessTransformer(at, mod);
}
}
if (!errors.isEmpty())
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler) {
@@ -7,8 +7,10 @@ package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.SecureJar;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import cpw.mods.modlauncher.api.NamedPath;
import cpw.mods.modlauncher.api.TypesafeMap;
import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService;
import org.jetbrains.annotations.ApiStatus;
@@ -40,6 +42,17 @@ public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService
@Override
public void earlyInitialization(final String launchTarget, final String[] arguments) {
boolean isMixinEnabledInDev = false;
for (String arg : arguments) {
if (arg.startsWith("-mixin") || arg.startsWith("--mixin")) {
isMixinEnabledInDev = true;
break;
}
}
Launcher.INSTANCE.blackboard().putIfAbsent(
TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "isMixinEnabledInDev", Boolean.class),
isMixinEnabledInDev
);
ImmediateWindowHandler.load(launchTarget, arguments);
}
@@ -46,7 +46,7 @@ public class ModSorter {
List<ModFile> modFiles;
try {
modFiles = new UniqueModListBuilder(mods).buildUniqueList().modFiles();
modFiles = UniqueModListBuilder.buildUniqueList(mods).modFiles();
} catch (EarlyLoadingException e) {
// We cannot build any list with duped mods. We have to abort immediately and report it
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
@@ -27,7 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class RuntimeDistCleaner implements ILaunchPluginService {
public final class RuntimeDistCleaner implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
private static String DIST;
@@ -52,6 +52,10 @@ public class RuntimeDistCleaner implements ILaunchPluginService {
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;
}
@@ -17,8 +17,6 @@ import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
@@ -26,19 +24,12 @@ import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
@ApiStatus.Internal
@Deprecated(since = "1.21.3", forRemoval = true) // TODO: [FML][Loading] Convert to package private in 1.22
public class UniqueModListBuilder {
private final static Logger LOGGER = LogUtils.getLogger();
public final class UniqueModListBuilder {
private UniqueModListBuilder() {}
private final List<ModFile> modFiles;
public UniqueModListBuilder(final List<ModFile> modFiles) {
this.modFiles = modFiles;
}
public UniqueModListData buildUniqueList() {
List<ModFile> uniqueModList;
List<ModFile> uniqueLibListWithVersion;
private static final Logger LOGGER = LogUtils.getLogger();
public static UniqueModListData buildUniqueList(List<ModFile> modFiles) {
// Collect mod files by module name. This will be used for deduping purposes
final Map<String, List<ModFile>> modFilesByFirstId = modFiles.stream()
.filter(mf -> mf.getModFileInfo() != null)
@@ -49,12 +40,12 @@ public class UniqueModListBuilder {
.collect(groupingBy(UniqueModListBuilder::getModId));
// Select the newest by artifact version sorting of non-unique files thus identified
uniqueModList = modFilesByFirstId.entrySet().stream()
final List<ModFile> uniqueModList = modFilesByFirstId.entrySet().stream()
.map(UniqueModListBuilder::selectNewestModInfo)
.toList();
// Select the newest by artifact version sorting of non-unique files thus identified
uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream()
final List<ModFile> uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream()
.map(UniqueModListBuilder::selectNewestModInfo)
.toList();
@@ -66,12 +57,10 @@ public class UniqueModListBuilder {
.collect(groupingBy(IModInfo::getModId));
// Transform to the full lib id list
final Map<String, List<ModFile>> versionedLibIds = uniqueLibListWithVersion.stream()
final List<List<ModFile>> versionedLibs = uniqueLibListWithVersion.stream()
.map(UniqueModListBuilder::getModId)
.collect(Collectors.toMap(
Function.identity(),
libFilesWithVersionByModuleName::get
));
.map(libFilesWithVersionByModuleName::get)
.toList();
// Its theoretically possible that some mod has somehow moved an id to a secondary place, thus causing a dupe.
// We can't handle this
@@ -84,24 +73,24 @@ public class UniqueModListBuilder {
)).toList();
if (!dupedModErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate mods:\n{}", dupedModErrors.stream().collect(joining("\n")));
LOGGER.error(LOADING, "Found duplicate mods:\n{}", String.join("\n", dupedModErrors));
throw new EarlyLoadingException("Duplicate mods found", null, dupedModErrors.stream()
.map(s -> new EarlyLoadingException.ExceptionData(s))
.map(EarlyLoadingException.ExceptionData::new)
.toList());
}
final List<String> dupedLibErrors = versionedLibIds.values().stream()
.filter(modFiles -> modFiles.size() > 1)
final List<String> dupedLibErrors = versionedLibs.stream()
.filter(libModFiles -> libModFiles.size() > 1)
.map(mods -> String.format("\tLibrary: '%s' from files: %s",
getModId(mods.getFirst()),
mods.stream().map(ModFile::getFileName).collect(joining(", "))
)).toList();
if (!dupedLibErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate plugins or libraries:\n{}", dupedLibErrors.stream().collect(joining("\n")));
LOGGER.error(LOADING, "Found duplicate plugins or libraries:\n{}", String.join("\n", dupedLibErrors));
throw new EarlyLoadingException("Duplicate plugins or libraries found", null, dupedLibErrors.stream()
.map(s -> new EarlyLoadingException.ExceptionData(s))
.map(EarlyLoadingException.ExceptionData::new)
.toList());
}
@@ -122,7 +111,7 @@ public class UniqueModListBuilder {
modInfoList.sort(Comparator.comparing(UniqueModListBuilder::getVersion).reversed());
LOGGER.debug("Selected file {} for modid {} with version {}", modInfoList.getFirst().getFileName(), fullList.getKey(), getVersion(modInfoList.getFirst()));
}
return modInfoList.get(0);
return modInfoList.getFirst();
}
private static ArtifactVersion getVersion(final ModFile mf) {
@@ -130,7 +119,7 @@ public class UniqueModListBuilder {
return mf.getJarVersion();
}
return mf.getModInfos().get(0).getVersion();
return mf.getModInfos().getFirst().getVersion();
}
private static String getModId(ModFile modFile) {
@@ -138,7 +127,7 @@ public class UniqueModListBuilder {
return modFile.getSecureJar().name();
}
return modFile.getModFileInfo().getMods().get(0).getModId();
return modFile.getModFileInfo().getMods().getFirst().getModId();
}
public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {}
@@ -54,12 +54,16 @@ public abstract class AbstractModProvider implements IModProvider {
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) {
var debug = path.toString();
if (debug.equals("/"))
debug = path.toUri().toString();
var mjm = new ModJarMetadata();
SecureJar sj = null;
try {
sj = SecureJar.from(jar -> loadMetaFromJar(jar, mjm), path);
} catch (Throwable t) {
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + path + "\" - " + t.getMessage()));
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + debug + "\" - " + t.getMessage()));
}
IModFile mod;
@@ -68,7 +72,7 @@ public abstract class AbstractModProvider implements IModProvider {
type = defaultType;
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, debug);
mod = new ModFile(sj, this, ModFileParser::modsTomlParser);
// ModJarMetadata is only used when loading mods.toml mods as ModJarMetadata
mjm.setModFile(mod);
@@ -77,17 +81,17 @@ public abstract class AbstractModProvider implements IModProvider {
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);
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, debug);
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));
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + debug));
return new IModLocator.ModFileOrException(mod, null);
}
private static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) {
protected static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) {
var info = jar.moduleDataProvider().open(MODULE_INFO).orElse(null);
if (info != null) {
try {
@@ -145,6 +149,12 @@ public abstract class AbstractModProvider implements IModProvider {
public <T> Optional<T> getConfigElement(String... key) {
return Optional.empty();
}
@Override
public List<? extends IConfigurable> getConfigList(String key) {
return Collections.emptyList();
}
@Override
public List<? extends IConfigurable> getConfigList(String... key) {
return Collections.emptyList();
@@ -74,7 +74,8 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
var ret = new ArrayList<ModFileOrException>();
for (var path : claimed) {
// Filter out anything found by the ServiceLoader
if (!ModDirTransformerDiscoverer.isServiceProvider(path))
if (!ModDirTransformerDiscoverer.isServiceProvider(path)
&& !JarInJarDependencyLocator.isOption(path))
ret.add(createMod(path));
}
return ret;
@@ -107,7 +108,7 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
return Path.of(URI.create(str));
}
private static Path getPathFromResource(ClassLoader cl, String resource) {
static Path getPathFromResource(ClassLoader cl, String resource) {
var url = cl.getResource(resource);
if (url == null)
return null;
@@ -5,22 +5,39 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.collect.ImmutableMap;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.TypesafeMap;
import net.minecraftforge.fml.loading.EarlyLoadingException;
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.locating.IDependencyLocator;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import net.minecraftforge.forgespi.locating.IModFile.Type;
import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier;
import net.minecraftforge.jarjar.metadata.ContainedJarMetadata;
import net.minecraftforge.jarjar.metadata.ContainedVersion;
import net.minecraftforge.jarjar.metadata.MetadataIOHandler;
import net.minecraftforge.jarjar.selection.JarSelector;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.module.ModuleDescriptor;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
@@ -28,14 +45,20 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApiStatus.Internal
public class JarInJarDependencyLocator extends AbstractModProvider implements IDependencyLocator {
private static final String ROIMFS = "roimfs";
private static final String COLOR_CODE = "\u00a7";
private static final String RESET = COLOR_CODE + "r";
private static final String YELLOW = COLOR_CODE + "e";
@@ -43,32 +66,238 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
private static final String GREEN = COLOR_CODE + "2";
private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker MARKER = MarkerFactory.getMarker("JAR-JAR"); // LogMarkers.SCAN;
private static final Map<Path, Option> OPTIONS = new HashMap<>();
private static volatile boolean optionsLoaded = false;
private static final Attributes.Name MIXIN_CONFIGS_ATTR = new Attributes.Name("MixinConfigs");
private static final Attributes.Name MIXIN_CONNECTOR_ATTR = new Attributes.Name("MixinConnector");
private static final ContainedJarMetadata MIXIN_EXTRAS_DEPENDENCY = makeMixinExtraDependency();
private static ContainedJarMetadata makeMixinExtraDependency() {
VersionRange range = null;
try {
range = VersionRange.createFromVersionSpec("[0,)");
} catch (InvalidVersionSpecificationException e) {
throw new RuntimeException("Failed to create version range for mixinextras-forge dependency", e);
}
return new ContainedJarMetadata(
new ContainedJarIdentifier("io.github.llamalad7", "mixinextras-forge"),
new ContainedVersion(range, null),
null, false
);
}
@Override
public String name() {
return "JarInJar";
}
private int fsID = 0;
private synchronized int nextId() {
return fsID++;
}
@Override
public List<IModFile> scanMods(Iterable<IModFile> loadedMods) {
final List<IModFile> sources = new ArrayList<>();
loadedMods.forEach(sources::add);
var mods = new ArrayList<IModFile>();
loadedMods.forEach(mods::add);
var dependenciesToLoad = JarSelector.detectAndSelect(
sources,
this::loadResourceFromModFile,
this::loadModFileFrom,
this::identifyMod,
this::exception
);
var selector = new Selector(mods);
if (dependenciesToLoad.isEmpty()) {
// Add a synthetic Mixin-Extras dependency if we detect anyone using Mixin
if (anyMixinsLoaded(mods)) {
if (!selector.isRequired(MIXIN_EXTRAS_DEPENDENCY.identifier()))
selector.addRequirement(MIXIN_EXTRAS_DEPENDENCY);
} else if (selector.entries.size() == mods.size()) {
LOGGER.info("No dependencies to load found. Skipping!");
return Collections.emptyList();
}
LOGGER.info("Found {} dependencies adding them to mods collection", dependenciesToLoad.size());
return dependenciesToLoad;
loadOptions();
// Ideally, the json would be in order so we only have to loop once. But its written this way just in case.
var seen = new HashSet<Option>();
var added = false;
do {
added = false;
for (var entry : OPTIONS.values()) {
if (seen.contains(entry) || !selector.isRequired(entry.meta.identifier()))
continue;
seen.add(entry);
entry.addTo(selector);
if (entry.deps != null && !entry.deps.isEmpty()) {
added = true;
for (var dep : entry.deps)
selector.addRequirement(dep);
}
}
} while (added);
var selected = selector.select();
if (LOGGER.isDebugEnabled()) {
var ids = new TreeMap<String, List<Entry>>();
for (var entry : selector.entries.values()) {
if (entry != FAILED && entry.coord != null)
ids.computeIfAbsent(entry.coord, id -> new ArrayList<>()).add(entry);
}
for (var entry : ids.entrySet()) {
LOGGER.info(MARKER, "JarJar Candidated for {}", entry.getKey());
Collections.sort(entry.getValue());
for (var option : entry.getValue())
LOGGER.info(MARKER, "\t{}{}", selected.contains(option) ? '*' : ' ', option);
}
}
if (selected.isEmpty()) {
LOGGER.info("No dependencies to load found. Skipping!");
return Collections.emptyList();
}
/* Since Java 11, the JRE decompresses all zip files to memory when getting a ByteChannel for them.
* JarJar only targets Minecraft 1.18+ which is Java17+ Which means we can exploit the fact that
* these are Disjointed file systems, and close all unselected libraries.
*
* https://github.com/openjdk/jdk11u/blob/25a9b9e5594e88c9e1e66f95c7ca45d5a9da8854/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java#L703
*
* Combined with the fact that the JarJarFileSystem has always simply called into FileSystems.newFileSystem for its wrapped targets.
* https://github.com/MinecraftForge/JarJar/blame/b39b2051439c81519d826d38898778bf3081356f/src/main/java/net/minecraftforge/jarjar/nio/pathfs/PathFileSystem.java#L38
*
* This effectively means that JarJar has ALWAYS been a wrapper around in-memory copies of every jar it scans.
*
* It also never closes these FileSystems, which potentially means they are leaked if the GC can't inherently GC them.
*
* Ideally we would extract these contained jars to a temp folder, so that we can use the nice optimizations Java has for ZipFile/JarFile.
* But in order to do that we would need to write the file to a place that could potentially have conflicts.
* To resolve those conflicts we should take a hint out of maven/gradle/minecraft's book and key the filepath based on a hash of the file being extracted.
* However, because that hash is no available in existing metadata we would need to re-calculate it.
*
* To do it in an efficient way we I needed to be able to share the single opened FileSystem with both the SecureJar implementation, and with our recursive search.
* So I use my new ReadOnlyInMemoryFileSystem which is specifically designed to use the same backing array for the JarInJar search as it does with the resulting dependency
* selected SecureJars.
*
* This means that if we wanted to we could rather efficiently calculate a hash for extracting the file. However, it also means that we don't have to extract to file to
* support ZipFileSystem caching properly. So as long as we are okay with not using the JRE's optimized ZipFile implementation, or we want to support legacy JarInJar metadata,
* using this efficient in memory file system is the best option performance wise. Extracting the files during launch without an efficient caching/unique identifier system
* would incur a lot of Disc IO which can be super slow depending on your setup.
*
* So, it is a stated goal of our future re-write to extract files into a cache directory to gain the benefits of JRE optimizations, using a FileSystem much simpler then
* the existing JarInJarFileSystem is good enough.
*/
// Lets close all unselected FileSystems
var wasSelected = new HashSet<>(selected);
for (var entry : selector.entries.values())
entry.cleanup(wasSelected.contains(entry));
LOGGER.info(MARKER, "Found {} dependencies adding them to mods collection", selected.size());
var ret = new ArrayList<IModFile>(selected.size());
// Now lets build the actual mod files
for (var entry : selected) {
try {
var root = entry.getFinalPath();
var mod = createMod(root, false, entry.type.name());
if (mod.ex() != null)
throw fail("Failed to load JarInJar file " + entry, mod.ex());
ret.add(mod.file());
} catch (EarlyLoadingException e) {
throw e;
} catch (Throwable e) {
throw fail("Failed to load JarInJar file " + entry, e);
}
}
return ret;
}
private static Boolean anyMixinsLoaded = null;
private static boolean anyMixinsLoaded(List<IModFile> mods) {
var ret = anyMixinsLoaded;
if (ret != null) return ret;
if (!FMLEnvironment.production
&& Launcher.INSTANCE.blackboard().get(TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "isMixinEnabledInDev", Boolean.class)).orElse(false)) {
anyMixinsLoaded = true;
return true;
}
for (var mod : mods) {
var attributes = mod.getSecureJar().moduleDataProvider().getManifest().getMainAttributes();
if (attributes.getValue(MIXIN_CONFIGS_ATTR) != null || attributes.getValue(MIXIN_CONNECTOR_ATTR) != null) {
anyMixinsLoaded = true;
return true;
}
}
anyMixinsLoaded = false;
return false;
}
private record Options(List<OptionMetadata> options) {}
private record OptionMetadata(String resource, Type layer, String id, List<ContainedJarMetadata> deps, ContainedJarMetadata meta, boolean nested) {}
private static void loadOptions() {
if (optionsLoaded)
return;
synchronized (OPTIONS) {
if (optionsLoaded)
return;
optionsLoaded = true;
var self = JarInJarDependencyLocator.class;
try (var stream = self.getModule().getResourceAsStream("/jarjar_options.json")) {
if (stream == null) {
LOGGER.error(MARKER, "Failed to find jarjar_options.json");
return;
}
var meta = MetadataIOHandler.getGson().fromJson(new InputStreamReader(stream), Options.class);
//var meta = MetadataIOHandler.fromStream(stream).orElse(null);
if (meta == null) {
LOGGER.error(MARKER, "Corrupted jarjar_options.json");
return;
}
for (var jar : meta.options()) {
Path path = ClasspathLocator.getPathFromResource(self.getClassLoader(), jar.resource());
if (path == null) {
LOGGER.error(MARKER, "Failed to find JarJar option for {}", jar.resource());
continue;
}
LOGGER.debug(MARKER, "Found JarJar Option: {}", path.toAbsolutePath());
if (jar.nested())
OPTIONS.put(path, new NestedOption(jar.id(), path, jar.layer(), jar.meta(), jar.deps()));
else
OPTIONS.put(path, new Option(jar.id(), path, jar.layer(), jar.meta(), jar.deps()));
}
} catch (Throwable e) {
LOGGER.error(MARKER, "Failed to read JarJar Options file", e);
}
}
}
static boolean isOption(Path path) {
loadOptions();
return OPTIONS.containsKey(path);
}
private static EarlyLoadingException fail(String message, @Nullable Throwable cause) {
LOGGER.error(MARKER, message);
return new EarlyLoadingException(message, cause, Collections.emptyList());
}
@Override
@@ -76,89 +305,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
return IModFile.Type.GAMELIBRARY.name();
}
protected Optional<IModFile> loadModFileFrom(IModFile file, Path path) {
try {
final Path pathInModFile = file.findResource(path.toString());
final URI filePathUri = new URI("jij:" + (pathInModFile.toAbsolutePath().toUri().getRawSchemeSpecificPart())).normalize();
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, false, modType).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());
exception.initCause(e);
throw exception;
}
}
protected EarlyLoadingException exception(Collection<JarSelector.ResolutionFailureInformation<IModFile>> failedDependencies) {
final List<EarlyLoadingException.ExceptionData> errors = failedDependencies.stream()
.filter(entry -> !entry.sources().isEmpty()) //Should never be the case, but just to be sure
.map(JarInJarDependencyLocator::buildExceptionData)
.toList();
return new EarlyLoadingException(failedDependencies.size() + " Dependency restrictions were not met.", null, errors);
}
@NotNull
private static EarlyLoadingException.ExceptionData buildExceptionData(JarSelector.ResolutionFailureInformation<IModFile> entry) {
return new EarlyLoadingException.ExceptionData(
getErrorTranslationKey(entry),
entry.identifier().group() + ":" + entry.identifier().artifact(),
entry.sources()
.stream()
.flatMap(JarInJarDependencyLocator::getModWithVersionRangeStream)
.map(JarInJarDependencyLocator::formatError)
.collect(Collectors.joining(", "))
);
}
@NotNull
private static String getErrorTranslationKey(JarSelector.ResolutionFailureInformation<IModFile> entry) {
return entry.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ?
"fml.dependencyloading.conflictingdependencies" :
"fml.dependencyloading.mismatchedcontaineddependencies";
}
@NotNull
private static Stream<ModWithVersionRange> getModWithVersionRangeStream(JarSelector.SourceWithRequestedVersionRange<IModFile> file) {
return file.sources()
.stream()
.map(IModFile::getModFileInfo)
.flatMap(modFileInfo -> modFileInfo.getMods().stream())
.map(modInfo -> new ModWithVersionRange(modInfo, file.requestedVersionRange(), file.includedVersion()));
}
protected Optional<InputStream> loadResourceFromModFile(IModFile modFile, Path path) {
try {
var pathInModFile = modFile.findResource(path.toString());
if (!Files.exists(pathInModFile)) {
LOGGER.debug("Failed to load resource {} from {}, it does not contain dependency information.", path, modFile.getFileName());
return Optional.empty();
}
return Optional.of(Files.newInputStream(pathInModFile));
} catch (Exception e) {
LOGGER.error("Failed to load resource {} from mod {}, cause {}", path, modFile.getFileName(), e);
return Optional.empty();
}
}
@NotNull
private static String formatError(ModWithVersionRange modWithVersionRange){
return YELLOW + modWithVersionRange.modInfo().getModId() + RESET + " - " +
RED + modWithVersionRange.versionRange().toString() + RESET + " - " +
GREEN + modWithVersionRange.artifactVersion().toString() + RESET;
}
protected String identifyMod(IModFile modFile) {
protected static String identifyMod(IModFile modFile) {
if (modFile.getModFileInfo() != null && !modFile.getModInfos().isEmpty())
return modFile.getModInfos().stream().map(IModInfo::getModId).collect(Collectors.joining());
@@ -169,5 +316,377 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
return modFile.getFileName();
}
private record ModWithVersionRange(IModInfo modInfo, VersionRange versionRange, ArtifactVersion artifactVersion) {}
private static final Entry FAILED = new Entry("FAILED ENTRY", Path.of(""), Type.LIBRARY, null);
private static sealed class Entry implements Comparable<Entry> {
final String id;
final Path path;
final Type type;
final @Nullable String coord;
private Entry(String id, Path path, Type type, @Nullable String coord) {
this.id = id;
this.path = path;
this.type = type;
this.coord = coord;
}
Path getFinalPath() {
return path;
}
void cleanup(boolean selected) {
}
@Override
public String toString() {
if (path.getFileName() == null)
return path.toUri().toString();
return path.getFileName().toString();
}
@Nullable
Path getResource(String path) {
return null;
}
@Override
public int compareTo(Entry o) {
return o.toString().compareTo(toString());
}
}
private static final class ModEntry extends Entry {
private final IModFile mod;
ModEntry(IModFile mod) {
super(identifyMod(mod), mod.getFilePath(), mod.getType(), null);
this.mod = mod;
}
@Override
@Nullable
Path getResource(String path) {
return mod.findResource(path);
}
}
private static sealed class Option extends Entry {
final ContainedJarMetadata meta;
final List<ContainedJarMetadata> deps;
private Option(String id, Path path, Type type, ContainedJarMetadata meta, List<ContainedJarMetadata> deps) {
super(id, path, type, meta.identifier().group() + ':' + meta.identifier().artifact());
this.meta = meta;
this.deps = deps;
}
public void addTo(Selector selector) {
selector.option(this, meta);
}
}
private static final class NestedOption extends Option {
private FileSystem zip;
private Path root;
private NestedOption(String id, Path path, Type type, ContainedJarMetadata meta, List<ContainedJarMetadata> deps) {
super(id, path, type, meta, deps);
}
@Override
public void addTo(Selector selector) {
super.addTo(selector);
selector.add(this);
}
@Override
void cleanup(boolean selected) {
if (this.zip != null) {
try {
zip.close();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to close unselected FileSystem {}", this, e);
}
}
}
@Nullable
Path getResource(String path) {
if (zip == null) {
try {
this.zip = FileSystems.newFileSystem(this.path);
this.root = zip.getRootDirectories().iterator().next();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to open FileSystem for option root {}", this, e);
return null;
}
}
var target = root.resolve(path);
if (Files.exists(target))
return target;
return null;
}
}
private static final class Nested extends Entry {
private final Entry parent;
private final String nestedPath;
private final Path zipPath;
Nested(String id, Path path, Type type, String coords, Entry parent, String nestedPath, Path zipPath) {
super(id, path, type, coords);
this.parent = parent;
this.nestedPath = nestedPath;
this.zipPath = zipPath;
}
/*
* Due to a bug in Mixin, anything that is not on the DefaultFileSystem MUST be a directory.
* Or else it can't resolve resources correctly. So for anything we put on the roimfs we need
* to return the nested zip file system.
*
* This will be an annoying to backport, but we can cross that bridge when we come to it.
*
* See: https://github.com/SpongePowered/Mixin/blob/4053421aa10aaac6127d969028a29c94fe3054f6/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java#L102
*/
@Override
public Path getFinalPath() {
return zipPath;
}
@Override
void cleanup(boolean selected) {
if (selected)
return;
LOGGER.info(MARKER, "Closeing unselected FileSystem {}", this);
try {
zipPath.getFileSystem().close();
path.getFileSystem().close();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to close unselected FileSystem {}", this, e);
}
}
@Override
@Nullable
Path getResource(String path) {
return zipPath.resolve(path);
}
@Override
public String toString() {
return parent + "!/" + nestedPath;
}
}
private record Key(Entry parent, String path) {}
private final class Selector extends JarSelector<Entry> {
private final HashMap<Key, Entry> entries = new HashMap<>();
private final HashMap<Entry, HashMap<String, String>> children = new HashMap<>();
private Selector(Iterable<IModFile> mods) {
for (var mod : mods)
this.force(new ModEntry(mod));
}
@Override
public void force(Entry entry) {
super.force(entry);
entries.put(new Key(entry, ""), entry);
}
@Override
public void option(Entry entry, ContainedJarMetadata meta) {
super.option(entry, meta);
entries.put(new Key(entry, ""), entry);
}
@Override
public void add(Entry entry) {
super.add(entry);
entries.put(new Key(entry, ""), entry);
}
@Override
@Nullable
protected InputStream getResource(Entry source, String path) {
try {
Path target = source.getResource(path);
if (target == null || !Files.exists(target)) {
LOGGER.debug(MARKER, "Failed to load resource {} from {}, it does not contain dependency information.", path, source);
return null;
}
// Read the metadata file and store identifiers so we can group them later.
if (JarSelector.CONTAINED_JARS_METADATA_PATH.equals(path)) {
try (var is = Files.newInputStream(target)) {
var meta = MetadataIOHandler.fromStream(is).orElse(null);
if (meta == null)
return Files.newInputStream(target);
var children = new HashMap<String, String>();
for (var child : meta.jars())
children.put(child.path().replace('\\', '/'), child.identifier().group() + ':' + child.identifier().artifact());
this.children.put(source, children);
}
}
return Files.newInputStream(target);
} catch (Exception e) {
LOGGER.error(MARKER, "Failed to load resource {} from {}, cause {}", path, source, e);
return null;
}
}
@Override
protected Entry getNested(Entry source, String path) {
var cleaned = path.replace('\\', '/');
var key = new Key(source, cleaned);
var entry = entries.get(key);
if (entry == null) {
entry = createNested(source, path, cleaned);
if (entry == null)
entry = FAILED;
entries.put(key, entry);
}
return entry == FAILED ? null : entry;
}
private Entry createNested(Entry source, String path, String cleaned) {
var targetPath = source.getResource(path);
if (targetPath == null || !Files.isRegularFile(targetPath))
return null;
Path roimfsPath = null;
Path zipPath = null;
try {
// Lets copy the uncompressed file to memory, and then create a ReadOnlyInMemorryFileSystem for it, this allows us to reference it by URI.
// Which is needed because a lot of things require navigation via URI.
// And ZipFileSystem only caches the FileSystem instance when accessed via URI.
byte[] data = Files.readAllBytes(targetPath);
String filename = targetPath.getFileName().toString();
URI uri = new URI(ROIMFS, "jar-jar-" + nextId() + "/" + filename, null);
var roimfs = FileSystems.newFileSystem(uri, Collections.singletonMap("data", data));
roimfsPath = roimfs.getPath(filename);
var zip = FileSystems.newFileSystem(new URI("jar:" + roimfsPath.toUri()), Collections.emptyMap());
zipPath = zip.getRootDirectories().iterator().next(); // Get first root, which on ZipFileSystem is the only root
} catch (IOException | URISyntaxException e) {
LOGGER.error(MARKER, "Failed to create FileSystem for nested jar {}", source, e);
return null;
}
var mf = new Manifest();
var mfPath = zipPath.resolve(JarFile.MANIFEST_NAME);
if (Files.exists(mfPath)) {
try (var is = Files.newInputStream(mfPath)) {
mf = new Manifest(is);
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read manifest from {}", source, e);
}
}
IModFile.Type type = null;
String id = null;
var tomlPath = zipPath.resolve(MODS_TOML);
if (Files.exists(tomlPath)) {
var cfg = FileConfig.builder(tomlPath).build();
cfg.load();
cfg.close();
if (cfg.getOrElse("mods", null) instanceof Collection collection) {
@SuppressWarnings("unchecked")
var mods = (Collection<UnmodifiableConfig>)collection;
if (!mods.isEmpty()) {
var first = mods.iterator().next();
var modId = first.getOrElse("modId", null);
if (modId instanceof String str)
id = str;
}
}
var value = mf.getMainAttributes().getValue(ModFile.TYPE);
if (value != null)
type = IModFile.Type.valueOf(value);
else
type = IModFile.Type.MOD;
} else {
var value = mf.getMainAttributes().getValue(ModFile.TYPE);
if (value != null)
type = IModFile.Type.valueOf(value);
else {
// No mods.toml, no entry value, so decide based on the container's type
if (source.type == IModFile.Type.LIBRARY || source.type == IModFile.Type.LANGPROVIDER)
type = IModFile.Type.LIBRARY;
else
type = IModFile.Type.GAMELIBRARY;
}
}
if (id == null) {
var modulePath = zipPath.resolve(MODULE_INFO);
if (Files.exists(modulePath)) {
try (var is = Files.newInputStream(modulePath)) {
var module = ModuleDescriptor.read(is);
id = module.name();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read module-info.class from {}", source, e);
}
}
}
if (id == null)
id = mf.getMainAttributes().getValue("Automatic-Module-Name");
if (id == null)
id = Path.of(path).getFileName().toString();
String coords = null;
var child = this.children.get(source);
if (child != null)
coords = child.get(cleaned);
return new Nested(id, roimfsPath, type, coords, source, cleaned, zipPath);
}
@Override
protected String getIdentifier(Entry entry) {
return entry.id;
}
@Override
protected Throwable getFailureException(Collection<ResolutionFailureInformation<Entry>> failures) {
var errors = new ArrayList<ExceptionData>();
for (var failure : failures) {
var message = failure.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ? "fml.dependencyloading.conflictingdependencies" : "fml.dependencyloading.mismatchedcontaineddependencies";
var joiner = new StringJoiner(", ");
for (var source : failure.sources()) {
String paths = null;
if (source.sources().size() == 0) {
paths = "[No Sources]";
} else if (source.sources().size() == 1) {
var entry = source.sources().iterator().next();
paths = entry.toString();
} else {
var j = new StringJoiner(", ", "[", "]");
for (var entry : source.sources())
j.add(entry.toString());
paths = j.toString();
}
var error = YELLOW + paths + RESET + " - " +
RED + source.requestedVersionRange() + RESET + " - " +
GREEN + source.includedVersion() + RESET;
joiner.add(error);
}
errors.add(new ExceptionData(message, failure.identifier().group() + ":" + failure.identifier().artifact(), joiner.toString()));
}
return new EarlyLoadingException(failures.size() + " Dependency restrictions were not met.", null, errors);
}
}
}
@@ -5,7 +5,6 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.collect.ImmutableList;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IModuleLayerManager;
@@ -35,41 +34,36 @@ import java.util.ServiceLoader;
import java.util.stream.Collectors;
@ApiStatus.Internal
public class ModDiscoverer {
private static final Logger LOGGER = LogUtils.getLogger();
private final ServiceLoader<IModLocator> modLocators;
private final ServiceLoader<IDependencyLocator> dependencyLocators;
private final List<IModLocator> modLocatorList;
private final List<IDependencyLocator> dependencyLocatorList;
public final class ModDiscoverer {
private ModDiscoverer() {}
public ModDiscoverer(Map<String, ?> arguments) {
private static final Logger LOGGER = LogUtils.getLogger();
@SuppressWarnings("removal")
public static ModValidator discoverMods(Map<String, ?> arguments) {
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), v->ModsFolderLocator::new);
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{}));
final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow();
modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
modLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> modLocators, sce->LOGGER.error("Failed to load mod locator list", sce)).collect(Collectors.toList());
ServiceLoader<IModLocator> modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
ServiceLoader<IDependencyLocator> dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
List<IModLocator> modLocatorList = ServiceLoaderUtils.streamWithErrorHandling(modLocators, sce -> LOGGER.error("Failed to load mod locator list", sce)).toList();
for (IModLocator iModLocator : modLocatorList) {
iModLocator.initArguments(arguments);
}
dependencyLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> dependencyLocators, sce->LOGGER.error("Failed to load dependency locator list", sce)).collect(Collectors.toList());
List<IDependencyLocator> dependencyLocatorList = ServiceLoaderUtils.streamWithErrorHandling(dependencyLocators, sce -> LOGGER.error("Failed to load dependency locator list", sce)).toList();
for (IDependencyLocator l : dependencyLocatorList) {
l.initArguments(arguments);
}
if (LOGGER.isDebugEnabled(LogMarkers.CORE))
{
if (LOGGER.isDebugEnabled(LogMarkers.CORE)) {
LOGGER.debug(LogMarkers.CORE, "Found Mod Locators : {}", modLocatorList.stream()
.map(modLocator -> "(%s:%s)".formatted(modLocator.name(),
modLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
.map(modLocator -> "(%s:%s)".formatted(modLocator.name(),
modLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
LOGGER.debug(LogMarkers.CORE, "Found Dependency Locators : {}", dependencyLocatorList.stream()
.map(dependencyLocator -> "(%s:%s)".formatted(dependencyLocator.name(),
dependencyLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
.map(dependencyLocator -> "(%s:%s)".formatted(dependencyLocator.name(),
dependencyLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
}
}
@SuppressWarnings("removal")
public ModValidator discoverMods() {
LOGGER.debug(LogMarkers.SCAN,"Scanning for mods and other resources to load. We know {} ways to find mods", modLocatorList.size());
List<ModFile> loadedFiles = new ArrayList<>();
List<EarlyLoadingException.ExceptionData> discoveryErrorData = new ArrayList<>();
@@ -117,7 +111,7 @@ public class ModDiscoverer {
}
LOGGER.debug(LogMarkers.SCAN, "Locator {} found {} valid mod files", locator, locatedFiles.size());
handleLocatedFiles(loadedFiles, locatedFiles);
handleLocatedFiles(loadedFiles, locatedFiles, locator);
} catch (InvalidModFileException imfe) {
// We don't generally expect this exception, since it should come from the candidates stream above and be handled in the Locator, but just in case.
LOGGER.error(LogMarkers.SCAN, "Locator {} found an invalid mod file {}", locator, imfe.getBrokenFile(), imfe);
@@ -131,8 +125,7 @@ public class ModDiscoverer {
//First processing run of the mod list. Any duplicates will cause resolution failure and dependency loading will be skipped.
Map<IModFile.Type, List<ModFile>> modFilesMap = new EnumMap<>(IModFile.Type.class);
try {
final UniqueModListBuilder modsUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
final UniqueModListBuilder.UniqueModListData uniqueModsData = modsUniqueListBuilder.buildUniqueList();
final UniqueModListBuilder.UniqueModListData uniqueModsData = UniqueModListBuilder.buildUniqueList(loadedFiles);
//Grab the temporary results.
//This allows loading to continue to a base state, in case dependency loading fails.
@@ -152,14 +145,10 @@ public class ModDiscoverer {
for (IDependencyLocator locator : dependencyLocatorList) {
try {
LOGGER.debug(LogMarkers.SCAN,"Trying locator {}", locator);
final List<IModFile> locatedMods = ImmutableList.copyOf(loadedFiles);
final List<IModFile> locatedMods = List.copyOf(loadedFiles);
var locatedFiles = locator.scanMods(locatedMods);
if (locatedFiles.stream().anyMatch(file -> !(file instanceof ModFile))) {
LOGGER.error(LogMarkers.SCAN, "A dependency locator returned a file which is not a ModFile instance!. They will be skipped!");
}
handleLocatedFiles(loadedFiles, locatedFiles);
handleLocatedFiles(loadedFiles, locatedFiles, locator);
}
catch (EarlyLoadingException exception) {
LOGGER.error(LogMarkers.SCAN, "Failed to load dependencies with locator {}", locator, exception);
@@ -169,8 +158,7 @@ public class ModDiscoverer {
//Second processing run of the mod list. Any duplicates will cause resolution failure and only the mods list will be loaded.
try {
final UniqueModListBuilder modsAndDependenciesUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
final UniqueModListBuilder.UniqueModListData uniqueModsAndDependenciesData = modsAndDependenciesUniqueListBuilder.buildUniqueList();
final UniqueModListBuilder.UniqueModListData uniqueModsAndDependenciesData = UniqueModListBuilder.buildUniqueList(loadedFiles);
//We now only need the mod files map, not the list.
modFilesMap = uniqueModsAndDependenciesData.modFiles().stream()
@@ -193,11 +181,14 @@ public class ModDiscoverer {
return validator;
}
private static void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles) {
var locatedModFiles = locatedFiles.stream().filter(ModFile.class::isInstance).map(ModFile.class::cast).toList();
for (IModFile mf : locatedModFiles) {
LOGGER.info(LogMarkers.SCAN, "Found mod file {} of type {} with provider {}", mf.getFileName(), mf.getType(), mf.getProvider());
private static void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles, final Object locator) {
for (IModFile mf : locatedFiles) {
if (mf instanceof ModFile modFile) {
LOGGER.info(LogMarkers.SCAN, "Found mod file {} of type {} with provider {}", mf.getFileName(), mf.getType(), mf.getProvider());
loadedFiles.add(modFile);
} else {
LOGGER.error(LogMarkers.SCAN, "Skipping mod file {} found by {}, as it was not a ModFile instance!", mf.getFileName(), locator);
}
}
loadedFiles.addAll(locatedModFiles);
}
}
@@ -21,13 +21,13 @@ import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.slf4j.Logger;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@@ -39,18 +39,18 @@ import java.util.jar.Manifest;
public class ModFile implements IModFile {
private static final Logger LOGGER = LogUtils.getLogger();
private final String jarVersion;
private final ModFileFactory.ModFileInfoParser parser;
private Map<String, Object> fileProperties;
private List<IModLanguageProvider> loaders;
private Throwable scanError;
private final SecureJar jar;
private final Type modFileType;
private final IModProvider provider;
private IModFileInfo modFileInfo;
private final IModFileInfo modFileInfo;
private ModFileScanData fileModFileScanData;
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;
@@ -62,12 +62,11 @@ public class ModFile implements IModFile {
public ModFile(final SecureJar jar, final IModProvider provider, final ModFileFactory.ModFileInfoParser parser, String type) {
this.provider = provider;
this.jar = jar;
this.parser = parser;
var manifest = this.jar.moduleDataProvider().getManifest();
modFileType = Type.valueOf(type);
jarVersion = Optional.ofNullable(manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION)).orElse("0.0NONE");
this.modFileInfo = ModFileParser.readModList(this, this.parser);
this.modFileInfo = ModFileParser.readModList(this, parser);
}
@Override
@@ -94,17 +93,47 @@ public class ModFile implements IModFile {
return modFileInfo.getMods();
}
/** @deprecated Use {@link #getAccessTransformers()} instead */
@Deprecated(forRemoval = true, since = "1.21.11")
public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(Files.exists(accessTransformer) ? accessTransformer : null);
return Optional.ofNullable(accessTransformer);
}
public List<Path> getAccessTransformers() {
return this.accessTransformers;
}
public boolean identifyMods() {
this.modFileInfo = ModFileParser.readModList(this, this.parser);
if (this.modFileInfo == null) return this.getType() != Type.MOD;
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFileName(), this.modFileInfo.requiredLanguageLoaders());
this.coreMods = ModFileParser.getCoreMods(this);
this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath()));
this.accessTransformer = findResource("META-INF", "accesstransformer.cfg");
if (!this.coreMods.isEmpty())
LOGGER.warn("Mod file {} contains javascript coremods! JS CoreMods are deprecated and will be removed in a future release. Consider using Mixin or ModLauncher transformers.", this.getFileName());
for (var mi : this.coreMods)
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);
}
return true;
}
@@ -179,12 +208,28 @@ public class ModFile implements IModFile {
@Override
public String toString() {
return "Mod File: " + Objects.toString(this.jar.getPrimaryPath());
var path = getFilePath();
return "Mod File: " + path == null ? "null" : path.toUri().toString();
}
@Override
public String getFileName() {
return getFilePath().getFileName().toString();
// This is only used for debugging, so lets try and make it a useful debug
var path = getFilePath();
var filename = path.getFileName();
// ZipFileSystem toString will return the outer file path
var ret = filename == null ? path.getFileSystem().toString() : filename.toString();
// If it's a directory on the default file system, return the full path
if (Files.isDirectory(path) && path.getFileSystem() == FileSystems.getDefault())
ret = path.toAbsolutePath().toString();
// If we are in a FileSystem 'root' like UnionFS, return the full uri
if (ret.isEmpty() || ret.equals("/"))
ret = path.toUri().toString();
return ret;
}
@Override
@@ -264,7 +264,7 @@ public class ModFileInfo implements IModFileInfo, IConfigurable {
@Override
public String versionString() {
return getMods().get(0).getVersion().toString();
return getMods().getFirst().getVersion().toString();
}
@Override
@@ -6,6 +6,7 @@
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;
@@ -13,6 +14,7 @@ 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;
@@ -31,6 +33,7 @@ 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());
@@ -41,10 +44,15 @@ public class ModFileParser {
}
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
fileConfig.load();
fileConfig.close();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
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.");
}
}
protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
@@ -34,7 +34,6 @@ public class ModValidator {
private LoadingModList loadingModList;
private final List<IModFile> brokenFiles = new ArrayList<>();
private final List<EarlyLoadingException.ExceptionData> discoveryErrorData;
private final List<ModFileLoadingException> modFileLoadingExceptions;
public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData, List<ModFileLoadingException> modFileLoadingExceptions) {
this.candidateMods = lst(modFiles.get(IModFile.Type.MOD));
@@ -44,7 +43,6 @@ public class ModValidator {
this.candidatePlugins.addAll(lst(modFiles.get(IModFile.Type.LIBRARY)));
this.discoveryErrorData = discoveryErrorData;
this.brokenFiles.addAll(brokenFiles.stream().map(IModFileInfo::getFile).toList());
this.modFileLoadingExceptions = modFileLoadingExceptions;
}
public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData) {
@@ -52,7 +50,9 @@ public class ModValidator {
}
private static List<ModFile> lst(List<ModFile> files) {
return files == null ? new ArrayList<>() : new ArrayList<>(files);
if (files == null) return new ArrayList<>();
if (files instanceof ArrayList) return files;
return new ArrayList<>(files);
}
public void stage1Validation() {
@@ -60,7 +60,7 @@ public class ModValidator {
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod files with {} mods", candidateMods.size(), candidateMods.stream().mapToInt(mf -> mf.getModInfos().size()).sum());
}
ImmediateWindowHandler.updateProgress("Found "+candidateMods.size()+" mod candidates");
ImmediateWindowHandler.updateProgress("Found " + candidateMods.size() + " mod candidates");
}
@NotNull
@@ -84,7 +84,7 @@ public abstract class CommonLaunchHandler implements ILaunchHandlerService {
protected static final LaunchType CLIENT_DATA = new LaunchType("client_data", "minecraft", "net.minecraft.client.data.Main", Dist.CLIENT, true);
protected static final LaunchType DATA = new LaunchType("data", "minecraft", "net.minecraft.data.Main", Dist.CLIENT, true);
protected static final LaunchType SERVER = new LaunchType("server", "minecraft", "net.minecraft.server.Main", Dist.DEDICATED_SERVER, false);
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "net.minecraftforge.forge", "net.minecraftforge.gametest.GameTestMain", Dist.DEDICATED_SERVER, false);
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "minecraft", "net.minecraft.gametest.Main", Dist.DEDICATED_SERVER, false);
protected void runTarget(String module, String target, final String[] arguments, final ModuleLayer layer) throws Throwable {
var mod = layer.findModule(module).orElse(null);
@@ -96,14 +96,14 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
// Find resource directories for every mod in this group
var paths = new LinkedHashSet<Path>();
for (var modid : modids) {
for (var modid : modids.stream().sorted().toList()) {
var rsc = path.resolve(modid);
if (Files.exists(rsc))
paths.add(rsc);
}
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
buildModsToml(paths, modids, root);
buildModsToml(paths, modids, root, pkg.startsWith("net/minecraftforge/debug/client/"));
buildPackMeta(paths, root);
moveModuleInfo(paths, root);
@@ -187,7 +187,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
}
// Builds or update the mods.toml file for all @Mods in this package
private static void buildModsToml(Set<Path> resources, Set<String> modids, Path root) {
private static void buildModsToml(Set<Path> resources, Set<String> modids, Path root, boolean clientOnly) {
var toml = resources.stream()
.map(p -> p.resolve(MODS_TOML))
.filter(Files::exists)
@@ -205,7 +205,8 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
var defaults = Map.of(
"modLoader", "javafml",
"loaderVersion", "[0,)",
"license", "Doesnt fucking matter"
"license", "Doesnt fucking matter",
"clientSideOnly", clientOnly
);
for (var key : defaults.keySet()) {
@@ -1,5 +1,4 @@
net.minecraftforge.fml.loading.log4j.SLF4JFixerLaunchPluginService
net.minecraftforge.fml.loading.RuntimeDistCleaner
net.minecraftforge.fml.common.asm.RuntimeEnumExtender
net.minecraftforge.fml.common.asm.ObjectHolderDefinalize
net.minecraftforge.fml.common.asm.CapabilityTokenSubclass
@@ -0,0 +1,35 @@
{
"options": [
{
"resource": "com/llamalad7/mixinextras/platform/forge/MixinExtrasConfigPlugin.class",
"layer": "GAMELIBRARY",
"id": "mixinextras",
"deps": [
{
"identifier": {
"group": "com.github.LlamaLad7",
"artifact": "MixinExtras"
},
"version": {
"range": "[0.5.3,)",
"artifactVersion": "0.5.3"
},
"path": "",
"isObfuscated": false
}
],
"meta": {
"identifier": {
"group": "io.github.llamalad7",
"artifact": "mixinextras-forge"
},
"version": {
"artifactVersion": "0.5.3"
},
"path": "",
"isObfuscated": false
},
"nested": true
}
]
}
+73
View File
@@ -0,0 +1,73 @@
import net.minecraftforge.gradleutils.PomUtils
plugins {
id 'java-library'
id 'maven-publish'
id 'net.minecraftforge.licenser'
id 'net.minecraftforge.gradleutils'
alias(libs.plugins.apt)
}
apply from: rootProject.file('build_shared.gradle')
configurations.forEach{ it.transitive = false }
dependencies {
compileOnly(libs.jetbrains.annotations)
implementation(libs.bundles.asm) // Needed by all the black magic
implementation(libs.log4j.api)
implementation(libs.gson)
implementation(libs.modlauncher)
implementation(libs.coremods) // Used for ASMAPI (for now)
testCompileOnly(libs.jetbrains.annotations)
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
withSourcesJar()
}
tasks.named('jar', Jar) {
manifest {
attributes([
'Automatic-Module-Name': 'net.minecraftforge.forge.transformers',
'Forge-Module-Layer': 'boot'
] as LinkedHashMap)
attributes([
'Specification-Title': 'Forge Transformers',
'Specification-Vendor': 'Forge Development LLC',
'Specification-Version': '1',
'Implementation-Title': 'Forge Transformers',
'Implementation-Vendor': 'Forge Development LLC',
'Implementation-Version': FORGE_VERSION
] as LinkedHashMap, 'net/minecraftforge/forge/transformers/')
}
}
tasks.withType(JavaCompile).configureEach {
options.compilerArgs << '-Xlint:unchecked'
}
license {
header = rootProject.file('LICENSE-header.txt')
}
publishing {
publications.register('mavenJava', MavenPublication) {
from components.java
artifactId = 'forge-transformers'
pom {
name = project.name
description = 'Forge-specific transformers unrelated to the FML project.'
url = 'https://github.com/MinecraftForge/MinecraftForge'
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
license PomUtils.Licenses.LGPLv2_1
}
}
repositories {
maven gradleutils.publishingForgeMaven
}
}
@@ -0,0 +1,78 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.forge.transformers;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import net.minecraftforge.coremod.api.ASMAPI;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.tree.ClassNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
record FieldToMethodTransformer(String className, Map<String, String> fields) implements ITransformer<ClassNode> {
// TODO [Forge][Transformer] Make this properly data driven or configurable.
// It was hard-coded like this before when using JS CoreMods, though.
static final Map<String, Map<String, String>> TARGETS = Map.of(
"net.minecraft.world.level.biome.Biome",
Map.of(
"climateSettings", "getModifiedClimateSettings",
"specialEffects", "getModifiedSpecialEffects"
),
"net.minecraft.world.effect.MobEffectInstance",
Map.of(
"effect", "getEffect"
),
"net.minecraft.world.level.block.LiquidBlock",
Map.of(
"fluid", "getFluid"
),
"net.minecraft.world.item.BucketItem",
Map.of(
"content", "getFluid"
),
"net.minecraft.world.level.block.FlowerPotBlock",
Map.of(
"potted", "getPotted"
)
);
@SuppressWarnings("rawtypes")
static List<ITransformer> getAll() {
var ret = new ArrayList<ITransformer>(TARGETS.size());
for (var entry : TARGETS.entrySet()) {
ret.add(new FieldToMethodTransformer(entry.getKey(), entry.getValue()));
}
return ret;
}
@Override
public @NotNull ClassNode transform(ClassNode input, ITransformerVotingContext context) {
for (var entry : this.fields.entrySet()) {
ASMAPI.redirectFieldToMethod(input, entry.getKey(), entry.getValue());
}
return input;
}
@Override
public @NotNull TransformerVoteResult castVote(ITransformerVotingContext context) {
return TransformerVoteResult.YES;
}
@Override
public @NotNull Set<Target> targets() {
return Set.of(Target.targetClass(this.className));
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.forge.transformers;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ITransformationService;
import cpw.mods.modlauncher.api.ITransformer;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
public record ForgeModTransformers(String name) implements ITransformationService {
public ForgeModTransformers() {
this("forge");
}
@Override
public void initialize(IEnvironment environment) { }
@Override
public void onLoad(IEnvironment env, Set<String> otherServices) { }
@Override
@SuppressWarnings("rawtypes")
public @NotNull List<ITransformer> transformers() {
List<ITransformer> transformers = FieldToMethodTransformer.getAll();
transformers.add(new MethodRedirector());
return transformers;
}
}
@@ -0,0 +1,142 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.forge.transformers;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import net.minecraftforge.coremod.api.ASMAPI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
// NOTE: THIS IS A SINGLETON!
record MethodRedirector() implements ITransformer<ClassNode> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new Gson();
private static final Replacement[] REPLACEMENTS = {
new Replacement(
// finalizeSpawn redirection to ForgeEventFactory.onFinalizeSpawn
ASMAPI.MethodType.VIRTUAL,
"finalizeSpawn",
"(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;",
GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class),
insn -> ASMAPI.buildMethodCall(
ASMAPI.MethodType.STATIC,
"net/minecraftforge/event/ForgeEventFactory",
"onFinalizeSpawn",
"(Lnet/minecraft/world/entity/Mob;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
)
)
};
private static <T> T sneak(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
record Replacement(
ASMAPI.MethodType type,
String name,
String desc,
Target[] targets,
UnaryOperator<MethodInsnNode> factory
) { }
record Target(
@SerializedName("class") String className,
String[] methods
) { }
@Override
public @NotNull TransformerVoteResult castVote(ITransformerVotingContext context) {
return TransformerVoteResult.YES;
}
@Override
public @NotNull Set<ITransformer.Target> targets() {
return Arrays
.stream(REPLACEMENTS)
.map(Replacement::targets)
.flatMap(Arrays::stream)
.map(Target::className)
.map(ITransformer.Target::targetClass)
.collect(Collectors.toUnmodifiableSet());
}
@Override
public @NotNull ClassNode transform(ClassNode clazz, ITransformerVotingContext context) {
for (var replacement : REPLACEMENTS) {
for (var methodString : getClassTargetMethods(clazz, replacement)) {
// cut up the string since we've put both the name and desc as the target
var splitPos = methodString.indexOf('(');
var methodName = methodString.substring(0, splitPos);
var methodDesc = methodString.substring(splitPos);
var method = ASMAPI.findMethodNode(clazz, methodName, methodDesc);
if (method == null) {
LOGGER.error("Failed to redirect method call for {}! Method {} not found in class {}! This is a Forge bug, and is likely due to a Minecraft update changing something.", replacement.name, methodString, clazz.name);
continue;
}
for (var insn : method.instructions) {
if (!shouldReplace(insn, replacement)) continue;
var methodInsn = (MethodInsnNode) insn;
var redirection = replacement.factory.apply(methodInsn);
LOGGER.debug("Redirecting method call {}{} to {}{} inside of {}.{}", methodInsn.name, methodInsn.desc, redirection.name, redirection.desc, clazz.name, method.name);
ASMAPI.insertInsn(method, methodInsn, redirection, ASMAPI.InsertMode.REMOVE_ORIGINAL);
}
}
}
return clazz;
}
private static boolean shouldReplace(AbstractInsnNode insn, Replacement replacement) {
return insn.getOpcode() == replacement.type.toOpcode()
&& replacement.name.equals(((MethodInsnNode) insn).name)
&& replacement.desc.equals(((MethodInsnNode) insn).desc);
}
private static List<String> getClassTargetMethods(ClassNode clazz, Replacement replacement) {
for (var t : replacement.targets) {
if (!t.className.equals(clazz.name)) continue;
// declared methods
var targets = new ArrayList<>(Arrays.asList(t.methods));
// synthetic methods
for (var method : clazz.methods) {
if ((method.access & Opcodes.ACC_SYNTHETIC) != 0)
targets.add(method.name + method.desc);
}
return targets;
}
return List.of();
}
}
@@ -0,0 +1 @@
net.minecraftforge.forge.transformers.ForgeModTransformers
@@ -107,7 +107,7 @@
{
"class": "net/minecraft/world/level/levelgen/PhantomSpawner",
"methods": [
"tick(Lnet/minecraft/server/level/ServerLevel;ZZ)V"
"tick(Lnet/minecraft/server/level/ServerLevel;Z)V"
]
},
{
+3 -3
View File
@@ -5,11 +5,11 @@ org.gradle.daemon=false
org.gradle.parallel=true
JAVA_VERSION=21
MC_VERSION=1.21.7
MC_VERSION=1.21.10
MC_NEXT_VERSION=1.22
MCP_VERSION=20250630.104312
MCP_VERSION=20251007.101210
MAPPING_CHANNEL=official
MAPPING_VERSION=1.21.7
MAPPING_VERSION=1.21.10
# Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false
@@ -48,11 +48,13 @@ import java.util.stream.Collectors;
* annotations and passes the class instances to the {@link Bus}
* defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/
public class AutomaticEventSubscriber {
public final 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);
private static final List<EnumData> DEFAULT_SIDES = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER"));
private static final EnumData DEFAULT_BUS = new EnumData(null, "BOTH");
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
if (scanData == null) return;
@@ -71,9 +73,6 @@ public class AutomaticEventSubscriber {
.filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
var defaultSides = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER"));
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");
@@ -82,13 +81,13 @@ public class AutomaticEventSubscriber {
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId);
var sidesValue = value(data, "value", defaultSides);
var sidesValue = value(data, "value", DEFAULT_SIDES);
var sides = sidesValue.stream()
.map(EnumData::value)
.map(Dist::valueOf)
.collect(Collectors.toSet());
var busName = value(data, "bus", defaultBus).value();
var busName = value(data, "bus", DEFAULT_BUS).value();
var busTarget = Bus.valueOf(busName);
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) {
try {
@@ -173,7 +172,7 @@ public class AutomaticEventSubscriber {
Class<? extends Event> eventType = (Class<? extends Event>) parameterTypes[0];
var subscribeEventAnnotation = method.getAnnotation(SubscribeEvent.class);
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method);
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method, false);
listenersCount++;
if (firstValidListenerEventType == null)
@@ -259,7 +258,7 @@ public class AutomaticEventSubscriber {
throw fail(method, "Return type boolean is only valid for cancellable events");
}
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method);
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method, true);
listenersCount++;
if (firstValidListenerEventType == null)
@@ -276,11 +275,24 @@ public class AutomaticEventSubscriber {
@SuppressWarnings({"unchecked", "rawtypes"})
private static EventListener registerListener(@Nullable BusGroup busGroup,
int paramCount, Class<?> returnType, Class<? extends Event> eventType,
SubscribeEvent subscribeEventAnnotation, Method method) {
SubscribeEvent subscribeEventAnnotation, Method method, boolean strict) {
if (busGroup == null) {
busGroup = IModBusEvent.class.isAssignableFrom(eventType)
? FMLJavaModLoadingContext.get().getModBusGroup()
: BusGroup.DEFAULT;
} else if (strict) {
String solution = "To fix this, remove the bus param from your @EventBusSubscriber annotation or move this event listener to another class.";
var isDefaultBusGroup = busGroup == BusGroup.DEFAULT;
var isModBusEvent = IModBusEvent.class.isAssignableFrom(eventType);
if (isDefaultBusGroup && isModBusEvent) { // requested forge bus and has IModBusEvent
throw fail(method, "Event type " + eventType.getName()
+ " is on the mod BusGroup but you are asking to register it on the default BusGroup (BusGroup.DEFAULT/EventBusSubscriber.Bus.FORGE). "
+ solution);
} else if (!isDefaultBusGroup && !isModBusEvent) { // requested mod bus and does not have IModBusEvent
throw fail(method, "Event type " + eventType.getName()
+ " is on the default BusGroup but you are asking to register it on the mod BusGroup (context.getModBusGroup()/EventBusSubscriber.Bus.MOD). "
+ solution);
}
}
// determine the listener type from its parameters and return type
@@ -43,12 +43,13 @@ public class FMLModContainer extends ModContainer {
LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className);
this.scanResults = modFileScanResults;
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId());
this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId(), IModBusEvent.class);
this.contextExtension = () -> context;
try {
var moduleName = info.getOwningFile().moduleName();
var module = gameLayer.findModule(moduleName)
.orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer));
var module = gameLayer.findModule(moduleName).orElse(null);
if (module == null)
throw new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer);
openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar());
@@ -166,6 +167,7 @@ public class FMLModContainer extends ModContainer {
return modInstance;
}
@Override
public BusGroup getModBusGroup() {
return this.eventBusGroup;
}
@@ -193,6 +195,6 @@ public class FMLModContainer extends ModContainer {
@Override
public String toString() {
return "FMLModContainer[" + this.getModInfo().getModId() + ", " + this.getClass().getName() + "]";
return "FMLModContainer[" + this.getModInfo().getModId() + ", " + this.getClass().getName() + ']';
}
}
@@ -8,8 +8,6 @@ package net.minecraftforge.fml.mclanguageprovider;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.forgespi.language.IModInfo;
import java.util.Objects;
public class MinecraftModContainer extends ModContainer {
private static final String MCMODINSTANCE = "minecraft, the mod";
@@ -20,7 +18,7 @@ public class MinecraftModContainer extends ModContainer {
@Override
public boolean matches(final Object mod) {
return Objects.equals(mod, MCMODINSTANCE);
return MCMODINSTANCE.equals(mod);
}
@Override
@@ -10,7 +10,6 @@ import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.language.IModLanguageProvider;
import net.minecraftforge.forgespi.language.ModFileScanData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@@ -20,7 +19,7 @@ import java.util.function.Supplier;
import static net.minecraftforge.fml.Logging.LOADING;
public class MinecraftModLanguageProvider implements IModLanguageProvider {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public String name() {
return "minecraft";
@@ -45,7 +44,7 @@ public class MinecraftModLanguageProvider implements IModLanguageProvider {
final Class<?> mcModClass = Class.forName(getClass().getModule(), "net.minecraftforge.fml.mclanguageprovider.MinecraftModContainer");
return (T)mcModClass.getConstructor(IModInfo.class).newInstance(info);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
LOGGER.fatal(LOADING,"Unable to load MinecraftModContainer, wut?", e);
LogManager.getLogger().fatal(LOADING, "Unable to load MinecraftModContainer, wut?", e);
throw new RuntimeException(e);
}
}
+30 -201
View File
@@ -1,235 +1,64 @@
// This is a minimal setup of a Forge mod workspace.
// For complex examples (including AccessTransformers, Jar-in-Jar, and Mixin), see our examples repository.
// https://github.com/MinecraftForge/MDKExamples
plugins {
id 'eclipse'
id 'java'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0.36,6.2)'
id 'eclipse'
id 'net.minecraftforge.gradle' version '[7.0.3,8)'
}
version = mod_version
group = mod_group_id
base {
archivesName = mod_id
}
version = '1.0.0'
group = 'com.example.examplemod'
// 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'}"
// Include generated resources
sourceSets.main.resources { srcDir 'src/generated/resources' }
minecraft {
// The mappings can be changed at any time and must be in the following format.
// Channel: Version:
// official MCVersion Official field/method names from Mojang mapping files
// parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official
//
// Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started
//
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
mappings channel: 'official', version: '@MC_VERSION@'
// Forge 1.20.6 and newer use official mappings at runtime, so we shouldn't reobf from official to SRG
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.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game.
// It is REQUIRED to be set to true for this template to function.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// When true, this property will add the folder name of all declared run configurations to generated IDE run configurations.
// The folder name can be set on a run configuration using the "folderName" property.
// By default, the folder name of a run configuration is the name of the Gradle project containing it.
// generateRunFolders = true
// This property enables access transformers for use in development, applied to the Minecraft artifact.
// The access transformer file can be anywhere in the project.
// However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge.
// This default location is a best practice to automatically put the file in the right place in the final jar.
// See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
// applies to all the run configs below
configureEach {
workingDirectory project.file('run')
workingDir = layout.projectDirectory.dir('run')
// Optional additional logging. The markers can be added/remove as needed, separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
// property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
// Recommended for development - enables more descriptive errors at the cost of slower startup and registration.
property 'eventbus.api.strictRuntimeChecks', 'true'
// arg "-mixin.config=${mod_id}.mixins.json"
systemProperty 'eventbus.api.strictRuntimeChecks', 'true'
systemProperty 'forge.enabledGameTestNamespaces', 'examplemod'
}
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
}
register('client')
server {
property 'forge.enabledGameTestNamespaces', mod_id
register('server') {
args '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
property 'forge.enabledGameTestNamespaces', mod_id
}
register('gameTestServer')
data {
// example of overriding the workingDirectory set in configureEach above
workingDirectory project.file('run-data')
register('data') {
workingDir = layout.projectDirectory.dir('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
args '--mod', 'examplemod', '--all', '--output', layout.projectDirectory.dir('src/generated/resources'), '--existing', layout.projectDirectory.dir('src/main/resources')
}
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories {
// Put repositories for dependencies here
minecraft.mavenizer(it) // In Kotlin, it = this
maven fg.forgeMaven
maven fg.minecraftLibsMaven
mavenCentral()
maven {
name = 'Forge'
url = 'https://maven.minecraftforge.net'
}
maven {
name = 'Minecraft libraries'
url = 'https://libraries.minecraft.net'
}
exclusiveContent {
forRepository {
maven {
name = 'Sponge'
url = 'https://repo.spongepowered.org/repository/maven-public'
}
}
filter {
includeGroupAndSubgroups('org.spongepowered')
}
}
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
}
dependencies {
// Specify the version of Minecraft to use.
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact.
// The "userdev" classifier will be requested and setup by ForgeGradle.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// 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}"
// Forge 1.21.6+ uses EventBus 7, which shifts most of its runtime validation to compile-time via an annotation processor
// to improve performance in production environments. This line is required to enable said compile-time validation
// in your development environment, helping you catch issues early.
annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.10'
// Example mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// 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
// The group id is ignored when searching -- in this case, it is "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.named('processResources', ProcessResources) {
var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range,
loader_version_range: loader_version_range,
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
}
}
// Example for how to get properties into the manifest for reading at runtime.
tasks.named('jar', Jar) {
manifest {
attributes([
'Specification-Title' : mod_id,
'Specification-Vendor' : mod_authors,
'Specification-Version' : '1', // We are version 1 of ourselves
'Implementation-Title' : project.name,
'Implementation-Version' : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors
])
// attributes['MixinConfigs'] = "${mod_id}.mixins.json"
}
}
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
register('mavenJava', MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file://${project.projectDir}/mcmodsrepo"
}
}
implementation minecraft.dependency('net.minecraftforge:forge:@MC_VERSION@-@FORGE_VERSION@')
annotationProcessor 'net.minecraftforge:eventbus-validator:@EVENTBUS_VERSION@'
}
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 IntelliJ to do it.
idea.module { downloadJavadoc = downloadSources = true }
eclipse {
// Run everytime eclipse builds the code
//autoBuildTasks genEclipseRuns
// Run when importing the project
synchronizationTasks 'genEclipseRuns'
}
// Merge the resources and classes into the same directory, because Java expects modules to be in a single directory.
// And if we have it in multiple we have to do performance intensive hacks like having the UnionFileSystem
// This will eventually be migrated to ForgeGradle so modders don't need to manually do it. But that is later.
sourceSets.each {
def dir = layout.buildDirectory.dir("sourcesSets/$it.name")
it.output.resourcesDir = dir
it.java.destinationDirectory = dir
// Use the UTF-8 charset for Java compilation
// This is done by default in Java 18+, but this ensures it no matter the Java or Gradle version
options.encoding = 'UTF-8'
}
+6 -16
View File
@@ -1,13 +1,11 @@
Source installation information for modders
-------------------------------------------
This code follows the Minecraft Forge installation methodology. It will apply
some small patches to the vanilla MCP source code, giving you and it access
some small patches to the vanilla MCP source code, giving you and it access
to some of the data and functions you need to build a successful mod.
Note also that the patches are built against "un-renamed" MCP source code (aka
SRG Names) - this means that you will not be able to read them directly against
normal code.
Please note that this example MDK is a simple showcase for the most basic of mods.
To see more examples see our dedicated examples repository under the "Additional Resources" section.
Setup Process:
==============================
@@ -17,30 +15,22 @@ Step 1: Open your command-line and browse to the folder where you extracted the
Step 2: You're left with a choice.
If you prefer to use Eclipse:
1. Run the following command: `./gradlew genEclipseRuns`
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
or run `gradlew eclipse` to generate the project.
If you prefer to use IntelliJ:
1. Open IDEA, and import project.
2. Select your build.gradle file and have it import.
3. Run the following command: `./gradlew genIntellijRuns`
4. Refresh the Gradle Project in IDEA if required.
3. Use the run tasks located under the "Slime Launcher" Gradle task group.
If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
(this does not affect your code) and then start the process again.
Mapping Names:
=============================
By default, the MDK is configured to use the official mapping names from Mojang for methods and fields
in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this
license, if you do not agree with it you can change your mapping names to other crowdsourced names in your
build.gradle. For the latest license text, refer to the mapping file itself, or the reference copy here:
https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
Additional Resources:
=========================
Community Documentation: https://docs.minecraftforge.net/en/latest/gettingstarted/
Additional Examples: https://github.com/MinecraftForge/MDKExamples
LexManos' Install Video: https://youtu.be/8VEdtQLuLO0
Forge Forums: https://forums.minecraftforge.net/
Forge Discord: https://discord.minecraftforge.net/
+1
View File
@@ -22,4 +22,5 @@ eclipse
run
# Files from Forge MDK
forge_README.txt
forge*changelog.txt
+7 -64
View File
@@ -1,66 +1,9 @@
# Sets default memory used for Gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx5G
org.gradle.daemon=false
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.configureondemand=true
# In the case that Gradle needs to fork to recompile, this will set the memory for that process.
systemProp.net.minecraftforge.gradle.repo.recompile.fork=true
systemProp.net.minecraftforge.gradle.repo.recompile.fork.args=-Xmx5G
org.gradle.configuration-cache=true
org.gradle.configuration-cache.parallel=true
org.gradle.configuration-cache.problems=warn
# Opts-out of ForgeGradle automatically adding mavenCentral(), Forge's maven and MC libs maven to the repositories block
systemProp.net.minecraftforge.gradle.repo.attach=false
## Environment Properties
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=@MC_VERSION@
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[@MC_VERSION@,@MC_NEXT_VERSION@)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=@FORGE_VERSION@
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[@FORGE_SPEC_VERSION@,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[@FORGE_SPEC_VERSION@,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=@MAPPING_CHANNEL@
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=@MAPPING_VERSION@
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=examplemod
# The human-readable display name for the mod.
mod_name=Example Mod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=1.0.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.example.examplemod
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=YourNameHere, OtherNameHere
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Example mod description.\nNewline characters can be used and will be replaced properly.
net.minecraftforge.gradle.merge-source-sets=true
+3 -11
View File
@@ -1,13 +1,5 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.10.0'
}
rootProject.name = 'examplemod'
+36 -66
View File
@@ -1,73 +1,43 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or Open to LAN),
# set this to true, and Forge will set the correct displayTest for you and skip loading your mod on dedicated servers.
#clientSideOnly=true #optional - defaults to false if absent
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# A text field displayed in the mod UI
authors="${mod_authors}" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component.
# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value.
# 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)
# See https://docs.minecraftforge.net/en/1.21.x/gettingstarted/modfiles/#modstoml
# There are lots of things you can do with the mods.toml, and not all fields are included with this MDK
# References: https://github.com/MinecraftForge/MDKExamples
# 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.
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="${forge_version_range}" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
modLoader="javafml"
loaderVersion="[@FORGE_SPEC_VERSION@,)"
license="All Rights Reserved"
#issueTrackerURL="https://github.com/MyOrganization/MyMod/" #optional
#clientSideOnly=true #optional, default=false
[[mods]]
modId="examplemod"
version="1.0.0"
displayName="Example Mod"
#updateJSONURL="https://example.com/updates.json" #optional
#displayURL="https://example.com/" #optional
#logoFile="examplemod.png" #optional
#credits="" #optional
authors="YourNameHere, OtherNameHere" #optional
#displayTest="MATCH_VERSION" #optional, default=MATCH_VERSION when not clientSideOnly, else IGNORE_ALL_VERSION
# 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 = []
description='''Example mod description.
Newline characters can be used like this, and rendered on the mods screen properly.'''
[[dependencies.examplemod]] #recommended
modId="forge"
mandatory=true
versionRange="[@FORGE_SPEC_VERSION@,)"
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.${mod_id}]]
[[dependencies.examplemod]] #recommended
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="${minecraft_version_range}"
versionRange="[@MC_VERSION@,@MC_NEXT_VERSION@,)"
ordering="NONE"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/opengl/GlCommandEncoder.java
+++ b/com/mojang/blaze3d/opengl/GlCommandEncoder.java
@@ -132,6 +_,9 @@
@@ -131,6 +_,9 @@
GlStateManager._colorMask(true, true, true, true);
GlStateManager._clear(16384);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, 0, 0);
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/opengl/GlDevice.java
+++ b/com/mojang/blaze3d/opengl/GlDevice.java
@@ -89,8 +_,15 @@
@@ -90,8 +_,15 @@
public GpuTexture createTexture(
@Nullable Supplier<String> p_397830_, int p_394481_, TextureFormat p_394839_, int p_391831_, int p_395609_, int p_407582_, int p_408928_
) {
@@ -17,7 +17,7 @@
);
}
@@ -98,6 +_,15 @@
@@ -99,6 +_,15 @@
public GpuTexture createTexture(
@Nullable String p_394142_, int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_
) {
@@ -33,7 +33,7 @@
if (p_406483_ < 1) {
throw new IllegalArgumentException("mipLevels must be at least 1");
} else if (p_408015_ < 1) {
@@ -148,11 +_,14 @@
@@ -149,11 +_,14 @@
GlStateManager._texImage2D(
k,
l,
@@ -48,7 +48,7 @@
GlConst.toGlType(p_394951_),
null
);
@@ -163,11 +_,14 @@
@@ -164,11 +_,14 @@
GlStateManager._texImage2D(
j,
i1,
@@ -63,7 +63,7 @@
GlConst.toGlType(p_394951_),
null
);
@@ -180,7 +_,7 @@
@@ -181,7 +_,7 @@
} else if (j1 != 0) {
throw new IllegalStateException("OpenGL error " + j1);
} else {
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/opengl/GlStateManager.java
+++ b/com/mojang/blaze3d/opengl/GlStateManager.java
@@ -89,6 +_,11 @@
@@ -85,6 +_,11 @@
}
}
@@ -12,7 +12,7 @@
public static void _disableBlend() {
RenderSystem.assertOnRenderThread();
BLEND.mode.disable();
@@ -404,9 +_,17 @@
@@ -371,9 +_,17 @@
}
}
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/pipeline/RenderTarget.java
+++ b/com/mojang/blaze3d/pipeline/RenderTarget.java
@@ -92,7 +_,7 @@
@@ -86,7 +_,7 @@
this.width = p_83951_;
this.height = p_83952_;
if (this.useDepth) {
@@ -9,7 +9,7 @@
this.depthTextureView = gpudevice.createTextureView(this.depthTexture);
this.depthTexture.setTextureFilter(FilterMode.NEAREST, false);
this.depthTexture.setAddressMode(AddressMode.CLAMP_TO_EDGE);
@@ -166,5 +_,26 @@
@@ -155,5 +_,26 @@
@Nullable
public GpuTextureView getDepthTextureView() {
return this.depthTextureView;
@@ -25,7 +25,7 @@
+ public void enableStencil() {
+ if (stencilEnabled) return;
+ stencilEnabled = true;
+ this.resize(viewWidth, viewHeight);
+ this.resize(width, height);
+ }
+
+ /**
@@ -1,16 +1,16 @@
--- a/com/mojang/blaze3d/platform/Window.java
+++ b/com/mojang/blaze3d/platform/Window.java
@@ -88,7 +_,8 @@
GLFW.glfwWindowHint(139267, 2);
@@ -91,7 +_,8 @@
GLFW.glfwWindowHint(139267, 3);
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);
- this.handle = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.handle = 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;
@@ -100,6 +_,7 @@
@@ -103,6 +_,7 @@
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
@@ -18,8 +18,8 @@
this.setMode();
this.refreshFramebufferSize();
@@ -266,6 +_,9 @@
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
@@ -269,6 +_,9 @@
GLFW.glfwGetFramebufferSize(this.handle, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) {
@@ -9,7 +9,7 @@
VertexConsumer addVertex(float p_344294_, float p_342213_, float p_344859_);
VertexConsumer setColor(int p_342749_, int p_344324_, int p_343336_, int p_342831_);
@@ -135,9 +_,11 @@
@@ -131,9 +_,11 @@
int j1 = ARGB.color(k, (int)f3, (int)f4, (int)f5);
int k1 = LightTexture.lightCoordsWithEmission(p_331444_[i1], l);
@@ -7,9 +7,9 @@
-public class VertexFormat {
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
public static final int UNKNOWN_ELEMENT = -1;
private static final boolean USE_STAGING_BUFFER_WORKAROUND = Util.getPlatform() == Util.OS.WINDOWS && Util.isAarch64();
@Nullable
@@ -34,6 +_,7 @@
private final List<VertexFormatElement> elements;
private final List<String> names;
@@ -31,6 +_,7 @@
private GpuBuffer immediateDrawVertexBuffer;
@Nullable
private GpuBuffer immediateDrawIndexBuffer;
@@ -17,7 +17,7 @@
VertexFormat(List<VertexFormatElement> p_343616_, List<String> p_345241_, IntList p_345522_, int p_344162_) {
this.elements = p_343616_;
@@ -46,6 +_,11 @@
@@ -43,6 +_,11 @@
int j = vertexformatelement != null ? p_343616_.indexOf(vertexformatelement) : -1;
this.offsetsByElement[i] = j != -1 ? p_345522_.getInt(j) : -1;
}
@@ -29,8 +29,8 @@
}
public static VertexFormat.Builder builder() {
@@ -162,6 +_,9 @@
);
@@ -141,6 +_,9 @@
this.immediateDrawIndexBuffer = uploadToBuffer(this.immediateDrawIndexBuffer, p_391835_, 72, () -> "Immediate index buffer for " + this);
return this.immediateDrawIndexBuffer;
}
+
@@ -4,12 +4,12 @@
}
@Override
+ public boolean keyPressed(int key, int scanCode, int modifiers) {
+ if (key == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) {
+ public boolean keyPressed(net.minecraft.client.input.KeyEvent event) {
+ if (event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) {
+ minecraft.setScreen(this.nextScreen);
+ return true;
+ }
+ return super.keyPressed(key, scanCode, modifiers);
+ return super.keyPressed(event);
+ }
+
+ @Override
@@ -1,6 +1,6 @@
--- a/net/minecraft/CrashReportCategory.java
+++ b/net/minecraft/CrashReportCategory.java
@@ -112,8 +_,10 @@
@@ -116,8 +_,10 @@
if (astacktraceelement.length <= 0) {
return 0;
} else {
@@ -13,7 +13,7 @@
return this.stackTrace.length;
}
}
@@ -160,16 +_,16 @@
@@ -164,16 +_,16 @@
if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:");
@@ -1,10 +1,10 @@
--- a/net/minecraft/SharedConstants.java
+++ b/net/minecraft/SharedConstants.java
@@ -175,6 +_,7 @@
@@ -224,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.ENABLE_COMMAND_STACK_TRACES = COMMAND_STACK_TRACES;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
@@ -1,6 +1,6 @@
--- a/net/minecraft/Util.java
+++ b/net/minecraft/Util.java
@@ -268,7 +_,7 @@
@@ -266,7 +_,7 @@
.getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version()))
.getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/advancements/Advancement.java
+++ b/net/minecraft/advancements/Advancement.java
@@ -226,7 +_,11 @@
@@ -233,7 +_,11 @@
}
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Camera.java
+++ b/net/minecraft/client/Camera.java
@@ -133,9 +_,13 @@
@@ -132,9 +_,13 @@
}
protected void setRotation(float p_90573_, float p_90574_) {
@@ -15,7 +15,7 @@
FORWARDS.rotate(this.rotation, this.forwards);
UP.rotate(this.rotation, this.up);
LEFT.rotate(this.rotation, this.left);
@@ -251,6 +_,13 @@
@@ -250,6 +_,13 @@
public float getPartialTickTime() {
return this.partialTickTime;
@@ -1,35 +1,27 @@
--- a/net/minecraft/client/KeyMapping.java
+++ b/net/minecraft/client/KeyMapping.java
@@ -15,9 +_,9 @@
@@ -19,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 Map<InputConstants.Key, List<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";
@@ -43,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++;
}
private final String name;
private final InputConstants.Key defaultKey;
private final KeyMapping.Category category;
@@ -38,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_);
}
@@ -101,7 +_,7 @@
private static void forAllKeyMappings(InputConstants.Key p_424096_, Consumer<KeyMapping> p_427756_) {
- List<KeyMapping> list = MAP.get(p_424096_);
+ List<KeyMapping> list = MAP.getAll(p_424096_);
if (list != null && !list.isEmpty()) {
for (KeyMapping keymapping : list) {
p_427756_.accept(keymapping);
@@ -100,7 +_,7 @@
}
public boolean isDown() {
@@ -37,26 +29,26 @@
+ return this.isDown && isConflictContextAndModifierActive();
}
public String getCategory() {
@@ -137,7 +_,16 @@
public KeyMapping.Category getCategory() {
@@ -140,7 +_,16 @@
public int compareTo(KeyMapping p_90841_) {
return this.category.equals(p_90841_.category)
return this.category == 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));
- : Integer.compare(KeyMapping.Category.SORT_ORDER.indexOf(this.category), KeyMapping.Category.SORT_ORDER.indexOf(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);
+ private static int compareSort(Category c1, Category c2) {
+ int o1 = KeyMapping.Category.SORT_ORDER.indexOf(c1);
+ int o2 = KeyMapping.Category.SORT_ORDER.indexOf(c2);
+ if (o1 == -1 && o2 != -1) return 1;
+ if (o1 != -1 && o2 == -1) return -1;
+ if (o1 == -1 && o2 == -1) return I18n.get(c1.id().toLanguageKey("key.category")).compareTo(I18n.get(c1.id().toLanguageKey("key.category")));
+ return o1 - o2;
}
public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -146,6 +_,20 @@
@@ -149,6 +_,20 @@
}
public boolean same(KeyMapping p_90851_) {
@@ -77,7 +69,7 @@
return this.key.equals(p_90851_.key);
}
@@ -164,11 +_,13 @@
@@ -167,11 +_,13 @@
}
public Component getTranslatedKeyMessage() {
@@ -92,7 +84,14 @@
}
public String saveString() {
@@ -182,5 +_,88 @@
@@ -183,12 +_,94 @@
}
private void registerMapping(InputConstants.Key p_423386_) {
- MAP.computeIfAbsent(p_423386_, p_420623_ -> new ArrayList<>()).add(this);
+ MAP.put(p_423386_, this);
}
@Nullable
public static KeyMapping get(String p_378660_) {
return ALL.get(p_378660_);
@@ -105,28 +104,28 @@
+ /**
+ * 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) {
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, Category 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) {
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, Category 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) {
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, Category 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) {
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, Category category) {
+ this.name = description;
+ this.key = keyCode;
+ this.defaultKey = keyCode;
@@ -138,7 +137,6 @@
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this);
+ MAP.put(keyCode, this);
+ CATEGORIES.add(category);
+ }
+
+ @Override
@@ -180,4 +178,5 @@
+
+ MAP.put(keyCode, this);
}
}
@OnlyIn(Dist.CLIENT)
@@ -1,39 +1,34 @@
--- a/net/minecraft/client/KeyboardHandler.java
+++ b/net/minecraft/client/KeyboardHandler.java
@@ -440,12 +_,12 @@
@@ -499,12 +_,12 @@
if (screen != null) {
try {
if (p_90897_ != 1 && p_90897_ != 2) {
- if (p_90897_ == 0 && screen.keyReleased(p_90895_, p_90896_, p_90898_)) {
+ if (p_90897_ == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, p_90895_, p_90896_, p_90898_)) {
if (p_90895_ != 1 && p_90895_ != 2) {
- if (p_90895_ == 0 && screen.keyReleased(p_423534_)) {
+ if (p_90895_ == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, p_423534_)) {
return;
}
} else {
screen.afterKeyboardAction();
- if (screen.keyPressed(p_90895_, p_90896_, p_90898_)) {
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, p_90895_, p_90896_, p_90898_)) {
return;
}
}
@@ -504,6 +_,7 @@
- if (screen.keyPressed(p_423534_)) {
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, p_423534_)) {
if (this.minecraft.screen == null) {
InputConstants.Key inputconstants$key = InputConstants.getKey(p_423534_);
KeyMapping.set(inputconstants$key, false);
@@ -568,6 +_,7 @@
}
}
}
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_423534_, p_90895_);
}
}
@@ -513,10 +_,10 @@
@@ -576,7 +_,7 @@
Screen screen = this.minecraft.screen;
if (screen != null && this.minecraft.getOverlay() == null) {
try {
if (Character.isBmpCodePoint(p_90891_)) {
- screen.charTyped((char)p_90891_, p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, (char)p_90891_, p_90892_);
} else if (Character.isValidCodePoint(p_90891_)) {
- screen.charTyped(Character.highSurrogate(p_90891_), p_90892_);
- screen.charTyped(Character.lowSurrogate(p_90891_), p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, Character.highSurrogate(p_90891_), p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, Character.lowSurrogate(p_90891_), p_90892_);
}
- screen.charTyped(p_427531_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, p_427531_);
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.forThrowable(throwable, "charTyped event handler");
screen.fillCrashDetails(crashreport);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Minecraft.java
+++ b/net/minecraft/client/Minecraft.java
@@ -256,7 +_,7 @@
@@ -260,7 +_,7 @@
import org.slf4j.Logger;
@OnlyIn(Dist.CLIENT)
@@ -8,8 +8,8 @@
+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;
@@ -435,7 +_,6 @@
private static final int MAX_TICKS_PER_UPDATE = 10;
@@ -439,7 +_,6 @@
}
}, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", this.user.getName());
@@ -17,19 +17,19 @@
this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat;
@@ -486,10 +_,9 @@
@@ -491,10 +_,9 @@
LOGGER.error("Couldn't set icon", (Throwable)ioexception);
}
+ // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window.getWindow());
- this.mouseHandler.setup(this.window);
this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window.getWindow());
- this.keyboardHandler.setup(this.window);
RenderSystem.initRenderer(
this.window.getWindow(),
this.window.handle(),
this.options.glDebugVerbosity,
@@ -500,6 +_,7 @@
@@ -505,6 +_,7 @@
LOGGER.info("Using optional rendering extensions: {}", String.join(", ", RenderSystem.getDevice().getEnabledExtensions()));
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
@@ -37,33 +37,33 @@
this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode, p_340763_ -> {
@@ -578,6 +_,7 @@
this.blockEntityRenderDispatcher = new BlockEntityRenderDispatcher(this.font, this.modelManager.entityModels(), this.blockRenderer, this.itemModelResolver, this.itemRenderer, this.entityRenderDispatcher);
this.resourceManager.registerReloadListener(this.blockEntityRenderDispatcher);
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);
@@ -593,6 +_,9 @@
@@ -593,6 +_,7 @@
this.particleResources = new ParticleResources();
this.resourceManager.registerReloadListener(this.particleResources);
this.particleEngine = new ParticleEngine(this.level, this.particleResources);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleResources);
this.particleResources.onReload(this.particleEngine::clearParticles);
this.waypointStyles = new WaypointStyleManager();
this.resourceManager.registerReloadListener(this.waypointStyles);
@@ -604,6 +_,9 @@
this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies);
this.gui = new Gui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
+ this.mouseHandler.setup(this.window);
+ this.keyboardHandler.setup(this.window);
RealmsClient realmsclient = RealmsClient.getOrCreate(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
@@ -626,6 +_,7 @@
RenderSystem.setErrorCallback(this::onFullscreenError);
@@ -636,6 +_,7 @@
}
}
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setDefaultErrorCallback();
@@ -648,16 +_,17 @@
this.window.setAllowCursorChanges(this.options.allowCursorChanges().get());
@@ -659,16 +_,17 @@
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
this.setOverlay(
@@ -84,7 +84,7 @@
);
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.logPath());
this.framerateLimitTracker = new FramerateLimitTracker(this.options, this);
@@ -759,6 +_,7 @@
@@ -787,6 +_,7 @@
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) {
stringbuilder.append("*");
@@ -92,16 +92,16 @@
}
stringbuilder.append(" ");
@@ -782,6 +_,8 @@
@@ -810,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_193587_.user.user.getType() != User.Type.MSA
? UserApiService.OFFLINE
: p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
@@ -792,7 +_,7 @@
return p_193587_.game.offlineDeveloperMode ? UserApiService.OFFLINE : p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
}
@@ -822,7 +_,7 @@
}
private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
@@ -110,7 +110,7 @@
this.clearResourcePacksOnError(p_91240_, null, p_299515_);
} else {
Util.throwAsRuntime(p_91240_);
@@ -1078,12 +_,6 @@
@@ -1108,12 +_,6 @@
LOGGER.error("setScreen called from non-game thread");
}
@@ -120,34 +120,34 @@
- this.setLastInputType(InputType.NONE);
- }
-
if (p_91153_ == null && this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
} else {
@@ -1097,6 +_,23 @@
}
if (p_91153_ == null) {
if (this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
@@ -1132,6 +_,23 @@
}
}
+ 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;
+ }
+ 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);
+ }
+ 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();
@@ -1180,6 +_,7 @@
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1214,6 +_,7 @@
FreeTypeUtil.destroy();
Util.shutdownExecutors();
RenderSystem.getDevice().close();
@@ -155,19 +155,17 @@
} catch (Throwable throwable) {
LOGGER.error("Shutdown failure!", throwable);
throw throwable;
@@ -1248,9 +_,11 @@
this.mouseHandler.handleAccumulatedMovement();
profilerfiller.pop();
@@ -1278,7 +_,9 @@
RenderSystem.getDevice().createCommandEncoder().clearColorAndDepthTextures(rendertarget.getColorTexture(), 0, rendertarget.getDepthTexture(), 1.0);
profilerfiller.push("gameRenderer");
if (!this.noRender) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker);
profilerfiller.popPush("gameRenderer");
this.gameRenderer.render(this.deltaTracker, p_91384_);
profilerfiller.pop();
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker);
}
profilerfiller.push("blit");
@@ -1379,10 +_,12 @@
profilerfiller.popPush("blit");
@@ -1388,10 +_,12 @@
this.window.setGuiScale(i);
if (this.screen != null) {
this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
@@ -180,7 +178,7 @@
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove();
}
@@ -1520,6 +_,7 @@
@@ -1529,6 +_,7 @@
}
public void stop() {
@@ -188,7 +186,7 @@
this.running = false;
}
@@ -1547,10 +_,18 @@
@@ -1556,10 +_,18 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
@@ -197,20 +195,20 @@
+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) {
+ if (inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.level.addBreakingBlockEffect(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.particleEngine.crack(blockpos, direction);
- this.level.addBreakingBlockEffect(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.level.addBreakingBlockEffect(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1578,6 +_,8 @@
@@ -1587,6 +_,8 @@
return false;
} else {
boolean flag = false;
@@ -219,7 +217,7 @@
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1585,7 +_,7 @@
@@ -1594,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
@@ -228,7 +226,7 @@
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1598,8 +_,10 @@
@@ -1607,8 +_,10 @@
}
this.player.resetAttackStrengthTicker();
@@ -239,7 +237,7 @@
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
}
@@ -1615,6 +_,12 @@
@@ -1624,6 +_,12 @@
}
for (InteractionHand interactionhand : InteractionHand.values()) {
@@ -252,7 +250,7 @@
ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return;
@@ -1635,7 +_,7 @@
@@ -1644,7 +_,7 @@
}
if (interactionresult instanceof InteractionResult.Success interactionresult$success2) {
@@ -261,7 +259,7 @@
this.player.swing(interactionhand);
}
@@ -1647,7 +_,7 @@
@@ -1656,7 +_,7 @@
int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1 instanceof InteractionResult.Success interactionresult$success) {
@@ -270,7 +268,7 @@
this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.player.hasInfiniteMaterials())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1663,6 +_,9 @@
@@ -1672,6 +_,9 @@
}
}
@@ -280,7 +278,7 @@
if (!itemstack.isEmpty()
&& this.gameMode.useItem(this.player, interactionhand) instanceof InteractionResult.Success interactionresult$success1) {
if (interactionresult$success1.swingSource() == InteractionResult.SwingSource.CLIENT) {
@@ -1692,6 +_,8 @@
@@ -1701,6 +_,8 @@
}
ProfilerFiller profilerfiller = Profiler.get();
@@ -289,7 +287,7 @@
profilerfiller.push("gui");
this.chatListener.tick();
this.gui.tick(this.pause);
@@ -1778,6 +_,7 @@
@@ -1786,6 +_,7 @@
this.tutorial.tick();
@@ -297,7 +295,7 @@
try {
this.level.tick(() -> true);
} catch (Throwable throwable1) {
@@ -1791,6 +_,7 @@
@@ -1799,6 +_,7 @@
throw new ReportedException(crashreport1);
}
@@ -305,7 +303,7 @@
}
profilerfiller.popPush("animateTick");
@@ -1815,6 +_,7 @@
@@ -1823,6 +_,7 @@
profilerfiller.popPush("keyboard");
this.keyboardHandler.tick();
profilerfiller.pop();
@@ -313,15 +311,15 @@
}
private boolean isLevelRunningNormally() {
@@ -2031,6 +_,7 @@
@@ -2041,6 +_,7 @@
}
public void setLevel(ClientLevel p_91157_, ReceivingLevelScreen.Reason p_335893_) {
public void setLevel(ClientLevel p_91157_) {
+ 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_);
@@ -2068,6 +_,7 @@
}
@@ -2094,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null;
this.gameRenderer.resetData();
@@ -329,27 +327,27 @@
this.gameMode = null;
this.narrator.clear();
this.clientLevelTeardownInProgress = true;
@@ -2075,6 +_,7 @@
@@ -2101,6 +_,7 @@
try {
this.updateScreenAndTick(p_335030_);
if (this.level != null) {
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
if (integratedserver != null) {
ProfilerFiller profilerfiller = Profiler.get();
profilerfiller.push("waitForServer");
@@ -2088,6 +_,7 @@
this.gui.onDisconnected();
this.isLocalServer = false;
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
}
if (integratedserver != null) {
@@ -2113,6 +_,7 @@
}
profilerfiller.pop();
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
}
this.level = null;
@@ -2236,6 +_,7 @@
this.setScreenAndShow(p_335030_);
@@ -2254,6 +_,7 @@
private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInputPickBlock(this.options.keyPickItem)) return;
boolean flag = Screen.hasControlDown();
boolean flag = this.hasControlDown();
switch (this.hitResult) {
case BlockHitResult blockhitresult:
@@ -1,40 +1,40 @@
--- a/net/minecraft/client/MouseHandler.java
+++ b/net/minecraft/client/MouseHandler.java
@@ -90,6 +_,7 @@
this.activeButton = -1;
@@ -87,6 +_,7 @@
this.activeButton = null;
}
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo, p_423948_)) return;
if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) {
if (!this.mouseGrabbed && flag) {
@@ -103,7 +_,7 @@
screen.afterMouseAction();
try {
- if (screen.mouseClicked(d0, d1, i)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, i)) {
long i = Util.getMillis();
boolean flag1 = i - this.lastClickTime < 250L && this.lastClickButton == mousebuttonevent.button();
- if (screen.mouseClicked(mousebuttonevent, flag1)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, mousebuttonevent, flag1)) {
this.lastClickTime = i;
this.lastClickButton = mousebuttoninfo.button();
return;
}
} catch (Throwable throwable1) {
@@ -116,7 +_,7 @@
@@ -118,7 +_,7 @@
}
} else {
try {
- if (screen.mouseReleased(d0, d1, i)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, i)) {
- if (screen.mouseReleased(mousebuttonevent)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, mousebuttonevent)) {
return;
}
} catch (Throwable throwable) {
@@ -150,6 +_,7 @@
@@ -148,6 +_,7 @@
KeyMapping.click(inputconstants$key);
}
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo, p_423948_);
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
public void fillMousePositionDetails(CrashReportCategory p_398230_, Window p_398216_) {
@@ -189,7 +_,9 @@
@@ -204,7 +_,9 @@
if (this.minecraft.screen != null) {
double d3 = this.getScaledXPos(this.minecraft.getWindow());
double d4 = this.getScaledYPos(this.minecraft.getWindow());
@@ -45,7 +45,7 @@
this.minecraft.screen.afterMouseAction();
} else if (this.minecraft.player != null) {
Vector2i vector2i = this.scrollWheelHandler.onMouseScroll(d1, d2);
@@ -198,6 +_,7 @@
@@ -213,6 +_,7 @@
}
int i = vector2i.y == 0 ? -vector2i.x : vector2i.y;
@@ -53,16 +53,16 @@
if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-i);
@@ -303,7 +_,7 @@
@@ -321,7 +_,7 @@
double d5 = getScaledYPos(window, this.accumulatedDY);
try {
- screen.mouseDragged(d2, d3, this.activeButton, d4, d5);
+ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, d2, d3, this.activeButton, d4, d5);
- screen.mouseDragged(new MouseButtonEvent(d2, d3, this.activeButton), d4, d5);
+ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(d2, d3, this.activeButton), d4, d5);
} catch (Throwable throwable) {
CrashReport crashreport1 = CrashReport.forThrowable(throwable, "mouseDragged event handler");
screen.fillCrashDetails(crashreport1);
@@ -393,6 +_,14 @@
@@ -408,6 +_,14 @@
public double ypos() {
return this.ypos;
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Options.java
+++ b/net/minecraft/client/Options.java
@@ -671,7 +_,8 @@
@@ -709,7 +_,8 @@
},
new OptionInstance.LazyEnum<>(
() -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(),
@@ -10,7 +10,7 @@
? Optional.empty()
: Optional.of(p_232011_),
Codec.STRING
@@ -705,6 +_,7 @@
@@ -743,6 +_,7 @@
);
public boolean syncWrites;
public boolean startedCleanly = true;
@@ -18,7 +18,7 @@
public OptionInstance<Boolean> darkMojangStudiosBackground() {
return this.darkMojangStudiosBackground;
@@ -1088,6 +_,7 @@
@@ -1150,6 +_,7 @@
}
public Options(Minecraft p_92138_, File p_92139_) {
@@ -26,7 +26,7 @@
this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L;
@@ -1222,15 +_,28 @@
@@ -1290,15 +_,28 @@
this.startedCleanly = p_168428_.process("startedCleanly", this.startedCleanly);
p_168428_.process("showNowPlayingToast", this.showNowPlayingToast);
p_168428_.process("musicFrequency", this.musicFrequency);
@@ -56,7 +56,7 @@
for (SoundSource soundsource : SoundSource.values()) {
p_168428_.process("soundCategory_" + soundsource.getName(), this.soundSourceVolumes.get(soundsource));
}
@@ -1245,6 +_,10 @@
@@ -1313,6 +_,10 @@
}
public void load() {
@@ -67,7 +67,7 @@
try {
if (!this.optionsFile.exists()) {
return;
@@ -1269,7 +_,8 @@
@@ -1337,7 +_,8 @@
this.graphicsMode.set(isTrue(optional.get()) ? GraphicsStatus.FANCY : GraphicsStatus.FAST);
}
@@ -77,7 +77,7 @@
new Options.FieldAccess() {
@Nullable
private String getValue(String p_394210_) {
@@ -1350,6 +_,17 @@
@@ -1418,6 +_,17 @@
);
compoundtag1.getString("fullscreenResolution").ifPresent(p_389133_ -> this.fullscreenVideoModeString = p_389133_);
KeyMapping.resetMapping();
@@ -95,7 +95,7 @@
} catch (Exception exception) {
LOGGER.error("Failed to load options", (Throwable)exception);
}
@@ -1377,9 +_,11 @@
@@ -1445,9 +_,11 @@
public void save() {
try (final PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) {
printwriter.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version());
@@ -107,7 +107,7 @@
printwriter.print(p_168491_);
printwriter.print(':');
}
@@ -1435,6 +_,12 @@
@@ -1503,6 +_,12 @@
if (s != null) {
printwriter.println("fullscreenResolution:" + s);
}
@@ -120,7 +120,7 @@
} catch (Exception exception) {
LOGGER.error("Failed to save options", (Throwable)exception);
}
@@ -1473,6 +_,7 @@
@@ -1541,6 +_,7 @@
}
public void broadcastOptions() {
@@ -128,7 +128,7 @@
if (this.minecraft.player != null) {
this.minecraft.player.connection.broadcastClientInformation(this.buildPlayerInformation());
}
@@ -1586,6 +_,23 @@
@@ -1654,6 +_,23 @@
public static Component genericValueLabel(Component p_231901_, int p_231902_) {
return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_)));
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/ToggleKeyMapping.java
+++ b/net/minecraft/client/ToggleKeyMapping.java
@@ -17,7 +_,7 @@
@@ -31,7 +_,7 @@
@Override
public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) {
@@ -9,7 +9,7 @@
super.setDown(!this.isDown());
}
} else {
@@ -27,5 +_,9 @@
@@ -56,5 +_,9 @@
protected void reset() {
super.setDown(false);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/data/models/ItemModelGenerators.java
+++ b/net/minecraft/client/data/models/ItemModelGenerators.java
@@ -871,6 +_,9 @@
@@ -882,6 +_,9 @@
this.declareCustomModelItem(Items.COD);
this.declareCustomModelItem(Items.FEATHER);
this.declareCustomModelItem(Items.LEAD);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/Font.java
+++ b/net/minecraft/client/gui/Font.java
@@ -32,7 +_,7 @@
@@ -31,7 +_,7 @@
import org.joml.Matrix4f;
@OnlyIn(Dist.CLIENT)
@@ -9,7 +9,26 @@
private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList;
@@ -377,7 +_,7 @@
@@ -196,6 +_,7 @@
() -> new JumpableVehicleBarRenderer(p_330021_)
);
this.resetTitleTimes();
+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.init(this, p_330021_);
}
public void resetTitleTimes() {
@@ -206,6 +_,10 @@
public void render(GuiGraphics p_282884_, DeltaTracker p_342095_) {
if (!(this.minecraft.screen instanceof LevelLoadingScreen)) {
+ if (Boolean.valueOf(true)) {
+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.beginRender(p_282884_, p_342095_);
+ return;
+ }
if (!this.minecraft.options.hideGui) {
this.renderCameraOverlays(p_282884_, p_342095_);
this.renderCrosshair(p_282884_, p_342095_);
@@ -389,7 +_,7 @@
int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window));
int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window));
p_329202_.nextStratum();
@@ -18,7 +37,7 @@
}
}
@@ -472,6 +_,8 @@
@@ -477,6 +_,8 @@
for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
Holder<MobEffect> holder = mobeffectinstance.getEffect();
@@ -27,7 +46,7 @@
if (mobeffectinstance.showIcon()) {
int k = p_282812_.guiWidth();
int l = 1;
@@ -502,6 +_,7 @@
@@ -507,6 +_,7 @@
}
}
@@ -35,10 +54,25 @@
p_282812_.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(holder), k + 3, l + 3, 18, 18, ARGB.white(f));
}
}
@@ -598,6 +_,10 @@
@@ -602,7 +_,25 @@
}
}
private void renderSelectedItemName(GuiGraphics p_283501_) {
+ // Forge: Maintain vanilla parity during FLD#BACKGROUND
+ public final void updateContextualInfo(final GuiGraphics graphics, DeltaTracker deltaTracker) {
+ var nextContextualInfo = this.nextContextualInfoState();
+ if (nextContextualInfo != this.contextualInfoBar.getKey()) {
+ this.contextualInfoBar = Pair.of(nextContextualInfo, this.contextualInfoBarRenderers.get(nextContextualInfo).get());
+ }
+
+ this.contextualInfoBar.getValue().renderBackground(graphics, deltaTracker);
+ }
+ // Forge: Same as above but for FLD#CONTEXTUAL_INFO
+ public final void extractContextualInfoState(final GuiGraphics graphics, DeltaTracker deltaTracker) {
+ this.contextualInfoBar.getValue().render(graphics, deltaTracker);
+ }
+
public void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+
@@ -46,7 +80,7 @@
Profiler.get().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color());
@@ -605,9 +_,13 @@
@@ -610,9 +_,13 @@
mutablecomponent.withStyle(ChatFormatting.ITALIC);
}
@@ -62,7 +96,7 @@
if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14;
}
@@ -618,7 +_,7 @@
@@ -623,7 +_,7 @@
}
if (l > 0) {
@@ -71,7 +105,7 @@
}
}
@@ -1148,7 +_,7 @@
@@ -1151,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelectedItem();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/GuiGraphics.java
+++ b/net/minecraft/client/gui/GuiGraphics.java
@@ -72,7 +_,7 @@
@@ -83,7 +_,7 @@
import org.joml.Vector3f;
@OnlyIn(Dist.CLIENT)
@@ -9,7 +9,7 @@
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
private final Minecraft minecraft;
private final Matrix3x2fStack pose;
@@ -875,6 +_,7 @@
@@ -950,6 +_,7 @@
CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item");
CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered");
crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_283653_.getItem()));
@@ -17,7 +17,7 @@
crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_283653_.getComponents()));
crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_283653_.hasFoil()));
throw new ReportedException(crashreport);
@@ -893,6 +_,7 @@
@@ -968,6 +_,7 @@
this.renderItemCooldown(p_283349_, p_282641_, p_282146_);
this.renderItemCount(p_282005_, p_283349_, p_282641_, p_282146_, p_282803_);
this.pose.popMatrix();
@@ -25,7 +25,7 @@
}
}
@@ -904,21 +_,30 @@
@@ -979,21 +_,30 @@
this.setTooltipForNextFrame(this.minecraft.font, p_407686_, DefaultTooltipPositioner.INSTANCE, p_410475_, p_407139_, false);
}
@@ -58,7 +58,7 @@
this.setTooltipForNextFrameInternal(p_407847_, list, p_409369_, p_407472_, DefaultTooltipPositioner.INSTANCE, p_410303_, false);
}
@@ -931,7 +_,22 @@
@@ -1006,7 +_,22 @@
}
public void setComponentTooltipForNextFrame(Font p_406239_, List<Component> p_410275_, int p_410594_, int p_409343_) {
@@ -82,11 +82,31 @@
}
public void setComponentTooltipForNextFrame(Font p_408650_, List<Component> p_407512_, int p_406019_, int p_408123_, @Nullable ResourceLocation p_409993_) {
@@ -994,11 +_,13 @@
ClientTooltipPositioner p_409451_,
@Nullable ResourceLocation p_409298_
@@ -1056,9 +_,14 @@
) {
+ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283678_, p_281696_, guiWidth(), guiHeight(), p_282716_, p_283128_, p_409451_);
if (!p_409928_.isEmpty()) {
if (this.deferredTooltip == null || p_410618_) {
- this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_407676_);
+ final var stackContext = this.tooltipStack;
+ this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_407676_, stackContext);
}
}
+ }
+
+ public void renderTooltip(Font p_283128_, List<ClientTooltipComponent> p_282716_, int p_283678_, int p_281696_, ClientTooltipPositioner p_409451_, @Nullable ResourceLocation p_409298_) {
+ renderTooltip(p_283128_, p_282716_, p_283678_, p_281696_, p_409451_, p_409298_, ItemStack.EMPTY);
}
public void renderTooltip(
@@ -1067,13 +_,16 @@
int p_283678_,
int p_281696_,
ClientTooltipPositioner p_409451_,
- @Nullable ResourceLocation p_409298_
+ @Nullable ResourceLocation p_409298_,
+ ItemStack itemstack
) {
+ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(itemstack, this, p_283678_, p_281696_, guiWidth(), guiHeight(), p_282716_, p_283128_, p_409451_, p_409298_);
+ if (preEvent == null) return;
int i = 0;
int j = p_282716_.size() == 1 ? -2 : 0;
@@ -97,7 +117,7 @@
if (k > i) {
i = k;
}
@@ -1008,16 +_,17 @@
@@ -1083,16 +_,16 @@
int l1 = i;
int i2 = j;
@@ -107,8 +127,7 @@
int i1 = vector2ic.y();
this.pose.pushMatrix();
- TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, p_409298_);
+ var background_event = net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTooltipBackground(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282716_, p_409298_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, background_event.getBackground());
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, preEvent.getBackground());
int j1 = i1;
for (int k1 = 0; k1 < p_282716_.size(); k1++) {
@@ -118,7 +137,7 @@
j1 += clienttooltipcomponent1.getHeight(p_283128_) + (k1 == 0 ? 2 : 0);
}
@@ -1025,7 +_,7 @@
@@ -1100,7 +_,7 @@
for (int j2 = 0; j2 < p_282716_.size(); j2++) {
ClientTooltipComponent clienttooltipcomponent2 = p_282716_.get(j2);
@@ -127,7 +146,7 @@
j1 += clienttooltipcomponent2.getHeight(p_283128_) + (j2 == 0 ? 2 : 0);
}
@@ -1222,6 +_,14 @@
@@ -1315,6 +_,14 @@
public void submitProfilerChartRenderState(List<ResultField> p_408565_, int p_410147_, int p_406156_, int p_407365_, int p_408180_) {
this.guiRenderState.submitPicturesInPictureState(new GuiProfilerChartRenderState(p_408565_, p_410147_, p_406156_, p_407365_, p_408180_, this.scissorStack.peek()));
@@ -141,4 +160,4 @@
+ return this.scissorStack;
}
@OnlyIn(Dist.CLIENT)
public TextureAtlasSprite getSprite(Material p_430745_) {
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/components/AbstractButton.java
+++ b/net/minecraft/client/gui/components/AbstractButton.java
@@ -38,7 +_,7 @@
@@ -41,7 +_,7 @@
this.getHeight(),
ARGB.white(this.alpha)
);
- int i = ARGB.color(this.alpha, this.active ? -1 : -6250336);
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i);
}
if (this.isHovered()) {
p_281670_.requestCursor(this.isActive() ? CursorTypes.POINTING_HAND : CursorTypes.NOT_ALLOWED);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/components/AbstractWidget.java
+++ b/net/minecraft/client/gui/components/AbstractWidget.java
@@ -236,6 +_,25 @@
@@ -238,6 +_,25 @@
this.focused = p_93693_;
}
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/components/Button.java
+++ b/net/minecraft/client/gui/components/Button.java
@@ -31,6 +_,12 @@
@@ -32,6 +_,12 @@
this.createNarration = p_259552_;
}
@@ -11,9 +11,9 @@
+ }
+
@Override
public void onPress() {
public void onPress(InputWithModifiers p_424878_) {
this.onPress.onPress(this);
@@ -95,9 +_,12 @@
@@ -96,9 +_,12 @@
}
public Button build() {
@@ -1,101 +0,0 @@
--- a/net/minecraft/client/gui/components/DebugScreenOverlay.java
+++ b/net/minecraft/client/gui/components/DebugScreenOverlay.java
@@ -139,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);
@@ -183,15 +_,19 @@
this.clientChunk = null;
}
- public void render(GuiGraphics p_281427_) {
- ProfilerFiller profilerfiller = Profiler.get();
- profilerfiller.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);
+ }
+
+ protected void drawText(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
this.drawGameInformation(p_281427_);
this.drawSystemInformation(p_281427_);
p_281427_.nextStratum();
+ }
+
+ protected void drawFPSCharts(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
this.profilerPieChart.setBottomOffset(10);
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
@@ -204,7 +_,9 @@
this.profilerPieChart.setBottomOffset(this.tpsChart.getFullHeight());
}
+ }
+ protected void drawNetworkCharts(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -220,12 +_,22 @@
try (Zone zone = profilerfiller.zone("profilerPie")) {
this.profilerPieChart.render(p_281427_);
}
+ }
+
+ public void render(GuiGraphics p_281427_) {
+ ProfilerFiller profilerfiller = Profiler.get();
+ profilerfiller.push("debug");
+ this.update();
+
+ this.drawText(profilerfiller, p_281427_);
+ this.drawFPSCharts(profilerfiller, p_281427_);
+ this.drawNetworkCharts(profilerfiller, p_281427_);
profilerfiller.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(
@@ -239,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());
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281525_, minecraft.getWindow(), minecraft.getDeltaTracker().getRealtimeDeltaTicks(), list, true);
+ this.renderLines(p_281525_, list, true);
}
protected void drawSystemInformation(GuiGraphics p_281261_) {
List<String> list = this.getSystemInformation();
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281261_, minecraft.getWindow(), minecraft.getDeltaTracker().getRealtimeDeltaTicks(), list, false);
this.renderLines(p_281261_, list, false);
}
@@ -597,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;
@@ -0,0 +1,10 @@
--- a/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java
+++ b/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java
@@ -25,6 +_,7 @@
if (entity != null) {
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()));
}
p_426755_.addToGroup(GROUP, list);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/render/GuiRenderer.java
+++ b/net/minecraft/client/gui/render/GuiRenderer.java
@@ -134,6 +_,7 @@
@@ -146,6 +_,7 @@
builder.put((Class<? extends PictureInPictureRenderState>)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer);
}
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/ChatScreen.java
+++ b/net/minecraft/client/gui/screens/ChatScreen.java
@@ -89,6 +_,7 @@
return true;
} else if (p_95591_ == 257 || p_95591_ == 335) {
@@ -115,6 +_,7 @@
} else if (p_426273_.isConfirmation()) {
this.handleChatInput(this.input.getValue(), true);
this.exitReason = ChatScreen.ExitReason.DONE;
+ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened.
this.minecraft.setScreen(null);
return true;
} else if (p_95591_ == 265) {
} else {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/ConnectScreen.java
+++ b/net/minecraft/client/gui/screens/ConnectScreen.java
@@ -102,6 +_,8 @@
@@ -103,6 +_,8 @@
}
if (optional.isEmpty()) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/LoadingOverlay.java
+++ b/net/minecraft/client/gui/screens/LoadingOverlay.java
@@ -61,6 +_,8 @@
@@ -62,6 +_,8 @@
return p_169325_ & 16777215 | p_169326_ << 24;
}
@@ -9,7 +9,7 @@
@Override
public void render(GuiGraphics p_281839_, int p_282704_, int p_283650_, float p_283394_) {
int i = p_281839_.guiWidth();
@@ -97,6 +_,7 @@
@@ -102,6 +_,7 @@
f2 = 1.0F;
}
@@ -17,7 +17,7 @@
int l2 = (int)(p_281839_.guiWidth() * 0.5);
int i1 = (int)(p_281839_.guiHeight() * 0.5);
double d0 = Math.min(p_281839_.guiWidth() * 0.75, (double)p_281839_.guiHeight()) * 0.25;
@@ -112,12 +_,14 @@
@@ -117,6 +_,7 @@
if (f < 1.0F) {
this.drawProgressBar(p_281839_, i / 2 - k1, i2 - 5, i / 2 + k1, i2 + 5, 1.0F - Mth.clamp(f, 0.0F, 1.0F));
}
@@ -25,18 +25,19 @@
if (f >= 2.0F) {
this.minecraft.setOverlay(null);
}
if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
@@ -126,6 +_,7 @@
@Override
public void tick() {
if (this.fadeOutStart == -1L && this.reload.isDone() && this.isReadyToFadeOut()) {
+ this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback
try {
this.reload.checkExceptions();
this.onFinish.accept(Optional.empty());
@@ -125,7 +_,6 @@
@@ -133,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());
}
Window window = this.minecraft.getWindow();
this.minecraft.screen.init(this.minecraft, window.getGuiScaledWidth(), window.getGuiScaledHeight());
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -105,6 +_,7 @@
@@ -103,6 +_,7 @@
} else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this)));
}
@@ -9,7 +9,7 @@
}
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -339,8 +_,10 @@
@@ -343,8 +_,10 @@
this.width = p_96608_;
this.height = p_96609_;
if (!this.initialized) {
@@ -20,7 +20,7 @@
} else {
this.repositionElements();
}
@@ -353,8 +_,10 @@
@@ -361,8 +_,10 @@
protected void rebuildWidgets() {
this.clearWidgets();
this.clearFocus();
@@ -31,15 +31,16 @@
}
protected void fadeWidgets(float p_409453_) {
@@ -389,6 +_,7 @@
@@ -402,6 +_,8 @@
this.renderMenuBackground(p_283688_);
}
this.renderBlurredBackground(p_283688_);
this.renderMenuBackground(p_283688_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_);
+
this.minecraft.gui.renderDeferredSubtitles();
}
protected void renderBlurredBackground(GuiGraphics p_407253_) {
@@ -492,6 +_,19 @@
@@ -484,6 +_,19 @@
}
public void onFilesDrop(List<Path> p_96591_) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/TitleScreen.java
+++ b/net/minecraft/client/gui/screens/TitleScreen.java
@@ -54,6 +_,7 @@
@@ -55,6 +_,7 @@
private boolean fading;
private long fadeInStart;
private final LogoRenderer logoRenderer;
@@ -8,7 +8,7 @@
public TitleScreen() {
this(false);
@@ -106,11 +_,15 @@
@@ -107,11 +_,15 @@
int j = this.width - i - 2;
int k = 24;
int l = this.height / 4 + 48;
@@ -24,7 +24,7 @@
l = this.createTestWorldButton(l, 24);
SpriteIconButton spriteiconbutton = this.addRenderableWidget(
@@ -175,7 +_,7 @@
@@ -178,7 +_,7 @@
}).bounds(this.width / 2 - 100, i = p_96764_ + p_96765_, 200, 20).tooltip(tooltip).build()).active = flag;
this.addRenderableWidget(
Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this)))
@@ -33,7 +33,7 @@
.tooltip(tooltip)
.build()
)
@@ -295,9 +_,18 @@
@@ -298,9 +_,18 @@
s = s + I18n.get("menu.modded");
}
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
@@ -51,6 +_,7 @@
@@ -53,6 +_,7 @@
@Nullable
private AdvancementTab selectedTab;
private boolean isScrolling;
@@ -8,7 +8,7 @@
public AdvancementsScreen(ClientAdvancements p_97340_) {
this(p_97340_, null);
@@ -64,6 +_,19 @@
@@ -66,6 +_,19 @@
@Override
protected void init() {
@@ -28,16 +28,16 @@
this.layout.addTitleHeader(TITLE, this.font);
this.tabs.clear();
this.selectedTab = null;
@@ -108,7 +_,7 @@
@@ -110,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_)) {
- if (advancementtab.isMouseOver(i, j, p_431395_.x(), p_431395_.y())) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_431395_.x(), p_431395_.y())) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break;
}
@@ -183,10 +_,12 @@
@@ -185,10 +_,12 @@
p_283395_.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, p_281890_, p_282532_, 0.0F, 0.0F, 252, 140, 256, 256);
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
@@ -50,7 +50,7 @@
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
}
}
@@ -205,6 +_,7 @@
@@ -207,6 +_,7 @@
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
@@ -107,6 +_,7 @@
@@ -105,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
super.render(p_409971_, p_409213_, p_408205_, p_408282_);
@@ -8,7 +8,7 @@
p_409971_.pose().pushMatrix();
p_409971_.pose().translate(i, j);
this.renderLabels(p_409971_, p_409213_, p_408205_);
@@ -119,6 +_,8 @@
@@ -117,6 +_,8 @@
this.onStopHovering(slot);
}
@@ -17,7 +17,7 @@
p_409971_.pose().popMatrix();
}
@@ -202,7 +_,7 @@
@@ -200,7 +_,7 @@
ItemStack itemstack = this.hoveredSlot.getItem();
if (this.menu.getCarried().isEmpty() || this.showTooltipWithItemInHand(itemstack)) {
p_283594_.setTooltipForNextFrame(
@@ -26,7 +26,7 @@
);
}
}
@@ -218,7 +_,8 @@
@@ -216,7 +_,8 @@
private void renderFloatingItem(GuiGraphics p_282567_, ItemStack p_281330_, int p_281772_, int p_281689_, @Nullable String p_282568_) {
p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
@@ -36,87 +36,84 @@
}
protected void renderLabels(GuiGraphics p_281635_, int p_282681_, int p_283686_) {
@@ -319,7 +_,8 @@
if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
@@ -317,7 +_,8 @@
if (super.mouseClicked(p_427253_, p_427622_)) {
return true;
} else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.player.hasInfiniteMaterials();
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.getHoveredSlot(p_97748_, p_97749_);
long i = Util.getMillis();
this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -330,6 +_,7 @@
int j = this.leftPos;
int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_427253_) && this.minecraft.player.hasInfiniteMaterials();
+ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(p_427253_.button());
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials();
Slot slot = this.getHoveredSlot(p_427253_.x(), p_427253_.y());
this.doubleclick = this.lastClickSlot == slot && p_427622_;
this.skipNextRelease = false;
@@ -327,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
boolean flag1 = this.hasClickedOutside(p_427253_.x(), p_427253_.y(), i, j);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int l = -1;
int k = -1;
if (slot != null) {
l = slot.index;
@@ -355,7 +_,7 @@
k = slot.index;
@@ -352,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);
this.slotClicked(slot, k, p_427253_.button(), ClickType.CLONE);
} else {
boolean flag2 = l != -999
@@ -383,7 +_,7 @@
boolean flag2 = k != -999 && p_427253_.hasShiftDown();
@@ -376,7 +_,7 @@
this.quickCraftingType = 0;
} else if (p_97750_ == 1) {
} else if (p_427253_.button() == 1) {
this.quickCraftingType = 1;
- } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2;
}
}
@@ -459,10 +_,13 @@
@@ -453,10 +_,13 @@
@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.getHoveredSlot(p_97812_, p_97813_);
public boolean mouseReleased(MouseButtonEvent p_430939_) {
+ super.mouseReleased(p_430939_); //Forge, Call parent to release buttons
Slot slot = this.getHoveredSlot(p_430939_.x(), p_430939_.y());
int i = this.leftPos;
int j = this.topPos;
boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
boolean flag = this.hasClickedOutside(p_430939_.x(), p_430939_.y(), i, j);
+ 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_);
+ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(p_430939_.button());
int k = -1;
if (slot != null) {
k = slot.index;
@@ -479,7 +_,7 @@
@@ -473,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);
this.slotClicked(slot2, slot2.index, p_430939_.button(), ClickType.QUICK_MOVE);
}
@@ -545,7 +_,7 @@
@@ -538,7 +_,7 @@
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.matchesMouse(p_430939_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
this.slotClicked(slot, k, p_430939_.button(), ClickType.CLONE);
} else {
boolean flag1 = k != -999
@@ -622,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_)) {
boolean flag1 = k != -999 && p_430939_.hasShiftDown();
@@ -609,7 +_,7 @@
public boolean keyPressed(KeyEvent p_424324_) {
if (super.keyPressed(p_424324_)) {
return true;
- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
- } else if (this.minecraft.options.keyInventory.matches(p_424324_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(com.mojang.blaze3d.platform.InputConstants.getKey(p_424324_))) {
this.onClose();
return true;
} else {
@@ -698,6 +_,13 @@
@@ -688,6 +_,13 @@
super.onClose();
}
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java
@@ -113,6 +_,8 @@
@@ -116,6 +_,8 @@
private final Set<TagKey<Item>> visibleTags = new HashSet<>();
private final boolean displayOperatorCreativeTab;
private final EffectsInInventory effects;
@@ -9,7 +9,7 @@
public CreativeModeInventoryScreen(LocalPlayer p_344408_, FeatureFlagSet p_260074_, boolean p_259569_) {
super(new CreativeModeInventoryScreen.ItemPickerMenu(p_344408_), p_344408_.getInventory(), CommonComponents.EMPTY);
@@ -161,7 +_,7 @@
@@ -164,7 +_,7 @@
private void refreshCurrentTabContents(Collection<ItemStack> p_261591_) {
int i = this.menu.getRowIndexForScroll(this.scrollOffs);
this.menu.items.clear();
@@ -18,7 +18,7 @@
this.refreshSearchResults();
} else {
this.menu.items.addAll(p_261591_);
@@ -329,6 +_,35 @@
@@ -332,6 +_,36 @@
protected void init() {
if (this.minecraft.player.hasInfiniteMaterials()) {
super.init();
@@ -26,6 +26,7 @@
+ int tabIndex = 0;
+ List<CreativeModeTab> currentPage = new java.util.ArrayList<>();
+ for (CreativeModeTab sortedCreativeModeTab : net.minecraftforge.common.CreativeModeTabRegistry.getSortedCreativeModeTabs()) {
+ if (!sortedCreativeModeTab.shouldDisplay()) continue;
+ currentPage.add(sortedCreativeModeTab);
+ tabIndex++;
+ if (tabIndex == 10) {
@@ -54,8 +55,8 @@
this.searchBox = new EditBox(this.font, this.leftPos + 82, this.topPos + 6, 80, 9, Component.translatable("itemGroup.search"));
this.searchBox.setMaxLength(50);
this.searchBox.setBordered(false);
@@ -375,7 +_,7 @@
public boolean charTyped(char p_98521_, int p_98522_) {
@@ -378,7 +_,7 @@
public boolean charTyped(CharacterEvent p_424087_) {
if (this.ignoreTextInput) {
return false;
- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
@@ -63,16 +64,16 @@
return false;
} else {
String s = this.searchBox.getValue();
@@ -394,7 +_,7 @@
@@ -397,7 +_,7 @@
@Override
public boolean keyPressed(int p_98547_, int p_98548_, int p_98549_) {
public boolean keyPressed(KeyEvent p_429237_) {
this.ignoreTextInput = false;
- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
+ if (!selectedTab.hasSearchBar()) {
if (this.minecraft.options.keyChat.matches(p_98547_, p_98548_)) {
if (this.minecraft.options.keyChat.matches(p_429237_)) {
this.ignoreTextInput = true;
this.selectTab(CreativeModeTabs.searchTab());
@@ -430,6 +_,7 @@
@@ -433,6 +_,7 @@
}
private void refreshSearchResults() {
@@ -80,7 +81,7 @@
this.menu.items.clear();
this.visibleTags.clear();
String s = this.searchBox.getValue();
@@ -442,10 +_,10 @@
@@ -445,10 +_,10 @@
SearchTree<ItemStack> searchtree;
if (s.startsWith("#")) {
s = s.substring(1);
@@ -93,7 +94,7 @@
}
this.menu.items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT)));
@@ -477,7 +_,8 @@
@@ -480,7 +_,8 @@
@Override
protected void renderLabels(GuiGraphics p_283168_, int p_281774_, int p_281466_) {
if (selectedTab.showTitle()) {
@@ -103,17 +104,17 @@
}
}
@@ -487,7 +_,7 @@
double d0 = p_98531_ - this.leftPos;
double d1 = p_98532_ - this.topPos;
@@ -490,7 +_,7 @@
double d0 = p_430803_.x() - this.leftPos;
double d1 = p_430803_.y() - this.topPos;
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabClicked(creativemodetab, d0, d1)) {
return true;
}
@@ -509,7 +_,7 @@
double d1 = p_98623_ - this.topPos;
@@ -512,7 +_,7 @@
double d1 = p_423848_.y() - this.topPos;
this.scrolling = false;
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
@@ -121,7 +122,7 @@
if (this.checkTabClicked(creativemodetab, d0, d1)) {
this.selectTab(creativemodetab);
return true;
@@ -603,13 +_,15 @@
@@ -606,13 +_,15 @@
this.originalSlots = null;
}
@@ -138,7 +139,7 @@
this.refreshSearchResults();
} else {
@@ -673,7 +_,14 @@
@@ -676,7 +_,14 @@
super.render(p_283000_, p_281317_, p_282770_, p_281295_);
this.effects.renderTooltip(p_283000_, p_281317_, p_282770_);
@@ -154,7 +155,7 @@
if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) {
break;
}
@@ -697,7 +_,7 @@
@@ -700,7 +_,7 @@
public List<Component> getTooltipFromContainerItem(ItemStack p_281769_) {
boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot;
boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY;
@@ -163,7 +164,7 @@
TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL;
TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default;
List<Component> list = p_281769_.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipflag);
@@ -718,7 +_,7 @@
@@ -721,7 +_,7 @@
int i = 1;
for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
@@ -172,7 +173,7 @@
list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE));
}
}
@@ -729,7 +_,7 @@
@@ -732,7 +_,7 @@
@Override
protected void renderBg(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) {
@@ -181,7 +182,7 @@
if (creativemodetab != selectedTab) {
this.renderTabButton(p_282663_, creativemodetab);
}
@@ -745,6 +_,7 @@
@@ -748,6 +_,7 @@
p_282663_.blitSprite(RenderPipelines.GUI_TEXTURED, resourcelocation, j, k + (int)((i - k - 17) * this.scrollOffs), 12, 15);
}
@@ -189,7 +190,7 @@
this.renderTabButton(p_282663_, selectedTab);
if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) {
InventoryScreen.renderEntityInInventoryFollowsMouse(
@@ -763,7 +_,7 @@
@@ -766,7 +_,7 @@
}
private int getTabX(CreativeModeTab p_260136_) {
@@ -198,7 +199,7 @@
int j = 27;
int k = 27 * i;
if (p_260136_.isAlignedRight()) {
@@ -775,7 +_,7 @@
@@ -778,7 +_,7 @@
private int getTabY(CreativeModeTab p_260181_) {
int i = 0;
@@ -207,7 +208,7 @@
i -= 32;
} else {
i += this.imageHeight;
@@ -803,8 +_,8 @@
@@ -806,8 +_,8 @@
protected void renderTabButton(GuiGraphics p_283590_, CreativeModeTab p_283489_) {
boolean flag = p_283489_ == selectedTab;
@@ -218,7 +219,7 @@
int j = this.leftPos + this.getTabX(p_283489_);
int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4));
ResourceLocation[] aresourcelocation;
@@ -814,6 +_,7 @@
@@ -817,6 +_,7 @@
aresourcelocation = flag ? SELECTED_BOTTOM_TABS : UNSELECTED_BOTTOM_TABS;
}
@@ -226,7 +227,7 @@
p_283590_.blitSprite(RenderPipelines.GUI_TEXTURED, aresourcelocation[Mth.clamp(i, 0, aresourcelocation.length)], j, k, 26, 32);
int l = j + 13 - 8;
int i1 = k + 16 - 8 + (flag1 ? 1 : -1);
@@ -850,6 +_,14 @@
@@ -853,6 +_,14 @@
}
}
@@ -241,7 +242,7 @@
@OnlyIn(Dist.CLIENT)
static class CustomCreativeSlot extends Slot {
public CustomCreativeSlot(Container p_98633_, int p_98634_, int p_98635_, int p_98636_) {
@@ -1031,6 +_,22 @@
@@ -1034,6 +_,22 @@
@Override
public boolean mayPickup(Player p_98665_) {
return this.target.mayPickup(p_98665_);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java
@@ -106,7 +_,7 @@
@@ -107,7 +_,7 @@
int l1 = 86 - this.font.width(s);
FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1);
int i2 = -9937334;
@@ -9,7 +9,7 @@
p_282430_.blitSprite(RenderPipelines.GUI_TEXTURED, ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19);
p_282430_.blitSprite(RenderPipelines.GUI_TEXTURED, DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16);
p_282430_.drawWordWrap(this.font, formattedtext, j1, j + 16 + 19 * l, l1, ARGB.opaque((i2 & 16711422) >> 1), false);
@@ -157,13 +_,16 @@
@@ -158,13 +_,16 @@
.registryAccess()
.lookupOrThrow(Registries.ENCHANTMENT)
.get(this.menu.enchantClue[j]);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/inventory/MerchantScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/MerchantScreen.java
@@ -229,6 +_,14 @@
@@ -230,6 +_,14 @@
} else {
p_281357_.renderItemDecorations(this.font, p_282046_, p_282403_, p_283601_, p_282046_.getCount() == 1 ? "1" : null);
p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_ + 14, p_283601_, p_283466_.getCount() == 1 ? "1" : null);
Loaded 100 of 657 files, more files were not shown because too many files have changed in this diff. Show more