mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-17 19:15:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d17cfd0b4b | ||
|
|
d697be351f | ||
|
|
703195cd36 | ||
|
|
3f1e9a90c9 | ||
|
|
da353a52fe | ||
|
|
3bac35089f | ||
|
|
cb2e205867 | ||
|
|
c5d015e60a | ||
|
|
72be0c9ccd | ||
|
|
dabe919492 | ||
|
|
3da1b644d0 | ||
|
|
d3476f3f80 | ||
|
|
6665cdcf4e | ||
|
|
d9665f6447 | ||
|
|
ec73fd5240 | ||
|
|
3bbdbacb81 | ||
|
|
478d8b3f18 | ||
|
|
03f928a3de | ||
|
|
4834f16aef | ||
|
|
7846d25606 | ||
|
|
77cb0c5c4e | ||
|
|
5e421e8b8b | ||
|
|
5f37e8af53 | ||
|
|
5ab792f1d7 | ||
|
|
38ebbf189c | ||
|
|
f247eebd55 | ||
|
|
555989cf10 | ||
|
|
49fe93b1b5 | ||
|
|
48167e93b4 | ||
|
|
2bd132a6f8 | ||
|
|
b8168a12df | ||
|
|
df271e0265 | ||
|
|
d7687a72d5 | ||
|
|
047e5fe252 |
No files matched your search
@@ -2,7 +2,7 @@ name: Publish
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ '1.21.11' ]
|
branches: [ '26.2' ]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|||||||
+15
-3
@@ -1,3 +1,6 @@
|
|||||||
|
#forgedev dev if the folder exists in here
|
||||||
|
forgedev
|
||||||
|
|
||||||
#eclipse
|
#eclipse
|
||||||
**/bin
|
**/bin
|
||||||
**/.settings
|
**/.settings
|
||||||
@@ -22,10 +25,12 @@
|
|||||||
/*/build
|
/*/build
|
||||||
/*/.gradle
|
/*/.gradle
|
||||||
|
|
||||||
|
# Minecraft
|
||||||
|
/run
|
||||||
|
/*.launch
|
||||||
|
|
||||||
# Projects repo, either ignore it, or ignore patches.
|
# Projects repo, either ignore it, or ignore patches.
|
||||||
/projects/mcp/
|
src/minecraft
|
||||||
/projects/clean/
|
|
||||||
/projects/forge/
|
|
||||||
|
|
||||||
#occupational hazards
|
#occupational hazards
|
||||||
/projects/**/build/
|
/projects/**/build/
|
||||||
@@ -33,6 +38,7 @@
|
|||||||
/projects/**/run/
|
/projects/**/run/
|
||||||
/projects/**/*.launch
|
/projects/**/*.launch
|
||||||
/repo/
|
/repo/
|
||||||
|
/rejects-*/
|
||||||
src/*/generated/**/.cache/
|
src/*/generated/**/.cache/
|
||||||
|
|
||||||
# Generated by gradle every import
|
# Generated by gradle every import
|
||||||
@@ -46,3 +52,9 @@ src/*/generated/**/.cache/
|
|||||||
/*/.gitignore
|
/*/.gitignore
|
||||||
/*/.factorypath
|
/*/.factorypath
|
||||||
/*/.apt_generated/
|
/*/.apt_generated/
|
||||||
|
/fmlcore/logs/
|
||||||
|
/lib/
|
||||||
|
/_actual/
|
||||||
|
/runs/
|
||||||
|
/forge.ipr
|
||||||
|
/forge.iws
|
||||||
+1
-1
@@ -3,7 +3,7 @@ parts herein are licensed under the terms of the LGPL 2.1 found
|
|||||||
here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and
|
here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and
|
||||||
copied below.
|
copied below.
|
||||||
|
|
||||||
Homepage: http://minecraftforge.net/
|
Homepage: https://minecraftforge.net/
|
||||||
https://github.com/MinecraftForge/MinecraftForge
|
https://github.com/MinecraftForge/MinecraftForge
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+776
-35
@@ -1,54 +1,795 @@
|
|||||||
import net.minecraftforge.forge.tasks.*
|
import org.apache.tools.ant.filters.ReplaceTokens
|
||||||
import net.minecraftforge.gradleutils.PomUtils
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'net.minecraftforge.licenser' version '1.0.1'
|
id 'java-library'
|
||||||
id 'com.github.ben-manes.versions' version '0.46.0'
|
id 'idea'
|
||||||
id 'net.minecraftforge.gradleutils' version '[2.6.4,2.7)'
|
|
||||||
id 'eclipse'
|
id 'eclipse'
|
||||||
id 'de.undercouch.download' version '5.4.0'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.gradle.patcher' version '[6.0.46,6.2)' apply false
|
alias libs.plugins.licenser
|
||||||
id 'net.minecraftforge.gradle.mcp' version '[6.0.46,6.2)' apply false
|
alias libs.plugins.versions
|
||||||
id 'net.minecraftforge.gradlejarsigner' version '1.0.4'
|
alias libs.plugins.gradleutils
|
||||||
id 'org.barfuin.gradle.taskinfo' version '2.1.0'
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
alias libs.plugins.jarsigner
|
||||||
|
id 'net.minecraftforge.forgedev'
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
Util.init() //Init all our extension methods!
|
gradleutils.displayName = 'Forge'
|
||||||
|
group = 'net.minecraftforge'
|
||||||
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
ext {
|
// NOTE: See settings.gradle for all the referenceable version variables.
|
||||||
VERSION = gitversion.getMCTagOffsetBranch(MC_VERSION)
|
// All subprojects (that apply 'net.minecraftforge.forge.build.convention') will have these available.
|
||||||
FORGE_VERSION = VERSION.substring(MC_VERSION.length() + 1)
|
println "Version: $version"
|
||||||
|
|
||||||
|
java.toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
|
||||||
|
jarSigner.autoDetect('forge')
|
||||||
|
|
||||||
|
// We have to tell ForgeDev to use the exact versions of tools we ship in the installer
|
||||||
|
fdtools {
|
||||||
|
configure('binpatcher') {
|
||||||
|
version = buildLibs.binarypatcher.get().version
|
||||||
|
}
|
||||||
|
configure('installertools') {
|
||||||
|
version = buildLibs.installertools.get().version
|
||||||
|
}
|
||||||
|
configure('jarcompatibilitychecker') {
|
||||||
|
javaLauncher = javaToolchains.launcherFor(java.toolchain)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
changelog {
|
/* This is used for debugging, comparing all published artifacts against actual production
|
||||||
from '47.999'
|
forgedev.validatePublish {
|
||||||
|
task {
|
||||||
|
baseBranch = 'upstream/26.1.2'
|
||||||
|
versionPrefix = minecraftVersion
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
final minecraftFiles = forgedev.minecraftFiles(minecraftVersion)
|
||||||
|
|
||||||
|
final mcpBase = forgedev.mcpBase {
|
||||||
|
mcpVersion = "${minecraftVersion}-${project.ext.mcpVersion}"
|
||||||
|
accessTransformers.from file('src/main/resources/META-INF/accesstransformer.cfg')
|
||||||
|
sideAnnotationStrippers.from file('src/main/resources/forge.sas')
|
||||||
|
}
|
||||||
|
|
||||||
|
forgedev.patches {
|
||||||
|
base = mcpBase
|
||||||
|
patches = file('patches/minecraft')
|
||||||
|
patched = file('src/minecraft/java')
|
||||||
|
sourceSets.main.java.srcDir patched
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.register('setup') {
|
tasks.register('setup') {
|
||||||
dependsOn ':forge:extractMapped'
|
dependsOn forgedev.patches.apply
|
||||||
if (findProject(':clean'))
|
|
||||||
dependsOn ':clean:extractMapped'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.register('doChecks') {
|
sourceSets {
|
||||||
dependsOn ':forge:checkJarCompatibility'
|
named('main') {
|
||||||
dependsOn ':forge:publish'
|
resources.srcDir 'src/main/generated'
|
||||||
}
|
}
|
||||||
|
named('test') {
|
||||||
project(':mcp') {
|
resources.srcDir 'src/test/generated'
|
||||||
apply plugin: 'net.minecraftforge.gradle.mcp'
|
|
||||||
mcp {
|
|
||||||
config MC_VERSION + '-' + MCP_VERSION
|
|
||||||
pipeline = 'joined'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (System.env.TEAMCITY_VERSION) {
|
license {
|
||||||
//Only setup the CI environment if and only if the environment variables are set.
|
header = file('LICENSE-header.txt')
|
||||||
tasks.named('configureTeamCity').configure {
|
|
||||||
doLast {
|
include 'net/minecraftforge/'
|
||||||
println "##teamcity[buildNumber '${project(':forge').version}']"
|
exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
|
||||||
println "##teamcity[setParameter name='env.PUBLISHED_JAVA_ARTIFACT_VERSION' value='${project(':forge').version}']"
|
|
||||||
|
tasks.tap {
|
||||||
|
register('main') {
|
||||||
|
files.from files('src/main/java')
|
||||||
|
}
|
||||||
|
|
||||||
|
register('test') {
|
||||||
|
files.from files('src/test/java')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
changelog {
|
||||||
|
from changelogBase
|
||||||
|
publishAll = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO [ForgeDev] Support compileOnlyApi, runtimeOnly, and a consumable annotation processor configuration
|
||||||
|
configurations {
|
||||||
|
// Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
|
||||||
|
register('bootstrap') {
|
||||||
|
transitive = false
|
||||||
|
canBeDeclared = true
|
||||||
|
canBeResolved = true
|
||||||
|
}
|
||||||
|
|
||||||
|
register('installer') {
|
||||||
|
transitive = false
|
||||||
|
canBeDeclared = true
|
||||||
|
canBeResolved = true
|
||||||
|
extendsFrom(bootstrap)
|
||||||
|
}
|
||||||
|
|
||||||
|
named('api') {
|
||||||
|
extendsFrom(installer)
|
||||||
|
}
|
||||||
|
|
||||||
|
named('implementation') {
|
||||||
|
// Inherit vanilla Minecraft's dependencies
|
||||||
|
extendsFrom(mcpBase.dependencyConfiguration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// These need to actually be on the classpath at the start. This is only used for the server shim jar.
|
||||||
|
// And this is only needed because custom file systems are REQUIRED to be on the boot classloader.
|
||||||
|
// This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project.
|
||||||
|
bootstrap libs.jarjar.fs // JarInJar file system
|
||||||
|
bootstrap libs.roimfs // JarInJar File System - FileSystems need to be on boot loader.
|
||||||
|
bootstrap libs.bundles.jimfs // In memory file system used for ForgeDev launches
|
||||||
|
bootstrap libs.securemodules // Has Union file system in it
|
||||||
|
bootstrap libs.unsafe // Needed by securemodules
|
||||||
|
bootstrap libs.bundles.asm // Needed by securemodules
|
||||||
|
|
||||||
|
implementation libs.jopt.simple
|
||||||
|
|
||||||
|
installer libs.bootstrap
|
||||||
|
installer libs.bootstrap.api // Needed by securemodules
|
||||||
|
installer libs.accesstransformers
|
||||||
|
installer libs.eventbus
|
||||||
|
installer libs.jspecify // Dep of EventBus
|
||||||
|
installer libs.forgespi
|
||||||
|
installer libs.coremods.api
|
||||||
|
installer libs.modlauncher
|
||||||
|
installer libs.mergetool.api
|
||||||
|
installer libs.bundles.night.config
|
||||||
|
installer libs.maven.artifact
|
||||||
|
installer libs.bundles.terminalconsoleappender
|
||||||
|
installer libs.mixin
|
||||||
|
installer libs.mixinextras.forge
|
||||||
|
installer libs.bundles.jarjar
|
||||||
|
installer libs.roimfs
|
||||||
|
|
||||||
|
installer projects.fmlcore
|
||||||
|
installer projects.fmlloader
|
||||||
|
installer projects.fmlearlydisplay
|
||||||
|
installer projects.javafmllanguage
|
||||||
|
installer projects.lowcodelanguage
|
||||||
|
installer projects.mclanguage
|
||||||
|
installer projects.forgeTransformers
|
||||||
|
|
||||||
|
runtimeOnly files(mcpBase.extra)
|
||||||
|
|
||||||
|
runtimeOnly libs.bootstrap
|
||||||
|
runtimeOnly libs.bootstrap.dev
|
||||||
|
|
||||||
|
annotationProcessor libs.eventbus.validator
|
||||||
|
}
|
||||||
|
|
||||||
|
final EXTRA_TXTS = [
|
||||||
|
file('LICENSE.txt'),
|
||||||
|
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', '-XX:+UseCompactObjectHeaders'
|
||||||
|
|
||||||
|
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 {
|
||||||
|
config {
|
||||||
|
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
|
args = ['--launchTarget', 'forge_server']
|
||||||
|
}
|
||||||
|
classpath {
|
||||||
|
libraries configurations.installer
|
||||||
|
library tasks.named('universalJar', Jar)
|
||||||
|
library forgedev.binaryPatches('server').apply, 'server'
|
||||||
|
serverBundle.fileProvider(minecraftFiles.server)
|
||||||
|
}
|
||||||
|
bootstrapClasspath(configurations.bootstrap)
|
||||||
|
jar {
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final finalizeSpawn = forgedev.methodCallFinder('findFinalizeSpawnTargets') {
|
||||||
|
jar.fileProvider(mcpBase.classes)
|
||||||
|
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.
|
||||||
|
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)) {
|
||||||
|
mcVersion = minecraftVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
forgedev.checks() {
|
||||||
|
base = mcpBase
|
||||||
|
ats {}
|
||||||
|
sas {}
|
||||||
|
execs {}
|
||||||
|
|
||||||
|
patches {
|
||||||
|
dependsOn forgedev.patches.make
|
||||||
|
patchDir = forgedev.patches.patches
|
||||||
|
patchesWithS2SArtifact = [
|
||||||
|
'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
|
||||||
|
'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fix {
|
||||||
|
dependsOn finalizeSpawn
|
||||||
|
}
|
||||||
|
|
||||||
|
forgedev.patches.make.configure {
|
||||||
|
finalizedBy forgedev.checks.patches.fix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final crowdin = forgedev.crowdin // Create the crowdin tasks
|
||||||
|
tasks.named('jar', Jar) {
|
||||||
|
from(EXTRA_TXTS)
|
||||||
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
|
exclude '.cache'
|
||||||
|
|
||||||
|
from(zipTree(crowdin.flatMap { it.output } )) {
|
||||||
|
include 'assets/forge/lang/*.json'
|
||||||
|
}
|
||||||
|
|
||||||
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.forge'
|
||||||
|
])
|
||||||
|
attributes([
|
||||||
|
'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-Vendor' : gradleutils.vendor.get(),
|
||||||
|
'Specification-Version' : minecraftVersion,
|
||||||
|
'Implementation-Title' : 'MCP',
|
||||||
|
'Implementation-Vendor' : gradleutils.vendor.get(),
|
||||||
|
'Implementation-Version': mcpVersion
|
||||||
|
], 'net/minecraftforge/versions/mcp/')
|
||||||
|
}
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
|
||||||
|
final universalJar = tasks.register('universalJar', Jar) {
|
||||||
|
from (zipTree(tasks.named('jar', Jar).flatMap { it.archiveFile } )) {
|
||||||
|
exclude(forgedev.filterVanilla(mcpBase.classes))
|
||||||
|
}
|
||||||
|
manifest = tasks.named('jar', Jar).get().manifest
|
||||||
|
archiveClassifier = 'universal'
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
|
||||||
|
final sourcesJarAll = tasks.register('sourcesJarAll', Jar) {
|
||||||
|
archiveClassifier = 'sources-all'
|
||||||
|
from(sourceSets.main.allJava.srcDirs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Our sources, plus the patches we do to Vanilla Minecraft
|
||||||
|
final sourcesJar = tasks.register('sourcesJar', Jar) {
|
||||||
|
archiveClassifier = 'sources'
|
||||||
|
from(sourceSets.main.allJava.srcDirs - forgedev.patches.patched.asFile.get())
|
||||||
|
mustRunAfter(forgedev.patches.make)
|
||||||
|
from(forgedev.patches.patches) {
|
||||||
|
into 'patches/'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
forgedev.userDev {
|
||||||
|
base(mcpBase)
|
||||||
|
|
||||||
|
config {
|
||||||
|
universal universalJar
|
||||||
|
sources sourcesJar
|
||||||
|
addLibraries(configurations.installer)
|
||||||
|
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
|
||||||
|
// so we don't gotta keep making exceptions for MixinExtras
|
||||||
|
addCompileDependency(libs.mixinextras.common)
|
||||||
|
addAnnotationProcessorDependency(libs.mixinextras.common)
|
||||||
|
|
||||||
|
// TODO [ForgeDev] Consolidate Patcher + UserDev Config runs in a sane way
|
||||||
|
runs {
|
||||||
|
configureEach {
|
||||||
|
parents = []
|
||||||
|
main = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
|
args '--gameDir', '.'
|
||||||
|
jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders'
|
||||||
|
client = it.name.containsIgnoreCase('client')
|
||||||
|
environment 'MCP_MAPPINGS', '{mcp_mappings}'
|
||||||
|
}
|
||||||
|
|
||||||
|
register('clientData') {
|
||||||
|
args '--launchTarget', "forge_userdev_client_data"
|
||||||
|
args '--assetIndex', '{asset_index}'
|
||||||
|
args '--assetsDir', '{assets_root}'
|
||||||
|
}
|
||||||
|
|
||||||
|
register('client') {
|
||||||
|
property 'forge.enableGameTest', 'true'
|
||||||
|
args '--launchTarget', "forge_userdev_client"
|
||||||
|
args '--version', 'MOD_DEV'
|
||||||
|
args '--assetIndex', '{asset_index}'
|
||||||
|
args '--assetsDir', '{assets_root}'
|
||||||
|
}
|
||||||
|
|
||||||
|
register('server') {
|
||||||
|
property 'forge.enableGameTest', 'true'
|
||||||
|
args '--launchTarget', "forge_userdev_server"
|
||||||
|
}
|
||||||
|
|
||||||
|
register('gameTestServer') {
|
||||||
|
args '--launchTarget', "forge_userdev_server_gametest"
|
||||||
|
}
|
||||||
|
|
||||||
|
register('data') {
|
||||||
|
args '--launchTarget', "forge_userdev_data"
|
||||||
|
args '--assetIndex', '{asset_index}'
|
||||||
|
args '--assetsDir', '{assets_root}'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
patches {
|
||||||
|
modified.setFrom(sourcesJarAll.flatMap { it.archiveFile })
|
||||||
|
}
|
||||||
|
binaryPatches {
|
||||||
|
mustRunAfter(forgedev.patches.make)
|
||||||
|
patches.setFrom(forgedev.patches.patches)
|
||||||
|
dirty.setFrom(tasks.named('jar', Jar).flatMap { it.archiveFile })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
forgedev.userdevCompatibility(minecraftVersion) {
|
||||||
|
clean = mcpBase.classes
|
||||||
|
dirty = tasks.named('jar', Jar)
|
||||||
|
}
|
||||||
|
|
||||||
|
// region Installer tasks, Not needed when we simplify the installer/remove obf
|
||||||
|
final clientBinPatches = forgedev.binaryPatches('client') {
|
||||||
|
clean = minecraftFiles.client
|
||||||
|
// Workaround for 3rd party launcher issues, marker needed to locate MC, store needed to fix zlib-ng issues
|
||||||
|
apply {
|
||||||
|
store = true
|
||||||
|
marker = '.forge_patched_minecraft'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final serverBinPatches = forgedev.binaryPatches('server') {
|
||||||
|
clean = minecraftFiles.serverExtracted
|
||||||
|
apply { store = true }
|
||||||
|
}
|
||||||
|
// endregion
|
||||||
|
|
||||||
|
forgedev.installer {
|
||||||
|
dev = !forgedev.ci
|
||||||
|
offline = false
|
||||||
|
baseVersion = buildLibs.installer.get().version.toString()
|
||||||
|
|
||||||
|
// 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 universalJar // I don't think this is strictly needed to be packed anymore, will need to double check later
|
||||||
|
|
||||||
|
launcherLibrary universalJar
|
||||||
|
// We configure the launcher here to keep the order for easier diff, after publishing, move this to the LauncherJson configuration below
|
||||||
|
launcherJson {
|
||||||
|
// We create this during install, so it's not downloadable
|
||||||
|
generated(clientBinPatches.apply, 'client')
|
||||||
|
}
|
||||||
|
|
||||||
|
launcherLibraries configurations.installer
|
||||||
|
|
||||||
|
final launcherId = "${minecraftVersion}-${project.name}-${forgeVersion}"
|
||||||
|
final installertools = tool(buildLibs.installertools)
|
||||||
|
final binarypatcher = tool(buildLibs.binarypatcher)
|
||||||
|
|
||||||
|
jar {
|
||||||
|
from(EXTRA_TXTS)
|
||||||
|
from(rootProject.file('/forge_installer_logo.png')) {
|
||||||
|
rename { 'big_logo.png' }
|
||||||
|
}
|
||||||
|
from(clientBinPatches.create.flatMap { t -> t.output }) {
|
||||||
|
rename { 'data/client.lzma' }
|
||||||
|
}
|
||||||
|
from(serverBinPatches.create.flatMap { t -> t.output }) {
|
||||||
|
rename { 'data/server.lzma' }
|
||||||
|
}
|
||||||
|
|
||||||
|
final argsFile = rootProject.file('server_files/args.txt')
|
||||||
|
final tokens = [tokens: [
|
||||||
|
SHIM_JAR_FILE: serverShim.jar.get().archiveFileName.get(),
|
||||||
|
MAVEN_PATH: forgedev.mavenArtifact.directory
|
||||||
|
]]
|
||||||
|
from(argsFile) {
|
||||||
|
filter(tokens, ReplaceTokens)
|
||||||
|
into 'data'
|
||||||
|
rename { 'unix_args.txt' }
|
||||||
|
}
|
||||||
|
from(argsFile) {
|
||||||
|
filter(tokens, ReplaceTokens)
|
||||||
|
into 'data'
|
||||||
|
rename { 'win_args.txt' }
|
||||||
|
}
|
||||||
|
|
||||||
|
from(rootProject.file('server_files')) {
|
||||||
|
filter(tokens, ReplaceTokens)
|
||||||
|
into 'data'
|
||||||
|
exclude 'args.txt'
|
||||||
|
}
|
||||||
|
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
json {
|
||||||
|
icon = rootProject.file('icon.ico')
|
||||||
|
executable serverShim.jar
|
||||||
|
minecraft = minecraftVersion
|
||||||
|
profileVersion = launcherId
|
||||||
|
|
||||||
|
final projectArtifact = "${project.group}:${project.name}:${project.version}"
|
||||||
|
|
||||||
|
data 'MC_UNPACKED', "[net.minecraft:client:${minecraftVersion}]", "[net.minecraft:server:${minecraftVersion}:unpacked]"
|
||||||
|
data 'MC_UNPACKED_SHA', minecraftFiles.client, minecraftFiles.serverExtracted
|
||||||
|
|
||||||
|
data 'BINPATCH', '/data/client.lzma', '/data/server.lzma'
|
||||||
|
data 'PATCHED', "[$projectArtifact:client]", "[$projectArtifact:server]"
|
||||||
|
data 'PATCHED_SHA', clientBinPatches.apply.flatMap { it.output }, serverBinPatches.apply.flatMap { it.output }
|
||||||
|
|
||||||
|
steps = [
|
||||||
|
extract(installertools) {
|
||||||
|
side = 'server'
|
||||||
|
archive '{INSTALLER}'
|
||||||
|
extract 'data/README.txt', '{ROOT}/README.txt'
|
||||||
|
extract 'data/run.sh', '{ROOT}/run.sh'
|
||||||
|
executable '{ROOT}/run.sh'
|
||||||
|
extract 'data/run.bat', '{ROOT}/run.bat'
|
||||||
|
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/win_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/win_args.txt"
|
||||||
|
},
|
||||||
|
extractBundle(installertools) {
|
||||||
|
side = 'server'
|
||||||
|
libraries()
|
||||||
|
},
|
||||||
|
extractBundle(installertools) {
|
||||||
|
side = 'server'
|
||||||
|
jar '{MINECRAFT_JAR}', '{MC_UNPACKED}'
|
||||||
|
cache '{MC_UNPACKED}', '{MC_UNPACKED_SHA}'
|
||||||
|
},
|
||||||
|
step(binarypatcher) {
|
||||||
|
side = 'server'
|
||||||
|
args = [
|
||||||
|
'--clean', '{MC_UNPACKED}',
|
||||||
|
'--output', '{PATCHED}',
|
||||||
|
'--apply', '{BINPATCH}',
|
||||||
|
'--data', '--unpatched',
|
||||||
|
'--store'
|
||||||
|
]
|
||||||
|
cache '{PATCHED}', '{PATCHED_SHA}'
|
||||||
|
},
|
||||||
|
step(binarypatcher) {
|
||||||
|
side = 'client'
|
||||||
|
args = [
|
||||||
|
'--clean', '{MINECRAFT_JAR}',
|
||||||
|
'--output', '{PATCHED}',
|
||||||
|
'--apply', '{BINPATCH}',
|
||||||
|
'--data', '--unpatched',
|
||||||
|
'--store',
|
||||||
|
'--marker', '.forge_patched_minecraft'
|
||||||
|
]
|
||||||
|
cache '{PATCHED}', '{PATCHED_SHA}'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
launcherJson {
|
||||||
|
// These are flags to preserve glitchy old behavior to make diffing easier, removing when migrating to production is recommended
|
||||||
|
sortLibraries = false // Don't sort, makes things non-deterministic, but easier to diff old versions
|
||||||
|
duplicateLibraries = true // Our 'bootstrap' layer go added twice
|
||||||
|
librariesLast = false // Makes libraries be added before args
|
||||||
|
|
||||||
|
id = launcherId
|
||||||
|
inheritsFrom = minecraftVersion
|
||||||
|
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
|
gameArgs = [ '--launchTarget', 'forge_client' ]
|
||||||
|
jvmArgs = [ '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' ]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
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/'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
tasks.named('javadoc', Javadoc) {
|
||||||
|
description = 'Generates the combined javadocs for the FML projects and the main Forge project'
|
||||||
|
var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage', ':forge-transformers' ]
|
||||||
|
source includedProjects.collect { project(it).sourceSets.main.allJava }
|
||||||
|
classpath = classpath + files(includedProjects.collect { project(it).sourceSets.main.compileClasspath })
|
||||||
|
|
||||||
|
var docsDir = rootProject.file('src/docs/')
|
||||||
|
inputs.dir(docsDir)
|
||||||
|
.withPropertyName('docs resources directory')
|
||||||
|
.withPathSensitivity(PathSensitivity.RELATIVE)
|
||||||
|
.optional()
|
||||||
|
|
||||||
|
failOnError = false
|
||||||
|
|
||||||
|
// Exclude the Minecraft classes if not enabled
|
||||||
|
if (!project.hasProperty('generateAllDocumentation')) {
|
||||||
|
exclude 'net/minecraft/**'
|
||||||
|
exclude 'com/mojang/**'
|
||||||
|
}
|
||||||
|
exclude 'mcp/**'
|
||||||
|
|
||||||
|
options {
|
||||||
|
stylesheetFile = new File(docsDir, 'stylesheet.css')
|
||||||
|
|
||||||
|
tags = [
|
||||||
|
'apiNote:a:<em>API Note:</em>',
|
||||||
|
'implSpec:a:<em>Implementation Requirements:</em>',
|
||||||
|
'implNote:a:<em>Implementation Note:</em>'
|
||||||
|
]
|
||||||
|
|
||||||
|
groups = [
|
||||||
|
'Forge Mod Loader': [
|
||||||
|
'net.minecraftforge.fml.common.asm*',
|
||||||
|
'net.minecraftforge.fml.loading*',
|
||||||
|
'net.minecraftforge.fml.server*'
|
||||||
|
],
|
||||||
|
'FML Core': [
|
||||||
|
'net.minecraftforge.fml',
|
||||||
|
'net.minecraftforge.fml.config*',
|
||||||
|
'net.minecraftforge.fml.event*',
|
||||||
|
'net.minecraftforge.fml.util*'
|
||||||
|
],
|
||||||
|
'FML Common': [
|
||||||
|
'net.minecraftforge.fml.core',
|
||||||
|
'net.minecraftforge.fml.event.config',
|
||||||
|
'net.minecraftforge.fml.event.lifecycle'
|
||||||
|
],
|
||||||
|
'FML Java/MC Language Providers': [
|
||||||
|
'net.minecraftforge.fml.common',
|
||||||
|
'net.minecraftforge.fml.javafmlmod',
|
||||||
|
'net.minecraftforge.fml.mclanguageprovider'
|
||||||
|
],
|
||||||
|
'Minecraft Forge API': [
|
||||||
|
'net.minecraftforge*'
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
author = false
|
||||||
|
noSince = true
|
||||||
|
noHelp = true
|
||||||
|
|
||||||
|
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}"
|
||||||
|
docTitle = "Minecraft Forge API - ${forgeVersion} for Minecraft ${minecraftVersion}"
|
||||||
|
header = "<div style=\"margin-top: 9px;padding: 5px 6px;\"><strong>${forgeVersion} for Minecraft ${minecraftVersion}</strong></div>"
|
||||||
|
}
|
||||||
|
|
||||||
|
doLast {
|
||||||
|
project.copy {
|
||||||
|
from docsDir
|
||||||
|
exclude '/stylesheet.css'
|
||||||
|
into destinationDir
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven gradleutils.publishingForgeMaven
|
||||||
|
}
|
||||||
|
|
||||||
|
publications.register('mavenJava', MavenPublication) {
|
||||||
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
artifact universalJar
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
// These are debugging tasks that are only used when developing ForgeDevPlugin, to bulk test task's config/caching
|
||||||
|
// region ForgeDev Tests
|
||||||
|
def all = tasks.register('all') {}
|
||||||
|
afterEvaluate {
|
||||||
|
if (gradle.startParameter.taskNames.contains('all')) {
|
||||||
|
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 (task.name in [all.name, 'dependencyInsight', 'dependencies', 'dependencyUpdates', 'init', 'buildEnvironment', 'idea',
|
||||||
|
'eclipse', 'javaToolchains', 'outgoingVariants', 'projects', 'properties', 'resolvableConfigurations', 'tasks', 'updateDaemonJvm',
|
||||||
|
'generateActionsWorkflow'
|
||||||
|
]) 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
|
||||||
|
all.configure { dependsOn(task) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
// endregion
|
||||||
|
// We dont have any unit tests, so disable this error
|
||||||
|
tasks.withType(AbstractTestTask).configureEach {
|
||||||
|
failOnNoDiscoveredTests = false
|
||||||
|
}
|
||||||
|
// 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
|
||||||
|
[ 'makePatches', 'compileJava', 'checkLicenseMain', 'updateLicenseMain', 'sourcesJar', 'sourcesJarAll' ]
|
||||||
|
.each{ tasks.named(it).configure{ mustRunAfter forgedev.patches.apply }}
|
||||||
|
forgedev.runs.configureEach {
|
||||||
|
run.configure { dependsOn finalizeSpawn}
|
||||||
|
runTest.configure { dependsOn finalizeSpawn}
|
||||||
|
}
|
||||||
|
// run gradlew dependencyUpdates --no-parallel
|
||||||
|
//noinspection UnnecessaryQualifiedReference
|
||||||
|
tasks.named('dependencyUpdates', com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask) {
|
||||||
|
resolutionStrategy {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
/.gradle/
|
|
||||||
/build/
|
|
||||||
/out/
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
repositories {
|
|
||||||
maven { url = 'https://maven.minecraftforge.net/' }
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation 'org.ow2.asm:asm:9.8'
|
|
||||||
implementation 'org.ow2.asm:asm-tree:9.8'
|
|
||||||
implementation 'net.minecraftforge:srgutils:0.6.2'
|
|
||||||
implementation 'net.minecraftforge:JarJarMetadata:0.3.27'
|
|
||||||
implementation 'commons-io:commons-io:2.13.0'
|
|
||||||
implementation 'com.google.code.gson:gson:2.10.1'
|
|
||||||
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.7.0.202309050840-r'
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import org.gradle.api.tasks.*
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.bundling.AbstractArchiveTask
|
|
||||||
|
|
||||||
import java.util.zip.ZipFile
|
|
||||||
|
|
||||||
abstract class BundleList extends DefaultTask {
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getConfig()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getConfigExtra()
|
|
||||||
@InputFile abstract RegularFileProperty getServerBundle()
|
|
||||||
@OutputFile abstract RegularFileProperty getOutput()
|
|
||||||
|
|
||||||
BundleList() {
|
|
||||||
config.setFrom(project.configurations.installer)
|
|
||||||
configExtra.setFrom(project.configurations.installerextra)
|
|
||||||
output.convention(project.layout.buildDirectory.file("$name/output.list"))
|
|
||||||
configure {
|
|
||||||
dependsOn(project.tasks.universalJar)
|
|
||||||
inputs.file(project.tasks.universalJar.archiveFile)
|
|
||||||
dependsOn(project.tasks.applyServerBinPatches)
|
|
||||||
inputs.file(project.tasks.applyServerBinPatches.output)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
void run() {
|
|
||||||
def entries = [:] as TreeMap
|
|
||||||
def resolved = project.configurations.installer.resolvedConfiguration.resolvedArtifacts
|
|
||||||
for (def dep : resolved) {
|
|
||||||
def info = Util.getMavenInfoFromDep(dep)
|
|
||||||
//println("$dep.file.sha1\t$info.name\t$info.path")
|
|
||||||
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
|
|
||||||
}
|
|
||||||
|
|
||||||
resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts
|
|
||||||
for (def dep : resolved) {
|
|
||||||
def info = Util.getMavenInfoFromDep(dep)
|
|
||||||
//println("$dep.file.sha1\t$info.name\t$info.path")
|
|
||||||
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
|
|
||||||
}
|
|
||||||
|
|
||||||
var packed = (AbstractArchiveTask) project.tasks.universalJar
|
|
||||||
var info = Util.getMavenInfoFromTask(packed)
|
|
||||||
def file = packed.archiveFile.get().asFile
|
|
||||||
entries.put("$info.art.group:$info.art.name:$info.art.classifier", "$file.sha256\t$info.name\t$info.path")
|
|
||||||
|
|
||||||
var classifier = 'server'
|
|
||||||
var genned = project.tasks.applyServerBinPatches
|
|
||||||
info = Util.getMavenInfoFromTask(genned, classifier)
|
|
||||||
file = genned.output.get().asFile
|
|
||||||
entries.put("$info.art.group:$info.art.name:$info.art.classifier", "$file.sha256\t$info.name\t$info.path")
|
|
||||||
|
|
||||||
try (def zip = new ZipFile(serverBundle.get().asFile)) {
|
|
||||||
def entry = zip.getEntry('META-INF/libraries.list')
|
|
||||||
def data = zip.getInputStream(entry).text.split('\n')
|
|
||||||
for (def line : data) {
|
|
||||||
def (sha, artifact, path) = line.split('\t')
|
|
||||||
def (group, name, other) = artifact.split(':', 3)
|
|
||||||
//println("Group: $group Name: $name")
|
|
||||||
def key = "$group:$name"
|
|
||||||
if (other.indexOf(':') != -1){
|
|
||||||
key += ':' + other.split(':', 2)[1]
|
|
||||||
//println("\tKey: $key")
|
|
||||||
}
|
|
||||||
if (!entries.containsKey(key))
|
|
||||||
entries.put(key, line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
output.get().asFile.text = entries.values().join('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.json.JsonBuilder
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFile
|
|
||||||
import org.gradle.api.tasks.Internal
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
import org.objectweb.asm.tree.ClassNode
|
|
||||||
import org.objectweb.asm.tree.FieldNode
|
|
||||||
import org.objectweb.asm.tree.MethodNode
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class BytecodeFinder extends DefaultTask {
|
|
||||||
@InputFile abstract RegularFileProperty getJar()
|
|
||||||
// It should be fine to mark the output as internal as we want to control when we run it anyways.
|
|
||||||
// This also shuts Gradle 8 up about implicit task dependencies.
|
|
||||||
@Internal abstract RegularFileProperty getOutput()
|
|
||||||
|
|
||||||
BytecodeFinder() {
|
|
||||||
output.convention(project.layout.buildDirectory.dir(name).map { it.file("output.json") })
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
Util.init()
|
|
||||||
|
|
||||||
var outputFile = output.get().asFile
|
|
||||||
if (outputFile.exists())
|
|
||||||
outputFile.delete()
|
|
||||||
|
|
||||||
pre()
|
|
||||||
|
|
||||||
Util.processClassNodes(jar.get().asFile, this.&process)
|
|
||||||
|
|
||||||
post()
|
|
||||||
outputFile.text = new JsonBuilder(getData()).toPrettyString()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
protected process(ClassNode node) {
|
|
||||||
if (node.fields !== null) node.fields.each { process(node, it) }
|
|
||||||
if (node.methods !== null) node.methods.each { process(node, it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
protected pre() {}
|
|
||||||
protected process(ClassNode parent, FieldNode node) {}
|
|
||||||
protected process(ClassNode parent, MethodNode node) {}
|
|
||||||
protected post() {}
|
|
||||||
protected abstract Object getData()
|
|
||||||
}
|
|
||||||
-48
@@ -1,48 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import org.gradle.api.tasks.Internal
|
|
||||||
import org.objectweb.asm.Opcodes
|
|
||||||
import org.objectweb.asm.tree.ClassNode
|
|
||||||
import org.objectweb.asm.tree.MethodNode
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class BytecodePredicateFinder extends BytecodeFinder {
|
|
||||||
|
|
||||||
@Internal
|
|
||||||
abstract Property<Closure<Boolean>> getPredicate()
|
|
||||||
|
|
||||||
private final Map<String, List<String>> matches = new TreeMap<>(Comparator.naturalOrder())
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected process(ClassNode parent, MethodNode node) {
|
|
||||||
for (final current : node.instructions) {
|
|
||||||
if (predicate.get().call(parent, node, current)) {
|
|
||||||
var methods = matches.compute(parent.name, { k, v -> v ?: new ArrayList<>() })
|
|
||||||
|
|
||||||
// only add non-synthetic methods
|
|
||||||
if ((node.access & Opcodes.ACC_SYNTHETIC) == 0) {
|
|
||||||
methods.add(node.name + node.desc)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Internal
|
|
||||||
@Override
|
|
||||||
protected Object getData() {
|
|
||||||
var array = new ArrayList<Object>()
|
|
||||||
matches.forEach { c, m ->
|
|
||||||
{
|
|
||||||
array.add(
|
|
||||||
'class': c,
|
|
||||||
'methods': m
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return array ?: { throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.') }()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks;
|
|
||||||
|
|
||||||
import groovy.transform.CompileDynamic;
|
|
||||||
import groovy.transform.CompileStatic;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Enumeration;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.TreeSet;
|
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.Reader;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.io.Writer;
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Eclipse config files are literally just java properties, with the header cleaned up.
|
|
||||||
* https://github.com/eclipse/buildship/blob/5b2c7fca7fa86cd74d71b3c099c7b1559eba038e/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/configuration/PreferenceStore.java#L238
|
|
||||||
*
|
|
||||||
* This does the same thing, as well as sorting alphabetically.
|
|
||||||
* It also ignores all comments. We can add them latter if someone cares.
|
|
||||||
*/
|
|
||||||
@CompileStatic
|
|
||||||
public class CleanProperties extends Properties {
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
private static final String LINE_SEP = System.getProperty("line.separator");
|
|
||||||
private static final String UNIX_LINE_SEP = "\n";
|
|
||||||
private static final Charset ENCODING = StandardCharsets.UTF_8;
|
|
||||||
|
|
||||||
public CleanProperties load(File input) throws IOException {
|
|
||||||
if (input.exists()) {
|
|
||||||
try (Reader is = new InputStreamReader(new FileInputStream(input), ENCODING)) {
|
|
||||||
super.load(is);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void store(File out) throws IOException {
|
|
||||||
if (!out.getParentFile().exists())
|
|
||||||
out.getParentFile().mkdirs();
|
|
||||||
|
|
||||||
try (OutputStream os = new FileOutputStream(out)) {
|
|
||||||
store(os, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public synchronized Enumeration<Object> keys() {
|
|
||||||
Set<Object> ret = new TreeSet<>();
|
|
||||||
for (Enumeration<?> e = super.keys(); e.hasMoreElements();)
|
|
||||||
ret.add(e.nextElement());
|
|
||||||
return Collections.enumeration(ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileDynamic
|
|
||||||
@Override
|
|
||||||
public Set<Map.Entry<Object, Object>> entrySet() {
|
|
||||||
Set<Map.Entry<Object, Object>> ret = new TreeSet<>((l, r) -> ((String)l.getKey()).compareTo((String)r.getKey()));
|
|
||||||
ret.addAll(super.entrySet());
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void store(OutputStream out, String comments) throws IOException {
|
|
||||||
out.write(clean().getBytes(ENCODING));
|
|
||||||
out.flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void store(Writer out, String comments) throws IOException {
|
|
||||||
out.write(clean());
|
|
||||||
out.flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String clean() throws IOException {
|
|
||||||
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
|
|
||||||
try {
|
|
||||||
super.store(tmp, null);
|
|
||||||
} finally {
|
|
||||||
tmp.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
String ret = tmp.toString(ENCODING).replace(LINE_SEP, UNIX_LINE_SEP);
|
|
||||||
ret = ret.substring(ret.indexOf(UNIX_LINE_SEP) + 1);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.stc.FirstParam
|
|
||||||
|
|
||||||
import java.util.function.BiConsumer
|
|
||||||
|
|
||||||
public class ClosureHelper {
|
|
||||||
BiConsumer<String, Closure> callback
|
|
||||||
|
|
||||||
public ClosureHelper(Closure cl, BiConsumer<String, Closure> callback) {
|
|
||||||
this.callback = callback
|
|
||||||
apply(this, cl)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def methodMissing(String name, Object args) {
|
|
||||||
if (!args.class.isArray()) return
|
|
||||||
Object[] aargs = (Object[])args
|
|
||||||
|
|
||||||
if (aargs.length == 1 && aargs[0] instanceof Closure) {
|
|
||||||
this.callback.accept(name, (Closure)aargs[0])
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException('Unknown method: "' + name + '" with arguments ' + args + ' for ' + this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static <T> T apply(T obj, @DelegatesTo(value = FirstParam, strategy = Closure.DELEGATE_FIRST) Closure cl) {
|
|
||||||
cl.delegate = obj
|
|
||||||
cl.resolveStrategy = Closure.DELEGATE_FIRST
|
|
||||||
cl()
|
|
||||||
return obj
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.DirectoryProperty
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFile
|
|
||||||
import org.gradle.api.tasks.Internal
|
|
||||||
import org.gradle.api.tasks.OutputFile
|
|
||||||
import org.gradle.api.tasks.OutputFiles
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
import org.gradle.api.tasks.OutputDirectory
|
|
||||||
|
|
||||||
import java.nio.file.Files
|
|
||||||
|
|
||||||
abstract class DownloadLibraries extends DefaultTask {
|
|
||||||
@InputFile abstract RegularFileProperty getInput()
|
|
||||||
@OutputDirectory abstract DirectoryProperty getOutput()
|
|
||||||
@OutputFile abstract RegularFileProperty getLibrariesOutput()
|
|
||||||
|
|
||||||
DownloadLibraries() {
|
|
||||||
output.convention(project.layout.buildDirectory.dir(name))
|
|
||||||
librariesOutput.convention(project.layout.buildDirectory.dir(name).map(d -> d.file('libraries.txt')))
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
def run() {
|
|
||||||
Util.init()
|
|
||||||
File outputDir = output.get().asFile
|
|
||||||
var libraries = new ArrayList<String>()
|
|
||||||
|
|
||||||
def json = input.get().asFile.json().libraries.each { lib ->
|
|
||||||
//TODO: Thread?
|
|
||||||
def artifacts = [lib.downloads.artifact] + lib.downloads.get('classifiers', [:]).values()
|
|
||||||
artifacts.each{ art ->
|
|
||||||
def target = new File(outputDir, art.path)
|
|
||||||
libraries.add(target.absolutePath)
|
|
||||||
if (!target.exists() || art.sha1 != target.sha1()) {
|
|
||||||
project.logger.lifecycle("Downloading ${art.url}")
|
|
||||||
if (!target.parentFile.exists()) {
|
|
||||||
target.parentFile.mkdirs()
|
|
||||||
}
|
|
||||||
new URL(art.url).withInputStream { i ->
|
|
||||||
target.withOutputStream { it << i }
|
|
||||||
}
|
|
||||||
if (art.sha1 != target.sha1()) {
|
|
||||||
throw new IllegalStateException("Failed to download ${art.url} to ${target.canonicalPath} SHA Mismatch")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Files.write(librariesOutput.get().asFile.toPath(), libraries)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
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.*
|
|
||||||
|
|
||||||
import java.util.zip.ZipFile
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class ExtractFile extends DefaultTask {
|
|
||||||
@InputFile abstract RegularFileProperty getInput()
|
|
||||||
@Input abstract Property<String> getTarget()
|
|
||||||
@OutputFile abstract RegularFileProperty getOutput()
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
var zip = new ZipFile(input.get().asFile);
|
|
||||||
var entry = zip.getEntry(target.get())
|
|
||||||
if (entry == null)
|
|
||||||
throw new IllegalStateException(input.get().asFile.absolutePath + " does not contain " + target.get())
|
|
||||||
var stream = zip.getInputStream(entry)
|
|
||||||
output.get().asFile.withOutputStream { out ->
|
|
||||||
stream.transferTo(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import groovy.transform.EqualsAndHashCode
|
|
||||||
|
|
||||||
import org.gradle.api.tasks.*
|
|
||||||
import org.objectweb.asm.tree.AbstractInsnNode
|
|
||||||
import org.objectweb.asm.tree.ClassNode
|
|
||||||
import org.objectweb.asm.tree.MethodNode
|
|
||||||
|
|
||||||
import static org.objectweb.asm.Opcodes.*
|
|
||||||
|
|
||||||
abstract class FieldCompareFinder extends BytecodeFinder {
|
|
||||||
@Nested
|
|
||||||
Map<String, Search> fields = [:] as HashMap
|
|
||||||
@Internal
|
|
||||||
Map<Search, String> fieldsReverse = [:] as HashMap
|
|
||||||
@Internal
|
|
||||||
Map<String, Set<ObjectTarget>> targets = [:] as TreeMap
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected pre() {
|
|
||||||
//fields.each{ k,v -> logger.lifecycle("Fields: " + k + ' ' + v) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected process(ClassNode parent, MethodNode node) {
|
|
||||||
AbstractInsnNode last = null
|
|
||||||
def parentInstance = new ObjectTarget(owner: parent.name, name: '', desc: '')
|
|
||||||
for (int x = 0; x < node.instructions.size(); x++) {
|
|
||||||
def current = node.instructions.get(x)
|
|
||||||
if (current.opcode === IF_ACMPEQ || current.opcode === IF_ACMPNE) {
|
|
||||||
if (last !== null && (last.opcode === GETSTATIC || last.opcode === GETFIELD)) {
|
|
||||||
def target = new Search(cls: last.owner, name: last.name)
|
|
||||||
def wanted = fieldsReverse.get(target)
|
|
||||||
def original = fields.get(wanted)
|
|
||||||
def instance = new ObjectTarget(owner: parent.name, name: node.name, desc: node.desc)
|
|
||||||
if (wanted !== null && (original.blacklist === null || (!original.blacklist.contains(instance) && !original.blacklist.contains(parentInstance)))) {
|
|
||||||
targets.computeIfAbsent(wanted, { k -> new TreeSet() }).add(instance)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
last = current
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Internal
|
|
||||||
@Override
|
|
||||||
protected Object getData() {
|
|
||||||
def ret = [:] as HashMap
|
|
||||||
targets.forEach{ k, v ->
|
|
||||||
def e = fields.get(k)
|
|
||||||
ret[k] = [
|
|
||||||
cls: e.cls,
|
|
||||||
name: e.name,
|
|
||||||
replacement: e.replacement,
|
|
||||||
targets: v
|
|
||||||
]
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
@EqualsAndHashCode(excludes = ['replacement', 'blacklist'])
|
|
||||||
static class Search {
|
|
||||||
@Input
|
|
||||||
String cls
|
|
||||||
|
|
||||||
@Input
|
|
||||||
String name
|
|
||||||
|
|
||||||
@Input
|
|
||||||
String replacement
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
@Optional
|
|
||||||
Set<ObjectTarget> blacklist
|
|
||||||
|
|
||||||
@Override
|
|
||||||
String toString() {
|
|
||||||
return cls + '.' + name
|
|
||||||
}
|
|
||||||
|
|
||||||
def blacklist(String owner, String name, String desc) {
|
|
||||||
if (blacklist === null)
|
|
||||||
blacklist = new HashSet<>()
|
|
||||||
blacklist.add(new ObjectTarget(owner: owner, name: name, desc: desc))
|
|
||||||
}
|
|
||||||
def blacklist(String owner) {
|
|
||||||
blacklist(owner, '', '')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void fields(Closure cl) {
|
|
||||||
new ClosureHelper(cl, {name, ccl ->
|
|
||||||
def search = ClosureHelper.apply(new Search(), ccl)
|
|
||||||
this.fields.put(name, search)
|
|
||||||
this.fieldsReverse.put(search, name)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import com.google.gson.reflect.TypeToken
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import groovy.transform.TupleConstructor
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
@TupleConstructor
|
|
||||||
final class InheritanceData implements Annotatable {
|
|
||||||
String name
|
|
||||||
int access
|
|
||||||
String superName
|
|
||||||
List<String> interfaces = []
|
|
||||||
Map<String, Method> methods = [:]
|
|
||||||
Map<String, Field> fields = [:]
|
|
||||||
List<Annotation> annotations = []
|
|
||||||
|
|
||||||
@TupleConstructor
|
|
||||||
static final class Method implements Annotatable {
|
|
||||||
int access
|
|
||||||
String override
|
|
||||||
List<Annotation> annotations = []
|
|
||||||
}
|
|
||||||
|
|
||||||
@TupleConstructor
|
|
||||||
static final class Field implements Annotatable {
|
|
||||||
int access
|
|
||||||
String desc
|
|
||||||
List<Annotation> annotations = []
|
|
||||||
}
|
|
||||||
|
|
||||||
@TupleConstructor
|
|
||||||
static final class Annotation {
|
|
||||||
String desc
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final Gson GSON = new Gson()
|
|
||||||
static Map<String, InheritanceData> parse(File file) {
|
|
||||||
try (final reader = file.newReader()) {
|
|
||||||
return GSON.fromJson(reader, new TypeToken<Map<String, InheritanceData>>() {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
interface Annotatable {
|
|
||||||
List<InheritanceData.Annotation> getAnnotations()
|
|
||||||
}
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import org.gradle.api.file.DuplicatesStrategy
|
|
||||||
import org.gradle.api.tasks.bundling.AbstractArchiveTask
|
|
||||||
import org.gradle.api.tasks.bundling.Zip
|
|
||||||
import org.gradle.api.tasks.*
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import groovy.json.JsonSlurper
|
|
||||||
|
|
||||||
abstract class InstallerJar extends Zip {
|
|
||||||
@Input @Optional abstract Property<Boolean> getFat()
|
|
||||||
@Input @Optional abstract Property<Boolean> getOffline()
|
|
||||||
|
|
||||||
InstallerJar() {
|
|
||||||
archiveClassifier.set('installer')
|
|
||||||
archiveExtension.set('jar') // Needs to be Zip task to not override Manifest, so set extension
|
|
||||||
destinationDirectory.set(project.layout.buildDirectory.dir('libs'))
|
|
||||||
fat.convention(false)
|
|
||||||
offline.convention(false)
|
|
||||||
|
|
||||||
def installerJson = project.tasks.installerJson
|
|
||||||
def launcherJson = project.tasks.launcherJson
|
|
||||||
def downloadInstaller = project.tasks.downloadInstaller
|
|
||||||
|
|
||||||
dependsOn(installerJson, launcherJson, downloadInstaller, project.configurations.installer)
|
|
||||||
from(installerJson, launcherJson)
|
|
||||||
|
|
||||||
from(project.rootProject.file('/src/main/resources/url.png'))
|
|
||||||
project.afterEvaluate {
|
|
||||||
from(project.zipTree(downloadInstaller.output)) {
|
|
||||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fat.get() || offline.get()) {
|
|
||||||
def cfg = project.tasks.register(name + "Config", Configure)
|
|
||||||
cfg.get().configure {
|
|
||||||
parent = this
|
|
||||||
dependsOn(project.tasks.installerJson, project.tasks.launcherJson)
|
|
||||||
}
|
|
||||||
dependsOn(cfg)
|
|
||||||
} else {
|
|
||||||
// Things we ALWAYS bundle, this just the server shim jar, because the installer spec only says to extract the file.
|
|
||||||
// I should make it allow downloads but thats a spec break, and this is just a ~14KB jar
|
|
||||||
[
|
|
||||||
project.tasks.serverShimJar // Server bootstrap executable jar
|
|
||||||
].forEach { AbstractArchiveTask packed ->
|
|
||||||
def path = Util.getMavenInfoFromTask(packed).path
|
|
||||||
from(packed) {
|
|
||||||
rename { "maven/$path" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static abstract class Configure extends DefaultTask {
|
|
||||||
public Zip parent
|
|
||||||
private int count = 0;
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
def deps = [:] as java.util.TreeMap
|
|
||||||
|
|
||||||
// Gather all things that need downloading
|
|
||||||
[
|
|
||||||
project.tasks.installerJson,
|
|
||||||
project.tasks.launcherJson
|
|
||||||
].each { task ->
|
|
||||||
def json = task.output.get().asFile.json
|
|
||||||
json.libraries.each { lib ->
|
|
||||||
if (lib.downloads?.artifact?.url !== null && !lib.downloads.artifact.url.isEmpty())
|
|
||||||
deps.put(lib.name, lib.downloads.artifact)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// First find things we build in this project.
|
|
||||||
[
|
|
||||||
project.tasks.universalJar, // Forge runtime code
|
|
||||||
project.tasks.serverShimJar // Shim jar for dedicated server
|
|
||||||
].forEach { AbstractArchiveTask packed ->
|
|
||||||
def name = Util.getMavenInfoFromTask(packed).name
|
|
||||||
def info = deps.remove(name)
|
|
||||||
if (info !== null) {
|
|
||||||
println("Adding: $packed.path $name")
|
|
||||||
parent.from(packed) {
|
|
||||||
rename { "maven/$info.path" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find any artifacts from the 'installer' config
|
|
||||||
// This config specifies the runtime files we intend for the interaller to have.
|
|
||||||
// And are typically what we would be developing and testing alongside Forge.
|
|
||||||
// So we may have local modified versions
|
|
||||||
def cfg = project.configurations.installer
|
|
||||||
while (cfg != null) {
|
|
||||||
//println('')
|
|
||||||
def resolved = cfg.resolvedConfiguration.resolvedArtifacts
|
|
||||||
int found = 0
|
|
||||||
for (def dep : resolved) {
|
|
||||||
def name = Util.getMavenInfoFromDep(dep).name
|
|
||||||
def info = deps.remove(name)
|
|
||||||
if (info == null) {
|
|
||||||
//println("Skipping: $name")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
//println("-$name")
|
|
||||||
found++
|
|
||||||
addFile(dep.file, info)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deps.isEmpty()) {
|
|
||||||
cfg = null
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prevent infinite loops if something fucky happens
|
|
||||||
if (found == 0)
|
|
||||||
throw new IllegalStateException("Failed to find any installer dependencies")
|
|
||||||
|
|
||||||
def seen = [] as Set
|
|
||||||
cfg = project.configurations.detachedConfiguration()
|
|
||||||
cfg.transitive = false
|
|
||||||
for (def key : deps.keySet()) {
|
|
||||||
def (group, artifact, other) = key.split(':', 3)
|
|
||||||
// Only resolve unique group:artifact so we don't get version overrides
|
|
||||||
if (seen.add(group + ':' + artifact)) {
|
|
||||||
//println("+$key")
|
|
||||||
cfg.dependencies.add(project.dependencies.create(key))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void addFile(file, info) {
|
|
||||||
boolean pack = parent.offline.get() || info.url.isEmpty()
|
|
||||||
|
|
||||||
// If it's a offline jar just always pack
|
|
||||||
if (!pack) {
|
|
||||||
try {
|
|
||||||
var remote = new URL("${info.url}.sha1").getText('UTF-8')
|
|
||||||
pack = info.sha1 != remote
|
|
||||||
} catch (FileNotFoundException e) {
|
|
||||||
pack = !info.url.startsWith('https://libraries.minecraft.net/')
|
|
||||||
// Oh noes its not there!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pack) {
|
|
||||||
println("Adding: $file.absolutePath")
|
|
||||||
parent.from(file) {
|
|
||||||
rename { "maven/$info.path" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.json.JsonBuilder
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import org.gradle.api.provider.SetProperty
|
|
||||||
import org.gradle.api.tasks.*
|
|
||||||
import org.gradle.api.tasks.bundling.AbstractArchiveTask
|
|
||||||
|
|
||||||
import java.nio.file.Files
|
|
||||||
|
|
||||||
abstract class InstallerJson extends DefaultTask {
|
|
||||||
@OutputFile abstract RegularFileProperty getOutput()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getInput()
|
|
||||||
@Input @Optional final Map<String, Object> libraries = new LinkedHashMap<>()
|
|
||||||
@Input Map<String, Object> json = new LinkedHashMap<>()
|
|
||||||
@InputFile abstract RegularFileProperty getIcon()
|
|
||||||
@Input abstract Property<String> getLauncherJsonName()
|
|
||||||
@Input abstract Property<String> getLogo()
|
|
||||||
@Input abstract Property<String> getMirrors()
|
|
||||||
@Input abstract Property<String> getWelcome()
|
|
||||||
|
|
||||||
InstallerJson() {
|
|
||||||
launcherJsonName.convention('/version.json')
|
|
||||||
logo.convention('/big_logo.png')
|
|
||||||
mirrors.convention('https://files.minecraftforge.net/mirrors-2.0.json')
|
|
||||||
welcome.convention("Welcome to the ${project.name.capitalize()} installer.")
|
|
||||||
output.convention(project.layout.buildDirectory.file('libs/install_profile.json'))
|
|
||||||
|
|
||||||
project.afterEvaluate {
|
|
||||||
[
|
|
||||||
project.tasks.universalJar,
|
|
||||||
project.tasks.serverShimJar
|
|
||||||
].forEach { packed ->
|
|
||||||
dependsOn(packed)
|
|
||||||
input.from packed.archiveFile
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
def libs = libraries
|
|
||||||
[
|
|
||||||
project.tasks.universalJar,
|
|
||||||
project.tasks.serverShimJar
|
|
||||||
].forEach { AbstractArchiveTask packed ->
|
|
||||||
def info = Util.getMavenInfoFromTask(packed)
|
|
||||||
libs.put(info.name, [
|
|
||||||
name: info.name,
|
|
||||||
downloads: [
|
|
||||||
artifact: [
|
|
||||||
path: info.path,
|
|
||||||
url: "https://maven.minecraftforge.net/$info.path",
|
|
||||||
sha1: packed.archiveFile.get().asFile.sha1(),
|
|
||||||
size: packed.archiveFile.get().asFile.length()
|
|
||||||
]
|
|
||||||
]
|
|
||||||
])
|
|
||||||
}
|
|
||||||
json.libraries = libs.values().sort{a,b -> a.name.compareTo(b.name)}
|
|
||||||
json.icon = "data:image/png;base64," + new String(Base64.getEncoder().encode(Files.readAllBytes(icon.get().asFile.toPath())))
|
|
||||||
json.json = launcherJsonName.get()
|
|
||||||
json.logo = logo.get()
|
|
||||||
if (!mirrors.get().isEmpty())
|
|
||||||
json.mirrorList = mirrors.get()
|
|
||||||
json.welcome = welcome.get()
|
|
||||||
|
|
||||||
Files.writeString(output.get().getAsFile().toPath(), new JsonBuilder(json).toPrettyString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,415 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.tasks;
|
|
||||||
|
|
||||||
import com.google.common.reflect.TypeToken;
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
import com.google.gson.GsonBuilder;
|
|
||||||
import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier;
|
|
||||||
import net.minecraftforge.jarjar.metadata.ContainedJarMetadata;
|
|
||||||
import net.minecraftforge.jarjar.metadata.ContainedVersion;
|
|
||||||
import net.minecraftforge.jarjar.metadata.Metadata;
|
|
||||||
import net.minecraftforge.jarjar.metadata.MetadataIOHandler;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.ArtifactVersionSerializer;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.ContainedJarIdentifierSerializer;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.ContainedJarMetadataSerializer;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.ContainedVersionSerializer;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.MetadataSerializer;
|
|
||||||
import net.minecraftforge.jarjar.metadata.json.VersionRangeSerializer;
|
|
||||||
import org.apache.maven.artifact.versioning.ArtifactVersion;
|
|
||||||
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
|
|
||||||
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
|
|
||||||
import org.apache.maven.artifact.versioning.VersionRange;
|
|
||||||
import org.codehaus.groovy.runtime.InvokerHelper;
|
|
||||||
import org.gradle.api.Action;
|
|
||||||
import org.gradle.api.DefaultTask;
|
|
||||||
import org.gradle.api.artifacts.ConfigurationContainer;
|
|
||||||
import org.gradle.api.artifacts.Dependency;
|
|
||||||
import org.gradle.api.artifacts.ExternalModuleDependency;
|
|
||||||
import org.gradle.api.artifacts.FileCollectionDependency;
|
|
||||||
import org.gradle.api.artifacts.MinimalExternalModuleDependency;
|
|
||||||
import org.gradle.api.artifacts.ModuleDependency;
|
|
||||||
import org.gradle.api.artifacts.ModuleIdentifier;
|
|
||||||
import org.gradle.api.artifacts.ModuleVersionIdentifier;
|
|
||||||
import org.gradle.api.artifacts.ResolvedArtifact;
|
|
||||||
import org.gradle.api.file.ProjectLayout;
|
|
||||||
import org.gradle.api.file.RegularFileProperty;
|
|
||||||
import org.gradle.api.provider.Provider;
|
|
||||||
import org.gradle.api.provider.SetProperty;
|
|
||||||
import org.gradle.api.tasks.Input;
|
|
||||||
import org.gradle.api.tasks.OutputFile;
|
|
||||||
import org.gradle.api.tasks.TaskAction;
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.Serial;
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.zip.ZipFile;
|
|
||||||
|
|
||||||
// TODO SUPER SUPER SUPER UGLY, CLEAN UP IN FORGEDEV 7
|
|
||||||
@Deprecated(forRemoval = true) // Will be moved to JarJar plugin in ForgeDev 7
|
|
||||||
public abstract class JarJarMetadataOptions extends DefaultTask {
|
|
||||||
private static final Gson GSON = new GsonBuilder()
|
|
||||||
.registerTypeAdapter(VersionRange.class, new VersionRangeSerializer())
|
|
||||||
.registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionSerializer())
|
|
||||||
.registerTypeAdapter(DefaultArtifactVersion.class, new ArtifactVersionSerializer())
|
|
||||||
.registerTypeAdapter(ContainedJarIdentifier.class, new ContainedJarIdentifierSerializer())
|
|
||||||
.registerTypeAdapter(ContainedJarMetadata.class, new ContainedJarMetadataSerializer())
|
|
||||||
.registerTypeAdapter(ContainedVersion.class, new ContainedVersionSerializer())
|
|
||||||
.registerTypeAdapter(Metadata.class, new MetadataSerializer())
|
|
||||||
.setPrettyPrinting()
|
|
||||||
.create();
|
|
||||||
|
|
||||||
protected abstract @Input SetProperty<ResolvedDependencyInfoImpl> getResolvedDependencies();
|
|
||||||
|
|
||||||
protected abstract @OutputFile RegularFileProperty getMetadataFile();
|
|
||||||
|
|
||||||
protected abstract @Inject ProjectLayout getLayout();
|
|
||||||
|
|
||||||
// NOTE: I'm not adding a non-provider version. please just use the version catalog entries for now.
|
|
||||||
public void add(Provider<MinimalExternalModuleDependency> dependency, Action<? super ResolvedDependencyInfo> action) {
|
|
||||||
this.getResolvedDependencies().add(dependency.map(d -> {
|
|
||||||
var ret = ResolvedDependencyInfoImpl.from(this.getProject().getConfigurations(), d);
|
|
||||||
action.execute(ret);
|
|
||||||
return ret;
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
public JarJarMetadataOptions() {
|
|
||||||
this.getMetadataFile().convention(this.getLayout().getBuildDirectory().file(this.getName() + "/options.json"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
record ForgeLocaterOptions(String resource, String layer, String id, List<ContainedJarMetadata> deps, ContainedJarMetadata meta, boolean nested) { }
|
|
||||||
|
|
||||||
var resolved = this.getResolvedDependencies().get();
|
|
||||||
var jars = new ArrayList<ForgeLocaterOptions>(resolved.size());
|
|
||||||
for (var dependency : resolved) {
|
|
||||||
var deps = new ArrayList<ContainedJarMetadata>();
|
|
||||||
try (var zip = new ZipFile(dependency.artifact)) {
|
|
||||||
var entry = zip.getEntry("META-INF/jarjar/metadata.json");
|
|
||||||
if (entry != null) {
|
|
||||||
try (var stream = zip.getInputStream(entry)) {
|
|
||||||
var meta = MetadataIOHandler.fromStream(stream).orElse(null);
|
|
||||||
if (meta == null)
|
|
||||||
throw new IllegalStateException("Corrupt metadata.json in " + dependency.artifact.getAbsolutePath());
|
|
||||||
for (var dep : meta.jars())
|
|
||||||
deps.add(new ContainedJarMetadata(dep.identifier(), dep.version(), "", dep.isObfuscated()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
jars.add(new ForgeLocaterOptions(
|
|
||||||
dependency.resource,
|
|
||||||
dependency.layer,
|
|
||||||
dependency.identifier,
|
|
||||||
deps,
|
|
||||||
new ContainedJarMetadata(
|
|
||||||
new ContainedJarIdentifier(validateGroup(dependency), dependency.module.getName()),
|
|
||||||
new ContainedVersion(null, parseVersion(dependency)),
|
|
||||||
Objects.requireNonNull(dependency.path, "Dependency path is unspecified: " + dependency.asString),
|
|
||||||
false
|
|
||||||
),
|
|
||||||
dependency.nested
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
record Meta(List<ForgeLocaterOptions> options){}
|
|
||||||
|
|
||||||
Files.writeString(
|
|
||||||
this.getMetadataFile().getAsFile().get().toPath(),
|
|
||||||
GSON.toJson(new Meta(jars), Meta.class)
|
|
||||||
);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String validateGroup(ResolvedDependencyInfoImpl dependency) {
|
|
||||||
try {
|
|
||||||
return Objects.requireNonNull(dependency.module.getGroup());
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
throw new IllegalArgumentException("Module dependency has no group: " + dependency.asString, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private ArtifactVersion parseVersion(ResolvedDependencyInfoImpl resolved) {
|
|
||||||
try {
|
|
||||||
return VersionRange.createFromVersionSpec(Objects.requireNonNull(resolved.version)).getRecommendedVersion();
|
|
||||||
} catch (InvalidVersionSpecificationException e) {
|
|
||||||
throw new IllegalArgumentException("Version is invalid for: " + resolved.asString, e);
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
throw new IllegalArgumentException("Version is unspecified for: " + resolved.asString, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private VersionRange parseVersionRange(ResolvedDependencyInfoImpl dependency) {
|
|
||||||
if (dependency.hasManuallySpecifiedRange) {
|
|
||||||
try {
|
|
||||||
return VersionRange.createFromVersionSpec(dependency.versionRange);
|
|
||||||
} catch (InvalidVersionSpecificationException e) {
|
|
||||||
throw new IllegalArgumentException("Version is invalid for: " + dependency.asString, e);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
return VersionRange.createFromVersionSpec("[%s,)".formatted(Objects.requireNonNull(dependency.versionRange)));
|
|
||||||
} catch (InvalidVersionSpecificationException e) {
|
|
||||||
throw new IllegalArgumentException("Version range is invalid for: " + dependency.asString, e);
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
throw new IllegalArgumentException("Version is unspecified for: " + dependency.asString, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface ResolvedDependencyInfo {
|
|
||||||
void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action);
|
|
||||||
|
|
||||||
void setResource(String resource);
|
|
||||||
|
|
||||||
void setLayer(String layer);
|
|
||||||
|
|
||||||
void setId(String identifier);
|
|
||||||
|
|
||||||
void setNested(boolean nested);
|
|
||||||
|
|
||||||
interface ContainedJarMetadataInfo {
|
|
||||||
void setGroup(String group);
|
|
||||||
|
|
||||||
void setName(String name);
|
|
||||||
|
|
||||||
void setPath(String version);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class ResolvedDependencyInfoImpl implements ResolvedDependencyInfo, ResolvedDependencyInfo.ContainedJarMetadataInfo, Serializable {
|
|
||||||
private static final @Serial long serialVersionUID = -7577318115877822993L;
|
|
||||||
|
|
||||||
final MinimalModuleVersionIdentifier module;
|
|
||||||
final String version;
|
|
||||||
String versionRange;
|
|
||||||
boolean hasManuallySpecifiedRange;
|
|
||||||
boolean nested;
|
|
||||||
final File artifact;
|
|
||||||
String path;
|
|
||||||
String resource;
|
|
||||||
String layer;
|
|
||||||
String identifier;
|
|
||||||
final String asString;
|
|
||||||
|
|
||||||
public ResolvedDependencyInfoImpl(MinimalModuleVersionIdentifier module, String version, File artifact, String asString) {
|
|
||||||
this.module = module;
|
|
||||||
this.version = version;
|
|
||||||
this.artifact = artifact;
|
|
||||||
this.asString = asString;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action) {
|
|
||||||
action.execute(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGroup(String group) {
|
|
||||||
this.module.group = group;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setName(String name) {
|
|
||||||
this.module.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setPath(String path) {
|
|
||||||
this.path = path;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setResource(String resource) {
|
|
||||||
this.resource = resource;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setLayer(String layer) {
|
|
||||||
this.layer = layer;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setId(String identifier) {
|
|
||||||
this.identifier = identifier;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setNested(boolean nested) {
|
|
||||||
this.nested = nested;
|
|
||||||
}
|
|
||||||
|
|
||||||
static Set<File> getFiles(Set<ResolvedDependencyInfoImpl> resolvedDependencies) {
|
|
||||||
var ret = new HashSet<File>(resolvedDependencies.size());
|
|
||||||
for (var dependency : resolvedDependencies) {
|
|
||||||
ret.add(dependency.artifact);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
static ResolvedDependencyInfoImpl from(ConfigurationContainer configurations, Dependency dependency) {
|
|
||||||
var group = dependency.getGroup();
|
|
||||||
var name = dependency.getName();
|
|
||||||
var version = dependency.getVersion();
|
|
||||||
|
|
||||||
if (dependency instanceof FileCollectionDependency filesDependency) {
|
|
||||||
File artifact;
|
|
||||||
try {
|
|
||||||
artifact = filesDependency.getFiles().getSingleFile();
|
|
||||||
} catch (IllegalStateException e) {
|
|
||||||
// TODO fileCollectionDependencyIsNotSingleFile
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ResolvedDependencyInfoImpl(
|
|
||||||
new MinimalModuleVersionIdentifier(group, name, version),
|
|
||||||
version,
|
|
||||||
artifact,
|
|
||||||
filesDependency.toString()
|
|
||||||
);
|
|
||||||
} else if (dependency instanceof ModuleDependency moduleDependency) {
|
|
||||||
moduleDependency = moduleDependency.copy();
|
|
||||||
if (moduleDependency instanceof ExternalModuleDependency externalModuleDependency) {
|
|
||||||
externalModuleDependency.version(v -> v.strictly(version.toString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
var detachedConfiguration = configurations.detachedConfiguration(moduleDependency);
|
|
||||||
detachedConfiguration.setTransitive(false);
|
|
||||||
|
|
||||||
ResolvedDependencyInfoImpl ret = null;
|
|
||||||
for (var artifact : detachedConfiguration.getResolvedConfiguration().getFirstLevelModuleDependencies().iterator().next().getModuleArtifacts()) {
|
|
||||||
var fileName = getFileName(artifact);
|
|
||||||
if (!fileName.endsWith(".jar"))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (ret != null)
|
|
||||||
throw new IllegalArgumentException("Module dependency has too many Jar artifacts: " + moduleDependency);
|
|
||||||
|
|
||||||
ret = new ResolvedDependencyInfoImpl(
|
|
||||||
new MinimalModuleVersionIdentifier(group, name, artifact.getModuleVersion().getId().getVersion()),
|
|
||||||
version,
|
|
||||||
artifact.getFile(),
|
|
||||||
moduleDependency.toString()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (ret == null)
|
|
||||||
throw new IllegalArgumentException("Module dependency has no Jar artifacts: " + moduleDependency);
|
|
||||||
|
|
||||||
return ret;
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException("Unsupported dependency type: " + dependency.getClass().getName() + " -- " + dependency);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String getFileName(ResolvedArtifact artifact) {
|
|
||||||
try {
|
|
||||||
return InvokerHelper.getProperty(artifact.getId(), "fileName").toString();
|
|
||||||
} catch (Throwable e) {
|
|
||||||
// NOTE: Why not just use this to begin with?
|
|
||||||
// ComponentArtifactIdentifier can have a getFileName() method, which doesn't necessarily resolve the file itself.
|
|
||||||
// This allows us to get the name of the file to be used without asking Gradle to download the file.
|
|
||||||
// So, if a file is not a JAR file, we can check the name without actually downloading it.
|
|
||||||
return artifact.getFile().getName();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (obj == this) return true;
|
|
||||||
if (obj == null || obj.getClass() != this.getClass()) return false;
|
|
||||||
var that = (ResolvedDependencyInfoImpl) obj;
|
|
||||||
return Objects.equals(this.module, that.module) &&
|
|
||||||
Objects.equals(this.version, that.version) &&
|
|
||||||
Objects.equals(this.versionRange, that.versionRange) &&
|
|
||||||
Objects.equals(this.artifact, that.artifact);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(module, version, versionRange, artifact);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return "ResolvedDependencyInfo[" +
|
|
||||||
"module=" + module + ", " +
|
|
||||||
"fixedVersion=" + version + ", " +
|
|
||||||
"versionRange=" + versionRange + ", " +
|
|
||||||
"artifact=" + artifact + ']';
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class MinimalModuleVersionIdentifier implements ModuleIdentifier, ModuleVersionIdentifier {
|
|
||||||
private static final @Serial long serialVersionUID = -955346236759069739L;
|
|
||||||
|
|
||||||
private String group;
|
|
||||||
private String name;
|
|
||||||
private final String version;
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
public MinimalModuleVersionIdentifier(String group, String name, String version) {
|
|
||||||
this.group = group;
|
|
||||||
this.name = name;
|
|
||||||
this.version = version;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ModuleIdentifier getModule() {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGroup() {
|
|
||||||
return this.group;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return this.name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getVersion() {
|
|
||||||
return this.version;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
return this == obj || obj instanceof MinimalModuleVersionIdentifier o
|
|
||||||
&& Objects.equals(this.group, o.group)
|
|
||||||
&& Objects.equals(this.name, o.name)
|
|
||||||
&& Objects.equals(this.version, o.version);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(group, name, version);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return "MinimalModuleVersionIdentifier[" +
|
|
||||||
"group=" + group + ", " +
|
|
||||||
"name=" + name + ", " +
|
|
||||||
"version=" + version + ']';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.json.JsonBuilder
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.provider.SetProperty
|
|
||||||
import org.gradle.api.tasks.*
|
|
||||||
import org.gradle.api.tasks.bundling.AbstractArchiveTask
|
|
||||||
|
|
||||||
import java.nio.file.Files
|
|
||||||
|
|
||||||
import static net.minecraftforge.forge.tasks.Util.getArtifacts
|
|
||||||
import static net.minecraftforge.forge.tasks.Util.iso8601Now
|
|
||||||
|
|
||||||
abstract class LauncherJson extends DefaultTask {
|
|
||||||
@OutputFile abstract RegularFileProperty getOutput()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getInput()
|
|
||||||
@Input Map<String, Object> json = new LinkedHashMap<>()
|
|
||||||
|
|
||||||
LauncherJson() {
|
|
||||||
output.convention(project.layout.buildDirectory.file('libs/version.json'))
|
|
||||||
|
|
||||||
dependsOn(project.tasks.universalJar)
|
|
||||||
input.from(project.tasks.universalJar.archiveFile)
|
|
||||||
input.from(project.configurations.installer)
|
|
||||||
input.from(project.configurations.installerextra)
|
|
||||||
configure {
|
|
||||||
def mc = project.rootProject.ext.MC_VERSION
|
|
||||||
def forge = project.rootProject.ext.FORGE_VERSION
|
|
||||||
def timestamp = iso8601Now()
|
|
||||||
json.putAll([
|
|
||||||
_comment: [
|
|
||||||
"Please do not automate the download and installation of Forge.",
|
|
||||||
"Our efforts are supported by ads from the download page.",
|
|
||||||
"If you MUST automate this, please consider supporting the project through https://www.patreon.com/LexManos/"
|
|
||||||
],
|
|
||||||
id: "$mc-$project.name-$forge",
|
|
||||||
time: timestamp,
|
|
||||||
releaseTime: timestamp,
|
|
||||||
inheritsFrom: mc,
|
|
||||||
type: 'release',
|
|
||||||
logging: [:],
|
|
||||||
mainClass: '',
|
|
||||||
libraries: []
|
|
||||||
] as LinkedHashMap)
|
|
||||||
|
|
||||||
[
|
|
||||||
project.tasks.universalJar
|
|
||||||
].forEach { packed ->
|
|
||||||
dependsOn(packed)
|
|
||||||
input.from packed.archiveFile
|
|
||||||
}
|
|
||||||
|
|
||||||
def patched = project.tasks.applyClientBinPatches
|
|
||||||
dependsOn(patched)
|
|
||||||
input.from patched.output
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
var packed = (AbstractArchiveTask) project.tasks.universalJar
|
|
||||||
def info = Util.getMavenInfoFromTask(packed)
|
|
||||||
json.libraries.add([
|
|
||||||
name: info.name,
|
|
||||||
downloads: [
|
|
||||||
artifact: [
|
|
||||||
path: info.path,
|
|
||||||
url: "https://maven.minecraftforge.net/$info.path",
|
|
||||||
sha1: packed.archiveFile.get().asFile.sha1(),
|
|
||||||
size: packed.archiveFile.get().asFile.length()
|
|
||||||
]
|
|
||||||
]
|
|
||||||
])
|
|
||||||
|
|
||||||
var classifier = 'client'
|
|
||||||
var genned = project.tasks.applyClientBinPatches
|
|
||||||
info = Util.getMavenInfoFromTask(genned, classifier)
|
|
||||||
json.libraries.add([
|
|
||||||
name: info.name,
|
|
||||||
downloads: [
|
|
||||||
artifact: [
|
|
||||||
path: info.path,
|
|
||||||
url: "",
|
|
||||||
sha1: genned.output.get().asFile.sha1(),
|
|
||||||
size: genned.output.get().asFile.length()
|
|
||||||
]
|
|
||||||
]
|
|
||||||
])
|
|
||||||
|
|
||||||
json.libraries.addAll(getArtifacts(project.configurations.installerextra).values())
|
|
||||||
json.libraries.addAll(getArtifacts(project.configurations.installer).values())
|
|
||||||
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.apache.commons.io.IOUtils
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFiles
|
|
||||||
import org.gradle.api.tasks.OutputFile
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
|
|
||||||
import java.util.zip.ZipEntry
|
|
||||||
import java.util.zip.ZipInputStream
|
|
||||||
import java.util.zip.ZipOutputStream
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class MergeJars extends DefaultTask {
|
|
||||||
MergeJars() {
|
|
||||||
output.convention(project.layout.buildDirectory.dir(name).map { it.file('output.jar') })
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
void run() {
|
|
||||||
def jars = inputJars.files
|
|
||||||
|
|
||||||
try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(output.get().asFile))) {
|
|
||||||
for (def jar : jars) {
|
|
||||||
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(jar))) {
|
|
||||||
ZipEntry entry
|
|
||||||
while ((entry = zin.getNextEntry()) !== null) {
|
|
||||||
ZipEntry _new = new ZipEntry(entry.getName())
|
|
||||||
_new.setTime(0) //SHOULD be the same time as the main entry, but NOOOO _new.setTime(entry.getTime()) throws DateTimeException, so you get 0, screw you!
|
|
||||||
zout.putNextEntry(_new)
|
|
||||||
IOUtils.copy(zin, zout)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@InputFiles
|
|
||||||
abstract ConfigurableFileCollection getInputJars()
|
|
||||||
|
|
||||||
@OutputFile
|
|
||||||
abstract RegularFileProperty getOutput()
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.EqualsAndHashCode
|
|
||||||
|
|
||||||
import org.gradle.api.tasks.Input
|
|
||||||
import org.gradle.api.tasks.Nested
|
|
||||||
import org.gradle.api.tasks.Optional
|
|
||||||
|
|
||||||
@EqualsAndHashCode
|
|
||||||
public class ObjectTarget implements Comparable<ObjectTarget> {
|
|
||||||
@Input
|
|
||||||
String owner
|
|
||||||
|
|
||||||
@Input
|
|
||||||
String name
|
|
||||||
|
|
||||||
@Input
|
|
||||||
@Optional
|
|
||||||
String desc
|
|
||||||
|
|
||||||
@Override
|
|
||||||
String toString() {
|
|
||||||
if (desc == null)
|
|
||||||
return owner + '.' + name
|
|
||||||
return owner + '.' + name + desc
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
int compareTo(ObjectTarget o) {
|
|
||||||
return toString() <=> o.toString()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-47
@@ -1,47 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.artifacts.Dependency
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import org.gradle.api.tasks.Input
|
|
||||||
import org.gradle.api.tasks.Optional
|
|
||||||
import org.gradle.api.tasks.OutputFile
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.StandardCopyOption
|
|
||||||
|
|
||||||
abstract class SetupCheckJarCompatibility extends DefaultTask {
|
|
||||||
SetupCheckJarCompatibility() {
|
|
||||||
group = 'jar compatibility'
|
|
||||||
onlyIf {
|
|
||||||
inputVersion.getOrNull() !== null
|
|
||||||
}
|
|
||||||
outputs.upToDateWhen { false } // Never up to date, because this setup task should always run
|
|
||||||
|
|
||||||
baseBinPatchesOutput.convention(project.layout.buildDirectory.dir(name).map { it.file('joined.lzma') })
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
void run() {
|
|
||||||
def inputVersion = inputVersion.get()
|
|
||||||
|
|
||||||
def baseForgeUserdev = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-userdev.jar") }.get().asFile
|
|
||||||
project.rootProject.extensions.download.run {
|
|
||||||
src "https://maven.minecraftforge.net/net/minecraftforge/forge/${inputVersion}/forge-${inputVersion}-userdev.jar"
|
|
||||||
dest baseForgeUserdev
|
|
||||||
}
|
|
||||||
|
|
||||||
def joinedLzma = project.zipTree(baseForgeUserdev).matching { it.include('joined.lzma') }.singleFile
|
|
||||||
|
|
||||||
Files.copy(joinedLzma.toPath(), baseBinPatchesOutput.get().asFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Input
|
|
||||||
@Optional
|
|
||||||
abstract Property<String> getInputVersion()
|
|
||||||
|
|
||||||
@OutputFile
|
|
||||||
abstract RegularFileProperty getBaseBinPatchesOutput()
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import com.google.gson.reflect.TypeToken
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.eclipse.jgit.api.Git
|
|
||||||
|
|
||||||
import javax.annotation.Nullable
|
|
||||||
import java.util.stream.Collectors
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
class TeamcityRequests {
|
|
||||||
public static final Gson GSON = new Gson()
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
static <T> T jsonRequest(TypeToken<T> clazz, String url) throws Exception {
|
|
||||||
final HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection()
|
|
||||||
conn.setRequestProperty('Accept', 'application/json')
|
|
||||||
conn.setReadTimeout(5 * 1000)
|
|
||||||
conn.setConnectTimeout(5 * 1000)
|
|
||||||
conn.connect()
|
|
||||||
|
|
||||||
if (conn.responseCode !== 200) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
try (final InputStream is = conn.getInputStream()) {
|
|
||||||
GSON.fromJson(new InputStreamReader(is), clazz.getType())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
static Map<String, Build> buildsByCommit() throws IOException {
|
|
||||||
final Map<String, Build> builds = [:]
|
|
||||||
jsonRequest(new TypeToken<Builds>() {}, 'https://teamcity.minecraftforge.net/guestAuth/app/rest/builds?fields=build:(revisions,number)&locator=buildType:(id:MinecraftForge_MinecraftForge_MinecraftForge_MinecraftForge__Build),defaultFilter:false,count:300,status:SUCCESS')
|
|
||||||
?.build?.forEach {
|
|
||||||
it.revisions.revision.each { rev -> builds[rev.version] = it }
|
|
||||||
}
|
|
||||||
return builds
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
static String attemptFindBase(File gitPath) {
|
|
||||||
try (final git = Git.open(gitPath)) {
|
|
||||||
final Map<String, Build> buildByCommit = buildsByCommit()
|
|
||||||
for (final commit in git.log().setMaxCount(100).call()) {
|
|
||||||
// Find the first commit which was built on CI
|
|
||||||
final build = buildByCommit[commit.id.name]
|
|
||||||
if (build) {
|
|
||||||
return build.number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class Builds {
|
|
||||||
public List<Build> build
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class Build {
|
|
||||||
public String number
|
|
||||||
public Revisions revisions
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class Revisions {
|
|
||||||
public int count
|
|
||||||
public List<Revision> revision
|
|
||||||
}
|
|
||||||
|
|
||||||
static final class Revision {
|
|
||||||
public String version
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.json.JsonBuilder
|
|
||||||
import groovy.json.JsonSlurper
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import groovy.transform.stc.ClosureParams
|
|
||||||
import groovy.transform.stc.SimpleType
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.gradle.api.Task
|
|
||||||
import org.gradle.api.artifacts.Configuration
|
|
||||||
import org.gradle.api.artifacts.ResolvedArtifact
|
|
||||||
import org.gradle.api.tasks.bundling.AbstractArchiveTask
|
|
||||||
import org.objectweb.asm.ClassReader
|
|
||||||
import org.objectweb.asm.Opcodes
|
|
||||||
import org.objectweb.asm.tree.ClassNode
|
|
||||||
|
|
||||||
import java.net.http.HttpClient
|
|
||||||
import java.net.http.HttpRequest
|
|
||||||
import java.net.http.HttpResponse
|
|
||||||
import java.security.MessageDigest
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.Semaphore
|
|
||||||
import java.util.zip.ZipEntry
|
|
||||||
import java.util.zip.ZipInputStream
|
|
||||||
|
|
||||||
final class Util {
|
|
||||||
public static final int ASM_LEVEL = Opcodes.ASM9
|
|
||||||
private static final HttpClient HTTP = HttpClient.newBuilder().build()
|
|
||||||
|
|
||||||
static void init() {
|
|
||||||
File.metaClass.sha1 = { ->
|
|
||||||
MessageDigest md = MessageDigest.getInstance('SHA-1')
|
|
||||||
delegate.eachByte(4096) { byte[] bytes, int size ->
|
|
||||||
md.update(bytes, 0, size)
|
|
||||||
}
|
|
||||||
return md.digest().collect(this.&toHex).join('')
|
|
||||||
}
|
|
||||||
File.metaClass.getSha1 = { !delegate.exists() ? null : delegate.sha1() }
|
|
||||||
File.metaClass.sha256 = { ->
|
|
||||||
MessageDigest md = MessageDigest.getInstance('SHA-256')
|
|
||||||
delegate.eachByte(4096) { byte[] bytes, int size ->
|
|
||||||
md.update(bytes, 0, size)
|
|
||||||
}
|
|
||||||
return md.digest().collect(this.&toHex).join('')
|
|
||||||
}
|
|
||||||
File.metaClass.getSha256 = { !delegate.exists() ? null : delegate.sha256() }
|
|
||||||
|
|
||||||
File.metaClass.json = { -> new JsonSlurper().parseText(delegate.text) }
|
|
||||||
File.metaClass.getJson = { return delegate.exists() ? new JsonSlurper().parse(delegate) : [:] }
|
|
||||||
File.metaClass.setJson = { json -> delegate.text = new JsonBuilder(json).toPrettyString() }
|
|
||||||
|
|
||||||
Date.metaClass.iso8601 = { ->
|
|
||||||
var format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
|
|
||||||
var result = format.format(delegate)
|
|
||||||
return result[0..21] + ':' + result[22..-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
String.metaClass.rsplit = { String del, int limit = -1 ->
|
|
||||||
var lst = new ArrayList<String>()
|
|
||||||
int x = 0
|
|
||||||
int idx
|
|
||||||
String tmp = delegate
|
|
||||||
while ((idx = tmp.lastIndexOf(del)) != -1 && (limit === -1 || x++ < limit)) {
|
|
||||||
lst.add(0, tmp.substring(idx + del.length(), tmp.length()))
|
|
||||||
tmp = tmp.substring(0, idx)
|
|
||||||
}
|
|
||||||
lst.add(0, tmp)
|
|
||||||
return lst
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static String[] getClasspath(Project project, Map libs, String artifact) {
|
|
||||||
def ret = []
|
|
||||||
artifactTree(project, artifact).each { key, lib ->
|
|
||||||
libs[lib.name] = lib
|
|
||||||
if (lib.name != artifact)
|
|
||||||
ret.add(lib.name)
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static Map getArtifacts(Configuration config) {
|
|
||||||
var ret = [:]
|
|
||||||
var semaphore = new Semaphore(1, true)
|
|
||||||
config.resolvedConfiguration.resolvedArtifacts.parallelStream().forEachOrdered(dep -> {
|
|
||||||
var info = getMavenInfoFromDep(dep)
|
|
||||||
var domain = 'libraries.minecraft.net'
|
|
||||||
var url = "https://$domain/$info.path"
|
|
||||||
if (!checkExists(url))
|
|
||||||
url.values[0] = 'maven.minecraftforge.net'
|
|
||||||
|
|
||||||
var sha1 = sha1(dep.file)
|
|
||||||
|
|
||||||
semaphore.acquire()
|
|
||||||
ret[info.key] = [
|
|
||||||
name: info.name,
|
|
||||||
downloads: [
|
|
||||||
artifact: [
|
|
||||||
path: info.path,
|
|
||||||
url: url.toString(),
|
|
||||||
sha1: sha1,
|
|
||||||
size: dep.file.length()
|
|
||||||
]
|
|
||||||
]
|
|
||||||
]
|
|
||||||
semaphore.release()
|
|
||||||
})
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static Map getMavenInfoFromDep(ResolvedArtifact dep) {
|
|
||||||
return getMavenInfoFromMap([
|
|
||||||
group: dep.moduleVersion.id.group,
|
|
||||||
name: dep.moduleVersion.id.name,
|
|
||||||
version: dep.moduleVersion.id.version,
|
|
||||||
classifier: dep.classifier,
|
|
||||||
extension: dep.extension
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static Map getMavenInfoFromTask(AbstractArchiveTask task) {
|
|
||||||
return getMavenInfoFromMap([
|
|
||||||
group: task.project.group.toString(),
|
|
||||||
name: task.project.name,
|
|
||||||
version: task.project.version.toString(),
|
|
||||||
classifier: task.archiveClassifier.get(),
|
|
||||||
extension: task.archiveExtension.get()
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static Map getMavenInfoFromTask(Task task, String classifier) {
|
|
||||||
return getMavenInfoFromMap([
|
|
||||||
group: task.project.group.toString(),
|
|
||||||
name: task.project.name,
|
|
||||||
version: task.project.version.toString(),
|
|
||||||
classifier: classifier,
|
|
||||||
extension: 'jar'
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
private static Map getMavenInfoFromMap(Map<String, String> art) {
|
|
||||||
var key = "$art.group:$art.name"
|
|
||||||
var name = "$art.group:$art.name:$art.version"
|
|
||||||
var path = "${art.group.replace('.', '/')}/$art.name/$art.version/$art.name-$art.version"
|
|
||||||
if (art.classifier !== null) {
|
|
||||||
name += ":$art.classifier"
|
|
||||||
path += "-$art.classifier"
|
|
||||||
}
|
|
||||||
if ('jar' != art.extension) {
|
|
||||||
name += "@$art.extension"
|
|
||||||
path += ".$art.extension"
|
|
||||||
} else {
|
|
||||||
path += ".jar"
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
key: key.toString(),
|
|
||||||
name: name.toString(),
|
|
||||||
path: path.toString(),
|
|
||||||
art: art
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
static String iso8601Now() { new Date().iso8601() }
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static String sha1(File file) {
|
|
||||||
MessageDigest md = MessageDigest.getInstance('SHA-1')
|
|
||||||
file.eachByte(4096) { byte[] bytes, int size ->
|
|
||||||
md.update(bytes, 0, size)
|
|
||||||
}
|
|
||||||
return md.digest().collect(this.&toHex).join('')
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
private static String toHex(byte bite) {
|
|
||||||
return String.format('%02x', bite)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Map artifactTree(Project project, String artifact, boolean transitive = true) {
|
|
||||||
if (!project.ext.has('tree_resolver'))
|
|
||||||
project.ext.tree_resolver = 1
|
|
||||||
def cfg = project.configurations.create('tree_resolver_' + project.ext.tree_resolver++)
|
|
||||||
cfg.transitive = transitive
|
|
||||||
def dep = project.dependencies.create(artifact)
|
|
||||||
cfg.dependencies.add(dep)
|
|
||||||
def files = cfg.resolve()
|
|
||||||
return getArtifacts(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static boolean checkExists(String url) {
|
|
||||||
try {
|
|
||||||
return HTTP.send(HttpRequest.newBuilder(new URI(url))
|
|
||||||
.method('HEAD', HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding()
|
|
||||||
).statusCode() === 200
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (e.toString().contains('unable to find valid certification path to requested target'))
|
|
||||||
throw new RuntimeException("Failed to connect to $url: Missing certificate root authority, try updating Java")
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static String getLatestForgeVersion(String mcVersion) {
|
|
||||||
final json = new JsonSlurper().parseText(new URL('https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json').getText('UTF-8'))
|
|
||||||
final ver = json.promos["$mcVersion-latest"]
|
|
||||||
ver === null ? null : (mcVersion + '-' + ver)
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static void processClassNodes(File file, @ClosureParams(value = SimpleType, options = 'org.objectweb.asm.tree.ClassNode') Closure process) {
|
|
||||||
file.withInputStream { i ->
|
|
||||||
new ZipInputStream(i).withCloseable { zin ->
|
|
||||||
ZipEntry zein
|
|
||||||
while ((zein = zin.nextEntry) !== null) {
|
|
||||||
if (zein.name.endsWith('.class')) {
|
|
||||||
var node = new ClassNode(ASM_LEVEL)
|
|
||||||
new ClassReader(zin).accept(node, 0)
|
|
||||||
process(node)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) Forge Development LLC and contributors
|
|
||||||
* SPDX-License-Identifier: LGPL-2.1-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net.minecraftforge.forge.tasks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import net.minecraftforge.srgutils.MinecraftVersion
|
|
||||||
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.InputFile
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
import org.objectweb.asm.tree.AnnotationNode
|
|
||||||
import org.objectweb.asm.tree.ClassNode
|
|
||||||
|
|
||||||
abstract class ValidateDeprecations extends DefaultTask {
|
|
||||||
@InputFile
|
|
||||||
abstract RegularFileProperty getInput()
|
|
||||||
|
|
||||||
@Input
|
|
||||||
abstract Property<String> getMcVersion()
|
|
||||||
|
|
||||||
ValidateDeprecations() {
|
|
||||||
this.onlyIf { !System.env.TEAMCITY_VERSION }
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
protected void exec() {
|
|
||||||
var mcVer = MinecraftVersion.from(mcVersion.get())
|
|
||||||
List<String> errors = []
|
|
||||||
|
|
||||||
Util.processClassNodes(input.get().asFile) {
|
|
||||||
processNode(mcVer, errors, it)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!errors.isEmpty()) {
|
|
||||||
errors.forEach {
|
|
||||||
this.logger.error("Deprecated ${it[0]} is marked for removal in ${it[1]} but is not yet removed")
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("Found deprecated members marked for removal but not yet removed in ${mcVer}; see log for details")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected processNode(MinecraftVersion mcVer, List<String> errors, ClassNode node) {
|
|
||||||
node.visibleAnnotations?.each { annotation ->
|
|
||||||
ValidateDeprecations.processAnnotations(annotation, mcVer, errors) {
|
|
||||||
"class ${node.name}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
node.fields?.each { field ->
|
|
||||||
field.visibleAnnotations?.each { annotation ->
|
|
||||||
ValidateDeprecations.processAnnotations(annotation, mcVer, errors) {
|
|
||||||
"field ${node.name}#${field.name}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
node.methods?.each { method ->
|
|
||||||
method.visibleAnnotations?.each { annotation ->
|
|
||||||
ValidateDeprecations.processAnnotations(annotation, mcVer, errors) {
|
|
||||||
"method ${node.name}#${method.name}${method.desc}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void processAnnotations(AnnotationNode annotation, MinecraftVersion mcVer, List<String> errors, Closure<String> context) {
|
|
||||||
def values = annotation.values
|
|
||||||
if (values === null)
|
|
||||||
return
|
|
||||||
int forRemoval = values.indexOf('forRemoval')
|
|
||||||
int since = values.indexOf('since')
|
|
||||||
if (annotation.desc == 'Ljava/lang/Deprecated;' && forRemoval !== -1 && since !== -1 && values.size() >= 4 && values[forRemoval + 1] === true) {
|
|
||||||
def oldVersion = MinecraftVersion.from(values[since + 1])
|
|
||||||
int[] split = ValidateDeprecations.splitDots(oldVersion.toString())
|
|
||||||
if (split.length < 2)
|
|
||||||
return
|
|
||||||
def removeVersion = MinecraftVersion.from("${split[0]}.${split[1] + 1}")
|
|
||||||
if (removeVersion <= mcVer)
|
|
||||||
errors.add([context(), removeVersion])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
private static int[] splitDots(String version) {
|
|
||||||
String[] pts = version.split('\\.')
|
|
||||||
int[] values = new int[pts.length]
|
|
||||||
for (int x = 0; x < pts.length; x++)
|
|
||||||
values[x] = Integer.parseInt(pts[x])
|
|
||||||
return values
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,311 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import groovy.transform.TupleConstructor
|
|
||||||
import net.minecraftforge.forge.tasks.InheritanceData
|
|
||||||
import net.minecraftforge.srgutils.IMappingFile
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFile
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFile
|
|
||||||
import org.gradle.api.tasks.InputFiles
|
|
||||||
import org.gradle.api.tasks.Optional
|
|
||||||
import org.objectweb.asm.Opcodes
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class CheckATs extends CheckTask {
|
|
||||||
|
|
||||||
@InputFile abstract RegularFileProperty getInheritance()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getAts()
|
|
||||||
@InputFile @Optional abstract RegularFileProperty getMappings()
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void check(Reporter reporter, boolean fix) {
|
|
||||||
final IMappingFile mappings = mappings.map { RegularFile it -> IMappingFile.load(it.asFile) }.getOrNull()
|
|
||||||
final inheritance = InheritanceData.parse(this.inheritance.get().asFile)
|
|
||||||
|
|
||||||
ats.each {
|
|
||||||
final lines = process(it, reporter, inheritance)
|
|
||||||
if (fix) {
|
|
||||||
it.text = joinBack(lines, inheritance, mappings).join('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static TreeMap<String, ATParser.Entry> process(File file, Reporter reporter, Map<String, InheritanceData> inheritance) {
|
|
||||||
final TreeMap<String, ATParser.Entry> lines = ATParser.parse(file.readLines(), reporter)
|
|
||||||
final Map<String, ATParser.Entry> constructorGroups = [:]
|
|
||||||
|
|
||||||
final itr = lines.entrySet().iterator()
|
|
||||||
final toRemove = []
|
|
||||||
while (itr.hasNext()) {
|
|
||||||
final next = itr.next()
|
|
||||||
String key = next.key
|
|
||||||
final entry = next.value
|
|
||||||
if (entry === null) continue
|
|
||||||
|
|
||||||
final binaryName = entry.cls.replaceAll('\\.', '/')
|
|
||||||
|
|
||||||
// Process Groups, this will remove any entries outside the group that is covered by the group
|
|
||||||
if (entry.group) {
|
|
||||||
final jcls = inheritance[binaryName]
|
|
||||||
if (jcls === null) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid group: $key")
|
|
||||||
} else if ('*' == entry.desc) {
|
|
||||||
if (!jcls.fields) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid group, class has no fields: $key")
|
|
||||||
} else {
|
|
||||||
jcls.fields.each { field, value ->
|
|
||||||
final fkey = entry.cls + ' ' + field
|
|
||||||
if (accessLevel(value.access) < accessStr(entry.modifier)) {
|
|
||||||
if (lines.containsKey(fkey)) {
|
|
||||||
toRemove.add(fkey)
|
|
||||||
} else if (!entry.existing.contains(fkey)) {
|
|
||||||
reporter.report("Missing group entry: $fkey")
|
|
||||||
}
|
|
||||||
entry.children.add(fkey)
|
|
||||||
} else if (lines.containsKey(fkey)) {
|
|
||||||
toRemove.add(fkey)
|
|
||||||
reporter.report("Found invalid group entry: $fkey")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entry.existing.findAll { it !in entry.children }.each { println('Removed: ' + it) }
|
|
||||||
}
|
|
||||||
} else if ('*()' == entry.desc) {
|
|
||||||
if (!jcls.methods) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid group, class has no methods: $key")
|
|
||||||
} else {
|
|
||||||
jcls.methods.each { mtd, value ->
|
|
||||||
if (mtd.startsWith('<clinit>') || mtd.startsWith('lambda$')) return
|
|
||||||
key = entry.cls + ' ' + mtd.replace(' ', '')
|
|
||||||
if (accessLevel(value.access) < accessStr(entry.modifier)) {
|
|
||||||
if (lines.containsKey(key)) {
|
|
||||||
toRemove.add(key)
|
|
||||||
} else if (!entry.existing.contains(key)) {
|
|
||||||
reporter.report("Missing group entry: $key")
|
|
||||||
}
|
|
||||||
entry.children.add(key)
|
|
||||||
} else if (lines.containsKey(key)) {
|
|
||||||
toRemove.add(key)
|
|
||||||
reporter.report("Found invalid group entry: $key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entry.existing.findAll { it !in entry.children }.each { println('Removed: ' + it) }
|
|
||||||
}
|
|
||||||
} else if ('<init>' == entry.desc) { //Make all public non-abstract subclasses
|
|
||||||
constructorGroups.put(binaryName, entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process normal lines, remove invalid and remove narrowing
|
|
||||||
else {
|
|
||||||
def jcls = inheritance.get(binaryName)
|
|
||||||
if (jcls === null) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid: $key")
|
|
||||||
} else if (entry.desc == '') {
|
|
||||||
if (accessLevel(jcls.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid Narrowing: $key")
|
|
||||||
}
|
|
||||||
} else if (!entry.desc.contains('(')) {
|
|
||||||
if (!jcls.fields || !jcls.fields.containsKey(entry.desc)) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid: $key")
|
|
||||||
} else {
|
|
||||||
final value = jcls.fields[entry.desc]
|
|
||||||
if (accessLevel(value.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid Narrowing: $key - ${entry.comment}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
final jdesc = entry.desc.replace('(', ' (')
|
|
||||||
if (!jcls.methods || !jcls.methods.containsKey(jdesc)) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid: $key")
|
|
||||||
} else {
|
|
||||||
final value = jcls.methods[jdesc]
|
|
||||||
if (accessLevel(value.access) > accessStr(entry.modifier) && (entry.comment === null || !entry.comment.startsWith('#force '))) {
|
|
||||||
itr.remove()
|
|
||||||
reporter.report("Invalid Narrowing: $key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inheritance.each { tcls, value ->
|
|
||||||
if (!value.methods || ((value.access & Opcodes.ACC_ABSTRACT) !== 0)) return
|
|
||||||
String parent = tcls
|
|
||||||
while (parent !== null) {
|
|
||||||
constructorGroups[parent]?.tap { entry ->
|
|
||||||
value.methods.each { mtd, v ->
|
|
||||||
if (mtd.startsWith('<init>')) {
|
|
||||||
final child = tcls.replaceAll('/', '\\.') + ' ' + mtd.replace(' ', '')
|
|
||||||
if (accessLevel(v.access) < 3) {
|
|
||||||
if (lines.containsKey(child)) {
|
|
||||||
toRemove.add(child)
|
|
||||||
} else if (child !in entry.existing) {
|
|
||||||
reporter.report("Missing group entry: $child")
|
|
||||||
}
|
|
||||||
entry.children.add(child)
|
|
||||||
} else if (lines.containsKey(child)) {
|
|
||||||
toRemove.add(child)
|
|
||||||
reporter.report("Found invalid group entry: $child")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
parent = inheritance[parent]?.superName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
constructorGroups.values().each { entry -> entry.existing.findAll { it !in entry.children }.each{ reporter.report("Found invalid group entry: $it") } }
|
|
||||||
|
|
||||||
toRemove.each(lines.&remove)
|
|
||||||
|
|
||||||
return lines
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<String> joinBack(TreeMap<String, ATParser.Entry> lines, Map<String, InheritanceData> inheritance, IMappingFile mappings) {
|
|
||||||
final data = [] as List<String>
|
|
||||||
final remapComment = { ATParser.Entry entry ->
|
|
||||||
if (!mappings || !entry || !entry.desc) return null
|
|
||||||
final comment = entry.comment?.substring(1)?.trim()
|
|
||||||
final jsonCls = inheritance.get(entry.cls.replaceAll('\\.', '/'))
|
|
||||||
final mappingsClass = mappings?.getClass(jsonCls.name)
|
|
||||||
if (mappingsClass === null) return entry.comment
|
|
||||||
final idx = entry.desc.indexOf('(')
|
|
||||||
|
|
||||||
String mappedName = idx == -1
|
|
||||||
? mappingsClass.remapField(entry.desc)
|
|
||||||
: mappingsClass.remapMethod(entry.desc.substring(0, idx), entry.desc.substring(idx))
|
|
||||||
if (!mappedName) return entry.comment
|
|
||||||
if (mappedName == '<init>')
|
|
||||||
mappedName = 'constructor'
|
|
||||||
|
|
||||||
if (comment?.startsWith(mappedName))
|
|
||||||
return '# ' + comment
|
|
||||||
if (comment && comment.indexOf(' ') !== -1) {
|
|
||||||
def split = comment.split(' - ').toList()
|
|
||||||
if (split[0].indexOf(' ') !== -1)
|
|
||||||
// The first string is more than one word, so append before it
|
|
||||||
return "# ${mappedName} - ${comment}"
|
|
||||||
split.remove(0)
|
|
||||||
return "# ${mappedName} - ${String.join(' - ', split)}"
|
|
||||||
}
|
|
||||||
return '# ' + mappedName
|
|
||||||
}
|
|
||||||
lines.each { key, value ->
|
|
||||||
if (!value.group) {
|
|
||||||
def comment = remapComment.call(value)
|
|
||||||
data.add(value.modifier + ' ' + key + (comment ? ' ' + comment : ''))
|
|
||||||
} else {
|
|
||||||
data.add(('#group ' + value.modifier + ' ' + key + ' ' + (value.comment ?: '')).trim())
|
|
||||||
value.children.each {
|
|
||||||
final line = value.modifier + ' ' + it
|
|
||||||
final entry = ATParser.parseEntry(line)
|
|
||||||
final comment = remapComment(entry)
|
|
||||||
data.add(line + (comment ? ' ' + comment : ''))
|
|
||||||
}
|
|
||||||
data.add('#endgroup')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
static int accessStr(String access) {
|
|
||||||
if (access.endsWith('-f') || access.endsWith('+f')) return 4
|
|
||||||
switch (access.toLowerCase()) {
|
|
||||||
case 'public': return 3
|
|
||||||
case 'protected': return 2
|
|
||||||
case 'default': return 1
|
|
||||||
case 'private': return 0
|
|
||||||
default: return -1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static int accessLevel(int access) {
|
|
||||||
if ((access & Opcodes.ACC_PUBLIC) !== 0) return 3
|
|
||||||
if ((access & Opcodes.ACC_PROTECTED) !== 0) return 2
|
|
||||||
if ((access & Opcodes.ACC_PRIVATE) !== 0) return 0
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
class ATParser {
|
|
||||||
static TreeMap<String, Entry> parse(List<String> lines, CheckTask.Reporter reporter) {
|
|
||||||
TreeMap<String, Entry> outLines = new TreeMap<>()
|
|
||||||
Entry group = null
|
|
||||||
for (final line : lines) {
|
|
||||||
if (line.isEmpty()) continue
|
|
||||||
if (line.startsWith('#group ')) {
|
|
||||||
final entry = parseEntry(line.substring(7))
|
|
||||||
|
|
||||||
if (entry.desc != '*' && entry.desc != '*()' && entry.desc != '<init>') {
|
|
||||||
reporter.report("Invalid group: $line", false)
|
|
||||||
}
|
|
||||||
|
|
||||||
entry.group = true
|
|
||||||
entry.children = []
|
|
||||||
entry.existing = []
|
|
||||||
|
|
||||||
group = entry
|
|
||||||
|
|
||||||
if (outLines.containsKey(entry.key)) {
|
|
||||||
reporter.report("Duplicate group: $line", false)
|
|
||||||
}
|
|
||||||
|
|
||||||
outLines[entry.key] = group
|
|
||||||
} else if (group !== null) {
|
|
||||||
if (line.startsWith('#endgroup')) {
|
|
||||||
group = null
|
|
||||||
} else {
|
|
||||||
final key = parseEntry(line).key
|
|
||||||
group.existing.add(key)
|
|
||||||
}
|
|
||||||
} else if (line.startsWith('#endgroup')) {
|
|
||||||
reporter.report("Invalid group ending: $line", false)
|
|
||||||
} else if (line.startsWith('#')) {
|
|
||||||
//Nom
|
|
||||||
} else {
|
|
||||||
final entry = parseEntry(line)
|
|
||||||
if (outLines.containsKey(entry.key)) {
|
|
||||||
reporter.report("Found duplicate: $line")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
outLines[entry.key] = entry
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return outLines
|
|
||||||
}
|
|
||||||
|
|
||||||
static Entry parseEntry(String line) {
|
|
||||||
final idx = line.indexOf('#')
|
|
||||||
final String comment = idx === -1 ? null : line.substring(idx)
|
|
||||||
if (idx !== -1) line = line.substring(0, idx - 1)
|
|
||||||
final data = (line.trim() + ' ').split(' ', -1)
|
|
||||||
data[1] = data[1].replaceAll('/', '.') // Convert to Source names, internal names are fine by spec, but not supported by old AST based AT implementations.
|
|
||||||
new Entry(data[0], data[1], data[2], comment)
|
|
||||||
}
|
|
||||||
|
|
||||||
@TupleConstructor
|
|
||||||
static final class Entry {
|
|
||||||
String modifier, cls, desc, comment
|
|
||||||
|
|
||||||
Set<String> existing
|
|
||||||
TreeSet<String> children
|
|
||||||
boolean group = false
|
|
||||||
|
|
||||||
@Lazy
|
|
||||||
String key = {cls + (desc.isEmpty() ? '' : ' ' + desc)}()
|
|
||||||
|
|
||||||
Object getAt(String key) {
|
|
||||||
return getProperty(key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import net.minecraftforge.forge.tasks.Util
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFile
|
|
||||||
import org.gradle.api.tasks.InputFiles
|
|
||||||
import org.objectweb.asm.ClassReader
|
|
||||||
import org.objectweb.asm.ClassVisitor
|
|
||||||
import org.objectweb.asm.MethodVisitor
|
|
||||||
import org.objectweb.asm.Type
|
|
||||||
|
|
||||||
import java.util.zip.ZipEntry
|
|
||||||
import java.util.zip.ZipInputStream
|
|
||||||
|
|
||||||
abstract class CheckExcs extends CheckTask {
|
|
||||||
|
|
||||||
@InputFile abstract RegularFileProperty getBinary()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getExcs()
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void check(Reporter reporter, boolean fix) {
|
|
||||||
final Set<String> known = []
|
|
||||||
collectKnown(known)
|
|
||||||
|
|
||||||
excs.each { f ->
|
|
||||||
final lines = []
|
|
||||||
f.eachLine { line ->
|
|
||||||
int idx = line.indexOf('#')
|
|
||||||
if (idx === 0 || line.isEmpty()) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (idx !== -1) line = line.substring(0, idx - 1)
|
|
||||||
|
|
||||||
if (!line.contains('=')) {
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
def (String key, String value) = line.split('=', 2)
|
|
||||||
if (!known.contains(key)) {
|
|
||||||
reporter.report("Unknown: $line")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
String desc = key.split('\\.', 2)[1]
|
|
||||||
if (!desc.contains('(')) {
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
desc = '(' + desc.split('\\(', 2)[1]
|
|
||||||
|
|
||||||
def (exceptions, String args) = value.contains('|') ? value.split('|', 2) : [value, '']
|
|
||||||
|
|
||||||
if (args.split(',').length !== Type.getArgumentTypes(desc).length) {
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
lines.add(line)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fix) f.text = lines.sort().join('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void collectKnown(Collection<String> known) {
|
|
||||||
binary.get().asFile.withInputStream { i ->
|
|
||||||
new ZipInputStream(i).withCloseable { zin ->
|
|
||||||
final visitor = new ClassVisitor(Util.ASM_LEVEL) {
|
|
||||||
private String cls
|
|
||||||
@Override
|
|
||||||
void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
|
|
||||||
this.cls = name
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
|
|
||||||
known.add(this.cls + '.' + name + descriptor)
|
|
||||||
super.visitMethod(access, name, descriptor, signature, exceptions)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ZipEntry zein
|
|
||||||
while ((zein = zin.nextEntry) !== null) {
|
|
||||||
if (zein.name.endsWith('.class')) {
|
|
||||||
ClassReader reader = new ClassReader(zin)
|
|
||||||
reader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
enum CheckMode {
|
|
||||||
CHECK,
|
|
||||||
FIX
|
|
||||||
|
|
||||||
CheckMode() {}
|
|
||||||
}
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import org.gradle.api.file.DirectoryProperty
|
|
||||||
import org.gradle.api.provider.ListProperty
|
|
||||||
import org.gradle.api.tasks.Input
|
|
||||||
import org.gradle.api.tasks.InputDirectory
|
|
||||||
import org.gradle.api.tasks.Optional
|
|
||||||
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.Path
|
|
||||||
import java.util.regex.Pattern
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class CheckPatches extends CheckTask {
|
|
||||||
|
|
||||||
private static final Pattern HUNK_START_PATTERN = Pattern.compile('^@@ -[0-9,]* \\+[0-9,_]* @@$')
|
|
||||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile('^[+\\-]\\s*$')
|
|
||||||
private static final Pattern IMPORT_PATTERN = Pattern.compile('^[+\\-]\\s*import.*')
|
|
||||||
private static final Pattern FIELD_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final)?([^=;]*)(=.*)?;\\s*$')
|
|
||||||
private static final Pattern METHOD_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final)?([^(]*)[(]([^)]*)?[)]\\s*[{]\\s*$')
|
|
||||||
private static final Pattern CLASS_PATTERN = Pattern.compile('^[+\\-][\\s]*((public|protected|private)[\\s]*)?(static[\\s]*)?(final[\\s]*)?(class|interface)([^{]*)[{]\\s*$')
|
|
||||||
private static final Map<String, Integer> ACCESS_MAP = [private: 0, protected: 2, public: 3].tap { it.put(null, 1) }
|
|
||||||
|
|
||||||
@InputDirectory abstract DirectoryProperty getPatchDir()
|
|
||||||
@Input @Optional abstract ListProperty<String> getPatchesWithS2SArtifact()
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void check(Reporter reporter, boolean fix) {
|
|
||||||
final patchDir = getPatchDir().get().asFile.toPath()
|
|
||||||
Files.walk(patchDir).withCloseable {
|
|
||||||
it.filter(Files.&isRegularFile).forEach { path ->
|
|
||||||
final String relativeName = patchDir.relativize(path).toString()
|
|
||||||
verifyPatch(path, reporter, fix, relativeName, patchesWithS2SArtifact.get().contains(relativeName.replace('\\', '/')))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean accessChange(String previous, String current) {
|
|
||||||
//return ACCESS_MAP[previous] < ACCESS_MAP[current]
|
|
||||||
return previous != current
|
|
||||||
}
|
|
||||||
|
|
||||||
void verifyPatch(Path patch, Reporter reporter, boolean fix, String patchPath, boolean hasS2SArtifact) {
|
|
||||||
int oldFixedErrors = reporter.fixed.size()
|
|
||||||
|
|
||||||
final lines = Files.readAllLines(patch)
|
|
||||||
|
|
||||||
int hunksStart = 0
|
|
||||||
boolean onlyWhiteSpace = false
|
|
||||||
|
|
||||||
final List<String> newLines = []
|
|
||||||
|
|
||||||
// First two lines are file name ++/-- and we do not care
|
|
||||||
newLines.add(lines[0] + '\n')
|
|
||||||
newLines.add(lines[1] + '\n')
|
|
||||||
|
|
||||||
int i
|
|
||||||
for (i = 2; i < lines.size(); ++i) {
|
|
||||||
def line = lines[i]
|
|
||||||
newLines.add(line + '\n')
|
|
||||||
|
|
||||||
if (HUNK_START_PATTERN.matcher(line).find()) {
|
|
||||||
if (onlyWhiteSpace) {
|
|
||||||
if (!hasS2SArtifact)
|
|
||||||
reporter.report("Patch contains only white space hunk starting at line ${hunksStart + 1}, file: $patchPath")
|
|
||||||
int toRemove = i - hunksStart
|
|
||||||
while (toRemove-- > 0)
|
|
||||||
newLines.remove(newLines.size() - 1)
|
|
||||||
}
|
|
||||||
hunksStart = i
|
|
||||||
onlyWhiteSpace = true
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (line.startsWithAny('+','-')) {
|
|
||||||
def prefixChange = false
|
|
||||||
def prevLine = lines[i - 1]
|
|
||||||
|
|
||||||
if (line.charAt(0) == (char)'+' && prevLine.charAt(0) == (char)'-') {
|
|
||||||
def prevTrim = prevLine.substring(1).replaceAll("\\s", "")
|
|
||||||
def currTrim = line.substring(1).replaceAll("\\s", "")
|
|
||||||
|
|
||||||
if (prevTrim == currTrim) {
|
|
||||||
prefixChange = true
|
|
||||||
}
|
|
||||||
|
|
||||||
def pMatcher = FIELD_PATTERN.matcher(prevLine)
|
|
||||||
def cMatcher = FIELD_PATTERN.matcher(line)
|
|
||||||
|
|
||||||
if (pMatcher.find() && cMatcher.find() &&
|
|
||||||
pMatcher.group(6) == cMatcher.group(6) && // = ...
|
|
||||||
pMatcher.group(5) == cMatcher.group(5) && // field name
|
|
||||||
pMatcher.group(3) == cMatcher.group(3) && // static
|
|
||||||
(accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) {
|
|
||||||
reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false)
|
|
||||||
}
|
|
||||||
|
|
||||||
pMatcher = METHOD_PATTERN.matcher(prevLine)
|
|
||||||
cMatcher = METHOD_PATTERN.matcher(line)
|
|
||||||
|
|
||||||
if (pMatcher.find() && cMatcher.find() &&
|
|
||||||
pMatcher.group(6) == cMatcher.group(6) && // params
|
|
||||||
pMatcher.group(5) == cMatcher.group(5) && // <T> void name
|
|
||||||
pMatcher.group(3) == cMatcher.group(3) && // static
|
|
||||||
(accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) {
|
|
||||||
reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false)
|
|
||||||
}
|
|
||||||
|
|
||||||
pMatcher = CLASS_PATTERN.matcher(prevLine)
|
|
||||||
cMatcher = CLASS_PATTERN.matcher(line)
|
|
||||||
|
|
||||||
if (pMatcher.find() && cMatcher.find() &&
|
|
||||||
pMatcher.group(6) == cMatcher.group(6) && // ClassName<> extends ...
|
|
||||||
pMatcher.group(5) == cMatcher.group(5) && // class | interface
|
|
||||||
pMatcher.group(3) == cMatcher.group(3) && // static
|
|
||||||
(accessChange(pMatcher.group(2), cMatcher.group(2)) || pMatcher.group(4) != cMatcher.group(4))) {
|
|
||||||
reporter.report("Patch contains access changes or final removal at line ${i + 1}, file: $patchPath", false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (line.charAt(0) == (char)'-' && i + 1 < lines.size()) {
|
|
||||||
final nextLine = lines[i + 1]
|
|
||||||
if (nextLine.charAt(0) == (char)'+') {
|
|
||||||
final nextTrim = nextLine.substring(1).replaceAll("\\s", "")
|
|
||||||
final currTrim = line.substring(1).replaceAll("\\s", "")
|
|
||||||
|
|
||||||
if (nextTrim == currTrim) {
|
|
||||||
prefixChange = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final isWhiteSpaceChange = WHITESPACE_PATTERN.matcher(line).find()
|
|
||||||
|
|
||||||
if (!prefixChange && !isWhiteSpaceChange) {
|
|
||||||
onlyWhiteSpace = hasS2SArtifact && IMPORT_PATTERN.matcher(line).find()
|
|
||||||
} else if (isWhiteSpaceChange) {
|
|
||||||
final prevLineChange = prevLine.startsWithAny('+','-')
|
|
||||||
final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-')
|
|
||||||
|
|
||||||
if (!prevLineChange && !nextLineChange) {
|
|
||||||
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath \n$prevLine\n$line\n${lines[i+1]}", false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (line.contains('\t')) {
|
|
||||||
reporter.report("Patch contains tabs on line ${i + 1}, file: $patchPath")
|
|
||||||
line = line.replaceAll('\t', ' ')
|
|
||||||
newLines.remove(newLines.size() - 1)
|
|
||||||
newLines.add(line + '\n')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IMPORT_PATTERN.matcher(line).find() && !hasS2SArtifact) {
|
|
||||||
reporter.report("Patch contains import change on line ${i + 1}, file: $patchPath", false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (onlyWhiteSpace) {
|
|
||||||
if (!hasS2SArtifact)
|
|
||||||
reporter.report("Patch contains only white space hunk starting at line ${hunksStart + 1}, file: $patchPath")
|
|
||||||
def toRemove = i - hunksStart;
|
|
||||||
while (toRemove-- > 0)
|
|
||||||
newLines.remove(newLines.size() - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((reporter.fixed.size() > oldFixedErrors && fix) || hasS2SArtifact) {
|
|
||||||
if (newLines.size() <= 2) {
|
|
||||||
logger.lifecycle("Patch is now empty removing, file: {}", patchPath)
|
|
||||||
Files.delete(patch)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (!hasS2SArtifact)
|
|
||||||
logger.lifecycle("*** Updating patch file. Please run setup then genPatches again. ***")
|
|
||||||
Files.newBufferedWriter(patch).withCloseable {
|
|
||||||
newLines.each { l -> it.write(l) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import net.minecraftforge.forge.tasks.Annotatable
|
|
||||||
import net.minecraftforge.forge.tasks.InheritanceData
|
|
||||||
import org.gradle.api.file.ConfigurableFileCollection
|
|
||||||
import org.gradle.api.file.RegularFileProperty
|
|
||||||
import org.gradle.api.tasks.InputFile
|
|
||||||
import org.gradle.api.tasks.InputFiles
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class CheckSAS extends CheckTask {
|
|
||||||
|
|
||||||
@InputFile abstract RegularFileProperty getInheritance()
|
|
||||||
@InputFiles abstract ConfigurableFileCollection getSass()
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void check(Reporter reporter, boolean fix) {
|
|
||||||
final inheritance = InheritanceData.parse(this.inheritance.get().asFile)
|
|
||||||
|
|
||||||
sass.each { f ->
|
|
||||||
final lines = []
|
|
||||||
f.eachLine { line ->
|
|
||||||
if (line[0] == '\t') return // Skip any tabbed lines, those are ones we add
|
|
||||||
final idx = line.indexOf('#')
|
|
||||||
if (idx == 0 || line.isEmpty()) {
|
|
||||||
lines.add(line)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
def comment = idx == -1 ? null : line.substring(idx)
|
|
||||||
if (idx != -1) line = line.substring(0, idx - 1)
|
|
||||||
final spl = (line.trim().replace('(', ' (') + ' ').split(' ', -1)
|
|
||||||
def (String cls, String name, String desc) = [spl[0], spl[1], spl[2]]
|
|
||||||
cls = cls.replaceAll('\\.', '/')
|
|
||||||
|
|
||||||
if (inheritance[cls] === null) {
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
} else if (name.isEmpty()) { //Class SAS
|
|
||||||
final toAdd = []
|
|
||||||
final clsSided = isSided(inheritance[cls])
|
|
||||||
boolean sided = clsSided
|
|
||||||
|
|
||||||
/* TODO: MergeTool doesn't do fields
|
|
||||||
if (json[cls]['fields'] != null) {
|
|
||||||
for (entry in json[cls]['fields']) {
|
|
||||||
if (isSided(entry.value)) {
|
|
||||||
sided = true
|
|
||||||
toAdd.add('\t' + cls + ' ' + entry.key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} */
|
|
||||||
|
|
||||||
final clsInh = inheritance[cls]
|
|
||||||
if (clsInh.methods) {
|
|
||||||
for (entry in clsInh.methods) {
|
|
||||||
if (isSided(entry.value)) {
|
|
||||||
sided = true
|
|
||||||
toAdd.add('\t' + cls + ' ' + entry.key.replaceAll(' ', ''))
|
|
||||||
findChildMethods(inheritance, cls, entry.key).each { lines.add('\t' + it) }
|
|
||||||
findChildMethods(inheritance, cls, entry.key).each { println(line + ' -- ' + it) }
|
|
||||||
} else if (clsSided) {
|
|
||||||
findChildMethods(inheritance, cls, entry.key).each { lines.add('\t' + it) }
|
|
||||||
findChildMethods(inheritance, cls, entry.key).each { println(line + ' -- ' + it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sided) {
|
|
||||||
lines.add(cls + (comment == null ? '' : ' ' + comment))
|
|
||||||
lines.addAll(toAdd.sort())
|
|
||||||
} else {
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (desc.isEmpty()) { // Fields
|
|
||||||
/* TODO: MergeTool doesn't do fields
|
|
||||||
if (json[cls]['fields'] != null && isSided(json[cls]['fields'][name]))
|
|
||||||
lines.add(cls + ' ' + name + (comment == null ? '' : ' ' + comment))
|
|
||||||
else */
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
} else { // Methods
|
|
||||||
final clsInh = inheritance[cls]
|
|
||||||
if (clsInh.methods === null || !isSided(clsInh.methods[name + ' ' + desc]))
|
|
||||||
reporter.report("Invalid: $line")
|
|
||||||
else {
|
|
||||||
lines.add(cls + ' ' + name + desc + (comment == null ? '' : ' ' + comment))
|
|
||||||
findChildMethods(inheritance, cls, name + ' ' + desc).each { println(line + ' -- ' + it) }
|
|
||||||
findChildMethods(inheritance, cls, name + ' ' + desc).each { lines.add('\t' + it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fix) f.text = lines.join('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected static boolean isSided(Annotatable annotatable) {
|
|
||||||
if (annotatable === null) return false
|
|
||||||
for (ann in annotatable.annotations) {
|
|
||||||
if ('Lnet/minecraftforge/api/distmarker/OnlyIn;' == ann.desc)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
protected static findChildMethods(Map<String, InheritanceData> json, String cls, String desc) {
|
|
||||||
return json.values().findAll{ it.methods !== null && it.methods[desc] !== null && it.methods[desc].override == cls && isSided(it.methods[desc]) }
|
|
||||||
.collect { it.name + ' ' + desc.replace(' ', '') } as TreeSet
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
package net.minecraftforge.forge.tasks.checks
|
|
||||||
|
|
||||||
import groovy.transform.CompileStatic
|
|
||||||
import groovy.transform.stc.ClosureParams
|
|
||||||
import groovy.transform.stc.ThirdParam
|
|
||||||
import net.minecraftforge.forge.tasks.Util
|
|
||||||
import org.gradle.api.Action
|
|
||||||
import org.gradle.api.DefaultTask
|
|
||||||
import org.gradle.api.logging.LogLevel
|
|
||||||
import org.gradle.api.provider.Property
|
|
||||||
import org.gradle.api.tasks.Input
|
|
||||||
import org.gradle.api.tasks.TaskAction
|
|
||||||
import org.gradle.api.tasks.TaskContainer
|
|
||||||
import org.gradle.api.tasks.VerificationTask
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
abstract class CheckTask extends DefaultTask implements VerificationTask {
|
|
||||||
@Input
|
|
||||||
abstract Property<CheckMode> getMode()
|
|
||||||
|
|
||||||
private boolean ignoreFailures = false
|
|
||||||
|
|
||||||
@Input
|
|
||||||
@Override
|
|
||||||
boolean getIgnoreFailures() {
|
|
||||||
return ignoreFailures
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void setIgnoreFailures(boolean ignoreFailures) {
|
|
||||||
this.ignoreFailures = ignoreFailures
|
|
||||||
}
|
|
||||||
|
|
||||||
@TaskAction
|
|
||||||
void run() {
|
|
||||||
Util.init()
|
|
||||||
|
|
||||||
boolean doFix = getMode().get() === CheckMode.FIX
|
|
||||||
final Reporter reporter = new Reporter(doFix)
|
|
||||||
check(reporter, doFix)
|
|
||||||
|
|
||||||
if (reporter.messages) {
|
|
||||||
if (getMode().get() === CheckMode.CHECK) {
|
|
||||||
logger.error("Check task '{}' found errors:\n{}", name, reporter.messages.join('\n'))
|
|
||||||
if (!ignoreFailures) {
|
|
||||||
throw new IllegalArgumentException("${reporter.messages.size()} errors were found!")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (logger.isEnabled(LogLevel.DEBUG)) {
|
|
||||||
logger.warn("Check task '{}' found {} errors and fixed {}:\n{}", name, reporter.messages.size(), reporter.fixed.size(), reporter.fixed.join('\n'))
|
|
||||||
} else {
|
|
||||||
logger.warn("Check task '{}' found {} errors and fixed {}.", name, reporter.messages.size(), reporter.fixed.size())
|
|
||||||
}
|
|
||||||
|
|
||||||
if (reporter.notFixed) {
|
|
||||||
logger.error('{} errors could not be fixed:\n{}', reporter.notFixed.size(), reporter.notFixed.join('\n'))
|
|
||||||
if (!ignoreFailures) {
|
|
||||||
throw new IllegalArgumentException("${reporter.notFixed.size()} errors which cannot be fixed were found!")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract void check(Reporter reporter, boolean fix)
|
|
||||||
|
|
||||||
@CompileStatic
|
|
||||||
static final class Reporter {
|
|
||||||
final boolean trackFixed
|
|
||||||
Reporter(boolean trackFixed) {
|
|
||||||
this.trackFixed = trackFixed
|
|
||||||
}
|
|
||||||
|
|
||||||
public final List<String> messages = []
|
|
||||||
|
|
||||||
public final List<String> fixed = []
|
|
||||||
public final List<String> notFixed = []
|
|
||||||
|
|
||||||
void report(String message, boolean canBeFixed = true) {
|
|
||||||
messages.add(message)
|
|
||||||
|
|
||||||
if (trackFixed) {
|
|
||||||
if (canBeFixed) {
|
|
||||||
fixed.add(message)
|
|
||||||
} else {
|
|
||||||
notFixed.add(message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static <T extends CheckTask> void registerTask(TaskContainer tasks, String taskName, @DelegatesTo.Target('type') Class<T> clazz,
|
|
||||||
@DelegatesTo(genericTypeIndex = 0, target = 'type')
|
|
||||||
@ClosureParams(ThirdParam.FirstGenericType) Closure configuration) {
|
|
||||||
taskName = taskName.capitalize()
|
|
||||||
tasks.register("check$taskName", clazz) { CheckTask task ->
|
|
||||||
def castedTask = task as T
|
|
||||||
configuration.setDelegate(castedTask)
|
|
||||||
configuration.call(castedTask)
|
|
||||||
castedTask.mode.set(CheckMode.CHECK)
|
|
||||||
castedTask.group = 'checks'
|
|
||||||
}
|
|
||||||
tasks.named('checkAll').configure { it.dependsOn("check$taskName") }
|
|
||||||
|
|
||||||
tasks.register("checkAndFix$taskName", clazz) { CheckTask task ->
|
|
||||||
def castedTask = task as T
|
|
||||||
configuration.setDelegate(castedTask)
|
|
||||||
configuration.call(castedTask)
|
|
||||||
castedTask.mode.set(CheckMode.FIX)
|
|
||||||
castedTask.group = 'checks'
|
|
||||||
}
|
|
||||||
tasks.named('checkAllAndFix').configure { it.dependsOn("checkAndFix$taskName") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'java-library'
|
|
||||||
id 'net.minecraftforge.gradle.patcher'
|
|
||||||
}
|
|
||||||
|
|
||||||
evaluationDependsOn(':mcp')
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
mavenCentral()
|
|
||||||
maven gradleutils.forgeMaven
|
|
||||||
maven gradleutils.minecraftLibsMaven
|
|
||||||
}
|
|
||||||
|
|
||||||
java.toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation(libs.forgespi)
|
|
||||||
}
|
|
||||||
|
|
||||||
patcher {
|
|
||||||
parent = project(':mcp')
|
|
||||||
mcVersion = MC_VERSION
|
|
||||||
patchedSrc = file('src/main/java')
|
|
||||||
|
|
||||||
mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
|
|
||||||
|
|
||||||
runs {
|
|
||||||
clean_client {
|
|
||||||
client true
|
|
||||||
taskName 'clean_client'
|
|
||||||
ideaModule "${rootProject.name}.${project.name}.main"
|
|
||||||
|
|
||||||
main 'net.minecraft.client.main.Main'
|
|
||||||
workingDirectory project.file('run/client')
|
|
||||||
|
|
||||||
args '--gameDir', '.'
|
|
||||||
args '--version', MC_VERSION
|
|
||||||
args '--assetsDir', downloadAssets.output
|
|
||||||
args '--assetIndex', '{asset_index}'
|
|
||||||
args '--accessToken', '0'
|
|
||||||
}
|
|
||||||
|
|
||||||
clean_server {
|
|
||||||
client false
|
|
||||||
taskName 'clean_server'
|
|
||||||
ideaModule "${rootProject.name}.${project.name}.main"
|
|
||||||
|
|
||||||
main 'net.minecraft.server.Main'
|
|
||||||
workingDirectory project.file('run/server')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
|
||||||
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
|
||||||
options.warnings = false // Shutup deprecated for removal warnings
|
|
||||||
}
|
|
||||||
|
|
||||||
eclipse.classpath.file.whenMerged {
|
|
||||||
// Disable optional warnings on the minecraft decompiled source code. It just muddies the warning window and hides warnings in our own codebase
|
|
||||||
def src = entries.find { it.path == 'src/main/java' }
|
|
||||||
if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
|
|
||||||
src.entryAttributes['ignore_optional_problems'] = 'true'
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('genPatches').configure {
|
|
||||||
onlyIf { false }
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('extractRangeMap').configure {
|
|
||||||
onlyIf { false }
|
|
||||||
tool = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
|
|
||||||
}
|
|
||||||
-1122
File diff suppressed because it is too large.
Load diff
@@ -1,89 +0,0 @@
|
|||||||
import net.minecraftforge.forge.tasks.CleanProperties
|
|
||||||
|
|
||||||
apply plugin: 'eclipse'
|
|
||||||
apply plugin: 'idea'
|
|
||||||
apply plugin: 'net.minecraftforge.gradleutils'
|
|
||||||
|
|
||||||
group = 'net.minecraftforge'
|
|
||||||
version = VERSION
|
|
||||||
println("Version: $version")
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
mavenCentral()
|
|
||||||
maven gradleutils.forgeMaven
|
|
||||||
maven gradleutils.minecraftLibsMaven
|
|
||||||
//mavenLocal()
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(Javadoc).configureEach {
|
|
||||||
options.tags = [
|
|
||||||
'apiNote:a:<em>API Note:</em>',
|
|
||||||
'implSpec:a:<em>Implementation Requirements:</em>',
|
|
||||||
'implNote:a:<em>Implementation Note:</em>'
|
|
||||||
]
|
|
||||||
options.addStringOption('Xdoclint:all,-missing', '-public')
|
|
||||||
}
|
|
||||||
|
|
||||||
// We need to write the manifest to the binary file so we have properly versioned packaged at dev time.
|
|
||||||
tasks.register('writeManifest') {
|
|
||||||
doLast {
|
|
||||||
if (plugins.findPlugin('net.minecraftforge.gradle.patcher')) // Forge project
|
|
||||||
universalJar.manifest.writeTo(rootProject.file('src/main/resources/META-INF/MANIFEST.MF'))
|
|
||||||
else
|
|
||||||
jar.manifest.writeTo(project.file('src/main/resources/META-INF/MANIFEST.MF'))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register('generateResources') {
|
|
||||||
dependsOn('writeManifest')
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named('processResources') {
|
|
||||||
dependsOn(generateResources)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make sure out manifests get written before compiling the code, IDEA calls this task if you tell it to use the gradle build.
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
|
||||||
dependsOn 'generateResources'
|
|
||||||
dependsOn 'processResources' // Needed because we merge the output of this with the output of the compile task. And gradle detects downstream tasks using the output without a hard dep
|
|
||||||
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
|
||||||
options.warnings = false // Shutup deprecated for removal warnings
|
|
||||||
options.forkOptions.jvmArgs += '-Xmx6G' // Needed to make compiling faster, and not run out of heap space in some cases.
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge the resources and classes into the same directory. We'll need to split them at runtime because
|
|
||||||
// Minecraft and Forge are in the same sourceSet as they are inter dependent.. for now..
|
|
||||||
sourceSets.each {
|
|
||||||
def dir = layout.buildDirectory.dir("classes/java/$it.name")
|
|
||||||
it.output.resourcesDir = dir
|
|
||||||
it.java.destinationDirectory = dir
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register('copyEclipseSettings') {
|
|
||||||
doLast {
|
|
||||||
rootProject.fileTree('ide/eclipse/template/.settings/').matching { include '**/*.prefs' }.each { file ->
|
|
||||||
def target = project.file('.settings/' + file.name)
|
|
||||||
def temp = new CleanProperties().load(file)
|
|
||||||
def exst = new CleanProperties().load(target)
|
|
||||||
exst.put('eclipse.preferences.version', '1')
|
|
||||||
exst.putAll(temp)
|
|
||||||
exst.store(target)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: [Gradle][IntelliJ] Auto trigger these tasks on import.
|
|
||||||
eclipse {
|
|
||||||
// Run everytime eclipse builds the code
|
|
||||||
//autoBuildTasks writeManifest
|
|
||||||
// Run when importing the project
|
|
||||||
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject
|
|
||||||
}
|
|
||||||
|
|
||||||
idea {
|
|
||||||
module {
|
|
||||||
// IntelliJ IDEA does not do this by itself anymore...
|
|
||||||
downloadJavadoc = true
|
|
||||||
downloadSources = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+10
-8
@@ -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,12 +34,13 @@ 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 |
|
||||||
|---------------|-------------------|
|
|------------------|-------------------|
|
||||||
| 1.20.6+ | [21][Adoptium-21] |
|
| 26.1+ | [25][Adoptium-25] |
|
||||||
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
| 1.20.6 - 1.21.11 | [21][Adoptium-21] |
|
||||||
| 1.17.1 | [16][Adoptium-16] |
|
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
||||||
| 1.16.5- | [8][Adoptium-8] |
|
| 1.17.1 | [16][Adoptium-16] |
|
||||||
|
| 1.16.5- | [8][Adoptium-8] |
|
||||||
|
|
||||||
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
||||||
|
|
||||||
@@ -80,6 +81,7 @@ YourKit for providing us accesss to their [YourKit Java Profiler] which helps id
|
|||||||
|
|
||||||
[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
|
||||||
|
|||||||
+50
-40
@@ -1,68 +1,78 @@
|
|||||||
import net.minecraftforge.gradleutils.PomUtils
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
id 'maven-publish'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.licenser'
|
alias libs.plugins.licenser
|
||||||
id 'net.minecraftforge.gradleutils'
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: rootProject.file('build_shared.gradle')
|
gradleutils.displayName = 'FML'
|
||||||
|
final vendor = 'Forge Development LLC'
|
||||||
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
compileOnly(libs.jetbrains.annotations)
|
compileOnly libs.jetbrains.annotations
|
||||||
|
|
||||||
api(libs.eventbus)
|
api libs.eventbus
|
||||||
annotationProcessor(libs.eventbus.validator)
|
|
||||||
|
|
||||||
implementation(project(':fmlloader'))
|
implementation projects.fmlloader
|
||||||
implementation(libs.commons.io)
|
implementation libs.commons.io
|
||||||
}
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
withSourcesJar()
|
withSourcesJar()
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('jar', Jar).configure {
|
license {
|
||||||
manifest {
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
attributes([
|
}
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.fmlcore',
|
changelog {
|
||||||
'FMLModType': 'LIBRARY'
|
from changelogBase
|
||||||
] as LinkedHashMap)
|
|
||||||
attributes([
|
|
||||||
'Specification-Title': 'FML',
|
|
||||||
'Specification-Vendor': 'Forge Development LLC',
|
|
||||||
'Specification-Version': '1',
|
|
||||||
'Implementation-Title': 'FML',
|
|
||||||
'Implementation-Version': '1.0',
|
|
||||||
'Implementation-Vendor': 'Forge Development LLC'
|
|
||||||
] as LinkedHashMap, 'net/minecraftforge/fml/')
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
tasks.withType(JavaCompile).configureEach {
|
||||||
options.compilerArgs << '-Xlint:-unchecked'
|
options.compilerArgs << '-Xlint:-unchecked'
|
||||||
}
|
}
|
||||||
|
|
||||||
license {
|
tasks.named('jar', Jar) {
|
||||||
header = rootProject.file('LICENSE-header.txt')
|
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 {
|
publishing {
|
||||||
publications.register('mavenJava', MavenPublication).configure {
|
|
||||||
from components.java
|
|
||||||
artifactId = 'fmlcore'
|
|
||||||
pom {
|
|
||||||
name = project.name
|
|
||||||
description = 'Modifactions to Minecraft to enable mod developers.'
|
|
||||||
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
|
||||||
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
|
|
||||||
license PomUtils.Licenses.LGPLv2_1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
maven gradleutils.publishingForgeMaven
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -14,16 +14,14 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,19 +31,15 @@ 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();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -58,31 +52,23 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -90,8 +76,7 @@ public class CrashReportCallables
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<ISystemReportExtender> allCrashCallables()
|
public static List<ISystemReportExtender> allCrashCallables() {
|
||||||
{
|
|
||||||
return List.copyOf(crashCallables);
|
return List.copyOf(crashCallables);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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,13 +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.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.ToIntFunction;
|
import java.util.function.IntSupplier;
|
||||||
|
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,
|
||||||
@@ -20,6 +21,7 @@ import java.util.function.ToIntFunction;
|
|||||||
*
|
*
|
||||||
* @see IModStateProvider
|
* @see IModStateProvider
|
||||||
*/
|
*/
|
||||||
|
@NullMarked
|
||||||
public interface IModLoadingState {
|
public interface IModLoadingState {
|
||||||
/**
|
/**
|
||||||
* {@return the name of this state}
|
* {@return the name of this state}
|
||||||
@@ -42,19 +44,21 @@ 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}
|
||||||
*/
|
*/
|
||||||
Function<ModList, String> message();
|
Supplier<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.
|
||||||
*/
|
*/
|
||||||
ToIntFunction<ModList> size();
|
default IntSupplier 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)
|
||||||
*/
|
*/
|
||||||
Optional<Consumer<ModList>> inlineRunnable();
|
@Nullable Runnable 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.
|
||||||
@@ -65,14 +69,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 Optional<CompletableFuture<Void>> buildTransition(
|
default @Nullable 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,
|
||||||
e -> CompletableFuture.completedFuture(null),
|
_ -> CompletableFuture.completedFuture(null),
|
||||||
e -> CompletableFuture.completedFuture(null)
|
_ -> CompletableFuture.completedFuture(null)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +91,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
|
||||||
*/
|
*/
|
||||||
Optional<CompletableFuture<Void>> buildTransition(final Executor syncExecutor,
|
@Nullable 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,21 +6,16 @@
|
|||||||
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;
|
||||||
}
|
}
|
||||||
@@ -40,15 +35,6 @@ 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;
|
||||||
@@ -57,25 +43,9 @@ 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,12 +7,10 @@ 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,63 +5,20 @@
|
|||||||
|
|
||||||
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 class InterModComms
|
public final 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.
|
||||||
@@ -72,8 +29,9 @@ public 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.get().isLoaded(modId)) return false;
|
if (!ModList.isLoaded(modId)) return false;
|
||||||
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(ModLoadingContext.get().getActiveContainer().getModId(), modId, method, thing));
|
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
||||||
|
.add(new IMCMessage(ModLoadingContext.get().getContainer().getModId(), modId, method, thing));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,8 +45,9 @@ public 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.get().isLoaded(modId)) return false;
|
if (!ModList.isLoaded(modId)) return false;
|
||||||
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(senderModId, modId, method, thing));
|
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
||||||
|
.add(new IMCMessage(senderModId, modId, method, thing));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +71,7 @@ public 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, s->Boolean.TRUE);
|
return getMessages(modId, _ -> true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record QueueFilteringSpliterator(
|
private record QueueFilteringSpliterator(
|
||||||
@@ -136,13 +95,10 @@ public 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();
|
||||||
@@ -157,6 +113,5 @@ public class InterModComms
|
|||||||
public Spliterator<IMCMessage> trySplit() {
|
public Spliterator<IMCMessage> trySplit() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,6 @@ 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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,11 +40,6 @@ 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();
|
||||||
@@ -59,7 +53,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, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
|
(incoming, _) -> 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
|
||||||
@@ -138,12 +132,7 @@ 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,33 +30,36 @@ 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 class ModList {
|
public final class ModList {
|
||||||
private static ModList INSTANCE;
|
private ModList() {}
|
||||||
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 ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
|
private static final List<IModFileInfo> MOD_FILES;
|
||||||
var modFileInfos = this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
|
private static final List<IModInfo> SORTED_LIST;
|
||||||
this.sortedList = sortedList.stream().map(IModInfo.class::cast).toList();
|
private static final Map<String, IModFileInfo> FILE_BY_ID;
|
||||||
|
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());
|
||||||
}
|
}
|
||||||
this.fileById = Map.copyOf(byId);
|
FILE_BY_ID = Map.copyOf(byId);
|
||||||
CrashReportCallables.registerCrashCallable("Mod List", this::crashReport);
|
CrashReportCallables.registerCrashCallable("Mod List", ModList::crashReport);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getModContainerState(String modId) {
|
private static 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 String fileToLine(IModFile mf) {
|
private static 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(),
|
||||||
@@ -66,92 +69,92 @@ public class ModList {
|
|||||||
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String crashReport() {
|
private static String crashReport() {
|
||||||
return "\n" + applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
return "\n" + applyForEachModFile(ModList::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) {
|
public static void init() {}
|
||||||
INSTANCE = new ModList(modFiles, sortedList);
|
|
||||||
return INSTANCE;
|
public static List<IModFileInfo> getModFiles() {
|
||||||
|
return MOD_FILES;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ModList get() {
|
public static IModFileInfo getModFileById(String modid) {
|
||||||
return INSTANCE;
|
return FILE_BY_ID.get(modid);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<IModFileInfo> getModFiles() {
|
static void setLoadedMods(final List<ModContainer> modContainers) {
|
||||||
return modFiles;
|
mods = modContainers;
|
||||||
|
sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> SORTED_LIST.indexOf(c.getModInfo()))).toList();
|
||||||
|
indexedMods = modContainers.stream().collect(Collectors.toUnmodifiableMap(ModContainer::getModId, Function.identity()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public IModFileInfo getModFileById(String modid) {
|
static void clearLoadedMods() {
|
||||||
return this.fileById.get(modid);
|
mods = List.of();
|
||||||
}
|
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 <T> Optional<T> getModObjectById(String modId) {
|
public static <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 Optional<? extends ModContainer> getModContainerById(String modId) {
|
public static Optional<? extends ModContainer> getModContainerById(String modId) {
|
||||||
return Optional.ofNullable(this.indexedMods.get(modId));
|
return Optional.ofNullable(indexedMods.get(modId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<? extends ModContainer> getModContainerByObject(Object obj) {
|
public static 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 List<IModInfo> getMods() {
|
public static List<IModInfo> getMods() {
|
||||||
return this.sortedList;
|
return SORTED_LIST;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isLoaded(String modTarget) {
|
public static boolean isLoaded(String modTarget) {
|
||||||
return this.indexedMods.containsKey(modTarget);
|
return indexedMods.containsKey(modTarget);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int size() {
|
public static int size() {
|
||||||
return mods.size();
|
return mods.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ModFileScanData> getAllScanData() {
|
public static List<ModFileScanData> getAllScanData() {
|
||||||
if (modFileScanData == null) {
|
final class LazyInit {
|
||||||
modFileScanData = this.sortedList.stream().
|
private LazyInit() {}
|
||||||
map(IModInfo::getOwningFile).
|
private static final List<ModFileScanData> MOD_FILE_SCAN_DATA = SORTED_LIST.stream()
|
||||||
filter(Objects::nonNull).
|
.map(IModInfo::getOwningFile)
|
||||||
map(IModFileInfo::getFile).
|
.filter(Objects::nonNull)
|
||||||
distinct().
|
.map(IModFileInfo::getFile)
|
||||||
map(IModFile::getScanResult).
|
.distinct()
|
||||||
toList();
|
.map(IModFile::getScanResult)
|
||||||
|
.toList();
|
||||||
}
|
}
|
||||||
return modFileScanData;
|
return LazyInit.MOD_FILE_SCAN_DATA;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void forEachModFile(Consumer<IModFile> fileConsumer) {
|
public static void forEachModFile(Consumer<IModFile> fileConsumer) {
|
||||||
modFiles.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
|
MOD_FILES.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
|
public static <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
|
||||||
return modFiles.stream().map(IModFileInfo::getFile).map(function);
|
return MOD_FILES.stream().map(IModFileInfo::getFile).map(function);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
public static void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
||||||
indexedMods.forEach(modContainerConsumer);
|
indexedMods.forEach(modContainerConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
|
public static void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
|
||||||
this.sortedContainers.forEach(containerConsumer);
|
sortedContainers.forEach(containerConsumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ModContainer> getLoadedMods() {
|
public static List<ModContainer> getLoadedMods() {
|
||||||
return this.sortedContainers;
|
return sortedContainers;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
public static <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
||||||
return indexedMods.values().stream().map(function);
|
return indexedMods.values().stream().map(function);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,16 +5,11 @@
|
|||||||
|
|
||||||
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.FMLEnvironment;
|
import net.minecraftforge.fml.loading.*;
|
||||||
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;
|
||||||
@@ -71,48 +66,18 @@ import static net.minecraftforge.fml.Logging.LOADING;
|
|||||||
* and completes the mod loading sequence.</dd>
|
* and completes the mod loading sequence.</dd>
|
||||||
* </dl>
|
* </dl>
|
||||||
*/
|
*/
|
||||||
public class ModLoader {
|
public final class ModLoader {
|
||||||
|
private ModLoader() {}
|
||||||
|
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private final LoadingModList loadingModList;
|
private static final ArrayList<ModLoadingException> LOADING_EXCEPTIONS = new ArrayList<>();
|
||||||
|
private static final ArrayList<ModLoadingWarning> LOADING_WARNINGS = new ArrayList<>();
|
||||||
private final List<ModLoadingException> loadingExceptions;
|
private static final Consumer<String> STATUS_CONSUMER = StartupNotificationManager.modLoaderConsumer().orElse(_ -> {});
|
||||||
private final Set<IModInfo> erroredModInfos;
|
private static final HashSet<IModLoadingState> COMPLETED_STATES = new HashSet<>();
|
||||||
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" + FMLLoader.getLanguageLoadingProvider()
|
return "\n" + LanguageLoadingProvider
|
||||||
.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", ""));
|
||||||
}
|
}
|
||||||
@@ -126,37 +91,51 @@ public 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 void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public static 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);
|
||||||
final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList(),
|
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
||||||
loadingModList.getMods());
|
LOGGER.fatal(CORE, "Error during pre-loading phase", LOADING_EXCEPTIONS.getFirst());
|
||||||
if (!this.loadingExceptions.isEmpty()) {
|
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||||
LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.getFirst());
|
ModList.clearLoadedMods();
|
||||||
statusConsumer.accept("ERROR DURING MOD LOADING");
|
|
||||||
modList.setLoadedMods(Collections.emptyList());
|
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
throw new LoadingFailedException(loadingExceptions);
|
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
||||||
}
|
}
|
||||||
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);
|
||||||
@@ -165,8 +144,8 @@ public 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);
|
||||||
statusConsumer.accept("ERROR DURING MOD LOADING");
|
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||||
modList.setLoadedMods(Collections.emptyList());
|
ModList.clearLoadedMods();
|
||||||
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)))
|
||||||
@@ -174,18 +153,18 @@ public 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 = this.buildMods(file.getFile());
|
var containers = buildMods(file.getFile());
|
||||||
for (var container : containers)
|
for (var container : containers)
|
||||||
modContainers.put(container.getModId(), container);
|
modContainers.put(container.getModId(), container);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!loadingExceptions.isEmpty()) {
|
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
||||||
LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.getFirst());
|
LOGGER.fatal(CORE, "Failed to initialize mod containers", LOADING_EXCEPTIONS.getFirst());
|
||||||
statusConsumer.accept("ERROR DURING MOD LOADING");
|
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||||
modList.setLoadedMods(Collections.emptyList());
|
ModList.clearLoadedMods();
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
throw new LoadingFailedException(loadingExceptions);
|
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -208,34 +187,33 @@ public class ModLoader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
modList.setLoadedMods(modContainers.values().stream().toList());
|
ModList.setLoadedMods(modContainers.values().stream().toList());
|
||||||
this.modList = modList;
|
var stateList = ModStateManager.getStates(ModLoadingPhase.GATHER);
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.GATHER);
|
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
||||||
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 void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public static void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.LOAD);
|
var stateList = ModStateManager.getStates(ModLoadingPhase.LOAD);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).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 void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public static void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.COMPLETE);
|
var stateList = ModStateManager.getStates(ModLoadingPhase.COMPLETE);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).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)
|
||||||
@@ -245,11 +223,11 @@ public class ModLoader {
|
|||||||
}
|
}
|
||||||
parallelExecutor.execute(BusGroup.DEFAULT::trim);
|
parallelExecutor.execute(BusGroup.DEFAULT::trim);
|
||||||
|
|
||||||
statusConsumer.accept("Mod loading complete - %d mods loaded".formatted(this.modList.size()));
|
STATUS_CONSUMER.accept("Mod loading complete - %d mods loaded".formatted(ModList.size()));
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) {
|
private static 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;
|
||||||
@@ -257,25 +235,25 @@ public class ModLoader {
|
|||||||
progressBar.label(progressBar.name() + " working");
|
progressBar.label(progressBar.name() + " working");
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
|
|
||||||
var inlineRunnable = state.inlineRunnable().orElse(null);
|
var inlineRunnable = state.inlineRunnable();
|
||||||
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
||||||
|
|
||||||
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar).orElse(null);
|
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar);
|
||||||
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
||||||
|
|
||||||
completedStates.add(state);
|
COMPLETED_STATES.add(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleInlineTransition(final Consumer<ModList> transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
|
private static void handleInlineTransition(final Runnable 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.accept(this.modList);
|
transition.run();
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
pb.complete();
|
pb.complete();
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) {
|
private static 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);
|
||||||
}
|
}
|
||||||
@@ -289,7 +267,7 @@ public 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);
|
||||||
statusConsumer.accept("ERROR DURING MOD LOADING");
|
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,12 +276,12 @@ public 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());
|
||||||
statusConsumer.accept("ERROR DURING MOD LOADING");
|
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||||
throw new LoadingFailedException(modLoadingExceptions);
|
throw new LoadingFailedException(modLoadingExceptions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ModContainer> buildMods(final IModFile modFile) {
|
private static 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);
|
||||||
@@ -333,14 +311,14 @@ public 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);
|
||||||
|
|
||||||
loadingExceptions.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
|
LOADING_EXCEPTIONS.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 ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap,
|
private static 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 {
|
||||||
@@ -352,7 +330,7 @@ public 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
|
||||||
loadingExceptions.add(mle);
|
LOADING_EXCEPTIONS.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();
|
||||||
}
|
}
|
||||||
@@ -366,15 +344,8 @@ public class ModLoader {
|
|||||||
return loadingStateValid;
|
return loadingStateValid;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated Use {@link #hasCompletedState(IModLoadingState)} instead */
|
public static boolean hasCompletedState(IModLoadingState state) {
|
||||||
@Deprecated(forRemoval = true)
|
return COMPLETED_STATES.contains(state);
|
||||||
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) {
|
||||||
@@ -382,7 +353,7 @@ public 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.get().getLoadedMods())
|
for (var mod : ModList.getLoadedMods())
|
||||||
mod.acceptEvent(generator.apply(mod));
|
mod.acceptEvent(generator.apply(mod));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,7 +362,7 @@ public 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.get().getLoadedMods())
|
for (var mod : ModList.getLoadedMods())
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,7 +371,7 @@ public 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 e;
|
return e;
|
||||||
}
|
}
|
||||||
for (var mod : ModList.get().getLoadedMods())
|
for (var mod : ModList.getLoadedMods())
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
@@ -408,8 +379,8 @@ public 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, e) -> ModLoadingContext.get().setActiveContainer(mc),
|
(mc, _) -> ModLoadingContext.get().setActiveContainer(mc),
|
||||||
(mc, e) -> ModLoadingContext.get().setActiveContainer(null)
|
(_, _) -> ModLoadingContext.get().setActiveContainer(null)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,19 +389,19 @@ public 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.get().getLoadedMods()) {
|
for (var mod : ModList.getLoadedMods()) {
|
||||||
pre.accept(mod, e);
|
pre.accept(mod, e);
|
||||||
mod.acceptEvent(e);
|
mod.acceptEvent(e);
|
||||||
post.accept(mod, e);
|
post.accept(mod, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ModLoadingWarning> getWarnings() {
|
public static List<ModLoadingWarning> getWarnings() {
|
||||||
return ImmutableList.copyOf(this.loadingWarnings);
|
return List.copyOf(LOADING_WARNINGS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addWarning(ModLoadingWarning warning) {
|
public static void addWarning(ModLoadingWarning warning) {
|
||||||
this.loadingWarnings.add(warning);
|
LOADING_WARNINGS.add(warning);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean runningDataGen = false;
|
private static boolean runningDataGen = false;
|
||||||
|
|||||||
@@ -32,24 +32,11 @@ 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.
|
||||||
*/
|
*/
|
||||||
@@ -58,11 +45,10 @@ 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 getActiveContainer();
|
return activeContainer == null
|
||||||
|
? ModList.getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!"))
|
||||||
|
: activeContainer;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -114,8 +100,7 @@ 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;
|
||||||
@@ -125,8 +110,7 @@ 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;
|
||||||
@@ -135,7 +119,6 @@ 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.ToIntFunction;
|
import java.util.function.IntSupplier;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of the {@link IModLoadingState} interface.
|
* Implementation of the {@link IModLoadingState} interface.
|
||||||
@@ -25,27 +25,26 @@ import java.util.function.ToIntFunction;
|
|||||||
* @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,
|
||||||
Function<ModList, String> message,
|
Supplier<String> message,
|
||||||
ToIntFunction<ModList> size,
|
IntSupplier size,
|
||||||
ModLoadingPhase phase,
|
ModLoadingPhase phase,
|
||||||
Optional<Consumer<ModList>> inlineRunnable,
|
@Nullable Runnable inlineRunnable,
|
||||||
Optional<IModStateTransition> transition
|
@Nullable IModStateTransition transition
|
||||||
) implements IModLoadingState {
|
) implements IModLoadingState {
|
||||||
@Override
|
@Override
|
||||||
public Optional<CompletableFuture<Void>> buildTransition(
|
public @Nullable 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
|
||||||
) {
|
) {
|
||||||
var transition = this.transition.orElse(null);
|
if (transition == null) return null;
|
||||||
return transition == null
|
return transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask);
|
||||||
? Optional.empty()
|
|
||||||
: Optional.ofNullable(transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,7 +59,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, ml -> "", ml -> 0, phase, Optional.empty(), Optional.empty());
|
return new ModLoadingState(name, previous, () -> "", () -> 0, phase, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -94,7 +93,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 Function<ModList, String> message, final ModLoadingPhase phase,
|
final Supplier<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);
|
||||||
}
|
}
|
||||||
@@ -113,7 +112,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 Consumer<ModList> inline) {
|
final Runnable inline) {
|
||||||
return of(name, phase).after(previous).withInline(inline);
|
return of(name, phase).after(previous).withInline(inline);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,23 +125,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)
|
||||||
&& Objects.equals(this.previous, that.previous);
|
&& this.previous.equals(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 + Objects.hashCode(previous);
|
result = 31 * result + previous.hashCode();
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Builder {
|
public static final 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 Function<ModList, String> message = null;
|
private @Nullable Supplier<String> message = null;
|
||||||
private ToIntFunction<ModList> size = null;
|
private @Nullable IntSupplier size = null;
|
||||||
|
|
||||||
private Builder(final String name, final ModLoadingPhase phase) {
|
private Builder(final String name, final ModLoadingPhase phase) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
@@ -155,28 +154,28 @@ public record ModLoadingState(
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder message(final String value) { return message(ml -> value); }
|
public Builder message(final String value) { return message(() -> value); }
|
||||||
public Builder message(final Function<ModList, String> value) {
|
public Builder message(final Supplier<String> value) {
|
||||||
this.message = value;
|
this.message = value;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder size(final int value) { return size(ml -> value); }
|
public Builder size(final int value) { return size(() -> value); }
|
||||||
public Builder size(final ToIntFunction<ModList> value) {
|
public Builder size(final IntSupplier 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 : ml -> "", size != null ? size : ml -> 0, phase, Optional.empty(), Optional.empty());
|
return new ModLoadingState(name, after, message != null ? message : () -> "", size != null ? size : () -> 0, phase, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModLoadingState withTransition(final IModStateTransition transition) {
|
public ModLoadingState withTransition(final IModStateTransition transition) {
|
||||||
return new ModLoadingState(name, after, message != null ? message : ml -> "Processing transition " + name, size != null ? size : ModList::size, phase, Optional.empty(), Optional.of(transition));
|
return new ModLoadingState(name, after, message != null ? message : () -> "Processing transition " + name, size != null ? size : ModList::size, phase, null, transition);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModLoadingState withInline(final Consumer<ModList> inline) {
|
public ModLoadingState withInline(final Runnable inline) {
|
||||||
return new ModLoadingState(name, after, message != null ? message : ml -> "Processing work " + name, size != null ? size : ml -> 0, phase, Optional.of(inline), Optional.empty());
|
return new ModLoadingState(name, after, message != null ? message : () -> "Processing work " + name, size != null ? size : () -> 0, phase, inline, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,41 +5,27 @@
|
|||||||
|
|
||||||
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
|
||||||
* Mod Info for mod with warning
|
* @param warningStage The stage where this warning was encountered
|
||||||
*/
|
* @param i18nMessage I18N message to use for display
|
||||||
private final IModInfo modInfo;
|
* @param context Context for message display
|
||||||
/**
|
*/
|
||||||
* The stage where this warning was encountered
|
public record ModLoadingWarning(IModInfo modInfo, ModLoadingStage warningStage, String i18nMessage, List<Object> context) {
|
||||||
*/
|
|
||||||
private final ModLoadingStage warningStage;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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) {
|
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
|
||||||
this.modInfo = modInfo;
|
this(modInfo, warningStage, i18nMessage, List.of(context));
|
||||||
this.warningStage = warningStage;
|
}
|
||||||
this.i18nMessage = i18nMessage;
|
|
||||||
this.context = Arrays.asList(context);
|
public ModLoadingWarning {
|
||||||
|
context = List.copyOf(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatToString() {
|
public String formatToString() {
|
||||||
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Stream.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,18 +15,19 @@ import java.util.function.Function;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@SuppressWarnings("UnstableApiUsage")
|
@SuppressWarnings("UnstableApiUsage")
|
||||||
public class ModStateManager {
|
public final class ModStateManager {
|
||||||
private final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
private ModStateManager() {}
|
||||||
|
private static final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
||||||
|
|
||||||
public ModStateManager() {
|
static {
|
||||||
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
||||||
this.stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, sce->{})
|
stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, _ -> {})
|
||||||
.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 List<IModLoadingState> getStates(final ModLoadingPhase phase) {
|
public static 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()));
|
||||||
|
|
||||||
@@ -40,7 +41,7 @@ public 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 IModLoadingState findState(final String stateName) {
|
public static 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
|
||||||
class ModStateTransitionHelper {
|
final 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,7 +62,30 @@ class ModStateTransitionHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
record FutureResult<V>(V value, Throwable exception){}
|
/// Same as [#completableFutureFromExceptionList(List)] but specialised for a single future
|
||||||
|
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());
|
||||||
@@ -76,25 +99,17 @@ 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((r, th)->null).thenApply(res -> list);
|
return CompletableFuture.allOf(results).handle((_, _)->null).thenApply(_ -> list);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static <T extends IModBusEvent> void addCompletableFutureTaskForModDispatch(
|
private static <T extends IModBusEvent> CompletableFuture<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.get().getLoadedMods()) {
|
for (var mod : ModList.getLoadedMods()) {
|
||||||
|
|
||||||
CompletableFuture<Void> parent = null;
|
CompletableFuture<Void> parent = null;
|
||||||
if (mod.dependencies.isEmpty()) {
|
if (mod.dependencies.isEmpty()) {
|
||||||
@@ -120,7 +135,7 @@ class ModStateTransitionHelper {
|
|||||||
handler.run();
|
handler.run();
|
||||||
mod.acceptEvent(eventGenerator.apply(mod));
|
mod.acceptEvent(eventGenerator.apply(mod));
|
||||||
}, executor)
|
}, executor)
|
||||||
.whenComplete((mc, exception) -> {
|
.whenComplete((_, 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);
|
||||||
@@ -129,20 +144,7 @@ class ModStateTransitionHelper {
|
|||||||
modFutures.put(mod.getModId(), dispatch);
|
modFutures.put(mod.getModId(), dispatch);
|
||||||
}
|
}
|
||||||
|
|
||||||
var dispatch = gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor);
|
return 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(
|
||||||
@@ -154,31 +156,25 @@ 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
|
||||||
) {
|
) {
|
||||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
CompletableFuture<Void> future;
|
||||||
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
|
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
|
||||||
|
|
||||||
@SuppressWarnings({ "removal", "unchecked" })
|
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
||||||
var events = transition.eventFunctionStream().get().map(f -> (EventGenerator<T>)f).toList();
|
CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF
|
||||||
for (int x = 0; x < events.size(); x++) {
|
.thenRunAsync(() -> progressBar.label(progressBar.name() + ": dispatching " + name), parallelExecutor);
|
||||||
var gen = events.get(x);
|
|
||||||
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = x == events.size() - 1
|
var eventGenerator = transition.eventFunction();
|
||||||
? transition.nextModLoadingStage()
|
if (eventGenerator != null) {
|
||||||
: ModLoadingStage::currentState;
|
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = transition.nextModLoadingStage();
|
||||||
addCompletableFutureTaskForModDispatch(transition, executor, futures, progressBar, gen, state);
|
future = addCompletableFutureTaskForModDispatch(executor, progressBar, eventGenerator, state);
|
||||||
|
|
||||||
|
final CompletableFuture<Void> eventDispatchCF = future.handle(FutureResult::new)
|
||||||
|
.thenCompose(ModStateTransitionHelper::completableFutureFromException);
|
||||||
|
postEventDispatchCF = postEventDispatchCF.thenComposeAsync(_ -> eventDispatchCF, parallelExecutor);
|
||||||
}
|
}
|
||||||
|
|
||||||
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
postEventDispatchCF = postEventDispatchCF.thenRun(() -> postSyncTask.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,25 +14,12 @@ import java.util.concurrent.locks.LockSupport;
|
|||||||
|
|
||||||
import static net.minecraftforge.fml.Logging.LOADING;
|
import static net.minecraftforge.fml.Logging.LOADING;
|
||||||
|
|
||||||
public class ModWorkManager {
|
public final 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 interface DrivenExecutor extends Executor {
|
public sealed interface DrivenExecutor extends Executor {
|
||||||
boolean selfDriven();
|
void drive(Runnable ticker);
|
||||||
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 {
|
||||||
@@ -40,8 +27,7 @@ public class ModWorkManager {
|
|||||||
this(new ConcurrentLinkedDeque<>());
|
this(new ConcurrentLinkedDeque<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
private boolean driveOne() {
|
||||||
public boolean driveOne() {
|
|
||||||
final Runnable task = tasks.pollFirst();
|
final Runnable task = tasks.pollFirst();
|
||||||
if (task != null) {
|
if (task != null) {
|
||||||
task.run();
|
task.run();
|
||||||
@@ -50,31 +36,30 @@ public class ModWorkManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean selfDriven() {
|
public void execute(final Runnable command) {
|
||||||
return false;
|
tasks.addLast(command);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void execute(final Runnable command) {
|
public void drive(Runnable ticker) {
|
||||||
tasks.addLast(command);
|
ticker.run();
|
||||||
|
while (true) {
|
||||||
|
if (!driveOne()) break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
||||||
@Override
|
|
||||||
public boolean selfDriven() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean driveOne() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void execute(final Runnable command) {
|
public void execute(final Runnable command) {
|
||||||
wrapped.execute(command);
|
wrapped.execute(command);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drive(Runnable ticker) {
|
||||||
|
// Park for a bit so other threads can schedule
|
||||||
|
LockSupport.parkNanos(PARK_TIME);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final SyncExecutor syncExecutor = new SyncExecutor();
|
private static final SyncExecutor syncExecutor = new SyncExecutor();
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public final class OptionalMod<T>
|
|||||||
private T getValue()
|
private T getValue()
|
||||||
{
|
{
|
||||||
if (!searched) {
|
if (!searched) {
|
||||||
this.value = ModList.get().<T>getModObjectById(this.modId).orElse(null);
|
this.value = ModList.<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, parallel) -> sync),
|
SYNC((sync, _) -> sync),
|
||||||
PARALLEL((sync, parallel) -> parallel);
|
PARALLEL((_, parallel) -> parallel);
|
||||||
|
|
||||||
private final BinaryOperator<Executor> selector;
|
private final BinaryOperator<Executor> selector;
|
||||||
|
|
||||||
|
|||||||
@@ -93,8 +93,8 @@ public class VersionChecker {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var mc = ModList.get().getModContainerById("minecraft");
|
var mc = ModList.getModContainerById("minecraft");
|
||||||
var forge = ModList.get().getModContainerById("forge");
|
var forge = ModList.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.get().getMods()) {
|
for (IModInfo info : ModList.getMods()) {
|
||||||
if (info.getUpdateURL().isPresent())
|
if (info.getUpdateURL().isPresent())
|
||||||
ret.add(info);
|
ret.add(info);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ 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.api.distmarker.Dist;
|
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||||
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;
|
||||||
@@ -19,57 +18,54 @@ import java.nio.file.Path;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
public class ConfigTracker {
|
public final 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");
|
||||||
public static final ConfigTracker INSTANCE = new ConfigTracker();
|
private static final ConcurrentHashMap<String, ModConfig> FILE_MAP = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentHashMap<String, ModConfig> fileMap;
|
private static final Map<ModConfig.Type, Set<ModConfig>> CONFIG_SETS = Map.of(
|
||||||
private final EnumMap<ModConfig.Type, Set<ModConfig>> configSets;
|
ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()),
|
||||||
private final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> configsByMod;
|
ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()),
|
||||||
|
ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>())
|
||||||
|
);
|
||||||
|
private static final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> CONFIGS_BY_MOD = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private ConfigTracker() {
|
static void trackConfig(final ModConfig config) {
|
||||||
this.fileMap = new ConcurrentHashMap<>();
|
if (FILE_MAP.containsKey(config.getFileName())) {
|
||||||
this.configSets = new EnumMap<>(ModConfig.Type.class);
|
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), FILE_MAP.get(config.getFileName()).getModId(), config.getModId());
|
||||||
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!");
|
||||||
}
|
}
|
||||||
this.fileMap.put(config.getFileName(), config);
|
FILE_MAP.put(config.getFileName(), config);
|
||||||
this.configSets.get(config.getType()).add(config);
|
CONFIG_SETS.get(config.getType()).add(config);
|
||||||
this.configsByMod.computeIfAbsent(config.getModId(), (k)->new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
|
CONFIGS_BY_MOD.computeIfAbsent(config.getModId(), _ -> 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 void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
public static void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
||||||
for (ModConfig config : this.configSets.get(type)) {
|
for (ModConfig config : CONFIG_SETS.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 void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
public static void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
||||||
for (ModConfig config : this.configSets.get(type)) {
|
for (ModConfig config : CONFIG_SETS.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 void forceUnload() {
|
public static 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
|
||||||
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
|
if (FMLEnvironment.dist.isClient())
|
||||||
this.unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
unloadConfigs(ModConfig.Type.CLIENT, 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();
|
||||||
@@ -96,8 +92,8 @@ public class ConfigTracker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loadDefaultServerConfigs() {
|
public static void loadDefaultServerConfigs() {
|
||||||
configSets.get(ModConfig.Type.SERVER).forEach(modConfig -> {
|
CONFIG_SETS.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);
|
||||||
@@ -105,16 +101,16 @@ public class ConfigTracker {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getConfigFileName(String modId, ModConfig.Type type) {
|
public static String getConfigFileName(String modId, ModConfig.Type type) {
|
||||||
return Optional.ofNullable(configsByMod.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
return Optional.ofNullable(CONFIGS_BY_MOD.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
||||||
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<ModConfig.Type, Set<ModConfig>> configSets() {
|
public static Map<ModConfig.Type, Set<ModConfig>> configSets() {
|
||||||
return configSets;
|
return CONFIG_SETS;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentHashMap<String, ModConfig> fileMap() {
|
public static ConcurrentHashMap<String, ModConfig> fileMap() {
|
||||||
return fileMap;
|
return FILE_MAP;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,7 @@ 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,8 +13,6 @@ 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
|
||||||
{
|
{
|
||||||
@@ -31,7 +29,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.INSTANCE.trackConfig(this);
|
ConfigTracker.trackConfig(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
|
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
|
||||||
@@ -40,8 +38,9 @@ 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 String.format(Locale.ROOT, "%s-%s.toml", modId, type.extension());
|
return modId + '-' + type.extension() + ".toml";
|
||||||
}
|
}
|
||||||
|
|
||||||
public Type getType() {
|
public Type getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,67 +1,74 @@
|
|||||||
import net.minecraftforge.gradleutils.PomUtils
|
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||||
|
import org.gradle.internal.os.OperatingSystem
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
|
id 'jvm-test-suite'
|
||||||
id 'maven-publish'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.licenser'
|
alias libs.plugins.licenser
|
||||||
id 'net.minecraftforge.gradleutils'
|
alias libs.plugins.gradleutils
|
||||||
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: rootProject.file('build_shared.gradle')
|
|
||||||
|
|
||||||
import org.gradle.internal.os.OperatingSystem
|
|
||||||
switch (OperatingSystem.current()) {
|
switch (OperatingSystem.current()) {
|
||||||
case OperatingSystem.LINUX:
|
case OperatingSystem.LINUX:
|
||||||
project.ext.lwjglNatives = "natives-linux"
|
project.ext.lwjglNatives = "natives-linux"
|
||||||
break
|
break
|
||||||
case OperatingSystem.MAC_OS:
|
case OperatingSystem.MAC_OS:
|
||||||
project.ext.lwjglNatives = "natives-macos"
|
project.ext.lwjglNatives = "natives-macos"
|
||||||
break
|
break
|
||||||
case OperatingSystem.WINDOWS:
|
case OperatingSystem.WINDOWS:
|
||||||
project.ext.lwjglNatives = "natives-windows"
|
project.ext.lwjglNatives = "natives-windows"
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
gradleutils.displayName = 'FML Early Display'
|
||||||
|
final vendor = 'Forge Development LLC'
|
||||||
|
description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.'
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
withSourcesJar()
|
withSourcesJar()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
license {
|
||||||
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
|
}
|
||||||
|
|
||||||
|
changelog {
|
||||||
|
from changelogBase
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
compileOnly(libs.jetbrains.annotations)
|
compileOnly libs.jetbrains.annotations
|
||||||
implementation(project(':fmlloader'))
|
|
||||||
implementation(project(':fmlcore'))
|
implementation projects.fmlloader
|
||||||
implementation(libs.bundles.lwjgl)
|
implementation projects.fmlcore
|
||||||
implementation('org.slf4j:slf4j-api:1.8.0-beta4')
|
implementation libs.bundles.lwjgl
|
||||||
implementation(libs.jopt.simple)
|
implementation earlyDisplayLibs.slf4j.api
|
||||||
testImplementation('org.junit.jupiter:junit-jupiter-api:5.8.2')
|
implementation libs.jopt.simple
|
||||||
testImplementation('org.powermock:powermock-core:2.0.9')
|
|
||||||
testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.8.2')
|
|
||||||
testRuntimeOnly('org.slf4j:slf4j-jdk14:1.8.0-beta4')
|
|
||||||
testRuntimeOnly("org.lwjgl:lwjgl::$lwjglNatives")
|
|
||||||
testRuntimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives")
|
|
||||||
testRuntimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives")
|
|
||||||
testRuntimeOnly("org.lwjgl:lwjgl-stb::$lwjglNatives")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('test', Test).configure {
|
// See gradle/gradle#35070 (https://github.com/gradle/gradle/issues/35070)
|
||||||
useJUnitPlatform()
|
// 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() } }
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('jar', Jar).configure {
|
testing.suites.named('test', JvmTestSuite) {
|
||||||
manifest {
|
useJUnitJupiter('5.8.2')
|
||||||
attributes([
|
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.earlydisplay',
|
dependencies {
|
||||||
'Forge-Module-Layer': 'boot'
|
implementation earlyDisplayTestLibs.powermock.core
|
||||||
] as LinkedHashMap)
|
runtimeOnly earlyDisplayLibs.slf4j.jdk14
|
||||||
attributes([
|
runtimeOnly.bundle lwjglTestLibs
|
||||||
'Specification-Title': 'FML Early Display',
|
|
||||||
'Specification-Vendor': 'Forge Development LLC',
|
|
||||||
'Specification-Version': '1',
|
|
||||||
'Implementation-Title': 'FML Early Display',
|
|
||||||
'Implementation-Vendor': 'Forge Development LLC',
|
|
||||||
'Implementation-Version': '1.0'
|
|
||||||
] as LinkedHashMap, 'net/minecraftforge/fml/earlydisplay/')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,24 +76,42 @@ tasks.withType(JavaCompile).configureEach {
|
|||||||
options.compilerArgs << '-Xlint:unchecked'
|
options.compilerArgs << '-Xlint:unchecked'
|
||||||
}
|
}
|
||||||
|
|
||||||
license {
|
tasks.named('jar', Jar) {
|
||||||
header = rootProject.file('LICENSE-header.txt')
|
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 {
|
publishing {
|
||||||
publications.register('mavenJava', MavenPublication).configure {
|
|
||||||
from components.java
|
|
||||||
artifactId = 'fmlearlydisplay'
|
|
||||||
pom {
|
|
||||||
name = project.name
|
|
||||||
description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.'
|
|
||||||
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
|
||||||
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
|
|
||||||
license PomUtils.Licenses.LGPLv2_1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
maven gradleutils.publishingForgeMaven
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
-15
@@ -46,8 +46,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
import java.util.function.BiConsumer;
|
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.Collector;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -70,7 +68,7 @@ import static org.lwjgl.opengl.GL32C.*;
|
|||||||
* 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}, {3,2}};
|
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 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);
|
||||||
|
|
||||||
@@ -115,6 +113,14 @@ 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();
|
||||||
@@ -139,7 +145,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
this.colourScheme = ColourScheme.BLACK;
|
this.colourScheme = ColourScheme.BLACK;
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
// check the options file for the colour scheme
|
// check the options file for the color 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) {
|
||||||
@@ -314,17 +320,18 @@ 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", false);
|
var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", 0);
|
||||||
if (res) {
|
if (res != 0) {
|
||||||
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", false);
|
TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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.
|
||||||
*
|
*
|
||||||
@@ -460,7 +467,9 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
this.winWidth = x[0];
|
this.winWidth = x[0];
|
||||||
this.winHeight = y[0];
|
this.winHeight = y[0];
|
||||||
|
|
||||||
|
// Setting the window position isn't supported on wayland, so check the error here
|
||||||
glfwSetWindowPos(window, (vidmode.width() - this.winWidth) / 2 + monitorX, (vidmode.height() - this.winHeight) / 2 + monitorY);
|
glfwSetWindowPos(window, (vidmode.width() - this.winWidth) / 2 + monitorX, (vidmode.height() - this.winHeight) / 2 + monitorY);
|
||||||
|
handleLastGLFWError();
|
||||||
|
|
||||||
// Attempt setting the icon
|
// Attempt setting the icon
|
||||||
// int[] channels = new int[1];
|
// int[] channels = new int[1];
|
||||||
@@ -483,7 +492,10 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
// Show the window
|
// Show the window
|
||||||
glfwShowWindow(window);
|
glfwShowWindow(window);
|
||||||
|
// Getting the window position isn't supported on wayland, so check the error here
|
||||||
glfwGetWindowPos(window, x, y);
|
glfwGetWindowPos(window, x, y);
|
||||||
|
handleLastGLFWError();
|
||||||
|
|
||||||
this.winX = x[0];
|
this.winX = x[0];
|
||||||
this.winY = y[0];
|
this.winY = y[0];
|
||||||
glfwGetFramebufferSize(window, x, y);
|
glfwGetFramebufferSize(window, x, y);
|
||||||
@@ -492,6 +504,18 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
glfwPollEvents();
|
glfwPollEvents();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void handleLastGLFWError() {
|
||||||
|
handleLastGLFWError((error, description) -> {
|
||||||
|
if (error == GLFW_FEATURE_UNAVAILABLE) {
|
||||||
|
// suppress window pos errors for unsupported platforms (wayland)
|
||||||
|
LOGGER.debug(String.format("Suppressing GLFW error: [0x%X]%s", error, description));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalStateException(String.format("GLFW error: [0x%X]%s", error, description));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private void winResize(long window, int width, int height) {
|
private void winResize(long window, int width, int height) {
|
||||||
if (window == this.window && width != 0 && height != 0) {
|
if (window == this.window && width != 0 && height != 0) {
|
||||||
this.winWidth = width;
|
this.winWidth = width;
|
||||||
@@ -529,7 +553,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
*
|
*
|
||||||
* @return the Window we own.
|
* @return the Window we own.
|
||||||
*/
|
*/
|
||||||
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 long monitorSupplier, 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);
|
||||||
@@ -549,11 +573,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();
|
||||||
}
|
}
|
||||||
@@ -563,7 +587,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
glfwMakeContextCurrent(window);
|
glfwMakeContextCurrent(window);
|
||||||
// Set the title to what the game wants
|
// Set the title to what the game wants
|
||||||
glfwSetWindowTitle(window, title.get());
|
glfwSetWindowTitle(window, title);
|
||||||
glfwSwapInterval(0);
|
glfwSwapInterval(0);
|
||||||
// Clean up our hooks
|
// Clean up our hooks
|
||||||
glfwSetFramebufferSizeCallback(window, null).free();
|
glfwSetFramebufferSizeCallback(window, null).free();
|
||||||
@@ -649,4 +673,4 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
this.context.elementShader().close();
|
this.context.elementShader().close();
|
||||||
SimpleBufferBuilder.destroy();
|
SimpleBufferBuilder.destroy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+8
-8
@@ -116,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, fnt, ctx)->
|
return new RenderElement(RenderElement.initializeText(font, (bb, _, 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)))));
|
||||||
@@ -178,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()}, f->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()}, _->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()}, f -> colour, f -> 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()}, _ -> colour, _ -> new float[]{0f, pm.progress()});
|
||||||
}
|
}
|
||||||
Renderer label = (bb, ctx, frame) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx);
|
Renderer label = (bb, ctx, _) -> 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) {
|
||||||
@@ -198,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()}, f -> colour, f -> new float[]{0f, pi.memory()});
|
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 width = font.stringWidth(pi.text());
|
var width = font.stringWidth(pi.text());
|
||||||
Renderer label = (bb, ctx, frame) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx);
|
Renderer label = (bb, ctx, _) -> 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,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, frame) -> renderText(font, textGenerator, bb, context);
|
return (bb, context, _) -> 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) {
|
||||||
@@ -262,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, context) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour));
|
return (bb, font, _) -> 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) {
|
||||||
|
|||||||
+144
-100
@@ -1,69 +1,75 @@
|
|||||||
import net.minecraftforge.gradleutils.PomUtils
|
import groovy.transform.CompileDynamic
|
||||||
|
import groovy.transform.CompileStatic
|
||||||
|
import groovy.transform.PackageScope
|
||||||
|
import net.minecraftforge.forgedev.legacy.tasks.JarJarMetadataOptions
|
||||||
|
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||||
|
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
|
id 'jvm-test-suite'
|
||||||
id 'maven-publish'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.licenser'
|
alias libs.plugins.licenser
|
||||||
id 'net.minecraftforge.gradleutils'
|
alias libs.plugins.gradleutils
|
||||||
alias(libs.plugins.apt)
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
alias libs.plugins.apt
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: rootProject.file('build_shared.gradle')
|
gradleutils.displayName = 'FMLLoader'
|
||||||
|
final vendor = 'Forge Development LLC'
|
||||||
configurations.forEach{ it.transitive = false }
|
description = 'Modifications to Minecraft to enable mod developers.'
|
||||||
|
|
||||||
dependencies {
|
|
||||||
compileOnly(libs.jetbrains.annotations)
|
|
||||||
|
|
||||||
api(libs.bundles.asm) // Needed by all the black magic
|
|
||||||
api(libs.forgespi)
|
|
||||||
api(libs.mergetool.api)
|
|
||||||
api(libs.log4j.api)
|
|
||||||
api(libs.slf4j.api)
|
|
||||||
api(libs.guava)
|
|
||||||
api(libs.gson)
|
|
||||||
api(libs.maven.artifact)
|
|
||||||
api(libs.apache.commons)
|
|
||||||
api(libs.bundles.night.config)
|
|
||||||
api(libs.modlauncher)
|
|
||||||
api(libs.mojang.logging)
|
|
||||||
api(libs.jarjar.selector)
|
|
||||||
api(libs.jarjar.meta)
|
|
||||||
|
|
||||||
implementation(libs.jopt.simple)
|
|
||||||
implementation(libs.securemodules)
|
|
||||||
implementation(libs.accesstransformers)
|
|
||||||
implementation(libs.terminalconsoleappender)
|
|
||||||
implementation(libs.jimfs)
|
|
||||||
implementation(libs.roimfs)
|
|
||||||
|
|
||||||
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
|
|
||||||
implementation(libs.log4j.core)
|
|
||||||
annotationProcessor(libs.bundles.log4j)
|
|
||||||
|
|
||||||
testCompileOnly(libs.jetbrains.annotations)
|
|
||||||
testRuntimeOnly(libs.bootstrap)
|
|
||||||
}
|
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
withSourcesJar()
|
withSourcesJar()
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('jar', Jar).configure {
|
license {
|
||||||
manifest {
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
attributes([
|
}
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.fmlloader',
|
|
||||||
'Forge-Module-Layer': 'boot'
|
changelog {
|
||||||
] as LinkedHashMap)
|
from changelogBase
|
||||||
attributes([
|
}
|
||||||
'Specification-Title': 'FMLLoader',
|
|
||||||
'Specification-Vendor': 'Forge Development LLC',
|
dependencies {
|
||||||
'Specification-Version': '1',
|
compileOnly libs.jetbrains.annotations
|
||||||
'Implementation-Title': 'FMLLoader',
|
|
||||||
'Implementation-Vendor': 'Forge Development LLC',
|
// TODO [FMLLoader] Figure out a better way to lock transitive dependencies to the explicit versions shipped by the isntaller
|
||||||
'Implementation-Version': FORGE_VERSION
|
api(libs.bundles.asm ){ transitive = false } // Needed by all the black magic
|
||||||
] as LinkedHashMap, 'net/minecraftforge/fml/loading/')
|
api(libs.forgespi ){ transitive = false }
|
||||||
|
api(libs.mergetool.api ){ transitive = false }
|
||||||
|
api(libs.log4j.api ){ transitive = false }
|
||||||
|
api(libs.slf4j.api ){ transitive = false }
|
||||||
|
api(libs.guava ){ transitive = false }
|
||||||
|
api(libs.gson ){ transitive = false }
|
||||||
|
api(libs.maven.artifact ){ transitive = false }
|
||||||
|
api(libs.apache.commons ){ transitive = false }
|
||||||
|
api(libs.bundles.night.config){ transitive = false }
|
||||||
|
api(libs.modlauncher ){ transitive = false }
|
||||||
|
api(libs.mojang.logging ){ transitive = false }
|
||||||
|
api(libs.jarjar.selector ){ transitive = false }
|
||||||
|
api(libs.jarjar.meta ){ transitive = false }
|
||||||
|
|
||||||
|
implementation(libs.jopt.simple ){ transitive = false }
|
||||||
|
implementation(libs.securemodules ){ transitive = false }
|
||||||
|
implementation(libs.accesstransformers ){ transitive = false }
|
||||||
|
implementation(libs.terminalconsoleappender){ transitive = false }
|
||||||
|
implementation(libs.jimfs ){ transitive = false }
|
||||||
|
implementation(libs.roimfs ){ transitive = false }
|
||||||
|
|
||||||
|
// 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 }
|
||||||
|
annotationProcessor(libs.bundles.log4j){ transitive = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
testing.suites.named('test', JvmTestSuite) {
|
||||||
|
dependencies {
|
||||||
|
compileOnly libs.jetbrains.annotations
|
||||||
|
runtimeOnly libs.bootstrap
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,39 +77,81 @@ tasks.withType(JavaCompile).configureEach {
|
|||||||
options.compilerArgs << '-Xlint:unchecked'
|
options.compilerArgs << '-Xlint:unchecked'
|
||||||
}
|
}
|
||||||
|
|
||||||
license {
|
tasks.named('jar', Jar) {
|
||||||
header = rootProject.file('LICENSE-header.txt')
|
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 {
|
publishing {
|
||||||
publications.register('mavenJava', MavenPublication).configure {
|
|
||||||
from components.java
|
|
||||||
artifactId = 'fmlloader'
|
|
||||||
pom {
|
|
||||||
name = project.name
|
|
||||||
description = 'Modifactions to Minecraft to enable mod developers.'
|
|
||||||
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
|
||||||
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
|
|
||||||
license PomUtils.Licenses.LGPLv2_1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
maven gradleutils.publishingForgeMaven
|
maven gradleutils.publishingForgeMaven
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register('writeForgeVersionJson') {
|
publications.register('mavenJava', MavenPublication) {
|
||||||
doLast {
|
changelog.publish(it)
|
||||||
file('src/main/resources/forge_version.json').json = [
|
gradleutils.promote(it)
|
||||||
forge: FORGE_VERSION,
|
|
||||||
mc: MC_VERSION,
|
from components.java
|
||||||
mcp: MCP_VERSION
|
|
||||||
]
|
pom {
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.register('jarJarOptionsJson', net.minecraftforge.forge.tasks.JarJarMetadataOptions) {
|
// 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
|
||||||
|
|
||||||
|
outputFile = file('src/main/resources/forge_version.json')
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('jarJarOptionsJson', JarJarMetadataOptions) {
|
||||||
metadataFile = project.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')
|
||||||
@@ -118,29 +166,25 @@ tasks.register('jarJarOptionsJson', net.minecraftforge.forge.tasks.JarJarMetadat
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('generateResources').configure {
|
tasks.named('generateResources') {
|
||||||
dependsOn('eclipseJdt')
|
dependsOn(
|
||||||
dependsOn('eclipseJdtApt')
|
tasks.named('eclipseJdt'),
|
||||||
dependsOn('eclipseFactorypath')
|
tasks.named('eclipseJdtApt'),
|
||||||
dependsOn('writeForgeVersionJson')
|
tasks.named('eclipseFactorypath'),
|
||||||
dependsOn('jarJarOptionsJson')
|
tasks.named('writeForgeVersionJson', WriteForgeVersionJson),
|
||||||
|
tasks.named('jarJarOptionsJson')
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('sourcesJar') {
|
eclipse.classpath {
|
||||||
dependsOn('jarJarOptionsJson')
|
// We need to set the default output directory for the log4j annotation processor
|
||||||
}
|
// Ideally we'd just set the value, but the eclipse plugin deduplicates the output directories
|
||||||
|
// So we have to do a hacky whenMerged
|
||||||
eclipse {
|
//defaultOutputDir = file('bin/main')
|
||||||
classpath {
|
file.whenMerged {
|
||||||
// We need to set the default output directory for the log4j annotation processor
|
entries.each { entry ->
|
||||||
// Ideally we'd just set the value, but the eclipse plugin deduplicates the output directories
|
if (entry.kind == 'output' && entry.hasProperty('path'))
|
||||||
// So we have to do a hacky whenMerged
|
entry.path = 'bin/main'
|
||||||
//defaultOutputDir = file('bin/main')
|
}
|
||||||
file.whenMerged {
|
|
||||||
entries.each { entry ->
|
|
||||||
if (entry.kind == 'output' && entry.hasProperty('path'))
|
|
||||||
entry.path = 'bin/main'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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.get().getMods().size() > 2; // 2: forge, minecraft
|
private static final boolean ANY_MODS = LoadingModList.getMods().size() > 2; // 2: forge, minecraft
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -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, (action, path, incorrectValue, correctedValue) ->
|
configSpec.correct(configData, (_, 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(), v->naming);
|
environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), _->naming);
|
||||||
environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), v->dist);
|
environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), _->dist);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Keys {
|
public static class Keys {
|
||||||
|
|||||||
@@ -30,13 +30,11 @@ 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 class FMLLoader {
|
public final 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();
|
||||||
@@ -151,16 +149,11 @@ public class FMLLoader {
|
|||||||
|
|
||||||
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
|
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
|
||||||
moduleLayerManager = layerManager;
|
moduleLayerManager = layerManager;
|
||||||
languageLoadingProvider = new LanguageLoadingProvider();
|
LanguageLoadingProvider.reload();
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -180,10 +173,6 @@ public 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,7 +12,6 @@ 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;
|
||||||
@@ -42,7 +41,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(), k->ModFile::new);
|
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), _->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,8 +10,13 @@ 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;
|
||||||
@@ -41,18 +46,64 @@ 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");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
|
private static String findBackend(String[] arguments) {
|
||||||
return provider.setupMinecraftWindow(width, height, title, monitor);
|
// Try and parse from the command line arguments
|
||||||
|
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 long monitor, final Supplier<Object> backend) {
|
||||||
|
return provider.setupMinecraftWindow(width, height, title, monitor, 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) {
|
||||||
@@ -83,7 +134,7 @@ public class ImmediateWindowHandler {
|
|||||||
earlyProgress.label(message);
|
earlyProgress.label(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record DummyProvider() implements ImmediateWindowProvider {
|
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;
|
||||||
@@ -104,9 +155,9 @@ public class ImmediateWindowHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
|
public long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier<Object> backend) {
|
||||||
try {
|
try {
|
||||||
var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, monitor);
|
var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, monitor, backend);
|
||||||
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);
|
||||||
|
|||||||
+26
-3
@@ -8,8 +8,6 @@ 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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,11 +24,36 @@ 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.
|
||||||
*
|
*
|
||||||
@@ -66,7 +89,7 @@ public interface ImmediateWindowProvider {
|
|||||||
* @param monitor This is the monitor it should appear on.
|
* @param monitor This is the monitor it should appear on.
|
||||||
* @return The window id
|
* @return The window id
|
||||||
*/
|
*/
|
||||||
long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor);
|
long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier<Object> backend);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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
|
||||||
|
|||||||
+11
-19
@@ -18,7 +18,6 @@ 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;
|
||||||
@@ -28,43 +27,36 @@ 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 class LanguageLoadingProvider {
|
public final class LanguageLoadingProvider {
|
||||||
public void forEach(Consumer<IModLanguageProvider> consumer) {
|
public static void forEach(Consumer<IModLanguageProvider> consumer) {
|
||||||
providers.forEach(consumer);
|
providers.forEach(consumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) {
|
public static <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) {
|
||||||
return providers.stream().map(function);
|
return providers.stream().map(function);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reload() {
|
public static 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 SHIT *
|
* INTERNAL *
|
||||||
*==========================================================================*/
|
*==========================================================================*/
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private final ServiceLoader<IModLanguageProvider> serviceLoader;
|
private static final ServiceLoader<IModLanguageProvider> serviceLoader;
|
||||||
private final List<IModLanguageProvider> providers = new ArrayList<>();
|
private static final ArrayList<IModLanguageProvider> providers = new ArrayList<>();
|
||||||
private final Map<String, Wrapper> providersByName = new HashMap<>();
|
private static final HashMap<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) {}
|
||||||
|
|
||||||
LanguageLoadingProvider() {
|
static {
|
||||||
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 void loadLanguageProviders() {
|
private static void loadLanguageProviders() {
|
||||||
providers.clear();
|
providers.clear();
|
||||||
providersByName.clear();
|
providersByName.clear();
|
||||||
|
|
||||||
@@ -97,7 +89,7 @@ public class LanguageLoadingProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public IModLanguageProvider findLanguage(ModFile mod, String language, VersionRange versionRange) {
|
public static 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,118 +5,46 @@
|
|||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
/// Master list of all mods in the loading context
|
||||||
|
public sealed interface LoadingModList permits LoadingModListImpl {
|
||||||
import com.mojang.logging.LogUtils;
|
static ModFileInfo getModFileById(String modId) {
|
||||||
|
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<>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static LoadingModList of(List<ModFile> modFiles, List<ModInfo> sortedList, final EarlyLoadingException earlyLoadingException) {
|
static List<ModFileInfo> getModFiles() {
|
||||||
INSTANCE = new LoadingModList(modFiles, sortedList);
|
return get().getModFiles();
|
||||||
if (earlyLoadingException != null)
|
|
||||||
INSTANCE.preLoadErrors.add(earlyLoadingException);
|
|
||||||
return INSTANCE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static LoadingModList get() {
|
static List<ModInfo> getMods() {
|
||||||
return INSTANCE;
|
return get().getMods();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addAccessTransformers() {
|
static @Nullable Path findResource(String className) {
|
||||||
var errors = new ArrayList<ExceptionData>();
|
for (ModFileInfo modFileInfo : get().getModFiles()) {
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModFileInfo getModFileById(String modid) {
|
static List<EarlyLoadingException> getErrors() {
|
||||||
return this.fileById.get(modid);
|
return get().getErrors();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ModInfo> getMods() {
|
static List<IModFile> getBrokenFiles() {
|
||||||
return this.sortedList;
|
return get().getBrokenFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<EarlyLoadingException> getErrors() {
|
private static LoadingModListImpl get() {
|
||||||
return preLoadErrors;
|
return LoadingModListImpl.get();
|
||||||
}
|
|
||||||
|
|
||||||
public void setBrokenFiles(final List<IModFile> brokenFiles) {
|
|
||||||
this.brokenFiles = brokenFiles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<IModFile> getBrokenFiles() {
|
|
||||||
return this.brokenFiles;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
* 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,7 +7,6 @@ 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,7 +6,6 @@
|
|||||||
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 class ModSorter {
|
public final class ModSorter {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
|
|
||||||
private record State(List<ModFile> files, List<ModInfo> mods) {}
|
record State(List<ModFile> files, List<ModInfo> mods) {}
|
||||||
|
|
||||||
private ModSorter() {}
|
private ModSorter() {}
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ public 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 LoadingModList.of(systemMods.files(), systemMods.mods(), e);
|
return LoadingModListImpl.init(systemMods, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
var named = new HashMap<String, ModInfo>();
|
var named = new HashMap<String, ModInfo>();
|
||||||
@@ -66,15 +66,15 @@ public 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 LoadingModList.of(systemMods.files(), systemMods.mods(), new EarlyLoadingException("failure to validate mod list", null, failedList));
|
return LoadingModListImpl.init(systemMods, 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 LoadingModList.of(sorted.files(), sorted.mods(), null);
|
return LoadingModListImpl.init(sorted, 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 LoadingModList.of(systemMods.files(), systemMods.mods(), e);
|
return LoadingModListImpl.init(systemMods, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ 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() {
|
||||||
@@ -45,11 +44,17 @@ 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;
|
||||||
|
|
||||||
@@ -57,7 +62,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;
|
return YAY; // mod classes might have @OnlyIn, so parse them in dev to find out and throw if they do
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -66,29 +71,14 @@ 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 (!annotations.isEmpty()) {
|
if (isNonMinecraftClass && !annotations.isEmpty())
|
||||||
if (isNonMinecraftClass) {
|
throw new UnsupportedOperationException("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("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) {
|
||||||
@@ -121,12 +111,8 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
itr.remove();
|
itr.remove();
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
if (isNonMinecraftClass) {
|
if (isNonMinecraftClass)
|
||||||
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");
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,12 +125,8 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
lambdaGatherer.accept(method);
|
lambdaGatherer.accept(method);
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
if (isNonMinecraftClass) {
|
if (isNonMinecraftClass)
|
||||||
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");
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,18 +207,6 @@ 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/");
|
||||||
}
|
}
|
||||||
@@ -250,7 +220,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class LambdaGatherer extends MethodVisitor {
|
private static final 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,6 +12,7 @@ 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,6 +26,7 @@ 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,19 +115,22 @@ public final class UniqueModListBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static ArtifactVersion getVersion(final ModFile mf) {
|
private static ArtifactVersion getVersion(final ModFile mf) {
|
||||||
if (mf.getModFileInfo() == null || mf.getModInfos() == null || mf.getModInfos().isEmpty()) {
|
List<IModInfo> modInfos;
|
||||||
|
if (mf.getModFileInfo() == null || (modInfos = mf.getModInfos()) == null || modInfos.isEmpty()) {
|
||||||
return mf.getJarVersion();
|
return mf.getJarVersion();
|
||||||
}
|
}
|
||||||
|
|
||||||
return mf.getModInfos().getFirst().getVersion();
|
return modInfos.getFirst().getVersion();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String getModId(ModFile modFile) {
|
private static String getModId(ModFile modFile) {
|
||||||
if (modFile.getModFileInfo() == null || modFile.getModFileInfo().getMods().isEmpty()) {
|
var modFileInfo = modFile.getModFileInfo();
|
||||||
|
List<IModInfo> mods;
|
||||||
|
if (modFileInfo == null || (mods = modFileInfo.getMods()).isEmpty()) {
|
||||||
return modFile.getSecureJar().name();
|
return modFile.getSecureJar().name();
|
||||||
}
|
}
|
||||||
|
|
||||||
return modFile.getModFileInfo().getMods().getFirst().getModId();
|
return mods.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,7 +13,6 @@ 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 {
|
||||||
@@ -32,15 +31,6 @@ 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);
|
||||||
|
|||||||
+2
-15
@@ -7,7 +7,6 @@ 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;
|
||||||
@@ -17,8 +16,7 @@ import java.time.Instant;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
public class BackgroundScanHandler
|
public final class BackgroundScanHandler {
|
||||||
{
|
|
||||||
private enum ScanStatus {
|
private enum ScanStatus {
|
||||||
NOT_STARTED,
|
NOT_STARTED,
|
||||||
RUNNING,
|
RUNNING,
|
||||||
@@ -33,7 +31,6 @@ public 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;
|
||||||
@@ -58,7 +55,7 @@ public 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((r, t) -> addCompletedFile(file, t));
|
if (DEBUG) future = future.whenComplete((_, t) -> addCompletedFile(file, t));
|
||||||
file.setFutureScanResult(future);
|
file.setFutureScanResult(future);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,16 +66,6 @@ public 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/obfuscate/DontObfuscate.class");
|
var minecraft = getPathFromResource(cl, "net/minecraft/world/item/Item.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((f,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed
|
INVALIDZIP((_,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 (f, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false);
|
return (_, 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, id -> new ArrayList<>()).add(entry);
|
ids.computeIfAbsent(entry.coord, _ -> 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(jar -> meta, paths);
|
var mcjar = SecureJar.from(_ -> 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);
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -41,9 +41,10 @@ public final class ModDiscoverer {
|
|||||||
|
|
||||||
@SuppressWarnings("removal")
|
@SuppressWarnings("removal")
|
||||||
public static ModValidator discoverMods(Map<String, ?> arguments) {
|
public static ModValidator discoverMods(Map<String, ?> arguments) {
|
||||||
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), v->ModsFolderLocator::new);
|
var env = Launcher.INSTANCE.environment();
|
||||||
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{}));
|
env.computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), _ -> ModsFolderLocator::new);
|
||||||
final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow();
|
env.computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), _ -> StartupNotificationManager.locatorConsumer().orElse(_ -> {}));
|
||||||
|
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.FMLLoader;
|
import net.minecraftforge.fml.loading.LanguageLoadingProvider;
|
||||||
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,7 +25,6 @@ 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;
|
||||||
@@ -48,8 +47,7 @@ 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 Path accessTransformer;
|
private List<Path> accessTransformers = List.of();
|
||||||
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;
|
||||||
@@ -92,11 +90,6 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -111,7 +104,6 @@ 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()) {
|
||||||
@@ -181,9 +173,8 @@ 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 = services.findLanguage(this, spec.languageName(), spec.acceptedVersions());
|
var service = LanguageLoadingProvider.findLanguage(this, spec.languageName(), spec.acceptedVersions());
|
||||||
lst.add(service);
|
lst.add(service);
|
||||||
}
|
}
|
||||||
this.loaders = List.copyOf(lst);
|
this.loaders = List.copyOf(lst);
|
||||||
|
|||||||
+16
-5
@@ -6,11 +6,13 @@
|
|||||||
package net.minecraftforge.fml.loading.moddiscovery;
|
package net.minecraftforge.fml.loading.moddiscovery;
|
||||||
|
|
||||||
import com.electronwill.nightconfig.core.file.FileConfig;
|
import com.electronwill.nightconfig.core.file.FileConfig;
|
||||||
|
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
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.locating.IModFile;
|
import net.minecraftforge.forgespi.locating.IModFile;
|
||||||
import net.minecraftforge.forgespi.locating.ModFileFactory;
|
import net.minecraftforge.forgespi.locating.ModFileFactory;
|
||||||
|
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
@@ -24,6 +26,7 @@ public class ModFileParser {
|
|||||||
return parser.build(modFile);
|
return parser.build(modFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Note: Although @Nullable, several other places in FML assume ModFileInfo is not null. Keep this in mind
|
||||||
public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) {
|
public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) {
|
||||||
ModFile modFile = (ModFile) imodFile;
|
ModFile modFile = (ModFile) imodFile;
|
||||||
LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath());
|
LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath());
|
||||||
@@ -32,11 +35,19 @@ 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;
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
|
||||||
|
fileConfig.load();
|
||||||
|
fileConfig.close();
|
||||||
|
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
|
||||||
|
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
|
||||||
|
} catch (ParsingException e) { // Handle landmine toml errors, e.g. incorrectly ported mods.
|
||||||
|
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.");
|
||||||
|
} 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.");
|
||||||
|
}
|
||||||
|
|
||||||
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
|
|
||||||
fileConfig.load();
|
|
||||||
fileConfig.close();
|
|
||||||
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
|
|
||||||
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+7
-7
@@ -31,7 +31,6 @@ 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;
|
||||||
|
|
||||||
@@ -87,7 +86,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 : this.loadingModList.getModFiles())
|
for (var info : 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
|
||||||
@@ -124,11 +123,12 @@ public class ModValidator {
|
|||||||
var allErrors = new ArrayList<>(errors);
|
var allErrors = new ArrayList<>(errors);
|
||||||
allErrors.addAll(this.discoveryErrorData);
|
allErrors.addAll(this.discoveryErrorData);
|
||||||
|
|
||||||
loadingModList = ModSorter.sort(candidateMods, allErrors);
|
ModSorter.sort(candidateMods, allErrors);
|
||||||
loadingModList.addAccessTransformers();
|
LoadingModList.getBrokenFiles().addAll(brokenFiles);
|
||||||
loadingModList.setBrokenFiles(brokenFiles);
|
var backgroundScanHandler = new BackgroundScanHandler(candidateMods);
|
||||||
BackgroundScanHandler backgroundScanHandler = new BackgroundScanHandler(candidateMods);
|
LoadingModList.getModFiles().stream()
|
||||||
loadingModList.addForScanning(backgroundScanHandler);
|
.map(ModFileInfo::getFile)
|
||||||
|
.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, (key, existingList) -> {
|
newMessages.compute(type, (_, 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, base) -> {
|
var modJar = SecureJar.from((path, _) -> {
|
||||||
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;
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
|
|||||||
|
|
||||||
// We want just the class files from the root of the input paths. So make a new union with a filter.
|
// 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(
|
var classes = UnionHelper.newFileSystem(
|
||||||
(name, base) -> {
|
(name, _) -> {
|
||||||
if (name.endsWith("/")) {
|
if (name.endsWith("/")) {
|
||||||
if (name.startsWith("/"))
|
if (name.startsWith("/"))
|
||||||
name = name.substring(1);
|
name = name.substring(1);
|
||||||
@@ -164,7 +164,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
|
|||||||
if ("value".equals(key)) {
|
if ("value".equals(key)) {
|
||||||
int idx = clsName.lastIndexOf('/');
|
int idx = clsName.lastIndexOf('/');
|
||||||
var pkg = clsName.substring(0, idx);
|
var pkg = clsName.substring(0, idx);
|
||||||
mods.computeIfAbsent(pkg, k -> new HashSet<>()).add((String)value);
|
mods.computeIfAbsent(pkg, _ -> new HashSet<>()).add((String)value);
|
||||||
|
|
||||||
idx = pkg.lastIndexOf('/');
|
idx = pkg.lastIndexOf('/');
|
||||||
while (idx != -1) {
|
while (idx != -1) {
|
||||||
|
|||||||
+3
-1
@@ -25,7 +25,9 @@ sealed abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Path> getMinecraftPaths() {
|
public List<Path> getMinecraftPaths() {
|
||||||
return List.of(getPathFromResource("net/minecraft/client/Minecraft.class"));
|
// We use a marker because 3rd party launcher don't build their class paths correctly
|
||||||
|
// https://github.com/MinecraftForge/MinecraftForge/issues/10797
|
||||||
|
return List.of(getPathFromResource(".forge_patched_minecraft"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
"artifact": "MixinExtras"
|
"artifact": "MixinExtras"
|
||||||
},
|
},
|
||||||
"version": {
|
"version": {
|
||||||
"range": "[0.5.3,)",
|
"range": "[0.5.4,)",
|
||||||
"artifactVersion": "0.5.3"
|
"artifactVersion": "0.5.4"
|
||||||
},
|
},
|
||||||
"path": "",
|
"path": "",
|
||||||
"isObfuscated": false
|
"isObfuscated": false
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"artifact": "mixinextras-forge"
|
"artifact": "mixinextras-forge"
|
||||||
},
|
},
|
||||||
"version": {
|
"version": {
|
||||||
"artifactVersion": "0.5.3"
|
"artifactVersion": "0.5.4"
|
||||||
},
|
},
|
||||||
"path": "",
|
"path": "",
|
||||||
"isObfuscated": false
|
"isObfuscated": false
|
||||||
|
|||||||
@@ -1,73 +1,78 @@
|
|||||||
import net.minecraftforge.gradleutils.PomUtils
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'java-library'
|
id 'java-library'
|
||||||
id 'maven-publish'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.licenser'
|
alias libs.plugins.licenser
|
||||||
id 'net.minecraftforge.gradleutils'
|
alias libs.plugins.gradleutils
|
||||||
alias(libs.plugins.apt)
|
alias libs.plugins.gitversion
|
||||||
|
alias libs.plugins.changelog
|
||||||
|
id 'net.minecraftforge.forge.build.convention'
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: rootProject.file('build_shared.gradle')
|
gradleutils.displayName = 'Forge Transformers'
|
||||||
|
final vendor = 'Forge Development LLC'
|
||||||
configurations.forEach{ it.transitive = false }
|
description = 'Forge-specific transformers unrelated to the FML project.'
|
||||||
|
|
||||||
dependencies {
|
|
||||||
compileOnly(libs.jetbrains.annotations)
|
|
||||||
|
|
||||||
implementation(libs.bundles.asm) // Needed by all the black magic
|
|
||||||
implementation(libs.log4j.api)
|
|
||||||
implementation(libs.gson)
|
|
||||||
implementation(libs.modlauncher)
|
|
||||||
implementation(libs.coremods.api)
|
|
||||||
|
|
||||||
testCompileOnly(libs.jetbrains.annotations)
|
|
||||||
}
|
|
||||||
|
|
||||||
java {
|
java {
|
||||||
toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
|
toolchain.languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
withSourcesJar()
|
withSourcesJar()
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('jar', Jar) {
|
|
||||||
manifest {
|
|
||||||
attributes([
|
|
||||||
'Automatic-Module-Name': 'net.minecraftforge.forge.transformers',
|
|
||||||
'Forge-Module-Layer': 'boot'
|
|
||||||
] as LinkedHashMap)
|
|
||||||
attributes([
|
|
||||||
'Specification-Title': 'Forge Transformers',
|
|
||||||
'Specification-Vendor': 'Forge Development LLC',
|
|
||||||
'Specification-Version': '1',
|
|
||||||
'Implementation-Title': 'Forge Transformers',
|
|
||||||
'Implementation-Vendor': 'Forge Development LLC',
|
|
||||||
'Implementation-Version': FORGE_VERSION
|
|
||||||
] as LinkedHashMap, 'net/minecraftforge/forge/transformers/')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(JavaCompile).configureEach {
|
|
||||||
options.compilerArgs << '-Xlint:unchecked'
|
|
||||||
}
|
|
||||||
|
|
||||||
license {
|
license {
|
||||||
header = rootProject.file('LICENSE-header.txt')
|
header = rootProject.file('LICENSE-header.txt')
|
||||||
}
|
}
|
||||||
|
|
||||||
publishing {
|
changelog {
|
||||||
publications.register('mavenJava', MavenPublication) {
|
from changelogBase
|
||||||
from components.java
|
}
|
||||||
artifactId = 'forge-transformers'
|
|
||||||
pom {
|
|
||||||
name = project.name
|
|
||||||
description = 'Forge-specific transformers unrelated to the FML project.'
|
|
||||||
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
|
||||||
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
|
|
||||||
license PomUtils.Licenses.LGPLv2_1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
compileOnly(libs.jetbrains.annotations)
|
||||||
|
|
||||||
|
implementation(libs.bundles.asm ){ transitive = false } // Needed by all the black magic
|
||||||
|
implementation(libs.log4j.api ){ transitive = false }
|
||||||
|
implementation(libs.gson ){ transitive = false }
|
||||||
|
implementation(libs.modlauncher ){ transitive = false }
|
||||||
|
implementation(libs.coremods.api){ transitive = false }
|
||||||
|
|
||||||
|
testCompileOnly(libs.jetbrains.annotations)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('jar', Jar) {
|
||||||
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.forge.transformers',
|
||||||
|
'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/forge/transformers/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
repositories {
|
repositories {
|
||||||
maven gradleutils.publishingForgeMaven
|
maven gradleutils.publishingForgeMaven
|
||||||
}
|
}
|
||||||
|
|
||||||
|
publications.register('mavenJava', MavenPublication) {
|
||||||
|
changelog.publish(it)
|
||||||
|
gradleutils.promote(it)
|
||||||
|
|
||||||
|
from components.java
|
||||||
|
|
||||||
|
pom { pom ->
|
||||||
|
description = project.description
|
||||||
|
|
||||||
|
gradleutils.pom.addRemoteDetails(pom)
|
||||||
|
|
||||||
|
licenses {
|
||||||
|
license gradleutils.pom.licenses.LGPLv2_1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -126,7 +126,7 @@ record FieldToMethodTransformer(String className, Map<String, String> fields) im
|
|||||||
throw new IllegalStateException("No field with name " + fieldName + " found");
|
throw new IllegalStateException("No field with name " + fieldName + " found");
|
||||||
|
|
||||||
if (!Modifier.isPrivate(foundField.access) || Modifier.isStatic(foundField.access))
|
if (!Modifier.isPrivate(foundField.access) || Modifier.isStatic(foundField.access))
|
||||||
throw new IllegalStateException("Field " + fieldName + " is not private and an instance field");
|
throw new IllegalStateException("Field " + classNode.name + '.' + fieldName + " is not private and an instance field");
|
||||||
|
|
||||||
var methodSignature = "()" + foundField.desc;
|
var methodSignature = "()" + foundField.desc;
|
||||||
var foundMethod = findMethod(classNode, methodName, methodSignature);
|
var foundMethod = findMethod(classNode, methodName, methodSignature);
|
||||||
|
|||||||
+1
-1
@@ -41,7 +41,7 @@ record MethodRedirector() implements ITransformer<ClassNode> {
|
|||||||
"finalizeSpawn",
|
"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;",
|
"(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;",
|
||||||
GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class),
|
GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class),
|
||||||
insn -> new MethodInsnNode(
|
_ -> new MethodInsnNode(
|
||||||
Opcodes.INVOKESTATIC,
|
Opcodes.INVOKESTATIC,
|
||||||
"net/minecraftforge/event/ForgeEventFactory",
|
"net/minecraftforge/event/ForgeEventFactory",
|
||||||
"onFinalizeSpawn",
|
"onFinalizeSpawn",
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
"class": "net/minecraft/gametest/framework/GameTestHelper",
|
"class": "net/minecraft/gametest/framework/GameTestEntityBuilder",
|
||||||
"methods": [
|
"methods": [
|
||||||
"spawn(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/entity/EntitySpawnReason;)Lnet/minecraft/world/entity/Entity;"
|
"spawn()Lnet/minecraft/world/entity/Entity;"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
{
|
{
|
||||||
"class": "net/minecraft/world/entity/EntityType",
|
"class": "net/minecraft/world/entity/EntityType",
|
||||||
"methods": [
|
"methods": [
|
||||||
"create(Lnet/minecraft/server/level/ServerLevel;Ljava/util/function/Consumer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;"
|
"create(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/PostSpawnProcessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -42,12 +42,6 @@
|
|||||||
"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;"
|
"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;"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"class": "net/minecraft/world/entity/animal/frog/Tadpole",
|
|
||||||
"methods": [
|
|
||||||
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"class": "net/minecraft/world/entity/monster/Strider",
|
"class": "net/minecraft/world/entity/monster/Strider",
|
||||||
"methods": [
|
"methods": [
|
||||||
@@ -85,24 +79,12 @@
|
|||||||
"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;"
|
"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;"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"class": "net/minecraft/world/entity/monster/zombie/ZombieVillager",
|
|
||||||
"methods": [
|
|
||||||
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"class": "net/minecraft/world/entity/npc/CatSpawner",
|
"class": "net/minecraft/world/entity/npc/CatSpawner",
|
||||||
"methods": [
|
"methods": [
|
||||||
"spawnCat(Lnet/minecraft/core/BlockPos;Lnet/minecraft/server/level/ServerLevel;Z)V"
|
"spawnCat(Lnet/minecraft/core/BlockPos;Lnet/minecraft/server/level/ServerLevel;Z)V"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"class": "net/minecraft/world/entity/npc/villager/Villager",
|
|
||||||
"methods": [
|
|
||||||
"getBreedOffspring(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/AgeableMob;)Lnet/minecraft/world/entity/npc/villager/Villager;"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"class": "net/minecraft/world/entity/raid/Raid",
|
"class": "net/minecraft/world/entity/raid/Raid",
|
||||||
"methods": [
|
"methods": [
|
||||||
@@ -158,11 +140,5 @@
|
|||||||
"methods": [
|
"methods": [
|
||||||
"handleDataMarker(Ljava/lang/String;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/structure/BoundingBox;)V"
|
"handleDataMarker(Ljava/lang/String;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/structure/BoundingBox;)V"
|
||||||
]
|
]
|
||||||
},
|
|
||||||
{
|
|
||||||
"class": "net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate",
|
|
||||||
"methods": [
|
|
||||||
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
+23
-11
@@ -1,17 +1,29 @@
|
|||||||
|
# TODO Re-evaluate
|
||||||
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
|
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
|
||||||
# This is required to provide enough memory for the Minecraft decompilation process.
|
# This is required to provide enough memory for the Minecraft decompilation process.
|
||||||
org.gradle.jvmargs=-Xmx6G
|
org.gradle.jvmargs=-Xmx6G
|
||||||
org.gradle.daemon=false
|
|
||||||
|
org.gradle.warning.mode=all
|
||||||
|
org.gradle.caching=true
|
||||||
org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
|
org.gradle.configureondemand=true
|
||||||
|
|
||||||
JAVA_VERSION=21
|
# TODO [ForgeDev] Enable this once ForgeDev 7 tasks are fully migrated
|
||||||
MC_VERSION=1.21.11
|
org.gradle.configuration-cache=false
|
||||||
MC_NEXT_VERSION=1.22
|
org.gradle.configuration-cache.parallel=false
|
||||||
MCP_VERSION=20251223.124241
|
#org.gradle.configuration-cache.problems=warn
|
||||||
MAPPING_CHANNEL=official
|
#org.gradle.configuration-cache.integrity-check=true
|
||||||
MAPPING_VERSION=1.21.11
|
|
||||||
|
|
||||||
# Set to true before the first build of a new MC version, so we don't do compatibility checks
|
net.minecraftforge.gradleutils.ide.automatic.sources=true
|
||||||
CHECK_COMPATIBILITY=false
|
net.minecraftforge.gradleutils.compilation.defaults=true
|
||||||
# Set to true to allow for fuzzy patching. Useful during updateing
|
|
||||||
UPDATING=false
|
net.minecraftforge.gradle.merge-source-sets=true
|
||||||
|
|
||||||
|
# Controls if the compatibility checks are auto-added to the 'check' task.
|
||||||
|
# The check tasks are still created and can be run, they just are not grouped with the normal 'check' task.
|
||||||
|
# Set to false for the first builds of a new Minecraft version.
|
||||||
|
net.minecraftforge.forge.build.check.compatibility=false
|
||||||
|
# Set to true to allow for fuzzy patching. Useful during updating.
|
||||||
|
net.minecraftforge.forge.build.updating=false
|
||||||
|
# Set to true to enable the 'validatePublish' task which is currently a work in progress
|
||||||
|
net.minecraftforge.forgedev.validate.publish=false
|
||||||
Vendored
BIN
Binary file not shown.
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
Loaded 100 of 1828 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user