mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-14 09:05:17 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6da89dd6c | ||
|
|
a1e611bbcb | ||
|
|
7ec1a5e58d | ||
|
|
2c0fe5b985 | ||
|
|
885eba73ba | ||
|
|
4fa61fa0c0 | ||
|
|
5d4438b0e3 | ||
|
|
fbb7507ef1 | ||
|
|
59955f186b | ||
|
|
249ace972e | ||
|
|
8438b4a82b | ||
|
|
5b82b16ad2 | ||
|
|
485e93d652 | ||
|
|
947480ed28 | ||
|
|
e52740058a | ||
|
|
01a4d503ad | ||
|
|
284710527c | ||
|
|
3ce2f03cf2 | ||
|
|
39f41fcda9 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ '1.21.4' ]
|
||||
|
||||
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 }}
|
||||
@@ -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 }}
|
||||
Vendored
-104
@@ -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>
|
||||
Vendored
-193
@@ -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
@@ -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,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.2'
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-6
@@ -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
|
||||
]
|
||||
@@ -925,23 +924,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,
|
||||
|
||||
@@ -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
|
||||
@@ -175,7 +175,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ public class ModFile implements IModFile {
|
||||
private CompletableFuture<ModFileScanData> futureScanResult;
|
||||
private List<CoreModFile> coreMods;
|
||||
private Path accessTransformer;
|
||||
private List<Path> accessTransformers = Collections.emptyList();
|
||||
|
||||
static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
|
||||
private SecureJar.Status securityStatus;
|
||||
@@ -94,8 +95,14 @@ 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() {
|
||||
@@ -104,7 +111,28 @@ public class ModFile implements IModFile {
|
||||
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
|
||||
this.coreMods = ModFileParser.getCoreMods(this);
|
||||
this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath()));
|
||||
this.accessTransformer = findResource("META-INF", "accesstransformer.cfg");
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
+12
-4
@@ -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) {
|
||||
|
||||
+29
-183
@@ -1,216 +1,62 @@
|
||||
// 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.24,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
|
||||
//
|
||||
// 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 MinecraftForge
|
||||
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started
|
||||
//
|
||||
// Use non-default mappings at your own risk. They may not always work.
|
||||
// Simply re-run your setup task after changing the mappings to update your workspace.
|
||||
mappings channel: mapping_channel, version: mapping_version
|
||||
|
||||
// Tell FG to not automtically create the reobf tasks, as we now use Official mappings at runtime, If you don't use them at dev time then you'll have to fix your reobf yourself.
|
||||
reobf = false
|
||||
mappings channel: 'official', version: '@MC_VERSION@'
|
||||
|
||||
// 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.
|
||||
// They will be 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')
|
||||
|
||||
// Recommended logging data for a userdev environment
|
||||
// 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'
|
||||
|
||||
// Recommended logging level for the console
|
||||
// You can set various levels here.
|
||||
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
|
||||
property 'forge.logging.console.level', 'debug'
|
||||
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
|
||||
// ForgeGradle automatically adds the Forge maven and Maven Central for you
|
||||
|
||||
// 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'
|
||||
// }
|
||||
minecraft.mavenizer(it) // In Kotlin, it = this
|
||||
maven fg.forgeMaven
|
||||
maven fg.minecraftLibsMaven
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
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}"
|
||||
|
||||
// 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).configure {
|
||||
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).configure {
|
||||
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
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
// 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@')
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
||||
}
|
||||
|
||||
// IntelliJ no longer downloads javadocs and sources by default.
|
||||
// This tells Gradle to force IDEA to do it.
|
||||
idea.module { downloadJavadoc = downloadSources = true }
|
||||
|
||||
eclipse {
|
||||
// Run everytime eclipse builds the code
|
||||
//autoBuildTasks genEclipseRuns
|
||||
// Run when importing the project
|
||||
synchronizationTasks 'genEclipseRuns'
|
||||
}
|
||||
|
||||
// Merge the resources and classes into the same directory.
|
||||
// This is done 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'
|
||||
}
|
||||
@@ -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/
|
||||
@@ -22,4 +22,5 @@ eclipse
|
||||
run
|
||||
|
||||
# Files from Forge MDK
|
||||
forge_README.txt
|
||||
forge*changelog.txt
|
||||
+7
-57
@@ -1,59 +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=-Xmx3G
|
||||
org.gradle.daemon=false
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.configureondemand=true
|
||||
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.configuration-cache.parallel=true
|
||||
org.gradle.configuration-cache.problems=warn
|
||||
|
||||
## 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
@@ -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.7.0'
|
||||
}
|
||||
rootProject.name = 'examplemod'
|
||||
@@ -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,)"
|
||||
@@ -9,6 +9,40 @@
|
||||
private final SubtitleOverlay subtitleOverlay;
|
||||
private final SpectatorGui spectatorGui;
|
||||
private final PlayerTabOverlay tabList;
|
||||
@@ -167,7 +_,7 @@
|
||||
private int lastBubblePopSoundPlayed;
|
||||
private float autosaveIndicatorValue;
|
||||
private float lastAutosaveIndicatorValue;
|
||||
- private final LayeredDraw layers = new LayeredDraw();
|
||||
+ private final LayeredDraw layers = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.VANILLA_ROOT, net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.COMBINE_LIST);
|
||||
private float scopeScale;
|
||||
|
||||
public Gui(Minecraft p_330021_) {
|
||||
@@ -179,14 +_,14 @@
|
||||
this.bossOverlay = new BossHealthOverlay(p_330021_);
|
||||
this.subtitleOverlay = new SubtitleOverlay(p_330021_);
|
||||
this.resetTitleTimes();
|
||||
- LayeredDraw layereddraw = new LayeredDraw()
|
||||
+ LayeredDraw layereddraw = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.PRE_SLEEP_STACK, net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.PRE_LIST)
|
||||
.add(this::renderCameraOverlays)
|
||||
.add(this::renderCrosshair)
|
||||
.add(this::renderHotbarAndDecorations)
|
||||
.add(this::renderExperienceLevel)
|
||||
.add(this::renderEffects)
|
||||
.add((p_325313_, p_342678_) -> this.bossOverlay.render(p_325313_));
|
||||
- LayeredDraw layereddraw1 = new LayeredDraw()
|
||||
+ LayeredDraw layereddraw1 = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.POST_SLEEP_STACK,net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.POST_LIST)
|
||||
.add(this::renderDemoOverlay)
|
||||
.add((p_325315_, p_344521_) -> {
|
||||
if (this.debugOverlay.showDebugScreen()) {
|
||||
@@ -203,6 +_,7 @@
|
||||
.add(layereddraw, () -> !p_330021_.options.hideGui)
|
||||
.add(this::renderSleepOverlay)
|
||||
.add(layereddraw1, () -> !p_330021_.options.hideGui);
|
||||
+ ((net.minecraftforge.client.gui.overlay.ForgeLayeredDraw) layers).resolveLayers();
|
||||
}
|
||||
|
||||
public void resetTitleTimes() {
|
||||
@@ -345,7 +_,7 @@
|
||||
Window window = this.minecraft.getWindow();
|
||||
int i = Mth.floor(this.minecraft.mouseHandler.xpos() * (double)window.getGuiScaledWidth() / (double)window.getScreenWidth());
|
||||
|
||||
@@ -18,6 +18,14 @@
|
||||
CloudStatus cloudstatus = this.minecraft.options.getCloudsType();
|
||||
if (cloudstatus != CloudStatus.OFF) {
|
||||
float f2 = this.level.effects().getCloudHeight();
|
||||
@@ -499,6 +_,7 @@
|
||||
}
|
||||
|
||||
this.addLateDebugPass(framegraphbuilder, vec3, fogparameters);
|
||||
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onLastFramePassAddition(framegraphbuilder, targets);
|
||||
profilerfiller.popPush("framegraph");
|
||||
framegraphbuilder.execute(p_367325_, new FrameGraphBuilder.Inspector() {
|
||||
@Override
|
||||
@@ -564,7 +_,11 @@
|
||||
double d2 = vec3.z();
|
||||
p_369478_.push("terrain");
|
||||
|
||||
@@ -324,7 +324,7 @@
|
||||
public boolean isPushedByFluid() {
|
||||
return true;
|
||||
}
|
||||
@@ -3307,9 +_,17 @@
|
||||
@@ -3307,9 +_,26 @@
|
||||
return Mth.lerp(p_344421_, this.yRotO, this.yRot);
|
||||
}
|
||||
|
||||
@@ -334,20 +334,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);
|
||||
@@ -3324,25 +_,28 @@
|
||||
Vec3 vec3 = Vec3.ZERO;
|
||||
int k1 = 0;
|
||||
@@ -3321,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++) {
|
||||
@@ -355,66 +367,81 @@
|
||||
blockpos$mutableblockpos.set(l1, i2, j2);
|
||||
FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos);
|
||||
- if (fluidstate.is(p_204032_)) {
|
||||
- double d1 = (double)((float)i2 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos));
|
||||
+ net.minecraftforge.fluids.FluidType fluidType = fluidstate.getFluidType();
|
||||
+ if (!fluidType.isAir() && shouldUpdate.test(fluidstate)) {
|
||||
double d1 = (double)((float)i2 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos));
|
||||
+ double d1 = i2 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos);
|
||||
if (d1 >= aabb.minY) {
|
||||
flag1 = true;
|
||||
- d0 = Math.max(d1 - aabb.minY, d0);
|
||||
- if (flag) {
|
||||
+ var interim = interimCalcs.computeIfAbsent(fluidType, t -> org.apache.commons.lang3.tuple.MutableTriple.of(0.0D, Vec3.ZERO, 0));
|
||||
+ interim.setLeft(Math.max(d1 - aabb.minY, interim.getLeft()));
|
||||
+ if (this.isPushedByFluid(fluidType)) {
|
||||
+ 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++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3350,27 +_,28 @@
|
||||
@@ -3350,27 +_,32 @@
|
||||
}
|
||||
}
|
||||
|
||||
- if (vec3.length() > 0.0) {
|
||||
- if (k1 > 0) {
|
||||
- vec3 = vec3.scale(1.0 / (double)k1);
|
||||
+ interimCalcs.forEach((fluidType, interim) -> {
|
||||
+ if (interim.getMiddle().length() > 0.0D) {
|
||||
+ if (interim.getRight() > 0) {
|
||||
+ interim.setMiddle(interim.getMiddle().scale(1.0D / (double)interim.getRight()));
|
||||
}
|
||||
|
||||
if (!(this instanceof Player)) {
|
||||
- }
|
||||
-
|
||||
- if (!(this instanceof Player)) {
|
||||
- vec3 = vec3.normalize();
|
||||
+ interim.setMiddle(interim.getMiddle().normalize());
|
||||
}
|
||||
|
||||
Vec3 vec32 = this.getDeltaMovement();
|
||||
- }
|
||||
-
|
||||
- Vec3 vec32 = this.getDeltaMovement();
|
||||
- vec3 = vec3.scale(p_204033_);
|
||||
+ interim.setMiddle(interim.getMiddle().scale(this.getFluidMotionScale(fluidType)));
|
||||
double d2 = 0.003;
|
||||
- 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 (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);
|
||||
+ }
|
||||
+
|
||||
+ if (!(this instanceof Player)) {
|
||||
+ vec3 = vec3.normalize();
|
||||
+ }
|
||||
+
|
||||
+ Vec3 vec32 = this.getDeltaMovement();
|
||||
+ 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);
|
||||
+ }
|
||||
+
|
||||
+ this.setDeltaMovement(this.getDeltaMovement().add(vec3));
|
||||
+ }
|
||||
+
|
||||
+ this.setFluidTypeHeight(entry.getKey(), entry.getValue().height);
|
||||
}
|
||||
|
||||
-
|
||||
- this.fluidHeight.put(p_204032_, d0);
|
||||
- return flag1;
|
||||
+ this.setFluidTypeHeight(fluidType, interim.getLeft());
|
||||
+ });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
--- a/net/minecraft/world/level/block/CrafterBlock.java
|
||||
+++ b/net/minecraft/world/level/block/CrafterBlock.java
|
||||
@@ -192,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;
|
||||
}
|
||||
@@ -208,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/chunk/PalettedContainer.java
|
||||
+++ b/net/minecraft/world/level/chunk/PalettedContainer.java
|
||||
@@ -56,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()
|
||||
+2
-2
@@ -27,7 +27,7 @@ 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')
|
||||
@@ -52,7 +52,7 @@ dependencyResolutionManagement {
|
||||
library('bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim').versionRef('bootstrap')
|
||||
|
||||
// ASM it's used for so many of our hacks
|
||||
version('asm', '9.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')
|
||||
|
||||
@@ -108,7 +108,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
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.event;
|
||||
|
||||
import com.mojang.blaze3d.framegraph.FrameGraphBuilder;
|
||||
import com.mojang.blaze3d.framegraph.FramePass;
|
||||
import net.minecraft.client.renderer.LevelTargetBundle;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Fired after all vanilla frame passes are added into the pass list.
|
||||
*
|
||||
* <p>This event is not {@linkplain net.minecraftforge.eventbus.api.Cancelable cancellable}, and does not
|
||||
* {@linkplain HasResult have a result}.</p>
|
||||
*
|
||||
* <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}.
|
||||
*/
|
||||
public final class AddFramePassEvent extends Event {
|
||||
private final FrameGraphBuilder builder;
|
||||
private final LevelTargetBundle bundle;
|
||||
|
||||
private final Set<String> addedNames = new HashSet<>();
|
||||
|
||||
@ApiStatus.Internal
|
||||
public AddFramePassEvent(FrameGraphBuilder builder, LevelTargetBundle bundle) {
|
||||
this.builder = builder;
|
||||
this.bundle = bundle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a frame pass to the end of the pass list.
|
||||
*
|
||||
* @param rl Resource location for frame pass name. Use RLs to avoid duplicate names.
|
||||
* @return Reference to pass to add modder rendering to.
|
||||
* @throws IllegalArgumentException If the name is a duplicate.
|
||||
*/
|
||||
public FramePass createPass(ResourceLocation rl) {
|
||||
String name = rl.toString();
|
||||
if (!this.addedNames.add(name)) // false if the set didn't change
|
||||
throw new IllegalArgumentException("Cannot create a frame pass with a duplicate name: " + name);
|
||||
|
||||
return this.builder.addPass(name);
|
||||
}
|
||||
|
||||
public LevelTargetBundle getBundle() {
|
||||
return bundle;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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.Event;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* 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 not {@linkplain net.minecraftforge.eventbus.api.Cancelable cancellable} and does not {@linkplain net.minecraftforge.eventbus.api.Event.HasResult have a result}</p>
|
||||
*
|
||||
* <p> This event is fired on the {@linkplain IModBusEvent mod event bus},
|
||||
* only on the {@linkplain net.minecraftforge.fml.LogicalSide logical client}.</p>
|
||||
*/
|
||||
public final class AddGuiOverlayLayersEvent extends Event implements IModBusEvent {
|
||||
@NotNull
|
||||
private final ForgeLayeredDraw layeredDraw;
|
||||
|
||||
@ApiStatus.Internal
|
||||
public AddGuiOverlayLayersEvent(ForgeLayeredDraw layeredDraw) {
|
||||
this.layeredDraw = layeredDraw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the layered draw.
|
||||
* @return the draw layer stack
|
||||
*/
|
||||
@NotNull
|
||||
public ForgeLayeredDraw getLayeredDraw() {
|
||||
return layeredDraw;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.Cancelable;
|
||||
@@ -23,6 +24,7 @@ import com.google.common.collect.ImmutableMap;
|
||||
import com.mojang.blaze3d.audio.Channel;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.framegraph.FrameGraphBuilder;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.ClientRecipeBook;
|
||||
import net.minecraft.client.DeltaTracker;
|
||||
@@ -51,6 +53,7 @@ import net.minecraft.client.renderer.entity.state.ItemFrameRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
|
||||
import net.minecraft.client.renderer.entity.state.PlayerRenderState;
|
||||
import net.minecraft.client.renderer.special.SpecialModelRenderer;
|
||||
import net.minecraft.client.renderer.LevelTargetBundle;
|
||||
import net.minecraft.client.resources.PlayerSkin.Model;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
@@ -303,4 +306,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 onComputeLayerOrder(ForgeLayeredDraw layeredDraw) {
|
||||
fireModBus(new AddGuiOverlayLayersEvent(layeredDraw));
|
||||
}
|
||||
|
||||
public static void onLastFramePassAddition(FrameGraphBuilder builder, LevelTargetBundle bundle) {
|
||||
post(new AddFramePassEvent(builder, bundle));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.client.gui.overlay;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.LayeredDraw;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.client.event.ForgeEventFactoryClient;
|
||||
import net.minecraftforge.client.event.AddGuiOverlayLayersEvent;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import java.util.*;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* As vanilla has switched to a layered drawing system for overlays, this system replaces ForgeGui and its associated headaches.
|
||||
* Vanilla will now have resource locations to represent its render layers which modders can order against.
|
||||
* This class is effectively a pseudo-registry for Layers. Add what you need during {@linkplain AddGuiOverlayLayersEvent}
|
||||
* Layers must be uniquely named per ForgeLayeredDraw, but may be duplicated across different instances.
|
||||
* Any change which would result in a duplicate will not be applied.
|
||||
* All methods which return a {@linkplain ForgeLayeredDraw} will return its caller's instance.
|
||||
* To select a specific instance, use {@linkplain ForgeLayeredDraw#locateStack(ResourceLocation)} before adding
|
||||
* or use the methods that include a stack identifier.
|
||||
*/
|
||||
@FieldsAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@ParametersAreNonnullByDefault
|
||||
public final class ForgeLayeredDraw extends LayeredDraw {
|
||||
private static int unknown = 0;
|
||||
private final Map<ResourceLocation, Layer> namedLayers = new HashMap<>();
|
||||
private final Map<ResourceLocation, Map.Entry<LayeredDraw, BooleanSupplier>> subLayerStacks = new HashMap<>();
|
||||
private final List<ResourceLocation> order = new LinkedList<>();
|
||||
private final List<ResourceLocation> expectedNames = new ArrayList<>();
|
||||
private final ResourceLocation name;
|
||||
|
||||
public static final ResourceLocation PRE_SLEEP_STACK = ResourceLocation.withDefaultNamespace("pre_sleep_phase");
|
||||
public static final ResourceLocation CAMERA_OVERLAY = ResourceLocation.withDefaultNamespace("camera_overlay");
|
||||
public static final ResourceLocation CROSSHAIR = ResourceLocation.withDefaultNamespace("crosshair");
|
||||
public static final ResourceLocation HOTBAR = ResourceLocation.withDefaultNamespace("hotbar");
|
||||
public static final ResourceLocation EXPERIENCE = ResourceLocation.withDefaultNamespace("experience");
|
||||
public static final ResourceLocation POTION_EFFECTS = ResourceLocation.withDefaultNamespace("potion_effects");
|
||||
public static final ResourceLocation BOSS_OVERLAY = ResourceLocation.withDefaultNamespace("boss_overlay");
|
||||
|
||||
public static final ResourceLocation POST_SLEEP_STACK = ResourceLocation.withDefaultNamespace("post_sleep_phase");
|
||||
public static final ResourceLocation DEMO_OVERLAY = ResourceLocation.withDefaultNamespace("demo");
|
||||
public static final ResourceLocation DEBUG_OVERLAY = ResourceLocation.withDefaultNamespace("debug");
|
||||
public static final ResourceLocation SCOREBOARD = ResourceLocation.withDefaultNamespace("scoreboard");
|
||||
public static final ResourceLocation HOTBAR_MESSAGE = ResourceLocation.withDefaultNamespace("hotbar_message");
|
||||
public static final ResourceLocation TITLE_OVERLAY = ResourceLocation.withDefaultNamespace("title");
|
||||
public static final ResourceLocation CHAT_OVERLAY = ResourceLocation.withDefaultNamespace("chat_overlay");
|
||||
public static final ResourceLocation TAB_LIST = ResourceLocation.withDefaultNamespace("tab_list");
|
||||
public static final ResourceLocation SUBTITLE_OVERLAY = ResourceLocation.withDefaultNamespace("subtitle");
|
||||
|
||||
public static final ResourceLocation VANILLA_ROOT = ResourceLocation.withDefaultNamespace("vanilla_root");
|
||||
public static final ResourceLocation SLEEP_OVERLAY = ResourceLocation.withDefaultNamespace("sleep_overlay");
|
||||
|
||||
|
||||
public static final ImmutableList<ResourceLocation> PRE_LIST = ImmutableList.of(CAMERA_OVERLAY, CROSSHAIR, HOTBAR, EXPERIENCE, POTION_EFFECTS, BOSS_OVERLAY);
|
||||
public static final ImmutableList<ResourceLocation> POST_LIST = ImmutableList.of(DEMO_OVERLAY, DEBUG_OVERLAY, SCOREBOARD, HOTBAR_MESSAGE, TITLE_OVERLAY, CHAT_OVERLAY, TAB_LIST, SUBTITLE_OVERLAY);
|
||||
public static final ImmutableList<ResourceLocation> COMBINE_LIST = ImmutableList.of(PRE_SLEEP_STACK, SLEEP_OVERLAY, POST_SLEEP_STACK);
|
||||
|
||||
/**
|
||||
* Creates a stack of pre-named layers for vanilla.
|
||||
* Not intended for modder use. Use {@linkplain ForgeLayeredDraw(ResourceLocation, Boolean, String...)} instead.
|
||||
* @param name Stack identifier
|
||||
* @param layers locations of layers to add
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public ForgeLayeredDraw(ResourceLocation name, List<ResourceLocation> layers) {
|
||||
this.name = name;
|
||||
expectedNames.addAll(layers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty draw list. Add entries with {@linkplain ForgeLayeredDraw#add(ResourceLocation, Layer)}
|
||||
* @param name marker for which phase this is.
|
||||
*/
|
||||
public ForgeLayeredDraw(ResourceLocation name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a full, pre-named draw stack.
|
||||
* @param layeredDraw layer stack to be added.
|
||||
* @param booleanSupplier requirement for it to render.
|
||||
* @deprecated Modders should be using {@linkplain ForgeLayeredDraw#add(ResourceLocation, LayeredDraw, BooleanSupplier)}
|
||||
* @return this
|
||||
*/
|
||||
@Deprecated
|
||||
@Override
|
||||
public ForgeLayeredDraw add(LayeredDraw layeredDraw, BooleanSupplier booleanSupplier) {
|
||||
return add(getNextPreName(), layeredDraw, booleanSupplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a full draw stack with its provided condition.
|
||||
* Use {@linkplain ForgeLayeredDraw#putAbove} and {@linkplain ForgeLayeredDraw#putBelow} for fine location adjustment.
|
||||
* @param name RL of the name to identify this stack with.
|
||||
* @param layeredDraw the draw stack
|
||||
* @param supplier condition for this stack to render
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw add(ResourceLocation name, LayeredDraw layeredDraw, BooleanSupplier supplier) {
|
||||
if (isNameAvailable(name)) {
|
||||
subLayerStacks.put(name, Map.entry(layeredDraw, supplier));
|
||||
order.add(name);
|
||||
} else {
|
||||
nameTakenWarning(name);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a layer with an already known name provided by {@linkplain ForgeLayeredDraw(ResourceLocation, List)}
|
||||
* The layer will be rendered last (on top) of already added layers.
|
||||
* @param layer layer render code, see {@linkplain Layer} and example usages in {@linkplain Gui}
|
||||
* @deprecated Use {@linkplain ForgeLayeredDraw#add(ResourceLocation, Layer)} for adding individual layers.
|
||||
* @return this
|
||||
*/
|
||||
@Deprecated
|
||||
@Override
|
||||
public LayeredDraw add(Layer layer) {
|
||||
add(getNextPreName(), layer);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a layer to the layer list. This layer will be at the end of the list, which means
|
||||
* it will be rendered last (on top) of already added layers.
|
||||
* @param name RL for other mods to order against.
|
||||
* @param layer layer render code, see {@linkplain Layer} and example usages in {@linkplain Gui}
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw add(ResourceLocation targetStack, ResourceLocation name, Layer layer) {
|
||||
locateStack(targetStack).ifPresentOrElse((stack) -> stack.add(name, layer), () -> stackNotPresentWarning(targetStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method, assumes the intended draw stack instance is the caller.
|
||||
* Use any of the non-deprecated add methods if you want a specific instance,
|
||||
* or call {@linkplain ForgeLayeredDraw#locateStack(ResourceLocation)} to get a reference to an instance.
|
||||
* @param name RL of layer to add
|
||||
* @param layer layer render code, see {@linkplain Layer} and example usages in {@linkplain Gui}
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw add(ResourceLocation name, Layer layer) {
|
||||
if (isNameAvailable(name)) {
|
||||
namedLayers.put(name, layer);
|
||||
order.add(name);
|
||||
} else {
|
||||
nameTakenWarning(name);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use to specify where your custom draw stack should go. Can also be used to re-order layers.
|
||||
* Both target and destination must be in the same draw stack.
|
||||
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(ResourceLocation, ResourceLocation, LayerOffset)}
|
||||
* @param target layer name to move
|
||||
* @param destination layer name to order against
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw putAbove(ResourceLocation expectedStack, ResourceLocation target, ResourceLocation destination) {
|
||||
locateStack(expectedStack).ifPresentOrElse((stack) -> stack.move(target, destination, LayerOffset.ABOVE), () -> stackNotPresentWarning(expectedStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use to specify where your custom draw stack should go. Can also be used to re-order layers.
|
||||
* Both target and destination must be in the same draw stack.
|
||||
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(ResourceLocation, ResourceLocation, LayerOffset)}
|
||||
* @param target layer name to move
|
||||
* @param destination layer name to order against
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw putBelow(ResourceLocation expectedStack, ResourceLocation target, ResourceLocation destination) {
|
||||
locateStack(expectedStack).ifPresentOrElse((stack) -> stack.move(target, destination, LayerOffset.BELOW), () -> stackNotPresentWarning(expectedStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method, assumes the intended draw stack instance is the caller.
|
||||
* Moves pre-existing names around within the order.
|
||||
* @param target Layer being moved.
|
||||
* @param destination Layer being ordered against
|
||||
* @param offset Self-explanatory
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw move(ResourceLocation target, ResourceLocation destination, LayerOffset offset) {
|
||||
if (!order.contains(target)) {
|
||||
layerNotPresentWarning(target);
|
||||
return this;
|
||||
}
|
||||
int loc = order.indexOf(destination);
|
||||
if (loc == -1) {
|
||||
layerNotPresentWarning(destination);
|
||||
return this;
|
||||
}
|
||||
order.remove(target);
|
||||
order.add(loc + (offset == LayerOffset.ABOVE ? 1 : 0), target);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an overlay layer to be rendered above the other provided layer.
|
||||
* To render "above" another layer means thisLayer will be rendered after otherLayer
|
||||
* If the current stack does not contain otherLayer, no changes will be made.
|
||||
* @param newLayer name of the layer to be added
|
||||
* @param otherLayer name of the layer being ordered against
|
||||
* @param layer layer render code, see {@linkplain Layer} and example usages in {@linkplain Gui}
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addAbove(ResourceLocation expectedStack, ResourceLocation newLayer, ResourceLocation otherLayer, Layer layer) {
|
||||
locateStack(expectedStack).ifPresentOrElse((stack) -> {
|
||||
if (!stack.isNameAvailable(otherLayer)) {
|
||||
stack.add(newLayer, layer).move(newLayer, otherLayer, LayerOffset.ABOVE);
|
||||
} else {
|
||||
layerNotPresentWarning(otherLayer);
|
||||
}
|
||||
}, () -> stackNotPresentWarning(expectedStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method, assumes intended draw stack is the caller
|
||||
*/
|
||||
public ForgeLayeredDraw addAbove(ResourceLocation newLayer, ResourceLocation otherLayer, Layer layer) {
|
||||
return addAbove(name, newLayer, otherLayer, layer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an overlay layer to be rendered below the other provided layer.
|
||||
* To render "below" another layer means thisLayer will be rendered before otherLayer
|
||||
* If the current stack does not contain otherLayer, no changes will be made.
|
||||
* @param newLayer name of the layer to be added
|
||||
* @param otherLayer name of the layer being ordered against
|
||||
* @param layer layer render code, see {@linkplain Layer} and example usages in {@linkplain Gui}
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addBelow(ResourceLocation expectedStack, ResourceLocation newLayer, ResourceLocation otherLayer, Layer layer) {
|
||||
locateStack(expectedStack).ifPresentOrElse((stack) -> {
|
||||
if (!stack.isNameAvailable(otherLayer)) {
|
||||
stack.add(newLayer, layer).move(newLayer, otherLayer, LayerOffset.BELOW);
|
||||
} else {
|
||||
layerNotPresentWarning(otherLayer);
|
||||
}
|
||||
}, () -> stackNotPresentWarning(expectedStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method, assumes intended draw stack is the caller
|
||||
*/
|
||||
public ForgeLayeredDraw addBelow(ResourceLocation newLayer, ResourceLocation otherLayer, Layer layer) {
|
||||
return addBelow(name, newLayer, otherLayer, layer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new layer that will only be rendered when the condition is met. The layer will be added
|
||||
* at the end of the list, which means it will render last (on top) of already added layers
|
||||
* @param name name of the layer to be added
|
||||
* @param layer render code of layer being added
|
||||
* @param condition supplier for the condition
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addWithCondition(ResourceLocation targetStack, ResourceLocation name, Layer layer, BooleanSupplier condition) {
|
||||
locateStack(targetStack).ifPresentOrElse((stack) -> stack.addWithCondition(name, layer, condition), () -> stackNotPresentWarning(targetStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assumes the correct stack is the caller of this method, otherwise functions the same as other method.
|
||||
* @param name name of layer to be added
|
||||
* @param layer render code of layer being added
|
||||
* @param condition supplier for the condition
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addWithCondition(ResourceLocation name, Layer layer, BooleanSupplier condition) {
|
||||
add(name, layer).addConditionTo(name, condition);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a condition to a pre-existing layer in the specified stack, its render order is not changed.
|
||||
* If the target is not present, no changes are made.
|
||||
* @param targetStack name of the draw stack the target is expected to be in
|
||||
* @param targetLayer name of layer to add a condition to
|
||||
* @param condition supplier for the condition
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addConditionTo(ResourceLocation targetStack, ResourceLocation targetLayer, BooleanSupplier condition) {
|
||||
locateStack(targetStack).ifPresentOrElse((stack) -> stack.addConditionTo(targetLayer, condition), () -> stackNotPresentWarning(targetStack));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assumes the correct stack is the caller of this method.
|
||||
* Use {@linkplain ForgeLayeredDraw#addConditionTo(ResourceLocation, ResourceLocation, BooleanSupplier)}
|
||||
* if you do not have a reference to the draw stack you want.
|
||||
* @param targetLayer name of layer to add condition to
|
||||
* @param condition supplier for the condition
|
||||
* @return this
|
||||
*/
|
||||
public ForgeLayeredDraw addConditionTo(ResourceLocation targetLayer, BooleanSupplier condition) {
|
||||
var result = namedLayers.computeIfPresent(targetLayer,
|
||||
(name, layer) -> (guiGraphics, deltaTracker) -> {
|
||||
if (condition.getAsBoolean()) {
|
||||
layer.render(guiGraphics, deltaTracker);
|
||||
}
|
||||
});
|
||||
if (result == null) {
|
||||
layerNotPresentWarning(targetLayer);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagate the layer order down to the inner render list after providing modders an opportunity to alter the list as they wish.
|
||||
* @apiNote Modders should <emph>NEVER</emph> be calling this method.
|
||||
* @return this
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public ForgeLayeredDraw resolveLayers() {
|
||||
if (!order.isEmpty()) {
|
||||
ForgeEventFactoryClient.onComputeLayerOrder(this);
|
||||
}
|
||||
if (namedLayers.size() + subLayerStacks.size() < order.size()) {
|
||||
LogUtils.getLogger().warn("Found {} unbound pre-defined layer names when resolving gui overlay order. This is not an error, but potentially indicates a mod directly modifying Gui instead of using this api.", order.size() - namedLayers.size());
|
||||
}
|
||||
resolveNested();
|
||||
order.clear();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the layer order per stack, recursively as needed.
|
||||
* Parent layer stack {@linkplain ForgeLayeredDraw#VANILLA_ROOT} holds the results.
|
||||
*/
|
||||
private void resolveNested() {
|
||||
for (ResourceLocation layerName : order) {
|
||||
if (subLayerStacks.containsKey(layerName)) {
|
||||
var entry = subLayerStacks.get(layerName);
|
||||
if (entry.getKey() instanceof ForgeLayeredDraw resolveable) {
|
||||
resolveable.resolveNested();
|
||||
// Although unlikely, a LayeredDraw could be in the list, and we can't call resolveNested on one.
|
||||
}
|
||||
super.add((gg, tr) -> {
|
||||
if (entry.getValue().getAsBoolean()) entry.getKey().render(gg,tr);
|
||||
});
|
||||
} else {
|
||||
super.add(namedLayers.get(layerName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to locate a particular draw stack. Search starts at caller's instance. For global search call on VANILLA_ROOT
|
||||
* i.e. {@linkplain net.minecraftforge.client.event.AddGuiOverlayLayersEvent#getLayeredDraw()}
|
||||
* Entries which don't extend ForgeLayeredDraw may not have the proper fields to support internal list adjustment, so they are skipped.
|
||||
* @param targetStack Name of ForgeLayeredDraw to find
|
||||
* @return Filled Optional if target exists, empty otherwise.
|
||||
*/
|
||||
public Optional<ForgeLayeredDraw> locateStack(ResourceLocation targetStack) {
|
||||
if (!name.equals(targetStack)) {
|
||||
for (Map.Entry<LayeredDraw, BooleanSupplier> value : subLayerStacks.values()) {
|
||||
if (value.getKey() instanceof ForgeLayeredDraw searchable) {
|
||||
var res = searchable.locateStack(targetStack);
|
||||
if(res.isPresent()) return res;
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public LayeredDraw getChild(ResourceLocation childName) {
|
||||
return locateStack(childName).orElse(null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Layer getLayer(ResourceLocation layerName) {
|
||||
return namedLayers.get(layerName);
|
||||
}
|
||||
|
||||
private ResourceLocation getNextPreName() {
|
||||
return expectedNames.isEmpty() ? ResourceLocation.fromNamespaceAndPath("unknown", "layer_" + unknown++) : expectedNames.removeFirst();
|
||||
}
|
||||
|
||||
public ResourceLocation getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
private void stackNotPresentWarning(ResourceLocation stackName) {
|
||||
LogUtils.getLogger().warn("Target stack {} was not present anywhere. Is your ResourceLocation correct?", stackName);
|
||||
}
|
||||
|
||||
private void layerNotPresentWarning(ResourceLocation layer) {
|
||||
LogUtils.getLogger().warn("Expected layer {} was not found in stack {}, no layer modifications have been made.", layer, name);
|
||||
}
|
||||
|
||||
private void nameTakenWarning(ResourceLocation layer) {
|
||||
LogUtils.getLogger().warn("Name {} was already present in {} and cannot be re-used.", layer, name);
|
||||
}
|
||||
|
||||
private boolean isNameAvailable(ResourceLocation name) {
|
||||
return !namedLayers.containsKey(name) && !subLayerStacks.containsKey(name);
|
||||
}
|
||||
|
||||
public enum LayerOffset {
|
||||
ABOVE,
|
||||
BELOW
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,7 @@ public class ForgeConfig {
|
||||
}
|
||||
|
||||
public final ForgeConfigSpec.EnumValue<MigrationHelperMode> migrationHelperMode;
|
||||
public final ForgeConfigSpec.LongValue channelListLimit;
|
||||
|
||||
Common(ForgeConfigSpec.Builder builder) {
|
||||
builder.comment("General configuration settings")
|
||||
@@ -86,6 +87,17 @@ public class ForgeConfig {
|
||||
.translation("forge.configgui.migrationHelperMode")
|
||||
.defineEnum("logLegacyTagWarnings", MigrationHelperMode.OFF);
|
||||
|
||||
channelListLimit = builder
|
||||
.comment(
|
||||
"Maximum size to use to store the channel list for a network connection.",
|
||||
"The other end of the connection may send as many channels as it wishes.",
|
||||
"Some malicious actors may use this to use up all your memory causing OutOfMemoryException",
|
||||
"A sane default is 1KB (1024), but may need to be expanded for larger modpacks.",
|
||||
"Forge will auto-adjust this if mods register their channels using our channel manager."
|
||||
)
|
||||
.translation("forge.configui.channellistlimit")
|
||||
.defineInRange("channelListLimit", 1024, 1, Long.MAX_VALUE);
|
||||
|
||||
builder.pop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -27,6 +28,7 @@ import com.mojang.authlib.GameProfile;
|
||||
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.gametest.framework.GameTestAssertException;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.network.Connection;
|
||||
@@ -40,8 +42,10 @@ import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.entity.BaseContainerBlockEntity;
|
||||
import net.minecraftforge.common.ForgeI18n;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.common.capabilities.ForgeCapabilities;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
|
||||
public interface IForgeGameTestHelper {
|
||||
@@ -49,6 +53,10 @@ public interface IForgeGameTestHelper {
|
||||
return (GameTestHelper) this;
|
||||
}
|
||||
|
||||
default GameTestAssertException throwing(String message) {
|
||||
return new GameTestAssertException(Component.literal(message).getString());
|
||||
}
|
||||
|
||||
default void say(String message) {
|
||||
this.say(message, Style.EMPTY);
|
||||
}
|
||||
@@ -238,6 +246,48 @@ public interface IForgeGameTestHelper {
|
||||
}
|
||||
}
|
||||
|
||||
default void assertContainerContains(BlockPos pos, Item item, int expected) {
|
||||
BaseContainerBlockEntity basecontainerblockentity = self().getBlockEntity(pos);
|
||||
var actual = basecontainerblockentity.countItem(item);
|
||||
assertTrue(actual == expected, () -> "Failed to find %s x %d in container at %s, found %d".formatted(item, expected, pos, actual));
|
||||
}
|
||||
|
||||
default void assertItemHandlerContains(BlockPos pos, Item item) {
|
||||
assertItemHandlerContains(pos, null, item);
|
||||
}
|
||||
|
||||
default void assertItemHandlerContains(BlockPos pos, @Nullable Direction side, Item item) {
|
||||
assertFalse(countItemHandler(self(), pos, side, item) == 0, () -> "Failed to find any %s in IItemHandler at %s".formatted(item, pos));
|
||||
}
|
||||
|
||||
default void assertItemHandlerContains(BlockPos pos, Item item, int expected) {
|
||||
assertItemHandlerContains(pos, null, item, expected);
|
||||
}
|
||||
|
||||
default void assertItemHandlerContains(BlockPos pos, @Nullable Direction side, Item item, int expected) {
|
||||
int actual = countItemHandler(self(), pos, side, item);
|
||||
assertTrue(actual == expected, () -> "Failed to find %s x %d in IItemHandler at %s, found %d".formatted(item, expected, pos, actual));
|
||||
}
|
||||
|
||||
private static int countItemHandler(GameTestHelper self, BlockPos pos, @Nullable Direction side, Item item) {
|
||||
var blockEntity = self.getBlockEntity(pos);
|
||||
var handler = blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER, side).orElseThrow(
|
||||
() -> self.throwing("Block at %s has no item handler capability on side %s".formatted(pos, side)));
|
||||
|
||||
int actual = 0;
|
||||
for (int slot = 0; slot < handler.getSlots(); slot++) {
|
||||
var stack = handler.getStackInSlot(slot);
|
||||
if (stack.getItem().equals(item))
|
||||
actual += stack.getCount();
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
||||
default void tickBlock(BlockPos pos) {
|
||||
var blentity = self().getBlockEntity(pos);
|
||||
blentity.getBlockState().tick(self().getLevel(), self().absolutePos(pos), self().getLevel().random);
|
||||
}
|
||||
|
||||
default <T> Flag<T> flag(String name) {
|
||||
return new Flag<>(name);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.world.level.storage.LevelSummary;
|
||||
|
||||
@@ -114,13 +114,13 @@ public class ConcatenatedListView<T> implements List<T>
|
||||
@Override
|
||||
public Iterator<T> iterator()
|
||||
{
|
||||
return Iterables.unmodifiableIterable(Iterables.concat(lists)).iterator();
|
||||
return Iterables.unmodifiableIterable(Iterables.<T>concat(lists)).iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<T> spliterator()
|
||||
{
|
||||
return Iterables.unmodifiableIterable(Iterables.concat(lists)).spliterator();
|
||||
return Iterables.unmodifiableIterable(Iterables.<T>concat(lists)).spliterator();
|
||||
}
|
||||
|
||||
// Delegate to a concatenated collection
|
||||
|
||||
@@ -12,10 +12,12 @@ import net.minecraft.world.level.block.entity.Hopper;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.DispenserBlockEntity;
|
||||
import net.minecraft.world.level.block.entity.HopperBlockEntity;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraftforge.common.capabilities.ForgeCapabilities;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||
@@ -25,169 +27,129 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class VanillaInventoryCodeHooks
|
||||
{
|
||||
//TODO: [Forge][1.21.9][Cleanup] Mark as @ApiStatus.Internal
|
||||
public class VanillaInventoryCodeHooks {
|
||||
/**
|
||||
* Copied from TileEntityHopper#captureDroppedItems and added capability support
|
||||
* Copied from HopperBlockEntity#suckInItems and added capability support
|
||||
* @return Null if we did nothing {no IItemHandler}, True if we moved an item, False if we moved no items
|
||||
*/
|
||||
@Nullable
|
||||
public static Boolean extractHook(Level level, Hopper dest)
|
||||
{
|
||||
return getItemHandler(level, dest, Direction.UP)
|
||||
.map(itemHandlerResult -> {
|
||||
IItemHandler handler = itemHandlerResult.getKey();
|
||||
public static Boolean extractHook(Level level, Hopper dest) {
|
||||
var handler = getItemHandler(level, dest, Direction.UP).map(Pair::getKey).orElse(null);
|
||||
if (handler == null)
|
||||
return null;
|
||||
|
||||
for (int i = 0; i < handler.getSlots(); i++)
|
||||
{
|
||||
ItemStack extractItem = handler.extractItem(i, 1, true);
|
||||
if (!extractItem.isEmpty())
|
||||
{
|
||||
for (int j = 0; j < dest.getContainerSize(); j++)
|
||||
{
|
||||
ItemStack destStack = dest.getItem(j);
|
||||
if (dest.canPlaceItem(j, extractItem) && (destStack.isEmpty() || destStack.getCount() < destStack.getMaxStackSize() && destStack.getCount() < dest.getMaxStackSize() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)))
|
||||
{
|
||||
extractItem = handler.extractItem(i, 1, false);
|
||||
if (destStack.isEmpty())
|
||||
dest.setItem(j, extractItem);
|
||||
else
|
||||
{
|
||||
destStack.grow(1);
|
||||
dest.setItem(j, destStack);
|
||||
}
|
||||
dest.setChanged();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < handler.getSlots(); i++) {
|
||||
ItemStack extractItem = handler.extractItem(i, 1, true);
|
||||
if (!extractItem.isEmpty()) {
|
||||
for (int j = 0; j < dest.getContainerSize(); j++) {
|
||||
ItemStack destStack = dest.getItem(j);
|
||||
if (dest.canPlaceItem(j, extractItem) && (destStack.isEmpty() || destStack.getCount() < destStack.getMaxStackSize() && destStack.getCount() < dest.getMaxStackSize() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack))) {
|
||||
extractItem = handler.extractItem(i, 1, false);
|
||||
if (destStack.isEmpty())
|
||||
dest.setItem(j, extractItem);
|
||||
else {
|
||||
destStack.grow(1);
|
||||
dest.setItem(j, destStack);
|
||||
}
|
||||
dest.setChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.orElse(null); // TODO bad null
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from BlockDropper#dispense and added capability support
|
||||
*/
|
||||
public static boolean dropperInsertHook(Level level, BlockPos pos, DispenserBlockEntity dropper, int slot, @NotNull ItemStack stack)
|
||||
{
|
||||
Direction enumfacing = level.getBlockState(pos).getValue(DropperBlock.FACING);
|
||||
BlockPos blockpos = pos.relative(enumfacing);
|
||||
return getItemHandler(level, (double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), enumfacing.getOpposite())
|
||||
.map(destinationResult -> {
|
||||
IItemHandler itemHandler = destinationResult.getKey();
|
||||
Object destination = destinationResult.getValue();
|
||||
ItemStack dispensedStack = stack.copy().split(1);
|
||||
ItemStack remainder = putStackInInventoryAllSlots(dropper, destination, itemHandler, dispensedStack);
|
||||
|
||||
if (remainder.isEmpty())
|
||||
{
|
||||
remainder = stack.copy();
|
||||
remainder.shrink(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
remainder = stack.copy();
|
||||
}
|
||||
|
||||
dropper.setItem(slot, remainder);
|
||||
return false;
|
||||
})
|
||||
.orElse(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from TileEntityHopper#transferItemsOut and added capability support
|
||||
*/
|
||||
public static boolean insertHook(HopperBlockEntity hopper)
|
||||
{
|
||||
Direction hopperFacing = hopper.getBlockState().getValue(HopperBlock.FACING);
|
||||
return getItemHandler(hopper.getLevel(), hopper, hopperFacing)
|
||||
.map(destinationResult -> {
|
||||
IItemHandler itemHandler = destinationResult.getKey();
|
||||
Object destination = destinationResult.getValue();
|
||||
if (isFull(itemHandler))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < hopper.getContainerSize(); ++i)
|
||||
{
|
||||
if (!hopper.getItem(i).isEmpty())
|
||||
{
|
||||
ItemStack originalSlotContents = hopper.getItem(i).copy();
|
||||
ItemStack insertStack = hopper.removeItem(i, 1);
|
||||
ItemStack remainder = putStackInInventoryAllSlots(hopper, destination, itemHandler, insertStack);
|
||||
|
||||
if (remainder.isEmpty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
hopper.setItem(i, originalSlotContents);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private static ItemStack putStackInInventoryAllSlots(BlockEntity source, Object destination, IItemHandler destInventory, ItemStack stack)
|
||||
{
|
||||
for (int slot = 0; slot < destInventory.getSlots() && !stack.isEmpty(); slot++)
|
||||
{
|
||||
stack = insertStack(source, destination, destInventory, stack, slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from DropperBlock#dispenseFrom and added capability support
|
||||
*/
|
||||
public static boolean dropperInsertHook(Level level, BlockPos pos, DispenserBlockEntity dropper, int slot, @NotNull ItemStack stack) {
|
||||
var direction = level.getBlockState(pos).getValue(DropperBlock.FACING);
|
||||
var handler = getItemHandlerPair(level, pos.relative(direction), direction.getOpposite());
|
||||
if (handler.isEmpty())
|
||||
return true;
|
||||
|
||||
var itemHandler = handler.get().getKey();
|
||||
var destination = handler.get().getValue();
|
||||
|
||||
ItemStack dispensedStack = stack.copy().split(1);
|
||||
ItemStack remainder = putStackInInventoryAllSlots(dropper, destination, itemHandler, dispensedStack);
|
||||
|
||||
if (remainder.isEmpty()) {
|
||||
remainder = stack.copy();
|
||||
remainder.shrink(1);
|
||||
} else
|
||||
remainder = stack.copy();
|
||||
|
||||
dropper.setItem(slot, remainder);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from HopperBlockEntity#ejectItems and added capability support
|
||||
*/
|
||||
public static boolean insertHook(HopperBlockEntity hopper) {
|
||||
var handler = getItemHandler(hopper.getLevel(), hopper, hopper.getBlockState().getValue(HopperBlock.FACING));
|
||||
if (handler.isEmpty())
|
||||
return false;
|
||||
|
||||
var itemHandler = handler.get().getKey();
|
||||
var destination = handler.get().getValue();
|
||||
|
||||
if (isFull(itemHandler))
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < hopper.getContainerSize(); ++i) {
|
||||
if (!hopper.getItem(i).isEmpty()) {
|
||||
ItemStack originalSlotContents = hopper.getItem(i).copy();
|
||||
ItemStack insertStack = hopper.removeItem(i, 1);
|
||||
ItemStack remainder = putStackInInventoryAllSlots(hopper, destination, itemHandler, insertStack);
|
||||
|
||||
if (remainder.isEmpty())
|
||||
return true;
|
||||
|
||||
hopper.setItem(i, originalSlotContents);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ItemStack putStackInInventoryAllSlots(BlockEntity source, Object destination, IItemHandler destInventory, ItemStack stack) {
|
||||
for (int slot = 0; slot < destInventory.getSlots() && !stack.isEmpty(); slot++)
|
||||
stack = insertStack(source, destination, destInventory, stack, slot);
|
||||
return stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from TileEntityHopper#insertStack and added capability support
|
||||
* Copied from HopperBlockEntity#tryMoveInItem and added capability support
|
||||
*/
|
||||
private static ItemStack insertStack(BlockEntity source, Object destination, IItemHandler destInventory, ItemStack stack, int slot)
|
||||
{
|
||||
private static ItemStack insertStack(BlockEntity source, Object destination, IItemHandler destInventory, ItemStack stack, int slot) {
|
||||
ItemStack itemstack = destInventory.getStackInSlot(slot);
|
||||
|
||||
if (destInventory.insertItem(slot, stack, true).isEmpty())
|
||||
{
|
||||
if (destInventory.insertItem(slot, stack, true).isEmpty()) {
|
||||
boolean insertedItem = false;
|
||||
boolean inventoryWasEmpty = isEmpty(destInventory);
|
||||
|
||||
if (itemstack.isEmpty())
|
||||
{
|
||||
if (itemstack.isEmpty()) {
|
||||
destInventory.insertItem(slot, stack, false);
|
||||
stack = ItemStack.EMPTY;
|
||||
insertedItem = true;
|
||||
}
|
||||
else if (ItemHandlerHelper.canItemStacksStack(itemstack, stack))
|
||||
{
|
||||
} else if (ItemHandlerHelper.canItemStacksStack(itemstack, stack)) {
|
||||
int originalSize = stack.getCount();
|
||||
stack = destInventory.insertItem(slot, stack, false);
|
||||
insertedItem = originalSize < stack.getCount();
|
||||
}
|
||||
|
||||
if (insertedItem)
|
||||
{
|
||||
if (inventoryWasEmpty && destination instanceof HopperBlockEntity)
|
||||
{
|
||||
HopperBlockEntity destinationHopper = (HopperBlockEntity)destination;
|
||||
|
||||
if (!destinationHopper.isOnCustomCooldown())
|
||||
{
|
||||
if (insertedItem) {
|
||||
if (inventoryWasEmpty && destination instanceof HopperBlockEntity dHopper) {
|
||||
if (!dHopper.isOnCustomCooldown()) {
|
||||
int k = 0;
|
||||
if (source instanceof HopperBlockEntity)
|
||||
{
|
||||
if (destinationHopper.getLastUpdateTime() >= ((HopperBlockEntity) source).getLastUpdateTime())
|
||||
{
|
||||
k = 1;
|
||||
}
|
||||
}
|
||||
destinationHopper.setCooldown(8 - k);
|
||||
if (source instanceof HopperBlockEntity sHopper && dHopper.getLastUpdateTime() >= sHopper.getLastUpdateTime())
|
||||
k = 1;
|
||||
dHopper.setCooldown(8 - k);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,53 +158,90 @@ public class VanillaInventoryCodeHooks
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static Optional<Pair<IItemHandler, Object>> getItemHandler(Level level, Hopper hopper, Direction hopperFacing)
|
||||
{
|
||||
private static Optional<Pair<IItemHandler, Object>> getItemHandler(Level level, Hopper hopper, Direction hopperFacing) {
|
||||
double x = hopper.getLevelX() + (double) hopperFacing.getStepX();
|
||||
double y = hopper.getLevelY() + (double) hopperFacing.getStepY();
|
||||
double z = hopper.getLevelZ() + (double) hopperFacing.getStepZ();
|
||||
return getItemHandler(level, x, y, z, hopperFacing.getOpposite());
|
||||
}
|
||||
|
||||
private static boolean isFull(IItemHandler itemHandler)
|
||||
{
|
||||
for (int slot = 0; slot < itemHandler.getSlots(); slot++)
|
||||
{
|
||||
private static boolean isFull(IItemHandler itemHandler) {
|
||||
for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
|
||||
ItemStack stackInSlot = itemHandler.getStackInSlot(slot);
|
||||
if (stackInSlot.isEmpty() || stackInSlot.getCount() < itemHandler.getSlotLimit(slot))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isEmpty(IItemHandler itemHandler)
|
||||
{
|
||||
for (int slot = 0; slot < itemHandler.getSlots(); slot++)
|
||||
{
|
||||
private static boolean isEmpty(IItemHandler itemHandler) {
|
||||
for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
|
||||
ItemStack stackInSlot = itemHandler.getStackInSlot(slot);
|
||||
if (stackInSlot.getCount() > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Optional<Pair<IItemHandler, Object>> getItemHandler(Level worldIn, double x, double y, double z, final Direction side)
|
||||
{
|
||||
/**
|
||||
* Gets the IItemHandler at the given position, checking for both BlockEntities
|
||||
* and Entities. If both are present, the BlockEntity is preferred.
|
||||
*
|
||||
* This is equivalent to HopperBlockEntity#getContainerAt
|
||||
*
|
||||
* @param level The level to check
|
||||
* @param pos The position to check
|
||||
* @param side The side to check from. Can be null.
|
||||
* @return An IItemHandler and the object it was obtained from, or an empty
|
||||
* Optional if none was found.
|
||||
*/
|
||||
public static Optional<IItemHandler> getItemHandler(Level level, BlockPos pos, @Nullable Direction side) {
|
||||
var handler = getItemHandlerBlock(level, pos, side);
|
||||
if (!handler.isPresent())
|
||||
handler = getItemHandlerEntity(level, pos, side);
|
||||
return handler;
|
||||
}
|
||||
|
||||
public static Optional<IItemHandler> getItemHandlerEntity(Level level, BlockPos pos, @Nullable Direction side) {
|
||||
var entities = level.getEntities((Entity)null, new AABB(pos), e -> e.getCapability(ForgeCapabilities.ITEM_HANDLER, side).isPresent());
|
||||
|
||||
if (entities.isEmpty())
|
||||
return Optional.empty();
|
||||
|
||||
var rand = level.random.nextInt(entities.size());
|
||||
var entity = entities.get(rand);
|
||||
return entity.getCapability(ForgeCapabilities.ITEM_HANDLER, side).resolve();
|
||||
}
|
||||
|
||||
public static Optional<IItemHandler> getItemHandlerBlock(Level level, BlockPos pos, @Nullable Direction side) {
|
||||
if (!level.getBlockState(pos).hasBlockEntity())
|
||||
return Optional.empty();
|
||||
|
||||
var entity = level.getBlockEntity(pos);
|
||||
if (entity == null)
|
||||
return Optional.empty();
|
||||
|
||||
return entity.getCapability(ForgeCapabilities.ITEM_HANDLER, side).resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* I don't think anyone should be using this. If they are they probably want the non-pair version.
|
||||
* As the only use for knowing the object holding the IItemHandler is for hopper cooldowns
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "1.21.8")
|
||||
public static Optional<Pair<IItemHandler, Object>> getItemHandler(Level worldIn, double x, double y, double z, final Direction side) {
|
||||
int i = Mth.floor(x);
|
||||
int j = Mth.floor(y);
|
||||
int k = Mth.floor(z);
|
||||
BlockPos blockpos = new BlockPos(i, j, k);
|
||||
net.minecraft.world.level.block.state.BlockState state = worldIn.getBlockState(blockpos);
|
||||
return getItemHandlerPair(worldIn, new BlockPos(i, j, k), side);
|
||||
}
|
||||
|
||||
if (state.hasBlockEntity())
|
||||
{
|
||||
BlockEntity blockEntity = worldIn.getBlockEntity(blockpos);
|
||||
if (blockEntity != null)
|
||||
{
|
||||
private static Optional<Pair<IItemHandler, Object>> getItemHandlerPair(Level level, BlockPos pos, Direction side) {
|
||||
var state = level.getBlockState(pos);
|
||||
|
||||
if (state.hasBlockEntity()) {
|
||||
BlockEntity blockEntity = level.getBlockEntity(pos);
|
||||
if (blockEntity != null) {
|
||||
return blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER, side)
|
||||
.map(capability -> ImmutablePair.<IItemHandler, Object>of(capability, blockEntity));
|
||||
}
|
||||
|
||||
@@ -9,9 +9,11 @@ import com.mojang.logging.LogUtils;
|
||||
import net.minecraft.ResourceLocationException;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.ForgeConfig;
|
||||
import net.minecraftforge.event.ForgeEventFactory;
|
||||
import net.minecraftforge.event.network.ChannelRegistrationChangeEvent;
|
||||
import net.minecraftforge.event.network.CustomPayloadEvent;
|
||||
@@ -26,6 +28,7 @@ import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApiStatus.Internal // TODO: Decide what I want to have public, Right now it should just be add/remove channels.
|
||||
public class ChannelListManager {
|
||||
@@ -70,7 +73,7 @@ public class ChannelListManager {
|
||||
}
|
||||
|
||||
private static void register(Register payload, CustomPayloadEvent.Context ctx) {
|
||||
updateFrom(ctx, payload.channels(), ChannelRegistrationChangeEvent.Type.REGISTER);
|
||||
updateFrom(ctx, payload.channels(), ChannelRegistrationChangeEvent.Type.REGISTER, ctx.isClientSide());
|
||||
ctx.setPacketHandled(true);
|
||||
// Send the client's channels to the server whenever asked. If we're in the login state then our login wrapper will unwrap for us.
|
||||
if (ctx.isClientSide())
|
||||
@@ -78,7 +81,7 @@ public class ChannelListManager {
|
||||
}
|
||||
|
||||
private static void unregister(Unregister payload, CustomPayloadEvent.Context ctx) {
|
||||
updateFrom(ctx, payload.channels(), ChannelRegistrationChangeEvent.Type.UNREGISTER);
|
||||
updateFrom(ctx, payload.channels(), ChannelRegistrationChangeEvent.Type.UNREGISTER, ctx.isClientSide());
|
||||
ctx.setPacketHandled(true);
|
||||
}
|
||||
|
||||
@@ -145,7 +148,7 @@ public class ChannelListManager {
|
||||
return Collections.unmodifiableList(channels);
|
||||
}
|
||||
|
||||
private static void updateFrom(CustomPayloadEvent.Context source, List<String> channels, final ChannelRegistrationChangeEvent.Type changeType) {
|
||||
private static void updateFrom(CustomPayloadEvent.Context source, List<String> channels, final ChannelRegistrationChangeEvent.Type changeType, boolean isClient) {
|
||||
var changed = new HashSet<ResourceLocation>();
|
||||
for (var channel : channels) {
|
||||
// It also says nothing about the format of channels so ignore bad channels.
|
||||
@@ -162,11 +165,20 @@ public class ChannelListManager {
|
||||
|
||||
ForgeEventFactory.onChannelRegistrationChange(source.getConnection(), changeType, changed);
|
||||
|
||||
// It is a known issue, that I don't really care about, that we don't get the true in-memory size of each channel due to character encoding.
|
||||
// A sane limit of 1KB will be enough to catch any malicious actors even with non-8-bit strings.
|
||||
var list = NetworkContext.get(source.getConnection());
|
||||
for (var channel : changed) {
|
||||
boolean fire = changeType == ChannelRegistrationChangeEvent.Type.UNREGISTER
|
||||
? list.remoteChannels.remove(channel)
|
||||
: list.remoteChannels.add(channel);
|
||||
boolean fire = false;
|
||||
if (changeType == ChannelRegistrationChangeEvent.Type.UNREGISTER) {
|
||||
fire = list.remoteChannels.remove(channel);
|
||||
if (fire)
|
||||
list.remoteChannelsSize -= channel.toString().length();
|
||||
} else {
|
||||
fire = list.remoteChannels.add(channel);
|
||||
if (fire)
|
||||
list.remoteChannelsSize += channel.toString().length();
|
||||
}
|
||||
|
||||
if (fire) {
|
||||
var target = NetworkRegistry.findTarget(channel);
|
||||
@@ -174,5 +186,21 @@ public class ChannelListManager {
|
||||
target.registrationChange(channel, changeType == ChannelRegistrationChangeEvent.Type.REGISTER);
|
||||
}
|
||||
}
|
||||
|
||||
if (list.remoteChannelsSize >= NetworkRegistry.getChannelMemorySize() && list.remoteChannelsSize >= ForgeConfig.COMMON.channelListLimit.get()) {
|
||||
LOGGER.warn("Received too many network channels, {} channels using {} bytes, Limit is currently {}, to change edit the Forge {} in config\forge_common.toml",
|
||||
list.remoteChannels.size(), list.remoteChannelsSize, ForgeConfig.COMMON.channelListLimit.get(), ForgeConfig.COMMON.channelListLimit.getPath().stream().collect(Collectors.joining("."))
|
||||
);
|
||||
|
||||
if (isClient) {
|
||||
// We don't want to allow the server to screw with us, so just remove the added channels
|
||||
for (var channel : changed) {
|
||||
if (list.remoteChannels.remove(channel))
|
||||
list.remoteChannelsSize -= channel.toString().length();
|
||||
}
|
||||
} else {
|
||||
source.getSender().connection.disconnect(Component.translatable("forge.server.channellistlimit.kick"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,8 @@ public class NetworkContext {
|
||||
|
||||
@ApiStatus.Internal
|
||||
Set<ResourceLocation> remoteChannels = new HashSet<>();
|
||||
@ApiStatus.Internal
|
||||
long remoteChannelsSize = 0;
|
||||
private Set<ResourceLocation> remoteChannelsView = Collections.unmodifiableSet(this.remoteChannels);
|
||||
|
||||
@ApiStatus.Internal
|
||||
|
||||
@@ -43,6 +43,7 @@ public class NetworkRegistry {
|
||||
|
||||
private static Map<ResourceLocation, NetworkInstance> instances = Collections.synchronizedMap(new HashMap<>());
|
||||
private static Map<ResourceLocation, NetworkInstance> byName = Collections.synchronizedMap(new HashMap<>());
|
||||
private static long memorySize = 0;
|
||||
|
||||
public static boolean acceptsVanillaClientConnections() {
|
||||
return listRejectedVanillaMods(n -> n.clientAcceptedVersions).isEmpty() && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty();
|
||||
@@ -199,9 +200,14 @@ public class NetworkRegistry {
|
||||
if (NetworkRegistry.byName.containsKey(name))
|
||||
error("Payload name " + name + " already registered.");
|
||||
|
||||
memorySize += name.toString().length(); // This can fail if people don't use our api. So this is a best effort.
|
||||
byName.put(name, instance);
|
||||
}
|
||||
|
||||
static long getChannelMemorySize() {
|
||||
return memorySize;
|
||||
}
|
||||
|
||||
static void register(NetworkInstance instance) {
|
||||
checkLock(instance);
|
||||
|
||||
|
||||
@@ -351,7 +351,7 @@ public class GameData {
|
||||
if (forgeRegistry != null)
|
||||
forgeRegistry.freeze();
|
||||
LOGGER.debug(REGISTRIES, "Applying holder lookups: {}", registryKey.location());
|
||||
ObjectHolderRegistry.applyObjectHolders(registryKey.location()::equals);
|
||||
ObjectHolderRegistry.applyObjectHolders(registryKey.location());
|
||||
LOGGER.debug(REGISTRIES, "Holder lookups applied: {}", registryKey.location());
|
||||
} catch (Throwable t) {
|
||||
aggregate.addSuppressed(t);
|
||||
|
||||
@@ -19,7 +19,7 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
class ObjectHolderRef implements Consumer<Predicate<ResourceLocation>>
|
||||
class ObjectHolderRef implements Consumer<Predicate<ResourceLocation>>, Runnable
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final Field field;
|
||||
@@ -87,7 +87,12 @@ class ObjectHolderRef implements Consumer<Predicate<ResourceLocation>>
|
||||
{
|
||||
if (registry == null || !filter.test(registry.getRegistryName()))
|
||||
return;
|
||||
run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
Object thing;
|
||||
if (registry.containsKey(injectedObject))
|
||||
{
|
||||
|
||||
@@ -7,10 +7,11 @@ package net.minecraftforge.registries;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
@@ -40,12 +41,24 @@ public class ObjectHolderRegistry
|
||||
* The internal list is backed by a HashSet so it is HIGHLY recommended you implement a proper equals
|
||||
* and hashCode function to de-duplicate callers here.
|
||||
* The default @ObjectHolder implementation uses the hashCode/equals for the field the annotation is on.
|
||||
*
|
||||
* @deprecated Use {{@link #addHandler(ResourceLocation, Runnable)} if you are only targeting a single registry
|
||||
*/
|
||||
public static synchronized void addHandler(Consumer<Predicate<ResourceLocation>> ref)
|
||||
{
|
||||
objectHolders.add(ref);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Registers a handler that is run after the named registry has been injected and finalized.
|
||||
* Handlers are kept in a HashSet per registry, so the same instance is only ever registered once.
|
||||
*/
|
||||
public static synchronized void addHandler(ResourceLocation registry, Runnable ref)
|
||||
{
|
||||
namedHandlers.computeIfAbsent(registry, id -> new HashSet<>()).add(ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removed the specified handler from the notification list.
|
||||
*
|
||||
@@ -60,12 +73,36 @@ public class ObjectHolderRegistry
|
||||
return objectHolders.remove(ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a handler registered with {@link #addHandler(ResourceLocation, Runnable)}.
|
||||
*
|
||||
* @return true if handler was matched and removed.
|
||||
*/
|
||||
public static synchronized boolean removeHandler(ResourceLocation registry, Runnable ref)
|
||||
{
|
||||
var handlers = namedHandlers.get(registry);
|
||||
return handlers != null && handlers.remove(ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a check that is run once, before the handlers of the next holder pass.
|
||||
* Used to report holders that point at a registry that does not exist.
|
||||
*/
|
||||
public static synchronized void addValidator(Runnable ref)
|
||||
{
|
||||
validators.add(ref);
|
||||
}
|
||||
|
||||
//==============================================================
|
||||
// Everything below is internal, do not use.
|
||||
//==============================================================
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Set<Consumer<Predicate<ResourceLocation>>> objectHolders = new HashSet<>();
|
||||
// Order is not guaranteed, the old implementation kept every handler in one HashSet.
|
||||
private static final Map<ResourceLocation, Set<Runnable>> namedHandlers = new HashMap<>();
|
||||
private static final List<Runnable> validators = new ArrayList<>();
|
||||
|
||||
private static final Type OBJECT_HOLDER = Type.getType(ObjectHolder.class);
|
||||
private static final Type MOD = Type.getType(Mod.class);
|
||||
// Hardcoded list of vanilla classes that should have object holders for each field of the given registry type.
|
||||
@@ -83,48 +120,59 @@ public class ObjectHolderRegistry
|
||||
public static void findObjectHolders()
|
||||
{
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES,"Processing ObjectHolder annotations");
|
||||
final List<ModFileScanData.AnnotationData> annotations = ModList.get().getAllScanData().stream()
|
||||
.map(ModFileScanData::getAnnotations)
|
||||
.flatMap(Collection::stream)
|
||||
.filter(a -> OBJECT_HOLDER.equals(a.annotationType()) || MOD.equals(a.annotationType()))
|
||||
.toList();
|
||||
final HashMap<Type, String> classModIds = new HashMap<>();
|
||||
final List<ModFileScanData.AnnotationData> annotations = new ArrayList<>();
|
||||
|
||||
if (annotations.stream().noneMatch(a -> OBJECT_HOLDER.equals(a.annotationType())))
|
||||
return; // No object holders found, skip the rest of the processing
|
||||
for (var data : ModList.get().getAllScanData()) {
|
||||
for (var annotation : data.getAnnotations()) {
|
||||
if (OBJECT_HOLDER.equals(annotation.annotationType())) {
|
||||
annotations.add(annotation);
|
||||
}
|
||||
// Gather all @Mod classes so that @ObjectHolder's in those classes don't need to specify the mod id; modder convenience
|
||||
else if (MOD.equals(annotation.annotationType())) {
|
||||
classModIds.put(annotation.clazz(), (String)annotation.annotationData().get("value"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// In theory when a mod is installed, we want to make sure we can update vanilla fields that are overriden by mods.
|
||||
// However, due to Mojang registry changes, and this code being old and having an oversight, this short circuit is expected behavior
|
||||
// So Lets just ignore the potential pitfalls for if they ever come up.
|
||||
if (annotations.isEmpty()) {
|
||||
return; // No object holders found, skip the rest of the processing,
|
||||
}
|
||||
|
||||
Map<Type, String> classModIds = Maps.newHashMap();
|
||||
Map<Type, Class<?>> classCache = Maps.newHashMap();
|
||||
|
||||
// Gather all @Mod classes so that @ObjectHolder's in those classes don't need to specify the mod id; modder convenience
|
||||
annotations.stream()
|
||||
.filter(a -> MOD.equals(a.annotationType()))
|
||||
.forEach(data -> classModIds.put(data.clazz(), (String)data.annotationData().get("value")));
|
||||
|
||||
// Validate all the vanilla class-level object holders then scan those first
|
||||
VANILLA_OBJECT_HOLDERS.forEach(data -> {
|
||||
try
|
||||
{
|
||||
for (var data : VANILLA_OBJECT_HOLDERS) {
|
||||
try {
|
||||
Class<?> holderClass = Class.forName(data.holderClass(), true, ObjectHolderRegistry.class.getClassLoader());
|
||||
Class<?> registryClass = Class.forName(data.registryType(), true, ObjectHolderRegistry.class.getClassLoader());
|
||||
|
||||
Type holderType = Type.getType(holderClass);
|
||||
classCache.put(holderType, holderClass);
|
||||
scanTarget(classModIds, classCache, holderType, null, registryClass, data.registryName(), "minecraft", true, true);
|
||||
}
|
||||
catch (ClassNotFoundException e)
|
||||
{
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("Vanilla class not found, should not be possible", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Scan actual fields annotated with @ObjectHolder second
|
||||
annotations.stream()
|
||||
.filter(a -> OBJECT_HOLDER.equals(a.annotationType())).filter(a -> a.targetType() == ElementType.FIELD)
|
||||
.forEach(data -> scanTarget(classModIds, classCache, data.clazz(),
|
||||
data.memberName(), null, (String)data.annotationData().get("registryName"),
|
||||
(String)data.annotationData().get("value"), false, false));
|
||||
for (var data : annotations) {
|
||||
if (data.targetType() == ElementType.FIELD) {
|
||||
var registry = (String)data.annotationData().get("registryName");
|
||||
var name = (String)data.annotationData().get("value");
|
||||
scanTarget(classModIds, classCache, data.clazz(), data.memberName(), null, registry, name, false, false);
|
||||
}
|
||||
// This is where we WOULD scan for class targets, but Shrimp broke that in 1.19 and so I don't want to re-add a feature that apparently nobody used.
|
||||
}
|
||||
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES,"Found {} ObjectHolder annotations", objectHolders.size());
|
||||
int count = objectHolders.size();
|
||||
for (var set : namedHandlers.values())
|
||||
count += set.size();
|
||||
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES, "Found {} ObjectHolder annotations", count);
|
||||
}
|
||||
|
||||
private static void scanTarget(Map<Type, String> classModIds, Map<Type, Class<?>> classCache, Type type,
|
||||
@@ -149,9 +197,10 @@ public class ObjectHolderRegistry
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
ResourceLocation regName = ResourceLocation.parse(registryName);
|
||||
if (isClass)
|
||||
{
|
||||
scanClassForFields(classModIds, type, ResourceLocation.parse(registryName), registryClass, value, clazz, extractFromValue);
|
||||
scanClassForFields(classModIds, type, regName, registryClass, value, clazz, extractFromValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -168,9 +217,9 @@ public class ObjectHolderRegistry
|
||||
try
|
||||
{
|
||||
Field f = clazz.getDeclaredField(annotationTarget);
|
||||
ObjectHolderRef ref = ObjectHolderRef.create(ResourceLocation.parse(registryName), f, value, extractFromValue);
|
||||
ObjectHolderRef ref = ObjectHolderRef.create(regName, f, value, extractFromValue);
|
||||
if (ref != null)
|
||||
addHandler(ref);
|
||||
addHandler(regName, ref);
|
||||
}
|
||||
catch (NoSuchFieldException ex)
|
||||
{
|
||||
@@ -191,7 +240,7 @@ public class ObjectHolderRegistry
|
||||
continue;
|
||||
ObjectHolderRef ref = ObjectHolderRef.create(registryName, f, value + ':' + f.getName().toLowerCase(Locale.ENGLISH), extractFromExistingValues);
|
||||
if (ref != null)
|
||||
addHandler(ref);
|
||||
addHandler(registryName, ref);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,35 +256,115 @@ public class ObjectHolderRegistry
|
||||
throw new IllegalStateException("No registry name was declared for " + declaration);
|
||||
}
|
||||
|
||||
public static void applyObjectHolders()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
private static final Predicate<ResourceLocation> ALWAYS_TRUE = name -> true;
|
||||
public static void applyObjectHolders() {
|
||||
try {
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES, "Applying holder lookups");
|
||||
applyObjectHolders(key -> true);
|
||||
var exceptions = new ArrayList<Exception>();
|
||||
validate(exceptions);
|
||||
// Call named registries
|
||||
for (var handlers : namedHandlers.values())
|
||||
apply(handlers, exceptions);
|
||||
|
||||
// Call legacy for backward compatibility
|
||||
if (!objectHolders.isEmpty())
|
||||
apply(ALWAYS_TRUE, objectHolders, exceptions);
|
||||
|
||||
throwIfNeeded(exceptions);
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES, "Holder lookups applied");
|
||||
} catch (RuntimeException e)
|
||||
{
|
||||
} catch (RuntimeException e) {
|
||||
// It is more important that the calling contexts continue without exception to prevent further cascading errors
|
||||
LOGGER.error("", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use {@link #applyObjectHolders(ResourceLocation)}
|
||||
*/
|
||||
public static void applyObjectHolders(Predicate<ResourceLocation> filter)
|
||||
{
|
||||
RuntimeException aggregate = new RuntimeException("Failed to apply some object holders, see suppressed exceptions for details");
|
||||
for (Consumer<Predicate<ResourceLocation>> objectHolder : objectHolders) {
|
||||
try {
|
||||
objectHolder.accept(filter);
|
||||
} catch (Exception e) {
|
||||
aggregate.addSuppressed(e);
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES, "Apply filtered holder lookups");
|
||||
var exceptions = new ArrayList<Exception>();
|
||||
validate(exceptions);
|
||||
|
||||
// call new registries if needed
|
||||
for (var entry : namedHandlers.entrySet()) {
|
||||
if (filter.test(entry.getKey())) {
|
||||
apply(entry.getValue(), exceptions);
|
||||
}
|
||||
}
|
||||
|
||||
if (aggregate.getSuppressed().length > 0)
|
||||
{
|
||||
throw aggregate;
|
||||
// Call legacy
|
||||
if (!objectHolders.isEmpty())
|
||||
apply(filter, objectHolders, exceptions);
|
||||
|
||||
throwIfNeeded(exceptions);
|
||||
LOGGER.debug(ForgeRegistry.REGISTRIES, "Holder lookups applied");
|
||||
}
|
||||
|
||||
/** Runs the handlers of one registry. */
|
||||
public static void applyObjectHolders(ResourceLocation registry) {
|
||||
var exceptions = new ArrayList<Exception>();
|
||||
validate(exceptions);
|
||||
|
||||
var handlers = namedHandlers.get(registry);
|
||||
if (handlers != null)
|
||||
apply(handlers, exceptions);
|
||||
|
||||
if (!objectHolders.isEmpty())
|
||||
apply(registry::equals, objectHolders, exceptions);
|
||||
|
||||
throwIfNeeded(exceptions);
|
||||
}
|
||||
|
||||
// Each validator runs once, at the first holder pass after it was registered.
|
||||
private static void validate(List<Exception> exceptions) {
|
||||
List<Runnable> pending;
|
||||
synchronized (ObjectHolderRegistry.class) {
|
||||
if (validators.isEmpty())
|
||||
return;
|
||||
pending = new ArrayList<>(validators);
|
||||
validators.clear();
|
||||
}
|
||||
|
||||
for (var validator : pending) {
|
||||
try {
|
||||
validator.run();
|
||||
} catch (Exception e) {
|
||||
exceptions.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void apply(Set<Runnable> handlers, List<Exception> exceptions) {
|
||||
for (var handler : handlers) {
|
||||
try {
|
||||
handler.run();
|
||||
} catch (Exception e) {
|
||||
exceptions.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void apply(Predicate<ResourceLocation> filter, Set<Consumer<Predicate<ResourceLocation>>> handlers, List<Exception> exceptions) {
|
||||
for (var handler : handlers) {
|
||||
try {
|
||||
handler.accept(filter);
|
||||
} catch (Exception e) {
|
||||
exceptions.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void throwIfNeeded(List<Exception> exceptions) {
|
||||
if (exceptions.isEmpty())
|
||||
return;
|
||||
|
||||
var aggregate = new RuntimeException("Failed to apply some object holders, see suppressed exceptions for details");
|
||||
for (var e : exceptions)
|
||||
aggregate.addSuppressed(e);
|
||||
throw aggregate;
|
||||
}
|
||||
|
||||
private record VanillaObjectHolderData(String holderClass, String registryName, String registryType) {}
|
||||
|
||||
@@ -27,7 +27,6 @@ public final class RegistryObject<T> implements Supplier<T> {
|
||||
private final ResourceLocation name;
|
||||
@Nullable
|
||||
private final ResourceKey<T> key;
|
||||
private final boolean optionalRegistry;
|
||||
@Nullable
|
||||
private T value;
|
||||
@Nullable
|
||||
@@ -129,7 +128,6 @@ public final class RegistryObject<T> implements Supplier<T> {
|
||||
private RegistryObject() {
|
||||
this.name = null;
|
||||
this.key = null;
|
||||
this.optionalRegistry = false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -138,40 +136,21 @@ public final class RegistryObject<T> implements Supplier<T> {
|
||||
throw new IllegalArgumentException("Invalid registry argument, must not be null");
|
||||
this.name = name;
|
||||
this.key = (ResourceKey<T>) ResourceKey.create(registry.getRegistryKey(), name);
|
||||
this.optionalRegistry = false;
|
||||
ObjectHolderRegistry.addHandler(pred -> {
|
||||
if (pred.test(registry.getRegistryName()))
|
||||
this.updateReference((IForgeRegistry<? extends T>) registry);
|
||||
});
|
||||
ObjectHolderRegistry.addHandler(registry.getRegistryName(), () -> this.updateReference((IForgeRegistry<? extends T>) registry));
|
||||
this.updateReference((IForgeRegistry<? extends T>) registry);
|
||||
}
|
||||
|
||||
private RegistryObject(final ResourceLocation name, final ResourceLocation registryName, final String modid, boolean optionalRegistry) {
|
||||
this.name = name;
|
||||
this.key = ResourceKey.create(ResourceKey.createRegistryKey(registryName), name);
|
||||
this.optionalRegistry = optionalRegistry;
|
||||
final Throwable callerStack = new Throwable("Calling Site from mod: " + modid);
|
||||
ObjectHolderRegistry.addHandler(new Consumer<>() {
|
||||
private boolean registryExists = false;
|
||||
private boolean invalidRegistry = false;
|
||||
|
||||
@Override
|
||||
public void accept(Predicate<ResourceLocation> pred) {
|
||||
if (invalidRegistry)
|
||||
return;
|
||||
|
||||
if (!RegistryObject.this.optionalRegistry && !registryExists) {
|
||||
if (!registryExists(registryName)) {
|
||||
invalidRegistry = true;
|
||||
throw new IllegalStateException("Unable to find registry with key " + registryName + " for mod \"" + modid + "\". Check the 'caused by' to see further stack.", callerStack);
|
||||
}
|
||||
registryExists = true;
|
||||
}
|
||||
|
||||
if (pred.test(registryName))
|
||||
RegistryObject.this.updateReference(registryName);
|
||||
}
|
||||
});
|
||||
if (!optionalRegistry) {
|
||||
final Throwable callerStack = new Throwable("Calling Site from mod: " + modid);
|
||||
ObjectHolderRegistry.addValidator(() -> {
|
||||
if (!registryExists(registryName))
|
||||
throw new IllegalStateException("Unable to find registry with key " + registryName + " for mod \"" + modid + "\". Check the 'caused by' to see further stack.", callerStack);
|
||||
});
|
||||
}
|
||||
ObjectHolderRegistry.addHandler(registryName, () -> this.updateReference(registryName));
|
||||
this.updateReference(registryName);
|
||||
}
|
||||
|
||||
@@ -467,8 +446,8 @@ public final class RegistryObject<T> implements Supplier<T> {
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (obj instanceof RegistryObject o) {
|
||||
return Objects.equals(o.name, name);
|
||||
if (obj instanceof RegistryObject<?> o) {
|
||||
return o.key == key && Objects.equals(o.name, name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -200,6 +200,10 @@
|
||||
"forge.configgui.stabilizeDirectionGetNearest": "Stabilize Direction Get Nearest",
|
||||
"forge.configgui.stabilizeDirectionGetNearest.tooltip": "When enabled, a slightly biased Direction#getNearest calculation will be used to prevent normal fighting on 45 degree angle faces.",
|
||||
|
||||
"forge.configgui.channellistlimit": "Channel List Size Limit",
|
||||
"forge.configgui.channellistlimit.tooltip": "Maximum size to use to store the channel list for a network connection. Some malicious actors may use this to use up all your memory. A sane default is 1KB (1024), but may need to be expanded for larger modpacks.",
|
||||
"forge.server.channellistlimit.kick": "Received too many networking channels",
|
||||
|
||||
"forge.controlsgui.shift": "SHIFT + %s",
|
||||
"forge.controlsgui.control": "CTRL + %s",
|
||||
"forge.controlsgui.control.mac": "CMD + %s",
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.client.gui.LayeredDraw;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.client.event.AddGuiOverlayLayersEvent;
|
||||
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
|
||||
import net.minecraftforge.common.extensions.IForgeGameTestHelper;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraftforge.gametest.GameTestHolder;
|
||||
import net.minecraftforge.test.BaseTestMod;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import static net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.*;
|
||||
|
||||
|
||||
@Mod(ModifyOverlayTest.MODID)
|
||||
@GameTestHolder("forge." + ModifyOverlayTest.MODID)
|
||||
public class ModifyOverlayTest extends BaseTestMod {
|
||||
public static final String MODID = "modify_overlay_test";
|
||||
|
||||
private static final ResourceLocation myStackName = name("my_stack_name");
|
||||
private static final ForgeLayeredDraw myLayerStack = new ForgeLayeredDraw(myStackName);
|
||||
|
||||
private static final Layer notAddedLayer = (gg,tr) -> {};
|
||||
private static final Layer layerA = (gg,tr) -> {};
|
||||
private static final ResourceLocation layerAName = name("layer_a");
|
||||
private static final Layer layerB = (gg,tr) -> {};
|
||||
private static final ResourceLocation layerBName = name("layer_b");
|
||||
private static final Layer layerC = (gg,tr) -> {};
|
||||
private static final ResourceLocation layerCName = name("layer_c");
|
||||
|
||||
|
||||
private static final IForgeGameTestHelper.BoolFlag detectConditionFlag = new IForgeGameTestHelper.BoolFlag("det_cond_flag");
|
||||
private static final IForgeGameTestHelper.BoolFlag detectConditionStackFlag = new IForgeGameTestHelper.BoolFlag("det_cond_stack_flag");
|
||||
private static final IForgeGameTestHelper.BoolFlag enableConditionFlag = new IForgeGameTestHelper.BoolFlag("en_cond_flag");
|
||||
private static final IForgeGameTestHelper.BoolFlag enableConditionStackFlag = new IForgeGameTestHelper.BoolFlag("en_cond_stack_flag");
|
||||
|
||||
private static ForgeLayeredDraw drawStack;
|
||||
|
||||
public ModifyOverlayTest(FMLJavaModLoadingContext context) {
|
||||
super(context);
|
||||
context.getModEventBus().addListener(this::overlayTestListener);
|
||||
}
|
||||
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void not_present_in_stack(GameTestHelper helper) {
|
||||
// Test that we can't order against non-existent layers.
|
||||
List<Layer> internalLayersList = null;
|
||||
try {
|
||||
internalLayersList = getInternalLayersList(drawStack);
|
||||
} catch (Exception e) {
|
||||
helper.fail("Threw a " + e.getMessage() + " when trying to get the inner layer list.");
|
||||
}
|
||||
helper.assertFalse(internalLayersList.contains(notAddedLayer), "Found our layer when we shouldn't have. Not good!");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void add_condition(GameTestHelper helper) {
|
||||
// Test that we can add conditions to pre-existing layers.
|
||||
helper.assertFalse(detectConditionFlag.getBool(), "Conditional rendering ran when it shouldn't have.");
|
||||
enableConditionFlag.set(true);
|
||||
helper.runAfterDelay(5, () -> {
|
||||
boolean result = detectConditionFlag.getBool();// Just in case of weird race conditions.
|
||||
enableConditionFlag.set(false);
|
||||
helper.assertTrue(result, "");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void ordered_layers(GameTestHelper helper) {
|
||||
// Test that layers are in the correct order.
|
||||
List<Layer> internalLayersList = null;
|
||||
Map<ResourceLocation, Layer> check = null;
|
||||
try {
|
||||
Class<?> cls = drawStack.getClass();
|
||||
var field = cls.getDeclaredField("subLayerStacks");
|
||||
var field1 = cls.getDeclaredField("namedLayers");
|
||||
field.setAccessible(true);
|
||||
field1.setAccessible(true);
|
||||
Map<ResourceLocation, Map.Entry<LayeredDraw, BooleanSupplier>> VROOT = ((Map<ResourceLocation, Map.Entry<LayeredDraw, BooleanSupplier>>) field.get(drawStack));
|
||||
var PSS = ((ForgeLayeredDraw) VROOT.get(PRE_SLEEP_STACK).getKey());
|
||||
check = ((Map<ResourceLocation, Layer>) field1.get(PSS));
|
||||
internalLayersList = getInternalLayersList(PSS);
|
||||
} catch (Exception e) {
|
||||
helper.fail("Threw a " + e.getMessage() + " when trying to get the inner layer list.");
|
||||
}
|
||||
int locationOfPotionEffects = internalLayersList.indexOf(check.get(POTION_EFFECTS));
|
||||
int locationOfLayerA = internalLayersList.indexOf(check.get(layerAName));
|
||||
int locationOfLayerB = internalLayersList.indexOf(check.get(layerBName));
|
||||
int locationOfLayerC = internalLayersList.indexOf(check.get(layerCName));
|
||||
helper.assertTrue(locationOfPotionEffects == locationOfLayerA - 1, "Layer offset from vanilla -> A was incorrect");
|
||||
helper.assertTrue(locationOfLayerB == locationOfLayerA + 1, "Layer offset from A -> B was incorrect");
|
||||
helper.assertTrue(locationOfLayerC == locationOfLayerB + 1, "Layer offset from B -> C was incorrect");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void full_stack_condition(GameTestHelper helper) {
|
||||
// Test conditional rendering & whether a full stack can be added in the first place.
|
||||
helper.assertFalse(detectConditionStackFlag.getBool(), "Conditional rendering ran when it shouldn't have.");
|
||||
enableConditionStackFlag.set(true);
|
||||
helper.runAfterDelay(5, () -> {
|
||||
boolean result = detectConditionStackFlag.getBool();// Just in case of weird race conditions.
|
||||
enableConditionStackFlag.set(false);
|
||||
helper.assertTrue(result, "");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void overlayTestListener(AddGuiOverlayLayersEvent event) {
|
||||
drawStack = event.getLayeredDraw();
|
||||
var layeredDraw = event.getLayeredDraw();
|
||||
layeredDraw.addAbove(VANILLA_ROOT, name("i_won_t_exist"), name("non_existent_target_layer"), notAddedLayer);
|
||||
var pEffects = layeredDraw.locateStack(PRE_SLEEP_STACK).get();
|
||||
// Test if layers may be ordered against other layers.
|
||||
// Layers have to be present to be ordered against, of course, but we tested for that already above.
|
||||
pEffects.addAbove(layerBName, POTION_EFFECTS, layerB);
|
||||
pEffects.addAbove(layerCName, layerBName, layerC);
|
||||
layeredDraw.addBelow(PRE_SLEEP_STACK, layerAName, layerBName, layerA);
|
||||
layeredDraw.addConditionTo(PRE_SLEEP_STACK, BOSS_OVERLAY, () -> {
|
||||
if (enableConditionFlag.getBool()) {
|
||||
detectConditionFlag.set(true);
|
||||
return true;
|
||||
} else {
|
||||
detectConditionFlag.set(false);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
myLayerStack.add(name("my_inner_layer_name"), (gg, tr) -> {
|
||||
detectConditionStackFlag.set(true);
|
||||
});
|
||||
// Demonstrates that entire stacks can have conditions attached
|
||||
event.getLayeredDraw()
|
||||
.add(myStackName, myLayerStack, () -> {
|
||||
if (enableConditionStackFlag.getBool()) {
|
||||
return true;
|
||||
} else {
|
||||
detectConditionStackFlag.set(false);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private static ResourceLocation name(String name) {
|
||||
return ResourceLocation.fromNamespaceAndPath(MODID, name);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Layer> getInternalLayersList(ForgeLayeredDraw stack) throws ClassCastException, NoSuchFieldException, IllegalAccessException {
|
||||
Class<?> cls = stack.getClass().getSuperclass();
|
||||
var layersField = cls.getDeclaredField("layers");
|
||||
layersField.setAccessible(true);
|
||||
return (List<Layer>) layersField.get(stack);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.client.event.AddFramePassEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.gametest.GameTestHolder;
|
||||
import net.minecraftforge.test.BaseTestMod;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.ShapeRenderer;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.framegraph.FramePass;
|
||||
|
||||
|
||||
@Mod(RenderFrameLayerTest.MODID)
|
||||
@GameTestHolder("forge." + RenderFrameLayerTest.MODID)
|
||||
public class RenderFrameLayerTest extends BaseTestMod {
|
||||
public static final String MODID = "render_frame_layer_test";
|
||||
|
||||
public RenderFrameLayerTest(FMLJavaModLoadingContext context) {
|
||||
super(context);
|
||||
MinecraftForge.EVENT_BUS.addListener(RenderFrameLayerTest::renderTest);
|
||||
}
|
||||
|
||||
private static ResourceLocation rl(String path) {
|
||||
return ResourceLocation.fromNamespaceAndPath(MODID, path);
|
||||
}
|
||||
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void frame_passes_run(GameTestHelper helper) {
|
||||
var passOne = helper.boolFlag("passOne");
|
||||
var passTwo = helper.boolFlag("passOne");
|
||||
|
||||
helper.<AddFramePassEvent>addEventListener(event -> {
|
||||
FramePass pass = event.createPass(rl(MODID + "test_1") );
|
||||
event.getBundle().main = pass.readsAndWrites(event.getBundle().main);
|
||||
pass.executes(() -> passOne.set(true));
|
||||
|
||||
pass = event.createPass(rl(MODID + "test_2"));
|
||||
event.getBundle().main = pass.readsAndWrites(event.getBundle().main);
|
||||
pass.executes(() -> passTwo.set(true));
|
||||
});
|
||||
|
||||
helper.runAfterDelay(2, () -> {
|
||||
helper.assertTrue(passOne.getBool(), "Pass One was not executed");
|
||||
helper.assertTrue(passTwo.getBool(), "Pass Two was not executed");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* If this is working, two white line box cubes will be rendered at ground level in a superflat world around (0,0)
|
||||
*/
|
||||
@SubscribeEvent
|
||||
public static void renderTest(AddFramePassEvent event) {
|
||||
var mainCamera = Minecraft.getInstance().gameRenderer.getMainCamera();
|
||||
FramePass pass = event.createPass(rl(MODID));
|
||||
event.getBundle().main = pass.readsAndWrites(event.getBundle().main);
|
||||
|
||||
pass.executes(() -> {
|
||||
PoseStack ps = new PoseStack();
|
||||
ps.translate(mainCamera.getPosition().multiply(-1,-1,-1));
|
||||
ps.pushPose();
|
||||
var buffSource = Minecraft.getInstance().renderBuffers().bufferSource();
|
||||
var vc = buffSource.getBuffer(RenderType.lines());
|
||||
|
||||
ShapeRenderer.renderLineBox(ps, vc, 0, -60, 0, 10, -50, 10, 1f, 1f, 1f, 1f);
|
||||
buffSource.endBatch();
|
||||
ps.popPose();
|
||||
});
|
||||
|
||||
pass = event.createPass(rl(MODID+"2"));
|
||||
event.getBundle().main = pass.readsAndWrites(event.getBundle().main);
|
||||
|
||||
pass.executes(() -> {
|
||||
PoseStack ps = new PoseStack();
|
||||
ps.translate(mainCamera.getPosition().multiply(-1,-1,-1));
|
||||
ps.pushPose();
|
||||
var buffSource = Minecraft.getInstance().renderBuffers().bufferSource();
|
||||
var vc = buffSource.getBuffer(RenderType.lines());
|
||||
|
||||
ShapeRenderer.renderLineBox(ps, vc, 1, -61, 1, 9, -49, 9, 1f, 1f, 1f, 1f);
|
||||
buffSource.endBatch();
|
||||
ps.popPose();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.gameplay.block;
|
||||
|
||||
import net.minecraftforge.gametest.GameTestHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.FrontAndTop;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.gametest.framework.*;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.BaseEntityBlock;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.entity.CrafterBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
|
||||
import net.minecraftforge.common.capabilities.Capability;
|
||||
import net.minecraftforge.common.capabilities.ForgeCapabilities;
|
||||
import net.minecraftforge.common.util.LazyOptional;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.items.IItemHandler;
|
||||
import net.minecraftforge.items.ItemStackHandler;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.test.BaseTestMod;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
@Mod(CrafterBlockTest.MOD_ID)
|
||||
@GameTestHolder("forge." + CrafterBlockTest.MOD_ID)
|
||||
public class CrafterBlockTest extends BaseTestMod {
|
||||
static final String MOD_ID = "crafter_block";
|
||||
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(Registries.BLOCK, MOD_ID);
|
||||
private static final RegistryObject<Block> IITEM_BLOCK = BLOCKS.register("iitem", () -> new SimpleIItemHandlerBlock(Block.Properties.of().setId(BLOCKS.key("iitem"))));
|
||||
|
||||
public static final DeferredRegister<BlockEntityType<?>> BLOCK_TYPES = DeferredRegister.create(Registries.BLOCK_ENTITY_TYPE, MOD_ID);
|
||||
private static final RegistryObject<BlockEntityType<SimpleIItemHandler>> IITEM_BLOCK_TYPE = BLOCK_TYPES.register("iitem", () -> new BlockEntityType<>(SimpleIItemHandler::new, Set.of(IITEM_BLOCK.get())));
|
||||
|
||||
public CrafterBlockTest(FMLJavaModLoadingContext context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
// Make sure they can add items to vanilla containers.
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void places_in_chest(GameTestHelper helper) {
|
||||
var chestPos = new BlockPos(0, 1, 0);
|
||||
helper.setBlock(chestPos, Blocks.CHEST);
|
||||
helper.setBlock(BlockPos.ZERO, Blocks.CRAFTER.defaultBlockState().setValue(BlockStateProperties.ORIENTATION, FrontAndTop.UP_NORTH));
|
||||
var crafter = (CrafterBlockEntity) helper.getBlockEntity(BlockPos.ZERO);
|
||||
crafter.setItem(0, new ItemStack(Blocks.OAK_LOG));
|
||||
helper.tickBlock(BlockPos.ZERO);
|
||||
helper.assertContainerContains(chestPos, Blocks.OAK_PLANKS.asItem(), 4);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
// Make sure they can add items to IItemHandler BlockEntities that are not WorldlyContainers.
|
||||
@GameTest(template = "forge:empty3x3x3")
|
||||
public static void places_in_iitemhandler_block(GameTestHelper helper) {
|
||||
var chestPos = new BlockPos(0, 1, 0);
|
||||
helper.setBlock(chestPos, IITEM_BLOCK.get());
|
||||
helper.setBlock(BlockPos.ZERO, Blocks.CRAFTER.defaultBlockState().setValue(BlockStateProperties.ORIENTATION, FrontAndTop.UP_NORTH));
|
||||
var crafter = (CrafterBlockEntity) helper.getBlockEntity(BlockPos.ZERO);
|
||||
crafter.setItem(0, new ItemStack(Blocks.OAK_LOG));
|
||||
helper.tickBlock(BlockPos.ZERO);
|
||||
helper.assertItemHandlerContains(chestPos, Blocks.OAK_PLANKS.asItem(), 4);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
private static class SimpleIItemHandlerBlock extends BaseEntityBlock {
|
||||
private static final MapCodec<SimpleIItemHandlerBlock> CODEC = simpleCodec(SimpleIItemHandlerBlock::new);
|
||||
|
||||
protected SimpleIItemHandlerBlock(Properties props) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
|
||||
return IITEM_BLOCK_TYPE.get().create(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MapCodec<? extends BaseEntityBlock> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
private static class SimpleIItemHandler extends BlockEntity {
|
||||
private final LazyOptional<IItemHandler> itemHandler = LazyOptional.of(() -> new ItemStackHandler(1));
|
||||
|
||||
public SimpleIItemHandler(BlockPos pos, BlockState state) {
|
||||
super(IITEM_BLOCK_TYPE.get(), pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull <T> LazyOptional<T> getCapability(@NotNull final Capability<T> cap, final @Nullable Direction side) {
|
||||
if (cap == ForgeCapabilities.ITEM_HANDLER)
|
||||
return itemHandler.cast();
|
||||
return super.getCapability(cap, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
clientSideOnly=true
|
||||
@@ -0,0 +1 @@
|
||||
clientSideOnly=true
|
||||
Reference in new issue
Block a user