Compare commits

..
51 Commits
Author SHA1 Message Date
LexManos b6e4191997 Add protection against large network channel lists 2026-10-14 19:37:35 -07:00
LexManos d01b4128b0 Fix legacy object holders not being fired in the registry specific codepath
Better optimize the scanning for object holders by unrolling streams.
2026-10-13 10:35:28 -07:00
BonsUnleashedandLexManos 6162ec30bd Store object holder handlers per registry name (#10899)
Co-authored-by: LexManos <[email protected]>
2026-10-12 16:19:07 -07:00
LexManos 96ffdf9ee5 Update SRGUtils and Fix new eclipse compiler issue 2026-10-12 16:19:05 -07:00
Paint_NinjaandMartijn van den Brand 23856b57a9 Fix IForgeBlockStateModel.getModelData not being called correct for #getParticleIcon (#10818) (#10874)
Co-authored-by: Martijn van den Brand <[email protected]>
2026-08-15 00:41:45 -07:00
Meme Man 855bafc581 Update equality check for RegistryObject to include RegistryObject#key. (#10867) 2026-08-04 19:09:43 +01:00
Matt a42ea9bc2c Add DeltaTracker (partialTick) context to PassDefinitions (#10831) (#10851) 2026-07-21 16:09:23 -07:00
Matt a6eea5a004 Toml parsing errors are now visible in the latest log (#10839) 2026-07-09 12:34:25 -07:00
Matt 451c3a1f0a Add support for multiple access transformer configs. 2026-03-23 12:14:09 -07:00
Jonathing a6f68087b4 Migrate the MDK to ForgeGradle 7
Backport of d29524b to 1.21.8
2026-03-18 22:49:16 +00:00
Paint_Ninja ae3985f882 Bump ASM to 9.9.1 and EventBus to 7.0.1 2026-03-17 20:05:22 +00:00
Paint_Ninja 0f6951b560 Skip processing vanilla classes in RuntimeDistCleaner when running on a client
Backport of #10682 to 1.21.8
2026-03-17 19:55:18 +00:00
LexManos 19f6b6c294 Update SecureModules to address ZipPath bug with brackets. Closes #10755 2026-01-20 18:23:14 -08:00
LexManos 9441128b1a Fix Entity patch line numbers 2026-01-15 12:42:59 -08:00
MattandLexManos b9d842a484 Optimize memory allocation for checking entity fluid collisions. Backport of #10745 (#10749)
Co-authored-by: LexManos <[email protected]>
2026-01-15 10:34:47 -08:00
LexManos eb884f4f61 Mark applyServerBinpatches as a dependency of BundleList. Fixes: #10729 2025-12-04 08:52:37 -08:00
LexManos 74d2f1c7c3 Migrate to Github Actions 2025-12-02 14:17:14 -08:00
cech12 e75f0b67fe Fixes shearing leads for custom shears (interacting with entity & leash knot) (#10706) 2025-11-19 17:39:39 -08:00
Matt fae5c92daf Fix ItemStack context in RenderTooltipEvent.Pre (#10655) (#10658) 2025-11-14 07:08:10 -08:00
Paint_Ninja 60110cd916 Fix implicit Bus.BOTH not working in @EventBusSubscriber, add additional validation in strict mode, partial backport of #10676 2025-10-05 15:15:25 +01: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
LexManos 1e154cbe3e Minecraft 1.21.7 - Lava Chickens! 2025-06-30 11:06:39 -07:00
Paint_NinjaandLexManos d5c5df1b64 Bump ASM and EventBus
Improves support for Java 25 and better stability of the compile-time EventBus checks, respectively.

Co-Authored-By: LexManos <[email protected]>
2025-06-25 20:54:00 +01:00
Joseph T. McQuigg 5e75de5eb7 Add WanderTradesEvent#Pool Constructor with List<ItemListing> and int directly (#10566) 2025-06-23 17:06:32 -07:00
Mysticdrew ddb1e52e99 Fix client commands not working when using clickable commands. 2025-06-20 14:39:16 -07:00
Mysticdrew 9e55363e2c Add Event for Picture in Picture renderers registration. 2025-06-20 14:21:27 -07:00
Paint_Ninja 219abfed22 Make more events records 2025-06-20 18:22:53 +01:00
Paint_Ninja 6915753b5a Fix posting cancellable child events with non-cancellable inheritable parents
Also made more events SelfDestructing to save a tad more memory
2025-06-20 10:16:26 +01:00
LexManos 1527738ddc Fix wrong order in filter vanilla commands patch. Fixes #10563 2025-06-19 00:49:08 -07:00
LexManos 18c806f1d0 Fix not being able to break blocks in survival. Closes #10561 2025-06-18 12:28:19 -07:00
Paint_Ninja 47f7c68ed5 Fix bug with strict bulk registration
See EventBus#89 for more details
2025-06-18 18:10:33 +01:00
173 changed files with 3411 additions and 2030 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: Publish
on:
push:
branches: [ '1.21.8' ]
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.54,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.45,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)
}
+3 -3
View File
@@ -4,9 +4,9 @@ repositories {
}
dependencies {
implementation 'org.ow2.asm:asm:9.7'
implementation 'org.ow2.asm:asm-tree:9.7'
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.8'
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)
}
}
+20 -11
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
]
@@ -142,13 +141,14 @@ 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")
runtimeOnly(libs.bootstrap)
runtimeOnly(libs.bootstrap.dev)
//annotationProcessor(libs.eventbus.validator)
annotationProcessor(libs.eventbus.validator)
}
tasks.named('extractRangeMap').configure {
@@ -168,7 +168,7 @@ patcher {
runs {
forge_client {
property 'eventbus.checkTypesOnDispatch', 'true'
property 'eventbus.api.strictRuntimeChecks', 'true'
property 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
args '--launchTarget', 'forge_dev_client',
@@ -925,23 +925,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 +958,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 +1006,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 })
+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.8-&query=$.promos["1.21.8-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.8-&query=$.promos["1.21.8-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
@@ -10,6 +10,8 @@ import java.util.List;
import java.util.stream.Collectors;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.LoadingModList;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
@@ -47,9 +49,14 @@ 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();
@@ -68,6 +75,11 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE;
if (!classNode.name.startsWith("net/minecraft/")) {
LOGGER.warn("IExtensibleEnum found on non-Minecraft class: {}", classType.getClassName());
LOGGER.warn("This behaviour is deprecated for removal and will have no effect in a future MC release. Please use a record with static final field instances instead.");
}
Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor();
@@ -174,7 +174,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,13 @@
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
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 +26,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;
@@ -67,13 +70,22 @@ public class LoadingModList {
}
public void addAccessTransformers() {
var errors = new ArrayList<EarlyLoadingException.ExceptionData>();
for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile();
var at = mod.getAccessTransformer().orElse(null);
if (at != null) {
FMLLoader.addAccessTransformer(at, mod);
for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message);
} else {
FMLLoader.addAccessTransformer(at, mod);
}
}
}
if (!errors.isEmpty()) {
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler) {
@@ -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;
}
@@ -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,46 @@ 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 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());
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;
}
@@ -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) {
@@ -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()) {
+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,35 @@
/*
* 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.ArrayList;
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
+3 -3
View File
@@ -5,11 +5,11 @@ org.gradle.daemon=false
org.gradle.parallel=true
JAVA_VERSION=21
MC_VERSION=1.21.6
MC_VERSION=1.21.8
MC_NEXT_VERSION=1.22
MCP_VERSION=20250618.020446
MCP_VERSION=20250717.105350
MAPPING_CHANNEL=official
MAPPING_VERSION=1.21.6
MAPPING_VERSION=1.21.8
# Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false
@@ -53,6 +53,8 @@ public class AutomaticEventSubscriber {
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 {
@@ -152,6 +151,9 @@ public class AutomaticEventSubscriber {
if (!Modifier.isStatic(method.getModifiers()))
continue;
if (method.isSynthetic())
continue; // EventBus#89
int paramCount = method.getParameterCount();
if (paramCount == 0 || paramCount > 2)
continue;
@@ -170,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)
@@ -187,8 +189,10 @@ public class AutomaticEventSubscriber {
public static void registerStrict(BusGroup busGroup, Class<?> listenerClass) {
Class<? extends Event> firstValidListenerEventType = null;
Method[] declaredMethods = listenerClass.getDeclaredMethods();
if (declaredMethods.length == 0) {
List<Method> declaredMethods = Arrays.stream(listenerClass.getDeclaredMethods())
.filter(Predicate.not(Method::isSynthetic)) // EventBus#89
.toList();
if (declaredMethods.isEmpty()) {
var errMsg = "No declared methods found in " + listenerClass.getName();
var superClass = listenerClass.getSuperclass();
if (superClass != null && superClass != Record.class && superClass != Enum.class) {
@@ -254,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)
@@ -271,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
@@ -193,6 +193,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.7'
// 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/GlDevice.java
+++ b/com/mojang/blaze3d/opengl/GlDevice.java
@@ -88,8 +_,15 @@
@@ -89,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 @@
);
}
@@ -97,6 +_,15 @@
@@ -98,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) {
@@ -147,11 +_,14 @@
@@ -148,11 +_,14 @@
GlStateManager._texImage2D(
k,
l,
@@ -48,7 +48,7 @@
GlConst.toGlType(p_394951_),
null
);
@@ -162,11 +_,14 @@
@@ -163,11 +_,14 @@
GlStateManager._texImage2D(
j,
i1,
@@ -63,7 +63,7 @@
GlConst.toGlType(p_394951_),
null
);
@@ -179,7 +_,7 @@
@@ -180,7 +_,7 @@
} else if (j1 != 0) {
throw new IllegalStateException("OpenGL error " + j1);
} else {
@@ -1,15 +1,15 @@
--- a/com/mojang/blaze3d/vertex/VertexFormat.java
+++ b/com/mojang/blaze3d/vertex/VertexFormat.java
@@ -18,7 +_,7 @@
@@ -21,7 +_,7 @@
@OnlyIn(Dist.CLIENT)
@DontObfuscate
-public class VertexFormat {
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
public static final int UNKNOWN_ELEMENT = -1;
private final List<VertexFormatElement> elements;
private final List<String> names;
@@ -29,6 +_,7 @@
private static final boolean USE_STAGING_BUFFER_WORKAROUND = Util.getPlatform() == Util.OS.WINDOWS && Util.isAarch64();
@Nullable
@@ -35,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_;
@@ -41,6 +_,11 @@
@@ -47,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() {
@@ -138,6 +_,9 @@
@@ -169,6 +_,9 @@
);
return this.immediateDrawIndexBuffer;
}
+
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/data/models/ItemModelGenerators.java
+++ b/net/minecraft/client/data/models/ItemModelGenerators.java
@@ -870,6 +_,9 @@
@@ -871,6 +_,9 @@
this.declareCustomModelItem(Items.COD);
this.declareCustomModelItem(Items.FEATHER);
this.declareCustomModelItem(Items.LEAD);
@@ -6,6 +6,6 @@
@OnlyIn(Dist.CLIENT)
-public class Font {
+public class Font implements net.minecraftforge.client.extensions.IForgeFont {
private static final float EFFECT_DEPTH = 0.001F;
private static final float OVER_EFFECT_DEPTH = 0.001F;
private static final float UNDER_EFFECT_DEPTH = -0.001F;
private static final float EFFECT_DEPTH = 0.01F;
private static final float OVER_EFFECT_DEPTH = 0.01F;
private static final float UNDER_EFFECT_DEPTH = -0.01F;
@@ -9,6 +9,25 @@
private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList;
@@ -194,6 +_,7 @@
() -> new JumpableVehicleBarRenderer(p_330021_)
);
this.resetTitleTimes();
+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.init(this, p_330021_);
}
public void resetTitleTimes() {
@@ -204,6 +_,10 @@
public void render(GuiGraphics p_282884_, DeltaTracker p_342095_) {
if (this.minecraft.screen == null || !(this.minecraft.screen instanceof ReceivingLevelScreen)) {
+ 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_);
@@ -377,7 +_,7 @@
int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window));
int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window));
@@ -38,7 +57,7 @@
@@ -598,6 +_,10 @@
}
private void renderSelectedItemName(GuiGraphics p_283501_) {
public void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+
@@ -71,7 +90,7 @@
}
}
@@ -1148,7 +_,7 @@
@@ -1146,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelectedItem();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
@@ -9,7 +9,7 @@
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
private final Minecraft minecraft;
private final Matrix3x2fStack pose;
@@ -870,6 +_,7 @@
@@ -875,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);
@@ -888,6 +_,7 @@
@@ -893,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 @@
}
}
@@ -899,21 +_,30 @@
@@ -904,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);
}
@@ -926,7 +_,22 @@
@@ -931,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_) {
@@ -989,11 +_,13 @@
ClientTooltipPositioner p_409451_,
@Nullable ResourceLocation p_409298_
@@ -981,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(
@@ -992,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;
}
@@ -1003,16 +_,17 @@
@@ -1008,16 +_,17 @@
int l1 = i;
int i2 = j;
@@ -107,8 +127,8 @@
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());
+ var background = net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTooltipBackground(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282716_, preEvent.getBackground());
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, background.getBackground());
int j1 = i1;
for (int k1 = 0; k1 < p_282716_.size(); k1++) {
@@ -118,7 +138,7 @@
j1 += clienttooltipcomponent1.getHeight(p_283128_) + (k1 == 0 ? 2 : 0);
}
@@ -1020,7 +_,7 @@
@@ -1025,7 +_,7 @@
for (int j2 = 0; j2 < p_282716_.size(); j2++) {
ClientTooltipComponent clienttooltipcomponent2 = p_282716_.get(j2);
@@ -127,3 +147,18 @@
j1 += clienttooltipcomponent2.getHeight(p_283128_) + (j2 == 0 ? 2 : 0);
}
@@ -1222,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()));
+ }
+
+ public GuiRenderState getRenderState() {
+ return this.guiRenderState;
+ }
+
+ public GuiGraphics.ScissorStack getScissorStack() {
+ return this.scissorStack;
}
@OnlyIn(Dist.CLIENT)
@@ -0,0 +1,10 @@
--- a/net/minecraft/client/gui/render/GuiRenderer.java
+++ b/net/minecraft/client/gui/render/GuiRenderer.java
@@ -134,6 +_,7 @@
builder.put((Class<? extends PictureInPictureRenderState>)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer);
}
+ net.minecraftforge.client.ForgeHooksClient.onRegisterPictureInPictureRenderers(p_410565_, p_410441_, builder);
this.pictureInPictureRenderers = builder.buildOrThrow();
}
@@ -18,7 +18,7 @@
this.refreshSearchResults();
} else {
this.menu.items.addAll(p_261591_);
@@ -329,6 +_,35 @@
@@ -329,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) {
@@ -71,3 +71,11 @@
SignableCommand<ClientSuggestionProvider> signablecommand = SignableCommand.of(this.commands.parse(p_250092_, this.suggestionsProvider));
if (signablecommand.arguments().isEmpty()) {
this.send(new ServerboundChatCommandPacket(p_250092_));
@@ -2641,6 +_,7 @@
}
public void sendUnattendedCommand(String p_407213_, @Nullable Screen p_406262_) {
+ if (net.minecraftforge.client.ClientCommandHandler.runCommand(p_407213_)) return;
switch (this.verifyCommand(p_407213_)) {
case NO_ISSUES:
this.send(new ServerboundChatCommandPacket(p_407213_));
@@ -9,6 +9,14 @@
@Nullable
private ClientLevel level;
private final SectionOcclusionGraph sectionOcclusionGraph = new SectionOcclusionGraph();
@@ -161,6 +_,7 @@
this.entityRenderDispatcher = p_234246_;
this.blockEntityRenderDispatcher = p_234247_;
this.renderBuffers = p_234248_;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onInitLevelRenderer();
}
public void tickParticles(Camera p_369538_) {
@@ -480,7 +_,7 @@
postchain1.addToFrame(framegraphbuilder, i, j, this.targets);
}
@@ -18,6 +26,14 @@
CloudStatus cloudstatus = this.minecraft.options.getCloudsType();
if (cloudstatus != CloudStatus.OFF) {
Optional<Integer> optional = this.level.dimensionType().cloudHeight();
@@ -497,6 +_,7 @@
}
this.addLateDebugPass(framegraphbuilder, vec3, p_407881_);
+ net.minecraftforge.client.FramePassManager.insertForgePasses(framegraphbuilder, targets, p_342180_); // Forge: Modded passes are inserted here.
profilerfiller.popPush("framegraph");
framegraphbuilder.execute(p_367325_, new FrameGraphBuilder.Inspector() {
@Override
@@ -577,7 +_,7 @@
multibuffersource$buffersource.endLastBatch();
this.checkPoseStack(posestack);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/renderer/block/BlockModelShaper.java
+++ b/net/minecraft/client/renderer/block/BlockModelShaper.java
@@ -17,8 +_,13 @@
@@ -17,8 +_,15 @@
this.modelManager = p_110880_;
}
@@ -11,7 +11,9 @@
+ }
+
+ public TextureAtlasSprite getParticleIcon(BlockState p_110883_, net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) {
+ return this.getBlockModel(p_110883_).particleIcon(level.getModelDataManager().getAt(pos));
+ net.minecraftforge.client.model.data.ModelData data = level.getModelDataManager().getAtOrEmpty(pos);
+ BlockStateModel model = this.getBlockModel(p_110883_);
+ return model.particleIcon(model.getModelData(level, pos, p_110883_, data));
}
public BlockStateModel getBlockModel(BlockState p_110894_) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/renderer/texture/TextureAtlas.java
+++ b/net/minecraft/client/renderer/texture/TextureAtlas.java
@@ -88,6 +_,7 @@
@@ -91,6 +_,7 @@
this.sprites = List.copyOf(list);
this.animatedTextures = List.copyOf(list1);
}
@@ -8,7 +8,7 @@
}
@Override
@@ -165,5 +_,10 @@
@@ -168,5 +_,10 @@
int getHeight() {
return this.height;
@@ -37,16 +37,15 @@
if (contextchain != null) {
executeCommandInContext(
commandsourcestack,
@@ -395,8 +_,11 @@
public void sendCommands(ServerPlayer p_82096_) {
@@ -396,7 +_,10 @@
Map<CommandNode<CommandSourceStack>, CommandNode<CommandSourceStack>> map = new HashMap<>();
RootCommandNode<CommandSourceStack> rootcommandnode = new RootCommandNode<>();
+ // FORGE: Clean any modded command content if the client is vanilla
+ rootcommandnode = net.minecraftforge.server.command.CommandHelper.filterCommandList(p_82096_.connection.getConnection(), rootcommandnode);
map.put(this.dispatcher.getRoot(), rootcommandnode);
- fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, p_82096_.createCommandSourceStack(), map);
+ // FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551
+ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, p_82096_.createCommandSourceStack(), ctx -> 0, suggest -> suggest);
+ // FORGE: Clean any modded command content if the client is vanilla
+ rootcommandnode = net.minecraftforge.server.command.CommandHelper.filterCommandList(p_82096_.connection.getConnection(), rootcommandnode);
p_82096_.connection.send(new ClientboundCommandsPacket(rootcommandnode, COMMAND_NODE_INSPECTOR));
}
@@ -0,0 +1,11 @@
--- a/net/minecraft/commands/SharedSuggestionProvider.java
+++ b/net/minecraft/commands/SharedSuggestionProvider.java
@@ -98,7 +_,7 @@
p_82948_.accept(t);
}
} else if (matchesSubStr(p_82946_, resourcelocation.getNamespace())
- || resourcelocation.getNamespace().equals("minecraft") && matchesSubStr(p_82946_, resourcelocation.getPath())) {
+ || matchesSubStr(p_82946_, resourcelocation.getPath())) { // Forge: Removed "minecraft" namespace requirement for path searching to allow modded path suggestions to show up
p_82948_.accept(t);
}
}
@@ -0,0 +1,11 @@
--- a/net/minecraft/gametest/Main.java
+++ b/net/minecraft/gametest/Main.java
@@ -7,6 +_,8 @@
public class Main {
@DontObfuscate
public static void main(String[] p_393417_) throws Exception {
+ System.setProperty("forge.enableGameTest", "true");
+ System.setProperty("forge.gameTestServer", "true");
SharedConstants.tryDetectVersion();
GameTestMainUtil.runGameTestServer(p_393417_, p_393535_ -> {});
}
@@ -0,0 +1,10 @@
--- a/net/minecraft/gametest/framework/GameTestMainUtil.java
+++ b/net/minecraft/gametest/framework/GameTestMainUtil.java
@@ -69,6 +_,7 @@
Bootstrap.bootStrap();
Util.startTimerHackThread();
+ net.minecraftforge.server.loading.ServerModLoader.load();
String s = optionset.valueOf(universe);
createOrResetDir(s);
p_393652_.accept(s);
@@ -5,7 +5,7 @@
public void handleBlockBreakAction(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) {
+ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(player, p_215120_, p_215122_, p_215121_);
+ if (event == null || !this.isCreative()) {
+ if (event == null) {
+ return;
+ }
if (!this.player.canInteractWithBlock(p_215120_, 1.0)) {
@@ -238,7 +238,12 @@
p_409579_.addFreshEntity(itementity);
return itementity;
}
@@ -2127,7 +_,7 @@
@@ -2123,11 +_,11 @@
}
ItemStack itemstack = p_19978_.getItemInHand(p_19979_);
- if (itemstack.is(Items.SHEARS) && this.shearOffAllLeashConnections(p_19978_)) {
+ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.shearOffAllLeashConnections(p_19978_)) {
itemstack.hurtAndBreak(1, p_19978_, p_19979_);
return InteractionResult.SUCCESS;
} else if (this instanceof Mob mob
@@ -315,7 +320,7 @@
public boolean isPushedByFluid() {
return true;
}
@@ -3500,9 +_,17 @@
@@ -3500,9 +_,26 @@
return Mth.lerp(p_344421_, this.yRotO, this.yRot);
}
@@ -325,20 +330,32 @@
+ if(p_204032_ == FluidTags.WATER) return this.isInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get());
+ else if (p_204032_ == FluidTags.LAVA) return this.isInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get());
+ else return false;
+ }
+ }
+
+ public void updateFluidHeightAndDoFluidPushing(Predicate<FluidState> shouldUpdate) {
+ private static final class FluidCalcs {
+ double height = 0.0D;
+ Vec3 direction = Vec3.ZERO;
+ int count = 0;
+ double height(double height) {
+ return (this.height = this.height >= height ? this.height : height);
+ }
+ }
+
+ public void updateFluidHeightAndDoFluidPushing(Predicate<FluidState> shouldUpdate) {
if (this.touchingUnloadedChunk()) {
- return false;
+ return;
} else {
AABB aabb = this.getBoundingBox().deflate(0.001);
int i = Mth.floor(aabb.minX);
@@ -3517,25 +_,28 @@
Vec3 vec3 = Vec3.ZERO;
int k1 = 0;
@@ -3514,28 +_,32 @@
double d0 = 0.0;
boolean flag = this.isPushedByFluid();
boolean flag1 = false;
- Vec3 vec3 = Vec3.ZERO;
- int k1 = 0;
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
+ var interimCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<net.minecraftforge.fluids.FluidType, org.apache.commons.lang3.tuple.MutableTriple<Double, Vec3, Integer>>(net.minecraftforge.fluids.FluidType.SIZE.get() - 1);
+ it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<net.minecraftforge.fluids.FluidType, FluidCalcs> fluidPushCalcs = null;
for (int l1 = i; l1 < j; l1++) {
for (int i2 = k; i2 < l; i2++) {
@@ -352,60 +369,51 @@
if (d1 >= aabb.minY) {
flag1 = true;
- d0 = Math.max(d1 - aabb.minY, d0);
- if (flag) {
+ var interim = interimCalcs.computeIfAbsent(fluidType, t -> org.apache.commons.lang3.tuple.MutableTriple.of(0.0D, Vec3.ZERO, 0));
+ interim.setLeft(Math.max(d1 - aabb.minY, interim.getLeft()));
+ if (this.isPushedByFluid(fluidType)) {
+ if (fluidPushCalcs == null)
+ fluidPushCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<net.minecraftforge.fluids.FluidType, FluidCalcs>(2);
+ var interim = fluidPushCalcs.computeIfAbsent(fluidType, type -> new FluidCalcs());
+ d0 = interim.height(d1 - aabb.minY);
+ flag = this.isPushedByFluid(fluidType);
if (flag) {
Vec3 vec31 = fluidstate.getFlow(this.level(), blockpos$mutableblockpos);
- if (d0 < 0.4) {
- vec31 = vec31.scale(d0);
+ if (interim.getLeft() < 0.4D) {
+ vec31 = vec31.scale(interim.getLeft());
if (d0 < 0.4) {
vec31 = vec31.scale(d0);
}
- vec3 = vec3.add(vec31);
- k1++;
+ interim.setMiddle(interim.getMiddle().add(vec31));
+ interim.setRight(interim.getRight() + 1);
+ interim.direction = interim.direction.add(vec31);
+ interim.count++;
}
}
}
@@ -3543,27 +_,28 @@
@@ -3543,6 +_,10 @@
}
}
- if (vec3.length() > 0.0) {
- if (k1 > 0) {
- vec3 = vec3.scale(1.0 / k1);
+ interimCalcs.forEach((fluidType, interim) -> {
+ if (interim.getMiddle().length() > 0.0D) {
+ if (interim.getRight() > 0) {
+ interim.setMiddle(interim.getMiddle().scale(1.0D / (double)interim.getRight()));
}
if (!(this instanceof Player)) {
- vec3 = vec3.normalize();
+ interim.setMiddle(interim.getMiddle().normalize());
+ if (fluidPushCalcs == null) return;
+ for (var entry : fluidPushCalcs.entrySet()) {
+ var vec3 = entry.getValue().direction;
+ var k1 = entry.getValue().count;
if (vec3.length() > 0.0) {
if (k1 > 0) {
vec3 = vec3.scale(1.0 / k1);
@@ -3553,6 +_,7 @@
}
Vec3 vec32 = this.getDeltaMovement();
- vec3 = vec3.scale(p_204033_);
+ interim.setMiddle(interim.getMiddle().scale(this.getFluidMotionScale(fluidType)));
+ var p_204033_ = this.getFluidMotionScale(entry.getKey());
vec3 = vec3.scale(p_204033_);
double d2 = 0.003;
- if (Math.abs(vec32.x) < 0.003 && Math.abs(vec32.z) < 0.003 && vec3.length() < 0.0045000000000000005) {
- vec3 = vec3.normalize().scale(0.0045000000000000005);
+ if (Math.abs(vec32.x) < 0.003 && Math.abs(vec32.z) < 0.003 && interim.getMiddle().length() < 0.0045000000000000005) {
+ interim.setMiddle(interim.getMiddle().normalize().scale(0.0045000000000000005));
}
- this.setDeltaMovement(this.getDeltaMovement().add(vec3));
+ this.setDeltaMovement(this.getDeltaMovement().add(interim.getMiddle()));
if (Math.abs(vec32.x) < 0.003 && Math.abs(vec32.z) < 0.003 && vec3.length() < 0.0045000000000000005) {
@@ -3562,8 +_,8 @@
this.setDeltaMovement(this.getDeltaMovement().add(vec3));
}
- this.fluidHeight.put(p_204032_, d0);
- return flag1;
+ this.setFluidTypeHeight(fluidType, interim.getLeft());
+ });
+ this.setFluidTypeHeight(entry.getKey(), entry.getValue().height);
+ }
}
}
@@ -9,3 +9,12 @@
return false;
}
@@ -604,7 +_,7 @@
@Override
protected boolean isValidTarget(LevelReader p_29785_, BlockPos p_29786_) {
BlockState blockstate = p_29785_.getBlockState(p_29786_);
- if (blockstate.is(Blocks.FARMLAND) && this.wantsToRaid && !this.canRaid) {
+ if (blockstate.getBlock() instanceof net.minecraft.world.level.block.FarmBlock && this.wantsToRaid && !this.canRaid) {
blockstate = p_29785_.getBlockState(p_29786_.above());
if (blockstate.getBlock() instanceof CarrotBlock && ((CarrotBlock)blockstate.getBlock()).isMaxAge(blockstate)) {
this.canRaid = true;
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java
+++ b/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java
@@ -72,7 +_,7 @@
if (this.level().isClientSide) {
return InteractionResult.SUCCESS;
} else {
- if (p_31842_.getItemInHand(p_31843_).is(Items.SHEARS)) {
+ if (p_31842_.getItemInHand(p_31843_).canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) {
InteractionResult interactionresult = super.interact(p_31842_, p_31843_);
if (interactionresult instanceof InteractionResult.Success interactionresult$success && interactionresult$success.wasItemInteraction()) {
return interactionresult;
@@ -1,6 +1,6 @@
--- a/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java
+++ b/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java
@@ -84,7 +_,7 @@
@@ -83,7 +_,7 @@
this.timeInOverworld = 0;
}
@@ -9,7 +9,7 @@
this.playConvertedSound();
this.finishConversion(p_360786_);
}
@@ -103,7 +_,10 @@
@@ -102,7 +_,10 @@
this.convertTo(
EntityType.ZOMBIFIED_PIGLIN,
ConversionParams.single(this, true, true),
@@ -1,6 +1,6 @@
--- a/net/minecraft/world/entity/npc/Villager.java
+++ b/net/minecraft/world/entity/npc/Villager.java
@@ -321,7 +_,7 @@
@@ -320,7 +_,7 @@
@Override
public InteractionResult mobInteract(Player p_35472_, InteractionHand p_35473_) {
ItemStack itemstack = p_35472_.getItemInHand(p_35473_);
@@ -9,7 +9,7 @@
return super.mobInteract(p_35472_, p_35473_);
} else if (this.isBaby()) {
this.setUnhappy();
@@ -767,7 +_,7 @@
@@ -766,7 +_,7 @@
@Override
public void thunderHit(ServerLevel p_35409_, LightningBolt p_35410_) {
@@ -28,7 +28,7 @@
private Vec3 calculateHaltTrackSpeed(Vec3 p_364212_, BlockState p_362846_) {
- if (p_362846_.is(Blocks.POWERED_RAIL) && !p_362846_.getValue(PoweredRailBlock.POWERED)) {
+ if (p_362846_.getBlock() instanceof PoweredRailBlock && !p_362846_.getValue(PoweredRailBlock.POWERED)) {
+ if (p_362846_.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail() && !p_362846_.getValue(PoweredRailBlock.POWERED)) {
return p_364212_.length() < 0.03 ? Vec3.ZERO : p_364212_.scale(0.5);
} else {
return p_364212_;
@@ -37,7 +37,7 @@
private Vec3 calculateBoostTrackSpeed(Vec3 p_366761_, BlockPos p_361866_, BlockState p_368734_) {
- if (p_368734_.is(Blocks.POWERED_RAIL) && p_368734_.getValue(PoweredRailBlock.POWERED)) {
+ if (p_368734_.getBlock() instanceof PoweredRailBlock && p_368734_.getValue(PoweredRailBlock.POWERED)) {
+ if (p_368734_.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail() && p_368734_.getValue(PoweredRailBlock.POWERED)) {
if (p_366761_.length() > 0.01) {
return p_366761_.normalize().scale(p_366761_.length() + 0.06);
} else {
@@ -18,7 +18,7 @@
boolean flag1 = false;
- if (blockstate.is(Blocks.POWERED_RAIL)) {
+ BaseRailBlock baserailblock = (BaseRailBlock)blockstate.getBlock();
+ if (blockstate.getBlock() instanceof PoweredRailBlock) {
+ if (blockstate.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail()) {
flag = blockstate.getValue(PoweredRailBlock.POWERED);
flag1 = !flag;
}
@@ -89,7 +89,7 @@
private ResourceLocation backgroundTexture = CreativeModeTab.DEFAULT_BACKGROUND;
+ private boolean hasSearchBar = false;
+ private int searchBarWidth = 89;
+ private int labelColor = 4210752;
+ private int labelColor = 0xff404040;
+ private int slotColor = -2130706433;
+ private java.util.function.Function<CreativeModeTab.Builder, CreativeModeTab> tabFactory =
+ builder -> new CreativeModeTab(builder.row, builder.column, builder.type, builder.displayName, builder.iconGenerator, builder.displayItemsGenerator, builder);
@@ -1,6 +1,6 @@
--- a/net/minecraft/world/item/Items.java
+++ b/net/minecraft/world/item/Items.java
@@ -2152,7 +_,25 @@
@@ -2155,7 +_,25 @@
}
public static Item registerBlock(Block p_252092_, Block... p_248886_) {
@@ -27,7 +27,7 @@
for (Block block : p_248886_) {
Item.BY_BLOCK.put(block, item);
@@ -2191,10 +_,6 @@
@@ -2194,10 +_,6 @@
public static Item registerItem(ResourceKey<Item> p_364577_, Function<Item.Properties, Item> p_366144_, Item.Properties p_369845_) {
Item item = p_366144_.apply(p_369845_.setId(p_364577_));
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/level/block/AttachedStemBlock.java
+++ b/net/minecraft/world/level/block/AttachedStemBlock.java
@@ -81,7 +_,7 @@
@Override
protected boolean mayPlaceOn(BlockState p_48863_, BlockGetter p_48864_, BlockPos p_48865_) {
- return p_48863_.is(Blocks.FARMLAND);
+ return p_48863_.getBlock() instanceof net.minecraft.world.level.block.FarmBlock;
}
@Override
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/level/block/CactusFlowerBlock.java
+++ b/net/minecraft/world/level/block/CactusFlowerBlock.java
@@ -31,7 +_,7 @@
protected boolean mayPlaceOn(BlockState p_395694_, BlockGetter p_391810_, BlockPos p_391352_) {
BlockState blockstate = p_391810_.getBlockState(p_391352_);
return blockstate.is(Blocks.CACTUS)
- || blockstate.is(Blocks.FARMLAND)
+ || blockstate.getBlock() instanceof net.minecraft.world.level.block.FarmBlock
|| blockstate.isFaceSturdy(p_391810_, p_391352_, Direction.UP, SupportType.CENTER);
}
}
@@ -0,0 +1,33 @@
--- a/net/minecraft/world/level/block/CrafterBlock.java
+++ b/net/minecraft/world/level/block/CrafterBlock.java
@@ -185,12 +_,15 @@
ServerLevel p_336186_, BlockPos p_312358_, CrafterBlockEntity p_309887_, ItemStack p_310474_, BlockState p_310667_, RecipeHolder<?> p_329387_
) {
Direction direction = p_310667_.getValue(ORIENTATION).front();
+ var itemhandler = net.minecraftforge.items.VanillaInventoryCodeHooks.getItemHandler(p_336186_, p_312358_.relative(direction), direction.getOpposite()).orElse(null);
Container container = HopperBlockEntity.getContainerAt(p_336186_, p_312358_.relative(direction));
ItemStack itemstack = p_310474_.copy();
if (container != null && (container instanceof CrafterBlockEntity || p_310474_.getCount() > container.getMaxStackSize(p_310474_))) {
while (!itemstack.isEmpty()) {
ItemStack itemstack2 = itemstack.copyWithCount(1);
ItemStack itemstack1 = HopperBlockEntity.addItem(p_309887_, container, itemstack2, direction.getOpposite());
+ if (itemhandler != null && !itemstack1.isEmpty()) // Vanilla insert failed, try IItemHandler
+ itemstack1 = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack1, false);
if (!itemstack1.isEmpty()) {
break;
}
@@ -201,10 +_,14 @@
while (!itemstack.isEmpty()) {
int i = itemstack.getCount();
itemstack = HopperBlockEntity.addItem(p_309887_, container, itemstack, direction.getOpposite());
+ if (itemhandler != null && i == itemstack.getCount()) // Vanilla insert failed, try IItemHandler
+ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false);
if (i == itemstack.getCount()) {
break;
}
}
+ } else {
+ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false);
}
if (!itemstack.isEmpty()) {
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/level/block/PitcherCropBlock.java
+++ b/net/minecraft/world/level/block/PitcherCropBlock.java
@@ -107,7 +_,7 @@
@Override
protected boolean mayPlaceOn(BlockState p_277418_, BlockGetter p_277461_, BlockPos p_277608_) {
- return p_277418_.is(Blocks.FARMLAND);
+ return p_277418_.getBlock() instanceof net.minecraft.world.level.block.FarmBlock;
}
@Override
@@ -39,7 +39,7 @@
protected boolean isSameRailWithPower(Level p_55226_, BlockPos p_55227_, boolean p_55228_, int p_55229_, RailShape p_55230_) {
BlockState blockstate = p_55226_.getBlockState(p_55227_);
- if (!blockstate.is(this)) {
+ if (!(blockstate.getBlock() instanceof PoweredRailBlock other)) {
+ if (!(blockstate.getBlock() instanceof PoweredRailBlock other) || this.isActivatorRail() != other.isActivatorRail()) {
return false;
} else {
- RailShape railshape = blockstate.getValue(SHAPE);
@@ -1,6 +1,12 @@
--- a/net/minecraft/world/level/block/StemBlock.java
+++ b/net/minecraft/world/level/block/StemBlock.java
@@ -69,9 +_,11 @@
@@ -64,14 +_,16 @@
@Override
protected boolean mayPlaceOn(BlockState p_57053_, BlockGetter p_57054_, BlockPos p_57055_) {
- return p_57053_.is(Blocks.FARMLAND);
+ return p_57053_.getBlock() instanceof net.minecraft.world.level.block.FarmBlock;
}
@Override
protected void randomTick(BlockState p_222538_, ServerLevel p_222539_, BlockPos p_222540_, RandomSource p_222541_) {
@@ -13,6 +19,15 @@
int i = p_222538_.getValue(AGE);
if (i < 7) {
p_222538_ = p_222538_.setValue(AGE, i + 1);
@@ -80,7 +_,7 @@
Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(p_222541_);
BlockPos blockpos = p_222540_.relative(direction);
BlockState blockstate = p_222539_.getBlockState(blockpos.below());
- if (p_222539_.getBlockState(blockpos).isAir() && (blockstate.is(Blocks.FARMLAND) || blockstate.is(BlockTags.DIRT))) {
+ if (p_222539_.getBlockState(blockpos).isAir() && (blockstate.getBlock() instanceof net.minecraft.world.level.block.FarmBlock || blockstate.is(BlockTags.DIRT))) {
Registry<Block> registry = p_222539_.registryAccess().lookupOrThrow(Registries.BLOCK);
Optional<Block> optional = registry.getOptional(this.fruit);
Optional<Block> optional1 = registry.getOptional(this.attachedStem);
@@ -90,6 +_,7 @@
}
}
@@ -9,6 +9,15 @@
protected VegetationBlock(BlockBehaviour.Properties p_395394_) {
super(p_395394_);
}
@@ -21,7 +_,7 @@
protected abstract MapCodec<? extends VegetationBlock> codec();
protected boolean mayPlaceOn(BlockState p_395950_, BlockGetter p_394817_, BlockPos p_393668_) {
- return p_395950_.is(BlockTags.DIRT) || p_395950_.is(Blocks.FARMLAND);
+ return p_395950_.is(BlockTags.DIRT) || p_395950_.getBlock() instanceof net.minecraft.world.level.block.FarmBlock;
}
@Override
@@ -43,6 +_,9 @@
@Override
protected boolean canSurvive(BlockState p_397664_, LevelReader p_395119_, BlockPos p_393561_) {
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/level/chunk/PalettedContainer.java
+++ b/net/minecraft/world/level/chunk/PalettedContainer.java
@@ -55,7 +_,7 @@
private static <T, C extends PalettedContainerRO<T>> Codec<C> codec(
IdMap<T> p_238428_, Codec<T> p_238429_, PalettedContainer.Strategy p_238430_, T p_238431_, PalettedContainerRO.Unpacker<T, C> p_238432_
) {
- return RecordCodecBuilder.<PalettedContainerRO.PackedData>create(
+ return RecordCodecBuilder.<PalettedContainerRO.PackedData<T>>create(
p_327417_ -> p_327417_.group(
p_238429_.mapResult(ExtraCodecs.orElsePartial(p_238431_)).listOf().fieldOf("palette").forGetter(PalettedContainerRO.PackedData::paletteEntries),
Codec.LONG_STREAM.lenientOptionalFieldOf("data").forGetter(PalettedContainerRO.PackedData::storage)
+14 -12
View File
@@ -10,7 +10,7 @@ buildscript {
dependencies {
classpath('com.google.code.gson:gson') {
version {
strictly '2.10.1'
strictly '2.11.0'
}
}
}
@@ -27,13 +27,14 @@ dependencyResolutionManagement {
library('forgespi', 'net.minecraftforge:forgespi:7.1.5') // Needs modlauncher
library('modlauncher', 'net.minecraftforge:modlauncher:10.2.4') // Needs securemodules
library('securemodules', 'net.minecraftforge:securemodules:2.2.21') // Needs unsafe
library('securemodules', 'net.minecraftforge:securemodules:2.2.24') // Needs unsafe
library('unsafe', 'net.minecraftforge:unsafe:0.9.2')
library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.2')
library('coremods', 'net.minecraftforge:coremods:5.2.6')
library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.4') // Needed by coremods, because the JRE no longer ships JS
library('eventbus', 'net.minecraftforge:eventbus:7.0-beta.7')
library('eventbus-validator', 'net.minecraftforge:eventbus-validator:7.0-beta.7')
version('eventbus', '7.0.1')
library('eventbus', 'net.minecraftforge', 'eventbus').versionRef('eventbus')
library('eventbus-validator', 'net.minecraftforge', 'eventbus-validator').versionRef('eventbus')
library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0')
library('mixin', 'org.spongepowered:mixin:0.8.7')
@@ -53,7 +54,7 @@ dependencyResolutionManagement {
library('bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim').versionRef('bootstrap')
// ASM it's used for so many of our hacks
version('asm', '9.7.1')
version('asm', '9.9.1')
library('asm', 'org.ow2.asm', 'asm' ).versionRef('asm')
library('asm-tree', 'org.ow2.asm', 'asm-tree' ).versionRef('asm')
library('asm-util', 'org.ow2.asm', 'asm-util' ).versionRef('asm')
@@ -84,19 +85,19 @@ dependencyResolutionManagement {
// These are libraries shipped by the MC launcher, try and keep them in sync with the manifest
// but honestly if we don't it just means we ship them as normal libraries by adding them to the installer config in the forge project
library('gson', 'com.google.code.gson:gson:2.10.1')
library('guava', 'com.google.guava:guava:32.1.2-jre')
library('failureaccess', 'com.google.guava:failureaccess:1.0.1')
library('gson', 'com.google.code.gson:gson:2.11.0')
library('guava', 'com.google.guava:guava:33.3.1-jre')
library('failureaccess', 'com.google.guava:failureaccess:1.0.2')
version('log4j', '2.22.1')
version('log4j', '2.24.3')
library('log4j-api', 'org.apache.logging.log4j', 'log4j-api' ).versionRef('log4j')
library('log4j-core', 'org.apache.logging.log4j', 'log4j-core').versionRef('log4j')
bundle('log4j', ['log4j-api', 'log4j-core'])
library('apache-commons', 'org.apache.commons:commons-lang3:3.14.0')
library('mojang-logging', 'com.mojang:logging:1.2.7')
library('apache-commons', 'org.apache.commons:commons-lang3:3.17.0')
library('mojang-logging', 'com.mojang:logging:1.5.10')
library('jopt-simple', 'net.sf.jopt-simple:jopt-simple:5.0.4')
library('commons-io', 'commons-io:commons-io:2.15.1')
library('commons-io', 'commons-io:commons-io:2.17.0')
version('lwjgl', '3.3.3')
library('lwjgl', 'org.lwjgl', 'lwjgl' ).versionRef('lwjgl')
@@ -117,6 +118,7 @@ include 'mclanguage'
include 'javafmllanguage'
include 'lowcodelanguage'
include 'fmlearlydisplay'
include 'forge-transformers'
include ':mcp'
project(":mcp").projectDir = file("projects/mcp")
+1 -1
View File
@@ -3,6 +3,6 @@
"description": {
"translate": "pack.forge.description"
},
"pack_format": 80
"pack_format": 81
}
}
@@ -109,7 +109,11 @@ public class ClientCommandHandler {
new CommandSource() {
@Override
public void sendSystemMessage(Component message) {
mc.gui.getChat().addMessage(message);
var chat = mc.gui.getChat();
if (mc.isSameThread())
chat.addMessage(message);
else
mc.execute(() -> chat.addMessage(message));
}
@Override
@@ -7,6 +7,7 @@ package net.minecraftforge.client;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
@@ -21,10 +22,10 @@ import net.minecraftforge.fml.common.Mod;
public class ClientForgeMod {
@SubscribeEvent
public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) {
event.register("empty", (json, ctx) -> UnbakedGeometry.EMPTY);
event.register("obj", ObjLoader.INSTANCE);
event.register("fluid_container", DynamicFluidContainerModel.Loader.INSTANCE);
event.register("item_layers", ItemLayerGeometry.Loader.INSTANCE);
event.register(forgeRL("empty"), (json, ctx) -> UnbakedGeometry.EMPTY);
event.register(forgeRL("obj"), ObjLoader.INSTANCE);
event.register(forgeRL("fluid_container"), DynamicFluidContainerModel.Loader.INSTANCE);
event.register(forgeRL("item_layers"), ItemLayerGeometry.Loader.INSTANCE);
}
@SubscribeEvent
@@ -34,6 +35,10 @@ public class ClientForgeMod {
@SubscribeEvent
public static void onRegisterNamedRenderTypes(RegisterNamedRenderTypesEvent event) {
event.register("item_unlit", ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get());
event.register(forgeRL("item_unlit"), ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get());
}
private static ResourceLocation forgeRL(String path) {
return ResourceLocation.fromNamespaceAndPath("forge", path);
}
}
@@ -5,7 +5,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.color.block.BlockTintCache;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.world.level.ColorResolver;
@@ -13,22 +12,23 @@ import net.minecraftforge.client.event.RegisterColorHandlersEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Manager for custom {@link ColorResolver} instances, collected via {@link RegisterColorHandlersEvent.ColorResolvers}.
*/
public final class ColorResolverManager
{
public final class ColorResolverManager {
private ColorResolverManager() {}
private static ImmutableList<ColorResolver> colorResolvers;
private static List<ColorResolver> colorResolvers;
@ApiStatus.Internal
public static void init()
{
ImmutableList.Builder<ColorResolver> builder = ImmutableList.builder();
public static void init() {
var builder = new ArrayList<ColorResolver>();
ModLoader.get().postEvent(new RegisterColorHandlersEvent.ColorResolvers(builder));
colorResolvers = builder.build();
colorResolvers = List.copyOf(builder);
}
/**
@@ -37,15 +37,9 @@ public final class ColorResolverManager
* @param level the level to use
* @param target the map to populate
*/
public static void registerBlockTintCaches(ClientLevel level, Map<ColorResolver, BlockTintCache> target)
{
for (var resolver : colorResolvers)
{
public static void registerBlockTintCaches(ClientLevel level, Map<ColorResolver, BlockTintCache> target) {
for (var resolver : colorResolvers) {
target.put(resolver, new BlockTintCache(pos -> level.calculateBlockTint(pos, resolver)));
}
}
private ColorResolverManager()
{
}
}
@@ -5,7 +5,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
@@ -22,7 +21,9 @@ import java.util.Map;
* Provides a lookup by dimension type.
*/
public final class DimensionSpecialEffectsManager {
private static ImmutableMap<ResourceLocation, DimensionSpecialEffects> EFFECTS;
private DimensionSpecialEffectsManager() {}
private static Map<ResourceLocation, DimensionSpecialEffects> EFFECTS;
private static DimensionSpecialEffects DEFAULT_EFFECTS;
/**
@@ -38,7 +39,7 @@ public final class DimensionSpecialEffectsManager {
DEFAULT_EFFECTS = preRegisterVanillaEffects(effects);
var event = new RegisterDimensionSpecialEffectsEvent(effects);
ModLoader.get().postEventWrapContainerInModOrder(event);
EFFECTS = ImmutableMap.copyOf(effects);
EFFECTS = Map.copyOf(effects);
}
/**
@@ -53,6 +54,4 @@ public final class DimensionSpecialEffectsManager {
effects.put(BuiltinDimensionTypes.END_EFFECTS, new DimensionSpecialEffects.EndEffects());
return overworldEffects;
}
private DimensionSpecialEffectsManager() { }
}
@@ -5,7 +5,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableMap;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.client.event.RegisterEntitySpectatorShadersEvent;
@@ -21,29 +20,24 @@ import java.util.Map;
* <p>
* Provides a lookup.
*/
public final class EntitySpectatorShaderManager
{
public final class EntitySpectatorShaderManager {
private EntitySpectatorShaderManager() {}
private static Map<EntityType<?>, ResourceLocation> SHADERS;
/**
* Finds the path to the spectator mode shader used for the specified entity type, or null if none is registered.
*/
@Nullable
public static ResourceLocation get(EntityType<?> entityType)
{
public static ResourceLocation get(EntityType<?> entityType) {
return SHADERS.get(entityType);
}
@ApiStatus.Internal
public static void init()
{
public static void init() {
var shaders = new HashMap<EntityType<?>, ResourceLocation>();
var event = new RegisterEntitySpectatorShadersEvent(shaders);
ModLoader.get().postEventWrapContainerInModOrder(event);
SHADERS = ImmutableMap.copyOf(shaders);
}
private EntitySpectatorShaderManager()
{
SHADERS = Map.copyOf(shaders);
}
}
@@ -26,6 +26,8 @@ import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ChatComponent;
import net.minecraft.client.gui.components.LerpingBossEvent;
import net.minecraft.client.gui.render.pip.PictureInPictureRenderer;
import net.minecraft.client.gui.render.state.pip.PictureInPictureRenderState;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
@@ -96,6 +98,7 @@ import net.minecraftforge.client.event.ClientChatEvent;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.ClientPauseChangeEvent;
import net.minecraftforge.client.event.ClientPlayerChangeGameTypeEvent;
import net.minecraftforge.client.event.RegisterPictureInPictureRendererEvent;
import net.minecraftforge.client.event.SystemMessageReceivedEvent;
import net.minecraftforge.client.event.CustomizeGuiOverlayEvent;
import net.minecraftforge.client.event.EntityRenderersEvent;
@@ -151,6 +154,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -596,6 +600,12 @@ public class ForgeHooksClient {
ModLoader.get().postEvent(new RegisterKeyMappingsEvent(options));
}
public static void onRegisterPictureInPictureRenderers(List<PictureInPictureRenderer<?>> renderers,
MultiBufferSource.BufferSource bufferSource,
ImmutableMap.Builder<Class<? extends PictureInPictureRenderState>, PictureInPictureRenderer<?>> builder) {
RegisterPictureInPictureRendererEvent.BUS.post(new RegisterPictureInPictureRendererEvent(renderers, bufferSource, builder));
}
@Nullable
public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) {
ClientChatReceivedEvent event = new ClientChatReceivedEvent(boundChatType, message, sender);
@@ -626,8 +636,8 @@ public class ForgeHooksClient {
return stackFont == null ? fallbackFont : stackFont;
}
public static @Nullable RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner) {
var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner);
public static @Nullable RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner, @Nullable ResourceLocation background) {
var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner, background);
return RenderTooltipEvent.Pre.BUS.post(preEvent) ? null : preEvent;
}
@@ -874,4 +884,8 @@ public class ForgeHooksClient {
return parent.compute(p_395456_);
}
}
public static void addFramePass(ResourceLocation rl, FramePassManager.PassDefinition definition) {
FramePassManager.addPass(rl, definition);
}
}
@@ -0,0 +1,104 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client;
import com.mojang.blaze3d.framegraph.FrameGraphBuilder;
import com.mojang.blaze3d.framegraph.FramePass;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.renderer.LevelTargetBundle;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.ArrayList;
import java.util.List;
public class FramePassManager {
private static final List<PassInfo> addedPasses = new ArrayList<>();
protected static void addPass(ResourceLocation name, PassDefinition pass) {
if (addedPasses.stream().noneMatch(info -> info.name.equals(name.toString()))) {
addedPasses.add(new PassInfo(name.toString(), pass));
} else {
throw new IllegalArgumentException("Cannot create a frame pass with a duplicate name: " + name);
}
}
// Note: Pass order is determined automatically within FrameGraphBuilder. It's unclear what must be done to guarantee ordering.
@ApiStatus.Internal
public static void insertForgePasses(FrameGraphBuilder graphBuilder, LevelTargetBundle bundle, DeltaTracker tracker) {
for (PassInfo info : addedPasses) {
FramePass pass = graphBuilder.addPass(info.name);
PassDefinition forgePass = info.pass;
forgePass.extracts(bundle, pass, tracker);
pass.executes(forgePass::executes);
}
}
/// ### A PassDefinition must satisfy 3 things.
///
/// 1. The rendering order for the purpose of translucency sorting. Read further for specific details.
/// 2. A render state definition supplier; "what" will be rendered.
/// 3. A render state definition consumer; "how" it will be rendered.
///
///
/// To satisfy #1, all FramePasses (and thus PassDefinitions) must bind against at least one target.
/// The list of targets can be found in {@linkplain LevelTargetBundle}.
/// HOWEVER!!! Only {@linkplain LevelTargetBundle#main} is used if the graphics mode is not set to Fabulous!
/// So at minimum, all passes must guarantee a fallback binding to the main target, like the below.
/// ```
/// @Override
/// void extracts(LevelTargetBundle bundle, FramePass pass, DeltaTracker deltaTracker) {
/// if (bundle.clouds != null) { // Perhaps we want to bind to clouds if Fabulous! is on.
/// bundle.clouds = pass.readsAndWrites(bundle.clouds);
/// }
/// // An else clause could be used, but is not mandatory. It is fine to bind to more than one target.
/// bundle.main = pass.readsAndWrites(bundle.main);
/// }
/// ```
/// </pre>
///
/// It is up to the user to decide how their pass should bind to targets, but it must always bind to at least one.
/// Failure to satisfy this requirement will result in {@linkplain FrameGraphBuilder#resolvePassOrder} exploding.
/// Custom render targets are possible but not documented, see the implementation of {@linkplain LevelTargetBundle}
/// if you want to take a crack at it.
///
/// Satisfying #2 is simple. Any state information you need to extract
/// should be done during {@linkplain PassDefinition#extracts(LevelTargetBundle, FramePass, DeltaTracker)}.
/// No actual rendering should be done at this time. This can happen before or after binding to a target.
/// The specific implementation of your render state is up to you, it can even be done with some instance variables.
///
/// Satisfying #3 is also simple, this is the actual rendering that will consume the state created
/// during the extracts phase.
@NullMarked
public interface PassDefinition {
/**
* Use to define which targets your pass will bind against, see {@link FramePass#reads} and {@link FramePass#readsAndWrites}
* A FramePass must bind to at least ONE target. Otherwise, you get freaky issues with >1 modded passes.
* Additionally, this method should be used for extracting render states into instance variables if desired.
*/
default void extracts(LevelTargetBundle bundle, FramePass pass, DeltaTracker tracker) {
targets(bundle, pass);
}
/**
* @deprecated Prefer {@link PassDefinition#extracts}
*/
@Deprecated(forRemoval = true, since = "1.21.10")
default void targets(LevelTargetBundle bundle, FramePass pass) {}
/**
* Use to define what your pass does during the render stage
* @apiNote In 1.21.10+, LevelRenderState is used. Because that does not exist in 1.21.8, use the client level instead.
* This method is informally deprecated due to rendering changes in versions 1.21.10+
*/
default void executes(){};
}
private record PassInfo(String name, PassDefinition pass){}
}
@@ -16,16 +16,14 @@ import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraftforge.client.event.RegisterPresetEditorsEvent;
import net.minecraftforge.fml.ModLoader;
public final class PresetEditorManager
{
public final class PresetEditorManager {
private PresetEditorManager() {} // Utility class
private static Map<ResourceKey<WorldPreset>, PresetEditor> editors = Map.of();
@SuppressWarnings("deprecation")
@ApiStatus.Internal
static void init()
{
static void init() {
// Start with the vanilla entries
Map<ResourceKey<WorldPreset>, PresetEditor> gatheredEditors = new HashMap<>();
// Vanilla's map uses Optional<ResourceKey>s as its keys.
@@ -41,7 +39,7 @@ public final class PresetEditorManager
RegisterPresetEditorsEvent event = new RegisterPresetEditorsEvent(gatheredEditors);
ModLoader.get().postEventWrapContainerInModOrder(event);
editors = gatheredEditors;
editors = Map.copyOf(gatheredEditors);
}
/**
@@ -50,8 +48,7 @@ public final class PresetEditorManager
* @param key ResourceKey for the specified WorldPreset/PresetEditor.
*/
@Nullable
public static PresetEditor get(ResourceKey<WorldPreset> key)
{
public static PresetEditor get(ResourceKey<WorldPreset> key) {
return editors.get(key);
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.FramePassManager;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import org.jspecify.annotations.NullMarked;
/**
* Fired during the construction of {@linkplain net.minecraft.client.renderer.LevelRenderer}.
*
* <p>This event is fired on the {@linkplain net.minecraftforge.common.MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain net.minecraftforge.fml.LogicalSide#CLIENT logical client}.
*/
@NullMarked
public record AddFramePassEvent() implements RecordEvent {
public static final EventBus<AddFramePassEvent> BUS = EventBus.create(AddFramePassEvent.class);
/**
* Adds a frame pass to pass list.
* Create a new {@linkplain FramePassManager.PassDefinition} to handle render targets and render code.
* See javadocs for details on what creating a PassDefinition entails.
*
* @param rl Identifier for frame pass name. Use RLs to avoid duplicate names.
* @param definition see usages of {@linkplain com.mojang.blaze3d.framegraph.FramePass} in {@linkplain net.minecraft.client.renderer.LevelRenderer}
* @throws IllegalArgumentException If the name is a duplicate.
*/
public void addPass(ResourceLocation rl, FramePassManager.PassDefinition definition) {
ForgeHooksClient.addFramePass(rl, definition);
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
/**
* Fired when the {@linkplain ForgeLayeredDraw#VANILLA_ROOT}'s order is resolved during{@link ForgeLayeredDraw#resolveLayers().
* This can be used to add additional or move gui layers and entire layer stacks as needed.
*
* <p> This event is fired on the {@linkplain IModBusEvent mod event bus},
* only on the {@linkplain net.minecraftforge.fml.LogicalSide logical client}.</p>
*
* @param getLayedDraw The provided {@linkplain ForgeLayeredDraw#instance}. By default will be {@linkplain ForgeLayeredDraw#VANILLA_ROOT}.
*/
@NullMarked
public record AddGuiOverlayLayersEvent(ForgeLayeredDraw getLayeredDraw) implements IModBusEvent, SelfDestructing, RecordEvent {
@ApiStatus.Internal
public AddGuiOverlayLayersEvent {}
public static EventBus<AddGuiOverlayLayersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, AddGuiOverlayLayersEvent.class);
}
}
@@ -31,6 +31,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -60,12 +61,10 @@ public abstract sealed class EntityRenderersEvent implements IModBusEvent {
/**
* Fired for registering layer definitions at the appropriate time.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static final class RegisterLayerDefinitions extends EntityRenderersEvent {
public static final class RegisterLayerDefinitions extends EntityRenderersEvent implements SelfDestructing {
public static EventBus<RegisterLayerDefinitions> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterLayerDefinitions.class);
}
@@ -92,12 +91,10 @@ public abstract sealed class EntityRenderersEvent implements IModBusEvent {
* For registering entity renderer layers to existing entity renderers (whether vanilla or registered through this
* event), listen for the {@link AddLayers} event instead.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static final class RegisterRenderers extends EntityRenderersEvent {
public static final class RegisterRenderers extends EntityRenderersEvent implements SelfDestructing {
public static EventBus<RegisterRenderers> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterRenderers.class);
}
@@ -10,6 +10,8 @@ import java.util.List;
import java.util.Map;
import java.util.function.Function;
import net.minecraftforge.client.FramePassManager;
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.Result;
import net.minecraftforge.event.TickEvent;
@@ -283,4 +285,12 @@ public final class ForgeEventFactoryClient {
// This is on the mod bus because it happens during the initial texture reload, which is while the Forge bus is shut down.
return fireModBus(new ModelEvent.RegisterModelStateDefinitions());
}
public static void onInitLevelRenderer() {
AddFramePassEvent.BUS.post(new AddFramePassEvent());
}
public static void onComputeLayerOrder(ForgeLayeredDraw layeredDraw) {
fireModBus(new AddGuiOverlayLayersEvent(layeredDraw));
}
}
@@ -155,8 +155,6 @@ public abstract sealed class ModelEvent {
/**
* Allows users to register their own {@link IGeometryLoader geometry loaders} for use in block/item models.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
@@ -174,13 +172,23 @@ public abstract sealed class ModelEvent {
/**
* Registers a new geometry loader.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
*/
public void register(ResourceLocation resourceLocation, IGeometryLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Geometry loader already registered: " + resourceLocation);
loaders.put(resourceLocation, loader);
}
/**
* Registers a new geometry loader.
* @deprecated Use {@link #register(ResourceLocation, IGeometryLoader)} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.9") // removed in 1.21.9
public void register(String name, IGeometryLoader loader) {
@SuppressWarnings("removal")
var namespace = ModLoadingContext.get().getActiveNamespace();
var key = ResourceLocation.fromNamespaceAndPath(namespace, name);
Preconditions.checkArgument(!loaders.containsKey(key), "Geometry loader already registered: " + key);
loaders.put(key, loader);
register(key, loader);
}
}
}
@@ -11,6 +11,7 @@ import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraftforge.event.AddReloadListenerEvent;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -22,12 +23,10 @@ import org.jetbrains.annotations.ApiStatus;
*
* <p>For registering reload listeners on the server-side resource manager, see {@link AddReloadListenerEvent}.</p>
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterClientReloadListenersEvent implements IModBusEvent {
public final class RegisterClientReloadListenersEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterClientReloadListenersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterClientReloadListenersEvent.class);
}
@@ -9,6 +9,7 @@ import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -21,12 +22,10 @@ import java.util.function.Function;
* Allows users to register custom {@link net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent}
* factories for their {@link net.minecraft.world.inventory.tooltip.TooltipComponent} types.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterClientTooltipComponentFactoriesEvent implements IModBusEvent {
public final class RegisterClientTooltipComponentFactoriesEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterClientTooltipComponentFactoriesEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterClientTooltipComponentFactoriesEvent.class);
}
@@ -12,10 +12,14 @@ import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ColorResolver;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.ArrayList;
/**
* Fired for registering block and item color handlers at the appropriate time.
@@ -76,15 +80,16 @@ public abstract sealed class RegisterColorHandlersEvent implements IModBusEvent
* Allows registration of custom {@link ColorResolver} implementations to be used with
* {@link net.minecraft.world.level.BlockAndTintGetter#getBlockTint(BlockPos, ColorResolver)}.
*/
public static final class ColorResolvers extends RegisterColorHandlersEvent {
@NullMarked
public static final class ColorResolvers extends RegisterColorHandlersEvent implements SelfDestructing {
public static EventBus<ColorResolvers> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, ColorResolvers.class);
}
private final ImmutableList.Builder<ColorResolver> builder;
private final ArrayList<ColorResolver> builder;
@ApiStatus.Internal
public ColorResolvers(ImmutableList.Builder<ColorResolver> builder) {
public ColorResolvers(ArrayList<ColorResolver> builder) {
this.builder = builder;
}
@@ -9,22 +9,23 @@ import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.Map;
/**
* Allows users to register custom {@link DimensionSpecialEffects} for their dimensions.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterDimensionSpecialEffectsEvent implements IModBusEvent {
@NullMarked
public final class RegisterDimensionSpecialEffectsEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterDimensionSpecialEffectsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterDimensionSpecialEffectsEvent.class);
}
@@ -9,10 +9,12 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.Map;
@@ -20,12 +22,11 @@ import java.util.Map;
* Allows users to register custom shaders to be used when the player spectates a certain kind of entity.
* Vanilla examples of this are the green effect for creepers and the invert effect for endermen.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterEntitySpectatorShadersEvent implements IModBusEvent {
@NullMarked
public final class RegisterEntitySpectatorShadersEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterEntitySpectatorShadersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterEntitySpectatorShadersEvent.class);
}
@@ -11,6 +11,7 @@ import net.minecraftforge.client.IItemDecorator;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -23,12 +24,10 @@ import java.util.Map;
/**
* Allows users to register custom {@linkplain IItemDecorator IItemDecorator} to Items.
*
* <p>This event is not {@linkplain Cancelable cancelable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterItemDecorationsEvent implements IModBusEvent {
public final class RegisterItemDecorationsEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterItemDecorationsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterItemDecorationsEvent.class);
}
@@ -9,6 +9,7 @@ import net.minecraft.client.KeyMapping;
import net.minecraft.client.Options;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -18,12 +19,10 @@ import org.jetbrains.annotations.ApiStatus;
/**
* Allows users to register custom {@link net.minecraft.client.KeyMapping key mappings}.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterKeyMappingsEvent implements IModBusEvent {
public final class RegisterKeyMappingsEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterKeyMappingsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterKeyMappingsEvent.class);
}
@@ -13,6 +13,7 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.event.IModBusEvent;
@@ -25,7 +26,7 @@ import java.util.Map;
*
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterNamedRenderTypesEvent implements IModBusEvent {
public final class RegisterNamedRenderTypesEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterNamedRenderTypesEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterNamedRenderTypesEvent.class);
}
@@ -40,10 +41,40 @@ public final class RegisterNamedRenderTypesEvent implements IModBusEvent {
/**
* Registers a named {@link RenderTypeGroup}.
*
* @param name The name
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
* @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
*/
public void register(ResourceLocation resourceLocation, ChunkSectionLayer blockRenderType, RenderType entityRenderType) {
register(resourceLocation, blockRenderType, entityRenderType, entityRenderType);
}
/**
* Registers a named {@link RenderTypeGroup}.
*
* @param key The namespace should match your mod's namespace, such as your mod ID
* @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
* @param fabulousEntityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for use when
* "fabulous" rendering is enabled
*/
public void register(ResourceLocation key, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) {
Preconditions.checkArgument(!renderTypes.containsKey(key), "Render type already registered: " + key);
Preconditions.checkArgument(entityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The entity render type must use the NEW_ENTITY vertex format.");
Preconditions.checkArgument(fabulousEntityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The fabulous entity render type must use the NEW_ENTITY vertex format.");
renderTypes.put(key, new RenderTypeGroup(blockRenderType, entityRenderType, fabulousEntityRenderType));
}
/**
* Registers a named {@link RenderTypeGroup}.
*
* @param name The name
* @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
*
* @deprecated Use {@link #register(ResourceLocation, ChunkSectionLayer, RenderType, RenderType)} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.9") // removed in 1.21.9
public void register(String name, ChunkSectionLayer blockRenderType, RenderType entityRenderType) {
register(name, blockRenderType, entityRenderType, entityRenderType);
}
@@ -56,13 +87,13 @@ public final class RegisterNamedRenderTypesEvent implements IModBusEvent {
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
* @param fabulousEntityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for use when
* "fabulous" rendering is enabled
*
* @deprecated Use {@link #register(ResourceLocation, ChunkSectionLayer, RenderType, RenderType)} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.9") // removed in 1.21.9
public void register(String name, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) {
@SuppressWarnings("removal")
var key = ResourceLocation.fromNamespaceAndPath(ModLoadingContext.get().getActiveNamespace(), name);
Preconditions.checkArgument(!renderTypes.containsKey(key), "Render type already registered: " + key);
Preconditions.checkArgument(entityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The entity render type must use the NEW_ENTITY vertex format.");
Preconditions.checkArgument(fabulousEntityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The fabulous entity render type must use the NEW_ENTITY vertex format.");
renderTypes.put(key, new RenderTypeGroup(blockRenderType, entityRenderType, fabulousEntityRenderType));
register(key, blockRenderType, entityRenderType, fabulousEntityRenderType);
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.gui.render.pip.PictureInPictureRenderer;
import net.minecraft.client.gui.render.state.pip.PictureInPictureRenderState;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
import java.util.HashSet;
import java.util.List;
/**
* Used for registering custom picture in picture renderers.
* <p>
* Fired at the beginning of the loading screen when starting minecraft.
* Cannot be used to replace vanilla picture in picture renderers.
* This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}
*/
public final class RegisterPictureInPictureRendererEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterPictureInPictureRendererEvent> BUS = EventBus.create(RegisterPictureInPictureRendererEvent.class);
private final List<PictureInPictureRenderer<?>> renderers;
private final MultiBufferSource.BufferSource bufferSource;
private final ImmutableMap.Builder<Class<? extends PictureInPictureRenderState>, PictureInPictureRenderer<?>> builder;
@ApiStatus.Internal
public RegisterPictureInPictureRendererEvent(List<PictureInPictureRenderer<?>> renderers, MultiBufferSource.BufferSource bufferSource, ImmutableMap.Builder<Class<? extends PictureInPictureRenderState>, PictureInPictureRenderer<?>> builder) {
this.renderers = renderers;
this.bufferSource = bufferSource;
this.builder = builder;
}
public MultiBufferSource.BufferSource getBufferSource() {
return bufferSource;
}
public void register(PictureInPictureRenderer<?> renderer) {
var seen = HashSet.newHashSet(renderers.size());
for (var r : renderers)
seen.add(r.getRenderStateClass());
var key = renderer.getRenderStateClass();
if (seen.add(key))
this.builder.put(key, renderer);
}
}
@@ -9,6 +9,7 @@ import java.util.Map;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
@@ -24,12 +25,10 @@ import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
/**
* <p>Event for registering {@link PresetEditor} screen factories for world presets.</p>
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterPresetEditorsEvent implements IModBusEvent {
public final class RegisterPresetEditorsEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterPresetEditorsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterPresetEditorsEvent.class);
}
@@ -12,6 +12,7 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.event.IModBusEvent;
@@ -21,12 +22,10 @@ import org.jetbrains.annotations.ApiStatus;
/**
* Allows users to register custom {@link ITextureAtlasSpriteLoader texture atlas sprite loaders}.
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public final class RegisterTextureAtlasSpriteLoadersEvent implements IModBusEvent {
public final class RegisterTextureAtlasSpriteLoadersEvent implements SelfDestructing, IModBusEvent {
public static EventBus<RegisterTextureAtlasSpriteLoadersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterTextureAtlasSpriteLoadersEvent.class);
}
@@ -40,12 +39,22 @@ public final class RegisterTextureAtlasSpriteLoadersEvent implements IModBusEven
/**
* Registers a custom {@link ITextureAtlasSpriteLoader sprite loader}.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
*/
public void register(ResourceLocation resourceLocation, ITextureAtlasSpriteLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Sprite loader already registered: " + resourceLocation);
Preconditions.checkArgument(!loaders.containsValue(loader), "Sprite loader already registered as " + loaders.inverse().get(loader));
loaders.put(resourceLocation, loader);
}
/**
* Registers a custom {@link ITextureAtlasSpriteLoader sprite loader}.
* @deprecated Use {@link #register(ResourceLocation, ITextureAtlasSpriteLoader)} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.9") // removed in 1.21.9
public void register(String name, ITextureAtlasSpriteLoader loader) {
@SuppressWarnings("removal")
var key = ResourceLocation.fromNamespaceAndPath(ModLoadingContext.get().getActiveNamespace(), name);
Preconditions.checkArgument(!loaders.containsKey(key), "Sprite loader already registered: " + key);
Preconditions.checkArgument(!loaders.containsValue(loader), "Sprite loader already registered as " + loaders.inverse().get(loader));
loaders.put(key, loader);
register(key, loader);
}
}
@@ -9,9 +9,8 @@ import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.entity.HumanoidArm;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.Cancellable;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
@@ -21,48 +20,24 @@ import org.jetbrains.annotations.ApiStatus;
* and can be used to replace the rendering of the player's arm, such as for rendering armor on the arm or outright
* replacing the arm with armor.
*
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
* If this event is cancelled, then the arm will not be rendered.</p>
* <p>This event is {@linkplain Cancellable cancellable}. If this event is cancelled, then the arm will not be rendered.</p>
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* @param getPoseStack The pose stack used for rendering
* @param getMultiBufferSource The source of rendering buffers
* @param getArm The arm being rendered
*/
public final class RenderArmEvent extends MutableEvent implements Cancellable {
public record RenderArmEvent(
PoseStack getPoseStack,
MultiBufferSource getMultiBufferSource,
int getPackedLight,
HumanoidArm getArm
) implements Cancellable, RecordEvent {
public static final CancellableEventBus<RenderArmEvent> BUS = CancellableEventBus.create(RenderArmEvent.class);
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
private final HumanoidArm arm;
@ApiStatus.Internal
public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, HumanoidArm arm) {
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
this.arm = arm;
}
/**
* {@return the arm being rendered}
*/
public HumanoidArm getArm() {
return arm;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
public RenderArmEvent {}
/**
* {@return the amount of packed (sky and block) light for rendering}
@@ -70,6 +45,6 @@ public final class RenderArmEvent extends MutableEvent implements Cancellable {
* @see LightTexture
*/
public int getPackedLight() {
return packedLight;
return getPackedLight;
}
}
@@ -9,9 +9,8 @@ import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.Cancellable;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
@@ -19,13 +18,21 @@ import org.jetbrains.annotations.ApiStatus;
/**
* Fired before a block texture will be overlaid on the player's view.
*
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
* If this event is cancelled, then the overlay will not be rendered.</p>
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* @param getPlayer The player which the overlay will apply to
* @param getPoseStack The pose stack used for rendering
* @param getOverlayType The type of the overlay
* @param getBlockState The block which the overlay is gotten from
* @param getBlockPos The position of the block which the overlay is gotten from
*/
public final class RenderBlockScreenEffectEvent extends MutableEvent implements Cancellable {
public record RenderBlockScreenEffectEvent(
Player getPlayer,
PoseStack getPoseStack,
OverlayType getOverlayType,
BlockState getBlockState,
BlockPos getBlockPos
) implements Cancellable, RecordEvent {
public static final CancellableEventBus<RenderBlockScreenEffectEvent> BUS = CancellableEventBus.create(RenderBlockScreenEffectEvent.class);
/**
@@ -48,53 +55,6 @@ public final class RenderBlockScreenEffectEvent extends MutableEvent implements
WATER
}
private final Player player;
private final PoseStack poseStack;
private final OverlayType overlayType;
private final BlockState blockState;
private final BlockPos blockPos;
@ApiStatus.Internal
public RenderBlockScreenEffectEvent(Player player, PoseStack poseStack, OverlayType type, BlockState block, BlockPos blockPos) {
this.player = player;
this.poseStack = poseStack;
this.overlayType = type;
this.blockState = block;
this.blockPos = blockPos;
}
/**
* {@return the player which the overlay will apply to}
*/
public Player getPlayer() {
return player;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the type of the overlay}
*/
public OverlayType getOverlayType() {
return overlayType;
}
/**
* {@return the block which the overlay is gotten from}
*/
public BlockState getBlockState() {
return blockState;
}
/**
* {@return the position of the block which the overlay is gotten from}
*/
public BlockPos getBlockPos() {
return blockPos;
}
public RenderBlockScreenEffectEvent {}
}
@@ -10,9 +10,8 @@ import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.Cancellable;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
@@ -20,63 +19,36 @@ import org.jetbrains.annotations.ApiStatus;
/**
* Fired before a hand is rendered in the first person view.
*
* <p>This event is {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
* If this event is cancelled, then the hand will not be rendered.</p>
* <p>This event is {@linkplain Cancellable cancellable}. If this event is cancelled, then the hand will not be rendered.</p>
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* @param getHand The hand being rendered
* @param getPoseStack The pose stack used for rendering
* @param getMultiBufferSource The source of rendering buffers
* @param getPartialTick The partial tick
* @param getInterpolatedPitch The interpolated pitch of the player entity
* @param getSwingProgress The swing progress of the hand being rendered
* @param getEquipProgress The progress of the equip animation, from {@code 0.0} to {@code 1.0}
* @param getItemStack The item stack to be rendered
*
* @see RenderArmEvent
*/
public final class RenderHandEvent extends MutableEvent implements Cancellable {
public record RenderHandEvent(
InteractionHand getHand,
PoseStack getPoseStack,
MultiBufferSource getMultiBufferSource,
int getPackedLight,
float getPartialTick,
float getInterpolatedPitch,
float getSwingProgress,
float getEquipProgress,
ItemStack getItemStack
) implements Cancellable, RecordEvent {
public static final CancellableEventBus<RenderHandEvent> BUS = CancellableEventBus.create(RenderHandEvent.class);
private final InteractionHand hand;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
private final float partialTick;
private final float interpolatedPitch;
private final float swingProgress;
private final float equipProgress;
private final ItemStack stack;
@ApiStatus.Internal
public RenderHandEvent(InteractionHand hand, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight,
float partialTick, float interpolatedPitch,
float swingProgress, float equipProgress, ItemStack stack)
{
this.hand = hand;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
this.partialTick = partialTick;
this.interpolatedPitch = interpolatedPitch;
this.swingProgress = swingProgress;
this.equipProgress = equipProgress;
this.stack = stack;
}
/**
* {@return the hand being rendered}
*/
public InteractionHand getHand() {
return hand;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
public RenderHandEvent {}
/**
* {@return the amount of packed (sky and block) light for rendering}
@@ -84,41 +56,6 @@ public final class RenderHandEvent extends MutableEvent implements Cancellable {
* @see LightTexture
*/
public int getPackedLight() {
return packedLight;
}
/**
* {@return the partial tick}
*/
public float getPartialTick() {
return partialTick;
}
/**
* {@return the interpolated pitch of the player entity}
*/
public float getInterpolatedPitch() {
return interpolatedPitch;
}
/**
* {@return the swing progress of the hand being rendered}
*/
public float getSwingProgress() {
return swingProgress;
}
/**
* {@return the progress of the equip animation, from {@code 0.0} to {@code 1.0}}
*/
public float getEquipProgress() {
return equipProgress;
}
/**
* {@return the item stack to be rendered}
*/
public ItemStack getItemStack() {
return stack;
return getPackedLight;
}
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more