mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-19 11:59:25 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b981f4725 | ||
|
|
bca7eff231 | ||
|
|
5df71fb5df | ||
|
|
5e6d92a099 | ||
|
|
a171012411 | ||
|
|
44b30daa05 | ||
|
|
2d33dba36e | ||
|
|
c538816698 | ||
|
|
4f936fb5f7 | ||
|
|
66e4dab83b | ||
|
|
78d8d5495c | ||
|
|
e61aa67600 |
No files matched your search
@@ -2,7 +2,7 @@ name: Publish
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ '26.3' ]
|
branches: [ '1.21.11' ]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|||||||
+6
-7
@@ -11,7 +11,7 @@ forgedev
|
|||||||
/eclipse/
|
/eclipse/
|
||||||
|
|
||||||
#idea
|
#idea
|
||||||
**/.idea
|
/.idea
|
||||||
/*/out
|
/*/out
|
||||||
/classes
|
/classes
|
||||||
*.iml
|
*.iml
|
||||||
@@ -33,12 +33,12 @@ forgedev
|
|||||||
src/minecraft
|
src/minecraft
|
||||||
|
|
||||||
#occupational hazards
|
#occupational hazards
|
||||||
/*/runs/
|
/projects/**/build/
|
||||||
|
/projects/**/out/
|
||||||
|
/projects/**/run/
|
||||||
|
/projects/**/*.launch
|
||||||
/repo/
|
/repo/
|
||||||
/rejects-*/
|
src/*/generated/**/.cache/
|
||||||
**/src/*/generated/**/.cache/
|
|
||||||
**/*.launch
|
|
||||||
**/.project_info.properties
|
|
||||||
|
|
||||||
# Generated by gradle every import
|
# Generated by gradle every import
|
||||||
**/src/main/resources/META-INF/MANIFEST.MF
|
**/src/main/resources/META-INF/MANIFEST.MF
|
||||||
@@ -51,7 +51,6 @@ src/minecraft
|
|||||||
/*/.gitignore
|
/*/.gitignore
|
||||||
/*/.factorypath
|
/*/.factorypath
|
||||||
/*/.apt_generated/
|
/*/.apt_generated/
|
||||||
/fmlcore/logs/
|
|
||||||
/lib/
|
/lib/
|
||||||
/_actual/
|
/_actual/
|
||||||
/runs/
|
/runs/
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id("groovy-gradle-plugin")
|
|
||||||
alias(libs.plugins.licenser)
|
|
||||||
}
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
mavenCentral()
|
|
||||||
gradlePluginPortal()
|
|
||||||
maven { url = 'https://maven.minecraftforge.net/' }
|
|
||||||
//mavenLocal()
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
compileOnly gradleApi()
|
|
||||||
|
|
||||||
// Manually import plugins so that we can apply them by id.
|
|
||||||
implementation plugin('licenser')
|
|
||||||
implementation plugin('gradleutils')
|
|
||||||
implementation plugin('gitversion')
|
|
||||||
implementation plugin('changelog')
|
|
||||||
implementation plugin('forgedev')
|
|
||||||
}
|
|
||||||
|
|
||||||
gradlePlugin {
|
|
||||||
plugins {
|
|
||||||
register('convention') {
|
|
||||||
id = 'net.minecraftforge.forge.build.convention'
|
|
||||||
implementationClass = 'net.minecraftforge.forge.build.ConventionPlugin'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final Provider<String> plugin(String alias) {
|
|
||||||
return (Provider<String>)project.extensions.getByType(VersionCatalogsExtension)
|
|
||||||
.named("libs")
|
|
||||||
.findPlugin(alias).get()
|
|
||||||
.map { it.pluginId + ":" + it.pluginId + ".gradle.plugin:" + it.version }
|
|
||||||
}
|
|
||||||
|
|
||||||
license {
|
|
||||||
header = file('../LICENSE-header.txt')
|
|
||||||
}
|
|
||||||
BIN
Binary file not shown.
@@ -1,7 +0,0 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
|
||||||
distributionPath=wrapper/dists
|
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
|
||||||
networkTimeout=10000
|
|
||||||
validateDistributionUrl=true
|
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
|
||||||
zipStorePath=wrapper/dists
|
|
||||||
Vendored
-251
@@ -1,251 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
#
|
|
||||||
# Copyright © 2015 the original authors.
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
#
|
|
||||||
# SPDX-License-Identifier: Apache-2.0
|
|
||||||
#
|
|
||||||
|
|
||||||
##############################################################################
|
|
||||||
#
|
|
||||||
# Gradle start up script for POSIX generated by Gradle.
|
|
||||||
#
|
|
||||||
# Important for running:
|
|
||||||
#
|
|
||||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
|
||||||
# noncompliant, but you have some other compliant shell such as ksh or
|
|
||||||
# bash, then to run this script, type that shell name before the whole
|
|
||||||
# command line, like:
|
|
||||||
#
|
|
||||||
# ksh Gradle
|
|
||||||
#
|
|
||||||
# Busybox and similar reduced shells will NOT work, because this script
|
|
||||||
# requires all of these POSIX shell features:
|
|
||||||
# * functions;
|
|
||||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
|
||||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
|
||||||
# * compound commands having a testable exit status, especially «case»;
|
|
||||||
# * various built-in commands including «command», «set», and «ulimit».
|
|
||||||
#
|
|
||||||
# Important for patching:
|
|
||||||
#
|
|
||||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
|
||||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
|
||||||
#
|
|
||||||
# The "traditional" practice of packing multiple parameters into a
|
|
||||||
# space-separated string is a well documented source of bugs and security
|
|
||||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
|
||||||
# options in "$@", and eventually passing that to Java.
|
|
||||||
#
|
|
||||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
|
||||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
|
||||||
# see the in-line comments for details.
|
|
||||||
#
|
|
||||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
|
||||||
# Darwin, MinGW, and NonStop.
|
|
||||||
#
|
|
||||||
# (3) This script is generated from the Groovy template
|
|
||||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
|
||||||
# within the Gradle project.
|
|
||||||
#
|
|
||||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
|
||||||
#
|
|
||||||
##############################################################################
|
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
|
||||||
|
|
||||||
# Resolve links: $0 may be a link
|
|
||||||
app_path=$0
|
|
||||||
|
|
||||||
# Need this for daisy-chained symlinks.
|
|
||||||
while
|
|
||||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
|
||||||
[ -h "$app_path" ]
|
|
||||||
do
|
|
||||||
ls=$( ls -ld "$app_path" )
|
|
||||||
link=${ls#*' -> '}
|
|
||||||
case $link in #(
|
|
||||||
/*) app_path=$link ;; #(
|
|
||||||
*) app_path=$APP_HOME$link ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# This is normally unused
|
|
||||||
# shellcheck disable=SC2034
|
|
||||||
APP_BASE_NAME=${0##*/}
|
|
||||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
|
||||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
|
||||||
MAX_FD=maximum
|
|
||||||
|
|
||||||
warn () {
|
|
||||||
echo "$*"
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
die () {
|
|
||||||
echo
|
|
||||||
echo "$*"
|
|
||||||
echo
|
|
||||||
exit 1
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
|
||||||
cygwin=false
|
|
||||||
msys=false
|
|
||||||
darwin=false
|
|
||||||
nonstop=false
|
|
||||||
case "$( uname )" in #(
|
|
||||||
CYGWIN* ) cygwin=true ;; #(
|
|
||||||
Darwin* ) darwin=true ;; #(
|
|
||||||
MSYS* | MINGW* ) msys=true ;; #(
|
|
||||||
NONSTOP* ) nonstop=true ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
CLASSPATH="\\\"\\\""
|
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
|
||||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
|
||||||
else
|
|
||||||
JAVACMD=$JAVA_HOME/bin/java
|
|
||||||
fi
|
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
JAVACMD=java
|
|
||||||
if ! command -v java >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
|
||||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|
||||||
case $MAX_FD in #(
|
|
||||||
max*)
|
|
||||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
|
||||||
warn "Could not query maximum file descriptor limit"
|
|
||||||
esac
|
|
||||||
case $MAX_FD in #(
|
|
||||||
'' | soft) :;; #(
|
|
||||||
*)
|
|
||||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
ulimit -n "$MAX_FD" ||
|
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Collect all arguments for the java command, stacking in reverse order:
|
|
||||||
# * args from the command line
|
|
||||||
# * the main class name
|
|
||||||
# * -classpath
|
|
||||||
# * -D...appname settings
|
|
||||||
# * --module-path (only if needed)
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
|
||||||
|
|
||||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
|
||||||
if "$cygwin" || "$msys" ; then
|
|
||||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
|
||||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
|
||||||
|
|
||||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
|
||||||
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
|
||||||
for arg do
|
|
||||||
if
|
|
||||||
case $arg in #(
|
|
||||||
-*) false ;; # don't mess with options #(
|
|
||||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
|
||||||
[ -e "$t" ] ;; #(
|
|
||||||
*) false ;;
|
|
||||||
esac
|
|
||||||
then
|
|
||||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
|
||||||
fi
|
|
||||||
# Roll the args list around exactly as many times as the number of
|
|
||||||
# args, so each arg winds up back in the position where it started, but
|
|
||||||
# possibly modified.
|
|
||||||
#
|
|
||||||
# NB: a `for` loop captures its iteration list before it begins, so
|
|
||||||
# changing the positional parameters here affects neither the number of
|
|
||||||
# iterations, nor the values presented in `arg`.
|
|
||||||
shift # remove old arg
|
|
||||||
set -- "$@" "$arg" # push replacement arg
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
|
||||||
|
|
||||||
# Collect all arguments for the java command:
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
|
||||||
# and any embedded shellness will be escaped.
|
|
||||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
|
||||||
# treated as '${Hostname}' itself on the command line.
|
|
||||||
|
|
||||||
set -- \
|
|
||||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
|
||||||
-classpath "$CLASSPATH" \
|
|
||||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
|
||||||
"$@"
|
|
||||||
|
|
||||||
# Stop when "xargs" is not available.
|
|
||||||
if ! command -v xargs >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "xargs is not available"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Use "xargs" to parse quoted args.
|
|
||||||
#
|
|
||||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
|
||||||
#
|
|
||||||
# In Bash we could simply go:
|
|
||||||
#
|
|
||||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
|
||||||
# set -- "${ARGS[@]}" "$@"
|
|
||||||
#
|
|
||||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
|
||||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
|
||||||
# character that might be a shell metacharacter, then use eval to reverse
|
|
||||||
# that process (while maintaining the separation between arguments), and wrap
|
|
||||||
# the whole thing up as a single "set" statement.
|
|
||||||
#
|
|
||||||
# This will of course break if any of these variables contains a newline or
|
|
||||||
# an unmatched quote.
|
|
||||||
#
|
|
||||||
|
|
||||||
eval "set -- $(
|
|
||||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
|
||||||
xargs -n1 |
|
|
||||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
|
||||||
tr '\n' ' '
|
|
||||||
)" '"$@"'
|
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
|
||||||
Vendored
-94
@@ -1,94 +0,0 @@
|
|||||||
@rem
|
|
||||||
@rem Copyright 2015 the original author or authors.
|
|
||||||
@rem
|
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
@rem you may not use this file except in compliance with the License.
|
|
||||||
@rem You may obtain a copy of the License at
|
|
||||||
@rem
|
|
||||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
@rem
|
|
||||||
@rem Unless required by applicable law or agreed to in writing, software
|
|
||||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
@rem See the License for the specific language governing permissions and
|
|
||||||
@rem limitations under the License.
|
|
||||||
@rem
|
|
||||||
@rem SPDX-License-Identifier: Apache-2.0
|
|
||||||
@rem
|
|
||||||
|
|
||||||
@if "%DEBUG%"=="" @echo off
|
|
||||||
@rem ##########################################################################
|
|
||||||
@rem
|
|
||||||
@rem Gradle startup script for Windows
|
|
||||||
@rem
|
|
||||||
@rem ##########################################################################
|
|
||||||
|
|
||||||
@rem Set local scope for the variables with windows NT shell
|
|
||||||
if "%OS%"=="Windows_NT" setlocal
|
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
|
||||||
if "%DIRNAME%"=="" set DIRNAME=.
|
|
||||||
@rem This is normally unused
|
|
||||||
set APP_BASE_NAME=%~n0
|
|
||||||
set APP_HOME=%DIRNAME%
|
|
||||||
|
|
||||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
|
||||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
|
||||||
|
|
||||||
@rem Find java.exe
|
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
|
||||||
if %ERRORLEVEL% equ 0 goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:findJavaFromJavaHome
|
|
||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:execute
|
|
||||||
@rem Setup the command line
|
|
||||||
|
|
||||||
set CLASSPATH=
|
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
|
||||||
|
|
||||||
:end
|
|
||||||
@rem End local scope for the variables with windows NT shell
|
|
||||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
|
||||||
|
|
||||||
:fail
|
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
|
||||||
rem the _cmd.exe /c_ return code!
|
|
||||||
set EXIT_CODE=%ERRORLEVEL%
|
|
||||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
|
||||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
|
||||||
exit /b %EXIT_CODE%
|
|
||||||
|
|
||||||
:mainEnd
|
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
|
||||||
|
|
||||||
:omega
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
pluginManagement {
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
gradlePluginPortal()
|
|
||||||
maven { url = 'https://maven.minecraftforge.net/' }
|
|
||||||
mavenLocal()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
plugins {
|
|
||||||
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
|
|
||||||
}
|
|
||||||
|
|
||||||
//enableFeaturePreview 'TYPESAFE_PROJECT_ACCESSORS'
|
|
||||||
|
|
||||||
dependencyResolutionManagement.versionCatalogs {
|
|
||||||
register('bootLibs') {
|
|
||||||
description = 'Important version numbers that are externally declared for easy modification.'
|
|
||||||
from(files('../minecraft.versions.toml'))
|
|
||||||
}
|
|
||||||
|
|
||||||
create('libs') {
|
|
||||||
description = 'Libraries used by Forge and its subprojects.'
|
|
||||||
from(files("../gradle/libs.versions.toml"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (new File('forgedev/settings.gradle').exists())
|
|
||||||
includeBuild '../forgedev'
|
|
||||||
|
|
||||||
-166
@@ -1,166 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.Action
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.gradle.api.Task
|
|
||||||
import org.gradle.api.artifacts.ExternalModuleDependencyBundle
|
|
||||||
import org.gradle.api.artifacts.MinimalExternalModuleDependency
|
|
||||||
import org.gradle.api.model.ObjectFactory
|
|
||||||
import org.gradle.api.provider.Provider
|
|
||||||
import org.gradle.api.provider.ProviderFactory
|
|
||||||
import org.gradle.api.publish.maven.MavenPublication
|
|
||||||
import org.gradle.api.tasks.TaskProvider
|
|
||||||
import org.gradle.jvm.tasks.Jar
|
|
||||||
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class ConventionExtension implements Meta {
|
|
||||||
private final Project project;
|
|
||||||
private final Runs runs
|
|
||||||
|
|
||||||
protected abstract @Inject ObjectFactory getObjects()
|
|
||||||
protected abstract @Inject ProviderFactory getProviders()
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
ConventionExtension(Project project) {
|
|
||||||
this.project = project
|
|
||||||
this.runs = objects.newInstance(Runs, this)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
Project getProject() {
|
|
||||||
this.project
|
|
||||||
}
|
|
||||||
|
|
||||||
void manifest(String pkg) {
|
|
||||||
this.project.tasks.named('jar', Jar).configure {
|
|
||||||
this.gradleutils.manifestDefaults(it.manifest, pkg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void manifest(String pkg, Map<String, String> info) {
|
|
||||||
manifest(pkg)
|
|
||||||
this.project.tasks.named('jar', Jar).configure {
|
|
||||||
it.manifest.getAttributes().with {
|
|
||||||
for (var entry : info.entrySet())
|
|
||||||
put(entry.key, entry.value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// region Maven publishing ==============================================================
|
|
||||||
void publish() {
|
|
||||||
publish(pub -> pub.from(project.components.getByName('java')))
|
|
||||||
}
|
|
||||||
void publish(Action<MavenPublication> config) {
|
|
||||||
project.with {
|
|
||||||
publishing.with {
|
|
||||||
repositories.with {
|
|
||||||
maven gradleutils.publishingForgeMaven
|
|
||||||
}
|
|
||||||
publications.register('mavenJava', MavenPublication) {
|
|
||||||
changelog.publish(it)
|
|
||||||
gradleutils.promote(it)
|
|
||||||
|
|
||||||
// The actual artifacts to be published should be configured, so run the config
|
|
||||||
config.execute(it)
|
|
||||||
|
|
||||||
it.pom.with {
|
|
||||||
description = project.description
|
|
||||||
gradleutils.pom.addRemoteDetails(it)
|
|
||||||
license.with {
|
|
||||||
gradleutils.pom.licenses.LGPLv2_1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// endregion
|
|
||||||
|
|
||||||
// region Runs ================================================================
|
|
||||||
private TaskProvider<Task> genAllData = null
|
|
||||||
TaskProvider<Task> getGenAllData() {
|
|
||||||
if (genAllData == null)
|
|
||||||
genAllData = this.project.tasks.register('genAllData')
|
|
||||||
return genAllData
|
|
||||||
}
|
|
||||||
TaskProvider<Task> getGenAllData(Action<Task> config) {
|
|
||||||
getGenAllData().configure(config)
|
|
||||||
return getGenAllData()
|
|
||||||
}
|
|
||||||
|
|
||||||
Runs getRuns() {
|
|
||||||
return this.runs
|
|
||||||
}
|
|
||||||
Runs runs(Action<Runs> config) {
|
|
||||||
config.execute(this.runs)
|
|
||||||
return this.runs
|
|
||||||
}
|
|
||||||
Runs basicRuns() {
|
|
||||||
return basicRuns({})
|
|
||||||
}
|
|
||||||
Runs basicRuns(Action<Runs> config) {
|
|
||||||
this.runs.main(null, null)
|
|
||||||
config.execute(this.runs)
|
|
||||||
return getRuns()
|
|
||||||
}
|
|
||||||
Runs basicRuns(String mods, File output) {
|
|
||||||
return basicRuns(mods, output, {})
|
|
||||||
}
|
|
||||||
Runs basicRuns(String mods, File output, Action<Runs> config) {
|
|
||||||
this.runs.main(mods, output)
|
|
||||||
config.execute(this.runs)
|
|
||||||
return getRuns()
|
|
||||||
}
|
|
||||||
Runs testRuns(String mods, File output) {
|
|
||||||
return testRuns(mods, output, {})
|
|
||||||
}
|
|
||||||
Runs testRuns(String mods, File output, Action<Runs> config) {
|
|
||||||
this.runs.test(mods, output)
|
|
||||||
config.execute(this.runs)
|
|
||||||
return getRuns()
|
|
||||||
}
|
|
||||||
// endregion
|
|
||||||
|
|
||||||
// region Forge Version Json ===================================================
|
|
||||||
private TaskProvider<WriteForgeVersionJson> writeForgeVersionJson = null
|
|
||||||
TaskProvider<WriteForgeVersionJson> getForgeVersionJson() {
|
|
||||||
if (writeForgeVersionJson == null) {
|
|
||||||
writeForgeVersionJson = this.project.tasks.register('writeForgeVersionJson', WriteForgeVersionJson)
|
|
||||||
final versions = this.versions
|
|
||||||
writeForgeVersionJson.configure {
|
|
||||||
it.forgeVersion.set(versions.forge)
|
|
||||||
it.minecraftVersion.set(versions.minecraft)
|
|
||||||
it.mcpVersion.set(versions.mcp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return writeForgeVersionJson
|
|
||||||
}
|
|
||||||
TaskProvider<WriteForgeVersionJson> forgeVersionJson(Action<WriteForgeVersionJson> config) {
|
|
||||||
forgeVersionJson.configure(config)
|
|
||||||
return forgeVersionJson
|
|
||||||
}
|
|
||||||
// endregion
|
|
||||||
|
|
||||||
// region Natives helper =========================================================
|
|
||||||
// See gradle/gradle#35070 (https://github.com/gradle/gradle/issues/35070)
|
|
||||||
// We are making the list of providers first BEFORE mapping them to a provider of the resolved objects so
|
|
||||||
// that they can be finalized after configuration.
|
|
||||||
List<MinimalExternalModuleDependency> nativeVariants(Provider<ExternalModuleDependencyBundle> bundle) {
|
|
||||||
final natives = "natives-" + forgedev.os
|
|
||||||
final deps = this.project.dependencies
|
|
||||||
bundle.get().collect { dep ->
|
|
||||||
(deps.variantOf(providers.provider { (MinimalExternalModuleDependency)dep }) {
|
|
||||||
it.classifier(natives)
|
|
||||||
}).get()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// endregion
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.Plugin
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.gradle.api.tasks.compile.JavaCompile
|
|
||||||
import org.gradle.jvm.toolchain.JavaLanguageVersion
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
class ConventionPlugin implements Plugin<Project>, Meta {
|
|
||||||
Project project
|
|
||||||
@Override
|
|
||||||
Project getProject() {
|
|
||||||
this.project
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void apply(Project project) {
|
|
||||||
this.project = project
|
|
||||||
project.with {
|
|
||||||
pluginManager.with {
|
|
||||||
apply 'java-library'
|
|
||||||
apply 'maven-publish'
|
|
||||||
apply pluginId('licenser')
|
|
||||||
apply pluginId('gradleutils')
|
|
||||||
apply pluginId('gitversion')
|
|
||||||
apply pluginId('changelog')
|
|
||||||
apply pluginId('forgedev')
|
|
||||||
}
|
|
||||||
|
|
||||||
final versions = extensions.create("versions", VersionsExtension, project)
|
|
||||||
final convention = extensions.create('convention', ConventionExtension, project)
|
|
||||||
|
|
||||||
logger.lifecycle(name + " " + version)
|
|
||||||
|
|
||||||
gradleutils.with {
|
|
||||||
vendor.set('Forge Development LLC')
|
|
||||||
version.set(gitversion.version)
|
|
||||||
}
|
|
||||||
project.setGroup('net.minecraftforge')
|
|
||||||
|
|
||||||
java.with {
|
|
||||||
toolchain.languageVersion.set(JavaLanguageVersion.of(versions.java))
|
|
||||||
// This is needed for IDE runtime classpath to be correct/not have multiple of the same artifact
|
|
||||||
consistentResolution {
|
|
||||||
it.useCompileClasspathVersions()
|
|
||||||
}
|
|
||||||
// Forge needs to build its own sources jar due to patching, everything else should use the default
|
|
||||||
if (project != rootProject)
|
|
||||||
it.withSourcesJar()
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
|
||||||
it.options.with {
|
|
||||||
encoding = 'UTF-8'
|
|
||||||
compilerArgs << '-Xlint:-unchecked' // This is mainly for vanilla code, but just makes it quiet down outside the IDE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NOTE: We are adding dependencies to projects instead of through settings, so we don't have to apply forgedev in settings.
|
|
||||||
// Applying forgedev in settings will break IDE linting support, which makes it very hard to work with.
|
|
||||||
// We can reconsider this if/when JetBrains gets their shit together.
|
|
||||||
// - I doubt they will ever fix their shit 8/28/2006 - Lex
|
|
||||||
repositories.with {
|
|
||||||
// Libraries has to be before maven central because Mojang hosts a classifer that central doesn't (org.lwjgl:lwjgl-freetype:3.3.3:natives-macos-patch)
|
|
||||||
maven { url = 'https://libraries.minecraft.net/' }
|
|
||||||
mavenCentral()
|
|
||||||
maven gradleutils.forgeMaven
|
|
||||||
project.pluginManager.withPlugin('net.minecraftforge.forgedev') {
|
|
||||||
maven forgedev.mavenizer
|
|
||||||
}
|
|
||||||
|
|
||||||
mavenLocal()
|
|
||||||
}
|
|
||||||
|
|
||||||
changelog.with {
|
|
||||||
from versions.changelogBase
|
|
||||||
}
|
|
||||||
|
|
||||||
license.with {
|
|
||||||
header = rootProject.file('LICENSE-header.txt')
|
|
||||||
exclude('.project_info.properties')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Common dependencies,
|
|
||||||
project.dependencies.with {
|
|
||||||
add('compileOnly', libs.findLibrary('jetbrains.annotations').get())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import net.minecraftforge.forgedev.ForgeDevExtension
|
|
||||||
import net.minecraftforge.gitversion.gradle.GitVersionExtension
|
|
||||||
import net.minecraftforge.gitversion.gradle.changelog.ChangelogExtension
|
|
||||||
import net.minecraftforge.gradleutils.GradleUtilsExtensionForProject
|
|
||||||
import net.minecraftforge.licenser.LicenseExtension
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.gradle.api.artifacts.VersionCatalog
|
|
||||||
import org.gradle.api.artifacts.VersionCatalogsExtension
|
|
||||||
import org.gradle.api.plugins.ExtraPropertiesExtension
|
|
||||||
import org.gradle.api.plugins.JavaPluginExtension
|
|
||||||
import org.gradle.api.publish.PublishingExtension
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
interface Meta {
|
|
||||||
Project getProject();
|
|
||||||
|
|
||||||
default VersionCatalog getLibs() {
|
|
||||||
project.extensions.getByType(VersionCatalogsExtension).named("libs")
|
|
||||||
}
|
|
||||||
|
|
||||||
default ExtraPropertiesExtension getExt() {
|
|
||||||
project.extensions.getByType(ExtraPropertiesExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default JavaPluginExtension getJava() {
|
|
||||||
project.extensions.getByType(JavaPluginExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default GradleUtilsExtensionForProject getGradleutils() {
|
|
||||||
project.extensions.getByType(GradleUtilsExtensionForProject)
|
|
||||||
}
|
|
||||||
|
|
||||||
default GitVersionExtension getGitversion() {
|
|
||||||
project.extensions.getByType(GitVersionExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default ForgeDevExtension getForgedev() {
|
|
||||||
project.extensions.getByType(ForgeDevExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default ChangelogExtension getChangelog() {
|
|
||||||
project.extensions.getByType(ChangelogExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default LicenseExtension getLicense() {
|
|
||||||
project.extensions.getByType(LicenseExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default PublishingExtension getPublishing() {
|
|
||||||
project.extensions.getByType(PublishingExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default VersionsExtension getVersions() {
|
|
||||||
project.extensions.getByType(VersionsExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default ConventionExtension getConvention() {
|
|
||||||
project.extensions.getByType(ConventionExtension)
|
|
||||||
}
|
|
||||||
|
|
||||||
default String pluginId(String alias) {
|
|
||||||
getLibs().findPlugin(alias).orElseThrow { new IllegalStateException("Could not find plugin " + alias) }.get().pluginId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import net.minecraftforge.licenser.LicenseExtension
|
|
||||||
import net.minecraftforge.licenser.tasks.LicenseCheck
|
|
||||||
import org.gradle.api.Action
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.gradle.api.tasks.SourceSet
|
|
||||||
import org.gradle.api.tasks.TaskProvider
|
|
||||||
import org.gradle.api.tasks.WriteProperties
|
|
||||||
import org.jspecify.annotations.Nullable
|
|
||||||
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.naming.spi.ObjectFactory
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
class Runs implements Meta {
|
|
||||||
private final ConventionExtension ext
|
|
||||||
private boolean hasDependency = false
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
Runs(ConventionExtension ext) {
|
|
||||||
this.ext = ext
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
Project getProject() {
|
|
||||||
this.ext.project
|
|
||||||
}
|
|
||||||
|
|
||||||
void main(@Nullable String mods, @Nullable File output) {
|
|
||||||
final project = this.project
|
|
||||||
final genAllData = this.ext.genAllData
|
|
||||||
|
|
||||||
project.with {
|
|
||||||
final SourceSet sourceSet = getJava().getSourceSets().named("main").get()
|
|
||||||
if (!hasDependency && project != project.rootProject) {
|
|
||||||
dependencies.with {
|
|
||||||
add('implementation', it.project(':')) // Root project is forge itself
|
|
||||||
}
|
|
||||||
hasDependency = true
|
|
||||||
}
|
|
||||||
if (output != null)
|
|
||||||
sourceSet.resources.with { srcDir output }
|
|
||||||
|
|
||||||
forgedev.runs.with {
|
|
||||||
final File existing = sourceSet.getResources().getSrcDirs()[0]
|
|
||||||
|
|
||||||
configureEach {
|
|
||||||
it.with {
|
|
||||||
cache.set(project.layout.projectDirectory.dir('runs/cache'))
|
|
||||||
eclipsePrefix = project.name
|
|
||||||
|
|
||||||
// If we're not forge, we need to get the metadata from the forge project
|
|
||||||
if (project != project.rootProject)
|
|
||||||
metadata = project.files(getForgedev().consumeFile('metadata', project.rootProject))
|
|
||||||
|
|
||||||
var runName = it.name.toLowerCase(Locale.ENGLISH)
|
|
||||||
|
|
||||||
if (runName.contains('client') || runName.contains('data')) {
|
|
||||||
options.with {
|
|
||||||
// LWJGL needs native access, Mojang gets away with just saying 'ALL-UNNAMED' because it doesnt boot into module land
|
|
||||||
// We need a system to translate that to module names
|
|
||||||
//jvmArgs '--enable-native-access=ALL-UNNAMED', '--add-exports', 'java.base/jdk.internal.misc=ALL-UNNAMED'
|
|
||||||
args '--assetsDir', '{assets_root}', '--assetIndex', '{asset_index}'
|
|
||||||
systemProperty 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (runName.contains('data')) {
|
|
||||||
options.with(sourceSet).with {
|
|
||||||
systemProperties.put("forge.project.list", getProjectList().flatMap { it.destinationFile.map{ it.asFile.absolutePath } })
|
|
||||||
if (mods != null) args('--mod', mods)
|
|
||||||
if (output != null) args('--output', output)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
options.with {
|
|
||||||
getWorkingDir().set(project.layout.projectDirectory.dir("runs/$name"))
|
|
||||||
getMainClass().set('net.minecraftforge.bootstrap.ForgeBootstrap')
|
|
||||||
args '--gameDir', '.'
|
|
||||||
jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32'
|
|
||||||
|
|
||||||
//systemProperty 'forge.logging.marker.registries', 'ACCEPT'
|
|
||||||
//systemProperty 'forge.logging.console.level', 'debug'
|
|
||||||
systemProperty 'bsl.debug', 'true'
|
|
||||||
systemProperty 'terminal.jline', 'true'
|
|
||||||
systemProperty 'forge.enableGameTest', 'true'
|
|
||||||
systemProperty 'eventbus.api.strictRuntimeChecks', 'true'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
maybeCreate('client').with {
|
|
||||||
options.with {
|
|
||||||
args '--launchTarget', 'forge_dev_client',
|
|
||||||
'--username', 'Dev',
|
|
||||||
'--version', project.name,
|
|
||||||
'--accessToken', '0',
|
|
||||||
'--userType', 'mojang',
|
|
||||||
'--versionType', 'release'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
maybeCreate('server').with {
|
|
||||||
options.with {
|
|
||||||
args '--launchTarget', 'forge_dev_server'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
maybeCreate('gameTestServer').with {
|
|
||||||
options.with {
|
|
||||||
args '--launchTarget', 'forge_dev_server_gametest',
|
|
||||||
'--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
maybeCreate('data').with {
|
|
||||||
options.with {
|
|
||||||
args '--launchTarget', 'forge_dev_data',
|
|
||||||
'--all',
|
|
||||||
'--existing', existing
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
maybeCreate('clientData').with {
|
|
||||||
options.with {
|
|
||||||
args '--launchTarget', 'forge_dev_client_data',
|
|
||||||
'--all',
|
|
||||||
'--existing', existing
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
genAllData.configure {
|
|
||||||
it.dependsOn forgedev.runs.getByName('data').with(sourceSet).run, forgedev.runs.getByName('clientData').with(sourceSet).run
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void test(@Nullable String mods, @Nullable File output) {
|
|
||||||
final project = this.project
|
|
||||||
final genAllData = this.ext.genAllData
|
|
||||||
|
|
||||||
project.with {
|
|
||||||
final SourceSet sourceSet = getJava().getSourceSets().named("test").get()
|
|
||||||
forgedev.runs.with {
|
|
||||||
final File existing = sourceSet.getResources().getSrcDirs()[0]
|
|
||||||
|
|
||||||
configureEach {
|
|
||||||
it.with {
|
|
||||||
var runName = it.name.toLowerCase(Locale.ENGLISH)
|
|
||||||
options.with(sourceSet).with {
|
|
||||||
systemProperty 'forgedev.enableTestMods', 'true'
|
|
||||||
}
|
|
||||||
|
|
||||||
if (runName.contains('data')) {
|
|
||||||
options.with(sourceSet).with {
|
|
||||||
if (mods != null) args('--mod', mods)
|
|
||||||
if (output != null) args('--output', output)
|
|
||||||
args('--existing', existing)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
genAllData.configure {
|
|
||||||
it.dependsOn forgedev.runs.getByName('data').with(sourceSet).run, forgedev.runs.getByName('clientData').with(sourceSet).run
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private TaskProvider<WriteProperties> projectInfo = null
|
|
||||||
TaskProvider<WriteProperties> getProjectInfo() {
|
|
||||||
if (projectInfo == null) {
|
|
||||||
projectInfo = this.project.tasks.register("writeProjectInfo", WriteProperties)
|
|
||||||
projectInfo.configure {
|
|
||||||
it.destinationFile.set(this.project.file('src/main/resources/.project_info.properties'))
|
|
||||||
it.property('name', this.project.rootProject.name + this.project.isolated.path.replaceAll(':', '.'))
|
|
||||||
it.property('output', 'src/main/generated')
|
|
||||||
}
|
|
||||||
this.project.tasks.named("generateResources").configure { it.dependsOn(projectInfo) }
|
|
||||||
this.project.tasks.withType(LicenseCheck).configureEach {
|
|
||||||
it.dependsOn(projectInfo)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return projectInfo
|
|
||||||
}
|
|
||||||
TaskProvider<WriteProperties> projectInfo(Action<? extends WriteProperties> action) {
|
|
||||||
getProjectInfo().configure(action)
|
|
||||||
return getProjectInfo()
|
|
||||||
}
|
|
||||||
void setFlat(boolean value) {
|
|
||||||
projectInfo(task -> task.property('flat', value))
|
|
||||||
}
|
|
||||||
|
|
||||||
private TaskProvider<WriteProperties> projectList = null
|
|
||||||
TaskProvider<WriteProperties> getProjectList() {
|
|
||||||
if (projectList == null) {
|
|
||||||
projectList = this.project.tasks.register("writeProjectList", WriteProperties)
|
|
||||||
projectList.configure { task ->
|
|
||||||
task.destinationFile.set(this.project.layout.buildDirectory.file('project_list.properties'))
|
|
||||||
task.encoding = 'UTF-8'
|
|
||||||
final root = this.project.rootProject.name
|
|
||||||
this.project.rootProject.allprojects.forEach { p ->
|
|
||||||
task.property(root + p.isolated.path.replaceAll(':', '.'), p.isolated.projectDirectory.asFile.absolutePath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return projectList
|
|
||||||
}
|
|
||||||
TaskProvider<WriteProperties> projectList(Action<? extends WriteProperties> action) {
|
|
||||||
getProjectList().configure(action)
|
|
||||||
return getProjectList()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build;
|
|
||||||
|
|
||||||
import net.minecraftforge.gitversion.gradle.GitVersionExtension;
|
|
||||||
import org.gradle.api.Project;
|
|
||||||
import org.gradle.api.artifacts.VersionCatalog;
|
|
||||||
import org.gradle.api.artifacts.VersionCatalogsExtension;
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
|
||||||
|
|
||||||
public abstract class VersionsExtension {
|
|
||||||
private final VersionCatalog libs;
|
|
||||||
|
|
||||||
public final String java, minecraft, forge, forgeSpec, minecraftNext, mcp, changelogBase;
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
public VersionsExtension(Project project) {
|
|
||||||
final var extensions = project.getExtensions();
|
|
||||||
final var gitversion = extensions.getByType(GitVersionExtension.class);
|
|
||||||
libs = extensions.getByType(VersionCatalogsExtension.class).named("bootLibs");
|
|
||||||
java = get("java");
|
|
||||||
minecraft = get("minecraft");
|
|
||||||
minecraftNext = get("minecraft.next");
|
|
||||||
mcp = get("mcp");
|
|
||||||
changelogBase = get("changelog.base");
|
|
||||||
forge = gitversion.of(project.getRootProject()).getVersion();
|
|
||||||
forgeSpec = forge.split("\\.")[0];
|
|
||||||
project.setVersion(minecraft + '-' + gitversion.getVersion());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String get(String name) {
|
|
||||||
var ver = this.libs.findVersion(name);
|
|
||||||
if (ver.isEmpty())
|
|
||||||
throw new IllegalStateException("No version found for " + name);
|
|
||||||
return ver.get().toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-42
@@ -1,42 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.build
|
|
||||||
|
|
||||||
import groovy.json.JsonBuilder
|
|
||||||
import groovy.transform.CompileDynamic
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import org.gradle.api.tasks.Input
|
|
||||||
import org.gradle.api.tasks.OutputFile
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class WriteForgeVersionJson extends DefaultTask {
|
|
||||||
abstract @Input Property<String> getForgeVersion()
|
|
||||||
abstract @Input Property<String> getMinecraftVersion()
|
|
||||||
abstract @Input Property<String> getMcpVersion()
|
|
||||||
|
|
||||||
abstract @OutputFile RegularFileProperty getOutputFile()
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
WriteForgeVersionJson() {}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
@CompileDynamic
|
|
||||||
void exec() {
|
|
||||||
var json = new JsonBuilder()
|
|
||||||
json {
|
|
||||||
forge this.forgeVersion.get()
|
|
||||||
mc this.minecraftVersion.get()
|
|
||||||
mcp this.mcpVersion.get()
|
|
||||||
}
|
|
||||||
this.outputFile.asFile.get().text = json.toPrettyString()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+403
-117
@@ -1,16 +1,31 @@
|
|||||||
import org.apache.tools.ant.filters.ReplaceTokens
|
import org.apache.tools.ant.filters.ReplaceTokens
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'idea'
|
||||||
id 'eclipse'
|
id 'eclipse'
|
||||||
|
id 'maven-publish'
|
||||||
|
alias libs.plugins.licenser
|
||||||
alias libs.plugins.versions
|
alias libs.plugins.versions
|
||||||
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
alias libs.plugins.renamer
|
||||||
alias libs.plugins.jarsigner
|
alias libs.plugins.jarsigner
|
||||||
alias libs.plugins.forgedev
|
id 'net.minecraftforge.forgedev'
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
gradleutils.displayName = 'Forge'
|
gradleutils.displayName = 'Forge'
|
||||||
|
group = 'net.minecraftforge'
|
||||||
description = 'Modifications to Minecraft to enable mod developers.'
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
|
// NOTE: See settings.gradle for all the referenceable version variables.
|
||||||
|
// All subprojects (that apply 'net.minecraftforge.forge.build.convention') will have these available.
|
||||||
|
println "Version: $version"
|
||||||
|
|
||||||
|
java.toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
|
||||||
jarSigner.autoDetect('forge')
|
jarSigner.autoDetect('forge')
|
||||||
|
|
||||||
// We have to tell ForgeDev to use the exact versions of tools we ship in the installer
|
// We have to tell ForgeDev to use the exact versions of tools we ship in the installer
|
||||||
@@ -25,24 +40,34 @@ fdtools {
|
|||||||
javaLauncher = javaToolchains.launcherFor(java.toolchain)
|
javaLauncher = javaToolchains.launcherFor(java.toolchain)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
renamerTools {
|
||||||
|
configure('classes') {
|
||||||
|
artifact = buildLibs.renamer.get().toString() + ':all'
|
||||||
|
}
|
||||||
|
configure('srg2source') {
|
||||||
|
version = buildLibs.srg2source.get().version
|
||||||
|
javaLauncher = javaToolchains.launcherFor(java.toolchain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* This is used for debugging, comparing all published artifacts against actual production
|
/* This is used for debugging, comparing all published artifacts against actual production
|
||||||
forgedev.validatePublish {
|
forgedev.validatePublish {
|
||||||
task {
|
task {
|
||||||
baseBranch = 'upstream/26.1.2'
|
baseBranch = 'upstream/1.21.11'
|
||||||
versionPrefix = versions.minecraft
|
versionPrefix = minecraftVersion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
final minecraftFiles = forgedev.minecraftFiles(versions.minecraft)
|
final minecraftFiles = forgedev.minecraftFiles(minecraftVersion)
|
||||||
|
|
||||||
final mcpBase = forgedev.mcpBase {
|
final mcpBase = forgedev.mcpBase {
|
||||||
mcpVersion = "${versions.minecraft}-${versions.mcp}"
|
mcpVersion = "${minecraftVersion}-${project.ext.mcpVersion}"
|
||||||
|
mappingChannel = mappingsChannel
|
||||||
|
mappingVersion = mappingsVersion
|
||||||
accessTransformers.from file('src/main/resources/META-INF/accesstransformer.cfg')
|
accessTransformers.from file('src/main/resources/META-INF/accesstransformer.cfg')
|
||||||
sideAnnotationStrippers.from file('src/main/resources/forge.sas')
|
sideAnnotationStrippers.from file('src/main/resources/forge.sas')
|
||||||
}
|
}
|
||||||
forgedev.provideFile('metadata', mcpBase.metadata)
|
|
||||||
|
|
||||||
forgedev.patches {
|
forgedev.patches {
|
||||||
base = mcpBase
|
base = mcpBase
|
||||||
@@ -55,12 +80,34 @@ tasks.register('setup') {
|
|||||||
dependsOn forgedev.patches.apply
|
dependsOn forgedev.patches.apply
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
named('main') {
|
||||||
|
resources.srcDir 'src/main/generated'
|
||||||
|
}
|
||||||
|
named('test') {
|
||||||
|
resources.srcDir 'src/test/generated'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
license {
|
license {
|
||||||
|
header = file('LICENSE-header.txt')
|
||||||
|
|
||||||
include 'net/minecraftforge/'
|
include 'net/minecraftforge/'
|
||||||
exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
|
exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
|
||||||
|
|
||||||
|
tasks.tap {
|
||||||
|
register('main') {
|
||||||
|
files.from files('src/main/java')
|
||||||
|
}
|
||||||
|
|
||||||
|
register('test') {
|
||||||
|
files.from files('src/test/java')
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
changelog {
|
changelog {
|
||||||
|
from changelogBase
|
||||||
publishAll = false
|
publishAll = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,9 +127,17 @@ configurations {
|
|||||||
extendsFrom(bootstrap)
|
extendsFrom(bootstrap)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
register('installerextra') {
|
||||||
|
transitive = false
|
||||||
|
extendsFrom(bootstrap)
|
||||||
|
}
|
||||||
|
|
||||||
named('api') {
|
named('api') {
|
||||||
extendsFrom(installer)
|
extendsFrom(installer)
|
||||||
// Inherit vanilla Minecraft's dependencies, and let downstream access them
|
}
|
||||||
|
|
||||||
|
named('implementation') {
|
||||||
|
// Inherit vanilla Minecraft's dependencies
|
||||||
extendsFrom(mcpBase.dependencyConfiguration)
|
extendsFrom(mcpBase.dependencyConfiguration)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +179,14 @@ dependencies {
|
|||||||
installer projects.lowcodelanguage
|
installer projects.lowcodelanguage
|
||||||
installer projects.mclanguage
|
installer projects.mclanguage
|
||||||
installer projects.forgeTransformers
|
installer projects.forgeTransformers
|
||||||
|
|
||||||
|
// Remove when we bump to a version with no srg names, as this is needed to map srg->official at runtimes
|
||||||
|
installerextra("de.oceanlabs.mcp:mcp_config:${mcpBase.mcpVersion.get().toString()}:srg2off")
|
||||||
|
|
||||||
|
// Get the zip file with csv's of srg->mapepd for Runtime SRG->Mapped reflection remapping
|
||||||
|
// This is also only needed during dev time, and automatically added to the dep list by Mavenizer for userdev
|
||||||
|
// We shouldn't need this anymore now that we use runtime official mappings, but some of our code still references SRG names via reflection at dev time
|
||||||
|
runtimeOnly files(mcpBase.mappingZip)
|
||||||
runtimeOnly files(mcpBase.extra)
|
runtimeOnly files(mcpBase.extra)
|
||||||
|
|
||||||
runtimeOnly libs.bootstrap
|
runtimeOnly libs.bootstrap
|
||||||
@@ -133,12 +195,106 @@ dependencies {
|
|||||||
annotationProcessor libs.eventbus.validator
|
annotationProcessor libs.eventbus.validator
|
||||||
}
|
}
|
||||||
|
|
||||||
convention.basicRuns('forge', file('src/main/generated/'))
|
|
||||||
|
|
||||||
final EXTRA_TXTS = [
|
final EXTRA_TXTS = [
|
||||||
file('LICENSE.txt'),
|
file('LICENSE.txt'),
|
||||||
changelog.task.flatMap(task -> task.outputFile)
|
changelog.task.flatMap(task -> task.outputFile)
|
||||||
]
|
]
|
||||||
|
forgedev.runs {
|
||||||
|
configureEach {
|
||||||
|
options {
|
||||||
|
workingDir = layout.projectDirectory.dir("runs/$name")
|
||||||
|
|
||||||
|
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
|
args '--gameDir', '.'
|
||||||
|
jvmArgs '-Djava.net.preferIPv6Addresses=system'
|
||||||
|
|
||||||
|
systemProperty 'bsl.debug', 'true'
|
||||||
|
systemProperty 'terminal.jline', 'true'
|
||||||
|
with(sourceSets.test) {
|
||||||
|
systemProperty 'forge.enableGameTest', 'true'
|
||||||
|
systemProperty 'forgedev.enableTestMods', 'true'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create('client') {
|
||||||
|
options {
|
||||||
|
systemProperty 'eventbus.api.strictRuntimeChecks', 'true'
|
||||||
|
systemProperty 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
|
||||||
|
|
||||||
|
args '--launchTarget', 'forge_dev_client',
|
||||||
|
'--username', 'Dev',
|
||||||
|
'--version', project.name,
|
||||||
|
'--accessToken', '0',
|
||||||
|
'--userType', 'mojang',
|
||||||
|
'--versionType', 'release',
|
||||||
|
'--assetsDir', '{assets_root}',
|
||||||
|
'--assetIndex', '{asset_index}'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create('server') {
|
||||||
|
options {
|
||||||
|
args '--launchTarget', 'forge_dev_server'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create('gameTestServer') {
|
||||||
|
options {
|
||||||
|
args '--launchTarget', 'forge_dev_server_gametest'
|
||||||
|
args '--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create('data') {
|
||||||
|
options {
|
||||||
|
args '--launchTarget', 'forge_dev_data',
|
||||||
|
'--all',
|
||||||
|
'--existing', sourceSets.main.resources.srcDirs[0],
|
||||||
|
'--assetsDir', '{assets_root}',
|
||||||
|
'--assetIndex', '{asset_index}'
|
||||||
|
|
||||||
|
with(sourceSets.main) {
|
||||||
|
args '--mod', 'forge',
|
||||||
|
'--output', rootProject.file('src/main/generated/')
|
||||||
|
}
|
||||||
|
|
||||||
|
with(sourceSets.test) {
|
||||||
|
args '--mod', '.+',
|
||||||
|
'--existing', sourceSets.test.resources.srcDirs[0],
|
||||||
|
'--output', rootProject.file('src/test/generated/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create('clientData') {
|
||||||
|
options {
|
||||||
|
args '--all',
|
||||||
|
'--existing', sourceSets.main.resources.srcDirs[0],
|
||||||
|
'--assetsDir', '{assets_root}',
|
||||||
|
'--assetIndex', '{asset_index}'
|
||||||
|
|
||||||
|
with(sourceSets.main) {
|
||||||
|
args '--launchTarget', 'forge_dev_client_data',
|
||||||
|
'--mod', 'forge',
|
||||||
|
'--output', rootProject.file('src/main/generated/'),
|
||||||
|
'--mod', 'forge'
|
||||||
|
}
|
||||||
|
|
||||||
|
with(sourceSets.test) {
|
||||||
|
args '--launchTarget', 'forge_dev',
|
||||||
|
'--launchEntry', 'minecraft/net.minecraft.client.data.Main',
|
||||||
|
'--launchData',
|
||||||
|
'--mod', '.+',
|
||||||
|
'--existing', sourceSets.test.resources.srcDirs[0],
|
||||||
|
'--output', rootProject.file('src/test/generated/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tasks.register('genAllData') {
|
||||||
|
dependsOn forgedev.runs.data.run, forgedev.runs.data.runTest, forgedev.runs.clientData.run, forgedev.runs.clientData.runTest
|
||||||
|
}
|
||||||
|
|
||||||
final serverShim = forgedev.shim {
|
final serverShim = forgedev.shim {
|
||||||
config {
|
config {
|
||||||
@@ -147,6 +303,7 @@ final serverShim = forgedev.shim {
|
|||||||
}
|
}
|
||||||
classpath {
|
classpath {
|
||||||
libraries configurations.installer
|
libraries configurations.installer
|
||||||
|
libraries configurations.installerextra
|
||||||
library tasks.named('universalJar', Jar)
|
library tasks.named('universalJar', Jar)
|
||||||
library forgedev.binaryPatches('server').apply, 'server'
|
library forgedev.binaryPatches('server').apply, 'server'
|
||||||
serverBundle.fileProvider(minecraftFiles.server)
|
serverBundle.fileProvider(minecraftFiles.server)
|
||||||
@@ -158,28 +315,30 @@ final serverShim = forgedev.shim {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final finalizeSpawn = forgedev.methodCallFinder('findFinalizeSpawnTargets') {
|
final finalizeSpawn = forgedev.methodCallFinder('findFinalizeSpawnTargets') {
|
||||||
jar.fileProvider(mcpBase.classes)
|
jar = tasks.named('renameClientOfficial').flatMap{ it.output } //.fileProvider(mcpBase.classes)
|
||||||
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json')
|
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json')
|
||||||
blacklist 'net/minecraft/world/level/BaseSpawner' // Ignore this class as we special case it.
|
blacklist 'net/minecraft/world/level/BaseSpawner' // Ignore this class as we special case it.
|
||||||
invokeVirtual('finalizeSpawn', '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;')
|
invokeVirtual('finalizeSpawn', '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;')
|
||||||
}
|
}
|
||||||
|
|
||||||
forgedev.validateDeprecations(tasks.named('jar', Jar)) {
|
forgedev.validateDeprecations(tasks.named('jar', Jar)) {
|
||||||
mcVersion = versions.minecraft
|
mcVersion = minecraftVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
forgedev.checks() {
|
forgedev.checks() {
|
||||||
base = mcpBase
|
base = mcpBase
|
||||||
ats {}
|
ats {
|
||||||
|
mappings.fileProvider(mcpBase.map2Srg)
|
||||||
|
}
|
||||||
sas {}
|
sas {}
|
||||||
execs {}
|
execs { }
|
||||||
|
|
||||||
patches {
|
patches {
|
||||||
dependsOn forgedev.patches.make
|
dependsOn forgedev.patches.make
|
||||||
patchDir = forgedev.patches.patches
|
patchDir = forgedev.patches.patches
|
||||||
patchesWithS2SArtifact = [
|
patchesWithS2SArtifact = [
|
||||||
'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
|
'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
|
||||||
'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
|
'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,13 +365,22 @@ tasks.named('jar', Jar) {
|
|||||||
attributes([
|
attributes([
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.forge'
|
'Automatic-Module-Name': 'net.minecraftforge.forge'
|
||||||
])
|
])
|
||||||
gradleutils.manifestDefaults(it, 'net/minecraftforge/versions/forge/')
|
attributes([
|
||||||
gradleutils.manifestDefaults(it, 'net/minecraftforge/versions/mcp/', [
|
'Specification-Title' : gradleutils.displayName.get(),
|
||||||
|
'Specification-Vendor' : gradleutils.vendor.get(),
|
||||||
|
'Specification-Version' : gitversion.info.tag,
|
||||||
|
'Implementation-Title' : project.group,
|
||||||
|
'Implementation-Vendor' : gradleutils.vendor.get(),
|
||||||
|
'Implementation-Version': forgeVersion
|
||||||
|
], 'net/minecraftforge/versions/forge/')
|
||||||
|
attributes([
|
||||||
'Specification-Title' : 'Minecraft',
|
'Specification-Title' : 'Minecraft',
|
||||||
'Specification-Version' : versions.minecraft,
|
'Specification-Vendor' : gradleutils.vendor.get(),
|
||||||
|
'Specification-Version' : minecraftVersion,
|
||||||
'Implementation-Title' : 'MCP',
|
'Implementation-Title' : 'MCP',
|
||||||
'Implementation-Version': versions.mcp
|
'Implementation-Vendor' : gradleutils.vendor.get(),
|
||||||
])
|
'Implementation-Version': mcpVersion
|
||||||
|
], 'net/minecraftforge/versions/mcp/')
|
||||||
}
|
}
|
||||||
jarSigner.sign(it)
|
jarSigner.sign(it)
|
||||||
}
|
}
|
||||||
@@ -226,17 +394,39 @@ final universalJar = tasks.register('universalJar', Jar) {
|
|||||||
jarSigner.sign(it)
|
jarSigner.sign(it)
|
||||||
}
|
}
|
||||||
|
|
||||||
final sourcesJarAll = tasks.register('sourcesJarAll', Jar) {
|
final map2Tsrg = renamer.convert('map2Tsrg', mcpBase.map2Srg) // Remove when we bump renamer to version that supports gziped files (on MC version change)
|
||||||
archiveClassifier = 'sources-all'
|
final reobfJar = renamer.classes('srgJar', tasks.named('jar', Jar)) {
|
||||||
from(sourceSets.main.allJava.srcDirs)
|
libraries.setFrom(configurations.compileClasspath)
|
||||||
|
mappings map2Tsrg
|
||||||
|
archiveClassifier = 'srg'
|
||||||
|
}
|
||||||
|
final universalJarSrg = tasks.register('universalJarSrg', Jar) {
|
||||||
|
from (zipTree(reobfJar.flatMap { it.output } )) {
|
||||||
|
exclude(forgedev.filterVanilla(mcpBase.classes))
|
||||||
|
}
|
||||||
|
manifest = universalJar.get().manifest
|
||||||
|
archiveClassifier = 'universal-srg'
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
final sourcesSrg = renamer.sources(sourceSets.main) {
|
||||||
|
apply {
|
||||||
|
archiveClassifier = 'sources-srg'
|
||||||
|
mappings mcpBase.map2Srg
|
||||||
|
excFiles.from files('src/main/resources/forge.exc')
|
||||||
|
}
|
||||||
|
extract {
|
||||||
|
mustRunAfter(forgedev.patches.apply)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Our sources, plus the patches we do to Vanilla Minecraft
|
|
||||||
final sourcesJar = tasks.register('sourcesJar', Jar) {
|
final sourcesJar = tasks.register('sourcesJar', Jar) {
|
||||||
archiveClassifier = 'sources'
|
archiveClassifier = 'sources'
|
||||||
from(sourceSets.main.allJava.srcDirs - forgedev.patches.patched.asFile.get())
|
// If we don't need to reobf we can just do this
|
||||||
mustRunAfter(forgedev.patches.make)
|
//from(sourceSets.main.allJava.srcDirs - forgedev.patches.patched.asFile.get())
|
||||||
from(forgedev.patches.patches) {
|
dependsOn(sourcesSrg.apply)
|
||||||
|
from(zipTree(sourcesSrg.apply.flatMap{ it.output })) {
|
||||||
|
exclude { forgedev.patches.patched.file(it.path).get().asFile.exists() }
|
||||||
|
}
|
||||||
|
from(forgedev.userDev.patches.flatMap{ it.output }) {
|
||||||
into 'patches/'
|
into 'patches/'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -245,7 +435,7 @@ forgedev.userDev {
|
|||||||
base(mcpBase)
|
base(mcpBase)
|
||||||
|
|
||||||
config {
|
config {
|
||||||
universal universalJar
|
universal universalJarSrg
|
||||||
sources sourcesJar
|
sources sourcesJar
|
||||||
addLibraries(configurations.installer)
|
addLibraries(configurations.installer)
|
||||||
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
|
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
|
||||||
@@ -259,7 +449,7 @@ forgedev.userDev {
|
|||||||
parents = []
|
parents = []
|
||||||
main = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
main = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
args '--gameDir', '.'
|
args '--gameDir', '.'
|
||||||
jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32'
|
jvmArgs '-Djava.net.preferIPv6Addresses=system'
|
||||||
client = it.name.containsIgnoreCase('client')
|
client = it.name.containsIgnoreCase('client')
|
||||||
environment 'MCP_MAPPINGS', '{mcp_mappings}'
|
environment 'MCP_MAPPINGS', '{mcp_mappings}'
|
||||||
}
|
}
|
||||||
@@ -295,33 +485,40 @@ forgedev.userDev {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
patches {
|
patches {
|
||||||
modified.setFrom(sourcesJarAll.flatMap { it.archiveFile })
|
modified.setFrom(sourcesSrg.apply.flatMap{ it.output })
|
||||||
}
|
}
|
||||||
binaryPatches {
|
binaryPatches {
|
||||||
mustRunAfter(forgedev.patches.make)
|
patches.setFrom(forgedev.patches.apply.flatMap { it.output })
|
||||||
patches.setFrom(forgedev.patches.patches)
|
dirty.setFrom(reobfJar.flatMap { it.output })
|
||||||
dirty.setFrom(tasks.named('jar', Jar).flatMap { it.archiveFile })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
forgedev.userdevCompatibility(versions.minecraft) {
|
forgedev.userdevCompatibility(minecraftVersion) {
|
||||||
clean = mcpBase.classes
|
clean = mcpBase.classesRaw
|
||||||
dirty = tasks.named('jar', Jar)
|
dirty = reobfJar
|
||||||
}
|
}
|
||||||
|
|
||||||
// region Installer tasks, Not needed when we simplify the installer/remove obf
|
// region Installer tasks, Not needed when we simplify the installer/remove obf
|
||||||
final clientBinPatches = forgedev.binaryPatches('client') {
|
final renameOfficial = (side, inputProvider, mappingsProvider) -> {
|
||||||
clean = minecraftFiles.client
|
renamer.classes('rename' + side + 'Official') {
|
||||||
// Workaround for 3rd party launcher issues, marker needed to locate MC, store needed to fix zlib-ng issues
|
additionalArgs = ['--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
|
||||||
apply {
|
input.fileProvider(inputProvider)
|
||||||
store = true
|
libraries = mcpBase.dependencyConfiguration
|
||||||
marker = '.forge_patched_minecraft'
|
mappings mappingsProvider
|
||||||
|
output = layout.buildDirectory.file("libs/rename-${side.toLowerCase()}-official.jar")
|
||||||
|
logFile = layout.buildDirectory.file("libs/rename-${side.toLowerCase()}-official.log")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
final serverBinPatches = forgedev.binaryPatches('server') {
|
final clientOfficial = renameOfficial('Client', minecraftFiles.client, minecraftFiles.clientMappings)
|
||||||
clean = minecraftFiles.serverExtracted
|
final serverOfficial = renameOfficial('Server', minecraftFiles.serverExtracted, minecraftFiles.serverMappings)
|
||||||
apply { store = true }
|
final clientBinPatches = forgedev.binaryPatches('client') {
|
||||||
|
clean = clientOfficial.flatMap { it.output }
|
||||||
}
|
}
|
||||||
|
final serverBinPatches = forgedev.binaryPatches('server') {
|
||||||
|
clean = serverOfficial.flatMap { it.output }
|
||||||
|
}
|
||||||
|
final sanitizedClientMappings = renamer.convert("cleanClientMappings", minecraftFiles.clientMappings)
|
||||||
|
final sanitizedServerMappings = renamer.convert("cleanServerMappings", minecraftFiles.serverMappings)
|
||||||
// endregion
|
// endregion
|
||||||
|
|
||||||
forgedev.installer {
|
forgedev.installer {
|
||||||
@@ -332,6 +529,8 @@ forgedev.installer {
|
|||||||
// Add extra libraries
|
// Add extra libraries
|
||||||
pack serverShim.jar // The Server executable jar IS needed to be packed, as the installer would need a spec bump in order to download it
|
pack serverShim.jar // The Server executable jar IS needed to be packed, as the installer would need a spec bump in order to download it
|
||||||
pack universalJar // I don't think this is strictly needed to be packed anymore, will need to double check later
|
pack universalJar // I don't think this is strictly needed to be packed anymore, will need to double check later
|
||||||
|
// This isn't actually needed, but its here for some reason, probably wasn't deleted when then installer process was cleaned up
|
||||||
|
library mcpBase.mcpArtifact.get()
|
||||||
|
|
||||||
launcherLibrary universalJar
|
launcherLibrary universalJar
|
||||||
// We configure the launcher here to keep the order for easier diff, after publishing, move this to the LauncherJson configuration below
|
// We configure the launcher here to keep the order for easier diff, after publishing, move this to the LauncherJson configuration below
|
||||||
@@ -340,11 +539,13 @@ forgedev.installer {
|
|||||||
generated(clientBinPatches.apply, 'client')
|
generated(clientBinPatches.apply, 'client')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
launcherLibraries configurations.installerextra
|
||||||
launcherLibraries configurations.installer
|
launcherLibraries configurations.installer
|
||||||
|
|
||||||
final launcherId = "${versions.minecraft}-${project.name}-${versions.forge}"
|
final launcherId = "${minecraftVersion}-${project.name}-${forgeVersion}"
|
||||||
final installertools = tool(buildLibs.installertools)
|
final installertools = tool(buildLibs.installertools)
|
||||||
final binarypatcher = tool(buildLibs.binarypatcher)
|
final binarypatcher = tool(buildLibs.binarypatcher)
|
||||||
|
final renamer = tool(buildLibs.renamer)
|
||||||
|
|
||||||
jar {
|
jar {
|
||||||
from(EXTRA_TXTS)
|
from(EXTRA_TXTS)
|
||||||
@@ -360,8 +561,8 @@ forgedev.installer {
|
|||||||
|
|
||||||
final argsFile = rootProject.file('server_files/args.txt')
|
final argsFile = rootProject.file('server_files/args.txt')
|
||||||
final tokens = [tokens: [
|
final tokens = [tokens: [
|
||||||
SHIM_JAR_FILE: serverShim.jar.get().archiveFileName.get(),
|
SHIM_JAR_FILE: serverShim.jar.get().archiveFileName.get(),
|
||||||
MAVEN_PATH: forgedev.mavenArtifact.directory
|
MAVEN_PATH: forgedev.mavenArtifact.directory
|
||||||
]]
|
]]
|
||||||
from(argsFile) {
|
from(argsFile) {
|
||||||
filter(tokens, ReplaceTokens)
|
filter(tokens, ReplaceTokens)
|
||||||
@@ -385,62 +586,79 @@ forgedev.installer {
|
|||||||
json {
|
json {
|
||||||
icon = rootProject.file('icon.ico')
|
icon = rootProject.file('icon.ico')
|
||||||
executable serverShim.jar
|
executable serverShim.jar
|
||||||
minecraft = versions.minecraft
|
minecraft = minecraftVersion
|
||||||
profileVersion = launcherId
|
profileVersion = launcherId
|
||||||
|
|
||||||
final projectArtifact = "${project.group}:${project.name}:${project.version}"
|
final projectArtifact = "${project.group}:${project.name}:${project.version}"
|
||||||
|
|
||||||
data 'MC_UNPACKED', "[net.minecraft:client:${versions.minecraft}]", "[net.minecraft:server:${versions.minecraft}:unpacked]"
|
data 'MOJMAPS', "[net.minecraft:client:${minecraftVersion}:mappings@tsrg]", "[net.minecraft:server:${minecraftVersion}:mappings@tsrg]"
|
||||||
|
data 'MOJMAPS_SHA', sanitizedClientMappings.flatMap{ it.output }, sanitizedServerMappings.flatMap{ it.output }
|
||||||
|
|
||||||
|
data 'MC_UNPACKED', "[net.minecraft:client:${minecraftVersion}]", "[net.minecraft:server:${minecraftVersion}:unpacked]"
|
||||||
data 'MC_UNPACKED_SHA', minecraftFiles.client, minecraftFiles.serverExtracted
|
data 'MC_UNPACKED_SHA', minecraftFiles.client, minecraftFiles.serverExtracted
|
||||||
|
|
||||||
|
data 'MC_OFF', "[net.minecraft:client:${minecraftVersion}:official]", "[net.minecraft:server:${minecraftVersion}:official]"
|
||||||
|
data 'MC_OFF_SHA', clientOfficial.flatMap { it.output }, serverOfficial.flatMap { it.output }
|
||||||
|
|
||||||
data 'BINPATCH', '/data/client.lzma', '/data/server.lzma'
|
data 'BINPATCH', '/data/client.lzma', '/data/server.lzma'
|
||||||
data 'PATCHED', "[$projectArtifact:client]", "[$projectArtifact:server]"
|
data 'PATCHED', "[$projectArtifact:client]", "[$projectArtifact:server]"
|
||||||
data 'PATCHED_SHA', clientBinPatches.apply.flatMap { it.output }, serverBinPatches.apply.flatMap { it.output }
|
data 'PATCHED_SHA', clientBinPatches.apply.flatMap { it.output }, serverBinPatches.apply.flatMap { it.output }
|
||||||
|
|
||||||
|
def rename = (side, input) -> {
|
||||||
|
step(renamer) {
|
||||||
|
sides = [side]
|
||||||
|
args = [
|
||||||
|
'--input', input,
|
||||||
|
'--output', '{MC_OFF}',
|
||||||
|
'--names', '{MOJMAPS}',
|
||||||
|
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
|
||||||
|
]
|
||||||
|
cache '{MC_OFF}', '{MC_OFF_SHA}'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
steps = [
|
steps = [
|
||||||
extract(installertools) {
|
extract(installertools) {
|
||||||
side = 'server'
|
side = 'server'
|
||||||
archive '{INSTALLER}'
|
archive '{INSTALLER}'
|
||||||
extract 'data/README.txt', '{ROOT}/README.txt'
|
extract 'data/README.txt', '{ROOT}/README.txt'
|
||||||
extract 'data/run.sh', '{ROOT}/run.sh'
|
extract 'data/run.sh', '{ROOT}/run.sh'
|
||||||
executable '{ROOT}/run.sh'
|
executable '{ROOT}/run.sh'
|
||||||
extract 'data/run.bat', '{ROOT}/run.bat'
|
extract 'data/run.bat', '{ROOT}/run.bat'
|
||||||
optional 'data/user_jvm_args.txt', '{ROOT}/user_jvm_args.txt'
|
optional 'data/user_jvm_args.txt', '{ROOT}/user_jvm_args.txt'
|
||||||
extract 'data/unix_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/unix_args.txt"
|
extract 'data/unix_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/unix_args.txt"
|
||||||
extract 'data/win_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/win_args.txt"
|
extract 'data/win_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/win_args.txt"
|
||||||
},
|
},
|
||||||
extractBundle(installertools) {
|
extractBundle(installertools) {
|
||||||
side = 'server'
|
side = 'server'
|
||||||
libraries()
|
libraries()
|
||||||
},
|
},
|
||||||
extractBundle(installertools) {
|
extractBundle(installertools) {
|
||||||
side = 'server'
|
side = 'server'
|
||||||
jar '{MINECRAFT_JAR}', '{MC_UNPACKED}'
|
jar '{MINECRAFT_JAR}', '{MC_UNPACKED}'
|
||||||
cache '{MC_UNPACKED}', '{MC_UNPACKED_SHA}'
|
cache '{MC_UNPACKED}', '{MC_UNPACKED_SHA}'
|
||||||
},
|
},
|
||||||
step(binarypatcher) {
|
step(installertools) {
|
||||||
side = 'server'
|
args = [
|
||||||
args = [
|
'--task', 'DOWNLOAD_MOJMAPS',
|
||||||
'--clean', '{MC_UNPACKED}',
|
'--sanitize',
|
||||||
'--output', '{PATCHED}',
|
'--version', minecraftVersion,
|
||||||
'--apply', '{BINPATCH}',
|
'--side', '{SIDE}',
|
||||||
'--data', '--unpatched',
|
'--output', '{MOJMAPS}'
|
||||||
'--store'
|
]
|
||||||
]
|
cache '{MOJMAPS}', '{MOJMAPS_SHA}'
|
||||||
cache '{PATCHED}', '{PATCHED_SHA}'
|
},
|
||||||
},
|
rename.call('server', '{MC_UNPACKED}'),
|
||||||
step(binarypatcher) {
|
rename.call('client', '{MINECRAFT_JAR}'),
|
||||||
side = 'client'
|
step(binarypatcher) {
|
||||||
args = [
|
args = [
|
||||||
'--clean', '{MINECRAFT_JAR}',
|
'--clean', '{MC_OFF}',
|
||||||
'--output', '{PATCHED}',
|
'--output', '{PATCHED}',
|
||||||
'--apply', '{BINPATCH}',
|
'--apply', '{BINPATCH}',
|
||||||
'--data', '--unpatched',
|
'--data', '--unpatched'
|
||||||
'--store',
|
]
|
||||||
'--marker', '.forge_patched_minecraft'
|
cache '{PATCHED}', '{PATCHED_SHA}'
|
||||||
]
|
}
|
||||||
cache '{PATCHED}', '{PATCHED_SHA}'
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -451,10 +669,59 @@ forgedev.installer {
|
|||||||
librariesLast = false // Makes libraries be added before args
|
librariesLast = false // Makes libraries be added before args
|
||||||
|
|
||||||
id = launcherId
|
id = launcherId
|
||||||
inheritsFrom = versions.minecraft
|
inheritsFrom = minecraftVersion
|
||||||
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
gameArgs = [ '--launchTarget', 'forge_client' ]
|
gameArgs = [ '--launchTarget', 'forge_client' ]
|
||||||
jvmArgs = [ '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32' ]
|
jvmArgs = [ '-Djava.net.preferIPv6Addresses=system' ]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) {
|
||||||
|
gradleVersion = '9.5.0'
|
||||||
|
scriptFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradlew")
|
||||||
|
jarFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradle/wrapper/gradle-wrapper.jar")
|
||||||
|
}
|
||||||
|
|
||||||
|
final mdkZip = tasks.register('mdkZip', Zip) {
|
||||||
|
dependsOn mdkGradleWrapper
|
||||||
|
|
||||||
|
archiveBaseName = project.name
|
||||||
|
archiveClassifier = 'mdk'
|
||||||
|
archiveVersion = project.version
|
||||||
|
destinationDirectory = file('build/libs')
|
||||||
|
from(EXTRA_TXTS)
|
||||||
|
|
||||||
|
from mdkGradleWrapper.map(Wrapper.&getScriptFile)
|
||||||
|
from mdkGradleWrapper.map(Wrapper.&getBatchScript)
|
||||||
|
into('gradle/wrapper/') {
|
||||||
|
from mdkGradleWrapper.map(Wrapper.&getJarFile)
|
||||||
|
from mdkGradleWrapper.map(Wrapper.&getPropertiesFile)
|
||||||
|
}
|
||||||
|
from(rootProject.file('mdk/')){
|
||||||
|
rootProject.file('mdk/gitignore.txt').eachLine {
|
||||||
|
if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
|
||||||
|
exclude it
|
||||||
|
}
|
||||||
|
filter(ReplaceTokens, tokens: [
|
||||||
|
FORGE_VERSION: forgeVersion,
|
||||||
|
FORGE_GROUP: project.group,
|
||||||
|
FORGE_NAME: project.name,
|
||||||
|
MC_VERSION: minecraftVersion,
|
||||||
|
MAPPING_CHANNEL: mappingsChannel,
|
||||||
|
MAPPING_VERSION: mappingsVersion,
|
||||||
|
FORGE_SPEC_VERSION: gitversion.info.tag.split("\\.")[0],
|
||||||
|
MC_NEXT_VERSION: minecraftNextVersion,
|
||||||
|
EVENTBUS_VERSION: libs.versions.eventbus.get()
|
||||||
|
])
|
||||||
|
rename 'gitignore\\.txt', '.gitignore'
|
||||||
|
rename 'gitattributes\\.txt', '.gitattributes'
|
||||||
|
}
|
||||||
|
from(rootProject.file('src/test/java/com/example/examplemod/')) {
|
||||||
|
into('src/main/java/com/example/examplemod/')
|
||||||
|
}
|
||||||
|
from(rootProject.file('src/test/generated/mdk_datagen/')) {
|
||||||
|
into('src/main/resources/')
|
||||||
|
exclude '**/.cache/'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -522,8 +789,8 @@ tasks.named('javadoc', Javadoc) {
|
|||||||
|
|
||||||
bottom = "Minecraft Forge is an open source modding API for Minecraft: Java Edition, licensed under the Lesser GNU General Public License, version 2.1."
|
bottom = "Minecraft Forge is an open source modding API for Minecraft: Java Edition, licensed under the Lesser GNU General Public License, version 2.1."
|
||||||
windowTitle = "Minecraft Forge API ${version}"
|
windowTitle = "Minecraft Forge API ${version}"
|
||||||
docTitle = "Minecraft Forge API - ${versions.forge} for Minecraft ${versions.minecraft}"
|
docTitle = "Minecraft Forge API - ${forgeVersion} for Minecraft ${minecraftVersion}"
|
||||||
header = "<div style=\"margin-top: 9px;padding: 5px 6px;\"><strong>${versions.forge} for Minecraft ${versions.minecraft}</strong></div>"
|
header = "<div style=\"margin-top: 9px;padding: 5px 6px;\"><strong>${forgeVersion} for Minecraft ${minecraftVersion}</strong></div>"
|
||||||
}
|
}
|
||||||
|
|
||||||
doLast {
|
doLast {
|
||||||
@@ -535,36 +802,53 @@ tasks.named('javadoc', Javadoc) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
final mdkZip = forgedev.consumeFile("mdkZip", project(':forge-mdk'))
|
|
||||||
convention.publish {
|
publishing {
|
||||||
artifact universalJar
|
repositories {
|
||||||
artifact forgedev.installer.jar
|
maven gradleutils.publishingForgeMaven
|
||||||
artifact(mdkZip.map { it.singleFile }) {
|
}
|
||||||
builtBy mdkZip
|
|
||||||
classifier = "mdk"
|
publications.register('mavenJava', MavenPublication) {
|
||||||
extension = "zip"
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
artifact universalJar
|
||||||
|
artifact universalJarSrg
|
||||||
|
artifact forgedev.installer.jar
|
||||||
|
artifact mdkZip
|
||||||
|
artifact forgedev.userDev.jar
|
||||||
|
artifact sourcesJar
|
||||||
|
artifact serverShim.jar
|
||||||
|
|
||||||
|
pom {
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
artifact forgedev.userDev.jar
|
|
||||||
artifact sourcesJar
|
|
||||||
artifact serverShim.jar
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// These are debugging tasks that are only used when developing ForgeDevPlugin, to bulk test task's config/caching
|
// These are debugging tasks that are only used when developing ForgeDevPlugin, to bulk test task's config/caching
|
||||||
// region ForgeDev Tests
|
// region ForgeDev Tests
|
||||||
def all = tasks.register('all') {}
|
def all = tasks.register('all') {}
|
||||||
afterEvaluate {
|
afterEvaluate {
|
||||||
if (gradle.startParameter.taskNames.contains('all')) {
|
if (gradle.startParameter.taskNames.contains('all')) {
|
||||||
tasks.forEach { task -> // This forces everything to be realized, which is why we have the startParameter check
|
tasks.forEach { task -> // This forces everything to be realized, which is why we have the startParameter check
|
||||||
if (!gradle.startParameter.isTaskGraph() && task.name.startsWith('run')) return
|
if (!gradle.startParameter.isTaskGraph() && task.name.startsWith('run')) return
|
||||||
if (task.name in [all.name, 'dependencyInsight', 'dependencies', 'dependencyUpdates', 'init', 'buildEnvironment', 'idea',
|
if (task.name in [all.name, 'dependencyInsight', 'dependencies', 'dependencyUpdates', 'init', 'buildEnvironment', 'idea',
|
||||||
'eclipse', 'javaToolchains', 'outgoingVariants', 'projects', 'properties', 'resolvableConfigurations', 'tasks', 'updateDaemonJvm',
|
'eclipse', 'javaToolchains', 'outgoingVariants', 'projects', 'properties', 'resolvableConfigurations', 'tasks', 'updateDaemonJvm',
|
||||||
'generateActionsWorkflow'
|
'generateActionsWorkflow'
|
||||||
]) return
|
]) return
|
||||||
if (task.name.startsWith('clean')) return
|
if (task.name.startsWith('clean')) return
|
||||||
if (task.name == 'checkJarCompatibility') return // This doesn't work in FG6 dev, I think it's cuz we check vs srg names. Will need to look at later
|
if (task.name == 'checkJarCompatibility') return // This doesn't work in FG6 dev, I think it's cuz we check vs srg names. Will need to look at later
|
||||||
all.configure { dependsOn(task) }
|
all.configure { dependsOn(task) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
@@ -575,10 +859,11 @@ tasks.withType(AbstractTestTask).configureEach {
|
|||||||
}
|
}
|
||||||
// This shouldn't be needed according to the Gradle devs, as we never run these commands together.
|
// This shouldn't be needed according to the Gradle devs, as we never run these commands together.
|
||||||
// But in another case of Gradle being gradle, here we are
|
// But in another case of Gradle being gradle, here we are
|
||||||
[ 'makePatches', 'compileJava', 'checkLicenseMain', 'updateLicenseMain', 'sourcesJar', 'sourcesJarAll' ]
|
[ 'makePatches', 'compileJava', 'checkLicenseMain', 'updateLicenseMain', 'sourcesJar' ]
|
||||||
.each{ tasks.named(it).configure{ mustRunAfter forgedev.patches.apply }}
|
.each{ tasks.named(it).configure{ mustRunAfter forgedev.patches.apply }}
|
||||||
forgedev.runs.configureEach {
|
forgedev.runs.configureEach {
|
||||||
run.configure { dependsOn finalizeSpawn }
|
run.configure { dependsOn finalizeSpawn}
|
||||||
|
runTest.configure { dependsOn finalizeSpawn}
|
||||||
}
|
}
|
||||||
// run gradlew dependencyUpdates --no-parallel
|
// run gradlew dependencyUpdates --no-parallel
|
||||||
//noinspection UnnecessaryQualifiedReference
|
//noinspection UnnecessaryQualifiedReference
|
||||||
@@ -586,5 +871,6 @@ tasks.named('dependencyUpdates', com.github.benmanes.gradle.versions.updates.Dep
|
|||||||
resolutionStrategy {
|
resolutionStrategy {
|
||||||
mcpBase.dependencies.get().forEach {dep -> force(dep) } // Force all vanilla dependencies to their correct versions
|
mcpBase.dependencies.get().forEach {dep -> force(dep) } // Force all vanilla dependencies to their correct versions
|
||||||
force(earlyDisplayLibs.slf4j.jdk14) // Force slf4j implementation, its tied to the api from the manifest
|
force(earlyDisplayLibs.slf4j.jdk14) // Force slf4j implementation, its tied to the api from the manifest
|
||||||
|
force('de.oceanlabs.mcp:mcp_config:' + bootLibs.versions.mcp) // Don't warn abou MCPConfig updates
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-11
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
MinecraftForge
|
MinecraftForge
|
||||||
=============
|
=============
|
||||||
[][Download]
|
[][Download]
|
||||||
[][Download] [][Discord] [][Patreon]
|
)][Download] [][Discord] [][Patreon]
|
||||||
|
|
||||||
Forge is a free, open-source modding API all of your favourite mods use!
|
Forge is a free, open-source modding API all of your favourite mods use!
|
||||||
@@ -34,13 +34,12 @@ For support and questions, visit [the Support Forum][Support-Forum] or [the Forg
|
|||||||
|
|
||||||
We require the version of Java that Minecraft requires, which is currently:
|
We require the version of Java that Minecraft requires, which is currently:
|
||||||
|
|
||||||
| Minecraft | Java |
|
| Minecraft | Java |
|
||||||
|------------------|-------------------|
|
|---------------|-------------------|
|
||||||
| 26.1+ | [25][Adoptium-25] |
|
| 1.20.6+ | [21][Adoptium-21] |
|
||||||
| 1.20.6 - 1.21.11 | [21][Adoptium-21] |
|
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
||||||
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
| 1.17.1 | [16][Adoptium-16] |
|
||||||
| 1.17.1 | [16][Adoptium-16] |
|
| 1.16.5- | [8][Adoptium-8] |
|
||||||
| 1.16.5- | [8][Adoptium-8] |
|
|
||||||
|
|
||||||
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
||||||
|
|
||||||
@@ -74,14 +73,13 @@ Please ensure you have a valid email address associated with your GitHub account
|
|||||||
### Thanks
|
### Thanks
|
||||||
[](https://www.yourkit.com/)
|
[](https://www.yourkit.com/)
|
||||||
|
|
||||||
YourKit for providing us accesss to their [YourKit Java Profiler] which helps identify bottlenecks and places for improvement.
|
YourKit for providing us accesss to their [YourKit Java Profiler] which helps identify bottlenecks and places for improvment.
|
||||||
|
|
||||||
[Contributing]: ./CONTRIBUTING.md
|
[Contributing]: ./CONTRIBUTING.md
|
||||||
[CLA]: https://cla-assistant.io/MinecraftForge/MinecraftForge
|
[CLA]: https://cla-assistant.io/MinecraftForge/MinecraftForge
|
||||||
|
|
||||||
[Download]: https://files.minecraftforge.net/
|
[Download]: https://files.minecraftforge.net/
|
||||||
|
|
||||||
[Adoptium-25]: https://adoptium.net/temurin/releases/?version=25
|
|
||||||
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
|
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
|
||||||
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
|
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
|
||||||
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
|
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
#!/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
|
|
||||||
+64
-6
@@ -1,20 +1,78 @@
|
|||||||
plugins {
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'maven-publish'
|
||||||
|
alias libs.plugins.licenser
|
||||||
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
gradleutils.displayName = 'FML'
|
gradleutils.displayName = 'FML'
|
||||||
description = 'Core library used for Forge ModLoader.'
|
final vendor = 'Forge Development LLC'
|
||||||
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
compileOnly libs.jetbrains.annotations
|
||||||
|
|
||||||
api libs.eventbus
|
api libs.eventbus
|
||||||
|
|
||||||
implementation projects.fmlloader
|
implementation projects.fmlloader
|
||||||
implementation libs.commons.io
|
implementation libs.commons.io
|
||||||
}
|
}
|
||||||
|
|
||||||
convention.manifest('net/minecraftforge/fml/', [
|
java {
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.fmlcore',
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
'FMLModType' : 'LIBRARY'
|
withSourcesJar()
|
||||||
])
|
}
|
||||||
|
|
||||||
convention.publish()
|
license {
|
||||||
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
|
}
|
||||||
|
changelog {
|
||||||
|
from changelogBase
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.compilerArgs << '-Xlint:-unchecked'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('jar', Jar) {
|
||||||
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.fmlcore',
|
||||||
|
'FMLModType' : 'LIBRARY'
|
||||||
|
])
|
||||||
|
attributes([
|
||||||
|
'Specification-Title' : gradleutils.displayName.get(),
|
||||||
|
'Specification-Vendor' : vendor,
|
||||||
|
'Specification-Version' : '1',
|
||||||
|
'Implementation-Title' : gradleutils.displayName.get(),
|
||||||
|
'Implementation-Version': '1.0',
|
||||||
|
'Implementation-Vendor' : vendor
|
||||||
|
], 'net/minecraftforge/fml/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven gradleutils.publishingForgeMaven
|
||||||
|
}
|
||||||
|
|
||||||
|
publications.register('mavenJava', MavenPublication) {
|
||||||
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
from components.java
|
||||||
|
|
||||||
|
pom {
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ import java.util.function.Supplier;
|
|||||||
/**
|
/**
|
||||||
* Used to allow access to certain things from the game layer
|
* Used to allow access to certain things from the game layer
|
||||||
*/
|
*/
|
||||||
public final class Bindings {
|
public class Bindings {
|
||||||
private Bindings() {}
|
private Bindings() {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +27,7 @@ public final class Bindings {
|
|||||||
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
|
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return A supplier of {@link BusGroup#DEFAULT}
|
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
|
||||||
*/
|
*/
|
||||||
public static Supplier<BusGroup> getForgeBus() {
|
public static Supplier<BusGroup> getForgeBus() {
|
||||||
return PROVIDER.getForgeBusSupplier();
|
return PROVIDER.getForgeBusSupplier();
|
||||||
|
|||||||
@@ -14,14 +14,16 @@ import java.util.List;
|
|||||||
import java.util.function.BooleanSupplier;
|
import java.util.function.BooleanSupplier;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class CrashReportCallables {
|
public class CrashReportCallables
|
||||||
|
{
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final List<ISystemReportExtender> crashCallables = Collections.synchronizedList(new ArrayList<>());
|
private static final List<ISystemReportExtender> crashCallables = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register a custom {@link ISystemReportExtender}
|
* Register a custom {@link ISystemReportExtender}
|
||||||
*/
|
*/
|
||||||
public static void registerCrashCallable(ISystemReportExtender callable) {
|
public static void registerCrashCallable(ISystemReportExtender callable)
|
||||||
|
{
|
||||||
crashCallables.add(callable);
|
crashCallables.add(callable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,15 +33,19 @@ public class CrashReportCallables {
|
|||||||
* @param headerName The name of the system report entry
|
* @param headerName The name of the system report entry
|
||||||
* @param reportGenerator The report generator to be called when a crash report is built
|
* @param reportGenerator The report generator to be called when a crash report is built
|
||||||
*/
|
*/
|
||||||
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator) {
|
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator)
|
||||||
registerCrashCallable(new ISystemReportExtender() {
|
{
|
||||||
|
registerCrashCallable(new ISystemReportExtender()
|
||||||
|
{
|
||||||
@Override
|
@Override
|
||||||
public String getLabel() {
|
public String getLabel()
|
||||||
|
{
|
||||||
return headerName;
|
return headerName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String get() {
|
public String get()
|
||||||
|
{
|
||||||
return reportGenerator.get();
|
return reportGenerator.get();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -52,23 +58,31 @@ public class CrashReportCallables {
|
|||||||
* @param reportGenerator The report generator to be called when a crash report is built
|
* @param reportGenerator The report generator to be called when a crash report is built
|
||||||
* @param active The supplier of the flag to be checked when a crash report is built
|
* @param active The supplier of the flag to be checked when a crash report is built
|
||||||
*/
|
*/
|
||||||
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator, BooleanSupplier active) {
|
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator, BooleanSupplier active)
|
||||||
registerCrashCallable(new ISystemReportExtender() {
|
{
|
||||||
|
registerCrashCallable(new ISystemReportExtender()
|
||||||
|
{
|
||||||
@Override
|
@Override
|
||||||
public String getLabel() {
|
public String getLabel()
|
||||||
|
{
|
||||||
return headerName;
|
return headerName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String get() {
|
public String get()
|
||||||
|
{
|
||||||
return reportGenerator.get();
|
return reportGenerator.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isActive() {
|
public boolean isActive()
|
||||||
try {
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
return active.getAsBoolean();
|
return active.getAsBoolean();
|
||||||
} catch (Throwable t) {
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t);
|
LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -76,7 +90,8 @@ public class CrashReportCallables {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<ISystemReportExtender> allCrashCallables() {
|
public static List<ISystemReportExtender> allCrashCallables()
|
||||||
|
{
|
||||||
return List.copyOf(crashCallables);
|
return List.copyOf(crashCallables);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) Forge Development LLC and contributors
|
||||||
|
* SPDX-License-Identifier: LGPL-2.1-only
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
|
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.lang.invoke.SerializedLambda;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use to execute code conditionally based on sidedness.
|
||||||
|
* <ul>
|
||||||
|
* <li>When you want to call something on one side and return a result {@link #safeCallWhenOn(Dist, Supplier)}</li>
|
||||||
|
* <li>When you want to call one thing on one side, another thing on the other and return a result {@link #safeRunForDist(Supplier, Supplier)}</li>
|
||||||
|
* <li>When you want to run something on one side {@link #safeRunWhenOn(Dist, Supplier)}</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @deprecated Historically, this allowed for safe execution of code on the correct side by exploiting a low-level
|
||||||
|
* detail in Java 8, but in newer versions a simple if check is enough.
|
||||||
|
* <br>
|
||||||
|
* For example:
|
||||||
|
* <pre>{@code
|
||||||
|
* if (FMLEnvironment.dist.isClient()) {
|
||||||
|
* // client code here
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "1.21.5", forRemoval = true)
|
||||||
|
public final class DistExecutor
|
||||||
|
{
|
||||||
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
|
private DistExecutor() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the callable in the supplier only on the specified {@link Dist}.
|
||||||
|
* This method is NOT sided-safe and special care needs to be taken in code using this method that implicit class
|
||||||
|
* loading is not triggered by the Callable.
|
||||||
|
*
|
||||||
|
* This method can cause unexpected ClassNotFound exceptions.
|
||||||
|
*
|
||||||
|
* Use {@link #safeCallWhenOn(Dist, Supplier)} where possible.
|
||||||
|
*
|
||||||
|
* @param dist The dist to run on
|
||||||
|
* @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate dist)
|
||||||
|
* @param <T> The return type from the callable
|
||||||
|
* @return The callable's result
|
||||||
|
* @deprecated use {@link #safeCallWhenOn(Dist, Supplier)} instead. This remains for advanced use cases.
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public static <T> T callWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
|
||||||
|
return unsafeCallWhenOn(dist, toRun);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T unsafeCallWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
|
||||||
|
if (dist == FMLEnvironment.dist) {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return toRun.get().call();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call the SafeCallable when on the correct {@link Dist}.
|
||||||
|
*
|
||||||
|
* <strong>The lambda supplied here is required to be a method reference to a method defined in
|
||||||
|
* another class, otherwise an invalid SafeReferent error will be thrown</strong>
|
||||||
|
* @param dist the dist which this will run on
|
||||||
|
* @param toRun the SafeCallable to run and return the result from
|
||||||
|
* @param <T> The type of the SafeCallable
|
||||||
|
* @return the result of the SafeCallable or null if on the wrong side
|
||||||
|
*/
|
||||||
|
public static <T> T safeCallWhenOn(Dist dist, Supplier<SafeCallable<T>> toRun) {
|
||||||
|
validateSafeReferent(toRun);
|
||||||
|
return callWhenOn(dist, toRun::get);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #callWhenOn(Dist, Supplier)}.
|
||||||
|
*
|
||||||
|
* This method can cause unexpected ClassNotFound exceptions.
|
||||||
|
*
|
||||||
|
* @see #callWhenOn(Dist, Supplier)
|
||||||
|
* @param dist Dist to run this code on
|
||||||
|
* @param toRun The code to run
|
||||||
|
* @deprecated use {@link #safeRunWhenOn(Dist, Supplier)} where possible. Advanced uses only.
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public static void runWhenOn(Dist dist, Supplier<Runnable> toRun) {
|
||||||
|
unsafeRunWhenOn(dist, toRun);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #unsafeCallWhenOn(Dist, Supplier)}.
|
||||||
|
*
|
||||||
|
* This method can cause unexpected ClassNotFoundException problems in common scenarios. Understand the pitfalls of
|
||||||
|
* the way the class verifier works to load classes before using this.
|
||||||
|
*
|
||||||
|
* Use {@link #safeRunWhenOn(Dist, Supplier)} if you can.
|
||||||
|
*
|
||||||
|
* @see #unsafeCallWhenOn(Dist, Supplier)
|
||||||
|
* @param dist Dist to run this code on
|
||||||
|
* @param toRun The code to run
|
||||||
|
*/
|
||||||
|
public static void unsafeRunWhenOn(Dist dist, Supplier<Runnable> toRun) {
|
||||||
|
if (dist == FMLEnvironment.dist) {
|
||||||
|
toRun.get().run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call the supplied SafeRunnable when on the correct Dist.
|
||||||
|
* @param dist The dist to run on
|
||||||
|
* @param toRun The code to run
|
||||||
|
*/
|
||||||
|
public static void safeRunWhenOn(Dist dist, Supplier<SafeRunnable> toRun) {
|
||||||
|
validateSafeReferent(toRun);
|
||||||
|
if (dist == FMLEnvironment.dist) {
|
||||||
|
toRun.get().run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Executes one of the two suppliers, based on which side is active.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Example (replacement for old SidedProxy):<br/>
|
||||||
|
* {@code Proxy p = DistExecutor.runForDist(()->ClientProxy::new, ()->ServerProxy::new);}
|
||||||
|
*
|
||||||
|
* NOTE: the double supplier is required to avoid classloading the secondary target.
|
||||||
|
*
|
||||||
|
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||||
|
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||||
|
* @param <T> The common type to return
|
||||||
|
* @return The returned instance
|
||||||
|
* @deprecated Use {@link #safeRunForDist(Supplier, Supplier)}
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public static <T> T runForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
|
||||||
|
return unsafeRunForDist(clientTarget, serverTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsafe version of {@link #safeRunForDist(Supplier, Supplier)}. Use only when you know what you're doing
|
||||||
|
* and understand why the verifier can cause unexpected ClassNotFoundException crashes even when code is apparently
|
||||||
|
* not sided. Ensure you test both sides fully to be confident in using this.
|
||||||
|
*
|
||||||
|
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||||
|
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||||
|
* @param <T> The common type to return
|
||||||
|
* @return The returned instance
|
||||||
|
*/
|
||||||
|
public static <T> T unsafeRunForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
|
||||||
|
switch (FMLEnvironment.dist)
|
||||||
|
{
|
||||||
|
case CLIENT:
|
||||||
|
return clientTarget.get().get();
|
||||||
|
case DEDICATED_SERVER:
|
||||||
|
return serverTarget.get().get();
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("UNSIDED?");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Executes one of the two suppliers, based on which side is active.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Example (replacement for old SidedProxy):<br/>
|
||||||
|
* {@code Proxy p = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->ServerProxy::new);}
|
||||||
|
*
|
||||||
|
* NOTE: the double supplier is required to avoid classloading the secondary target.
|
||||||
|
*
|
||||||
|
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||||
|
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||||
|
* @param <T> The common type to return
|
||||||
|
* @return The returned instance
|
||||||
|
*/
|
||||||
|
public static <T> T safeRunForDist(Supplier<SafeSupplier<T>> clientTarget, Supplier<SafeSupplier<T>> serverTarget) {
|
||||||
|
validateSafeReferent(clientTarget);
|
||||||
|
validateSafeReferent(serverTarget);
|
||||||
|
switch (FMLEnvironment.dist)
|
||||||
|
{
|
||||||
|
case CLIENT:
|
||||||
|
return clientTarget.get().get();
|
||||||
|
case DEDICATED_SERVER:
|
||||||
|
return serverTarget.get().get();
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("UNSIDED?");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A safe referent. This will assert that it is being called via a separated class method reference. This will
|
||||||
|
* avoid the common pitfalls of {@link #callWhenOn(Dist, Supplier)} above.
|
||||||
|
*
|
||||||
|
* SafeReferents assert that they are defined as a separate method outside the scope of the calling class.
|
||||||
|
*
|
||||||
|
* <strong>Implementations need to be defined in a separate class to the referring site, with appropriate
|
||||||
|
* visibility to be accessible at the callsite (generally, avoid private methods).</strong>
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Valid:<br/>
|
||||||
|
*
|
||||||
|
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->AnotherClass::clientOnlyMethod);}
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Invalid:<br/>
|
||||||
|
*
|
||||||
|
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->()->Minecraft.getInstance().world);}
|
||||||
|
*/
|
||||||
|
public interface SafeReferent {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SafeCallable version of {@link SafeReferent}.
|
||||||
|
* @see SafeReferent
|
||||||
|
* @param <T> The return type of the Callable
|
||||||
|
*/
|
||||||
|
public interface SafeCallable<T> extends SafeReferent, Callable<T>, Serializable {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SafeSupplier version of {@link SafeReferent}
|
||||||
|
* @param <T> The return type of the Supplier
|
||||||
|
*/
|
||||||
|
public interface SafeSupplier<T> extends SafeReferent, Supplier<T>, Serializable {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SafeRunnable version of {@link SafeReferent}
|
||||||
|
*/
|
||||||
|
public interface SafeRunnable extends SafeReferent, Runnable, Serializable {}
|
||||||
|
|
||||||
|
private static final void validateSafeReferent(Supplier<? extends SafeReferent> safeReferentSupplier) {
|
||||||
|
if (FMLEnvironment.production) return;
|
||||||
|
final SafeReferent setter;
|
||||||
|
try {
|
||||||
|
setter = safeReferentSupplier.get();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Typically a class cast exception, just return out, expected.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Class<?> cl = setter.getClass(); cl != null; cl = cl.getSuperclass()) {
|
||||||
|
try {
|
||||||
|
Method m = cl.getDeclaredMethod("writeReplace");
|
||||||
|
m.setAccessible(true);
|
||||||
|
Object replacement = m.invoke(setter);
|
||||||
|
if (!(replacement instanceof SerializedLambda))
|
||||||
|
break;// custom interface implementation
|
||||||
|
SerializedLambda l = (SerializedLambda) replacement;
|
||||||
|
if (Objects.equals(l.getCapturingClass(), l.getImplClass())) {
|
||||||
|
LOGGER.fatal("Detected unsafe referent usage, please view the code at {}",Thread.currentThread().getStackTrace()[3]);
|
||||||
|
throw new RuntimeException("Unsafe Referent usage found in safe referent method");
|
||||||
|
}
|
||||||
|
} catch (NoSuchMethodException e) {
|
||||||
|
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,14 +6,13 @@
|
|||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||||
import org.jspecify.annotations.NullMarked;
|
|
||||||
import org.jspecify.annotations.Nullable;
|
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.function.IntSupplier;
|
import java.util.function.ToIntFunction;
|
||||||
import java.util.function.Supplier;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A mod loading state. During mod loading, the mod loader transitions between states in a defined sorted list of states,
|
* A mod loading state. During mod loading, the mod loader transitions between states in a defined sorted list of states,
|
||||||
@@ -21,7 +20,6 @@ import java.util.function.Supplier;
|
|||||||
*
|
*
|
||||||
* @see IModStateProvider
|
* @see IModStateProvider
|
||||||
*/
|
*/
|
||||||
@NullMarked
|
|
||||||
public interface IModLoadingState {
|
public interface IModLoadingState {
|
||||||
/**
|
/**
|
||||||
* {@return the name of this state}
|
* {@return the name of this state}
|
||||||
@@ -44,21 +42,19 @@ public interface IModLoadingState {
|
|||||||
/**
|
/**
|
||||||
* {@return a function returning a human-friendly message for this state}
|
* {@return a function returning a human-friendly message for this state}
|
||||||
*/
|
*/
|
||||||
Supplier<String> message();
|
Function<ModList, String> message();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return a function that computes the size of this transition based on the size of the modlist.
|
* @return a function that computes the size of this transition based on the size of the modlist.
|
||||||
* Used to compute progress.
|
* Used to compute progress.
|
||||||
*/
|
*/
|
||||||
default IntSupplier size() {
|
ToIntFunction<ModList> size();
|
||||||
return ModList::size;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@return an optional runnable, which runs before starting the transition from this state to the next}
|
* {@return an optional runnable, which runs before starting the transition from this state to the next}
|
||||||
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
||||||
*/
|
*/
|
||||||
@Nullable Runnable inlineRunnable();
|
Optional<Consumer<ModList>> inlineRunnable();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds the transition task for this state with a blank pre-sync and post-sync task.
|
* Builds the transition task for this state with a blank pre-sync and post-sync task.
|
||||||
@@ -69,14 +65,14 @@ public interface IModLoadingState {
|
|||||||
* @return a transition task for this state
|
* @return a transition task for this state
|
||||||
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
||||||
*/
|
*/
|
||||||
default @Nullable CompletableFuture<Void> buildTransition(
|
default Optional<CompletableFuture<Void>> buildTransition(
|
||||||
final Executor syncExecutor,
|
final Executor syncExecutor,
|
||||||
final Executor parallelExecutor,
|
final Executor parallelExecutor,
|
||||||
final ProgressMeter progressBar
|
final ProgressMeter progressBar
|
||||||
) {
|
) {
|
||||||
return buildTransition(syncExecutor, parallelExecutor, progressBar,
|
return buildTransition(syncExecutor, parallelExecutor, progressBar,
|
||||||
_ -> CompletableFuture.completedFuture(null),
|
e -> CompletableFuture.completedFuture(null),
|
||||||
_ -> CompletableFuture.completedFuture(null)
|
e -> CompletableFuture.completedFuture(null)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +87,7 @@ public interface IModLoadingState {
|
|||||||
* @param postSyncTask a function which returns a task to run after event post-dispatch hook
|
* @param postSyncTask a function which returns a task to run after event post-dispatch hook
|
||||||
* @return a transition task for this state
|
* @return a transition task for this state
|
||||||
*/
|
*/
|
||||||
@Nullable CompletableFuture<Void> buildTransition(final Executor syncExecutor,
|
Optional<CompletableFuture<Void>> buildTransition(final Executor syncExecutor,
|
||||||
final Executor parallelExecutor,
|
final Executor parallelExecutor,
|
||||||
final ProgressMeter progressBar,
|
final ProgressMeter progressBar,
|
||||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||||
|
|||||||
@@ -6,16 +6,21 @@
|
|||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
import net.minecraftforge.fml.event.IModBusEvent;
|
import net.minecraftforge.fml.event.IModBusEvent;
|
||||||
|
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||||
|
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.function.BiFunction;
|
import java.util.function.BiFunction;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
public interface IModStateTransition {
|
public interface IModStateTransition {
|
||||||
|
/** Magic value to allow me to optimize the futures list by ignoring the default value without making old methods nullable. */
|
||||||
|
BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> NULL_HOOK = (e, g) -> CompletableFuture.completedFuture(null);
|
||||||
|
|
||||||
static IModStateTransition buildNoopTransition() {
|
static IModStateTransition buildNoopTransition() {
|
||||||
return ModStateTransitionHelper.NOOP;
|
return ModStateTransitionHelper.NOOP;
|
||||||
}
|
}
|
||||||
@@ -35,6 +40,15 @@ public interface IModStateTransition {
|
|||||||
return ModLoadingStage::nextState;
|
return ModLoadingStage::nextState;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This used to allow you to fire multiple events during the transition. However, in doing so it would cause issues with the default
|
||||||
|
* ModContainer's event handlers causing issues such as mod classes being constructed multiple times.
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
|
default Supplier<Stream<EventGenerator<?>>> eventFunctionStream() {
|
||||||
|
return () -> Stream.ofNullable(eventFunction());
|
||||||
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
default <T extends IModBusEvent> EventGenerator<T> eventFunction() {
|
default <T extends IModBusEvent> EventGenerator<T> eventFunction() {
|
||||||
return null;
|
return null;
|
||||||
@@ -43,9 +57,25 @@ public interface IModStateTransition {
|
|||||||
ThreadSelector threadSelector();
|
ThreadSelector threadSelector();
|
||||||
BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator();
|
BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* I think this was meant as a way to do some things for each mod container beforge/after the transition had been sent to the container.
|
||||||
|
* However, the Future returned by this was never linked to the main transition future in any way. Which means that it was run
|
||||||
|
* in parallel and couldn't guarantee the state of the ModContainer.
|
||||||
|
* <p>
|
||||||
|
* Plus all existing code that I could find returned a completedFuture, so I don't think anyone ever used this.
|
||||||
|
* <p>
|
||||||
|
* If I were to add this back it would be a CompletableFuture wrap(ModContainer, CompletableFuture)
|
||||||
|
* <p>
|
||||||
|
* Added magic value NULL_HOOK to allow me to optimize the futures list by ignoring the default value without making this method nullable.
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
|
default BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> preDispatchHook() { return NULL_HOOK; }
|
||||||
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
|
default BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> postDispatchHook() { return NULL_HOOK; }
|
||||||
|
|
||||||
interface EventGenerator<T extends IModBusEvent> extends Function<ModContainer, T> {
|
interface EventGenerator<T extends IModBusEvent> extends Function<ModContainer, T> {
|
||||||
static <FN extends IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) {
|
static <FN extends IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) {
|
||||||
return fn::apply;
|
return fn::apply;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,10 +7,12 @@ package net.minecraftforge.fml;
|
|||||||
|
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public interface ISystemReportExtender extends Supplier<String> {
|
public interface ISystemReportExtender extends Supplier<String>
|
||||||
|
{
|
||||||
String getLabel();
|
String getLabel();
|
||||||
|
|
||||||
default boolean isActive() {
|
default boolean isActive()
|
||||||
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,20 +5,63 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.Spliterator;
|
import java.util.Spliterator;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||||
|
import java.util.concurrent.ConcurrentMap;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import java.util.stream.StreamSupport;
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
public final class InterModComms {
|
public class InterModComms
|
||||||
public record IMCMessage(String senderModId, String modId, String method, Supplier<?> messageSupplier) {}
|
{
|
||||||
|
public record IMCMessage(String senderModId, String modId, String method, Supplier<?> messageSupplier) {
|
||||||
|
|
||||||
private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
/**
|
||||||
|
* Deprecated: use {@link #senderModId()}
|
||||||
|
* @return The modid of the sender. This is supplied by the caller, or by the active mod container context.
|
||||||
|
* Consider it unreliable.
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final String getSenderModId() {
|
||||||
|
return this.senderModId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deprecated: use {@link #modId()}
|
||||||
|
* @return The modid being sent to.
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final String getModId() {
|
||||||
|
return this.modId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deprecated: use {@link #method()}
|
||||||
|
* @return The method being sent to.
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final String getMethod() {
|
||||||
|
return this.method;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param <T> The type of the message.
|
||||||
|
* @return A {@link Supplier} of the message.
|
||||||
|
* Use {@link #messageSupplier()}
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
@Deprecated
|
||||||
|
public final <T> Supplier<T> getMessageSupplier() {
|
||||||
|
return (Supplier<T>) this.messageSupplier;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final ConcurrentMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
||||||
@@ -29,9 +72,8 @@ public final class InterModComms {
|
|||||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||||
*/
|
*/
|
||||||
public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) {
|
public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) {
|
||||||
if (!ModList.isLoaded(modId)) return false;
|
if (!ModList.get().isLoaded(modId)) return false;
|
||||||
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(ModLoadingContext.get().getActiveContainer().getModId(), modId, method, thing));
|
||||||
.add(new IMCMessage(ModLoadingContext.get().getContainer().getModId(), modId, method, thing));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,9 +87,8 @@ public final class InterModComms {
|
|||||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||||
*/
|
*/
|
||||||
public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) {
|
public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) {
|
||||||
if (!ModList.isLoaded(modId)) return false;
|
if (!ModList.get().isLoaded(modId)) return false;
|
||||||
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(senderModId, modId, method, thing));
|
||||||
.add(new IMCMessage(senderModId, modId, method, thing));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +112,7 @@ public final class InterModComms {
|
|||||||
* @return All messages
|
* @return All messages
|
||||||
*/
|
*/
|
||||||
public static Stream<IMCMessage> getMessages(final String modId) {
|
public static Stream<IMCMessage> getMessages(final String modId) {
|
||||||
return getMessages(modId, _ -> true);
|
return getMessages(modId, s->Boolean.TRUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record QueueFilteringSpliterator(
|
private record QueueFilteringSpliterator(
|
||||||
@@ -95,10 +136,13 @@ public final class InterModComms {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean tryAdvance(final Consumer<? super IMCMessage> action) {
|
public boolean tryAdvance(final Consumer<? super IMCMessage> action)
|
||||||
|
{
|
||||||
IMCMessage next;
|
IMCMessage next;
|
||||||
do {
|
do
|
||||||
if (!iterator.hasNext()) {
|
{
|
||||||
|
if (!iterator.hasNext())
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
next = this.iterator.next();
|
next = this.iterator.next();
|
||||||
@@ -113,5 +157,6 @@ public final class InterModComms {
|
|||||||
public Spliterator<IMCMessage> trySplit() {
|
public Spliterator<IMCMessage> trySplit() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ import java.util.Objects;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.BiPredicate;
|
import java.util.function.BiPredicate;
|
||||||
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,6 +41,11 @@ public abstract class ModContainer {
|
|||||||
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
||||||
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
||||||
final Set<ModContainer> dependencies = new HashSet<>();
|
final Set<ModContainer> dependencies = new HashSet<>();
|
||||||
|
/**
|
||||||
|
* If you want to handle the event, override {@link #dispatchConfigEvent(IConfigEvent)}
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
|
protected Optional<Consumer<IConfigEvent>> configHandler = Optional.empty();
|
||||||
|
|
||||||
public ModContainer(IModInfo info) {
|
public ModContainer(IModInfo info) {
|
||||||
this.modId = info.getModId();
|
this.modId = info.getModId();
|
||||||
@@ -53,7 +59,7 @@ public abstract class ModContainer {
|
|||||||
Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) {
|
Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) {
|
||||||
case "MATCH_VERSION" -> // default displaytest checks for version string match
|
case "MATCH_VERSION" -> // default displaytest checks for version string match
|
||||||
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
|
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
|
||||||
(incoming, _) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
|
(incoming, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
|
||||||
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
|
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
|
||||||
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
|
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
|
||||||
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
|
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
|
||||||
@@ -132,7 +138,12 @@ public abstract class ModContainer {
|
|||||||
configs.put(modConfig.getType(), modConfig);
|
configs.put(modConfig.getType(), modConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void dispatchConfigEvent(IConfigEvent event) {}
|
public void dispatchConfigEvent(IConfigEvent event) {
|
||||||
|
var handler = configHandler.orElse(null);
|
||||||
|
if (handler != null) {
|
||||||
|
handler.accept(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Does this mod match the supplied mod?
|
* Does this mod match the supplied mod?
|
||||||
|
|||||||
@@ -5,14 +5,14 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.LoadingModList;
|
|
||||||
import net.minecraftforge.forgespi.language.IModFileInfo;
|
import net.minecraftforge.forgespi.language.IModFileInfo;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||||
|
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||||
import net.minecraftforge.forgespi.locating.IModFile;
|
import net.minecraftforge.forgespi.locating.IModFile;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -30,36 +30,33 @@ import java.util.stream.Stream;
|
|||||||
* Master list of all mods - game-side version. This is classloaded in the game scope and
|
* Master list of all mods - game-side version. This is classloaded in the game scope and
|
||||||
* can dispatch game level events as a result.
|
* can dispatch game level events as a result.
|
||||||
*/
|
*/
|
||||||
public final class ModList {
|
public class ModList {
|
||||||
private ModList() {}
|
private static ModList INSTANCE;
|
||||||
|
private final List<IModFileInfo> modFiles;
|
||||||
|
private final List<IModInfo> sortedList;
|
||||||
|
private final Map<String, IModFileInfo> fileById;
|
||||||
|
private List<ModContainer> mods;
|
||||||
|
private Map<String, ModContainer> indexedMods;
|
||||||
|
private List<ModFileScanData> modFileScanData;
|
||||||
|
private List<ModContainer> sortedContainers;
|
||||||
|
|
||||||
private static final List<IModFileInfo> MOD_FILES;
|
private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
|
||||||
private static final List<IModInfo> SORTED_LIST;
|
var modFileInfos = this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
|
||||||
private static final Map<String, IModFileInfo> FILE_BY_ID;
|
this.sortedList = sortedList.stream().map(IModInfo.class::cast).toList();
|
||||||
private static List<ModContainer> mods;
|
|
||||||
private static Map<String, ModContainer> indexedMods;
|
|
||||||
private static List<ModContainer> sortedContainers;
|
|
||||||
|
|
||||||
static {
|
|
||||||
var loadingModFiles = LoadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList();
|
|
||||||
var loadingSortedList = LoadingModList.getMods();
|
|
||||||
|
|
||||||
var modFileInfos = MOD_FILES = loadingModFiles.stream().map(ModFile::getModFileInfo).toList();
|
|
||||||
SORTED_LIST = loadingSortedList.stream().map(IModInfo.class::cast).toList();
|
|
||||||
var byId = new HashMap<String, IModFileInfo>();
|
var byId = new HashMap<String, IModFileInfo>();
|
||||||
for (var file : modFileInfos) {
|
for (var file : modFileInfos) {
|
||||||
for (var mod : file.getMods())
|
for (var mod : file.getMods())
|
||||||
byId.put(mod.getModId(), mod.getOwningFile());
|
byId.put(mod.getModId(), mod.getOwningFile());
|
||||||
}
|
}
|
||||||
FILE_BY_ID = Map.copyOf(byId);
|
this.fileById = Map.copyOf(byId);
|
||||||
CrashReportCallables.registerCrashCallable("Mod List", ModList::crashReport);
|
CrashReportCallables.registerCrashCallable("Mod List", this::crashReport);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String getModContainerState(String modId) {
|
private String getModContainerState(String modId) {
|
||||||
return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE");
|
return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String fileToLine(IModFile mf) {
|
private String fileToLine(IModFile mf) {
|
||||||
var mainMod = mf.getModInfos().getFirst();
|
var mainMod = mf.getModInfos().getFirst();
|
||||||
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
||||||
mainMod.getDisplayName(),
|
mainMod.getDisplayName(),
|
||||||
@@ -69,92 +66,92 @@ public final class ModList {
|
|||||||
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String crashReport() {
|
private String crashReport() {
|
||||||
return "\n" + applyForEachModFile(ModList::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
return "\n" + applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void init() {}
|
public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) {
|
||||||
|
INSTANCE = new ModList(modFiles, sortedList);
|
||||||
public static List<IModFileInfo> getModFiles() {
|
return INSTANCE;
|
||||||
return MOD_FILES;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IModFileInfo getModFileById(String modid) {
|
public static ModList get() {
|
||||||
return FILE_BY_ID.get(modid);
|
return INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void setLoadedMods(final List<ModContainer> modContainers) {
|
public List<IModFileInfo> getModFiles() {
|
||||||
mods = modContainers;
|
return modFiles;
|
||||||
sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> SORTED_LIST.indexOf(c.getModInfo()))).toList();
|
|
||||||
indexedMods = modContainers.stream().collect(Collectors.toUnmodifiableMap(ModContainer::getModId, Function.identity()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void clearLoadedMods() {
|
public IModFileInfo getModFileById(String modid) {
|
||||||
mods = List.of();
|
return this.fileById.get(modid);
|
||||||
indexedMods = Map.of();
|
}
|
||||||
sortedContainers = List.of();
|
|
||||||
|
void setLoadedMods(final List<ModContainer> modContainers) {
|
||||||
|
this.mods = modContainers;
|
||||||
|
this.sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> sortedList.indexOf(c.getModInfo()))).toList();
|
||||||
|
this.indexedMods = modContainers.stream().collect(Collectors.toMap(ModContainer::getModId, Function.identity()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static <T> Optional<T> getModObjectById(String modId) {
|
public <T> Optional<T> getModObjectById(String modId) {
|
||||||
return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o);
|
return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Optional<? extends ModContainer> getModContainerById(String modId) {
|
public Optional<? extends ModContainer> getModContainerById(String modId) {
|
||||||
return Optional.ofNullable(indexedMods == null ? null : indexedMods.get(modId));
|
return Optional.ofNullable(this.indexedMods.get(modId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Optional<? extends ModContainer> getModContainerByObject(Object obj) {
|
public Optional<? extends ModContainer> getModContainerByObject(Object obj) {
|
||||||
return mods.stream().filter(mc -> mc.getMod() == obj).findFirst();
|
return mods.stream().filter(mc -> mc.getMod() == obj).findFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<IModInfo> getMods() {
|
public List<IModInfo> getMods() {
|
||||||
return SORTED_LIST;
|
return this.sortedList;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isLoaded(String modTarget) {
|
public boolean isLoaded(String modTarget) {
|
||||||
return indexedMods.containsKey(modTarget);
|
return this.indexedMods.containsKey(modTarget);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int size() {
|
public int size() {
|
||||||
return mods.size();
|
return mods.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<ModFileScanData> getAllScanData() {
|
public List<ModFileScanData> getAllScanData() {
|
||||||
final class LazyInit {
|
if (modFileScanData == null) {
|
||||||
private LazyInit() {}
|
modFileScanData = this.sortedList.stream().
|
||||||
private static final List<ModFileScanData> MOD_FILE_SCAN_DATA = SORTED_LIST.stream()
|
map(IModInfo::getOwningFile).
|
||||||
.map(IModInfo::getOwningFile)
|
filter(Objects::nonNull).
|
||||||
.filter(Objects::nonNull)
|
map(IModFileInfo::getFile).
|
||||||
.map(IModFileInfo::getFile)
|
distinct().
|
||||||
.distinct()
|
map(IModFile::getScanResult).
|
||||||
.map(IModFile::getScanResult)
|
toList();
|
||||||
.toList();
|
|
||||||
}
|
}
|
||||||
return LazyInit.MOD_FILE_SCAN_DATA;
|
return modFileScanData;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void forEachModFile(Consumer<IModFile> fileConsumer) {
|
public void forEachModFile(Consumer<IModFile> fileConsumer) {
|
||||||
MOD_FILES.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
|
modFiles.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
|
public <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
|
||||||
return MOD_FILES.stream().map(IModFileInfo::getFile).map(function);
|
return modFiles.stream().map(IModFileInfo::getFile).map(function);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
public void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
||||||
indexedMods.forEach(modContainerConsumer);
|
indexedMods.forEach(modContainerConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
|
public void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
|
||||||
sortedContainers.forEach(containerConsumer);
|
this.sortedContainers.forEach(containerConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<ModContainer> getLoadedMods() {
|
public List<ModContainer> getLoadedMods() {
|
||||||
return sortedContainers;
|
return this.sortedContainers;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
public <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
||||||
return indexedMods.values().stream().map(function);
|
return indexedMods.values().stream().map(function);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,11 +5,16 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||||
import net.minecraftforge.fml.event.IModBusEvent;
|
import net.minecraftforge.fml.event.IModBusEvent;
|
||||||
import net.minecraftforge.fml.loading.*;
|
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||||
|
import net.minecraftforge.fml.loading.FMLLoader;
|
||||||
|
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
|
||||||
|
import net.minecraftforge.fml.loading.LoadingModList;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier;
|
import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||||
|
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
@@ -66,18 +71,48 @@ import static net.minecraftforge.fml.Logging.LOADING;
|
|||||||
* and completes the mod loading sequence.</dd>
|
* and completes the mod loading sequence.</dd>
|
||||||
* </dl>
|
* </dl>
|
||||||
*/
|
*/
|
||||||
public final class ModLoader {
|
public class ModLoader {
|
||||||
private ModLoader() {}
|
|
||||||
|
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private static final ArrayList<ModLoadingException> LOADING_EXCEPTIONS = new ArrayList<>();
|
private final LoadingModList loadingModList;
|
||||||
private static final ArrayList<ModLoadingWarning> LOADING_WARNINGS = new ArrayList<>();
|
|
||||||
private static final Consumer<String> STATUS_CONSUMER = StartupNotificationManager.modLoaderConsumer().orElse(_ -> {});
|
private final List<ModLoadingException> loadingExceptions;
|
||||||
private static final HashSet<IModLoadingState> COMPLETED_STATES = new HashSet<>();
|
private final Set<IModInfo> erroredModInfos;
|
||||||
|
private final List<ModLoadingWarning> loadingWarnings;
|
||||||
|
private final ModStateManager stateManager;
|
||||||
private static boolean loadingStateValid;
|
private static boolean loadingStateValid;
|
||||||
|
private final Consumer<String> statusConsumer = StartupNotificationManager.modLoaderConsumer().orElse(msg -> {});
|
||||||
|
private final Set<IModLoadingState> completedStates = new HashSet<>();
|
||||||
|
private ModList modList;
|
||||||
|
|
||||||
|
private ModLoader() {
|
||||||
|
var loadingModList = this.loadingModList = FMLLoader.getLoadingModList();
|
||||||
|
var loadingExceptions = this.loadingExceptions = loadingModList.getErrors().stream()
|
||||||
|
.flatMap(ModLoadingException::fromEarlyException)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
this.loadingWarnings = loadingModList.getBrokenFiles().stream()
|
||||||
|
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
if (loadingExceptions.isEmpty()) {
|
||||||
|
this.erroredModInfos = Collections.emptySet();
|
||||||
|
} else {
|
||||||
|
this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
|
this.erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
|
||||||
|
}
|
||||||
|
loadingModList.getModFiles().stream()
|
||||||
|
.filter(ModFileInfo::missingLicense)
|
||||||
|
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(this.erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
|
||||||
|
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
|
||||||
|
.forEach(this.loadingExceptions::add);
|
||||||
|
this.stateManager = new ModStateManager();
|
||||||
|
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
||||||
|
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
||||||
|
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
||||||
|
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
|
||||||
|
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
|
||||||
|
}
|
||||||
|
|
||||||
private static String computeLanguageList() {
|
private static String computeLanguageList() {
|
||||||
return "\n" + LanguageLoadingProvider
|
return "\n" + FMLLoader.getLanguageLoadingProvider()
|
||||||
.applyForEach(lp -> lp.name() + '@' + lp.getClass().getPackage().getImplementationVersion())
|
.applyForEach(lp -> lp.name() + '@' + lp.getClass().getPackage().getImplementationVersion())
|
||||||
.collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
.collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||||
}
|
}
|
||||||
@@ -91,51 +126,37 @@ public final class ModLoader {
|
|||||||
collect(Collectors.joining("\n\t\t","\t\t",""));
|
collect(Collectors.joining("\n\t\t","\t\t",""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ModLoader get() {
|
||||||
|
return LazyInit.INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class LazyInit {
|
||||||
|
private static final ModLoader INSTANCE = new ModLoader();
|
||||||
|
private LazyInit() {}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run on the primary starting thread by ClientModLoader and ServerModLoader
|
* Run on the primary starting thread by ClientModLoader and ServerModLoader
|
||||||
* @param syncExecutor An executor to run tasks on the main thread
|
* @param syncExecutor An executor to run tasks on the main thread
|
||||||
* @param parallelExecutor An executor to run tasks on a parallel loading thread pool
|
* @param parallelExecutor An executor to run tasks on a parallel loading thread pool
|
||||||
* @param periodicTask Optional periodic task to perform on the main thread while other activities run
|
* @param periodicTask Optional periodic task to perform on the main thread while other activities run
|
||||||
*/
|
*/
|
||||||
public static void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var loadingExceptions = LoadingModList.getErrors().stream()
|
|
||||||
.flatMap(ModLoadingException::fromEarlyException)
|
|
||||||
.toList();
|
|
||||||
ModLoader.LOADING_EXCEPTIONS.addAll(loadingExceptions);
|
|
||||||
LOADING_WARNINGS.addAll(LoadingModList.getBrokenFiles().stream()
|
|
||||||
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
|
|
||||||
.toList());
|
|
||||||
Set<IModInfo> erroredModInfos;
|
|
||||||
if (loadingExceptions.isEmpty()) {
|
|
||||||
erroredModInfos = Collections.emptySet();
|
|
||||||
} else {
|
|
||||||
erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
|
|
||||||
erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
|
|
||||||
}
|
|
||||||
LoadingModList.getModFiles().stream()
|
|
||||||
.filter(ModFileInfo::missingLicense)
|
|
||||||
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
|
|
||||||
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
|
|
||||||
.forEach(LOADING_EXCEPTIONS::add);
|
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
|
|
||||||
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
|
|
||||||
|
|
||||||
ForgeFeature.registerFeature("javaVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.BOTH, System.getProperty("java.version")));
|
ForgeFeature.registerFeature("javaVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.BOTH, System.getProperty("java.version")));
|
||||||
ForgeFeature.registerFeature("openGLVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.CLIENT, ImmediateWindowHandler.getGLVersion()));
|
ForgeFeature.registerFeature("openGLVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.CLIENT, ImmediateWindowHandler.getGLVersion()));
|
||||||
loadingStateValid = true;
|
loadingStateValid = true;
|
||||||
FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask);
|
FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask);
|
||||||
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList(),
|
||||||
LOGGER.fatal(CORE, "Error during pre-loading phase", LOADING_EXCEPTIONS.getFirst());
|
loadingModList.getMods());
|
||||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
if (!this.loadingExceptions.isEmpty()) {
|
||||||
ModList.clearLoadedMods();
|
LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.getFirst());
|
||||||
|
statusConsumer.accept("ERROR DURING MOD LOADING");
|
||||||
|
modList.setLoadedMods(Collections.emptyList());
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
throw new LoadingFailedException(loadingExceptions);
|
||||||
}
|
}
|
||||||
var failedBounds = new ArrayList<ForgeFeature.Bound>();
|
var failedBounds = new ArrayList<ForgeFeature.Bound>();
|
||||||
for (var mod : LoadingModList.getMods()) {
|
for (var mod : loadingModList.getMods()) {
|
||||||
for (var feature : mod.getForgeFeatures()) {
|
for (var feature : mod.getForgeFeatures()) {
|
||||||
if (!ForgeFeature.testFeature(FMLEnvironment.dist, feature))
|
if (!ForgeFeature.testFeature(FMLEnvironment.dist, feature))
|
||||||
failedBounds.add(feature);
|
failedBounds.add(feature);
|
||||||
@@ -144,8 +165,8 @@ public final class ModLoader {
|
|||||||
|
|
||||||
if (!failedBounds.isEmpty()) {
|
if (!failedBounds.isEmpty()) {
|
||||||
LOGGER.fatal(CORE, "Failed to validate feature bounds for mods: {}", failedBounds);
|
LOGGER.fatal(CORE, "Failed to validate feature bounds for mods: {}", failedBounds);
|
||||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
statusConsumer.accept("ERROR DURING MOD LOADING");
|
||||||
ModList.clearLoadedMods();
|
modList.setLoadedMods(Collections.emptyList());
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
throw new LoadingFailedException(failedBounds.stream()
|
throw new LoadingFailedException(failedBounds.stream()
|
||||||
.map(fb -> new ModLoadingException(fb.modInfo(), ModLoadingStage.CONSTRUCT, "fml.modloading.feature.missing", null, fb, ForgeFeature.featureValue(fb)))
|
.map(fb -> new ModLoadingException(fb.modInfo(), ModLoadingStage.CONSTRUCT, "fml.modloading.feature.missing", null, fb, ForgeFeature.featureValue(fb)))
|
||||||
@@ -153,18 +174,18 @@ public final class ModLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final var modContainers = new HashMap<String, ModContainer>();
|
final var modContainers = new HashMap<String, ModContainer>();
|
||||||
for (var file : LoadingModList.getModFiles()) {
|
for (var file : loadingModList.getModFiles()) {
|
||||||
var containers = buildMods(file.getFile());
|
var containers = this.buildMods(file.getFile());
|
||||||
for (var container : containers)
|
for (var container : containers)
|
||||||
modContainers.put(container.getModId(), container);
|
modContainers.put(container.getModId(), container);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
if (!loadingExceptions.isEmpty()) {
|
||||||
LOGGER.fatal(CORE, "Failed to initialize mod containers", LOADING_EXCEPTIONS.getFirst());
|
LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.getFirst());
|
||||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
statusConsumer.accept("ERROR DURING MOD LOADING");
|
||||||
ModList.clearLoadedMods();
|
modList.setLoadedMods(Collections.emptyList());
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
throw new LoadingFailedException(loadingExceptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gather all dependencies, so we can make sure they have finished their transition events before we fire ours
|
// Gather all dependencies, so we can make sure they have finished their transition events before we fire ours
|
||||||
@@ -187,33 +208,34 @@ public final class ModLoader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ModList.setLoadedMods(modContainers.values().stream().toList());
|
modList.setLoadedMods(modContainers.values().stream().toList());
|
||||||
var stateList = ModStateManager.getStates(ModLoadingPhase.GATHER);
|
this.modList = modList;
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
var stateList = stateManager.getStates(ModLoadingPhase.GATHER);
|
||||||
|
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(this.modList)).sum());
|
||||||
for (IModLoadingState mls : stateList) {
|
for (IModLoadingState mls : stateList) {
|
||||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
}
|
}
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = ModStateManager.getStates(ModLoadingPhase.LOAD);
|
var stateList = stateManager.getStates(ModLoadingPhase.LOAD);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
||||||
for (IModLoadingState mls : stateList) {
|
for (IModLoadingState mls : stateList) {
|
||||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
}
|
}
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = ModStateManager.getStates(ModLoadingPhase.COMPLETE);
|
var stateList = stateManager.getStates(ModLoadingPhase.COMPLETE);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
||||||
for (IModLoadingState mls : stateList) {
|
for (IModLoadingState mls : stateList) {
|
||||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
}
|
}
|
||||||
|
|
||||||
var modBusGroups = Set.of(
|
var modBusGroups = Set.of(
|
||||||
ModList.getLoadedMods().stream()
|
modList.getLoadedMods().stream()
|
||||||
.map(ModContainer::getModBusGroup)
|
.map(ModContainer::getModBusGroup)
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.toArray(BusGroup[]::new)
|
.toArray(BusGroup[]::new)
|
||||||
@@ -223,11 +245,11 @@ public final class ModLoader {
|
|||||||
}
|
}
|
||||||
parallelExecutor.execute(BusGroup.DEFAULT::trim);
|
parallelExecutor.execute(BusGroup.DEFAULT::trim);
|
||||||
|
|
||||||
STATUS_CONSUMER.accept("Mod loading complete - %d mods loaded".formatted(ModList.size()));
|
statusConsumer.accept("Mod loading complete - %d mods loaded".formatted(this.modList.size()));
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) {
|
private void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) {
|
||||||
if (!isLoadingStateValid()) {
|
if (!isLoadingStateValid()) {
|
||||||
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
||||||
return;
|
return;
|
||||||
@@ -235,25 +257,25 @@ public final class ModLoader {
|
|||||||
progressBar.label(progressBar.name() + " working");
|
progressBar.label(progressBar.name() + " working");
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
|
|
||||||
var inlineRunnable = state.inlineRunnable();
|
var inlineRunnable = state.inlineRunnable().orElse(null);
|
||||||
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
||||||
|
|
||||||
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar);
|
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar).orElse(null);
|
||||||
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
||||||
|
|
||||||
COMPLETED_STATES.add(state);
|
completedStates.add(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void handleInlineTransition(final Runnable transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
|
private void handleInlineTransition(final Consumer<ModList> transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
|
||||||
var pb = StartupMessageManager.addProgressBar("State transition " + state.name() + " running", 0);
|
var pb = StartupMessageManager.addProgressBar("State transition " + state.name() + " running", 0);
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
transition.run();
|
transition.accept(this.modList);
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
pb.complete();
|
pb.complete();
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) {
|
private void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) {
|
||||||
while (!transition.isDone()) {
|
while (!transition.isDone()) {
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
}
|
}
|
||||||
@@ -267,7 +289,7 @@ public final class ModLoader {
|
|||||||
.anyMatch(obj -> !(obj instanceof ModLoadingException));
|
.anyMatch(obj -> !(obj instanceof ModLoadingException));
|
||||||
if (hasNotModLoadingEx) {
|
if (hasNotModLoadingEx) {
|
||||||
LOGGER.fatal("Encountered non-modloading exceptions!", e);
|
LOGGER.fatal("Encountered non-modloading exceptions!", e);
|
||||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
statusConsumer.accept("ERROR DURING MOD LOADING");
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,12 +298,12 @@ public final class ModLoader {
|
|||||||
.map(ModLoadingException.class::cast)
|
.map(ModLoadingException.class::cast)
|
||||||
.toList();
|
.toList();
|
||||||
LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state.name(), modLoadingExceptions.size());
|
LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state.name(), modLoadingExceptions.size());
|
||||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
statusConsumer.accept("ERROR DURING MOD LOADING");
|
||||||
throw new LoadingFailedException(modLoadingExceptions);
|
throw new LoadingFailedException(modLoadingExceptions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<ModContainer> buildMods(final IModFile modFile) {
|
private List<ModContainer> buildMods(final IModFile modFile) {
|
||||||
final Map<String, IModInfo> modInfoMap = new HashMap<>();
|
final Map<String, IModInfo> modInfoMap = new HashMap<>();
|
||||||
for (var mod : modFile.getModFileInfo().getMods())
|
for (var mod : modFile.getModFileInfo().getMods())
|
||||||
modInfoMap.put(mod.getModId(), mod);
|
modInfoMap.put(mod.getModId(), mod);
|
||||||
@@ -311,14 +333,14 @@ public final class ModLoader {
|
|||||||
missingMods.removeAll(modIds);
|
missingMods.removeAll(modIds);
|
||||||
LOGGER.fatal(LOADING, "The following mods are missing, but have classes in the jar: {}", missingMods);
|
LOGGER.fatal(LOADING, "The following mods are missing, but have classes in the jar: {}", missingMods);
|
||||||
|
|
||||||
LOADING_EXCEPTIONS.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
|
loadingExceptions.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove errored mod containers
|
// remove errored mod containers
|
||||||
return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).toList();
|
return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap,
|
private ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap,
|
||||||
final String modId, final IModLanguageProvider.IModLanguageLoader languageLoader
|
final String modId, final IModLanguageProvider.IModLanguageLoader languageLoader
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
@@ -330,7 +352,7 @@ public final class ModLoader {
|
|||||||
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
|
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
|
||||||
} catch (ModLoadingException mle) {
|
} catch (ModLoadingException mle) {
|
||||||
// exceptions are caught and added to the error list for later handling
|
// exceptions are caught and added to the error list for later handling
|
||||||
LOADING_EXCEPTIONS.add(mle);
|
loadingExceptions.add(mle);
|
||||||
// return an errored container instance here, because we tried and failed building a container.
|
// return an errored container instance here, because we tried and failed building a container.
|
||||||
return new ErroredModContainer();
|
return new ErroredModContainer();
|
||||||
}
|
}
|
||||||
@@ -344,8 +366,15 @@ public final class ModLoader {
|
|||||||
return loadingStateValid;
|
return loadingStateValid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean hasCompletedState(IModLoadingState state) {
|
/** @deprecated Use {@link #hasCompletedState(IModLoadingState)} instead */
|
||||||
return COMPLETED_STATES.contains(state);
|
@Deprecated(forRemoval = true)
|
||||||
|
public boolean hasCompletedState(final String stateName) {
|
||||||
|
IModLoadingState state = stateManager.findState(stateName);
|
||||||
|
return completedStates.contains(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasCompletedState(IModLoadingState state) {
|
||||||
|
return completedStates.contains(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
|
public static <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
|
||||||
@@ -353,7 +382,7 @@ public final class ModLoader {
|
|||||||
LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
|
LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (var mod : ModList.getLoadedMods())
|
for (var mod : ModList.get().getLoadedMods())
|
||||||
mod.acceptEvent(generator.apply(mod));
|
mod.acceptEvent(generator.apply(mod));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,20 +391,16 @@ public final class ModLoader {
|
|||||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (var mod : ModList.getLoadedMods())
|
for (var mod : ModList.get().getLoadedMods())
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T extends IModBusEvent> void postEvent(ModContainer mod, T e) {
|
|
||||||
mod.acceptEvent(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T extends IModBusEvent> T postEventWithReturn(T e) {
|
public static <T extends IModBusEvent> T postEventWithReturn(T e) {
|
||||||
if (!loadingStateValid) {
|
if (!loadingStateValid) {
|
||||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
for (var mod : ModList.getLoadedMods())
|
for (var mod : ModList.get().getLoadedMods())
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
@@ -383,8 +408,8 @@ public final class ModLoader {
|
|||||||
@SuppressWarnings("removal")
|
@SuppressWarnings("removal")
|
||||||
public static <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
|
public static <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
|
||||||
postEventWithWrapInModOrder(event,
|
postEventWithWrapInModOrder(event,
|
||||||
(mc, _) -> ModLoadingContext.get().setActiveContainer(mc),
|
(mc, e) -> ModLoadingContext.get().setActiveContainer(mc),
|
||||||
(_, _) -> ModLoadingContext.get().setActiveContainer(null)
|
(mc, e) -> ModLoadingContext.get().setActiveContainer(null)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,19 +418,19 @@ public final class ModLoader {
|
|||||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (var mod : ModList.getLoadedMods()) {
|
for (var mod : ModList.get().getLoadedMods()) {
|
||||||
pre.accept(mod, e);
|
pre.accept(mod, e);
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
post.accept(mod, e);
|
post.accept(mod, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<ModLoadingWarning> getWarnings() {
|
public List<ModLoadingWarning> getWarnings() {
|
||||||
return List.copyOf(LOADING_WARNINGS);
|
return ImmutableList.copyOf(this.loadingWarnings);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void addWarning(ModLoadingWarning warning) {
|
public void addWarning(ModLoadingWarning warning) {
|
||||||
LOADING_WARNINGS.add(warning);
|
this.loadingWarnings.add(warning);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean runningDataGen = false;
|
private static boolean runningDataGen = false;
|
||||||
|
|||||||
@@ -32,11 +32,24 @@ public class ModLoadingContext {
|
|||||||
return context.get();
|
return context.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
void setActiveContainer(final ModContainer container) {
|
/**
|
||||||
|
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
|
public void setActiveContainer(final ModContainer container) {
|
||||||
this.activeContainer = container;
|
this.activeContainer = container;
|
||||||
this.languageExtension = container == null ? null : container.contextExtension.get();
|
this.languageExtension = container == null ? null : container.contextExtension.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Going to be moved to ForgeHooks for Internal use.
|
||||||
|
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
|
public ModContainer getActiveContainer() {
|
||||||
|
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
||||||
*/
|
*/
|
||||||
@@ -45,10 +58,11 @@ public class ModLoadingContext {
|
|||||||
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return {@link ModLoadingContext#getActiveContainer()} by default.
|
||||||
|
*/
|
||||||
public ModContainer getContainer() {
|
public ModContainer getContainer() {
|
||||||
return activeContainer == null
|
return getActiveContainer();
|
||||||
? ModList.getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!"))
|
|
||||||
: activeContainer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -100,7 +114,8 @@ public class ModLoadingContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
|
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
|
||||||
if (spec.isEmpty()) {
|
if (spec.isEmpty())
|
||||||
|
{
|
||||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
|
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
|
||||||
return;
|
return;
|
||||||
@@ -110,7 +125,8 @@ public class ModLoadingContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
|
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
|
||||||
if (spec.isEmpty()) {
|
if (spec.isEmpty())
|
||||||
|
{
|
||||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
|
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
|
||||||
return;
|
return;
|
||||||
@@ -119,6 +135,7 @@ public class ModLoadingContext {
|
|||||||
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
|
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public <T> T extension() {
|
public <T> T extension() {
|
||||||
return (T)languageExtension;
|
return (T)languageExtension;
|
||||||
|
|||||||
@@ -6,14 +6,14 @@
|
|||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||||
import org.jspecify.annotations.NullMarked;
|
|
||||||
import org.jspecify.annotations.Nullable;
|
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.function.IntSupplier;
|
import java.util.function.ToIntFunction;
|
||||||
import java.util.function.Supplier;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of the {@link IModLoadingState} interface.
|
* Implementation of the {@link IModLoadingState} interface.
|
||||||
@@ -25,26 +25,27 @@ import java.util.function.Supplier;
|
|||||||
* @param inlineRunnable an optional runnable, which runs before starting the transition from this state to the next
|
* @param inlineRunnable an optional runnable, which runs before starting the transition from this state to the next
|
||||||
* @param transition optional state transition information
|
* @param transition optional state transition information
|
||||||
*/
|
*/
|
||||||
@NullMarked
|
|
||||||
public record ModLoadingState(
|
public record ModLoadingState(
|
||||||
String name,
|
String name,
|
||||||
String previous,
|
String previous,
|
||||||
Supplier<String> message,
|
Function<ModList, String> message,
|
||||||
IntSupplier size,
|
ToIntFunction<ModList> size,
|
||||||
ModLoadingPhase phase,
|
ModLoadingPhase phase,
|
||||||
@Nullable Runnable inlineRunnable,
|
Optional<Consumer<ModList>> inlineRunnable,
|
||||||
@Nullable IModStateTransition transition
|
Optional<IModStateTransition> transition
|
||||||
) implements IModLoadingState {
|
) implements IModLoadingState {
|
||||||
@Override
|
@Override
|
||||||
public @Nullable CompletableFuture<Void> buildTransition(
|
public Optional<CompletableFuture<Void>> buildTransition(
|
||||||
final Executor syncExecutor,
|
final Executor syncExecutor,
|
||||||
final Executor parallelExecutor,
|
final Executor parallelExecutor,
|
||||||
final ProgressMeter progressBar,
|
final ProgressMeter progressBar,
|
||||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||||
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
||||||
) {
|
) {
|
||||||
if (transition == null) return null;
|
var transition = this.transition.orElse(null);
|
||||||
return transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask);
|
return transition == null
|
||||||
|
? Optional.empty()
|
||||||
|
: Optional.ofNullable(transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,7 +60,7 @@ public record ModLoadingState(
|
|||||||
*/
|
*/
|
||||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) {
|
public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) {
|
||||||
return new ModLoadingState(name, previous, () -> "", () -> 0, phase, null, null);
|
return new ModLoadingState(name, previous, ml -> "", ml -> 0, phase, Optional.empty(), Optional.empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -93,7 +94,7 @@ public record ModLoadingState(
|
|||||||
*/
|
*/
|
||||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
public static ModLoadingState withTransition(final String name, final String previous,
|
public static ModLoadingState withTransition(final String name, final String previous,
|
||||||
final Supplier<String> message, final ModLoadingPhase phase,
|
final Function<ModList, String> message, final ModLoadingPhase phase,
|
||||||
final IModStateTransition transition) {
|
final IModStateTransition transition) {
|
||||||
return of(name, phase).after(previous).message(message).withTransition(transition);
|
return of(name, phase).after(previous).message(message).withTransition(transition);
|
||||||
}
|
}
|
||||||
@@ -112,7 +113,7 @@ public record ModLoadingState(
|
|||||||
*/
|
*/
|
||||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||||
public static ModLoadingState withInline(final String name, final String previous, final ModLoadingPhase phase,
|
public static ModLoadingState withInline(final String name, final String previous, final ModLoadingPhase phase,
|
||||||
final Runnable inline) {
|
final Consumer<ModList> inline) {
|
||||||
return of(name, phase).after(previous).withInline(inline);
|
return of(name, phase).after(previous).withInline(inline);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,23 +126,23 @@ public record ModLoadingState(
|
|||||||
return o instanceof ModLoadingState that
|
return o instanceof ModLoadingState that
|
||||||
&& this.phase == that.phase
|
&& this.phase == that.phase
|
||||||
&& this.name.equals(that.name)
|
&& this.name.equals(that.name)
|
||||||
&& this.previous.equals(that.previous);
|
&& Objects.equals(this.previous, that.previous);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int result = phase.hashCode();
|
int result = phase.hashCode();
|
||||||
result = 31 * result + name.hashCode();
|
result = 31 * result + name.hashCode();
|
||||||
result = 31 * result + previous.hashCode();
|
result = 31 * result + Objects.hashCode(previous);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class Builder {
|
public static class Builder {
|
||||||
private final String name;
|
private final String name;
|
||||||
private final ModLoadingPhase phase;
|
private final ModLoadingPhase phase;
|
||||||
private String after = "";
|
private String after;
|
||||||
private @Nullable Supplier<String> message = null;
|
private Function<ModList, String> message = null;
|
||||||
private @Nullable IntSupplier size = null;
|
private ToIntFunction<ModList> size = null;
|
||||||
|
|
||||||
private Builder(final String name, final ModLoadingPhase phase) {
|
private Builder(final String name, final ModLoadingPhase phase) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
@@ -154,28 +155,28 @@ public record ModLoadingState(
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder message(final String value) { return message(() -> value); }
|
public Builder message(final String value) { return message(ml -> value); }
|
||||||
public Builder message(final Supplier<String> value) {
|
public Builder message(final Function<ModList, String> value) {
|
||||||
this.message = value;
|
this.message = value;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder size(final int value) { return size(() -> value); }
|
public Builder size(final int value) { return size(ml -> value); }
|
||||||
public Builder size(final IntSupplier value) {
|
public Builder size(final ToIntFunction<ModList> value) {
|
||||||
this.size = value;
|
this.size = value;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModLoadingState empty() {
|
public ModLoadingState empty() {
|
||||||
return new ModLoadingState(name, after, message != null ? message : () -> "", size != null ? size : () -> 0, phase, null, null);
|
return new ModLoadingState(name, after, message != null ? message : ml -> "", size != null ? size : ml -> 0, phase, Optional.empty(), Optional.empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModLoadingState withTransition(final IModStateTransition transition) {
|
public ModLoadingState withTransition(final IModStateTransition transition) {
|
||||||
return new ModLoadingState(name, after, message != null ? message : () -> "Processing transition " + name, size != null ? size : ModList::size, phase, null, transition);
|
return new ModLoadingState(name, after, message != null ? message : ml -> "Processing transition " + name, size != null ? size : ModList::size, phase, Optional.empty(), Optional.of(transition));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModLoadingState withInline(final Runnable inline) {
|
public ModLoadingState withInline(final Consumer<ModList> inline) {
|
||||||
return new ModLoadingState(name, after, message != null ? message : () -> "Processing work " + name, size != null ? size : () -> 0, phase, inline, null);
|
return new ModLoadingState(name, after, message != null ? message : ml -> "Processing work " + name, size != null ? size : ml -> 0, phase, Optional.of(inline), Optional.empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,27 +5,41 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml;
|
package net.minecraftforge.fml;
|
||||||
|
|
||||||
|
import com.google.common.collect.Streams;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
/**
|
public class ModLoadingWarning {
|
||||||
* @param modInfo Mod info for mod with warning
|
/**
|
||||||
* @param warningStage The stage where this warning was encountered
|
* Mod Info for mod with warning
|
||||||
* @param i18nMessage I18N message to use for display
|
*/
|
||||||
* @param context Context for message display
|
private final IModInfo modInfo;
|
||||||
*/
|
/**
|
||||||
public record ModLoadingWarning(IModInfo modInfo, ModLoadingStage warningStage, String i18nMessage, List<Object> context) {
|
* The stage where this warning was encountered
|
||||||
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
|
*/
|
||||||
this(modInfo, warningStage, i18nMessage, List.of(context));
|
private final ModLoadingStage warningStage;
|
||||||
}
|
|
||||||
|
|
||||||
public ModLoadingWarning {
|
/**
|
||||||
context = List.copyOf(context);
|
* I18N message to use for display
|
||||||
|
*/
|
||||||
|
private final String i18nMessage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Context for message display
|
||||||
|
*/
|
||||||
|
private final List<Object> context;
|
||||||
|
|
||||||
|
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
|
||||||
|
this.modInfo = modInfo;
|
||||||
|
this.warningStage = warningStage;
|
||||||
|
this.i18nMessage = i18nMessage;
|
||||||
|
this.context = Arrays.asList(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatToString() {
|
public String formatToString() {
|
||||||
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Stream.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,19 +15,18 @@ import java.util.function.Function;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@SuppressWarnings("UnstableApiUsage")
|
@SuppressWarnings("UnstableApiUsage")
|
||||||
public final class ModStateManager {
|
public class ModStateManager {
|
||||||
private ModStateManager() {}
|
private final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
||||||
private static final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
|
||||||
|
|
||||||
static {
|
public ModStateManager() {
|
||||||
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
||||||
stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, _ -> {})
|
this.stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, sce->{})
|
||||||
.map(IModStateProvider::getAllStates)
|
.map(IModStateProvider::getAllStates)
|
||||||
.flatMap(List::stream)
|
.flatMap(List::stream)
|
||||||
.collect(Collectors.groupingBy(IModLoadingState::phase, () -> new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
|
.collect(Collectors.groupingBy(IModLoadingState::phase, ()->new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<IModLoadingState> getStates(final ModLoadingPhase phase) {
|
public List<IModLoadingState> getStates(final ModLoadingPhase phase) {
|
||||||
var nodes = stateMap.get(phase);
|
var nodes = stateMap.get(phase);
|
||||||
var lookup = nodes.stream().collect(Collectors.toMap(IModLoadingState::name, Function.identity()));
|
var lookup = nodes.stream().collect(Collectors.toMap(IModLoadingState::name, Function.identity()));
|
||||||
|
|
||||||
@@ -41,7 +40,7 @@ public final class ModStateManager {
|
|||||||
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
|
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IModLoadingState findState(final String stateName) {
|
public IModLoadingState findState(final String stateName) {
|
||||||
var result = stateMap.values()
|
var result = stateMap.values()
|
||||||
.stream()
|
.stream()
|
||||||
.flatMap(List::stream)
|
.flatMap(List::stream)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import net.minecraftforge.fml.event.IModBusEvent;
|
|||||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
final class ModStateTransitionHelper {
|
class ModStateTransitionHelper {
|
||||||
static final IModStateTransition NOOP = new NoopTransition();
|
static final IModStateTransition NOOP = new NoopTransition();
|
||||||
record NoopTransition() implements IModStateTransition {
|
record NoopTransition() implements IModStateTransition {
|
||||||
@Override
|
@Override
|
||||||
@@ -62,30 +62,7 @@ final class ModStateTransitionHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Same as [#completableFutureFromExceptionList(List)] but specialised for a single future
|
record FutureResult<V>(V value, Throwable exception){}
|
||||||
static <V> CompletionStage<Void> completableFutureFromException(FutureResult<V> t) {
|
|
||||||
if (t.exception() == null) {
|
|
||||||
return CompletableFuture.completedFuture(null);
|
|
||||||
} else {
|
|
||||||
var exception = t.exception();
|
|
||||||
CompletableFuture<Void> cf = new CompletableFuture<>();
|
|
||||||
RuntimeException accumulator = new RuntimeException();
|
|
||||||
cf.completeExceptionally(accumulator);
|
|
||||||
if (exception instanceof CompletionException) {
|
|
||||||
exception = exception.getCause();
|
|
||||||
}
|
|
||||||
if (exception.getSuppressed().length != 0) {
|
|
||||||
for (Throwable throwable : exception.getSuppressed()) {
|
|
||||||
accumulator.addSuppressed(throwable);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
accumulator.addSuppressed(exception);
|
|
||||||
}
|
|
||||||
return cf;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
record FutureResult<V>(V value, Throwable exception) {}
|
|
||||||
|
|
||||||
static <V> CompletableFuture<List<FutureResult<V>>> gather(Collection<? extends CompletableFuture<? extends V>> futures) {
|
static <V> CompletableFuture<List<FutureResult<V>>> gather(Collection<? extends CompletableFuture<? extends V>> futures) {
|
||||||
var list = new ArrayList<FutureResult<V>>(futures.size());
|
var list = new ArrayList<FutureResult<V>>(futures.size());
|
||||||
@@ -99,17 +76,25 @@ final class ModStateTransitionHelper {
|
|||||||
results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception)));
|
results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception)));
|
||||||
}
|
}
|
||||||
|
|
||||||
return CompletableFuture.allOf(results).handle((_, _)->null).thenApply(_ -> list);
|
return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static <T extends IModBusEvent> CompletableFuture<Void> addCompletableFutureTaskForModDispatch(
|
private static <T extends IModBusEvent> void addCompletableFutureTaskForModDispatch(
|
||||||
|
final IModStateTransition transition,
|
||||||
final Executor executor,
|
final Executor executor,
|
||||||
|
final List<CompletableFuture<Void>> completableFutures,
|
||||||
final ProgressMeter progressBar,
|
final ProgressMeter progressBar,
|
||||||
final EventGenerator<T> eventGenerator,
|
final EventGenerator<T> eventGenerator,
|
||||||
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState
|
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
@SuppressWarnings("removal")
|
||||||
|
var preDispatchHook = getHook(transition.preDispatchHook(), executor, eventGenerator);
|
||||||
|
if (preDispatchHook != null)
|
||||||
|
completableFutures.add(preDispatchHook);
|
||||||
|
|
||||||
var modFutures = new LinkedHashMap<String, CompletableFuture<Void>>();
|
var modFutures = new LinkedHashMap<String, CompletableFuture<Void>>();
|
||||||
for (var mod : ModList.getLoadedMods()) {
|
for (var mod : ModList.get().getLoadedMods()) {
|
||||||
|
|
||||||
CompletableFuture<Void> parent = null;
|
CompletableFuture<Void> parent = null;
|
||||||
if (mod.dependencies.isEmpty()) {
|
if (mod.dependencies.isEmpty()) {
|
||||||
@@ -135,7 +120,7 @@ final class ModStateTransitionHelper {
|
|||||||
handler.run();
|
handler.run();
|
||||||
mod.acceptEvent(eventGenerator.apply(mod));
|
mod.acceptEvent(eventGenerator.apply(mod));
|
||||||
}, executor)
|
}, executor)
|
||||||
.whenComplete((_, exception) -> {
|
.whenComplete((mc, exception) -> {
|
||||||
mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception);
|
mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception);
|
||||||
progressBar.increment();
|
progressBar.increment();
|
||||||
ModLoadingContext.get().setActiveContainer(null);
|
ModLoadingContext.get().setActiveContainer(null);
|
||||||
@@ -144,7 +129,20 @@ final class ModStateTransitionHelper {
|
|||||||
modFutures.put(mod.getModId(), dispatch);
|
modFutures.put(mod.getModId(), dispatch);
|
||||||
}
|
}
|
||||||
|
|
||||||
return gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor);
|
var dispatch = gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor);
|
||||||
|
completableFutures.add(dispatch);
|
||||||
|
|
||||||
|
@SuppressWarnings("removal")
|
||||||
|
var postDispatchHook = getHook(transition.preDispatchHook(), executor, eventGenerator);
|
||||||
|
if (postDispatchHook != null)
|
||||||
|
completableFutures.add(postDispatchHook);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T extends IModBusEvent> CompletableFuture<Void> getHook(BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> hook, Executor executor, EventGenerator<T> eventGenerator) {
|
||||||
|
if (hook == null || hook == IModStateTransition.NULL_HOOK) return null;
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var hookTyped = (BiFunction<Executor, EventGenerator<T>, CompletableFuture<Void>>)hook;
|
||||||
|
return hookTyped.apply(executor, eventGenerator);
|
||||||
}
|
}
|
||||||
|
|
||||||
static <T extends IModBusEvent> CompletableFuture<Void> build(
|
static <T extends IModBusEvent> CompletableFuture<Void> build(
|
||||||
@@ -156,25 +154,31 @@ final class ModStateTransitionHelper {
|
|||||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||||
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
||||||
) {
|
) {
|
||||||
CompletableFuture<Void> future;
|
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||||
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
|
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
|
||||||
|
|
||||||
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
@SuppressWarnings({ "removal", "unchecked" })
|
||||||
CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF
|
var events = transition.eventFunctionStream().get().map(f -> (EventGenerator<T>)f).toList();
|
||||||
.thenRunAsync(() -> progressBar.label(progressBar.name() + ": dispatching " + name), parallelExecutor);
|
for (int x = 0; x < events.size(); x++) {
|
||||||
|
var gen = events.get(x);
|
||||||
var eventGenerator = transition.eventFunction();
|
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = x == events.size() - 1
|
||||||
if (eventGenerator != null) {
|
? transition.nextModLoadingStage()
|
||||||
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = transition.nextModLoadingStage();
|
: ModLoadingStage::currentState;
|
||||||
future = addCompletableFutureTaskForModDispatch(executor, progressBar, eventGenerator, state);
|
addCompletableFutureTaskForModDispatch(transition, executor, futures, progressBar, gen, state);
|
||||||
|
|
||||||
final CompletableFuture<Void> eventDispatchCF = future.handle(FutureResult::new)
|
|
||||||
.thenCompose(ModStateTransitionHelper::completableFutureFromException);
|
|
||||||
postEventDispatchCF = postEventDispatchCF.thenComposeAsync(_ -> eventDispatchCF, parallelExecutor);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
postEventDispatchCF = postEventDispatchCF.thenRun(() -> postSyncTask.apply(syncExecutor));
|
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
||||||
|
final CompletableFuture<Void> eventDispatchCF = gather(futures).thenCompose(ModStateTransitionHelper::completableFutureFromExceptionList);
|
||||||
|
final CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF
|
||||||
|
.thenApplyAsync(n -> {
|
||||||
|
progressBar.label(progressBar.name() + ": dispatching " + name);
|
||||||
|
return null;
|
||||||
|
}, parallelExecutor)
|
||||||
|
.thenComposeAsync(n -> eventDispatchCF, parallelExecutor)
|
||||||
|
.thenApply(r -> {
|
||||||
|
postSyncTask.apply(syncExecutor);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
return transition.finalActivityGenerator().apply(syncExecutor, postEventDispatchCF);
|
return transition.finalActivityGenerator().apply(syncExecutor, postEventDispatchCF);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,12 +14,25 @@ import java.util.concurrent.locks.LockSupport;
|
|||||||
|
|
||||||
import static net.minecraftforge.fml.Logging.LOADING;
|
import static net.minecraftforge.fml.Logging.LOADING;
|
||||||
|
|
||||||
public final class ModWorkManager {
|
public class ModWorkManager {
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
||||||
|
|
||||||
public sealed interface DrivenExecutor extends Executor {
|
public interface DrivenExecutor extends Executor {
|
||||||
void drive(Runnable ticker);
|
boolean selfDriven();
|
||||||
|
boolean driveOne();
|
||||||
|
|
||||||
|
default void drive(Runnable ticker) {
|
||||||
|
if (!selfDriven()) {
|
||||||
|
ticker.run();
|
||||||
|
while (true) {
|
||||||
|
if (!driveOne()) break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// park for a bit so other threads can schedule
|
||||||
|
LockSupport.parkNanos(PARK_TIME);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor {
|
private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor {
|
||||||
@@ -27,7 +40,8 @@ public final class ModWorkManager {
|
|||||||
this(new ConcurrentLinkedDeque<>());
|
this(new ConcurrentLinkedDeque<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean driveOne() {
|
@Override
|
||||||
|
public boolean driveOne() {
|
||||||
final Runnable task = tasks.pollFirst();
|
final Runnable task = tasks.pollFirst();
|
||||||
if (task != null) {
|
if (task != null) {
|
||||||
task.run();
|
task.run();
|
||||||
@@ -36,29 +50,30 @@ public final class ModWorkManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void execute(final Runnable command) {
|
public boolean selfDriven() {
|
||||||
tasks.addLast(command);
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void drive(Runnable ticker) {
|
public void execute(final Runnable command) {
|
||||||
ticker.run();
|
tasks.addLast(command);
|
||||||
while (true) {
|
|
||||||
if (!driveOne()) break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
||||||
@Override
|
@Override
|
||||||
public void execute(final Runnable command) {
|
public boolean selfDriven() {
|
||||||
wrapped.execute(command);
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void drive(Runnable ticker) {
|
public boolean driveOne() {
|
||||||
// Park for a bit so other threads can schedule
|
return false;
|
||||||
LockSupport.parkNanos(PARK_TIME);
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(final Runnable command) {
|
||||||
|
wrapped.execute(command);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public final class OptionalMod<T>
|
|||||||
private T getValue()
|
private T getValue()
|
||||||
{
|
{
|
||||||
if (!searched) {
|
if (!searched) {
|
||||||
this.value = ModList.<T>getModObjectById(this.modId).orElse(null);
|
this.value = ModList.get().<T>getModObjectById(this.modId).orElse(null);
|
||||||
searched = true;
|
searched = true;
|
||||||
}
|
}
|
||||||
return this.value;
|
return this.value;
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import java.util.concurrent.Executor;
|
|||||||
import java.util.function.BinaryOperator;
|
import java.util.function.BinaryOperator;
|
||||||
|
|
||||||
public enum ThreadSelector implements BinaryOperator<Executor> {
|
public enum ThreadSelector implements BinaryOperator<Executor> {
|
||||||
SYNC((sync, _) -> sync),
|
SYNC((sync, parallel) -> sync),
|
||||||
PARALLEL((_, parallel) -> parallel);
|
PARALLEL((sync, parallel) -> parallel);
|
||||||
|
|
||||||
private final BinaryOperator<Executor> selector;
|
private final BinaryOperator<Executor> selector;
|
||||||
|
|
||||||
|
|||||||
@@ -93,8 +93,8 @@ public class VersionChecker {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var mc = ModList.getModContainerById("minecraft");
|
var mc = ModList.get().getModContainerById("minecraft");
|
||||||
var forge = ModList.getModContainerById("forge");
|
var forge = ModList.get().getModContainerById("forge");
|
||||||
this.mcVersion = mc.get().getModInfo().getVersion().toString();
|
this.mcVersion = mc.get().getModInfo().getVersion().toString();
|
||||||
|
|
||||||
this.agent = "Java-http-client/" + System.getProperty("java.version")
|
this.agent = "Java-http-client/" + System.getProperty("java.version")
|
||||||
@@ -223,7 +223,7 @@ public class VersionChecker {
|
|||||||
// Gather a list of mods that have opted in to this update system by providing a URL.
|
// Gather a list of mods that have opted in to this update system by providing a URL.
|
||||||
private static List<IModInfo> gatherMods() {
|
private static List<IModInfo> gatherMods() {
|
||||||
List<IModInfo> ret = new LinkedList<>();
|
List<IModInfo> ret = new LinkedList<>();
|
||||||
for (IModInfo info : ModList.getMods()) {
|
for (IModInfo info : ModList.get().getMods()) {
|
||||||
if (info.getUpdateURL().isPresent())
|
if (info.getUpdateURL().isPresent())
|
||||||
ret.add(info);
|
ret.add(info);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ package net.minecraftforge.fml.config;
|
|||||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
|
import net.minecraftforge.fml.DistExecutor;
|
||||||
import net.minecraftforge.fml.loading.FMLPaths;
|
import net.minecraftforge.fml.loading.FMLPaths;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.Marker;
|
import org.slf4j.Marker;
|
||||||
@@ -18,54 +19,57 @@ import java.nio.file.Path;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
public final class ConfigTracker {
|
public class ConfigTracker {
|
||||||
private ConfigTracker() {}
|
|
||||||
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
static final Marker CONFIG = MarkerFactory.getMarker("CONFIG");
|
static final Marker CONFIG = MarkerFactory.getMarker("CONFIG");
|
||||||
private static final ConcurrentHashMap<String, ModConfig> FILE_MAP = new ConcurrentHashMap<>();
|
public static final ConfigTracker INSTANCE = new ConfigTracker();
|
||||||
private static final Map<ModConfig.Type, Set<ModConfig>> CONFIG_SETS = Map.of(
|
private final ConcurrentHashMap<String, ModConfig> fileMap;
|
||||||
ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()),
|
private final EnumMap<ModConfig.Type, Set<ModConfig>> configSets;
|
||||||
ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()),
|
private final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> configsByMod;
|
||||||
ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>())
|
|
||||||
);
|
|
||||||
private static final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> CONFIGS_BY_MOD = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
static void trackConfig(final ModConfig config) {
|
private ConfigTracker() {
|
||||||
if (FILE_MAP.containsKey(config.getFileName())) {
|
this.fileMap = new ConcurrentHashMap<>();
|
||||||
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), FILE_MAP.get(config.getFileName()).getModId(), config.getModId());
|
this.configSets = new EnumMap<>(ModConfig.Type.class);
|
||||||
|
this.configsByMod = new ConcurrentHashMap<>();
|
||||||
|
this.configSets.put(ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||||
|
this.configSets.put(ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||||
|
// this.configSets.put(ModConfig.Type.PLAYER, new ConcurrentSkipListSet<>());
|
||||||
|
this.configSets.put(ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void trackConfig(final ModConfig config) {
|
||||||
|
if (this.fileMap.containsKey(config.getFileName())) {
|
||||||
|
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), this.fileMap.get(config.getFileName()).getModId(), config.getModId());
|
||||||
throw new RuntimeException("Config conflict detected!");
|
throw new RuntimeException("Config conflict detected!");
|
||||||
}
|
}
|
||||||
FILE_MAP.put(config.getFileName(), config);
|
this.fileMap.put(config.getFileName(), config);
|
||||||
CONFIG_SETS.get(config.getType()).add(config);
|
this.configSets.get(config.getType()).add(config);
|
||||||
CONFIGS_BY_MOD.computeIfAbsent(config.getModId(), _ -> new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
|
this.configsByMod.computeIfAbsent(config.getModId(), (k)->new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
|
||||||
LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId());
|
LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
public void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
||||||
for (ModConfig config : CONFIG_SETS.get(type)) {
|
for (ModConfig config : this.configSets.get(type)) {
|
||||||
openConfig(config, configBasePath);
|
openConfig(config, configBasePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: [FML] This is only called for the server (outside of forceUnload)
|
// TODO: [FML] This is only called for the server (outside of forceUnload)
|
||||||
// rethink config implementation for eventual FML rewrite
|
// rethink config implementation for eventual FML rewrite
|
||||||
public static void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
||||||
for (ModConfig config : CONFIG_SETS.get(type)) {
|
for (ModConfig config : this.configSets.get(type)) {
|
||||||
closeConfig(config, configBasePath);
|
closeConfig(config, configBasePath);
|
||||||
}
|
}
|
||||||
ConfigFileTypeHandler.get(type).stopWatcher();
|
ConfigFileTypeHandler.get(type).stopWatcher();
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there is a better way to do this, please tell me. Because this is FUCKED
|
// If there is a better way to do this, please tell me. Because this is FUCKED
|
||||||
public static void forceUnload() {
|
public void forceUnload() {
|
||||||
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
|
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
|
||||||
if (FMLEnvironment.dist.isClient())
|
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
|
||||||
unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get());
|
this.unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
||||||
|
|
||||||
unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
|
||||||
|
|
||||||
// just in case server watcher is still alive somehow...
|
// just in case server watcher is still alive somehow...
|
||||||
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
|
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
|
||||||
@@ -92,8 +96,8 @@ public final class ConfigTracker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void loadDefaultServerConfigs() {
|
public void loadDefaultServerConfigs() {
|
||||||
CONFIG_SETS.get(ModConfig.Type.SERVER).forEach(modConfig -> {
|
configSets.get(ModConfig.Type.SERVER).forEach(modConfig -> {
|
||||||
final CommentedConfig commentedConfig = CommentedConfig.inMemory();
|
final CommentedConfig commentedConfig = CommentedConfig.inMemory();
|
||||||
modConfig.getSpec().correct(commentedConfig);
|
modConfig.getSpec().correct(commentedConfig);
|
||||||
modConfig.setConfigData(commentedConfig);
|
modConfig.setConfigData(commentedConfig);
|
||||||
@@ -101,16 +105,16 @@ public final class ConfigTracker {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getConfigFileName(String modId, ModConfig.Type type) {
|
public String getConfigFileName(String modId, ModConfig.Type type) {
|
||||||
return Optional.ofNullable(CONFIGS_BY_MOD.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
return Optional.ofNullable(configsByMod.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
||||||
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Map<ModConfig.Type, Set<ModConfig>> configSets() {
|
public Map<ModConfig.Type, Set<ModConfig>> configSets() {
|
||||||
return CONFIG_SETS;
|
return configSets;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ConcurrentHashMap<String, ModConfig> fileMap() {
|
public ConcurrentHashMap<String, ModConfig> fileMap() {
|
||||||
return FILE_MAP;
|
return fileMap;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,6 @@ import java.util.function.Function;
|
|||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
public interface IConfigEvent {
|
public interface IConfigEvent {
|
||||||
// TODO: [FML] Get rid of this indirection somehow
|
|
||||||
record ConfigConfig(Function<ModConfig, IConfigEvent> loading, Function<ModConfig, IConfigEvent> reloading, @Nullable Function<ModConfig, IConfigEvent> unloading) {}
|
record ConfigConfig(Function<ModConfig, IConfigEvent> loading, Function<ModConfig, IConfigEvent> reloading, @Nullable Function<ModConfig, IConfigEvent> unloading) {}
|
||||||
|
|
||||||
ConfigConfig CONFIGCONFIG = Bindings.getConfigConfiguration().get();
|
ConfigConfig CONFIGCONFIG = Bindings.getConfigConfiguration().get();
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import net.minecraftforge.fml.loading.StringUtils;
|
|||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
public class ModConfig
|
public class ModConfig
|
||||||
{
|
{
|
||||||
@@ -29,7 +31,7 @@ public class ModConfig
|
|||||||
this.fileName = fileName;
|
this.fileName = fileName;
|
||||||
this.container = container;
|
this.container = container;
|
||||||
this.configHandler = ConfigFileTypeHandler.get(type);
|
this.configHandler = ConfigFileTypeHandler.get(type);
|
||||||
ConfigTracker.trackConfig(this);
|
ConfigTracker.INSTANCE.trackConfig(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
|
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
|
||||||
@@ -38,9 +40,8 @@ public class ModConfig
|
|||||||
|
|
||||||
private static String defaultConfigName(Type type, String modId) {
|
private static String defaultConfigName(Type type, String modId) {
|
||||||
// config file name would be "forge-client.toml" and "forge-server.toml"
|
// config file name would be "forge-client.toml" and "forge-server.toml"
|
||||||
return modId + '-' + type.extension() + ".toml";
|
return String.format(Locale.ROOT, "%s-%s.toml", modId, type.extension());
|
||||||
}
|
}
|
||||||
|
|
||||||
public Type getType() {
|
public Type getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,49 @@
|
|||||||
import org.gradle.api.plugins.jvm.JvmTestSuite
|
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||||
|
import org.gradle.internal.os.OperatingSystem
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
id 'jvm-test-suite'
|
id 'jvm-test-suite'
|
||||||
|
id 'maven-publish'
|
||||||
|
alias libs.plugins.licenser
|
||||||
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch (OperatingSystem.current()) {
|
||||||
|
case OperatingSystem.LINUX:
|
||||||
|
project.ext.lwjglNatives = "natives-linux"
|
||||||
|
break
|
||||||
|
case OperatingSystem.MAC_OS:
|
||||||
|
project.ext.lwjglNatives = "natives-macos"
|
||||||
|
break
|
||||||
|
case OperatingSystem.WINDOWS:
|
||||||
|
project.ext.lwjglNatives = "natives-windows"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
gradleutils.displayName = 'FML Early Display'
|
gradleutils.displayName = 'FML Early Display'
|
||||||
|
final vendor = 'Forge Development LLC'
|
||||||
description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.'
|
description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.'
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
withSourcesJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
license {
|
||||||
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
|
}
|
||||||
|
|
||||||
|
changelog {
|
||||||
|
from changelogBase
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
compileOnly libs.jetbrains.annotations
|
||||||
|
|
||||||
implementation projects.fmlloader
|
implementation projects.fmlloader
|
||||||
implementation projects.fmlcore
|
implementation projects.fmlcore
|
||||||
implementation libs.bundles.lwjgl
|
implementation libs.bundles.lwjgl
|
||||||
@@ -16,19 +51,67 @@ dependencies {
|
|||||||
implementation libs.jopt.simple
|
implementation libs.jopt.simple
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// See gradle/gradle#35070 (https://github.com/gradle/gradle/issues/35070)
|
||||||
|
// We are making the list of providers first BEFORE mapping them to a provider of the resolved objects so that they can be finalized after configuration.
|
||||||
|
var lwjglTestLibs = [
|
||||||
|
dependencies.variantOf(earlyDisplayTestLibs.lwjgl) { classifier lwjglNatives },
|
||||||
|
dependencies.variantOf(earlyDisplayTestLibs.lwjgl.glfw) { classifier lwjglNatives },
|
||||||
|
dependencies.variantOf(earlyDisplayTestLibs.lwjgl.opengl) { classifier lwjglNatives },
|
||||||
|
dependencies.variantOf(earlyDisplayTestLibs.lwjgl.stb) { classifier lwjglNatives }
|
||||||
|
].with { list ->
|
||||||
|
provider { list.collect { it.get() } }
|
||||||
|
}
|
||||||
|
|
||||||
testing.suites.named('test', JvmTestSuite) {
|
testing.suites.named('test', JvmTestSuite) {
|
||||||
useJUnitJupiter('5.8.2')
|
useJUnitJupiter('5.8.2')
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation earlyDisplayTestLibs.powermock.core
|
implementation earlyDisplayTestLibs.powermock.core
|
||||||
runtimeOnly earlyDisplayLibs.slf4j.jdk14
|
runtimeOnly earlyDisplayLibs.slf4j.jdk14
|
||||||
runtimeOnly.bundle convention.nativeVariants(earlyDisplayTestLibs.bundles.lwjgl)
|
runtimeOnly.bundle lwjglTestLibs
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
convention.manifest('net/minecraftforge/fml/earlydisplay/', [
|
tasks.withType(JavaCompile).configureEach {
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.earlydisplay',
|
options.compilerArgs << '-Xlint:unchecked'
|
||||||
'Forge-Module-Layer' : 'boot'
|
}
|
||||||
])
|
|
||||||
|
|
||||||
convention.publish()
|
tasks.named('jar', Jar) {
|
||||||
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.earlydisplay',
|
||||||
|
'Forge-Module-Layer' : 'boot'
|
||||||
|
])
|
||||||
|
attributes([
|
||||||
|
'Specification-Title' : gradleutils.displayName.get(),
|
||||||
|
'Specification-Vendor' : vendor,
|
||||||
|
'Specification-Version' : '1',
|
||||||
|
'Implementation-Title' : gradleutils.displayName.get(),
|
||||||
|
'Implementation-Vendor' : vendor,
|
||||||
|
'Implementation-Version': '1.0'
|
||||||
|
], 'net/minecraftforge/fml/earlydisplay/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven gradleutils.publishingForgeMaven
|
||||||
|
}
|
||||||
|
|
||||||
|
publications.register('mavenJava', MavenPublication) {
|
||||||
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
from components.java
|
||||||
|
|
||||||
|
pom {
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+175
-239
@@ -13,12 +13,10 @@ import net.minecraftforge.fml.loading.ImmediateWindowHandler;
|
|||||||
import net.minecraftforge.fml.loading.ImmediateWindowProvider;
|
import net.minecraftforge.fml.loading.ImmediateWindowProvider;
|
||||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.lwjgl.opengl.GL;
|
import org.lwjgl.PointerBuffer;
|
||||||
import org.lwjgl.sdl.SDLError;
|
import org.lwjgl.glfw.GLFWVidMode;
|
||||||
import org.lwjgl.sdl.SDLVideo;
|
|
||||||
import org.lwjgl.sdl.SDL_Event;
|
|
||||||
import org.lwjgl.sdl.SDL_Rect;
|
|
||||||
import org.lwjgl.system.MemoryStack;
|
import org.lwjgl.system.MemoryStack;
|
||||||
|
import org.lwjgl.system.MemoryUtil;
|
||||||
import org.lwjgl.util.tinyfd.TinyFileDialogs;
|
import org.lwjgl.util.tinyfd.TinyFileDialogs;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -31,10 +29,12 @@ import java.net.URI;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.StringJoiner;
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
@@ -43,18 +43,19 @@ import java.util.concurrent.Semaphore;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.TimeoutException;
|
import java.util.concurrent.TimeoutException;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.function.IntConsumer;
|
import java.util.function.IntConsumer;
|
||||||
|
import java.util.function.IntSupplier;
|
||||||
|
import java.util.function.LongSupplier;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collector;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.lwjgl.glfw.GLFW.*;
|
||||||
|
import static org.lwjgl.opengl.GL.createCapabilities;
|
||||||
import static org.lwjgl.opengl.GL32C.*;
|
import static org.lwjgl.opengl.GL32C.*;
|
||||||
|
|
||||||
import static org.lwjgl.sdl.SDLError.*;
|
|
||||||
import static org.lwjgl.sdl.SDLEvents.*;
|
|
||||||
import static org.lwjgl.sdl.SDLHints.*;
|
|
||||||
import static org.lwjgl.sdl.SDLInit.*;
|
|
||||||
import static org.lwjgl.sdl.SDLVideo.*;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Loading Window that is opened Immediately after Forge starts.
|
* The Loading Window that is opened Immediately after Forge starts.
|
||||||
* It is called from the ModDirTransformerDiscoverer, the soonest method that ModLauncher calls into Forge code.
|
* It is called from the ModDirTransformerDiscoverer, the soonest method that ModLauncher calls into Forge code.
|
||||||
@@ -69,7 +70,7 @@ import static org.lwjgl.sdl.SDLVideo.*;
|
|||||||
* Based on the prior ClientVisualization, with some personal touches.
|
* Based on the prior ClientVisualization, with some personal touches.
|
||||||
*/
|
*/
|
||||||
public class DisplayWindow implements ImmediateWindowProvider {
|
public class DisplayWindow implements ImmediateWindowProvider {
|
||||||
private static final int[][] GL_VERSIONS = new int[][] {{4,6}, {4,5}, {4,4}, {4,3}, {4,2}, {4,1}, {4,0}, {3,3}};
|
private static final int[][] GL_VERSIONS = new int[][] {{4,6}, {4,5}, {4,4}, {4,3}, {4,2}, {4,1}, {4,0}, {3,3}, {3,2}};
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY");
|
private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY");
|
||||||
private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true);
|
private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true);
|
||||||
|
|
||||||
@@ -84,10 +85,10 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
private ScheduledFuture<?> initializationFuture;
|
private ScheduledFuture<?> initializationFuture;
|
||||||
|
|
||||||
private PerformanceInfo performanceInfo;
|
private PerformanceInfo performanceInfo;
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private ScheduledFuture<?> performanceTick;
|
||||||
// The GL ID of the window. Used for all operations
|
// The GL ID of the window. Used for all operations
|
||||||
private long window;
|
private long window;
|
||||||
// The SDL Context we use for switching between threads
|
|
||||||
private long sdlContext;
|
|
||||||
// The thread that contains and ticks the window while Forge is loading mods
|
// The thread that contains and ticks the window while Forge is loading mods
|
||||||
private static final ScheduledExecutorService renderScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
private static final ScheduledExecutorService renderScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
final var thread = Executors.defaultThreadFactory().newThread(r);
|
final var thread = Executors.defaultThreadFactory().newThread(r);
|
||||||
@@ -114,14 +115,6 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
return "fmlearlywindow";
|
return "fmlearlywindow";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public ImmediateWindowProvider selectBackend(String backend) {
|
|
||||||
// We only support opengl
|
|
||||||
//if ("default".equals(backend) || "opengl".equals(backend))
|
|
||||||
// return this;
|
|
||||||
return ImmediateWindowProvider.getFallbackHandler();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Runnable initialize(String[] arguments) {
|
public Runnable initialize(String[] arguments) {
|
||||||
String mcVersion = FMLLoader.versionInfo().mcVersion();
|
String mcVersion = FMLLoader.versionInfo().mcVersion();
|
||||||
@@ -146,7 +139,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
this.colourScheme = ColourScheme.BLACK;
|
this.colourScheme = ColourScheme.BLACK;
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
// check the options file for the color scheme
|
// check the options file for the colour scheme
|
||||||
var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt")));
|
var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt")));
|
||||||
var keyName = "darkMojangStudiosBackground:";
|
var keyName = "darkMojangStudiosBackground:";
|
||||||
for (String line : optionLines) {
|
for (String line : optionLines) {
|
||||||
@@ -185,7 +178,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
nextFrameTime = nt + MINFRAMETIME;
|
nextFrameTime = nt + MINFRAMETIME;
|
||||||
SDL_GL_MakeCurrent(window, sdlContext);
|
glfwMakeContextCurrent(window);
|
||||||
framebuffer.activate();
|
framebuffer.activate();
|
||||||
glViewport(0, 0, this.context.scaledWidth(), this.context.scaledHeight());
|
glViewport(0, 0, this.context.scaledWidth(), this.context.scaledHeight());
|
||||||
this.context.elementShader().activate();
|
this.context.elementShader().activate();
|
||||||
@@ -197,12 +190,11 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
glViewport(0, 0, fbWidth, fbHeight);
|
glViewport(0, 0, fbWidth, fbHeight);
|
||||||
framebuffer.draw(this.fbWidth, this.fbHeight);
|
framebuffer.draw(this.fbWidth, this.fbHeight);
|
||||||
// Swap buffers; we're done
|
// Swap buffers; we're done
|
||||||
SDL_GL_SwapWindow(window);
|
glfwSwapBuffers(window);
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
LOGGER.error("BARF", t);
|
LOGGER.error("BARF", t);
|
||||||
} finally {
|
} finally {
|
||||||
if (this.windowTick != null)
|
if (this.windowTick != null) glfwMakeContextCurrent(0); // we release the gl context IF we're running off the main thread
|
||||||
SDL_GL_MakeCurrent(window, 0); // we release the gl context IF we're running off the main thread
|
|
||||||
renderLock.release();
|
renderLock.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,18 +206,12 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
* Nothing fancy, we just want to draw and render text.
|
* Nothing fancy, we just want to draw and render text.
|
||||||
*/
|
*/
|
||||||
private void initRender(final @Nullable String mcVersion, final String forgeVersion) {
|
private void initRender(final @Nullable String mcVersion, final String forgeVersion) {
|
||||||
this.sdlContext = SDL_GL_CreateContext(window);
|
|
||||||
if (sdlContext == 0)
|
|
||||||
throw new IllegalStateException("Failed to create OpenGL context: " + SDL_GetError());
|
|
||||||
|
|
||||||
// This thread owns the GL render context now. We should make a note of that.
|
// This thread owns the GL render context now. We should make a note of that.
|
||||||
bindGlContext();
|
glfwMakeContextCurrent(window);
|
||||||
GL.createCapabilities();
|
|
||||||
|
|
||||||
// Wait for one frame to be complete before swapping; enable vsync in other words.
|
// Wait for one frame to be complete before swapping; enable vsync in other words.
|
||||||
SDL_GL_SetSwapInterval(1);
|
glfwSwapInterval(1);
|
||||||
|
createCapabilities();
|
||||||
LOGGER.info("GL info: " + glGetString(GL_RENDERER) + " GL version " + glGetString(GL_VERSION) + ", " + glGetString(GL_VENDOR));
|
LOGGER.info("GL info: "+ glGetString(GL_RENDERER) + " GL version " + glGetString(GL_VERSION) + ", " + glGetString(GL_VENDOR));
|
||||||
|
|
||||||
elementShader = new ElementShader();
|
elementShader = new ElementShader();
|
||||||
try {
|
try {
|
||||||
@@ -235,7 +221,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
crashElegantly("An error occurred initializing shaders.");
|
crashElegantly("An error occurred initializing shaders.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the clear color based on the color scheme
|
// Set the clear color based on the colour scheme
|
||||||
glClearColor(colourScheme.background().redf(), colourScheme.background().greenf(), colourScheme.background().bluef(), 1f);
|
glClearColor(colourScheme.background().redf(), colourScheme.background().greenf(), colourScheme.background().bluef(), 1f);
|
||||||
|
|
||||||
// we always render to an 854x480 texture and then fit that to the screen - with a scale factor
|
// we always render to an 854x480 texture and then fit that to the screen - with a scale factor
|
||||||
@@ -261,15 +247,11 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
glEnable(GL_BLEND);
|
glEnable(GL_BLEND);
|
||||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
glfwMakeContextCurrent(0);
|
||||||
releaseGlContext();
|
|
||||||
|
|
||||||
this.windowTick = renderScheduler.scheduleAtFixedRate(this::renderThreadFunc, 50, 50, TimeUnit.MILLISECONDS);
|
this.windowTick = renderScheduler.scheduleAtFixedRate(this::renderThreadFunc, 50, 50, TimeUnit.MILLISECONDS);
|
||||||
|
this.performanceTick = renderScheduler.scheduleAtFixedRate(performanceInfo::update, 0, 500, TimeUnit.MILLISECONDS);
|
||||||
// Update the performance information every 1/2 second
|
|
||||||
renderScheduler.scheduleAtFixedRate(performanceInfo::update, 0, 500, TimeUnit.MILLISECONDS);
|
|
||||||
// schedule a 50 ms ticker to try and smooth out the rendering
|
// schedule a 50 ms ticker to try and smooth out the rendering
|
||||||
//renderScheduler.scheduleAtFixedRate(() -> animationTimerTrigger.set(true), 1, 50, TimeUnit.MILLISECONDS);
|
renderScheduler.scheduleAtFixedRate(()-> animationTimerTrigger.set(true), 1, 50, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -306,7 +288,6 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
glBindVertexArray(currentVAO);
|
glBindVertexArray(currentVAO);
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, currentFB);
|
glBindFramebuffer(GL_FRAMEBUFFER, currentFB);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start the window and Render Thread; we're ready to go.
|
* Start the window and Render Thread; we're ready to go.
|
||||||
*/
|
*/
|
||||||
@@ -333,18 +314,17 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
LOGGER.error("ERROR DISPLAY\n"+msgBuilder);
|
LOGGER.error("ERROR DISPLAY\n"+msgBuilder);
|
||||||
// we show the display on a new dedicated thread
|
// we show the display on a new dedicated thread
|
||||||
Executors.newSingleThreadExecutor().submit(()-> {
|
Executors.newSingleThreadExecutor().submit(()-> {
|
||||||
var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", 0);
|
var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", false);
|
||||||
if (res != 0) {
|
if (res) {
|
||||||
try {
|
try {
|
||||||
Desktop.getDesktop().browse(URI.create(ERROR_URL));
|
Desktop.getDesktop().browse(URI.create(ERROR_URL));
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", 0);
|
TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called to initialize the window when preparing for the Render Thread.
|
* Called to initialize the window when preparing for the Render Thread.
|
||||||
*
|
*
|
||||||
@@ -355,65 +335,71 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
* As long as we can verify that, then GL (and things like OS X) have no complaints with doing this.
|
* As long as we can verify that, then GL (and things like OS X) have no complaints with doing this.
|
||||||
*
|
*
|
||||||
* @param mcVersion Minecraft Version
|
* @param mcVersion Minecraft Version
|
||||||
|
* @return The selected GL profile as an integer pair
|
||||||
*/
|
*/
|
||||||
public void initWindow(@Nullable String mcVersion) {
|
public void initWindow(@Nullable String mcVersion) {
|
||||||
// Initialize a time guard, in case something goes wrong
|
// Initialize GLFW with a time guard, in case something goes wrong
|
||||||
long initBegin = System.nanoTime();
|
long glfwInitBegin = System.nanoTime();
|
||||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
if (!glfwInit()) {
|
||||||
crashElegantly("We are unable to initialize the graphics system.\nSDL_Init failed.\n");
|
crashElegantly("We are unable to initialize the graphics system.\nglfwInit failed.\n");
|
||||||
throw new IllegalStateException("Unable to initialize SDL");
|
throw new IllegalStateException("Unable to initialize GLFW");
|
||||||
}
|
}
|
||||||
long initEnd = System.nanoTime();
|
long glfwInitEnd = System.nanoTime();
|
||||||
|
|
||||||
if (initEnd - initBegin > 1e9)
|
if (glfwInitEnd - glfwInitBegin > 1e9) {
|
||||||
LOGGER.error("WARNING : Window init took {} seconds to start.", (initEnd - initBegin) / 1.0e9);
|
LOGGER.error("WARNING : glfwInit took {} seconds to start.", (glfwInitEnd - glfwInitBegin) / 1.0e9);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear the Last Exception (#7285 - Prevent Vanilla throwing an IllegalStateException due to invalid controller mappings)
|
||||||
|
handleLastGLFWError((error, description) -> LOGGER.error(String.format("Suppressing Last GLFW error: [0x%X]%s", error, description)));
|
||||||
|
|
||||||
// Set window hints for the new window we're gonna create.
|
// Set window hints for the new window we're gonna create.
|
||||||
SDL_ResetHints();
|
glfwDefaultWindowHints();
|
||||||
|
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
|
||||||
|
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
|
||||||
|
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
|
||||||
|
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
|
||||||
|
|
||||||
String vanillaWindowTitle = "Minecraft* ";
|
String vanillaWindowTitle = "Minecraft* ";
|
||||||
if (mcVersion != null)
|
if (mcVersion != null) vanillaWindowTitle += mcVersion;
|
||||||
vanillaWindowTitle += mcVersion;
|
|
||||||
|
|
||||||
var primaryMonitor = SDL_GetPrimaryDisplay();
|
// this emulates what we would get without early progress window
|
||||||
|
// as vanilla never sets these, so GLFW uses the first window title
|
||||||
|
// set them explicitly to avoid it using "FML early loading progress" as the class
|
||||||
|
glfwWindowHintString(GLFW_X11_CLASS_NAME, vanillaWindowTitle);
|
||||||
|
glfwWindowHintString(GLFW_X11_INSTANCE_NAME, vanillaWindowTitle);
|
||||||
|
|
||||||
|
long primaryMonitor = glfwGetPrimaryMonitor();
|
||||||
if (primaryMonitor == 0) {
|
if (primaryMonitor == 0) {
|
||||||
LOGGER.error("Failed to find a primary monitor - this means LWJGL isn't working properly");
|
LOGGER.error("Failed to find a primary monitor - this means LWJGL isn't working properly");
|
||||||
crashElegantly("Failed to locate a primary monitor.\nSDL_GetPrimaryDisplay failed.\n");
|
crashElegantly("Failed to locate a primary monitor.\nglfwGetPrimaryMonitor failed.\n");
|
||||||
throw new IllegalStateException("Can't find a primary monitor");
|
throw new IllegalStateException("Can't find a primary monitor");
|
||||||
}
|
}
|
||||||
|
GLFWVidMode vidmode = glfwGetVideoMode(primaryMonitor);
|
||||||
|
|
||||||
var vidmode = SDL_GetDesktopDisplayMode(primaryMonitor);
|
|
||||||
if (vidmode == null) {
|
if (vidmode == null) {
|
||||||
LOGGER.error("Failed to get the current display video mode.");
|
LOGGER.error("Failed to get the current display video mode.");
|
||||||
crashElegantly("Failed to get current display resolution.\nSDL_GetDesktopDisplayMode failed.\n");
|
crashElegantly("Failed to get current display resolution.\nglfwGetVideoMode failed.\n");
|
||||||
throw new IllegalStateException("Can't get a resolution");
|
throw new IllegalStateException("Can't get a resolution");
|
||||||
}
|
}
|
||||||
|
|
||||||
long window = 0;
|
long window = 0;
|
||||||
var successfulWindow = new AtomicBoolean(false);
|
var successfulWindow = new AtomicBoolean(false);
|
||||||
var windowFailFuture = renderScheduler.schedule(() -> {
|
var windowFailFuture = renderScheduler.schedule(()->{
|
||||||
if (!successfulWindow.get())
|
if (!successfulWindow.get()) crashElegantly("Timed out trying to setup the Game Window.");
|
||||||
crashElegantly("Timed out trying to setup the Game Window.");
|
|
||||||
}, 10, TimeUnit.SECONDS);
|
}, 10, TimeUnit.SECONDS);
|
||||||
|
int versidx = 0;
|
||||||
var skipVersions = FMLConfig.<String>getListConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SKIP_GL_VERSIONS);
|
var skipVersions = FMLConfig.<String>getListConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SKIP_GL_VERSIONS);
|
||||||
boolean showHelpLog = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG);
|
boolean showHelpLog = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG);
|
||||||
|
final String[] lastGLError = new String[GL_VERSIONS.length];
|
||||||
record Attempt(String vesion, String error) {}
|
do {
|
||||||
final List<Attempt> attempts = new ArrayList<>();
|
final var glVersionToTry = GL_VERSIONS[versidx][0] + "." + GL_VERSIONS[versidx][1];
|
||||||
String requestedVersion = null;
|
if (skipVersions.contains(glVersionToTry)) {
|
||||||
|
LOGGER.info("Skipping GL version "+ glVersionToTry+" because of configuration");
|
||||||
for (int x = 0; x < GL_VERSIONS.length; x++) {
|
versidx++;
|
||||||
var version = GL_VERSIONS[x];
|
|
||||||
requestedVersion = version[0] + "." + version[1];
|
|
||||||
|
|
||||||
if (skipVersions.contains(requestedVersion)) {
|
|
||||||
LOGGER.info("Skipping GL version " + requestedVersion + " because of configuration");
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
LOGGER.info("Trying GL version " + glVersionToTry);
|
||||||
LOGGER.info("Trying GL version " + requestedVersion);
|
if (showHelpLog && versidx == 0) {
|
||||||
if (showHelpLog && x == 0) {
|
|
||||||
LOGGER.info("""
|
LOGGER.info("""
|
||||||
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
|
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
|
||||||
|
|
||||||
@@ -425,105 +411,115 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
You can safely ignore this message if the game starts up successfully.""");
|
You can safely ignore this message if the game starts up successfully.""");
|
||||||
}
|
}
|
||||||
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSIONS[versidx][0]); // we try our versions one at a time
|
||||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, version[0]);
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GL_VERSIONS[versidx][1]);
|
||||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, version[1]);
|
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
|
||||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
|
||||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
|
window = glfwCreateWindow(winWidth, winHeight, vanillaWindowTitle, 0L, 0L);
|
||||||
SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, GL_TRUE);
|
var erridx = versidx;
|
||||||
window = SDL_CreateWindow(vanillaWindowTitle, winWidth, winHeight,
|
handleLastGLFWError((error, description) -> lastGLError[erridx] = String.format("Trying %d.%d: GLFW error: [0x%X]%s", GL_VERSIONS[erridx][0], GL_VERSIONS[erridx][1], error, description));
|
||||||
SDL_WINDOW_OPENGL
|
if (lastGLError[versidx] != null) {
|
||||||
| SDL_WINDOW_RESIZABLE
|
LOGGER.trace(lastGLError[versidx]);
|
||||||
| SDL_WINDOW_HIGH_PIXEL_DENSITY
|
|
||||||
);
|
|
||||||
|
|
||||||
if (window == 0) {
|
|
||||||
var error = Objects.requireNonNullElse(SDLError.SDL_GetError(), "<no error>");
|
|
||||||
attempts.add(new Attempt(requestedVersion, error));
|
|
||||||
LOGGER.trace("Failed to create window using %d.%d: %s", version[0], version[1], error);
|
|
||||||
} else {
|
|
||||||
SDLVideo.SDL_SetWindowMinimumSize(window, 320, 240);
|
|
||||||
LOGGER.info("Created window using SDL video driver: {}", SDLVideo.SDL_GetCurrentVideoDriver());
|
|
||||||
break; // We got a valid window!
|
|
||||||
}
|
}
|
||||||
}
|
versidx++;
|
||||||
|
} while (window == 0 && versidx < GL_VERSIONS.length);
|
||||||
|
// LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(12));
|
||||||
|
if (versidx== GL_VERSIONS.length && window == 0) {
|
||||||
|
LOGGER.error("Failed to find any valid GLFW profile. "+lastGLError[0]);
|
||||||
|
|
||||||
if (window == 0) {
|
crashElegantly("Failed to find a valid GLFW profile.\nWe tried "+
|
||||||
LOGGER.error("Failed to find any valid GLFW profile.");
|
Arrays.stream(GL_VERSIONS).map(p->p[0]+"."+p[1]).filter(o -> !skipVersions.contains(o))
|
||||||
var message = new StringBuilder()
|
.collect(Collector.of(()->new StringJoiner(", ").setEmptyValue("no versions"), StringJoiner::add, StringJoiner::merge, StringJoiner::toString))+
|
||||||
.append("Failed to find a valid GLFW profile.\n");
|
" but none of them worked.\n"+ Arrays.stream(lastGLError).filter(Objects::nonNull).collect(Collectors.joining("\n")));
|
||||||
|
|
||||||
if (attempts.isEmpty()) {
|
|
||||||
message.append("All GL Versions were skipped");
|
|
||||||
} else {
|
|
||||||
message.append("We tried:");
|
|
||||||
for (var attempt : attempts)
|
|
||||||
message.append("\n\t").append(attempt.vesion).append(':').append(attempt.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
crashElegantly(message.toString());
|
|
||||||
throw new IllegalStateException("Failed to create a GLFW window with any profile");
|
throw new IllegalStateException("Failed to create a GLFW window with any profile");
|
||||||
}
|
}
|
||||||
|
|
||||||
successfulWindow.set(true);
|
successfulWindow.set(true);
|
||||||
if (!windowFailFuture.cancel(true))
|
if (!windowFailFuture.cancel(true)) throw new IllegalStateException("We died but didn't somehow?");
|
||||||
throw new IllegalStateException("We died but didn't somehow?");
|
var requestedVersion = GL_VERSIONS[versidx-1][0]+"."+GL_VERSIONS[versidx-1][1];
|
||||||
|
var maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
|
||||||
try (var stack = org.lwjgl.system.MemoryStack.stackPush()) {
|
var min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
|
||||||
var majBuf = stack.mallocInt(1);
|
var gotVersion = maj+"."+min;
|
||||||
var minBuf = stack.mallocInt(1);
|
LOGGER.info("Requested GL version "+requestedVersion+" got version "+gotVersion);
|
||||||
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majBuf);
|
this.glVersion = gotVersion;
|
||||||
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minBuf);
|
|
||||||
this.glVersion = majBuf.get(0) + "." + minBuf.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
LOGGER.info("Requested GL version " + requestedVersion + " got version " + this.glVersion);
|
|
||||||
this.window = window;
|
this.window = window;
|
||||||
|
|
||||||
if (showHelpLog)
|
if (showHelpLog)
|
||||||
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG, false);
|
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG, false);
|
||||||
|
|
||||||
if (this.maximized)
|
int[] x = new int[1];
|
||||||
SDL_MaximizeWindow(window);
|
int[] y = new int[1];
|
||||||
|
glfwGetMonitorPos(primaryMonitor, x, y);
|
||||||
|
int monitorX = x[0];
|
||||||
|
int monitorY = y[0];
|
||||||
|
// glfwSetWindowSizeLimits(window, 854, 480, GLFW_DONT_CARE, GLFW_DONT_CARE);
|
||||||
|
if (this.maximized) {
|
||||||
|
glfwMaximizeWindow(window);
|
||||||
|
}
|
||||||
|
|
||||||
var size = getWindowSize(window);
|
glfwGetWindowSize(window, x, y);
|
||||||
this.onWindowResize(size.x, size.y);
|
this.winWidth = x[0];
|
||||||
|
this.winHeight = y[0];
|
||||||
|
|
||||||
var monitor = getMonitorSize(primaryMonitor);
|
glfwSetWindowPos(window, (vidmode.width() - this.winWidth) / 2 + monitorX, (vidmode.height() - this.winHeight) / 2 + monitorY);
|
||||||
if (monitor != null)
|
|
||||||
SDL_SetWindowPosition(window, (monitor.width - size.x) / 2 + monitor.x, (monitor.height - size.y) / 2 + monitor.y);
|
|
||||||
|
|
||||||
pollEvents();
|
// Attempt setting the icon
|
||||||
|
// int[] channels = new int[1];
|
||||||
|
// try (var glfwImgBuffer = GLFWImage.create(MemoryUtil.getAllocator().malloc(GLFWImage.SIZEOF), 1)) {
|
||||||
|
// final ByteBuffer imgBuffer;
|
||||||
|
// try (GLFWImage glfwImages = GLFWImage.malloc()) {
|
||||||
|
// imgBuffer = STBHelper.loadImageFromClasspath("forge_logo.png", 20000, x, y, channels);
|
||||||
|
// glfwImgBuffer.put(glfwImages.set(x[0], y[0], imgBuffer));
|
||||||
|
// glfwSetWindowIcon(window, glfwImgBuffer);
|
||||||
|
// STBImage.stbi_image_free(imgBuffer);
|
||||||
|
// }
|
||||||
|
// } catch (NullPointerException e) {
|
||||||
|
// System.err.println("Failed to load forge logo");
|
||||||
|
// }
|
||||||
|
// handleLastGLFWError((error, description) -> LOGGER.debug(String.format("Suppressing GLFW icon error: [0x%X]%s", error, description)));
|
||||||
|
|
||||||
SDL_ShowWindow(window);
|
glfwSetFramebufferSizeCallback(window, this::fbResize);
|
||||||
|
glfwSetWindowPosCallback(window, this::winMove);
|
||||||
|
glfwSetWindowSizeCallback(window, this::winResize);
|
||||||
|
|
||||||
|
// Show the window
|
||||||
|
glfwShowWindow(window);
|
||||||
|
glfwGetWindowPos(window, x, y);
|
||||||
|
this.winX = x[0];
|
||||||
|
this.winY = y[0];
|
||||||
|
glfwGetFramebufferSize(window, x, y);
|
||||||
|
this.fbWidth = x[0];
|
||||||
|
this.fbHeight = y[0];
|
||||||
|
glfwPollEvents();
|
||||||
}
|
}
|
||||||
|
|
||||||
private record Point(int x, int y) {}
|
private void winResize(long window, int width, int height) {
|
||||||
private record Rect(int x, int y, int width, int height) {}
|
if (window == this.window && width != 0 && height != 0) {
|
||||||
|
this.winWidth = width;
|
||||||
private static @Nullable Rect getMonitorSize(int monitor) {
|
this.winHeight = height;
|
||||||
try (var bounds = SDL_Rect.malloc()) {
|
}
|
||||||
// Fetch the display bounds for the current index
|
}
|
||||||
if (SDL_GetDisplayBounds(monitor, bounds)) {
|
private void fbResize(long window, int width, int height) {
|
||||||
int x = bounds.x();
|
if (window == this.window && width != 0 && height != 0) {
|
||||||
int y = bounds.y();
|
this.fbWidth = width;
|
||||||
int width = bounds.w();
|
this.fbHeight = height;
|
||||||
int height = bounds.h();
|
|
||||||
LOGGER.info("Display {} Bounds -> X: {}, Y: {}, Width: {}, Height: {}", monitor, x, y, width, height);
|
|
||||||
return new Rect(x, y, width, height);
|
|
||||||
} else {
|
|
||||||
LOGGER.warn("Could not get bounds for display: " + SDL_GetError());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Point getWindowSize(long window) {
|
private void winMove(long window, int x, int y) {
|
||||||
try (var stack = MemoryStack.stackPush()) {
|
if (window == this.window) {
|
||||||
var width = stack.mallocInt(1);
|
this.winX = x;
|
||||||
var height = stack.mallocInt(1);
|
this.winY = y;
|
||||||
SDL_GetWindowSize(window, width, height);
|
}
|
||||||
return new Point(width.get(0), height.get(0));
|
}
|
||||||
|
private static void handleLastGLFWError(BiConsumer<Integer, String> handler) {
|
||||||
|
try (MemoryStack memorystack = MemoryStack.stackPush()) {
|
||||||
|
PointerBuffer pointerbuffer = memorystack.mallocPointer(1);
|
||||||
|
int error = glfwGetError(pointerbuffer);
|
||||||
|
if (error != GLFW_NO_ERROR) {
|
||||||
|
long pDescription = pointerbuffer.get();
|
||||||
|
String description = pDescription == 0L ? "" : MemoryUtil.memUTF8(pDescription);
|
||||||
|
handler.accept(error, description);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,8 +529,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
*
|
*
|
||||||
* @return the Window we own.
|
* @return the Window we own.
|
||||||
*/
|
*/
|
||||||
@Override
|
public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitorSupplier) {
|
||||||
public long setupMinecraftWindow(final int width, final int height, final String title, final Supplier<Object> backend) {
|
|
||||||
// wait for the window to actually be initialized
|
// wait for the window to actually be initialized
|
||||||
try {
|
try {
|
||||||
this.initializationFuture.get(30, TimeUnit.SECONDS);
|
this.initializationFuture.get(30, TimeUnit.SECONDS);
|
||||||
@@ -554,11 +549,11 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
var renderlockticket = false;
|
var renderlockticket = false;
|
||||||
do {
|
do {
|
||||||
try {
|
try {
|
||||||
renderlockticket = renderLock.tryAcquire(100, TimeUnit.MILLISECONDS);
|
renderlockticket = renderLock.tryAcquire(100, TimeUnit.MILLISECONDS);
|
||||||
if (++tries > 9) {
|
if (++tries > 9) {
|
||||||
Thread.dumpStack();
|
Thread.dumpStack();
|
||||||
crashElegantly("We seem to be having trouble handing off the window, tried for 1 second");
|
crashElegantly("We seem to be having trouble handing off the window, tried for 1 second");
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.interrupted();
|
Thread.interrupted();
|
||||||
}
|
}
|
||||||
@@ -566,10 +561,14 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
// we don't want the lock, just making sure it's back on the main thread
|
// we don't want the lock, just making sure it's back on the main thread
|
||||||
renderLock.release();
|
renderLock.release();
|
||||||
|
|
||||||
SDL_GL_MakeCurrent(window, sdlContext);
|
glfwMakeContextCurrent(window);
|
||||||
// Set the title to what the game wants
|
// Set the title to what the game wants
|
||||||
SDL_SetWindowTitle(window, title);
|
glfwSetWindowTitle(window, title.get());
|
||||||
SDL_GL_SetSwapInterval(0); // Disable vsync, let Minecraft control it
|
glfwSwapInterval(0);
|
||||||
|
// Clean up our hooks
|
||||||
|
glfwSetFramebufferSizeCallback(window, null).free();
|
||||||
|
glfwSetWindowPosCallback(window, null).free();
|
||||||
|
glfwSetWindowSizeCallback(window, null).free();
|
||||||
this.repaintTick = this::renderThreadFunc; // the repaint will continue to be called until the overlay takes over
|
this.repaintTick = this::renderThreadFunc; // the repaint will continue to be called until the overlay takes over
|
||||||
this.windowTick = null; // this tells the render thread that the async ticker is done
|
this.windowTick = null; // this tells the render thread that the async ticker is done
|
||||||
return window;
|
return window;
|
||||||
@@ -635,7 +634,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void periodicTick() {
|
public void periodicTick() {
|
||||||
pollEvents();
|
glfwPollEvents();
|
||||||
repaintTick.run();
|
repaintTick.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -650,67 +649,4 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
this.context.elementShader().close();
|
this.context.elementShader().close();
|
||||||
SimpleBufferBuilder.destroy();
|
SimpleBufferBuilder.destroy();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
private void bindGlContext() {
|
|
||||||
SDL_GL_MakeCurrent(window, sdlContext);
|
|
||||||
//if (!SDL_GL_MakeCurrent(window, sdlContext))
|
|
||||||
// throw new IllegalStateException("Failed to make OpenGL context current: " + SDL_GetError());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void releaseGlContext() {
|
|
||||||
SDL_GL_MakeCurrent(window, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private void pollEvents() {
|
|
||||||
try (var event = SDL_Event.malloc()) {
|
|
||||||
while (SDL_PollEvent(event)) {
|
|
||||||
switch (event.type()) {
|
|
||||||
case SDL_EVENT_WINDOW_MOVED:
|
|
||||||
this.onWindowMove(event.window().data1(), event.window().data2());
|
|
||||||
break;
|
|
||||||
case SDL_EVENT_WINDOW_RESIZED:
|
|
||||||
this.onWindowResize(event.window().data1(), event.window().data2());
|
|
||||||
break;
|
|
||||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
|
|
||||||
this.onFrameBufferResize(event.window().data1(), event.window().data2());
|
|
||||||
break;
|
|
||||||
|
|
||||||
/*
|
|
||||||
We were told to quit for some reason, find a way to abort?
|
|
||||||
case SDL_EVENT_QUIT:
|
|
||||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
|
||||||
case SDL_EVENT_TERMINATING:
|
|
||||||
|
|
||||||
Window was minimized or restored, maybe stop rendering?
|
|
||||||
case SDL_EVENT_WINDOW_MINIMIZED:
|
|
||||||
case SDL_EVENT_WINDOW_MAXIMIZED:
|
|
||||||
case SDL_EVENT_WINDOW_RESTORED:
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onWindowResize(int width, int height) {
|
|
||||||
if (width == 0 || height == 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
this.winWidth = width;
|
|
||||||
this.winHeight = height;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onFrameBufferResize(int width, int height) {
|
|
||||||
if (width == 0 || height == 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
this.fbWidth = width;
|
|
||||||
this.fbHeight = height;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onWindowMove(int x, int y) {
|
|
||||||
this.winX = x;
|
|
||||||
this.winY = y;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+22
-8
@@ -11,6 +11,8 @@ import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
import static org.lwjgl.opengl.GL32C.*;
|
import static org.lwjgl.opengl.GL32C.*;
|
||||||
|
|
||||||
public class RenderElement {
|
public class RenderElement {
|
||||||
@@ -37,6 +39,11 @@ public class RenderElement {
|
|||||||
void accept(SimpleBufferBuilder bb, DisplayContext context, int[] size, int frame);
|
void accept(SimpleBufferBuilder bb, DisplayContext context, int[] size, int frame);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @deprecated Use {@link Renderer} directly. This was always eagerly resolved, making it an unnecessary wrapper. */
|
||||||
|
@Deprecated(since = "1.21.5", forRemoval = true)
|
||||||
|
@FunctionalInterface
|
||||||
|
interface Initializer extends Supplier<Renderer> {}
|
||||||
|
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
interface TextGenerator {
|
interface TextGenerator {
|
||||||
void accept(SimpleBufferBuilder bb, SimpleFont fh, DisplayContext ctx);
|
void accept(SimpleBufferBuilder bb, SimpleFont fh, DisplayContext ctx);
|
||||||
@@ -52,6 +59,13 @@ public class RenderElement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @deprecated Use {@link RenderElement#RenderElement(Renderer)} instead */
|
||||||
|
@Deprecated(since = "1.21.5", forRemoval = true)
|
||||||
|
public RenderElement(final Initializer rendererInitializer) {
|
||||||
|
this.bb = new SimpleBufferBuilder(1);
|
||||||
|
this.renderer = rendererInitializer.get();
|
||||||
|
}
|
||||||
|
|
||||||
public RenderElement(Renderer renderer) {
|
public RenderElement(Renderer renderer) {
|
||||||
this.bb = new SimpleBufferBuilder(1);
|
this.bb = new SimpleBufferBuilder(1);
|
||||||
this.renderer = renderer;
|
this.renderer = renderer;
|
||||||
@@ -102,7 +116,7 @@ public class RenderElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static RenderElement forgeVersionOverlay(SimpleFont font, String version) {
|
public static RenderElement forgeVersionOverlay(SimpleFont font, String version) {
|
||||||
return new RenderElement(RenderElement.initializeText(font, (bb, _, ctx)->
|
return new RenderElement(RenderElement.initializeText(font, (bb, fnt, ctx)->
|
||||||
font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10,
|
font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10,
|
||||||
ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb,
|
ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb,
|
||||||
new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha)))));
|
new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha)))));
|
||||||
@@ -164,11 +178,11 @@ public class RenderElement {
|
|||||||
var colour = (alpha << 24) | 0xFFFFFF;
|
var colour = (alpha << 24) | 0xFFFFFF;
|
||||||
Renderer bar;
|
Renderer bar;
|
||||||
if (pm.steps() == 0) {
|
if (pm.steps() == 0) {
|
||||||
bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _->colour, frame -> indeterminateBar(frame, cnt == 0));
|
bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f->colour, frame -> indeterminateBar(frame, cnt == 0));
|
||||||
} else {
|
} else {
|
||||||
bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pm.progress()});
|
bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pm.progress()});
|
||||||
}
|
}
|
||||||
Renderer label = (bb, ctx, _) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx);
|
Renderer label = (bb, ctx, frame) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx);
|
||||||
return bar.then(label);
|
return bar.then(label);
|
||||||
}
|
}
|
||||||
private static float[] indeterminateBar(int frame, boolean isActive) {
|
private static float[] indeterminateBar(int frame, boolean isActive) {
|
||||||
@@ -184,9 +198,9 @@ public class RenderElement {
|
|||||||
var y = 10 * context.scale();
|
var y = 10 * context.scale();
|
||||||
PerformanceInfo pi = context.performance();
|
PerformanceInfo pi = context.performance();
|
||||||
final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f);
|
final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f);
|
||||||
var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pi.memory()});
|
var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pi.memory()});
|
||||||
var width = font.stringWidth(pi.text());
|
var width = font.stringWidth(pi.text());
|
||||||
Renderer label = (bb, ctx, _) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx);
|
Renderer label = (bb, ctx, frame) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx);
|
||||||
bar.then(label).accept(buffer, context, frameNumber);
|
bar.then(label).accept(buffer, context, frameNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,7 +250,7 @@ public class RenderElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) {
|
private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) {
|
||||||
return (bb, context, _) -> renderText(font, textGenerator, bb, context);
|
return (bb, context, frame) -> renderText(font, textGenerator, bb, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) {
|
private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) {
|
||||||
@@ -248,7 +262,7 @@ public class RenderElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static TextGenerator text(int x, int y, String text, int colour) {
|
private static TextGenerator text(int x, int y, String text, int colour) {
|
||||||
return (bb, font, _) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour));
|
return (bb, font, context) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) {
|
private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) {
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
|
||||||
id 'jvm-test-suite'
|
|
||||||
}
|
|
||||||
|
|
||||||
gradleutils.displayName = 'FMLLoader-Tests'
|
|
||||||
description = 'JUnit tests for FMLLoader, not meant for distribution'
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
testImplementation(project(':fmlloader'))
|
|
||||||
testImplementation(libs.guava)
|
|
||||||
testImplementation(libs.junit.api)
|
|
||||||
testRuntimeOnly(libs.bundles.junit.runtime)
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('test') {
|
|
||||||
useJUnitPlatform()
|
|
||||||
}
|
|
||||||
-172
@@ -1,172 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.fml.loading.test;
|
|
||||||
|
|
||||||
import com.google.common.graph.Graph;
|
|
||||||
import com.google.common.graph.GraphBuilder;
|
|
||||||
import com.google.common.graph.MutableGraph;
|
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.toposort.CyclePresentException;
|
|
||||||
import net.minecraftforge.fml.loading.toposort.StronglyConnectedComponentDetector;
|
|
||||||
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
|
|
||||||
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tests for {@link TopologicalSort} and {@link StronglyConnectedComponentDetector}
|
|
||||||
*/
|
|
||||||
class TopologicalSortTest {
|
|
||||||
@Test
|
|
||||||
void resultProperlySorted() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("a", "c");
|
|
||||||
graph.putEdge("b", "c");
|
|
||||||
var sorted = TopologicalSort.topologicalSort(graph, Comparator.naturalOrder());
|
|
||||||
assertEquals(List.of("a", "b", "c"), sorted);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void throwsOnCycle() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("b", "a");
|
|
||||||
|
|
||||||
var exception = Assertions.assertThrows(CyclePresentException.class, () -> TopologicalSort.topologicalSort(graph, Comparator.naturalOrder()));
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("a", "b")
|
|
||||||
), exception.getCycles());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void simpleCycle() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
// a -> b -> c -> a
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("b", "c");
|
|
||||||
graph.putEdge("c", "a");
|
|
||||||
|
|
||||||
var cycles = cyclesOf(graph);
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("a", "b", "c")
|
|
||||||
), cycles);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void noCycle() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("a", "c");
|
|
||||||
graph.putEdge("b", "d");
|
|
||||||
graph.putEdge("c", "d");
|
|
||||||
graph.putEdge("d", "e");
|
|
||||||
|
|
||||||
var cycles = cyclesOf(graph);
|
|
||||||
assertTrue(cycles.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Regression test: the previous implementation lowered the lowlink of a node from every already-visited
|
|
||||||
* successor, including successors whose component was already completed. That merged nodes into the wrong
|
|
||||||
* component, so a member of the real cycle ({@code c}) was missing from the reported cycle.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void reportsAllMembersOfCycle() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
graph.addNode("a");
|
|
||||||
graph.addNode("b");
|
|
||||||
graph.addNode("c");
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("a", "c");
|
|
||||||
graph.putEdge("b", "a");
|
|
||||||
graph.putEdge("c", "b");
|
|
||||||
|
|
||||||
var cycles = cyclesOf(graph);
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("a", "b", "c")
|
|
||||||
), cycles);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Regression test: the previous implementation invented a cycle out of {@code c -> d -> a}, which is a plain
|
|
||||||
* path, because it compared against the DFS depth instead of a discovery counter and ignored whether a
|
|
||||||
* successor was still on the stack.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void doesNotInventCycles() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
graph.addNode("a");
|
|
||||||
graph.addNode("b");
|
|
||||||
graph.addNode("c");
|
|
||||||
graph.addNode("d");
|
|
||||||
graph.putEdge("a", "b");
|
|
||||||
graph.putEdge("b", "a");
|
|
||||||
graph.putEdge("c", "d");
|
|
||||||
graph.putEdge("d", "a");
|
|
||||||
|
|
||||||
var cycles = cyclesOf(graph);
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("a", "b")
|
|
||||||
), cycles);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reproduces the shape of the mod graphs that reported bogus cycles in the wild: one real three-node cycle,
|
|
||||||
* with nodes that merely depend on members of the cycle and a node on a plain path into it.
|
|
||||||
*
|
|
||||||
* <p>Every reported component must be the real cycle itself; nodes such as {@code dependent_a} only depend on
|
|
||||||
* the cycle and must not be reported.
|
|
||||||
*
|
|
||||||
* @see <a href="https://github.com/MinecraftForge/MinecraftForge/pull/10924">related GitHub issue</a>
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
void reportsOnlyRealCycles() {
|
|
||||||
MutableGraph<String> graph = GraphBuilder.directed().build();
|
|
||||||
// Mirrors the insertion order of ModSorter: every mod is added as a node first, edges are added afterwards.
|
|
||||||
for (String mod : List.of("upstream", "cycle_a", "cycle_b", "dependent_a", "cycle_c", "dependent_b")) {
|
|
||||||
graph.addNode(mod);
|
|
||||||
}
|
|
||||||
// a -> b -> a
|
|
||||||
graph.putEdge("cycle_a", "cycle_b");
|
|
||||||
graph.putEdge("cycle_b", "cycle_a");
|
|
||||||
// a -> c -> b -> a
|
|
||||||
graph.putEdge("cycle_a", "cycle_c");
|
|
||||||
graph.putEdge("cycle_c", "cycle_b");
|
|
||||||
// dA -> b -> a - Valid
|
|
||||||
graph.putEdge("dependent_a", "cycle_b");
|
|
||||||
// dB -> b -> a - Valid
|
|
||||||
graph.putEdge("dependent_b", "cycle_b");
|
|
||||||
// u -> a -> b -> a - Not valid, but u is not part of the cycle so shouldn't be reported
|
|
||||||
graph.putEdge("upstream", "cycle_a");
|
|
||||||
|
|
||||||
var cycles = cyclesOf(graph);
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("cycle_a", "cycle_b", "cycle_c")
|
|
||||||
), cycles);
|
|
||||||
|
|
||||||
var exception = Assertions.assertThrows(CyclePresentException.class, () -> TopologicalSort.topologicalSort(graph, Comparator.naturalOrder()));
|
|
||||||
assertEquals(Set.of(
|
|
||||||
Set.of("cycle_a", "cycle_b", "cycle_c")
|
|
||||||
), exception.getCycles());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Set<Set<String>> cyclesOf(Graph<String> graph) {
|
|
||||||
var detector = new StronglyConnectedComponentDetector<>(graph);
|
|
||||||
var connected = detector.getComponents();
|
|
||||||
var cycles = new HashSet<>(connected);
|
|
||||||
cycles.removeIf(component -> component.size() < 2);
|
|
||||||
return cycles;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
+117
-14
@@ -1,15 +1,44 @@
|
|||||||
|
import groovy.transform.CompileDynamic
|
||||||
|
import groovy.transform.CompileStatic
|
||||||
|
import groovy.transform.PackageScope
|
||||||
import net.minecraftforge.forgedev.legacy.tasks.JarJarMetadataOptions
|
import net.minecraftforge.forgedev.legacy.tasks.JarJarMetadataOptions
|
||||||
|
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||||
|
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
id 'java-library'
|
||||||
|
id 'jvm-test-suite'
|
||||||
|
id 'maven-publish'
|
||||||
|
alias libs.plugins.licenser
|
||||||
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
alias libs.plugins.apt
|
alias libs.plugins.apt
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
gradleutils.displayName = 'FMLLoader'
|
gradleutils.displayName = 'FMLLoader'
|
||||||
description = 'Mod Locator and manager for Minecraft Forge.'
|
final vendor = 'Forge Development LLC'
|
||||||
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
withSourcesJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
license {
|
||||||
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
|
}
|
||||||
|
|
||||||
|
changelog {
|
||||||
|
from changelogBase
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
// TODO [FMLLoader] Figure out a better way to lock transitive dependencies to the explicit versions shipped by the installer
|
compileOnly libs.jetbrains.annotations
|
||||||
|
|
||||||
|
// TODO [FMLLoader] Figure out a better way to lock transitive dependencies to the explicit versions shipped by the isntaller
|
||||||
api(libs.bundles.asm ){ transitive = false } // Needed by all the black magic
|
api(libs.bundles.asm ){ transitive = false } // Needed by all the black magic
|
||||||
api(libs.forgespi ){ transitive = false }
|
api(libs.forgespi ){ transitive = false }
|
||||||
api(libs.mergetool.api ){ transitive = false }
|
api(libs.mergetool.api ){ transitive = false }
|
||||||
@@ -29,26 +58,100 @@ dependencies {
|
|||||||
implementation(libs.securemodules ){ transitive = false }
|
implementation(libs.securemodules ){ transitive = false }
|
||||||
implementation(libs.accesstransformers ){ transitive = false }
|
implementation(libs.accesstransformers ){ transitive = false }
|
||||||
implementation(libs.terminalconsoleappender){ transitive = false }
|
implementation(libs.terminalconsoleappender){ transitive = false }
|
||||||
implementation(libs.roimfs ){ transitive = false }
|
implementation(libs.jimfs ){ transitive = false }
|
||||||
|
|
||||||
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
|
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
|
||||||
implementation(libs.log4j.core ){ transitive = false }
|
implementation(libs.log4j.core ){ transitive = false }
|
||||||
annotationProcessor(libs.bundles.log4j){ transitive = false }
|
annotationProcessor(libs.bundles.log4j){ transitive = false }
|
||||||
}
|
}
|
||||||
|
|
||||||
convention.manifest('net/minecraftforge/fml/loading/', [
|
testing.suites.named('test', JvmTestSuite) {
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.fmlloader',
|
dependencies {
|
||||||
'Forge-Module-Layer' : 'boot'
|
compileOnly libs.jetbrains.annotations
|
||||||
])
|
runtimeOnly libs.bootstrap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
convention.publish()
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.compilerArgs << '-Xlint:unchecked'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('jar', Jar) {
|
||||||
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.fmlloader',
|
||||||
|
'Forge-Module-Layer' : 'boot'
|
||||||
|
])
|
||||||
|
attributes([
|
||||||
|
'Specification-Title' : gradleutils.displayName.get(),
|
||||||
|
'Specification-Vendor' : vendor,
|
||||||
|
'Specification-Version' : '1',
|
||||||
|
'Implementation-Title' : gradleutils.displayName.get(),
|
||||||
|
'Implementation-Vendor' : vendor,
|
||||||
|
'Implementation-Version': forgeVersion
|
||||||
|
], 'net/minecraftforge/fml/loading/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven gradleutils.publishingForgeMaven
|
||||||
|
}
|
||||||
|
|
||||||
|
publications.register('mavenJava', MavenPublication) {
|
||||||
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
from components.java
|
||||||
|
|
||||||
|
pom {
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A simple task to write JSON to a file. Using Task#doLast to output files is no longer supported.
|
||||||
|
// This code may seem verbose, but it's better this way. If more projects need this, we can move it to buildSrc.
|
||||||
|
@CompileStatic
|
||||||
|
@PackageScope abstract class WriteForgeVersionJson extends DefaultTask {
|
||||||
|
abstract @Input Property<String> getForgeVersion()
|
||||||
|
abstract @Input Property<String> getMinecraftVersion()
|
||||||
|
abstract @Input Property<String> getMcpVersion()
|
||||||
|
|
||||||
|
abstract @OutputFile RegularFileProperty getOutputFile()
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
WriteForgeVersionJson() {}
|
||||||
|
|
||||||
|
@TaskAction
|
||||||
|
@CompileDynamic
|
||||||
|
void exec() {
|
||||||
|
var json = new groovy.json.JsonBuilder()
|
||||||
|
json {
|
||||||
|
forge this.forgeVersion.get()
|
||||||
|
mc this.minecraftVersion.get()
|
||||||
|
mcp this.mcpVersion.get()
|
||||||
|
}
|
||||||
|
this.outputFile.asFile.get().text = json.toPrettyString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('writeForgeVersionJson', WriteForgeVersionJson) {
|
||||||
|
forgeVersion = project.forgeVersion
|
||||||
|
minecraftVersion = project.minecraftVersion
|
||||||
|
mcpVersion = project.mcpVersion
|
||||||
|
|
||||||
final forgeJson = convention.forgeVersionJson {
|
|
||||||
outputFile = file('src/main/resources/forge_version.json')
|
outputFile = file('src/main/resources/forge_version.json')
|
||||||
}
|
}
|
||||||
|
|
||||||
final jarJarJson = tasks.register('jarJarOptionsJson', JarJarMetadataOptions) {
|
tasks.register('jarJarOptionsJson', JarJarMetadataOptions) {
|
||||||
metadataFile = file('src/main/resources/jarjar_options.json')
|
metadataFile = project.file('src/main/resources/jarjar_options.json')
|
||||||
// This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually...
|
// This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually...
|
||||||
//add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class')
|
//add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class')
|
||||||
add(libs.mixinextras.forge) {
|
add(libs.mixinextras.forge) {
|
||||||
@@ -67,8 +170,8 @@ tasks.named('generateResources') {
|
|||||||
tasks.named('eclipseJdt'),
|
tasks.named('eclipseJdt'),
|
||||||
tasks.named('eclipseJdtApt'),
|
tasks.named('eclipseJdtApt'),
|
||||||
tasks.named('eclipseFactorypath'),
|
tasks.named('eclipseFactorypath'),
|
||||||
forgeJson,
|
tasks.named('writeForgeVersionJson', WriteForgeVersionJson),
|
||||||
jarJarJson
|
tasks.named('jarJarOptionsJson')
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
|
|
||||||
private static final class LazyInit {
|
private static final class LazyInit {
|
||||||
private LazyInit() {}
|
private LazyInit() {}
|
||||||
private static final boolean ANY_MODS = LoadingModList.getMods().size() > 2; // 2: forge, minecraft
|
private static final boolean ANY_MODS = LoadingModList.get().getMods().size() > 2; // 2: forge, minecraft
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -136,7 +136,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
classNode.methods.stream().filter(m -> m.name.equals("<init>")).forEach(m -> sb.append(" : ").append(m.desc).append("\n"));
|
classNode.methods.stream().filter(m -> m.name.equals("<init>")).forEach(m -> sb.append(" : ").append(m.desc).append("\n"));
|
||||||
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
||||||
}
|
}
|
||||||
throw new IllegalStateException("Enum has create method with no matching constructor: " + classType.getClassName() + " " + desc);
|
throw new IllegalStateException("Enum has create method with no matching constructor: " + desc);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (values == null)
|
if (values == null)
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ public class FMLConfig
|
|||||||
}
|
}
|
||||||
if (!configSpec.isCorrect(configData)) {
|
if (!configSpec.isCorrect(configData)) {
|
||||||
LOGGER.warn(CORE, "Configuration file {} is not correct. Correcting", configFile);
|
LOGGER.warn(CORE, "Configuration file {} is not correct. Correcting", configFile);
|
||||||
configSpec.correct(configData, (_, path, incorrectValue, correctedValue) ->
|
configSpec.correct(configData, (action, path, incorrectValue, correctedValue) ->
|
||||||
LOGGER.info(CORE, "Incorrect key {} was corrected from {} to {}", path, incorrectValue, correctedValue));
|
LOGGER.info(CORE, "Incorrect key {} was corrected from {} to {}", path, incorrectValue, correctedValue));
|
||||||
}
|
}
|
||||||
configData.putAllComments(configComments);
|
configData.putAllComments(configComments);
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ public class FMLEnvironment
|
|||||||
public static final boolean secureJarsEnabled = FMLLoader.isSecureJarEnabled();
|
public static final boolean secureJarsEnabled = FMLLoader.isSecureJarEnabled();
|
||||||
|
|
||||||
static void setupInteropEnvironment(IEnvironment environment) {
|
static void setupInteropEnvironment(IEnvironment environment) {
|
||||||
environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), _->naming);
|
environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), v->naming);
|
||||||
environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), _->dist);
|
environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), v->dist);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Keys {
|
public static class Keys {
|
||||||
|
|||||||
@@ -30,11 +30,13 @@ import java.util.function.BiFunction;
|
|||||||
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
|
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
|
||||||
import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
|
import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
|
||||||
|
|
||||||
public final class FMLLoader {
|
public class FMLLoader {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static AccessTransformerService accessTransformer;
|
private static AccessTransformerService accessTransformer;
|
||||||
|
private static LanguageLoadingProvider languageLoadingProvider;
|
||||||
private static Dist dist;
|
private static Dist dist;
|
||||||
private static String naming;
|
private static String naming;
|
||||||
|
private static LoadingModList loadingModList;
|
||||||
private static RuntimeDistCleaner runtimeDistCleaner;
|
private static RuntimeDistCleaner runtimeDistCleaner;
|
||||||
private static Path gamePath;
|
private static Path gamePath;
|
||||||
private static final VersionInfo versionInfo = VersionInfo.detect();
|
private static final VersionInfo versionInfo = VersionInfo.detect();
|
||||||
@@ -149,11 +151,16 @@ public final class FMLLoader {
|
|||||||
|
|
||||||
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
|
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
|
||||||
moduleLayerManager = layerManager;
|
moduleLayerManager = layerManager;
|
||||||
LanguageLoadingProvider.reload();
|
languageLoadingProvider = new LanguageLoadingProvider();
|
||||||
backgroundScanHandler = modValidator.stage2Validation();
|
backgroundScanHandler = modValidator.stage2Validation();
|
||||||
|
loadingModList = backgroundScanHandler.getLoadingModList();
|
||||||
return List.of(modValidator.getModResources());
|
return List.of(modValidator.getModResources());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static LanguageLoadingProvider getLanguageLoadingProvider() {
|
||||||
|
return languageLoadingProvider;
|
||||||
|
}
|
||||||
|
|
||||||
public static CommonLaunchHandler getLaunchHandler() {
|
public static CommonLaunchHandler getLaunchHandler() {
|
||||||
return commonLaunchHandler;
|
return commonLaunchHandler;
|
||||||
}
|
}
|
||||||
@@ -173,6 +180,10 @@ public final class FMLLoader {
|
|||||||
progressWindowTick.run();
|
progressWindowTick.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static LoadingModList getLoadingModList() {
|
||||||
|
return loadingModList;
|
||||||
|
}
|
||||||
|
|
||||||
public static Path getGamePath() {
|
public static Path getGamePath() {
|
||||||
return gamePath;
|
return gamePath;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import net.minecraftforge.forgespi.Environment;
|
|||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
@@ -41,7 +42,7 @@ public class FMLServiceProvider implements ITransformationService {
|
|||||||
LOGGER.debug(CORE, "Loading configuration");
|
LOGGER.debug(CORE, "Loading configuration");
|
||||||
FMLConfig.load();
|
FMLConfig.load();
|
||||||
LOGGER.debug(CORE, "Preparing ModFile");
|
LOGGER.debug(CORE, "Preparing ModFile");
|
||||||
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), _->ModFile::new);
|
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), k->ModFile::new);
|
||||||
LOGGER.debug(CORE, "Preparing launch handler");
|
LOGGER.debug(CORE, "Preparing launch handler");
|
||||||
FMLLoader.setupLaunchHandler(environment, arguments);
|
FMLLoader.setupLaunchHandler(environment, arguments);
|
||||||
FMLEnvironment.setupInteropEnvironment(environment);
|
FMLEnvironment.setupInteropEnvironment(environment);
|
||||||
|
|||||||
@@ -10,13 +10,8 @@ import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
|||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
import joptsimple.OptionParser;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.function.*;
|
import java.util.function.*;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -46,64 +41,18 @@ public class ImmediateWindowHandler {
|
|||||||
if (provider == null) {
|
if (provider == null) {
|
||||||
LOGGER.info("Failed to find ImmediateWindowProvider {}, disabling", providername);
|
LOGGER.info("Failed to find ImmediateWindowProvider {}, disabling", providername);
|
||||||
provider = new DummyProvider();
|
provider = new DummyProvider();
|
||||||
} else {
|
|
||||||
var backend = findBackend(arguments);
|
|
||||||
var newProvider = provider.selectBackend(backend);
|
|
||||||
if (provider != newProvider) {
|
|
||||||
if (newProvider == null)
|
|
||||||
newProvider = new DummyProvider();
|
|
||||||
|
|
||||||
LOGGER.info("ImmediateWindowProvider {} does not support {}, switching to {}", provider.name(), backend, newProvider.name());
|
|
||||||
provider = newProvider;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only update config if the provider isn't the dummy provider
|
// Only update config if the provider isn't the dummy provider
|
||||||
if (!Objects.equals(provider.name(), "dummyprovider"))
|
if (!Objects.equals(provider.name(), "dummyprovider"))
|
||||||
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER, provider.name());
|
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER, provider.name());
|
||||||
|
|
||||||
FMLLoader.progressWindowTick = provider.initialize(arguments);
|
FMLLoader.progressWindowTick = provider.initialize(arguments);
|
||||||
earlyProgress = StartupNotificationManager.addProgressBar("EARLY", 0);
|
earlyProgress = StartupNotificationManager.addProgressBar("EARLY", 0);
|
||||||
earlyProgress.label("Bootstrapping Minecraft");
|
earlyProgress.label("Bootstrapping Minecraft");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String findBackend(String[] arguments) {
|
public static long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
|
||||||
// Try and parse from the command line arguments
|
return provider.setupMinecraftWindow(width, height, title, monitor);
|
||||||
var parser = new OptionParser();
|
|
||||||
var backendOption = parser.accepts("graphicsBackend").withRequiredArg();
|
|
||||||
parser.allowsUnrecognizedOptions();
|
|
||||||
var parsed = parser.parse(arguments);
|
|
||||||
|
|
||||||
if (parsed.has(backendOption))
|
|
||||||
return parsed.valueOf(backendOption).toLowerCase(Locale.ENGLISH);
|
|
||||||
|
|
||||||
|
|
||||||
// Read the options.txt if it exists.
|
|
||||||
var optionsFile = FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt"));
|
|
||||||
if (!Files.exists(optionsFile)) // Default is OpenGL first
|
|
||||||
return "default";
|
|
||||||
|
|
||||||
List<String> lines = null;
|
|
||||||
try {
|
|
||||||
lines = Files.readAllLines(optionsFile);
|
|
||||||
} catch (IOException e) {
|
|
||||||
return "default"; // We failed to read for some reason, assume we're using the default.
|
|
||||||
}
|
|
||||||
|
|
||||||
final String key = "preferredGraphicsBackend:";
|
|
||||||
for (var line : lines) {
|
|
||||||
if (line.startsWith(key)) {
|
|
||||||
var backend = line.substring(key.length() + 1, line.length() - 1);
|
|
||||||
return backend.toLowerCase(Locale.ENGLISH);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "default";
|
|
||||||
}
|
|
||||||
|
|
||||||
public static long setupMinecraftWindow(final int width, final int height, final String title, final Supplier<Object> backend) {
|
|
||||||
return provider.setupMinecraftWindow(width, height, title, backend);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean positionWindow(Optional<Object> monitor,IntConsumer widthSetter, IntConsumer heightSetter, IntConsumer xSetter, IntConsumer ySetter) {
|
public static boolean positionWindow(Optional<Object> monitor,IntConsumer widthSetter, IntConsumer heightSetter, IntConsumer xSetter, IntConsumer ySetter) {
|
||||||
@@ -134,7 +83,7 @@ public class ImmediateWindowHandler {
|
|||||||
earlyProgress.label(message);
|
earlyProgress.label(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
record DummyProvider() implements ImmediateWindowProvider {
|
private record DummyProvider() implements ImmediateWindowProvider {
|
||||||
private static Method NV_HANDOFF;
|
private static Method NV_HANDOFF;
|
||||||
private static Method NV_POSITION;
|
private static Method NV_POSITION;
|
||||||
private static Method NV_OVERLAY;
|
private static Method NV_OVERLAY;
|
||||||
@@ -155,9 +104,9 @@ public class ImmediateWindowHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long setupMinecraftWindow(final int width, final int height, final String title, final Supplier<Object> backend) {
|
public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
|
||||||
try {
|
try {
|
||||||
var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, backend);
|
var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, monitor);
|
||||||
return longsupplier.getAsLong();
|
return longsupplier.getAsLong();
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw new IllegalStateException("How did you get here?", e);
|
throw new IllegalStateException("How did you get here?", e);
|
||||||
|
|||||||
+4
-26
@@ -8,6 +8,8 @@ package net.minecraftforge.fml.loading;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.function.IntConsumer;
|
import java.util.function.IntConsumer;
|
||||||
|
import java.util.function.IntSupplier;
|
||||||
|
import java.util.function.LongSupplier;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,36 +26,11 @@ import java.util.function.Supplier;
|
|||||||
* No doubt many more things can be said here.
|
* No doubt many more things can be said here.
|
||||||
*/
|
*/
|
||||||
public interface ImmediateWindowProvider {
|
public interface ImmediateWindowProvider {
|
||||||
/**
|
|
||||||
* Returns a new instance of ImmediateWindowProvider which just bounces to the vanilla code.
|
|
||||||
* This can be useful when you want to disable your provider and defer to vanilla behavior for some reason.
|
|
||||||
*/
|
|
||||||
public static ImmediateWindowProvider getFallbackHandler() {
|
|
||||||
return new ImmediateWindowHandler.DummyProvider();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The name of this window provider. Do NOT use fmlearlywindow.
|
* @return The name of this window provider. Do NOT use fmlearlywindow.
|
||||||
*/
|
*/
|
||||||
String name();
|
String name();
|
||||||
|
|
||||||
/**
|
|
||||||
* This is called before initialize, but after reading the preferred graphics backend config value from the user's
|
|
||||||
* options.txt or command line.
|
|
||||||
*
|
|
||||||
* If you do not support the requested backend, you can return a new ImmediateWindowProvider that does.
|
|
||||||
* {@link #getFallbackHandler()} can be used to get an instance that falls back to Vanilla's code effectively
|
|
||||||
* disabling the early loading screen.
|
|
||||||
*
|
|
||||||
* @param backend - The backend the user has selected, known values: "default", "opengl", and "vulkan". However this
|
|
||||||
* is read from the config file, or command line arguments so could be anything.
|
|
||||||
* Default and OpenGL are treated the same, attempting to load OpenGL first, then Vulkan.
|
|
||||||
* Vulkan attempts to load Vulkan first then OpenGL
|
|
||||||
*/
|
|
||||||
default ImmediateWindowProvider selectBackend(String backend) {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is called very early on to initialize ourselves. Use this to initialize the window and other GL core resources.
|
* This is called very early on to initialize ourselves. Use this to initialize the window and other GL core resources.
|
||||||
*
|
*
|
||||||
@@ -86,9 +63,10 @@ public interface ImmediateWindowProvider {
|
|||||||
* @param width This is the width of the window Mojang expects
|
* @param width This is the width of the window Mojang expects
|
||||||
* @param height This is the height of the Window Mojang expects.
|
* @param height This is the height of the Window Mojang expects.
|
||||||
* @param title This is the title for the window.
|
* @param title This is the title for the window.
|
||||||
|
* @param monitor This is the monitor it should appear on.
|
||||||
* @return The window id
|
* @return The window id
|
||||||
*/
|
*/
|
||||||
long setupMinecraftWindow(final int width, final int height, final String title, final Supplier<Object> backend);
|
long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is called after window handoff to allow us to tell Mojang about our window's position. This might give a
|
* This is called after window handoff to allow us to tell Mojang about our window's position. This might give a
|
||||||
|
|||||||
+19
-11
@@ -18,6 +18,7 @@ import org.slf4j.Logger;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.ServiceConfigurationError;
|
import java.util.ServiceConfigurationError;
|
||||||
import java.util.ServiceLoader;
|
import java.util.ServiceLoader;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
@@ -27,36 +28,43 @@ import java.util.stream.Stream;
|
|||||||
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
|
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
|
||||||
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
||||||
|
|
||||||
public final class LanguageLoadingProvider {
|
public class LanguageLoadingProvider {
|
||||||
public static void forEach(Consumer<IModLanguageProvider> consumer) {
|
public void forEach(Consumer<IModLanguageProvider> consumer) {
|
||||||
providers.forEach(consumer);
|
providers.forEach(consumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) {
|
public <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) {
|
||||||
return providers.stream().map(function);
|
return providers.stream().map(function);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void reload() {
|
public void reload() {
|
||||||
loadLanguageProviders();
|
loadLanguageProviders();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** This doesn't actually do anything with the argument, so just call reload(). Not sure when cpw broke that. */
|
||||||
|
@Deprecated(forRemoval = true, since = "1.20.2")
|
||||||
|
public void addAdditionalLanguages(List<ModFile> modFiles) {
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
|
||||||
/*==========================================================================*
|
/*==========================================================================*
|
||||||
* INTERNAL *
|
* INTERNAL SHIT *
|
||||||
*==========================================================================*/
|
*==========================================================================*/
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final ServiceLoader<IModLanguageProvider> serviceLoader;
|
private final ServiceLoader<IModLanguageProvider> serviceLoader;
|
||||||
private static final ArrayList<IModLanguageProvider> providers = new ArrayList<>();
|
private final List<IModLanguageProvider> providers = new ArrayList<>();
|
||||||
private static final HashMap<String, Wrapper> providersByName = new HashMap<>();
|
private final Map<String, Wrapper> providersByName = new HashMap<>();
|
||||||
private static final DefaultArtifactVersion IN_DEV = new DefaultArtifactVersion("0.0-dev");
|
private static final DefaultArtifactVersion IN_DEV = new DefaultArtifactVersion("0.0-dev");
|
||||||
|
|
||||||
private record Wrapper(ArtifactVersion version, IModLanguageProvider service) {}
|
private record Wrapper(ArtifactVersion version, IModLanguageProvider service) {}
|
||||||
|
|
||||||
static {
|
LanguageLoadingProvider() {
|
||||||
var sl = Launcher.INSTANCE.environment().findModuleLayerManager().flatMap(lm -> lm.getLayer(Layer.PLUGIN)).orElseThrow();
|
var sl = Launcher.INSTANCE.environment().findModuleLayerManager().flatMap(lm -> lm.getLayer(Layer.PLUGIN)).orElseThrow();
|
||||||
serviceLoader = ServiceLoader.load(sl, IModLanguageProvider.class);
|
serviceLoader = ServiceLoader.load(sl, IModLanguageProvider.class);
|
||||||
|
loadLanguageProviders();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void loadLanguageProviders() {
|
private void loadLanguageProviders() {
|
||||||
providers.clear();
|
providers.clear();
|
||||||
providersByName.clear();
|
providersByName.clear();
|
||||||
|
|
||||||
@@ -89,7 +97,7 @@ public final class LanguageLoadingProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IModLanguageProvider findLanguage(ModFile mod, String language, VersionRange versionRange) {
|
public IModLanguageProvider findLanguage(ModFile mod, String language, VersionRange versionRange) {
|
||||||
var consumer = mod.getFileName();
|
var consumer = mod.getFileName();
|
||||||
var wrapper = providersByName.get(language);
|
var wrapper = providersByName.get(language);
|
||||||
|
|
||||||
|
|||||||
@@ -5,46 +5,118 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml.loading;
|
package net.minecraftforge.fml.loading;
|
||||||
|
|
||||||
|
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
|
||||||
|
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
|
||||||
|
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||||
import net.minecraftforge.forgespi.locating.IModFile;
|
import net.minecraftforge.forgespi.locating.IModFile;
|
||||||
import org.jetbrains.annotations.Nullable;
|
|
||||||
|
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/// Master list of all mods in the loading context
|
import org.slf4j.Logger;
|
||||||
public sealed interface LoadingModList permits LoadingModListImpl {
|
|
||||||
static ModFileInfo getModFileById(String modId) {
|
import com.mojang.logging.LogUtils;
|
||||||
return get().fileById().get(modId);
|
|
||||||
|
/**
|
||||||
|
* Master list of all mods <em>in the loading context. This class cannot refer outside the
|
||||||
|
* 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;
|
||||||
|
private final Map<String, ModFileInfo> fileById;
|
||||||
|
private final List<EarlyLoadingException> preLoadErrors;
|
||||||
|
private List<IModFile> brokenFiles;
|
||||||
|
|
||||||
|
private LoadingModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
|
||||||
|
this.modFiles = modFiles.stream()
|
||||||
|
.map(ModFile::getModFileInfo)
|
||||||
|
.map(ModFileInfo.class::cast)
|
||||||
|
.toList();
|
||||||
|
this.sortedList = sortedList.stream().toList();
|
||||||
|
this.fileById = this.modFiles.stream()
|
||||||
|
.map(ModFileInfo::getMods)
|
||||||
|
.flatMap(Collection::stream)
|
||||||
|
.map(ModInfo.class::cast)
|
||||||
|
.collect(Collectors.toMap(ModInfo::getModId, ModInfo::getOwningFile));
|
||||||
|
this.preLoadErrors = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
static List<ModFileInfo> getModFiles() {
|
public static LoadingModList of(List<ModFile> modFiles, List<ModInfo> sortedList, final EarlyLoadingException earlyLoadingException) {
|
||||||
return get().getModFiles();
|
INSTANCE = new LoadingModList(modFiles, sortedList);
|
||||||
|
if (earlyLoadingException != null)
|
||||||
|
INSTANCE.preLoadErrors.add(earlyLoadingException);
|
||||||
|
return INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
static List<ModInfo> getMods() {
|
public static LoadingModList get() {
|
||||||
return get().getMods();
|
return INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
static @Nullable Path findResource(String className) {
|
public void addAccessTransformers() {
|
||||||
for (ModFileInfo modFileInfo : get().getModFiles()) {
|
var errors = new ArrayList<ExceptionData>();
|
||||||
Path resource = modFileInfo.getFile().findResource(className);
|
|
||||||
|
for (ModFileInfo modFile : modFiles) {
|
||||||
|
ModFile mod = modFile.getFile();
|
||||||
|
for (var at : mod.getAccessTransformers()) {
|
||||||
|
if (!Files.exists(at)) {
|
||||||
|
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
|
||||||
|
errors.add(new ExceptionData(message));
|
||||||
|
LOGGER.error(message);
|
||||||
|
} else
|
||||||
|
FMLLoader.addAccessTransformer(at, mod);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!errors.isEmpty())
|
||||||
|
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addForScanning(BackgroundScanHandler backgroundScanHandler) {
|
||||||
|
backgroundScanHandler.setLoadingModList(this);
|
||||||
|
modFiles.stream()
|
||||||
|
.map(ModFileInfo::getFile)
|
||||||
|
.forEach(backgroundScanHandler::submitForScanning);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModFileInfo> getModFiles() {
|
||||||
|
return modFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Path findResource(final String className) {
|
||||||
|
for (ModFileInfo mf : modFiles) {
|
||||||
|
final Path resource = mf.getFile().findResource(className);
|
||||||
if (Files.exists(resource)) return resource;
|
if (Files.exists(resource)) return resource;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
static List<EarlyLoadingException> getErrors() {
|
public ModFileInfo getModFileById(String modid) {
|
||||||
return get().getErrors();
|
return this.fileById.get(modid);
|
||||||
}
|
}
|
||||||
|
|
||||||
static List<IModFile> getBrokenFiles() {
|
public List<ModInfo> getMods() {
|
||||||
return get().getBrokenFiles();
|
return this.sortedList;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static LoadingModListImpl get() {
|
public List<EarlyLoadingException> getErrors() {
|
||||||
return LoadingModListImpl.get();
|
return preLoadErrors;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBrokenFiles(final List<IModFile> brokenFiles) {
|
||||||
|
this.brokenFiles = brokenFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<IModFile> getBrokenFiles() {
|
||||||
|
return this.brokenFiles;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.fml.loading;
|
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
|
|
||||||
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 java.nio.file.Files;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
|
|
||||||
import com.mojang.logging.LogUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Master list of all mods <em>in the loading context. This class cannot refer outside the
|
|
||||||
* loading package</em>
|
|
||||||
*/
|
|
||||||
record LoadingModListImpl(
|
|
||||||
List<ModFileInfo> getModFiles,
|
|
||||||
List<ModInfo> getMods,
|
|
||||||
Map<String, ModFileInfo> fileById,
|
|
||||||
ArrayList<EarlyLoadingException> getErrors,
|
|
||||||
ArrayList<IModFile> getBrokenFiles
|
|
||||||
) implements LoadingModList {
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
|
||||||
private static ModSorter.State temp;
|
|
||||||
|
|
||||||
LoadingModListImpl(List<ModFile> modFiles, List<ModInfo> sortedList) {
|
|
||||||
var modFileInfos = modFiles.stream()
|
|
||||||
.map(ModFile::getModFileInfo)
|
|
||||||
.map(ModFileInfo.class::cast)
|
|
||||||
.toList();
|
|
||||||
sortedList = sortedList.stream().toList();
|
|
||||||
var fileById = modFileInfos.stream()
|
|
||||||
.map(ModFileInfo::getMods)
|
|
||||||
.flatMap(Collection::stream)
|
|
||||||
.map(ModInfo.class::cast)
|
|
||||||
.collect(Collectors.toUnmodifiableMap(ModInfo::getModId, ModInfo::getOwningFile));
|
|
||||||
this(modFileInfos, sortedList, fileById, new ArrayList<>(), new ArrayList<>());
|
|
||||||
}
|
|
||||||
|
|
||||||
static LoadingModListImpl init(ModSorter.State modSorterState, EarlyLoadingException earlyLoadingException) {
|
|
||||||
temp = modSorterState;
|
|
||||||
var instance = get();
|
|
||||||
if (earlyLoadingException != null)
|
|
||||||
instance.getErrors.add(earlyLoadingException);
|
|
||||||
temp = null;
|
|
||||||
instance.addAccessTransformers();
|
|
||||||
return instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
static LoadingModListImpl get() {
|
|
||||||
final class LazyInit {
|
|
||||||
private LazyInit() {}
|
|
||||||
private static final LoadingModListImpl INSTANCE
|
|
||||||
= new LoadingModListImpl(LoadingModListImpl.temp.files(), LoadingModListImpl.temp.mods());
|
|
||||||
}
|
|
||||||
return LazyInit.INSTANCE;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addAccessTransformers() {
|
|
||||||
var errors = new ArrayList<ExceptionData>();
|
|
||||||
|
|
||||||
for (ModFileInfo modFile : getModFiles) {
|
|
||||||
ModFile mod = modFile.getFile();
|
|
||||||
for (var at : mod.getAccessTransformers()) {
|
|
||||||
if (!Files.exists(at)) {
|
|
||||||
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
|
|
||||||
errors.add(new ExceptionData(message));
|
|
||||||
LOGGER.error(message);
|
|
||||||
} else
|
|
||||||
FMLLoader.addAccessTransformer(at, mod);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!errors.isEmpty())
|
|
||||||
getErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading;
|
|||||||
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import cpw.mods.modlauncher.api.INameMappingService;
|
import cpw.mods.modlauncher.api.INameMappingService;
|
||||||
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
package net.minecraftforge.fml.loading;
|
package net.minecraftforge.fml.loading;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a maven coordinate into a Path.
|
* Convert a maven coordinate into a Path.
|
||||||
|
|||||||
@@ -33,10 +33,10 @@ import java.util.stream.Stream;
|
|||||||
|
|
||||||
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
||||||
|
|
||||||
public final class ModSorter {
|
public class ModSorter {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
|
|
||||||
record State(List<ModFile> files, List<ModInfo> mods) {}
|
private record State(List<ModFile> files, List<ModInfo> mods) {}
|
||||||
|
|
||||||
private ModSorter() {}
|
private ModSorter() {}
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ public final class ModSorter {
|
|||||||
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
|
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
|
||||||
// So all this is really doing is wasting time.
|
// So all this is really doing is wasting time.
|
||||||
// But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck.
|
// But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck.
|
||||||
return LoadingModListImpl.init(systemMods, e);
|
return LoadingModList.of(systemMods.files(), systemMods.mods(), e);
|
||||||
}
|
}
|
||||||
|
|
||||||
var named = new HashMap<String, ModInfo>();
|
var named = new HashMap<String, ModInfo>();
|
||||||
@@ -66,15 +66,15 @@ public final class ModSorter {
|
|||||||
|
|
||||||
// if we miss one or the other, we abort now
|
// if we miss one or the other, we abort now
|
||||||
if (!failedList.isEmpty()) {
|
if (!failedList.isEmpty()) {
|
||||||
return LoadingModListImpl.init(systemMods, new EarlyLoadingException("failure to validate mod list", null, failedList));
|
return LoadingModList.of(systemMods.files(), systemMods.mods(), new EarlyLoadingException("failure to validate mod list", null, failedList));
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, lets try and sort the modlist and proceed
|
// Otherwise, lets try and sort the modlist and proceed
|
||||||
try {
|
try {
|
||||||
var sorted = sort(modFiles, named);
|
var sorted = sort(modFiles, named);
|
||||||
return LoadingModListImpl.init(sorted, null);
|
return LoadingModList.of(sorted.files(), sorted.mods(), null);
|
||||||
} catch (EarlyLoadingException e) {
|
} catch (EarlyLoadingException e) {
|
||||||
// The only exception that can happen here is a cyclic exception, but fall back to system mods so we can display the nice screen.
|
// The only exception that can happen here is a cyclic exception, but fall back to system mods so we can display the nice screen.
|
||||||
return LoadingModListImpl.init(systemMods, e);
|
return LoadingModList.of(systemMods.files(), systemMods.mods(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
private static String DIST;
|
private static String DIST;
|
||||||
private static final String ONLYIN = Type.getDescriptor(OnlyIn.class);
|
private static final String ONLYIN = Type.getDescriptor(OnlyIn.class);
|
||||||
private static final String ONLYINS = Type.getDescriptor(OnlyIns.class);
|
private static final String ONLYINS = Type.getDescriptor(OnlyIns.class);
|
||||||
|
private static final String MOD = "Lnet/minecraftforge/fml/common/Mod;";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
@@ -44,17 +45,11 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||||
|
// TODO: [FML][RuntimeDistCleaner] In 26.1, only return YAY for MC classes on mod dev server
|
||||||
if (isEmpty)
|
if (isEmpty)
|
||||||
return NAY;
|
return NAY;
|
||||||
|
|
||||||
String internalName = classType.getInternalName();
|
String internalName = classType.getInternalName();
|
||||||
|
|
||||||
// Only apply to MC classes when on a dedicated server in a production environment
|
|
||||||
if (FMLEnvironment.production)
|
|
||||||
return FMLEnvironment.dist.isDedicatedServer() && isMinecraftClass(internalName) ? YAY : NAY;
|
|
||||||
|
|
||||||
// For dev time it's a bit trickier so that we can throw exceptions when someone uses @OnlyIn in their mod code,
|
|
||||||
// so that it's more obvious that the behaviour they're expecting won't work in production anymore
|
|
||||||
if (internalName.startsWith("net/minecraftforge/"))
|
if (internalName.startsWith("net/minecraftforge/"))
|
||||||
return NAY;
|
return NAY;
|
||||||
|
|
||||||
@@ -62,7 +57,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
if (FMLEnvironment.dist.isClient() && isMinecraftClass(internalName))
|
if (FMLEnvironment.dist.isClient() && isMinecraftClass(internalName))
|
||||||
return NAY;
|
return NAY;
|
||||||
|
|
||||||
return YAY; // mod classes might have @OnlyIn, so parse them in dev to find out and throw if they do
|
return YAY;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -71,14 +66,29 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
|
|
||||||
var annotations = unpack(classNode.visibleAnnotations);
|
var annotations = unpack(classNode.visibleAnnotations);
|
||||||
var isNonMinecraftClass = !isMinecraftClass(classNode.name);
|
var isNonMinecraftClass = !isMinecraftClass(classNode.name);
|
||||||
|
final class LazyInit {
|
||||||
|
private LazyInit() {}
|
||||||
|
private static final boolean CAN_EXPLODE = !FMLEnvironment.production && "21.6".equals(FMLLoader.versionInfo().mcVersion());
|
||||||
|
}
|
||||||
|
|
||||||
if (remove(annotations, DIST)) {
|
if (remove(annotations, DIST)) {
|
||||||
LOGGER.error(DISTXFORM, "Attempted to load class {} for invalid dist {}", classNode.name, DIST);
|
LOGGER.error(DISTXFORM, "Attempted to load class {} for invalid dist {}", classNode.name, DIST);
|
||||||
throw new RuntimeException("Attempted to load class " + classNode.name + " for invalid dist " + DIST);
|
throw new RuntimeException("Attempted to load class " + classNode.name + " for invalid dist " + DIST);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isNonMinecraftClass && !annotations.isEmpty())
|
if (!annotations.isEmpty()) {
|
||||||
throw new UnsupportedOperationException("Mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
if (isNonMinecraftClass) {
|
||||||
|
if (LazyInit.CAN_EXPLODE)
|
||||||
|
throw new UnsupportedOperationException("Mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
||||||
|
else
|
||||||
|
LOGGER.warn(DISTXFORM, "Class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", classNode.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!FMLEnvironment.production && hasModAnnotation(classNode.visibleAnnotations)) {
|
||||||
|
LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
|
||||||
|
throw new RuntimeException("Found @OnlyIn on @Mod class " + classNode.name + " - this is not allowed as it causes crashes. Remove the OnlyIn and consider setting clientSideOnly=true in the root of your mods.toml instead");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (classNode.interfaces != null && !classNode.interfaces.isEmpty()) {
|
if (classNode.interfaces != null && !classNode.interfaces.isEmpty()) {
|
||||||
for (var ann : annotations) {
|
for (var ann : annotations) {
|
||||||
@@ -111,8 +121,12 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
itr.remove();
|
itr.remove();
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
if (isNonMinecraftClass)
|
if (isNonMinecraftClass) {
|
||||||
throw new UnsupportedOperationException("Field " + field.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
if (LazyInit.CAN_EXPLODE)
|
||||||
|
throw new UnsupportedOperationException("Field " + field.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
||||||
|
else
|
||||||
|
LOGGER.warn(DISTXFORM, "Field {} in class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", field.name, classNode.name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,8 +139,12 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
lambdaGatherer.accept(method);
|
lambdaGatherer.accept(method);
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
if (isNonMinecraftClass)
|
if (isNonMinecraftClass) {
|
||||||
throw new UnsupportedOperationException("Method " + method.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
if (LazyInit.CAN_EXPLODE)
|
||||||
|
throw new UnsupportedOperationException("Method " + method.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
|
||||||
|
else
|
||||||
|
LOGGER.warn(DISTXFORM, "Method {} in class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", method.name, classNode.name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,6 +225,18 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean hasModAnnotation(final List<AnnotationNode> anns) {
|
||||||
|
if (anns == null || anns.isEmpty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (var ann : anns) {
|
||||||
|
if (ann.desc.equals(MOD))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isMinecraftClass(final String internalName) {
|
private static boolean isMinecraftClass(final String internalName) {
|
||||||
return internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/");
|
return internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/");
|
||||||
}
|
}
|
||||||
@@ -220,7 +250,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class LambdaGatherer extends MethodVisitor {
|
private static class LambdaGatherer extends MethodVisitor {
|
||||||
private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC,
|
private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC,
|
||||||
"java/lang/invoke/LambdaMetafactory", "metafactory",
|
"java/lang/invoke/LambdaMetafactory", "metafactory",
|
||||||
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
|
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import java.util.Map;
|
|||||||
import org.apache.commons.lang3.text.StrLookup;
|
import org.apache.commons.lang3.text.StrLookup;
|
||||||
import org.apache.commons.lang3.text.StrSubstitutor;
|
import org.apache.commons.lang3.text.StrSubstitutor;
|
||||||
|
|
||||||
// TODO: [FML] Remove this
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public class StringSubstitutor {
|
public class StringSubstitutor {
|
||||||
private static final Map<String, String> GLOBALS = Map.of(
|
private static final Map<String, String> GLOBALS = Map.of(
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ public class StringUtils {
|
|||||||
return java.util.stream.Stream.of(endings).anyMatch(lowerSearch::endsWith);
|
return java.util.stream.Stream.of(endings).anyMatch(lowerSearch::endsWith);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
public static URL toURL(final String string) {
|
public static URL toURL(final String string) {
|
||||||
if (string == null || string.trim().isEmpty() || string.contains("myurl.me") || string.contains("example.invalid"))
|
if (string == null || string.trim().isEmpty() || string.contains("myurl.me") || string.contains("example.invalid"))
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -115,22 +115,19 @@ public final class UniqueModListBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static ArtifactVersion getVersion(final ModFile mf) {
|
private static ArtifactVersion getVersion(final ModFile mf) {
|
||||||
List<IModInfo> modInfos;
|
if (mf.getModFileInfo() == null || mf.getModInfos() == null || mf.getModInfos().isEmpty()) {
|
||||||
if (mf.getModFileInfo() == null || (modInfos = mf.getModInfos()) == null || modInfos.isEmpty()) {
|
|
||||||
return mf.getJarVersion();
|
return mf.getJarVersion();
|
||||||
}
|
}
|
||||||
|
|
||||||
return modInfos.getFirst().getVersion();
|
return mf.getModInfos().getFirst().getVersion();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String getModId(ModFile modFile) {
|
private static String getModId(ModFile modFile) {
|
||||||
var modFileInfo = modFile.getModFileInfo();
|
if (modFile.getModFileInfo() == null || modFile.getModFileInfo().getMods().isEmpty()) {
|
||||||
List<IModInfo> mods;
|
|
||||||
if (modFileInfo == null || (mods = modFileInfo.getMods()).isEmpty()) {
|
|
||||||
return modFile.getSecureJar().name();
|
return modFile.getSecureJar().name();
|
||||||
}
|
}
|
||||||
|
|
||||||
return mods.getFirst().getModId();
|
return modFile.getModFileInfo().getMods().getFirst().getModId();
|
||||||
}
|
}
|
||||||
|
|
||||||
public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {}
|
public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import org.jetbrains.annotations.ApiStatus;
|
|||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.function.BiPredicate;
|
||||||
|
|
||||||
@ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version
|
@ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version
|
||||||
public class VersionSupportMatrix {
|
public class VersionSupportMatrix {
|
||||||
@@ -31,6 +32,15 @@ public class VersionSupportMatrix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@link #testVersionSupportMatrix(VersionRange, String, String)} instead, unwrapping your BiPredicate.
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since = "1.21.1")
|
||||||
|
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type, BiPredicate<String, VersionRange> standardLookup) {
|
||||||
|
if (standardLookup.test(lookupId, declaredRange)) return true;
|
||||||
|
return testVersionSupportMatrix(declaredRange, lookupId, type);
|
||||||
|
}
|
||||||
|
|
||||||
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type) {
|
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type) {
|
||||||
if (OVERRIDE_VERSIONS.isEmpty()) return false;
|
if (OVERRIDE_VERSIONS.isEmpty()) return false;
|
||||||
List<ArtifactVersion> custom = OVERRIDE_VERSIONS.get(type + "." + lookupId);
|
List<ArtifactVersion> custom = OVERRIDE_VERSIONS.get(type + "." + lookupId);
|
||||||
|
|||||||
+15
-2
@@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
|
|||||||
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
|
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
|
||||||
|
import net.minecraftforge.fml.loading.LoadingModList;
|
||||||
import net.minecraftforge.fml.loading.LogMarkers;
|
import net.minecraftforge.fml.loading.LogMarkers;
|
||||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -16,7 +17,8 @@ import java.time.Instant;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
public final class BackgroundScanHandler {
|
public class BackgroundScanHandler
|
||||||
|
{
|
||||||
private enum ScanStatus {
|
private enum ScanStatus {
|
||||||
NOT_STARTED,
|
NOT_STARTED,
|
||||||
RUNNING,
|
RUNNING,
|
||||||
@@ -31,6 +33,7 @@ public final class BackgroundScanHandler {
|
|||||||
private final ExecutorService modContentScanner;
|
private final ExecutorService modContentScanner;
|
||||||
private final List<ModFile> modFiles;
|
private final List<ModFile> modFiles;
|
||||||
private ScanStatus status;
|
private ScanStatus status;
|
||||||
|
private LoadingModList loadingModList;
|
||||||
|
|
||||||
public BackgroundScanHandler(final List<ModFile> modFiles) {
|
public BackgroundScanHandler(final List<ModFile> modFiles) {
|
||||||
this.modFiles = modFiles;
|
this.modFiles = modFiles;
|
||||||
@@ -55,7 +58,7 @@ public final class BackgroundScanHandler {
|
|||||||
ImmediateWindowHandler.updateProgress("Scanning mod candidates");
|
ImmediateWindowHandler.updateProgress("Scanning mod candidates");
|
||||||
CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner)
|
CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner)
|
||||||
.whenComplete(file::setScanResult);
|
.whenComplete(file::setScanResult);
|
||||||
if (DEBUG) future = future.whenComplete((_, t) -> addCompletedFile(file, t));
|
if (DEBUG) future = future.whenComplete((r, t) -> addCompletedFile(file, t));
|
||||||
file.setFutureScanResult(future);
|
file.setFutureScanResult(future);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +69,16 @@ public final class BackgroundScanHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setLoadingModList(LoadingModList loadingModList)
|
||||||
|
{
|
||||||
|
this.loadingModList = loadingModList;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LoadingModList getLoadingModList()
|
||||||
|
{
|
||||||
|
return loadingModList;
|
||||||
|
}
|
||||||
|
|
||||||
public void waitForScanToComplete(final Runnable ticker) {
|
public void waitForScanToComplete(final Runnable ticker) {
|
||||||
boolean timeoutActive = System.getProperty("fml.disableScanTimeout") == null;
|
boolean timeoutActive = System.getProperty("fml.disableScanTimeout") == null;
|
||||||
Instant deadline = Instant.now().plus(Duration.ofMinutes(10));
|
Instant deadline = Instant.now().plus(Duration.ofMinutes(10));
|
||||||
|
|||||||
+1
-1
@@ -45,7 +45,7 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
|
|||||||
// Find 'minecraft' during dev time this is also Forge. So skip it.
|
// Find 'minecraft' during dev time this is also Forge. So skip it.
|
||||||
// Can return null for dedicated server as Minecraft isn't on the classpath
|
// Can return null for dedicated server as Minecraft isn't on the classpath
|
||||||
// On the client it doesn't matter as it's the vanilla jar so wouldnt have mods.toml in it.
|
// On the client it doesn't matter as it's the vanilla jar so wouldnt have mods.toml in it.
|
||||||
var minecraft = getPathFromResource(cl, "net/minecraft/world/item/Item.class");
|
var minecraft = getPathFromResource(cl, "net/minecraft/obfuscate/DontObfuscate.class");
|
||||||
|
|
||||||
var claimed = new HashSet<Path>();
|
var claimed = new HashSet<Path>();
|
||||||
var tomls = getUrls(cl, MODS_TOML);
|
var tomls = getUrls(cl, MODS_TOML);
|
||||||
|
|||||||
+2
-2
@@ -24,7 +24,7 @@ public enum InvalidModIdentifier {
|
|||||||
LITELOADER(filePresent("litemod.json")),
|
LITELOADER(filePresent("litemod.json")),
|
||||||
OPTIFINE(filePresent("optifine/Installer.class")),
|
OPTIFINE(filePresent("optifine/Installer.class")),
|
||||||
BUKKIT(filePresent("plugin.yml")),
|
BUKKIT(filePresent("plugin.yml")),
|
||||||
INVALIDZIP((_,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed
|
INVALIDZIP((f,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed
|
||||||
|
|
||||||
private final BiPredicate<Path, Optional<ZipFile>> ident;
|
private final BiPredicate<Path, Optional<ZipFile>> ident;
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ public enum InvalidModIdentifier {
|
|||||||
|
|
||||||
private static BiPredicate<Path, Optional<ZipFile>> filePresent(String filename)
|
private static BiPredicate<Path, Optional<ZipFile>> filePresent(String filename)
|
||||||
{
|
{
|
||||||
return (_, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false);
|
return (f, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static <T> Optional<T> optionalFromException(Supplier_WithExceptions<T, ? extends Exception> supp)
|
private static <T> Optional<T> optionalFromException(Supplier_WithExceptions<T, ? extends Exception> supp)
|
||||||
|
|||||||
+1
-1
@@ -145,7 +145,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
|
|||||||
var ids = new TreeMap<String, List<Entry>>();
|
var ids = new TreeMap<String, List<Entry>>();
|
||||||
for (var entry : selector.entries.values()) {
|
for (var entry : selector.entries.values()) {
|
||||||
if (entry != FAILED && entry.coord != null)
|
if (entry != FAILED && entry.coord != null)
|
||||||
ids.computeIfAbsent(entry.coord, _ -> new ArrayList<>()).add(entry);
|
ids.computeIfAbsent(entry.coord, id -> new ArrayList<>()).add(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (var entry : ids.entrySet()) {
|
for (var entry : ids.entrySet()) {
|
||||||
|
|||||||
+1
-1
@@ -27,7 +27,7 @@ public final class MinecraftLocator extends AbstractModProvider implements IModL
|
|||||||
|
|
||||||
// Minecraft itself.
|
// Minecraft itself.
|
||||||
var meta = new ModJarMetadata();
|
var meta = new ModJarMetadata();
|
||||||
var mcjar = SecureJar.from(_ -> meta, paths);
|
var mcjar = SecureJar.from(jar -> meta, paths);
|
||||||
var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML);
|
var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML);
|
||||||
meta.setModFile(mc);
|
meta.setModFile(mc);
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -41,10 +41,9 @@ public final class ModDiscoverer {
|
|||||||
|
|
||||||
@SuppressWarnings("removal")
|
@SuppressWarnings("removal")
|
||||||
public static ModValidator discoverMods(Map<String, ?> arguments) {
|
public static ModValidator discoverMods(Map<String, ?> arguments) {
|
||||||
var env = Launcher.INSTANCE.environment();
|
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), v->ModsFolderLocator::new);
|
||||||
env.computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), _ -> ModsFolderLocator::new);
|
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{}));
|
||||||
env.computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), _ -> StartupNotificationManager.locatorConsumer().orElse(_ -> {}));
|
final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow();
|
||||||
final var moduleLayerManager = env.findModuleLayerManager().orElseThrow();
|
|
||||||
ServiceLoader<IModLocator> modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
|
ServiceLoader<IModLocator> modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
|
||||||
ServiceLoader<IDependencyLocator> dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
|
ServiceLoader<IDependencyLocator> dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
|
||||||
List<IModLocator> modLocatorList = ServiceLoaderUtils.streamWithErrorHandling(modLocators, sce -> LOGGER.error("Failed to load mod locator list", sce)).toList();
|
List<IModLocator> modLocatorList = ServiceLoaderUtils.streamWithErrorHandling(modLocators, sce -> LOGGER.error("Failed to load mod locator list", sce)).toList();
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
|
|||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import cpw.mods.jarhandling.SecureJar;
|
import cpw.mods.jarhandling.SecureJar;
|
||||||
import net.minecraftforge.fml.loading.LanguageLoadingProvider;
|
import net.minecraftforge.fml.loading.FMLLoader;
|
||||||
import net.minecraftforge.fml.loading.LogMarkers;
|
import net.minecraftforge.fml.loading.LogMarkers;
|
||||||
import net.minecraftforge.forgespi.language.IModFileInfo;
|
import net.minecraftforge.forgespi.language.IModFileInfo;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
@@ -25,6 +25,7 @@ import java.nio.file.FileSystems;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -47,7 +48,8 @@ public class ModFile implements IModFile {
|
|||||||
private final IModFileInfo modFileInfo;
|
private final IModFileInfo modFileInfo;
|
||||||
private ModFileScanData fileModFileScanData;
|
private ModFileScanData fileModFileScanData;
|
||||||
private CompletableFuture<ModFileScanData> futureScanResult;
|
private CompletableFuture<ModFileScanData> futureScanResult;
|
||||||
private List<Path> accessTransformers = List.of();
|
private Path accessTransformer;
|
||||||
|
private List<Path> accessTransformers = Collections.emptyList();
|
||||||
|
|
||||||
static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
|
static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
|
||||||
private SecureJar.Status securityStatus;
|
private SecureJar.Status securityStatus;
|
||||||
@@ -90,6 +92,11 @@ public class ModFile implements IModFile {
|
|||||||
return modFileInfo.getMods();
|
return modFileInfo.getMods();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Deprecated(forRemoval = true, since = "1.21.11")
|
||||||
|
public Optional<Path> getAccessTransformer() {
|
||||||
|
return Optional.ofNullable(accessTransformer);
|
||||||
|
}
|
||||||
|
|
||||||
public List<Path> getAccessTransformers() {
|
public List<Path> getAccessTransformers() {
|
||||||
return this.accessTransformers;
|
return this.accessTransformers;
|
||||||
}
|
}
|
||||||
@@ -104,6 +111,7 @@ public class ModFile implements IModFile {
|
|||||||
if (cfg == null) {
|
if (cfg == null) {
|
||||||
var path = findResource("META-INF", "accesstransformer.cfg");
|
var path = findResource("META-INF", "accesstransformer.cfg");
|
||||||
if (Files.exists(path)) {
|
if (Files.exists(path)) {
|
||||||
|
this.accessTransformer = path;
|
||||||
this.accessTransformers = List.of(path);
|
this.accessTransformers = List.of(path);
|
||||||
}
|
}
|
||||||
} else if (!cfg.isEmpty()) {
|
} else if (!cfg.isEmpty()) {
|
||||||
@@ -173,8 +181,9 @@ public class ModFile implements IModFile {
|
|||||||
|
|
||||||
public void identifyLanguage() {
|
public void identifyLanguage() {
|
||||||
var lst = new ArrayList<IModLanguageProvider>(this.modFileInfo.requiredLanguageLoaders().size());
|
var lst = new ArrayList<IModLanguageProvider>(this.modFileInfo.requiredLanguageLoaders().size());
|
||||||
|
var services = FMLLoader.getLanguageLoadingProvider();
|
||||||
for (var spec : this.modFileInfo.requiredLanguageLoaders()) {
|
for (var spec : this.modFileInfo.requiredLanguageLoaders()) {
|
||||||
var service = LanguageLoadingProvider.findLanguage(this, spec.languageName(), spec.acceptedVersions());
|
var service = services.findLanguage(this, spec.languageName(), spec.acceptedVersions());
|
||||||
lst.add(service);
|
lst.add(service);
|
||||||
}
|
}
|
||||||
this.loaders = List.copyOf(lst);
|
this.loaders = List.copyOf(lst);
|
||||||
|
|||||||
+3
-5
@@ -35,18 +35,16 @@ public class ModFileParser {
|
|||||||
LOGGER.warn(LogMarkers.LOADING, "Mod file {} is missing mods.toml file", modFile.getFilePath());
|
LOGGER.warn(LogMarkers.LOADING, "Mod file {} is missing mods.toml file", modFile.getFilePath());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
|
||||||
try {
|
try {
|
||||||
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
|
|
||||||
fileConfig.load();
|
fileConfig.load();
|
||||||
fileConfig.close();
|
fileConfig.close();
|
||||||
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
|
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
|
||||||
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
|
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
|
||||||
} catch (ParsingException e) { // Handle landmine toml errors, e.g. incorrectly ported mods.
|
} catch (ParsingException e) {
|
||||||
LOGGER.error("Mod candidate {} contains a corrupt or misconfigured toml.", modFile.getFileName());
|
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.");
|
throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains a corrupt or misconfigured toml.");
|
||||||
} catch (Exception other) { // Otherwise this is just someone who (probably) forgot a comma or something.
|
|
||||||
LOGGER.error("Mod candidate {}'s toml .", modFile.getFileName());
|
|
||||||
throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains broken toml, likely due to a typo.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-7
@@ -31,6 +31,7 @@ public class ModValidator {
|
|||||||
private final List<ModFile> candidatePlugins;
|
private final List<ModFile> candidatePlugins;
|
||||||
private final List<ModFile> candidateMods;
|
private final List<ModFile> candidateMods;
|
||||||
private final List<ModFile> gameLibraries;
|
private final List<ModFile> gameLibraries;
|
||||||
|
private LoadingModList loadingModList;
|
||||||
private final List<IModFile> brokenFiles = new ArrayList<>();
|
private final List<IModFile> brokenFiles = new ArrayList<>();
|
||||||
private final List<EarlyLoadingException.ExceptionData> discoveryErrorData;
|
private final List<EarlyLoadingException.ExceptionData> discoveryErrorData;
|
||||||
|
|
||||||
@@ -86,7 +87,7 @@ public class ModValidator {
|
|||||||
// If any detectable error happens during the sorting process {missing deps, duplicates,
|
// If any detectable error happens during the sorting process {missing deps, duplicates,
|
||||||
// This helps prevent coremods/mixins from screwing up us displaying the error screens that the sorting/validation is trying to display.
|
// This helps prevent coremods/mixins from screwing up us displaying the error screens that the sorting/validation is trying to display.
|
||||||
// This won't fix them all as they are still loaded and will still apply but it might help
|
// This won't fix them all as they are still loaded and will still apply but it might help
|
||||||
for (var info : LoadingModList.getModFiles())
|
for (var info : this.loadingModList.getModFiles())
|
||||||
mods.add(info.getFile().getSecureJar());
|
mods.add(info.getFile().getSecureJar());
|
||||||
|
|
||||||
// Add any game libraries, this *may* be duplicates, depending on the state of the sorting. But until I get around to re-writing
|
// Add any game libraries, this *may* be duplicates, depending on the state of the sorting. But until I get around to re-writing
|
||||||
@@ -123,12 +124,11 @@ public class ModValidator {
|
|||||||
var allErrors = new ArrayList<>(errors);
|
var allErrors = new ArrayList<>(errors);
|
||||||
allErrors.addAll(this.discoveryErrorData);
|
allErrors.addAll(this.discoveryErrorData);
|
||||||
|
|
||||||
ModSorter.sort(candidateMods, allErrors);
|
loadingModList = ModSorter.sort(candidateMods, allErrors);
|
||||||
LoadingModList.getBrokenFiles().addAll(brokenFiles);
|
loadingModList.addAccessTransformers();
|
||||||
var backgroundScanHandler = new BackgroundScanHandler(candidateMods);
|
loadingModList.setBrokenFiles(brokenFiles);
|
||||||
LoadingModList.getModFiles().stream()
|
BackgroundScanHandler backgroundScanHandler = new BackgroundScanHandler(candidateMods);
|
||||||
.map(ModFileInfo::getFile)
|
loadingModList.addForScanning(backgroundScanHandler);
|
||||||
.forEach(backgroundScanHandler::submitForScanning);
|
|
||||||
return backgroundScanHandler;
|
return backgroundScanHandler;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -56,7 +56,7 @@ public class StartupNotificationManager {
|
|||||||
private synchronized static void addMessage(Message.MessageType type, String message, int maxSize)
|
private synchronized static void addMessage(Message.MessageType type, String message, int maxSize)
|
||||||
{
|
{
|
||||||
EnumMap<Message.MessageType, List<Message>> newMessages = new EnumMap<>(messages);
|
EnumMap<Message.MessageType, List<Message>> newMessages = new EnumMap<>(messages);
|
||||||
newMessages.compute(type, (_, existingList) -> {
|
newMessages.compute(type, (key, existingList) -> {
|
||||||
List<Message> newList = new ArrayList<>();
|
List<Message> newList = new ArrayList<>();
|
||||||
if (existingList != null)
|
if (existingList != null)
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -141,7 +141,7 @@ abstract class CommonDevLaunchHandler extends CommonLaunchHandler {
|
|||||||
protected static Path getForgeOnly(Path forge) {
|
protected static Path getForgeOnly(Path forge) {
|
||||||
var packages = getPackages(); // Pulled out so it is passed to the lambda as value
|
var packages = getPackages(); // Pulled out so it is passed to the lambda as value
|
||||||
// We need to separate out our resources/code so that we can show up as a different data pack.
|
// We need to separate out our resources/code so that we can show up as a different data pack.
|
||||||
var modJar = SecureJar.from((path, _) -> {
|
var modJar = SecureJar.from((path, base) -> {
|
||||||
if (!path.endsWith(".class")) return true;
|
if (!path.endsWith(".class")) return true;
|
||||||
for (var pkg : packages)
|
for (var pkg : packages)
|
||||||
if (path.startsWith(pkg)) return true;
|
if (path.startsWith(pkg)) return true;
|
||||||
|
|||||||
@@ -5,16 +5,39 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml.loading.targets;
|
package net.minecraftforge.fml.loading.targets;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
import org.objectweb.asm.AnnotationVisitor;
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import com.electronwill.nightconfig.core.Config;
|
||||||
|
import com.electronwill.nightconfig.core.file.FileNotFoundAction;
|
||||||
|
import com.electronwill.nightconfig.core.io.WritingMode;
|
||||||
|
import com.electronwill.nightconfig.toml.TomlParser;
|
||||||
|
import com.electronwill.nightconfig.toml.TomlWriter;
|
||||||
|
import com.google.common.jimfs.Jimfs;
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.FMLLoader;
|
import net.minecraftforge.fml.loading.FMLLoader;
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.AbstractModProvider;
|
import net.minecraftforge.fml.loading.moddiscovery.AbstractModProvider;
|
||||||
import net.minecraftforge.forgespi.locating.IModLocator;
|
import net.minecraftforge.forgespi.locating.IModLocator;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public final class ForgeDevLocator extends AbstractModProvider implements IModLocator {
|
public final class ForgeDevLocator extends AbstractModProvider implements IModLocator {
|
||||||
|
private static final String PACK_META = "pack.mcmeta";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
return "forge_dev_locator";
|
return "forge_dev_locator";
|
||||||
@@ -48,6 +71,228 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
|
|||||||
}
|
}
|
||||||
var ret = new ArrayList<Path>();
|
var ret = new ArrayList<Path>();
|
||||||
ret.add(forge);
|
ret.add(forge);
|
||||||
|
|
||||||
|
var isTest = Boolean.getBoolean("forgedev.enableTestMods");
|
||||||
|
if (!isTest)
|
||||||
|
return ret;
|
||||||
|
|
||||||
|
var test = ForgeDevLaunchHandler.getPathFromResource("net/minecraftforge/test/BaseTestMod.class", ClassLoader.getSystemClassLoader());
|
||||||
|
// Explode our test mods into a framework that treats them all as separate jars.
|
||||||
|
var tests = explodeTestMods(test);
|
||||||
|
ret.addAll(tests);
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static List<Path> explodeTestMods(Path path) {
|
||||||
|
var mod = new ArrayList<Path>();
|
||||||
|
var memory = Jimfs.newFileSystem();
|
||||||
|
|
||||||
|
// First lets find all class files, that have the @Mod annotation and map packages to modids.
|
||||||
|
var packages = findTestModPackages(path);
|
||||||
|
for (var entry : packages.entrySet()) {
|
||||||
|
var pkg = entry.getKey() + '/';
|
||||||
|
var modids = entry.getValue();
|
||||||
|
|
||||||
|
// Find resource directories for every mod in this group
|
||||||
|
var paths = new LinkedHashSet<Path>();
|
||||||
|
for (var modid : modids.stream().sorted().toList()) {
|
||||||
|
var rsc = path.resolve(modid);
|
||||||
|
if (Files.exists(rsc))
|
||||||
|
paths.add(rsc);
|
||||||
|
}
|
||||||
|
|
||||||
|
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
|
||||||
|
buildModsToml(paths, modids, root, pkg.startsWith("net/minecraftforge/debug/client/"));
|
||||||
|
buildPackMeta(paths, root);
|
||||||
|
moveModuleInfo(paths, root);
|
||||||
|
|
||||||
|
if (Files.exists(root))
|
||||||
|
paths.add(root);
|
||||||
|
|
||||||
|
// We want just the class files from the root of the input paths. So make a new union with a filter.
|
||||||
|
var classes = UnionHelper.newFileSystem(
|
||||||
|
(name, base) -> {
|
||||||
|
if (name.endsWith("/")) {
|
||||||
|
if (name.startsWith("/"))
|
||||||
|
name = name.substring(1);
|
||||||
|
return pkg.startsWith(name) || name.startsWith(pkg);
|
||||||
|
}
|
||||||
|
return name.endsWith(".class") && name.startsWith(pkg);
|
||||||
|
}, new Path[] { path }
|
||||||
|
);
|
||||||
|
|
||||||
|
paths.addFirst(classes.getRootDirectories().iterator().next());
|
||||||
|
|
||||||
|
// Union of unions, Yay!
|
||||||
|
var union = UnionHelper.newFileSystem(null, paths.stream().toArray(Path[]::new));
|
||||||
|
mod.add(union.getRootDirectories().iterator().next());
|
||||||
|
}
|
||||||
|
|
||||||
|
return mod;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find all the @Mods so we can generate tomls, and so we can pick packages. Right now it doesn't allow mods in parent directories,
|
||||||
|
// I could make it merge all the way up, but I think this would be fine.
|
||||||
|
private static Map<String, Set<String>> findTestModPackages(Path path) {
|
||||||
|
var mods = new HashMap<String, Set<String>>();
|
||||||
|
try (var files = Files.walk(path)) {
|
||||||
|
var classes = files
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".class"))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
for (var cls : classes) {
|
||||||
|
try (var is = Files.newInputStream(cls)) {
|
||||||
|
var reader = new ClassReader(is);
|
||||||
|
reader.accept(new ClassVisitor(Opcodes.ASM9) {
|
||||||
|
private String clsName;
|
||||||
|
@Override
|
||||||
|
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
|
||||||
|
this.clsName = name;
|
||||||
|
super.visit(version, access, name, signature, superName, interfaces);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AnnotationVisitor visitAnnotation(String name, boolean runtime) {
|
||||||
|
if (!"Lnet/minecraftforge/fml/common/Mod;".equals(name))
|
||||||
|
return super.visitAnnotation(name, runtime);
|
||||||
|
|
||||||
|
return new AnnotationVisitor(Opcodes.ASM9) {
|
||||||
|
@Override
|
||||||
|
public void visit(String key, Object value) {
|
||||||
|
if ("value".equals(key)) {
|
||||||
|
int idx = clsName.lastIndexOf('/');
|
||||||
|
var pkg = clsName.substring(0, idx);
|
||||||
|
mods.computeIfAbsent(pkg, k -> new HashSet<>()).add((String)value);
|
||||||
|
|
||||||
|
idx = pkg.lastIndexOf('/');
|
||||||
|
while (idx != -1) {
|
||||||
|
pkg = pkg.substring(0, idx);
|
||||||
|
idx = pkg.lastIndexOf('/');
|
||||||
|
if (mods.containsKey(pkg))
|
||||||
|
throw new IllegalStateException("Invalid ForgeDev test mod layout, conflicting packages: " + pkg + " for " + clsName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
sneak(e);
|
||||||
|
}
|
||||||
|
return mods;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builds or update the mods.toml file for all @Mods in this package
|
||||||
|
private static void buildModsToml(Set<Path> resources, Set<String> modids, Path root, boolean clientOnly) {
|
||||||
|
var toml = resources.stream()
|
||||||
|
.map(p -> p.resolve(MODS_TOML))
|
||||||
|
.filter(Files::exists)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
Config cfg = null;
|
||||||
|
|
||||||
|
if (toml != null)
|
||||||
|
cfg = new TomlParser().parse(toml, FileNotFoundAction.READ_NOTHING);
|
||||||
|
else
|
||||||
|
cfg = Config.inMemory();
|
||||||
|
|
||||||
|
boolean modified = false;
|
||||||
|
var defaults = Map.of(
|
||||||
|
"modLoader", "javafml",
|
||||||
|
"loaderVersion", "[0,)",
|
||||||
|
"license", "Doesnt fucking matter",
|
||||||
|
"clientSideOnly", clientOnly
|
||||||
|
);
|
||||||
|
|
||||||
|
for (var key : defaults.keySet()) {
|
||||||
|
if (!cfg.contains(key)) {
|
||||||
|
cfg.set(key, defaults.get(key));
|
||||||
|
modified = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var modlist = new ArrayList<Config>();
|
||||||
|
if (cfg.contains("mods")) {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var existing = ((List<Config>)cfg.get("mods"));
|
||||||
|
modlist.addAll(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var modid : modids) {
|
||||||
|
if (modlist.stream().noneMatch(c -> modid.equals(c.get("modId")))) {
|
||||||
|
modified = true;
|
||||||
|
var tmp = Config.inMemory();
|
||||||
|
tmp.set("modId", modid);
|
||||||
|
modlist.add(tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.set("mods", modlist);
|
||||||
|
|
||||||
|
if (modified) {
|
||||||
|
var target = root.resolve(MODS_TOML);
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
new TomlWriter().write(cfg, target, WritingMode.REPLACE);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("Failed to create in memory toml: " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is optional, it just hides a warning screen when starting up. I should probably remove this once I restructure how data gen for test mods work and make it generate there.
|
||||||
|
private static void buildPackMeta(Set<Path> paths, Path root) {
|
||||||
|
var existing = paths.stream()
|
||||||
|
.map(p -> p.resolve(PACK_META))
|
||||||
|
.filter(Files::exists)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (existing != null)
|
||||||
|
return;
|
||||||
|
var target = root.resolve(PACK_META);
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
Files.writeString(target,
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"pack": {
|
||||||
|
"description": "doesn't matter",
|
||||||
|
"pack_format": 18
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""", StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("Failed to make in memory pack.mcmeta: " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void moveModuleInfo(Set<Path> paths, Path root) {
|
||||||
|
var existing = paths.stream()
|
||||||
|
.map(p -> p.resolve("module-info.dat"))
|
||||||
|
.filter(Files::exists)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (existing == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var target = root.resolve("module-info.class");
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
Files.copy(existing, target);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("Failed to copy module-info.dat to memory: " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
||||||
|
throw (E)e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-3
@@ -25,9 +25,7 @@ sealed abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Path> getMinecraftPaths() {
|
public List<Path> getMinecraftPaths() {
|
||||||
// We use a marker because 3rd party launcher don't build their class paths correctly
|
return List.of(getPathFromResource("net/minecraft/client/Minecraft.class"));
|
||||||
// https://github.com/MinecraftForge/MinecraftForge/issues/10797
|
|
||||||
return List.of(getPathFromResource(".forge_patched_minecraft"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+28
-26
@@ -22,18 +22,15 @@ import java.util.Set;
|
|||||||
*
|
*
|
||||||
* <p>This detector evaluates the graph lazily and won't reflect the modifications in the
|
* <p>This detector evaluates the graph lazily and won't reflect the modifications in the
|
||||||
* graph after initial evaluation.
|
* graph after initial evaluation.
|
||||||
*
|
|
||||||
* <p> Implementation based on <a href="https://en.wikipedia.org/w/index.php?title=Tarjan%27s_strongly_connected_components_algorithm&oldid=1384955226">Wikipedia Psudocode</a>
|
|
||||||
*/
|
*/
|
||||||
public class StronglyConnectedComponentDetector<T> {
|
public class StronglyConnectedComponentDetector<T> {
|
||||||
private final Graph<T> graph;
|
private final Graph<T> graph;
|
||||||
private final Map<T, Integer> ids = new HashMap<>();
|
private final Map<T, Integer> ids = new HashMap<>();
|
||||||
private T[] elements;
|
private T[] elements;
|
||||||
private int[] indexes;
|
private int[] dfn;
|
||||||
private int[] lowlinks;
|
private int[] low;
|
||||||
private int[] stack;
|
private int[] stack;
|
||||||
private int top;
|
private int top;
|
||||||
private int index;
|
|
||||||
private BitSet onStack;
|
private BitSet onStack;
|
||||||
private Set<Set<T>> components;
|
private Set<Set<T>> components;
|
||||||
|
|
||||||
@@ -61,43 +58,48 @@ public class StronglyConnectedComponentDetector<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final int n = nodes.size();
|
final int n = nodes.size();
|
||||||
indexes = new int[n];
|
dfn = new int[n];
|
||||||
lowlinks = new int[n];
|
low = new int[n];
|
||||||
stack = new int[n];
|
stack = new int[n];
|
||||||
onStack = new BitSet(n);
|
onStack = new BitSet(n);
|
||||||
top = -1;
|
top = -1;
|
||||||
index = 1;
|
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
if (indexes[i] == 0)
|
if (dfn[i] == 0) {
|
||||||
dfs(i);
|
dfs(i, 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void dfs(int now) {
|
private void dfs(int now, int depth) {
|
||||||
indexes[now] = lowlinks[now] = index++;
|
dfn[now] = depth;
|
||||||
stack[++top] = now;
|
low[now] = depth;
|
||||||
|
top++;
|
||||||
|
stack[top] = now;
|
||||||
onStack.set(now);
|
onStack.set(now);
|
||||||
|
|
||||||
for (T each : graph.successors(elements[now])) {
|
for (T each : graph.successors(elements[now])) {
|
||||||
int to = ids.get(each);
|
int to = ids.get(each);
|
||||||
if (indexes[to] == 0) { // 0 is unvisited
|
if (dfn[to] != 0) {
|
||||||
dfs(to);
|
if (low[now] > dfn[to]) {
|
||||||
if (lowlinks[now] > lowlinks[to])
|
low[now] = dfn[to];
|
||||||
lowlinks[now] = lowlinks[to];
|
}
|
||||||
} else if (onStack.get(to)) {
|
} else {
|
||||||
if (lowlinks[now] > indexes[to])
|
dfs(to, depth + 1);
|
||||||
lowlinks[now] = indexes[to];
|
if (low[now] > low[to]) {
|
||||||
|
low[now] = low[to];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (indexes[now] == lowlinks[now]) {
|
if (dfn[now] == low[now]) {
|
||||||
Set<T> component = new HashSet<>();
|
Set<T> component = new HashSet<>();
|
||||||
while (top >= 0) {
|
while (top >= 0) {
|
||||||
final int w = stack[top--];
|
final int t = stack[top];
|
||||||
onStack.clear(w);
|
component.add(elements[t]);
|
||||||
component.add(elements[w]);
|
onStack.clear(t);
|
||||||
if (w == now)
|
top--;
|
||||||
|
if (t == now) {
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
components.add(component);
|
components.add(component);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
|
||||||
}
|
|
||||||
|
|
||||||
gradleutils.displayName = 'Forge-Examiner'
|
|
||||||
description = 'Forge Mod Locator for multiple mods merged together into one code source'
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation project(':fmlloader')
|
|
||||||
implementation(libs.jimfs){ transitive = false }
|
|
||||||
implementation(libs.bootstrap.api)
|
|
||||||
}
|
|
||||||
|
|
||||||
convention.manifest('net/minecraftforge/examiner/', [
|
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.examiner',
|
|
||||||
'Forge-Module-Layer' : 'boot'
|
|
||||||
])
|
|
||||||
|
|
||||||
convention.publish()
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.examiner;
|
|
||||||
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import net.minecraftforge.bootstrap.api.BootstrapClasspathModifier;
|
|
||||||
|
|
||||||
public class BootstrapFilter implements BootstrapClasspathModifier {
|
|
||||||
@Override
|
|
||||||
public String name() {
|
|
||||||
return "examiner";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean process(List<Path[]> classpath) {
|
|
||||||
var modified = false;
|
|
||||||
|
|
||||||
for (var itr = classpath.iterator(); itr.hasNext(); ) {
|
|
||||||
for (var path : itr.next()) {
|
|
||||||
final var target = path.resolve(Locator.MARKER);
|
|
||||||
if (Files.exists(target)) {
|
|
||||||
itr.remove();
|
|
||||||
modified = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return modified;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,338 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.examiner;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URL;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.StandardOpenOption;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
|
||||||
import org.objectweb.asm.AnnotationVisitor;
|
|
||||||
import org.objectweb.asm.ClassReader;
|
|
||||||
import org.objectweb.asm.ClassVisitor;
|
|
||||||
import org.objectweb.asm.Opcodes;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
|
|
||||||
import com.electronwill.nightconfig.core.Config;
|
|
||||||
import com.electronwill.nightconfig.core.file.FileNotFoundAction;
|
|
||||||
import com.electronwill.nightconfig.core.io.WritingMode;
|
|
||||||
import com.electronwill.nightconfig.toml.TomlParser;
|
|
||||||
import com.electronwill.nightconfig.toml.TomlWriter;
|
|
||||||
import com.google.common.jimfs.Jimfs;
|
|
||||||
import com.mojang.logging.LogUtils;
|
|
||||||
|
|
||||||
import net.minecraftforge.fml.loading.LogMarkers;
|
|
||||||
import net.minecraftforge.fml.loading.moddiscovery.AbstractModProvider;
|
|
||||||
import net.minecraftforge.forgespi.locating.IModLocator;
|
|
||||||
|
|
||||||
public class Locator extends AbstractModProvider implements IModLocator {
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
|
||||||
static final String MARKER = ".examiner";
|
|
||||||
private static final String PACK_META = "pack.mcmeta";
|
|
||||||
private static final String PROJECT_INFO = ".project_info.properties";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String name() {
|
|
||||||
return "examiner";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<ModFileOrException> scanMods() {
|
|
||||||
var mods = getMods();
|
|
||||||
var ret = new ArrayList<ModFileOrException>();
|
|
||||||
for (var path : mods) {
|
|
||||||
var mod = createMod(path);
|
|
||||||
if (mod != null)
|
|
||||||
ret.add(mod);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Collection<Path> getMods() {
|
|
||||||
var ret = new HashSet<Path>();
|
|
||||||
var cl = ClassLoader.getSystemClassLoader();
|
|
||||||
var markers = getUrls(cl, MARKER);
|
|
||||||
markers.addAll(getUrls(getClass().getClassLoader(), MARKER));
|
|
||||||
for (var url : markers) {
|
|
||||||
var path = getPath(url, MARKER);
|
|
||||||
var mods = explodeTestMods(path);
|
|
||||||
for (var mod : mods)
|
|
||||||
ret.add(mod);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Set<URL> getUrls(ClassLoader cl, String resource) {
|
|
||||||
try {
|
|
||||||
var lst = Collections.list(cl.getResources(resource));
|
|
||||||
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
|
|
||||||
lst.sort(Comparator.comparing(URL::toString));
|
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Scanning Classloader: {} for {}", cl, resource);
|
|
||||||
for (var url : lst)
|
|
||||||
LOGGER.debug(LogMarkers.SCAN, "\t{}", url);
|
|
||||||
}
|
|
||||||
return new LinkedHashSet<URL>(lst);
|
|
||||||
} catch (IOException e) {
|
|
||||||
LOGGER.warn(LogMarkers.SCAN, "Error finding resources for: " + resource, e);
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Path getPath(URL url, String resource) {
|
|
||||||
var str = url.toString();
|
|
||||||
int len = resource.length();
|
|
||||||
if ("jar".equalsIgnoreCase(url.getProtocol())) {
|
|
||||||
str = url.getFile();
|
|
||||||
len += 2;
|
|
||||||
}
|
|
||||||
str = str.substring(0, str.length() - len);
|
|
||||||
return Path.of(URI.create(str));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private static List<Path> explodeTestMods(Path path) {
|
|
||||||
var mod = new ArrayList<Path>();
|
|
||||||
var memory = Jimfs.newFileSystem();
|
|
||||||
|
|
||||||
var info = path.resolve(PROJECT_INFO);
|
|
||||||
if (!Files.exists(info))
|
|
||||||
info = null;
|
|
||||||
|
|
||||||
// First lets find all class files, that have the @Mod annotation and map packages to modids.
|
|
||||||
var packages = findTestModPackages(path);
|
|
||||||
|
|
||||||
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
|
|
||||||
var ordered = packages.entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.toString())).toList();
|
|
||||||
for (var entry : ordered)
|
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Examiner located {} with mods {}", entry.getKey(), entry.getValue().stream().sorted().toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var entry : packages.entrySet()) {
|
|
||||||
var pkg = entry.getKey() + '/';
|
|
||||||
var modids = entry.getValue();
|
|
||||||
|
|
||||||
// Find resource directories for every mod in this group
|
|
||||||
var paths = new LinkedHashSet<Path>();
|
|
||||||
for (var modid : modids.stream().sorted().toList()) {
|
|
||||||
var rsc = path.resolve(modid);
|
|
||||||
if (Files.exists(rsc))
|
|
||||||
paths.add(rsc);
|
|
||||||
}
|
|
||||||
|
|
||||||
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
|
|
||||||
buildModsToml(paths, modids, root, pkg.startsWith("net/minecraftforge/debug/client/"));
|
|
||||||
buildPackMeta(paths, root);
|
|
||||||
moveModuleInfo(paths, root);
|
|
||||||
copyFile(info, root.resolve(PROJECT_INFO));
|
|
||||||
|
|
||||||
if (Files.exists(root))
|
|
||||||
paths.add(root);
|
|
||||||
|
|
||||||
// We want just the class files from the root of the input paths. So make a new union with a filter.
|
|
||||||
var classes = UnionHelper.newFileSystem(
|
|
||||||
(name, _) -> {
|
|
||||||
if (name.endsWith("/")) {
|
|
||||||
if (name.startsWith("/"))
|
|
||||||
name = name.substring(1);
|
|
||||||
return pkg.startsWith(name) || name.startsWith(pkg);
|
|
||||||
}
|
|
||||||
return name.endsWith(".class") && name.startsWith(pkg);
|
|
||||||
}, new Path[] { path }
|
|
||||||
);
|
|
||||||
|
|
||||||
paths.addFirst(classes.getRootDirectories().iterator().next());
|
|
||||||
|
|
||||||
// Union of unions, Yay!
|
|
||||||
var union = UnionHelper.newFileSystem(null, paths.stream().toArray(Path[]::new));
|
|
||||||
mod.add(union.getRootDirectories().iterator().next());
|
|
||||||
}
|
|
||||||
|
|
||||||
return mod;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find all the @Mods so we can generate tomls, and so we can pick packages. Right now it doesn't allow mods in parent directories,
|
|
||||||
// I could make it merge all the way up, but I think this would be fine.
|
|
||||||
private static Map<String, Set<String>> findTestModPackages(Path path) {
|
|
||||||
var mods = new HashMap<String, Set<String>>();
|
|
||||||
try (var files = Files.walk(path)) {
|
|
||||||
var classes = files
|
|
||||||
.filter(Files::isRegularFile)
|
|
||||||
.filter(p -> p.getFileName().toString().endsWith(".class"))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
for (var cls : classes) {
|
|
||||||
try (var is = Files.newInputStream(cls)) {
|
|
||||||
var reader = new ClassReader(is);
|
|
||||||
reader.accept(new ClassVisitor(Opcodes.ASM9) {
|
|
||||||
private String clsName;
|
|
||||||
@Override
|
|
||||||
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
|
|
||||||
this.clsName = name;
|
|
||||||
super.visit(version, access, name, signature, superName, interfaces);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public AnnotationVisitor visitAnnotation(String name, boolean runtime) {
|
|
||||||
if (!"Lnet/minecraftforge/fml/common/Mod;".equals(name))
|
|
||||||
return super.visitAnnotation(name, runtime);
|
|
||||||
|
|
||||||
return new AnnotationVisitor(Opcodes.ASM9) {
|
|
||||||
@Override
|
|
||||||
public void visit(String key, Object value) {
|
|
||||||
if ("value".equals(key)) {
|
|
||||||
int idx = clsName.lastIndexOf('/');
|
|
||||||
var pkg = clsName.substring(0, idx);
|
|
||||||
mods.computeIfAbsent(pkg, _ -> new HashSet<>()).add((String)value);
|
|
||||||
|
|
||||||
idx = pkg.lastIndexOf('/');
|
|
||||||
while (idx != -1) {
|
|
||||||
pkg = pkg.substring(0, idx);
|
|
||||||
idx = pkg.lastIndexOf('/');
|
|
||||||
if (mods.containsKey(pkg))
|
|
||||||
throw new IllegalStateException("Invalid ForgeDev test mod layout, conflicting packages: " + pkg + " for " + clsName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
sneak(e);
|
|
||||||
}
|
|
||||||
return mods;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Builds or update the mods.toml file for all @Mods in this package
|
|
||||||
private static void buildModsToml(Set<Path> resources, Set<String> modids, Path root, boolean clientOnly) {
|
|
||||||
var toml = resources.stream()
|
|
||||||
.map(p -> p.resolve(MODS_TOML))
|
|
||||||
.filter(Files::exists)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
|
|
||||||
Config cfg = null;
|
|
||||||
|
|
||||||
if (toml != null)
|
|
||||||
cfg = new TomlParser().parse(toml, FileNotFoundAction.READ_NOTHING);
|
|
||||||
else
|
|
||||||
cfg = Config.inMemory();
|
|
||||||
|
|
||||||
boolean modified = false;
|
|
||||||
var defaults = Map.of(
|
|
||||||
"modLoader", "javafml",
|
|
||||||
"loaderVersion", "[0,)",
|
|
||||||
"license", "Doesnt fucking matter",
|
|
||||||
"clientSideOnly", clientOnly
|
|
||||||
);
|
|
||||||
|
|
||||||
for (var key : defaults.keySet()) {
|
|
||||||
if (!cfg.contains(key)) {
|
|
||||||
cfg.set(key, defaults.get(key));
|
|
||||||
modified = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var modlist = new ArrayList<Config>();
|
|
||||||
if (cfg.contains("mods")) {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
var existing = ((List<Config>)cfg.get("mods"));
|
|
||||||
modlist.addAll(existing);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var modid : modids) {
|
|
||||||
if (modlist.stream().noneMatch(c -> modid.equals(c.get("modId")))) {
|
|
||||||
modified = true;
|
|
||||||
var tmp = Config.inMemory();
|
|
||||||
tmp.set("modId", modid);
|
|
||||||
modlist.add(tmp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg.set("mods", modlist);
|
|
||||||
|
|
||||||
if (modified) {
|
|
||||||
var target = root.resolve(MODS_TOML);
|
|
||||||
try {
|
|
||||||
Files.createDirectories(target.getParent());
|
|
||||||
new TomlWriter().write(cfg, target, WritingMode.REPLACE);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalStateException("Failed to create in memory toml: " + target, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is optional, it just hides a warning screen when starting up. I should probably remove this once I restructure how data gen for test mods work and make it generate there.
|
|
||||||
private static void buildPackMeta(Set<Path> paths, Path root) {
|
|
||||||
var existing = paths.stream()
|
|
||||||
.map(p -> p.resolve(PACK_META))
|
|
||||||
.filter(Files::exists)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
|
|
||||||
if (existing != null)
|
|
||||||
return;
|
|
||||||
var target = root.resolve(PACK_META);
|
|
||||||
try {
|
|
||||||
Files.createDirectories(target.getParent());
|
|
||||||
Files.writeString(target,
|
|
||||||
"""
|
|
||||||
{
|
|
||||||
"pack": {
|
|
||||||
"description": "doesn't matter",
|
|
||||||
"pack_format": 18
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""", StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalStateException("Failed to make in memory pack.mcmeta: " + target, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void moveModuleInfo(Set<Path> paths, Path root) {
|
|
||||||
var existing = paths.stream()
|
|
||||||
.map(p -> p.resolve("module-info.dat"))
|
|
||||||
.filter(Files::exists)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
|
|
||||||
var target = root.resolve("module-info.class");
|
|
||||||
copyFile(existing, target);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void copyFile(@Nullable Path existing, Path target) {
|
|
||||||
if (existing == null)
|
|
||||||
return;
|
|
||||||
try {
|
|
||||||
Files.createDirectories(target.getParent());
|
|
||||||
Files.copy(existing, target);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalStateException("Failed to copy " + existing.getFileName() + " to memory: " + target, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
|
||||||
throw (E)e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.examiner;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.FileSystem;
|
|
||||||
import java.nio.file.FileSystems;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.spi.FileSystemProvider;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.function.BiPredicate;
|
|
||||||
|
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
|
||||||
|
|
||||||
@ApiStatus.Internal
|
|
||||||
final class UnionHelper {
|
|
||||||
private static final FileSystemProvider UFSP = getUnionFileSystemProvider();
|
|
||||||
private static FileSystemProvider getUnionFileSystemProvider() {
|
|
||||||
for (var provider : FileSystemProvider.installedProviders()) {
|
|
||||||
if ("union".equals(provider.getScheme()))
|
|
||||||
return provider;
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("Missing UnionFileSystemProvider");
|
|
||||||
};
|
|
||||||
|
|
||||||
static FileSystem newFileSystem(BiPredicate<String, String> filter, Path[] paths) {
|
|
||||||
try {
|
|
||||||
if (paths == null || paths.length == 0)
|
|
||||||
throw new IllegalArgumentException("Must contain atleast one path");
|
|
||||||
|
|
||||||
if (filter == null && paths.length == 1)
|
|
||||||
return FileSystems.newFileSystem(paths[0]);
|
|
||||||
|
|
||||||
var map = new HashMap<String, Object>();
|
|
||||||
if (filter != null)
|
|
||||||
map.put("filter", filter);
|
|
||||||
|
|
||||||
var lst = new ArrayList<>(Arrays.asList(paths));
|
|
||||||
var base = lst.remove(0);
|
|
||||||
map.put("additional", lst);
|
|
||||||
return UFSP.newFileSystem(base, map);
|
|
||||||
} catch (IOException e) {
|
|
||||||
return sneak(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
|
||||||
throw (E)e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
net.minecraftforge.examiner.BootstrapFilter
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
net.minecraftforge.examiner.Locator
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
|
||||||
}
|
|
||||||
|
|
||||||
gradleutils.displayName = 'Forge-Tests'
|
|
||||||
description = 'Mods used for testing Forge features'
|
|
||||||
|
|
||||||
license {
|
|
||||||
exclude 'com/example/'
|
|
||||||
}
|
|
||||||
|
|
||||||
convention.basicRuns('mdk_datagen', file('src/main/generated')) {
|
|
||||||
flat = true
|
|
||||||
}
|
|
||||||
|
|
||||||
final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) {
|
|
||||||
gradleVersion = libs.versions.gradle.get()
|
|
||||||
scriptFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradlew")
|
|
||||||
jarFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradle/wrapper/gradle-wrapper.jar")
|
|
||||||
}
|
|
||||||
|
|
||||||
final mdkZip = tasks.register('mdkZip', Zip) {
|
|
||||||
dependsOn mdkGradleWrapper
|
|
||||||
|
|
||||||
archiveBaseName = project.name
|
|
||||||
archiveClassifier = 'mdk'
|
|
||||||
archiveVersion = project.version
|
|
||||||
destinationDirectory = file('build/libs')
|
|
||||||
|
|
||||||
from(rootProject.file('LICENSE.txt'))
|
|
||||||
from(changelog.task.flatMap(task -> task.outputFile))
|
|
||||||
|
|
||||||
from mdkGradleWrapper.map(Wrapper.&getScriptFile)
|
|
||||||
from mdkGradleWrapper.map(Wrapper.&getBatchScript)
|
|
||||||
|
|
||||||
into('gradle/wrapper/') {
|
|
||||||
from mdkGradleWrapper.map(Wrapper.&getJarFile)
|
|
||||||
from mdkGradleWrapper.map(Wrapper.&getPropertiesFile)
|
|
||||||
}
|
|
||||||
from(file('template/')){
|
|
||||||
file('template/gitignore.txt').eachLine {
|
|
||||||
if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
|
|
||||||
exclude it
|
|
||||||
}
|
|
||||||
|
|
||||||
filter(org.apache.tools.ant.filters.ReplaceTokens, tokens: [
|
|
||||||
FORGE_VERSION: versions.forge,
|
|
||||||
FORGE_GROUP: project.group,
|
|
||||||
FORGE_NAME: project.name,
|
|
||||||
MC_VERSION: versions.minecraft,
|
|
||||||
FORGE_SPEC_VERSION: versions.forgeSpec,
|
|
||||||
MC_NEXT_VERSION: versions.minecraftNext,
|
|
||||||
EVENTBUS_VERSION: libs.versions.eventbus.get()
|
|
||||||
])
|
|
||||||
|
|
||||||
rename 'gitignore\\.txt', '.gitignore'
|
|
||||||
rename 'gitattributes\\.txt', '.gitattributes'
|
|
||||||
}
|
|
||||||
from(file('src/main/java/com/example/examplemod/')) {
|
|
||||||
into('src/main/java/com/example/examplemod/')
|
|
||||||
}
|
|
||||||
from(file('src/main/generated/')) {
|
|
||||||
into('src/main/resources/')
|
|
||||||
exclude '**/.cache/'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
forgedev.provideFile('mdkZip', mdkZip.flatMap { it.archiveFile } )
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"pack": {
|
|
||||||
"description": "${mod_id} resources",
|
|
||||||
"max_format": 121,
|
|
||||||
"min_format": 121
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
modLoader="javafml"
|
|
||||||
loaderVersion="[0,)"
|
|
||||||
license="LGPL_v2"
|
|
||||||
|
|
||||||
[[mods]]
|
|
||||||
modId="examplemod"
|
|
||||||
version="1.0.0"
|
|
||||||
displayName="Example Mod DataGen"
|
|
||||||
description="Example Mod DataGen"
|
|
||||||
|
|
||||||
[[mods]]
|
|
||||||
modId="mdk_datagen"
|
|
||||||
version="1.0.0"
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'net.minecraftforge.forge.build.convention'
|
|
||||||
}
|
|
||||||
|
|
||||||
gradleutils.displayName = 'Forge-Tests'
|
|
||||||
description = 'Mods used for testing Forge features'
|
|
||||||
|
|
||||||
license {
|
|
||||||
exclude 'com/example/'
|
|
||||||
}
|
|
||||||
|
|
||||||
convention.manifest('net/minecraftforge/forge/test/', [
|
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.forge.test'
|
|
||||||
])
|
|
||||||
convention.manifest('net/minecraftforge/forge/debug/')
|
|
||||||
|
|
||||||
convention.publish()
|
|
||||||
|
|
||||||
convention.basicRuns('.+', file('src/main/generated')) {
|
|
||||||
flat = false
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
api project(':forge-examiner')
|
|
||||||
}
|
|
||||||
-3
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"type": "minecraft:no_op"
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_dirt": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:dirt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_dirt"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-76
@@ -1,76 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_dirt": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:dirt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:children": [
|
|
||||||
{
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"child": {
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_oak_log": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:oak_log"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_oak_log"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:true"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_dirt"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_dirt": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:dirt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_dirt"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_bee_nest": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:bee_nest"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:true"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_bee_nest"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_dirt": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:dirt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_dirt"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_oak_log": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:oak_log"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:true"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_oak_log"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_redstone_ore": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:redstone_ore"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_redstone_ore"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_redstone_ore": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:redstone_ore"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:true"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_redstone_ore"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_redstone_ore": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:redstone_ore"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:true"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_redstone_ore"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_dirt": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:dirt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:false"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_dirt"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-36
@@ -1,36 +0,0 @@
|
|||||||
{
|
|
||||||
"parent": "minecraft:recipes/root",
|
|
||||||
"criteria": {
|
|
||||||
"has_iron_ore": {
|
|
||||||
"conditions": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"items": "minecraft:iron_ore"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:inventory_changed"
|
|
||||||
},
|
|
||||||
"has_the_recipe": {
|
|
||||||
"conditions": {
|
|
||||||
"recipes": "minecraft:diamond_block"
|
|
||||||
},
|
|
||||||
"trigger": "minecraft:recipe_unlocked"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"forge:condition": {
|
|
||||||
"type": "forge:tag_empty",
|
|
||||||
"tag": "minecraft:dirt"
|
|
||||||
},
|
|
||||||
"requirements": [
|
|
||||||
[
|
|
||||||
"has_the_recipe",
|
|
||||||
"has_iron_ore"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"rewards": {
|
|
||||||
"recipes": [
|
|
||||||
"minecraft:diamond_block"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loaded 100 of 2155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user