- // ForgeMC is a unique identifier for every MC version we have supported.
- // Essentially, the same as the old, except dropping the first number, and the builds are no longer unique.
- MCP_ARTIFACT = project(':mcp').mcp.config.get()
- VERSION_JSON = project(':mcp').file('build/mcp/downloadJson/version.json')
- PACKED_DEPS = [':fmlcore:jar', ':fmlloader:jar', ':fmlearlydisplay:jar', ':javafmllanguage:jar', ':lowcodelanguage:jar', ':mclanguage:jar']
- MAVEN_PATH = "${group.replace('.', '/')}/${project.name}/${VERSION}"
- }
-
- configurations {
- // Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
- installer { transitive = false }
- moduleonly { transitive = false }
- api.extendsFrom(installer)
- }
-
- dependencies {
- moduleonly(libs.bootstrap)
- moduleonly(libs.securemodules) // Needed by bootstrap
- moduleonly(libs.unsafe) // Needed by securemodules
- moduleonly(libs.bundles.asm) // Needed by all the black magic
- moduleonly(libs.jarjar.fs) // Filesystems need to be on the bootstrap? I think thats why this is here.
- moduleonly(libs.bundles.jimfs) // In memory file system used for ForgeDev launches
-
- installer(libs.unsafe)
- installer(libs.securemodules)
- installer(libs.bundles.asm) // Needed by all the black magic
- installer(libs.accesstransformers)
- installer(libs.antlr.runtime) // Dep of AccessTransformer
- installer(libs.eventbus)
- installer(libs.typetools) // Dep of EventBus
- installer(libs.forgespi)
- installer(libs.coremods)
- installer(libs.nashorn) // Dep of Coremods
- 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.bundles.jarjar)
-
- implementation project(':fmlcore')
- implementation project(':fmlloader')
- implementation project(':fmlearlydisplay')
- implementation project(':javafmllanguage')
- implementation project(':lowcodelanguage')
- implementation project(':mclanguage')
-
- runtimeOnly(libs.bootstrap)
- }
-
- patcher {
- excs.from file("$rootDir/src/main/resources/forge.exc")
- parent = project(':mcp')
- mcVersion = MC_VERSION
- mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
- patches = file("$rootDir/patches/minecraft")
- patchedSrc = file('src/main/java')
- srgPatches = false
- accessTransformers.from file("$rootDir/src/main/resources/META-INF/accesstransformer.cfg")
- sideAnnotationStrippers.from file("$rootDir/src/main/resources/forge.sas")
-
- runs {
- forge_client {
- property 'eventbus.checkTypesOnDispatch', 'true'
- property 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
-
- args '--launchTarget', 'forge_dev_client',
- '--username', 'Dev',
- '--version', project.name,
- '--accessToken', '0',
- '--userType', 'mojang',
- '--versionType', 'release',
- '--assetsDir', downloadAssets.output,
- '--assetIndex', "{asset_index}"
- }
-
- forge_client_test {
- parent runs.forge_client
- }
-
- forge_server {
- args '--launchTarget', 'forge_dev_server'
- }
-
- forge_server_test {
- parent runs.forge_server
- }
-
- forge_server_gametest {
- args '--launchTarget', 'forge_dev_server_gametest'
- }
-
- forge_server_gametest_test {
- parent runs.forge_server_gametest
- }
-
- forge_data {
- args '--launchTarget', 'forge_dev_data',
- '--mod', 'forge',
- '--all',
- '--validate',
- '--output', rootProject.file('src/generated/resources/'),
- '--validate',
- '--existing', sourceSets.main.resources.srcDirs[0],
- '--assetsDir', downloadAssets.output,
- '--assetIndex', "{asset_index}"
- }
-
- forge_data_test {
- args '--launchTarget', 'forge_dev_data',
- '--mod', '.+',
- '--all',
- '--validate',
- '--output', rootProject.file('src/generated_test/resources/'),
- '--existing', sourceSets.main.resources.srcDirs[0],
- '--existing', sourceSets.test.resources.srcDirs[0],
- '--assetsDir', downloadAssets.output,
- '--assetIndex', "{asset_index}"
- }
-
- }
- }
-
- afterEvaluate {
- if (!patcher.srgPatches) {
- srg2mcpClean {
- dependsOn = []
- input = project(':mcp').setupMCP.output
- }
- userdevJar {
- onlyIf = { t -> true }
- }
- def patches = project.file('build/genPatchesForUserdev/output/')
- patches.mkdirs()
- def genPatchesForUserdev = tasks.register('genPatchesForUserdev', GeneratePatches){
- base = project(':mcp').setupMCP.output
- modified = applyRangeMapBase.output
- originalPrefix = genPatches.originalPrefix
- modifiedPrefix = genPatches.modifiedPrefix
- output = patches
- autoHeader true
- lineEnding = '\n'
- }
- bakePatches {
- dependsOn = []
- input = genPatchesForUserdev.get().output
- }
- }
- }
-
- ext {
- MANIFESTS = [
- '/': [
- 'GitCommit': gradleutils.gitInfo.abbreviatedId,
- 'Git-Branch': gradleutils.gitInfo.branch,
- 'FML-System-Mods': 'forge'
- ] as LinkedHashMap,
- 'net/minecraftforge/versions/forge/': [
- 'Specification-Title': 'Forge',
- 'Specification-Vendor': 'Forge Development LLC',
- 'Specification-Version': SPEC_VERSION,
- 'Implementation-Title': project.group,
- 'Implementation-Version': project.version.substring(MC_VERSION.length() + 1),
- 'Implementation-Vendor': 'Forge Development LLC'
- ] as LinkedHashMap,
- 'net/minecraftforge/versions/mcp/': [
- 'Specification-Title': 'Minecraft',
- 'Specification-Vendor': 'Mojang',
- 'Specification-Version': MC_VERSION,
- 'Implementation-Title': 'MCP',
- 'Implementation-Version': MCP_VERSION,
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap,
- 'net/minecraftforge/fml/javafmlmod/': [
- 'Specification-Title': 'Mod Language Provider',
- 'Specification-Vendor': 'Forge Development LLC',
- 'Specification-Version': '1',
- 'Implementation-Title': 'FML Java Mod',
- 'Implementation-Version': SPEC_VERSION,
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap,
- 'net/minecraftforge/fml/mclanguageprovider/': [
- 'Specification-Title': 'Mod Language Provider',
- 'Specification-Vendor': 'Forge Development LLC',
- 'Specification-Version': '1',
- 'Implementation-Title': 'Minecraft Language Mod Provider',
- 'Implementation-Version': '1',
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap,
- 'net/minecraftforge/fml/loading/': [
- 'Specification-Title': 'Launcher',
- 'Specification-Vendor': 'Forge Development LLC',
- 'Specification-Version': '1',
- 'Implementation-Title': 'FML Launcher',
- 'Implementation-Version': SPEC_VERSION,
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap
- ]
- }
-
- tasks.register('downloadCrowdin', Download) {
- src 'https://files.minecraftforge.net/crowdin.zip'
- dest file('build/crowdin.zip')
- useETag 'all'
- onlyIfModified true
- quiet true
- }
-
- sharedFmlonlyForge.call(project)
-
- task downloadLibraries(type: DownloadLibraries, dependsOn: ':mcp:setupMCP') {
- input = VERSION_JSON
- output = rootProject.file('build/libraries/')
- }
-
- task extractInheritance(type: ExtractInheritance, dependsOn: [downloadLibraries]) {
- tool = INSTALLER_TOOLS + ':fatjar'
- args.add '--annotations'
- input = genJoinedBinPatches.cleanJar
- libraries.addAll downloadLibraries.librariesOutput.map { rf -> Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).collect(java.util.stream.Collectors.toList()) }
- }
-
- tasks.register("findFieldInstanceChecks", FieldCompareFinder) {
- jar = createJoinedSRG.output
- output = rootProject.file('src/main/resources/coremods/field_to_instanceof.json')
- fields {
- /* 1.17 changed most things to use Tags. So this isn't nessasary anymore so just make an empty list
- bows {
- cls = 'net/minecraft/world/item/Items'
- name = 'f_42411_'
- replacement = 'net/minecraft/world/item/BowItem'
- }
- crossbows {
- cls = 'net/minecraft/world/item/Items'
- name = 'f_42717_'
- replacement = 'net/minecraft/world/item/CrossbowItem'
- }
- */
- }
- }
-
- tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
- jar = createJoinedSRG.output
- output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json')
- predicate = {
- parent, node, insn ->
- 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
- && insn.getOpcode() == Opcodes.INVOKEVIRTUAL
- && insn.name.equals('m_6518_')
- && insn.desc.equals('(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;')
- }
- }
-
- tasks.register('validateDeprecations', ValidateDeprecations) {
- input = tasks.jar.archiveFile
- mcVersion = MC_VERSION
- }
-
- tasks.jar.finalizedBy 'validateDeprecations'
-
- tasks.register("downloadInstaller", DownloadMavenArtifact) {
- artifact = "net.minecraftforge:installer:${INSTALLER_VERSION}:shrunk"
- changing = true
- }
- tasks.register("downloadClientSlim", DownloadMavenArtifact) {
- artifact = "net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:slim"
- }
- tasks.register("downloadClientExtra", DownloadMavenArtifact) {
- artifact = "net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:extra"
- }
- tasks.register("downloadServerSlim", DownloadMavenArtifact) {
- artifact = "net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:slim"
- }
- tasks.register("downloadServerExtra", DownloadMavenArtifact) {
- artifact = "net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:extra"
- }
- tasks.register("downloadJoinedSlim", DownloadMavenArtifact) {
- artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:slim"
- }
- tasks.register("downloadJoinedExtra", DownloadMavenArtifact) {
- artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:extra"
- }
- tasks.register("createJoinedSRG", DownloadMavenArtifact) {
- artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
- }
- tasks.register("createClientSRG", RenameJar) {
- tool = FART
- args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix']
- mappings = createMcp2Srg.srg
- input = downloadClientSlim.output
- output = file("build/createClientSRG/output.jar")
- }
- tasks.register("createServerSRG", RenameJar) {
- tool = FART
- args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix']
- mappings = createMcp2Srg.srg
- input = downloadServerSlim.output
- output = file("build/createServerSRG/output.jar")
- }
- genClientBinPatches {
- tool = BINPATCH_TOOL
- cleanJar = createClientSRG.output
- }
- genServerBinPatches {
- tool = BINPATCH_TOOL
- cleanJar = createServerSRG.output
- }
- genJoinedBinPatches {
- tool = BINPATCH_TOOL
- cleanJar = createJoinedSRG.output
- }
- tasks.register("applyClientBinPatches", ApplyBinPatches) {
- tool = BINPATCH_TOOL
- clean = genClientBinPatches.cleanJar
- patch = genClientBinPatches.output
- }
- tasks.register("applyServerBinPatches", ApplyBinPatches) {
- tool = BINPATCH_TOOL
- clean = genServerBinPatches.cleanJar
- patch = genServerBinPatches.output
- }
- tasks.register("applyJoinedBinPatches", ApplyBinPatches) {
- tool = BINPATCH_TOOL
- clean = genJoinedBinPatches.cleanJar
- patch = genJoinedBinPatches.output
- }
-
-
- tasks.register('checkAll') {
- dependsOn 'checkLicenses'
- group = 'checks'
- }
- tasks.register('checkAllAndFix') {
- dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses'
- group = 'checks'
- }
-
- CheckTask.registerTask(tasks, 'ATs', CheckATs) {
- dependsOn extractInheritance, createSrg2Mcp
- ats.from patcher.accessTransformers
- inheritance = extractInheritance.output
- mappings = createSrg2Mcp.output
- }
-
- CheckTask.registerTask(tasks, 'SAS', CheckSAS) {
- dependsOn extractInheritance
- sass.from patcher.sideAnnotationStrippers
- inheritance = extractInheritance.output
- }
-
- CheckTask.registerTask(tasks, 'Excs', CheckExcs) {
- dependsOn jar
- binary = jar.archiveFile.get().asFile
- excs.from patcher.excs
- }
-
- CheckTask.registerTask(tasks, 'Patches', CheckPatches) {
- dependsOn genPatches
- patchDir = file("$rootDir/patches")
- patchesWithS2SArtifact = [
- 'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
- 'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
- ]
- }
-
- genPatches {
- finalizedBy checkAndFixPatches
- autoHeader true
- lineEnding = '\n'
- }
-
- def baseForgeVersionProperty = project.objects.property(String)
- baseForgeVersionProperty.set(project.provider { TeamcityRequests.attemptFindBase(rootDir) ?: getLatestForgeVersion(MC_VERSION) })
- baseForgeVersionProperty.finalizeValueOnRead()
- def jarCompatibilityTaskSetup = { task ->
- task.group = 'jar compatibility'
- task.onlyIf {
- baseForgeVersionProperty.getOrNull() != null
- }
- }
-
- tasks.register('setupCheckJarCompatibility', SetupCheckJarCompatibility) {
- inputVersion = baseForgeVersionProperty
- }
-
- tasks.register('applyBaseCompatibilityJarBinPatches', ApplyBinPatches) {
- jarCompatibilityTaskSetup(it)
-
- clean = project.tasks.createJoinedSRG.output
- patch = project.tasks.named('setupCheckJarCompatibility').flatMap { it.baseBinPatchesOutput }
- output = project.layout.buildDirectory.dir(name).map { it.file('output.jar') }
- }
-
- tasks.register('mergeBaseForgeJar', MergeJars) {
- jarCompatibilityTaskSetup(it)
-
- inputJars.from(project.tasks.named('applyBaseCompatibilityJarBinPatches').flatMap { it.output })
- inputJars.from(baseForgeVersionProperty.map { inputVersion ->
- def output = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-universal.jar") }.get().asFile
- project.rootProject.extensions.download.run {
- src "https://maven.minecraftforge.net/net/minecraftforge/forge/${inputVersion}/forge-${inputVersion}-universal.jar"
- dest output
- }
- return output
- })
- }
-
- tasks.register('checkJarCompatibility', CheckJarCompatibility) {
- jarCompatibilityTaskSetup(it)
- dependsOn 'setupCheckJarCompatibility'
-
- baseJar = project.tasks.named('mergeBaseForgeJar').flatMap { it.output }
- baseLibraries.from(project.tasks.named('createJoinedSRG').flatMap { it.output })
-
- inputJar = project.tasks.named('reobfJar').flatMap { it.output }
- concreteLibraries.from(project.PACKED_DEPS.collect { project.rootProject.tasks.getByPath(it).archiveFile })
-
- commonLibraries.from(project.configurations.minecraftImplementation)
- commonLibraries.from(project.configurations.installer)
- commonLibraries.from(project.configurations.moduleonly)
- }
-
- task launcherJson(type: LauncherJson) {
- packedDependencies = [':fmlloader:jar',':fmlearlydisplay:jar']
- doFirst {
- def forge_client = project(':forge').patcher.runs.forge_client
- json = [
- _comment_: comment,
- id: id,
- time: timestamp,
- releaseTime: timestamp,
- type: 'release',
- mainClass: 'net.minecraftforge.bootstrap.BootstrapLauncher',
- inheritsFrom: MC_VERSION,
- logging: {},
- arguments: [
- game: ['--launchTarget', 'forge_client',
- '--fml.forgeVersion', FORGE_VERSION,
- '--fml.mcVersion', MC_VERSION,
- '--fml.forgeGroup', project.group,
- '--fml.mcpVersion', MCP_VERSION],
- jvm: ['-Djava.net.preferIPv6Addresses=system',
- "-DignoreList=${forge_client.properties.ignoreList},\${version_name}.jar",
- "-DmergeModules=${forge_client.properties.mergeModules}",
- '-DlibraryDirectory=${library_directory}',
- '-p', Util.getArtifacts(project, configurations.moduleonly, false).values().collect{'${library_directory}/' + it.downloads.artifact.path}.join('${classpath_separator}'),
- '--add-modules', 'ALL-MODULE-PATH',
- // Additions to these JVM module args should be mirrored to server_files/args.txt and other similar blocks in the buildscript
- '--add-exports', 'jdk.naming.dns/com.sun.jndi.dns=java.naming'
- ]
- ],
- libraries: []
- ]
- }
- }
-
- task installerJson(type: InstallerJson, dependsOn: [launcherJson, genClientBinPatches, applyClientBinPatches, applyServerBinPatches, 'signUniversalJar']) {
- ext {
- // remove :fatjar
- BIN_PATCHER = BINPATCH_TOOL.substring(0, BINPATCH_TOOL.length() - 1 - BINPATCH_TOOL.split(':')[3].length())
- }
- input.from applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar, launcherJson.output
- icon = rootProject.file('icon.ico')
- packedDependencies = PACKED_DEPS
-
- doFirst {
- def libs = libraries
- def INSTALLER_TOOLS_CLASSPATH = getClasspath(project, libs, INSTALLER_TOOLS)
- def JAR_SPLITTER_CLASSPATH = getClasspath(project, libs, JAR_SPLITTER)
- json = [
- _comment_: launcherJson.comment,
- spec: 1,
- profile: project.name,
- version: launcherJson.id,
- path: null,
- minecraft: MC_VERSION,
- serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}.jar',
- data: [
- MAPPINGS: [
- client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@txt]",
- server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@txt]"
- ],
- MOJMAPS: [
- client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:mappings@txt]",
- server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:mappings@txt]"
- ],
- MERGED_MAPPINGS: [
- client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@txt]",
- server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@txt]"
- ],
- BINPATCH: [
- client: '/data/client.lzma',
- server: '/data/server.lzma'
- ],
- MC_UNPACKED: [
- client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:unpacked]",
- server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:unpacked]"
- ],
- MC_SLIM: [
- client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:slim]",
- server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:slim]"
- ],
- MC_SLIM_SHA: [
- client: "'${downloadClientSlim.output.get().asFile.sha1()}'",
- server: "'${downloadServerSlim.output.get().asFile.sha1()}'"
- ],
- MC_EXTRA: [
- client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:extra]",
- server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:extra]"
- ],
- MC_EXTRA_SHA: [
- client: "'${downloadClientExtra.output.get().asFile.sha1()}'",
- server: "'${downloadServerExtra.output.get().asFile.sha1()}'"
- ],
- MC_SRG: [
- client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]",
- server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]"
- ],
- /*MC_SRG_SHA: [
- client: "'${createClientSRG.output.sha1()}'",
- server: "'${createServerSRG.output.sha1()}'"
- ],*/
- PATCHED: [
- client: "[${project.group}:${project.name}:${project.version}:client]",
- server: "[${project.group}:${project.name}:${project.version}:server]"
- ],
- PATCHED_SHA: [
- client: "'${applyClientBinPatches.output.get().asFile.sha1()}'",
- server: "'${applyServerBinPatches.output.get().asFile.sha1()}'"
- ],
- MCP_VERSION: [
- client: "'${MCP_VERSION}'",
- server: "'${MCP_VERSION}'"
- ]
- ],
- processors: [
- [
- sides: ['server'],
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'EXTRACT_FILES',
- '--archive', '{INSTALLER}',
-
- '--from', 'data/run.sh',
- '--to', '{ROOT}/run.sh',
- '--exec', '{ROOT}/run.sh',
- //'--from', "data/run_forge_${VERSION.replace('-', '_').sh",
- //'--to', '{ROOT}/run_forge_${VERSION.replace('-', '_').sh',
- //'--exec', '{ROOT}/run_forge_${VERSION.replace('-', '_').sh',
-
- '--from', 'data/run.bat',
- '--to', '{ROOT}/run.bat',
- //'--from', 'data/run_forge_${VERSION.replace('-', '_').bat',
- //'--to', '{ROOT}/run_forge_${VERSION.replace('-', '_').bat',
-
- '--from', 'data/user_jvm_args.txt',
- '--to', '{ROOT}/user_jvm_args.txt',
- '--optional', '{ROOT}/user_jvm_args.txt',
-
- '--from', 'data/win_args.txt',
- '--to', "{ROOT}/libraries/${MAVEN_PATH}/win_args.txt",
-
- '--from', 'data/unix_args.txt',
- '--to', "{ROOT}/libraries/${MAVEN_PATH}/unix_args.txt"
- ]
- ], [
- sides: ['server'],
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'BUNDLER_EXTRACT',
- '--input', '{MINECRAFT_JAR}',
- '--output', '{ROOT}/libraries/',
- '--libraries'
- ]
- ], [
- sides: ['server'],
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'BUNDLER_EXTRACT',
- '--input', '{MINECRAFT_JAR}',
- '--output', '{MC_UNPACKED}',
- '--jar-only'
- ]
- ], [
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'MCP_DATA',
- '--input', "[${MCP_ARTIFACT.descriptor}]",
- '--output', '{MAPPINGS}',
- '--key', 'mappings'
- ]
- ], [
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'DOWNLOAD_MOJMAPS',
- '--version', MC_VERSION,
- '--side', '{SIDE}',
- '--output', '{MOJMAPS}'
- ]
- ], [
- jar: INSTALLER_TOOLS,
- classpath: INSTALLER_TOOLS_CLASSPATH,
- args: [
- '--task', 'MERGE_MAPPING',
- '--left', '{MAPPINGS}',
- '--right', '{MOJMAPS}',
- '--output', '{MERGED_MAPPINGS}',
- '--classes', '--reverse-right'
- ]
- ], [
- sides: ['client'],
- jar: JAR_SPLITTER,
- classpath: JAR_SPLITTER_CLASSPATH,
- args: [
- '--input', '{MINECRAFT_JAR}',
- '--slim', '{MC_SLIM}',
- '--extra', '{MC_EXTRA}',
- '--srg', '{MERGED_MAPPINGS}'
- ],
- outputs: [
- '{MC_SLIM}': '{MC_SLIM_SHA}',
- '{MC_EXTRA}': '{MC_EXTRA_SHA}'
- ]
- ], [
- sides: ['server'],
- jar: JAR_SPLITTER,
- classpath: JAR_SPLITTER_CLASSPATH,
- args: [
- '--input', '{MC_UNPACKED}',
- '--slim', '{MC_SLIM}',
- '--extra', '{MC_EXTRA}',
- '--srg', '{MERGED_MAPPINGS}'
- ],
- outputs: [
- '{MC_SLIM}': '{MC_SLIM_SHA}',
- '{MC_EXTRA}': '{MC_EXTRA_SHA}'
- ]
- ], [
- jar: FART,
- classpath: getClasspath(project, libs, FART),
- args: [
- '--input', '{MC_SLIM}',
- '--output', '{MC_SRG}',
- '--names', '{MERGED_MAPPINGS}',
- '--ann-fix', '--ids-fix', '--src-fix', '--record-fix'
- ]/*,
- outputs: [
- '{MC_SRG}': '{MC_SRG_SHA}'
- ]
- */
- ], [
- jar: BIN_PATCHER,
- classpath: getClasspath(project, libs, BIN_PATCHER),
- args: [
- '--clean', '{MC_SRG}',
- '--output', '{PATCHED}',
- '--apply', '{BINPATCH}'
- ]/*, Because Vignette is unstable, it screws with the entry order of the binpatched jar, so we can't use the hash right now
- // Re-enable this when https://github.com/CadixDev/Vignette/issues/1 is solved
- outputs: [
- '{PATCHED}': '{PATCHED_SHA}'
- ]*/
- ]
- ]
- ]
- getClasspath(project, libs, MCP_ARTIFACT.descriptor) //Tell it to download mcp_config
- }
- }
-
- universalJar {
- dependsOn downloadCrowdin
- from zipTree(downloadCrowdin.dest).matching {
- include 'assets/forge/lang/*.json'
- }
-
- from extraTxts
- duplicatesStrategy = 'exclude'
-
- doFirst {
- MANIFESTS.each{ pkg, values ->
- if (pkg == '/') {
- manifest.attributes(values)
- } else {
- manifest.attributes(values, pkg)
- }
- }
- }
- }
-
- task installerJar(type: InstallerJar, dependsOn: [genClientBinPatches, genServerBinPatches, 'signUniversalJar', launcherJson]) {
- packedDependencies = PACKED_DEPS
- from(extraTxts)
- from(rootProject.file('/forge_installer_logo.png')) {
- rename { 'big_logo.png' }
- }
- from(genClientBinPatches.output) {
- rename { 'data/client.lzma' }
- }
- from(genServerBinPatches.output) {
- rename { 'data/server.lzma' }
- }
- }
-
- tasks.register('devInstallerJar', DevInstallerJar) {
- input = installerJar.archiveFile
- }
-
- task makeMdk(type: Zip) {
- archiveBaseName = project.name
- archiveClassifier = 'mdk'
- archiveVersion = project.version
- destinationDirectory = file('build/libs')
-
- from rootProject.file('gradlew')
- from rootProject.file('gradlew.bat')
- from extraTxts
- from(rootProject.file('gradle/')){
- into('gradle/')
- }
- from(rootProject.file('mdk/')){
- rootProject.file('mdk/gitignore.txt').eachLine{
- if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
- exclude it
- }
- filter(ReplaceTokens, tokens: [
- FORGE_VERSION: FORGE_VERSION,
- FORGE_GROUP: project.group,
- FORGE_NAME: project.name,
- MC_VERSION: MC_VERSION,
- MAPPING_CHANNEL: MAPPING_CHANNEL,
- MAPPING_VERSION: MAPPING_VERSION,
- FORGE_SPEC_VERSION: SPEC_VERSION.split("\\.")[0],
- MC_NEXT_VERSION: MC_NEXT_VERSION
- ])
- rename 'gitignore\\.txt', '.gitignore'
- rename 'gitattributes\\.txt', '.gitattributes'
- }
- from(rootProject.file('src/generated_test/resources/mdk_datagen/')) {
- into('src/main/resources/')
- exclude '**/.cache/'
- }
- }
-
- license {
- header = file("$rootDir/LICENSE-header.txt")
-
- include 'net/minecraftforge/'
- exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
-
- tasks {
- main {
- files.from files("$rootDir/src/main/java")
- }
- test {
- files.from files("$rootDir/src/test/java")
- }
- }
- }
-
- tasks.register('genAllData') {
- dependsOn 'forge_data', 'forge_mdk_data', 'forge_test_data'
- }
-
- tasks.eclipse.dependsOn('genEclipseRuns')
-
- if (project.hasProperty('UPDATE_MAPPINGS')) {
- extractRangeMap {
- sources.from sourceSets.test.java.srcDirs
- addDependencies compileTestJava.classpath
- }
- applyRangeMap {
- sources.from sourceSets.test.java.srcDirs
- }
- sourceSets.test.java.srcDirs.each { extractMappedNew.addTarget it }
- }
-
- tasks.named('javadoc', Javadoc).configure {
- description 'Generates the combined javadocs for the FML projects and the main Forge project'
- var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage' ]
- 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.addStringOption('Xdoclint:all,-missing', '-public')
- options {
- stylesheetFile = new File(docsDir, 'stylesheet.css')
-
- tags = [
- 'apiNote:a:API Note:',
- 'implSpec:a:Implementation Requirements:',
- 'implNote:a:Implementation Note:'
- ]
-
- 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 - ${FORGE_VERSION} for Minecraft ${MC_VERSION}"
- header = "${FORGE_VERSION} for Minecraft ${MC_VERSION}
"
- }
-
- doLast {
- project.copy {
- from docsDir
- exclude '/stylesheet.css'
- into destinationDir
- }
- }
- }
-
- publishing {
- publications {
- mavenJava(MavenPublication) {
- artifact universalJar
- artifact installerJar
- artifact makeMdk
- artifact userdevJar
- artifact sourcesJar
- }
- }
- }
-
- // Since we need the modules in the bootstrap, we need to make sure they are compiled before we do each run
- afterEvaluate { prepareRuns.dependsOn(PACKED_DEPS) }
-
- // Make sure we run bin compat checking during local testing.
- if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
- publish.dependsOn(':forge:checkJarCompatibility')
+ from '47.999'
}
tasks.register('setup') {
@@ -1296,6 +40,14 @@ tasks.register('doChecks') {
dependsOn ':forge:publish'
}
+project(':mcp') {
+ apply plugin: 'net.minecraftforge.gradle.mcp'
+ mcp {
+ config MC_VERSION + '-' + MCP_VERSION
+ pipeline = 'joined'
+ }
+}
+
if (System.env.TEAMCITY_VERSION) {
//Only setup the CI environment if and only if the environment variables are set.
tasks.configureTeamCity {
@@ -1304,17 +56,4 @@ if (System.env.TEAMCITY_VERSION) {
println "##teamcity[setParameter name='env.PUBLISHED_JAVA_ARTIFACT_VERSION' value='${project(':forge').version}']"
}
}
-}
-
-allprojects { prj ->
- prj.tasks.eclipse.doFirst {
- 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')
- temp.forEach(exst::put)
- exst.store(target)
- }
- }
-}
+}
\ No newline at end of file
diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle
index 7faf142df1..297636c20a 100644
--- a/buildSrc/build.gradle
+++ b/buildSrc/build.gradle
@@ -1,6 +1,6 @@
repositories {
maven { url = 'https://maven.minecraftforge.net/' }
- mavenCentral()
+ mavenCentral()
}
dependencies {
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy
new file mode 100644
index 0000000000..9e24a9ff21
--- /dev/null
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/BundleList.groovy
@@ -0,0 +1,55 @@
+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
+
+abstract class BundleList extends DefaultTask {
+ @InputFiles abstract ConfigurableFileCollection getConfig()
+ @InputFile abstract RegularFileProperty getServerBundle()
+ @OutputFile abstract RegularFileProperty getOutput()
+
+ BundleList() {
+ config.setFrom(project.configurations.installer)
+ output.convention(project.layout.buildDirectory.file("$name/output.list"))
+ configure {
+ dependsOn(project.tasks.universalJar)
+ inputs.file(project.tasks.universalJar.archiveFile)
+ }
+ }
+
+ @TaskAction
+ void run() {
+ def entries = [:] as TreeMap
+ def resolved = project.configurations.installer.resolvedConfiguration.resolvedArtifacts
+ for (var 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")
+ }
+
+ [
+ project.tasks.universalJar
+ ].forEach{ packed ->
+ def 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")
+ }
+
+ try (def zip = new java.util.zip.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 (!entries.containsKey(key))
+ entries.put(key, line)
+ }
+ }
+
+ output.get().asFile.text = entries.values().join('\n')
+ }
+}
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DevInstallerJar.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DevInstallerJar.groovy
deleted file mode 100644
index cb7b922091..0000000000
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/DevInstallerJar.groovy
+++ /dev/null
@@ -1,67 +0,0 @@
-package net.minecraftforge.forge.tasks
-
-import org.gradle.api.tasks.*
-import org.gradle.api.DefaultTask
-import org.gradle.api.file.RegularFileProperty
-import groovy.json.JsonSlurper
-import java.util.zip.ZipEntry
-import java.util.zip.ZipFile
-import java.util.zip.ZipOutputStream
-
-abstract class DevInstallerJar extends DefaultTask {
- @OutputFile abstract RegularFileProperty getOutput()
- @InputFile abstract RegularFileProperty getInput()
-
- DevInstallerJar() {
- output.convention(project.layout.buildDirectory.file('libs/' + project.name + '-' + project.version + '-installer-dev.jar'))
- }
-
- @TaskAction
- protected void exec() {
- try (def zos = new ZipOutputStream(output.get().asFile.newDataOutputStream())) {
- def seen = [] as Set
- def deps = [:] as java.util.TreeMap
- try (def base = new ZipFile(input.get().asFile)) {
- base.entries().each { entry ->
- zos.putNextEntry(entry)
- def data = base.getInputStream(entry).bytes
- zos.write(data)
-
- if (entry.name == 'install_profile.json' || entry.name == 'version.json') {
- def json = new JsonSlurper().parse(data)
- json.libraries.each { lib ->
- deps.put(lib.name, lib.downloads.artifact)
- }
- }
-
- if (entry.name.startsWith('maven/'))
- seen.add(entry.name.substring(6))
- }
- }
-
- def resolved = project.configurations.installer.resolvedConfiguration.resolvedArtifacts
-
- deps.each { name, info ->
- if (seen.contains(info.path))
- return
-
- def art = resolved.find { "${it.moduleVersion.id.group}:${it.moduleVersion.id.name}:${it.moduleVersion.id.version}" == name }
-
- def file = null
- if (art != null) {
- if (!Util.checkExists(info.url))
- file = art.file
- } else {
- // TODO download missing things
- }
-
- if (file != null) {
- //println('maven/' + info.path)
- zos.putNextEntry(new ZipEntry('maven/' + info.path))
- zos.write(file.bytes)
- seen.add(info.path)
- }
- }
- }
- }
-}
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy
new file mode 100644
index 0000000000..315e3114d9
--- /dev/null
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/ExtractFile.groovy
@@ -0,0 +1,24 @@
+package net.minecraftforge.forge.tasks
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.*
+
+abstract class ExtractFile extends DefaultTask {
+ @InputFile abstract RegularFileProperty getInput()
+ @Input abstract Property getTarget()
+ @OutputFile abstract RegularFileProperty getOutput()
+
+ @TaskAction
+ protected void exec() {
+ def zip = new java.util.zip.ZipFile(input.get().asFile);
+ def entry = zip.getEntry(target.get())
+ if (entry == null)
+ throw new IllegalStateException(input.get().asFile.absolutePath + " does not contain " + target.get())
+ def stream = zip.getInputStream(entry)
+ output.get().asFile.withOutputStream { out ->
+ stream.transferTo(out)
+ }
+ }
+}
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy
index d40fbee418..4f25eea1c4 100644
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJar.groovy
@@ -2,21 +2,26 @@ package net.minecraftforge.forge.tasks
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.*
-import org.gradle.api.provider.SetProperty
+import org.gradle.api.DefaultTask
+import org.gradle.api.provider.Property
+import groovy.json.JsonSlurper
abstract class InstallerJar extends Zip {
- @Input @Optional abstract SetProperty getPackedDependencies()
+ @Input @Optional abstract Property getFat()
+ @Input @Optional abstract Property 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)
+ dependsOn(installerJson, launcherJson, downloadInstaller, project.configurations.installer)
from(installerJson, launcherJson)
from(project.rootProject.file('/src/main/resources/url.png'))
@@ -24,21 +29,128 @@ abstract class InstallerJar extends Zip {
from(project.zipTree(downloadInstaller.output)) {
duplicatesStrategy = 'exclude'
}
-
- if (!System.env.TEAMCITY_VERSION) {
- dependsOn(project.universalJar)
- from(project.universalJar) {
- into '/maven/' + project.group.replace('.', '/') + '/' + project.universalJar.archiveBaseName.get() + '/' + project.version + '/'
+
+ 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)
}
-
- packedDependencies.get().forEach {
- def jarTask = project.rootProject.getTasks().findByPath(it)
- dependsOn(jarTask)
- from(jarTask) {
- into '/maven/' + jarTask.project.group.replace('.', '/') + '/' + jarTask.archiveBaseName.get() + '/' + jarTask.project.version + '/'
+ 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 { 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 ->
+ deps.put(lib.name, lib.downloads.artifact)
+ //println(lib.name)
+ }
+ }
+
+ // First find things we build in this project.
+ [
+ project.tasks.universalJar, // Forge runtime code
+ project.tasks.serverShimJar // Shim jar for dedicated server
+ ].forEach { 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 (var 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) {
+ def pack = parent.offline.get() || info.url.isEmpty()
+
+ // If it's a offline jar just always pack
+ if (!pack) {
+ try {
+ def remote = new URL("${info.url}.sha1").getText('UTF-8')
+ pack = !info.sha1.equals(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" }
+ }
+ }
+ }
+ }
}
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy
index 4842c9f607..8ad1460dc1 100644
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/InstallerJson.groovy
@@ -13,7 +13,6 @@ import java.nio.file.Files
abstract class InstallerJson extends DefaultTask {
@OutputFile abstract RegularFileProperty getOutput()
@InputFiles abstract ConfigurableFileCollection getInput()
- @Input @Optional abstract SetProperty getPackedDependencies()
@Input @Optional final Map libraries = new LinkedHashMap<>()
@Input Map json = new LinkedHashMap<>()
@InputFile abstract RegularFileProperty getIcon()
@@ -23,29 +22,19 @@ abstract class InstallerJson extends DefaultTask {
@Input abstract Property getWelcome()
InstallerJson() {
- getLauncherJsonName().convention('/version.json')
- getLogo().convention('/big_logo.png')
- getMirrors().convention('https://files.minecraftforge.net/mirrors-2.0.json')
- getWelcome().convention("Welcome to the simple ${project.name.capitalize()} installer.")
-
- getOutput().convention(project.layout.buildDirectory.file('install_profile.json'))
-
- ['client', 'server'].each { side ->
- ['slim', 'extra'].each { type ->
- def tsk = project.tasks.getByName("download${side.capitalize()}${type.capitalize()}")
- dependsOn(tsk)
- input.from(tsk.output)
- }
- def tsk = project.tasks.getByName("create${side.capitalize()}SRG")
- dependsOn(tsk)
- input.from(tsk.output)
- }
-
+ 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 {
- (packedDependencies.get().collect{ project.rootProject.tasks.findByPath(it) } + [project.universalJar]).forEach {
- dependsOn(it)
- input.from it.archiveFile
+ [
+ project.tasks.universalJar,
+ project.tasks.serverShimJar
+ ].forEach { packed ->
+ dependsOn(packed)
+ input.from packed.archiveFile
}
}
}
@@ -53,17 +42,19 @@ abstract class InstallerJson extends DefaultTask {
@TaskAction
protected void exec() {
def libs = libraries
- for (def child : packedDependencies.get().collect{ project.rootProject.tasks.findByPath(it) } + [project.universalJar]) {
- def dep = Util.getMavenDep(child)
- def path = Util.getMavenPath(child)
- libs.put(dep.toString(), [
- name: dep,
+ [
+ project.tasks.universalJar,
+ project.tasks.serverShimJar
+ ].forEach { packed ->
+ def info = Util.getMavenInfoFromTask(packed)
+ libs.put(info.name, [
+ name: info.name,
downloads: [
artifact: [
- path: path,
- url: "https://maven.minecraftforge.net/${path}",
- sha1: child.archiveFile.get().asFile.sha1(),
- size: child.archiveFile.get().asFile.length()
+ path: info.path,
+ url: "https://maven.minecraftforge.net/$info.path",
+ sha1: packed.archiveFile.get().asFile.sha1(),
+ size: packed.archiveFile.get().asFile.length()
]
]
])
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy
index 4f730daf23..38a1c20669 100644
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/LauncherJson.groovy
@@ -16,59 +16,63 @@ abstract class LauncherJson extends DefaultTask {
@OutputFile abstract RegularFileProperty getOutput()
@InputFiles abstract ConfigurableFileCollection getInput()
@Input Map json = new LinkedHashMap<>()
- @Input @Optional abstract SetProperty getPackedDependencies()
-
- @Internal final vanilla = project.project(':mcp').file('build/mcp/downloadJson/version.json')
- @Internal final timestamp = iso8601Now()
- @Internal final 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/"
- ]
- @Internal final id = "${project.rootProject.ext.MC_VERSION}-${project.name}${project.version.substring(project.rootProject.ext.MC_VERSION.length())}"
LauncherJson() {
- getOutput().convention(project.layout.buildDirectory.file('version.json'))
+ output.convention(project.layout.buildDirectory.file('libs/version.json'))
- dependsOn(':fmlloader:jar', 'universalJar')
- getInput().from(project.tasks.universalJar.archiveFile,
- project.project(':fmlloader').jar.archiveFile,
- vanilla)
-
- project.afterEvaluate {
- packedDependencies.get().forEach {
- def jarTask = project.rootProject.tasks.findByPath(it)
- dependsOn(jarTask)
- input.from jarTask.archiveFile
+ dependsOn(project.tasks.universalJar)
+ input.from(project.tasks.universalJar.archiveFile)
+ input.from(project.configurations.installer)
+ 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
}
}
}
@TaskAction
protected void exec() {
- if (!json.libraries)
- json.libraries = []
- def libs = [:]
- getArtifacts(project, project.configurations.installer, false).each { key, lib -> libs[key] = lib }
- getArtifacts(project, project.configurations.moduleonly, false).each { key, lib -> libs[key] = lib }
-
- packedDependencies.get().collect{ project.rootProject.tasks.findByPath(it) }.forEach {
- def path = Util.getMavenPath(it)
- def key = Util.getMavenDep(it)
-
- libs[key] = [
- name: key,
+ [
+ project.tasks.universalJar
+ ].forEach { packed ->
+ def info = Util.getMavenInfoFromTask(packed)
+ json.libraries.add([
+ name: info.name,
downloads: [
artifact: [
- path: path,
- url: "https://maven.minecraftforge.net/${path}",
- sha1: it.archiveFile.get().asFile.sha1(),
- size: it.archiveFile.get().asFile.length()
+ path: info.path,
+ url: "https://maven.minecraftforge.net/$info.path",
+ sha1: packed.archiveFile.get().asFile.sha1(),
+ size: packed.archiveFile.get().asFile.length()
]
]
- ]
+ ])
+ }
+ getArtifacts(project, project.configurations.installer).each { key, lib ->
+ json.libraries.add(lib)
}
- libs.each { key, lib -> json.libraries.add(lib) }
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
}
}
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy
index d7f76b672e..09aa226a53 100644
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/SetupCheckJarCompatibility.groovy
@@ -26,16 +26,6 @@ abstract class SetupCheckJarCompatibility extends DefaultTask {
@TaskAction
void run() {
def inputVersion = inputVersion.get()
- def fmlLibs = project.configurations.detachedConfiguration(project.PACKED_DEPS.collect {
- def artifactId = it.split(':')[1]
- return project.dependencies.create("net.minecraftforge:${artifactId}:${inputVersion}")
- }.toArray(Dependency[]::new))
-
- project.tasks.named('checkJarCompatibility') {
- baseLibraries.from(project.provider {
- fmlLibs.resolvedConfiguration.lenientConfiguration.files
- })
- }
def baseForgeUserdev = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-userdev.jar") }.get().asFile
project.rootProject.extensions.download.run {
diff --git a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy
index 6c810e7131..37bf48ffca 100644
--- a/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy
+++ b/buildSrc/src/main/groovy/net/minecraftforge/forge/tasks/Util.groovy
@@ -16,25 +16,33 @@ import java.util.zip.ZipInputStream
public class Util {
static final ASM_LEVEL = Opcodes.ASM9
- static void init() {
- File.metaClass.sha1 = { ->
- MessageDigest md = MessageDigest.getInstance('SHA-1')
- delegate.eachByte 4096, {bytes, size ->
- md.update(bytes, 0, size)
- }
- return md.digest().collect {String.format "%02x", it}.join()
- }
+ static void init() {
+ File.metaClass.sha1 = { ->
+ MessageDigest md = MessageDigest.getInstance('SHA-1')
+ delegate.eachByte 4096, {bytes, size ->
+ md.update(bytes, 0, size)
+ }
+ return md.digest().collect {String.format "%02x", it}.join()
+ }
File.metaClass.getSha1 = { !delegate.exists() ? null : delegate.sha1() }
+ File.metaClass.sha256 = { ->
+ MessageDigest md = MessageDigest.getInstance('SHA-256')
+ delegate.eachByte 4096, {bytes, size ->
+ md.update(bytes, 0, size)
+ }
+ return md.digest().collect {String.format "%02x", it}.join()
+ }
+ File.metaClass.getSha256 = { !delegate.exists() ? null : delegate.sha256() }
- File.metaClass.json = { -> new JsonSlurper().parseText(delegate.text) }
+ 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 = { ->
- def format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
- def result = format.format(delegate)
- return result[0..21] + ':' + result[22..-1]
- }
+ Date.metaClass.iso8601 = { ->
+ def format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
+ def result = format.format(delegate)
+ return result[0..21] + ':' + result[22..-1]
+ }
String.metaClass.rsplit = { String del, int limit = -1 ->
def lst = new ArrayList()
@@ -47,100 +55,117 @@ public class Util {
lst.add(0, tmp)
return lst
}
- }
-
- public static String[] getClasspath(project, libs, artifact) {
- def ret = []
- artifactTree(project, artifact).each { key, lib ->
- libs[lib.name] = lib
- if (lib.name != artifact)
- ret.add(lib.name)
- }
- return ret
- }
-
- public static def getArtifacts(project, config, classifiers) {
- def ret = [:]
- config.resolvedConfiguration.resolvedArtifacts.each {
- def art = [
- group: it.moduleVersion.id.group,
- name: it.moduleVersion.id.name,
- version: it.moduleVersion.id.version,
- classifier: it.classifier,
- extension: it.extension,
- file: it.file
- ]
- def key = art.group + ':' + art.name
- def folder = "${art.group.replace('.', '/')}/${art.name}/${art.version}/"
- def filename = "${art.name}-${art.version}"
- if (art.classifier != null)
- filename += "-${art.classifier}"
- filename += ".${art.extension}"
- def path = "${folder}${filename}"
- def url = "https://libraries.minecraft.net/${path}"
- if (!checkExists(url)) {
- url = "https://maven.minecraftforge.net/${path}"
- }
- ret[key] = [
- name: "${art.group}:${art.name}:${art.version}" + (art.classifier == null ? '' : ":${art.classifier}") + (art.extension == 'jar' ? '' : "@${art.extension}"),
- downloads: [
- artifact: [
- path: path,
- url: url,
- sha1: sha1(art.file),
- size: art.file.length()
- ]
- ]
- ]
- }
- return ret
- }
-
- public static def getMavenPath(task) {
- def classifier = task.archiveClassifier.get()
- def dep = "${task.project.group}:${task.project.name}:${task.project.version}" + (classifier == '' ? '' : ':' + classifier)
- return "${task.project.group.replace('.', '/')}/${task.project.name}/${task.project.version}/${task.project.name}-${task.project.version}".toString() + (classifier == '' ? '' : '-' + classifier) + '.jar'
}
- public static def getMavenDep(task) {
- def classifier = task.archiveClassifier.get()
- return "${task.project.group}:${task.project.name}:${task.project.version}" + (classifier == '' ? '' : ':' + classifier)
+ public static String[] getClasspath(project, libs, artifact) {
+ def ret = []
+ artifactTree(project, artifact).each { key, lib ->
+ libs[lib.name] = lib
+ if (lib.name != artifact)
+ ret.add(lib.name)
+ }
+ return ret
}
- public static def iso8601Now() { new Date().iso8601() }
+ public static def getArtifacts(project, config) {
+ def ret = [:]
+ config.resolvedConfiguration.resolvedArtifacts.each { dep ->
+ def info = getMavenInfoFromDep(dep)
+ def url = "https://libraries.minecraft.net/$info.path"
+ if (!checkExists(url))
+ url = "https://maven.minecraftforge.net/$info.path"
+
+ ret[info.key] = [
+ name: info.name,
+ downloads: [
+ artifact: [
+ path: info.path,
+ url: url,
+ sha1: dep.file.sha1(),
+ size: dep.file.length()
+ ]
+ ]
+ ]
+ }
+ return ret
+ }
+
+ public static Map getMavenInfoFromDep(dep) {
+ return getMavenInfoFromMap([
+ group: dep.moduleVersion.id.group,
+ name: dep.moduleVersion.id.name,
+ version: dep.moduleVersion.id.version,
+ classifier: dep.classifier,
+ extension: dep.extension
+ ])
+ }
+ public static Map getMavenInfoFromTask(task) {
+ return getMavenInfoFromMap([
+ group: task.project.group,
+ name: task.project.name,
+ version: task.project.version,
+ classifier: task.archiveClassifier.get(),
+ extension: task.archiveExtension.get()
+ ])
+ }
+
+ private static Map getMavenInfoFromMap(art) {
+ def key = "$art.group:$art.name"
+ def name = "$art.group:$art.name:$art.version"
+ def path = "${art.group.replace('.', '/')}/$art.name/$art.version/$art.name-$art.version"
+ if (art.classifier != null) {
+ name += ":$art.classifier"
+ path += "-$art.classifier"
+ }
+ if (!'jar'.equals(art.extension)) {
+ name += "@$art.extension"
+ path += ".$art.extension"
+ } else {
+ path += ".jar"
+ }
+ return [
+ key: key,
+ name: name,
+ path: path,
+ art: art
+ ]
+ }
- public static def sha1(file) {
- MessageDigest md = MessageDigest.getInstance('SHA-1')
- file.eachByte 4096, {bytes, size ->
- md.update(bytes, 0, size)
- }
- return md.digest().collect {String.format "%02x", it}.join()
- }
+ public static def iso8601Now() { new Date().iso8601() }
- private static def artifactTree(project, artifact) {
- if (!project.ext.has('tree_resolver'))
- project.ext.tree_resolver = 1
- def cfg = project.configurations.create('tree_resolver_' + project.ext.tree_resolver++)
- def dep = project.dependencies.create(artifact)
- cfg.dependencies.add(dep)
- def files = cfg.resolve()
- return getArtifacts(project, cfg, true)
- }
+ public static def sha1(file) {
+ MessageDigest md = MessageDigest.getInstance('SHA-1')
+ file.eachByte 4096, {bytes, size ->
+ md.update(bytes, 0, size)
+ }
+ return md.digest().collect {String.format "%02x", it}.join()
+ }
- static boolean checkExists(url) {
- try {
- def code = new URL(url).openConnection().with {
- requestMethod = 'HEAD'
- connect()
- responseCode
- }
- return code == 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
- }
- }
+ private static def artifactTree(project, artifact, 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(project, cfg)
+ }
+
+ static boolean checkExists(url) {
+ try {
+ def code = new URL(url).openConnection().with {
+ requestMethod = 'HEAD'
+ connect()
+ responseCode
+ }
+ return code == 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(mcVersion) {
final json = new JsonSlurper().parseText(new URL('https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json').getText('UTF-8'))
diff --git a/build_clean.gradle b/build_clean.gradle
index aceb952700..29c4ab776c 100644
--- a/build_clean.gradle
+++ b/build_clean.gradle
@@ -1,11 +1,19 @@
plugins {
id 'java-library'
- id 'eclipse'
- id 'net.minecraftforge.gradle.patcher' version '[6.0.16,6.2)'
+ id 'org.cadixdev.licenser'
+ 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)
}
@@ -44,8 +52,14 @@ patcher {
}
}
+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' }
- src.entryAttributes['ignore_optional_problems'] = 'true'
-}
+ if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
+ src.entryAttributes['ignore_optional_problems'] = 'true'
+}
\ No newline at end of file
diff --git a/build_forge.gradle b/build_forge.gradle
new file mode 100644
index 0000000000..f9a47c03c9
--- /dev/null
+++ b/build_forge.gradle
@@ -0,0 +1,1034 @@
+import net.minecraftforge.forge.tasks.checks.CheckATs
+import net.minecraftforge.forge.tasks.checks.CheckExcs
+import net.minecraftforge.forge.tasks.checks.CheckPatches
+import net.minecraftforge.forge.tasks.checks.CheckSAS
+import net.minecraftforge.forge.tasks.checks.CheckTask
+
+import java.util.Date
+import java.util.LinkedHashMap
+import net.minecraftforge.forge.tasks.*
+import static net.minecraftforge.forge.tasks.Util.*
+import net.minecraftforge.gradle.common.tasks.ApplyBinPatches
+import net.minecraftforge.gradle.common.tasks.CheckJarCompatibility
+import net.minecraftforge.gradle.common.tasks.DownloadMavenArtifact
+import net.minecraftforge.gradle.common.tasks.ExtractInheritance
+import net.minecraftforge.gradle.patcher.tasks.GeneratePatches
+import net.minecraftforge.gradle.userdev.tasks.RenameJar
+import net.minecraftforge.gradleutils.PomUtils
+import org.apache.tools.ant.filters.ReplaceTokens
+import org.objectweb.asm.Opcodes
+
+plugins {
+ id 'idea'
+ id 'eclipse'
+ id 'java-library'
+ id 'maven-publish'
+ id 'org.cadixdev.licenser'
+ id 'de.undercouch.download'
+ id 'net.minecraftforge.gradleutils'
+ id 'net.minecraftforge.gradle.patcher'
+ id 'net.minecraftforge.gradlejarsigner'
+}
+
+Util.init() //Init all our extension methods!
+
+// We depend on all other projects so that we can know their versions for userdev config
+rootProject.subprojects.each { sib -> if (sib != project) evaluationDependsOn(sib.path) }
+
+apply from: rootProject.file('build_shared.gradle')
+
+java {
+ toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
+ withSourcesJar()
+}
+
+jarSigner.autoDetect('forge')
+
+applyPatches {
+ level 'WARNING'
+}
+
+sourceSets {
+ main {
+ java {
+ srcDir "$rootDir/src/main/java"
+ }
+ resources {
+ srcDir "$rootDir/src/main/resources"
+ srcDir "$rootDir/src/main/generated"
+ }
+ }
+ test {
+ java {
+ srcDir "$rootDir/src/test/java"
+ }
+ resources {
+ srcDir "$rootDir/src/test/resources"
+ srcDir "$rootDir/src/test/generated"
+ }
+ }
+}
+
+ext {
+ SPEC_VERSION = gradleutils.gitInfo.tag
+ // The new versioning sceme is -..
+ // ForgeMC is a unique identifier for every MC version we have supported.
+ // Essentially, the same as the old, except dropping the first number, and the builds are no longer unique.
+ MCP_ARTIFACT = project(':mcp').mcp.config.get()
+
+ EXTRA_TXTS = [
+ rootProject.file('CREDITS.txt'),
+ rootProject.file('LICENSE.txt'),
+ rootProject.tasks.createChangelog.outputFile
+ ]
+}
+
+configurations {
+ // Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
+ bootstrap { transitive = false }
+ installer {
+ extendsFrom(bootstrap)
+ transitive = false
+ }
+ api.extendsFrom(installer)
+}
+
+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.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
+
+ installer(libs.bootstrap)
+ installer(libs.bootstrap.api) // Needed by securemodules
+ installer(libs.accesstransformers)
+ installer(libs.antlr.runtime) // Dep of AccessTransformer
+ installer(libs.eventbus)
+ installer(libs.typetools) // Dep of EventBus
+ installer(libs.forgespi)
+ installer(libs.coremods)
+ installer(libs.nashorn) // Dep of Coremods
+ 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.bundles.jarjar)
+
+ installer(project(':fmlcore'))
+ installer(project(':fmlloader'))
+ installer(project(':fmlearlydisplay'))
+ installer(project(':javafmllanguage'))
+ installer(project(':lowcodelanguage'))
+ installer(project(':mclanguage'))
+
+ runtimeOnly(libs.bootstrap)
+}
+
+patcher {
+ excs.from file("$rootDir/src/main/resources/forge.exc")
+ parent = project(':mcp')
+ mcVersion = MC_VERSION
+ mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
+ patches = file("$rootDir/patches/minecraft")
+ patchedSrc = file('src/main/java')
+ srgPatches = false
+ accessTransformers.from file("$rootDir/src/main/resources/META-INF/accesstransformer.cfg")
+ sideAnnotationStrippers.from file("$rootDir/src/main/resources/forge.sas")
+
+ runs {
+ forge_client {
+ property 'eventbus.checkTypesOnDispatch', 'true'
+ property 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
+
+ args '--launchTarget', 'forge_dev_client',
+ '--username', 'Dev',
+ '--version', project.name,
+ '--accessToken', '0',
+ '--userType', 'mojang',
+ '--versionType', 'release',
+ '--assetsDir', downloadAssets.output,
+ '--assetIndex', "{asset_index}"
+ }
+
+ forge_client_test {
+ parent runs.forge_client
+ }
+
+ forge_server {
+ args '--launchTarget', 'forge_dev_server'
+ }
+
+ forge_server_test {
+ parent runs.forge_server
+ }
+
+ forge_server_gametest {
+ args '--launchTarget', 'forge_dev_server_gametest'
+ }
+
+ forge_server_gametest_test {
+ parent runs.forge_server_gametest
+ }
+
+ forge_data {
+ args '--launchTarget', 'forge_dev_data',
+ '--mod', 'forge',
+ '--all',
+ '--validate',
+ '--output', rootProject.file('src/main/generated/'),
+ '--validate',
+ '--existing', sourceSets.main.resources.srcDirs[0],
+ '--assetsDir', downloadAssets.output,
+ '--assetIndex', "{asset_index}"
+ }
+
+ forge_data_test {
+ args '--launchTarget', 'forge_dev_data',
+ '--mod', '.+',
+ '--all',
+ '--validate',
+ '--output', rootProject.file('src/test/generated/'),
+ '--existing', sourceSets.main.resources.srcDirs[0],
+ '--existing', sourceSets.test.resources.srcDirs[0],
+ '--assetsDir', downloadAssets.output,
+ '--assetIndex', "{asset_index}"
+ }
+
+ }
+}
+
+afterEvaluate {
+ if (!patcher.srgPatches) {
+ srg2mcpClean {
+ dependsOn = []
+ input = project(':mcp').setupMCP.output
+ }
+ userdevJar {
+ onlyIf = { t -> true }
+ }
+ def patches = project.file('build/genPatchesForUserdev/output/')
+ patches.mkdirs()
+ def genPatchesForUserdev = tasks.register('genPatchesForUserdev', GeneratePatches){
+ base = project(':mcp').setupMCP.output
+ modified = applyRangeMapBase.output
+ originalPrefix = genPatches.originalPrefix
+ modifiedPrefix = genPatches.modifiedPrefix
+ output = patches
+ autoHeader true
+ lineEnding = '\n'
+ }
+ bakePatches {
+ dependsOn = []
+ input = genPatchesForUserdev.get().output
+ }
+ }
+}
+
+tasks.register('downloadCrowdin', Download) {
+ src 'https://files.minecraftforge.net/crowdin.zip'
+ dest file('build/crowdin.zip')
+ useETag 'all'
+ onlyIfModified true
+ quiet true
+}
+
+tasks.userdevConfig.configure {
+ configurations.installer.allDependencies.forEach {
+ def dep = it.toString()
+ if (it instanceof ProjectDependency)
+ dep = "net.minecraftforge:$it.dependencyProject.name:$it.dependencyProject.version"
+ libraries.add(dep)
+ }
+
+ inject = '' // We don't have a userdev sourceset anymore. Empty as a gradle workaround...
+ runs {
+ client {
+ environment 'MCP_MAPPINGS', '{mcp_mappings}'
+ property 'forge.enableGameTest', 'true'
+ args '--launchTarget', "forge_userdev_client"
+ args '--version', 'MOD_DEV'
+ args '--assetIndex', '{asset_index}'
+ args '--assetsDir', '{assets_root}'
+ }
+
+ server {
+ environment 'MCP_MAPPINGS', '{mcp_mappings}'
+ property 'forge.enableGameTest', 'true'
+ args '--launchTarget', "forge_userdev_server"
+ }
+
+ gameTestServer {
+ environment 'MCP_MAPPINGS', '{mcp_mappings}'
+ args '--launchTarget', "forge_userdev_server_gametest"
+ }
+
+ data {
+ environment 'MCP_MAPPINGS', '{mcp_mappings}'
+ args '--launchTarget', "forge_userdev_data"
+ args '--assetIndex', '{asset_index}'
+ args '--assetsDir', '{assets_root}'
+ }
+ }
+}
+
+for (def run : patcher.runs + tasks.userdevConfig.runs) {
+ if (run.parents) continue // We already added this to the parent run config
+ //run.property 'bsl.debug', 'true'
+ run.args '--gameDir', '.'
+ run.jvmArgs '-Djava.net.preferIPv6Addresses=system'
+ run.client run.name.contains('client')
+ run.main 'net.minecraftforge.bootstrap.ForgeBootstrap'
+}
+
+for (def run : patcher.runs) {
+ def isTest = run.name.endsWith('_test')
+ run.taskName = run.name
+ run.workingDirectory file('run/' + run.name)
+ run.ideaModule rootProject.name + '.' + project.name + '.' + (isTest ? 'test' : 'main')
+ run.property 'bsl.debug', 'true'
+ run.property 'terminal.jline', 'true'
+ if (isTest) {
+ run.property 'forge.enableGameTest', 'true'
+ run.property 'forgedev.enableTestMods', 'true'
+ }
+}
+
+tasks.register('downloadVersionManifest', Download) {
+ src 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'
+ dest file('build/versions/version_manifest.json')
+ useETag 'all'
+ onlyIfModified true
+ quiet true
+}
+tasks.register('downloadJson', Download) {
+ dependsOn downloadVersionManifest
+ inputs.file downloadVersionManifest.dest
+ src { downloadVersionManifest.dest.json.versions.find{ it.id == MC_VERSION }.url }
+ dest file("build/versions/$MC_VERSION/version.json")
+ useETag 'all'
+ onlyIfModified true
+ quiet true
+}
+tasks.register('downloadClientRaw', Download) {
+ dependsOn downloadJson
+ inputs.file downloadJson.dest
+ src { downloadJson.dest.json.downloads.client.url }
+ dest file("build/versions/$MC_VERSION/client.jar")
+ useETag 'all'
+ onlyIfModified true
+ quiet true
+}
+tasks.register('downloadServerRaw', Download) {
+ dependsOn downloadJson
+ inputs.file downloadJson.dest
+ src { downloadJson.dest.json.downloads.server.url }
+ dest file("build/versions/$MC_VERSION/server-bundled.jar")
+ useETag 'all'
+ onlyIfModified true
+ quiet true
+}
+tasks.register('extractServer', ExtractFile) {
+ dependsOn downloadServerRaw
+ input = downloadServerRaw.dest
+ target = "META-INF/versions/$MC_VERSION/server-${MC_VERSION}.jar"
+ output = file("build/versions/$MC_VERSION/server.jar")
+}
+tasks.register('downloadLibraries', DownloadLibraries) {
+ dependsOn downloadJson
+ input = downloadJson.dest
+ output = rootProject.file('build/libraries/')
+}
+tasks.register('extractInheritance', ExtractInheritance) {
+ dependsOn downloadLibraries
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args.add '--annotations'
+ input = genJoinedBinPatches.cleanJar
+ libraries.addAll downloadLibraries.librariesOutput.map { rf ->
+ java.nio.file.Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).collect(java.util.stream.Collectors.toList())
+ }
+}
+tasks.register("findFieldInstanceChecks", FieldCompareFinder) {
+ jar = createJoinedSRG.output
+ output = rootProject.file('src/main/resources/coremods/field_to_instanceof.json')
+ fields {
+ /* 1.17 changed most things to use Tags. So this isn't nessasary anymore so just make an empty list
+ bows {
+ cls = 'net/minecraft/world/item/Items'
+ name = 'f_42411_'
+ replacement = 'net/minecraft/world/item/BowItem'
+ }
+ crossbows {
+ cls = 'net/minecraft/world/item/Items'
+ name = 'f_42717_'
+ replacement = 'net/minecraft/world/item/CrossbowItem'
+ }
+ */
+ }
+}
+tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
+ jar = createJoinedSRG.output
+ output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json')
+ predicate = {
+ parent, node, insn ->
+ 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
+ && insn.getOpcode() == Opcodes.INVOKEVIRTUAL
+ && insn.name.equals('m_6518_')
+ && insn.desc.equals('(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;')
+ }
+}
+tasks.register('validateDeprecations', ValidateDeprecations) {
+ input = tasks.jar.archiveFile
+ mcVersion = MC_VERSION
+}
+tasks.jar.finalizedBy 'validateDeprecations'
+tasks.register("downloadInstaller", DownloadMavenArtifact) {
+ artifact = "net.minecraftforge:installer:2.2.+:fatjar"
+ changing = true
+}
+tasks.register("downloadServerShim", DownloadMavenArtifact) {
+ artifact = libs.bootstrap.shim.get().toString()
+ changing = true
+}
+tasks.register("downloadMCPConfig", DownloadMavenArtifact) {
+ artifact = MCP_ARTIFACT
+}
+tasks.register('extractMCPConfigMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
+ ext.output = file('build/mcp_mappings.tsrg')
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args = ['--task', 'MCP_DATA', '--key', 'mappings', '--input', downloadMCPConfig.output.get().asFile.absolutePath, '--output', output.absolutePath]
+ outputs.file(output)
+ inputs.file(downloadMCPConfig.output)
+}
+tasks.register('downloadClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
+ ext.output = file('build/client_mappings.tsrg')
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'client', '--output', output.absolutePath]
+ outputs.file(output)
+}
+tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
+ ext.output = file('build/server_mappings.tsrg')
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath]
+ outputs.file(output)
+}
+tasks.register('mergeClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
+ ext.output = file('build/client_mappings_merged.tsrg')
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadClientMappings.output.absolutePath, '--output', output.absolutePath]
+ outputs.file(output)
+}
+tasks.register('mergeServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
+ ext.output = file('build/server_mappings_merged.tsrg')
+ tool = INSTALLER_TOOLS + ':fatjar'
+ args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadServerMappings.output.absolutePath, '--output', output.absolutePath]
+ outputs.file(output)
+}
+tasks.register("createJoinedSRG", DownloadMavenArtifact) {
+ artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
+}
+tasks.register("createClientSRG", RenameJar) {
+ tool = FART + ':all'
+ args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
+ mappings = createMcp2Srg.srg
+ dependsOn(downloadClientRaw)
+ input = downloadClientRaw.dest
+ output = file("build/createClientSRG/output.jar")
+}
+tasks.register("createServerSRG", RenameJar) {
+ tool = FART + ':all'
+ args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
+ mappings = createMcp2Srg.srg
+ input = extractServer.output
+ output = file("build/createServerSRG/output.jar")
+}
+tasks.named('genClientBinPatches').configure {
+ tool = BINPATCH_TOOL
+ cleanJar = createClientSRG.output
+}
+tasks.named('genServerBinPatches').configure {
+ tool = BINPATCH_TOOL
+ cleanJar = createServerSRG.output
+}
+tasks.named('genJoinedBinPatches').configure {
+ tool = BINPATCH_TOOL
+ cleanJar = createJoinedSRG.output
+}
+tasks.register('applyClientBinPatches', ApplyBinPatches) {
+ tool = BINPATCH_TOOL
+ clean = createClientSRG.output
+ patch = genClientBinPatches.output
+ args.addAll(['--data', '--unpatched'])
+}
+tasks.register('applyServerBinPatches', ApplyBinPatches) {
+ tool = BINPATCH_TOOL
+ clean = createServerSRG.output
+ patch = genServerBinPatches.output
+ args.addAll(['--data', '--unpatched'])
+}
+tasks.register('applyJoinedBinPatches', ApplyBinPatches) {
+ tool = BINPATCH_TOOL
+ clean = genJoinedBinPatches.cleanJar
+ patch = genJoinedBinPatches.output
+}
+tasks.register('createServerShimClasspath', BundleList) {
+ dependsOn(downloadServerRaw)
+ serverBundle = downloadServerRaw.dest
+}
+tasks.register('createServerShimConfig') {
+ ext.output = file('build/libs/bootstrap-shim.properties')
+ doLast {
+ def cfg = new CleanProperties()
+ cfg."Main-Class" = 'net.minecraftforge.bootstrap.ForgeBootstrap'
+ cfg."Java-Version" = '17'
+ cfg."Arguments" = "--launchTarget forge_server"
+ cfg.store(output)
+ }
+}
+tasks.register('serverShimJar', Jar) {
+ dependsOn(createServerShimConfig)
+ from (createServerShimConfig.output)
+ from (createServerShimClasspath.output) {
+ rename { 'bootstrap-shim.list' }
+ }
+ from (zipTree(downloadServerShim.output))
+ manifest {
+ from {
+ zipTree(downloadServerShim.output).find { it.name == 'MANIFEST.MF' }
+ }
+
+ attributes('Class-Path': configurations.bootstrap.resolvedConfiguration.resolvedArtifacts.collect { "libraries/${Util.getMavenInfoFromDep(it).path}" }.join(' '))
+ }
+ archiveClassifier = 'shim'
+ jarSigner.sign(it)
+}
+tasks.register('checkAll') {
+ dependsOn 'checkLicenses'
+ group = 'checks'
+}
+tasks.register('checkAllAndFix') {
+ dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses'
+ group = 'checks'
+}
+
+CheckTask.registerTask(tasks, 'ATs', CheckATs) {
+ dependsOn extractInheritance, createSrg2Mcp
+ ats.from patcher.accessTransformers
+ inheritance = extractInheritance.output
+ mappings = createSrg2Mcp.output
+}
+
+CheckTask.registerTask(tasks, 'SAS', CheckSAS) {
+ dependsOn extractInheritance
+ sass.from patcher.sideAnnotationStrippers
+ inheritance = extractInheritance.output
+}
+
+CheckTask.registerTask(tasks, 'Excs', CheckExcs) {
+ dependsOn jar
+ binary = jar.archiveFile.get().asFile
+ excs.from patcher.excs
+}
+
+CheckTask.registerTask(tasks, 'Patches', CheckPatches) {
+ dependsOn genPatches
+ patchDir = file("$rootDir/patches")
+ patchesWithS2SArtifact = [
+ 'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
+ 'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
+ ]
+}
+
+genPatches {
+ finalizedBy checkAndFixPatches
+ autoHeader true
+ lineEnding = '\n'
+}
+
+def baseForgeVersionProperty = project.objects.property(String)
+baseForgeVersionProperty.set(project.provider { TeamcityRequests.attemptFindBase(rootDir) ?: getLatestForgeVersion(MC_VERSION) })
+baseForgeVersionProperty.finalizeValueOnRead()
+def jarCompatibilityTaskSetup = { task ->
+ task.group = 'jar compatibility'
+ task.onlyIf {
+ baseForgeVersionProperty.getOrNull() != null
+ }
+}
+
+tasks.register('setupCheckJarCompatibility', SetupCheckJarCompatibility) {
+ inputVersion = baseForgeVersionProperty
+}
+
+tasks.register('applyBaseCompatibilityJarBinPatches', ApplyBinPatches) {
+ jarCompatibilityTaskSetup(it)
+
+ clean = project.tasks.createJoinedSRG.output
+ patch = project.tasks.named('setupCheckJarCompatibility').flatMap { it.baseBinPatchesOutput }
+ output = project.layout.buildDirectory.dir(name).map { it.file('output.jar') }
+}
+
+tasks.register('mergeBaseForgeJar', MergeJars) {
+ jarCompatibilityTaskSetup(it)
+
+ inputJars.from(project.tasks.named('applyBaseCompatibilityJarBinPatches').flatMap { it.output })
+ inputJars.from(baseForgeVersionProperty.map { inputVersion ->
+ def output = project.layout.buildDirectory.dir(name).map { it.file("forge-${inputVersion}-universal.jar") }.get().asFile
+ project.rootProject.extensions.download.run {
+ src "https://maven.minecraftforge.net/net/minecraftforge/forge/${inputVersion}/forge-${inputVersion}-universal.jar"
+ dest output
+ }
+ return output
+ })
+}
+
+tasks.register('checkJarCompatibility', CheckJarCompatibility) {
+ jarCompatibilityTaskSetup(it)
+ dependsOn 'setupCheckJarCompatibility'
+
+ baseJar = project.tasks.named('mergeBaseForgeJar').flatMap { it.output }
+ baseLibraries.from(project.tasks.named('createJoinedSRG').flatMap { it.output })
+
+ inputJar = project.tasks.named('reobfJar').flatMap { it.output }
+
+ commonLibraries.from(project.configurations.minecraftImplementation)
+ commonLibraries.from(project.configurations.installer)
+}
+
+tasks.register('launcherJson', LauncherJson).configure {
+ json.putAll([
+ mainClass: 'net.minecraftforge.bootstrap.ForgeBootstrap',
+ arguments: [
+ game: [
+ '--launchTarget', 'forge_client'
+ ],
+ jvm: [
+ '-Djava.net.preferIPv6Addresses=system'
+ ]
+ ]
+ ] as LinkedHashMap)
+}
+
+tasks.register('installerJson', InstallerJson) {
+ icon = rootProject.file('icon.ico')
+
+ // Json to install into the client's launcher
+ dependsOn(launcherJson)
+ input.from(launcherJson.output)
+
+ // Extract MCP Mappings
+ dependsOn(extractMCPConfigMappings)
+ input.from(extractMCPConfigMappings.output)
+ // Download Official Mappings
+ dependsOn(downloadClientMappings, downloadServerMappings)
+ input.from(downloadClientMappings.output, downloadServerMappings.output)
+ // Merge MCP and Official Mappings
+ dependsOn(mergeClientMappings, mergeServerMappings)
+ input.from(mergeClientMappings.output, mergeServerMappings.output)
+ // Get 'base' MC jar, Client is straight download, server is extracted from the bundle
+ dependsOn(downloadClientRaw, extractServer)
+ input.from(downloadClientRaw.dest, extractServer.output)
+ // Rename MC Jar
+ dependsOn(createClientSRG, createServerSRG)
+ input.from(createClientSRG.output, createServerSRG.output)
+ // Apply Binary patches to vanilla jar
+ dependsOn(applyClientBinPatches, applyServerBinPatches)
+ input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar)
+
+ doFirst {
+ def libs = libraries
+ def INSTALLER_TOOLS_CLASSPATH = getClasspath(project, libs, INSTALLER_TOOLS)
+ json.putAll([
+ _comment: launcherJson.json._comment,
+ hideExtract: true,
+ spec: 1,
+ profile: project.name,
+ version: launcherJson.json.id,
+ path: Util.getMavenInfoFromTask(tasks.serverShimJar).name,
+ minecraft: MC_VERSION,
+ serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar',
+ data: [
+ MAPPINGS: [
+ client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@tsrg]",
+ server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@tsrg]"
+ ],
+ MAPPINGS_SHA: [
+ client: "'${extractMCPConfigMappings.output.sha1}'",
+ server: "'${extractMCPConfigMappings.output.sha1}'"
+ ],
+ MOJMAPS: [
+ client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]",
+ server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]"
+ ],
+ MOJMAPS_SHA: [
+ client: "'${downloadClientMappings.output.sha1}'",
+ server: "'${downloadServerMappings.output.sha1}'"
+ ],
+ MERGED_MAPPINGS: [
+ client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]",
+ server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]"
+ ],
+ MERGED_MAPPINGS_SHA: [
+ client: "'${mergeClientMappings.output.sha1}'",
+ server: "'${mergeServerMappings.output.sha1}'"
+ ],
+ MC_UNPACKED: [
+ client: "[net.minecraft:client:${MC_VERSION}]",
+ server: "[net.minecraft:server:${MC_VERSION}:unpacked]"
+ ],
+ MC_UNPACKED_SHA: [
+ client: "'${downloadClientRaw.dest.sha1}'",
+ server: "'${extractServer.output.get().asFile.sha1}'"
+ ],
+ MC_SRG: [
+ client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]",
+ server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]"
+ ],
+ MC_SRG_SHA: [
+ client: "'${createClientSRG.output.get().asFile.sha1}'",
+ server: "'${createServerSRG.output.get().asFile.sha1}'"
+ ],
+ BINPATCH: [
+ client: '/data/client.lzma',
+ server: '/data/server.lzma'
+ ],
+ PATCHED: [
+ client: "[${project.group}:${project.name}:${project.version}:client]",
+ server: "[${project.group}:${project.name}:${project.version}:server]"
+ ],
+ PATCHED_SHA: [
+ client: "'${applyClientBinPatches.output.get().asFile.sha1}'",
+ server: "'${applyServerBinPatches.output.get().asFile.sha1}'"
+ ]
+ ],
+ processors: [
+ [
+ sides: ['server'],
+ jar: INSTALLER_TOOLS,
+ classpath: INSTALLER_TOOLS_CLASSPATH,
+ args: [
+ '--task', 'BUNDLER_EXTRACT',
+ '--input', '{MINECRAFT_JAR}',
+ '--output', '{ROOT}/libraries/',
+ '--libraries'
+ ]
+ ], [
+ sides: ['server'],
+ jar: INSTALLER_TOOLS,
+ classpath: INSTALLER_TOOLS_CLASSPATH,
+ args: [
+ '--task', 'BUNDLER_EXTRACT',
+ '--input', '{MINECRAFT_JAR}',
+ '--output', '{MC_UNPACKED}',
+ '--jar-only'
+ ],
+ outputs: [
+ '{MC_UNPACKED}': '{MC_UNPACKED_SHA}'
+ ]
+ ], [
+ jar: INSTALLER_TOOLS,
+ classpath: INSTALLER_TOOLS_CLASSPATH,
+ args: [
+ '--task', 'MCP_DATA',
+ '--input', "[${MCP_ARTIFACT.descriptor}]",
+ '--output', '{MAPPINGS}',
+ '--key', 'mappings'
+ ],
+ outputs: [
+ '{MAPPINGS}': '{MAPPINGS_SHA}'
+ ]
+ ], [
+ jar: INSTALLER_TOOLS,
+ classpath: INSTALLER_TOOLS_CLASSPATH,
+ args: [
+ '--task', 'DOWNLOAD_MOJMAPS',
+ '--sanitize',
+ '--version', MC_VERSION,
+ '--side', '{SIDE}',
+ '--output', '{MOJMAPS}'
+ ],
+ outputs: [
+ '{MOJMAPS}': '{MOJMAPS_SHA}'
+ ]
+ ], [
+ jar: INSTALLER_TOOLS,
+ classpath: INSTALLER_TOOLS_CLASSPATH,
+ args: [
+ '--task', 'MERGE_MAPPING',
+ '--left', '{MAPPINGS}',
+ '--right', '{MOJMAPS}',
+ '--output', '{MERGED_MAPPINGS}',
+ '--classes', '--reverse-right'
+ ],
+ outputs: [
+ '{MERGED_MAPPINGS}': '{MERGED_MAPPINGS_SHA}'
+ ]
+ ], [
+ sides: ['server'],
+ jar: FART,
+ classpath: getClasspath(project, libs, FART),
+ args: [
+ '--input', '{MC_UNPACKED}',
+ '--output', '{MC_SRG}',
+ '--names', '{MERGED_MAPPINGS}',
+ '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
+ ],
+ outputs: [
+ '{MC_SRG}': '{MC_SRG_SHA}'
+ ]
+ ], [
+ sides: ['client'],
+ jar: FART,
+ classpath: getClasspath(project, libs, FART),
+ args: [
+ '--input', '{MINECRAFT_JAR}',
+ '--output', '{MC_SRG}',
+ '--names', '{MERGED_MAPPINGS}',
+ '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
+ ],
+ outputs: [
+ '{MC_SRG}': '{MC_SRG_SHA}'
+ ]
+ ], [
+ jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar
+ classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
+ args: [
+ '--clean', '{MC_SRG}',
+ '--output', '{PATCHED}',
+ '--apply', '{BINPATCH}',
+ '--data', '--unpatched'
+ ],
+ outputs: [
+ '{PATCHED}': '{PATCHED_SHA}'
+ ]
+ ]
+ ]
+ ] as LinkedHashMap)
+ getClasspath(project, libs, MCP_ARTIFACT.descriptor) //Tell it to download mcp_config
+ }
+}
+
+tasks.named('universalJar').configure {
+ dependsOn downloadCrowdin
+ from zipTree(downloadCrowdin.dest).matching {
+ include 'assets/forge/lang/*.json'
+ }
+
+ from(EXTRA_TXTS)
+ duplicatesStrategy = 'exclude'
+ exclude '.cache'
+
+ manifest {
+ attributes([
+ 'Specification-Title': 'Forge',
+ 'Specification-Vendor': 'Forge Development LLC',
+ 'Specification-Version': SPEC_VERSION,
+ 'Implementation-Title': project.group,
+ 'Implementation-Vendor': 'Forge Development LLC',
+ 'Implementation-Version': FORGE_VERSION
+ ] as LinkedHashMap, 'net/minecraftforge/versions/forge/')
+ attributes([
+ 'Specification-Title': 'Minecraft',
+ 'Specification-Vendor': 'Forge Development LLC',
+ 'Specification-Version': MC_VERSION,
+ 'Implementation-Title': 'MCP',
+ 'Implementation-Vendor': 'Forge Development LLC',
+ 'Implementation-Version': MCP_VERSION
+ ] as LinkedHashMap, 'net/minecraftforge/versions/mcp/')
+ }
+ jarSigner.sign(it)
+}
+
+tasks.register('installerJar', InstallerJar) {
+ fat = !System.env.TEAMCITY_VERSION
+ //offline = true
+ from(EXTRA_TXTS)
+ from(rootProject.file('/forge_installer_logo.png')) {
+ rename { 'big_logo.png' }
+ }
+ from(genClientBinPatches.output) {
+ rename { 'data/client.lzma' }
+ }
+ from(genServerBinPatches.output) {
+ rename { 'data/server.lzma' }
+ }
+ jarSigner.sign(it)
+}
+
+tasks.register('mdkZip', Zip) {
+ archiveBaseName = project.name
+ archiveClassifier = 'mdk'
+ archiveVersion = project.version
+ destinationDirectory = file('build/libs')
+
+ from rootProject.file('gradlew')
+ from rootProject.file('gradlew.bat')
+ from(EXTRA_TXTS)
+ from(rootProject.file('gradle/')){
+ into('gradle/')
+ }
+ from(rootProject.file('mdk/')){
+ rootProject.file('mdk/gitignore.txt').eachLine{
+ if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
+ exclude it
+ }
+ filter(ReplaceTokens, tokens: [
+ FORGE_VERSION: FORGE_VERSION,
+ FORGE_GROUP: project.group,
+ FORGE_NAME: project.name,
+ MC_VERSION: MC_VERSION,
+ MAPPING_CHANNEL: MAPPING_CHANNEL,
+ MAPPING_VERSION: MAPPING_VERSION,
+ FORGE_SPEC_VERSION: SPEC_VERSION.split("\\.")[0],
+ MC_NEXT_VERSION: MC_NEXT_VERSION
+ ])
+ rename 'gitignore\\.txt', '.gitignore'
+ rename 'gitattributes\\.txt', '.gitattributes'
+ }
+ from(rootProject.file('src/test/generated/mdk_datagen/')) {
+ into('src/main/resources/')
+ exclude '**/.cache/'
+ }
+}
+
+license {
+ header = file("$rootDir/LICENSE-header.txt")
+
+ include 'net/minecraftforge/'
+ exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
+
+ tasks {
+ main {
+ files.from files("$rootDir/src/main/java")
+ }
+ test {
+ files.from files("$rootDir/src/test/java")
+ }
+ }
+}
+
+tasks.register('genAllData') {
+ dependsOn 'forge_data', 'forge_test_data'
+}
+
+if (project.hasProperty('UPDATE_MAPPINGS')) {
+ extractRangeMap {
+ sources.from sourceSets.test.java.srcDirs
+ addDependencies compileTestJava.classpath
+ }
+ applyRangeMap {
+ sources.from sourceSets.test.java.srcDirs
+ }
+ sourceSets.test.java.srcDirs.each { extractMappedNew.addTarget it }
+}
+
+tasks.named('javadoc', Javadoc).configure {
+ description 'Generates the combined javadocs for the FML projects and the main Forge project'
+ var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage' ]
+ 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.addStringOption('Xdoclint:all,-missing', '-public')
+ options {
+ stylesheetFile = new File(docsDir, 'stylesheet.css')
+
+ tags = [
+ 'apiNote:a:API Note:',
+ 'implSpec:a:Implementation Requirements:',
+ 'implNote:a:Implementation Note:'
+ ]
+
+ 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 - ${FORGE_VERSION} for Minecraft ${MC_VERSION}"
+ header = "${FORGE_VERSION} for Minecraft ${MC_VERSION}
"
+ }
+
+ doLast {
+ project.copy {
+ from docsDir
+ exclude '/stylesheet.css'
+ into destinationDir
+ }
+ }
+}
+
+publishing {
+ publications.register('mavenJava', MavenPublication).configure {
+ artifact universalJar
+ artifact installerJar
+ artifact mdkZip
+ artifact userdevJar
+ artifact sourcesJar
+ artifact serverShimJar
+
+ artifactId = project.name
+ 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 {
+ maven gradleutils.publishingForgeMaven
+ }
+}
+
+// Make sure we run bin compat checking during local testing.
+if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
+ publish.dependsOn(':forge:checkJarCompatibility')
+
+apply from: rootProject.file('build_forge_eclipse.gradle')
\ No newline at end of file
diff --git a/build_forge_eclipse.gradle b/build_forge_eclipse.gradle
new file mode 100644
index 0000000000..bf9fcd5d3a
--- /dev/null
+++ b/build_forge_eclipse.gradle
@@ -0,0 +1,44 @@
+apply plugin: 'eclipse'
+
+eclipse {
+ classpath.file.whenMerged {
+ def minecraft = entries.find { it.path == 'src/main/java' }
+ if (minecraft == null) throw new IllegalStateException("You must run `setup` task before importing")
+ // Disable optional warnings on the minecraft decompiled source code. It just muddies the warning window and hides warnings in our own codebase
+ minecraft.entryAttributes['ignore_optional_problems'] = 'true'
+
+ def mods = [
+ 'src/main/java': 'minecraft',
+ 'src/main/resources': 'minecraft',
+ 'src/test/java': 'minecraft-test',
+ 'src/test/resources': 'minecraft-test',
+
+ 'main-java': 'forge',
+ 'main-resources': 'forge',
+ 'generated': 'forge',
+
+ 'test-java': 'forge-test',
+ 'test-resources': 'forge-test',
+ 'test-generated': 'forge-test',
+ ]
+
+ entries.forEach { e ->
+ if ('src'.equals(e.kind) && e.hasProperty('output')) {
+ if (mods.containsKey(e.path))
+ e.output = 'bin/' + mods[e.path]
+ //else
+ // throw new IllegalStateException('Unknown path: ' + e.toString())
+ }
+ }
+ }
+
+ // Filter out the run directory
+ project.resourceFilter {
+ appliesTo = 'FOLDERS'
+ type = 'EXCLUDE_ALL'
+ matcher {
+ id = 'org.eclipse.ui.ide.multiFilter'
+ arguments = '1.0-name-matches-false-true-run'
+ }
+ }
+}
\ No newline at end of file
diff --git a/build_shared.gradle b/build_shared.gradle
new file mode 100644
index 0000000000..4e57e743e2
--- /dev/null
+++ b/build_shared.gradle
@@ -0,0 +1,76 @@
+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:API Note:',
+ 'implSpec:a:Implementation Requirements:',
+ 'implNote:a:Implementation Note:'
+ ]
+ 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')
+}
+
+// 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
+}
+
+// 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')
+ temp.forEach(exst::put)
+ 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
+}
\ No newline at end of file
diff --git a/fmlcore/build.gradle b/fmlcore/build.gradle
index 700beedf50..213149784e 100644
--- a/fmlcore/build.gradle
+++ b/fmlcore/build.gradle
@@ -1,12 +1,13 @@
+import net.minecraftforge.gradleutils.PomUtils
+
plugins {
- id 'com.github.ben-manes.versions'
- id 'org.javamodularity.moduleplugin' version '1.8.3' apply false
- id 'org.cadixdev.licenser'
id 'java-library'
- id 'jacoco'
+ id 'maven-publish'
+ id 'org.cadixdev.licenser'
+ id 'net.minecraftforge.gradleutils'
}
-dependencyUpdates.rejectVersionIf { isNonStable(it.candidate.version) }
+apply from: rootProject.file('build_shared.gradle')
dependencies {
compileOnly(libs.nulls)
@@ -17,57 +18,50 @@ dependencies {
implementation(libs.commons.io)
}
-task sourcesJar(type: Jar) {
- archiveClassifier = 'sources'
- from sourceSets.main.allSource
+java {
+ toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
+ withSourcesJar()
}
-ext {
- MANIFESTS = [
- '': [
- 'FMLModType': 'LIBRARY',
- 'Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
- 'Git-Commit': GIT_INFO.abbreviatedId,
- 'Git-Branch': GIT_INFO.branch,
- 'Build-Number': "${System.getenv('BUILD_NUMBER')?:0}"
- ] as LinkedHashMap,
- 'net/minecraftforge/fml/loading/': [
- 'Specification-Title': 'FMLLoader',
+tasks.named('jar', Jar).configure {
+ manifest {
+ attributes([
+ 'Automatic-Module-Name': 'net.minecraftforge.fmlcore',
+ 'FMLModType': 'LIBRARY'
+ ] as LinkedHashMap)
+ attributes([
+ 'Specification-Title': 'FML',
'Specification-Vendor': 'Forge Development LLC',
'Specification-Version': '1',
- 'Implementation-Title': 'FML Loader',
+ 'Implementation-Title': 'FML',
'Implementation-Version': '1.0',
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap
- ]
-}
-
-jar.doFirst {
- manifest.attributes['Automatic-Module-Name'] = project.name
- MANIFESTS.each { pkg, values ->
- if (pkg == '')
- manifest.attributes(values)
- else
- manifest.attributes(values, pkg)
+ 'Implementation-Vendor': 'Forge Development LLC'
+ ] as LinkedHashMap, 'net/minecraftforge/fml/')
}
}
tasks.withType(JavaCompile) {
- options.compilerArgs << '-Xlint:unchecked'
+ options.compilerArgs << '-Xlint:-unchecked'
}
license {
header = rootProject.file('LICENSE-header.txt')
-
- include 'net/minecraftforge/'
}
-artifacts {
- archives jar
- archives sourcesJar
-}
-
-publishing.publications.mavenJava(MavenPublication) {
- from components.java
- artifact sourcesJar
+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 {
+ maven gradleutils.publishingForgeMaven
+ }
}
\ No newline at end of file
diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/Bindings.java b/fmlcore/src/main/java/net/minecraftforge/fml/Bindings.java
index 6a34cea208..d7e9d073d5 100644
--- a/fmlcore/src/main/java/net/minecraftforge/fml/Bindings.java
+++ b/fmlcore/src/main/java/net/minecraftforge/fml/Bindings.java
@@ -5,11 +5,12 @@
package net.minecraftforge.fml;
-import cpw.mods.modlauncher.util.ServiceLoaderUtils;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.loading.FMLLoader;
+import java.util.ArrayList;
+import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.function.Supplier;
@@ -19,10 +20,18 @@ public class Bindings {
private final IBindingsProvider provider;
private Bindings() {
- final var providers = ServiceLoaderUtils.streamServiceLoader(()->ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class), sce->{}).toList();
- if (providers.size() != 1) {
- throw new IllegalStateException("Could not find bindings provider");
+ var providers = new ArrayList(1);
+ for (var itr = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class).iterator(); itr.hasNext(); ) {
+ try {
+ providers.add(itr.next());
+ } catch (ServiceConfigurationError sce) {
+ sce.printStackTrace();
+ }
}
+
+ if (providers.size() != 1)
+ throw new IllegalStateException("Could not find bindings provider: " + providers);
+
this.provider = providers.get(0);
}
diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/VersionChecker.java b/fmlcore/src/main/java/net/minecraftforge/fml/VersionChecker.java
index 0458d7ff52..3db178ceab 100644
--- a/fmlcore/src/main/java/net/minecraftforge/fml/VersionChecker.java
+++ b/fmlcore/src/main/java/net/minecraftforge/fml/VersionChecker.java
@@ -7,7 +7,6 @@ package net.minecraftforge.fml;
import com.google.gson.Gson;
import net.minecraftforge.fml.loading.FMLConfig;
-import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.forgespi.language.IModInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -35,81 +34,68 @@ import java.util.zip.GZIPInputStream;
import static net.minecraftforge.fml.VersionChecker.Status.*;
-public class VersionChecker
-{
+public class VersionChecker {
private static final Logger LOGGER = LogManager.getLogger();
private static final int MAX_HTTP_REDIRECTS = Integer.getInteger("http.maxRedirects", 20);
private static final int HTTP_TIMEOUT_SECS = Integer.getInteger("http.timeoutSecs", 15);
- public enum Status
- {
+ public enum Status {
PENDING(),
FAILED(),
UP_TO_DATE(),
- OUTDATED(3, true),
+ OUTDATED(3, true, true),
AHEAD(),
BETA(),
- BETA_OUTDATED(6, true);
+ BETA_OUTDATED(6, true, true);
final int sheetOffset;
final boolean draw, animated;
- Status()
- {
+ Status() {
this(0, false, false);
}
- Status(int sheetOffset)
- {
- this(sheetOffset, true, false);
- }
-
- Status(int sheetOffset, boolean animated)
- {
- this(sheetOffset, true, animated);
- }
-
- Status(int sheetOffset, boolean draw, boolean animated)
- {
+ Status(int sheetOffset, boolean draw, boolean animated) {
this.sheetOffset = sheetOffset;
this.draw = draw;
this.animated = animated;
}
- public int getSheetOffset()
- {
+ public int getSheetOffset() {
return sheetOffset;
}
- public boolean shouldDraw()
- {
+ public boolean shouldDraw() {
return draw;
}
- public boolean isAnimated()
- {
+ public boolean isAnimated() {
return animated;
}
-
}
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map changes, String url) {}
- public static void startVersionCheck()
- {
- new Thread("Forge Version Check")
- {
+ public static void startVersionCheck() {
+ new Thread("Forge Version Check") {
private HttpClient client;
+ private String mcVersion;
+ private String agent;
@Override
- public void run()
- {
- if (!FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.VERSION_CHECK))
- {
+ public void run() {
+ if (!FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.VERSION_CHECK)) {
LOGGER.info("Global Forge version check system disabled, no further processing.");
return;
}
+ var mc = ModList.get().getModContainerById("minecraft");
+ var forge = ModList.get().getModContainerById("forge");
+ this.mcVersion = mc.get().getModInfo().getVersion().toString();
+
+ this.agent = "Java-http-client/" + System.getProperty("java.version")
+ + " MinecraftForge/" + mcVersion + '-' + forge.get().getModInfo().getVersion();
+
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).build();
gatherMods().forEach(this::process);
}
@@ -119,15 +105,9 @@ public class VersionChecker
*/
private String openUrlString(URL url, IModInfo mod) throws IOException, URISyntaxException, InterruptedException {
URL currentUrl = url;
+ var userAgent = this.agent + ' ' + mod.getModId() + '/' + mod.getVersion();
- final StringBuilder sb = new StringBuilder();
- sb.append("Java-http-client/").append(System.getProperty("java.version")).append(' ');
- sb.append("MinecraftForge/").append(FMLLoader.versionInfo().mcAndForgeVersion()).append(' ');
- sb.append(mod.getModId()).append('/').append(mod.getVersion());
- final String userAgent = sb.toString();
-
- for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++)
- {
+ for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++) {
var request = HttpRequest.newBuilder()
.uri(currentUrl.toURI())
.timeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS))
@@ -139,8 +119,7 @@ public class VersionChecker
final HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int responseCode = response.statusCode();
- if (responseCode >= 300 && responseCode <= 399)
- {
+ if (responseCode >= 300 && responseCode <= 399) {
String newLocation = response.headers().firstValue("Location")
.orElseThrow(() -> new IOException("Got a 3xx response code but Location header was null while trying to fetch " + url));
currentUrl = new URL(currentUrl, newLocation);
@@ -150,26 +129,22 @@ public class VersionChecker
final boolean isGzipEncoded = response.headers().firstValue("Content-Encoding").orElse("").equals("gzip");
final String bodyStr;
- try (InputStream inStream = isGzipEncoded ? new GZIPInputStream(response.body()) : response.body())
- {
- try (var bufferedReader = new BufferedReader(new InputStreamReader(inStream)))
- {
- bodyStr = bufferedReader.lines().collect(Collectors.joining("\n"));
- }
+ try (var inStream = isGzipEncoded ? new GZIPInputStream(response.body()) : response.body();
+ var bufferedReader = new BufferedReader(new InputStreamReader(inStream))
+ ) {
+ bodyStr = bufferedReader.lines().collect(Collectors.joining("\n"));
}
return bodyStr;
}
throw new IOException("Too many redirects while trying to fetch " + url);
}
- private void process(IModInfo mod)
- {
+ private void process(IModInfo mod) {
Status status = PENDING;
ComparableVersion target = null;
Map changes = null;
String display_url = null;
- try
- {
+ try {
if (mod.getUpdateURL().isEmpty()) return;
URL url = mod.getUpdateURL().get();
LOGGER.info("[{}] Starting version check at {}", mod.getModId(), url.toString());
@@ -178,54 +153,40 @@ public class VersionChecker
LOGGER.debug("[{}] Received version check data:\n{}", mod.getModId(), data);
-
@SuppressWarnings("unchecked")
Map json = new Gson().fromJson(data, Map.class);
@SuppressWarnings("unchecked")
Map promos = (Map)json.get("promos");
display_url = (String)json.get("homepage");
- var mcVersion = FMLLoader.versionInfo().mcVersion();
String rec = promos.get(mcVersion + "-recommended");
String lat = promos.get(mcVersion + "-latest");
ComparableVersion current = new ComparableVersion(mod.getVersion().toString());
- if (rec != null)
- {
+ if (rec != null) {
ComparableVersion recommended = new ComparableVersion(rec);
int diff = recommended.compareTo(current);
if (diff == 0)
status = UP_TO_DATE;
- else if (diff < 0)
- {
+ else if (diff < 0) {
status = AHEAD;
- if (lat != null)
- {
+ if (lat != null) {
ComparableVersion latest = new ComparableVersion(lat);
- if (current.compareTo(latest) < 0)
- {
+ if (current.compareTo(latest) < 0) {
status = OUTDATED;
target = latest;
}
}
- }
- else
- {
+ } else {
status = OUTDATED;
target = recommended;
}
- }
- else if (lat != null)
- {
+ } else if (lat != null) {
ComparableVersion latest = new ComparableVersion(lat);
- if (current.compareTo(latest) < 0)
- status = BETA_OUTDATED;
- else
- status = BETA;
+ status = current.compareTo(latest) < 0 ? BETA_OUTDATED : BETA;
target = latest;
- }
- else
+ } else
status = BETA;
LOGGER.info("[{}] Found status: {} Current: {} Target: {}", mod.getModId(), status, current, target);
@@ -233,27 +194,20 @@ public class VersionChecker
changes = new LinkedHashMap<>();
@SuppressWarnings("unchecked")
Map tmp = (Map)json.get(mcVersion);
- if (tmp != null)
- {
+ if (tmp != null) {
List ordered = new ArrayList<>();
- for (String key : tmp.keySet())
- {
+ for (String key : tmp.keySet()) {
ComparableVersion ver = new ComparableVersion(key);
if (ver.compareTo(current) > 0 && (target == null || ver.compareTo(target) < 1))
- {
ordered.add(ver);
- }
}
Collections.sort(ordered);
- for (ComparableVersion ver : ordered)
- {
+ for (ComparableVersion ver : ordered) {
changes.put(ver, tmp.get(ver.toString()));
}
}
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
LOGGER.warn("Failed to process update information", e);
status = FAILED;
}
@@ -263,8 +217,7 @@ public class VersionChecker
}
// Gather a list of mods that have opted in to this update system by providing a URL.
- private static List gatherMods()
- {
+ private static List gatherMods() {
List ret = new LinkedList<>();
for (IModInfo info : ModList.get().getMods()) {
if (info.getUpdateURL().isPresent())
@@ -276,9 +229,7 @@ public class VersionChecker
private static Map results = new ConcurrentHashMap<>();
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
- public static CheckResult getResult(IModInfo mod)
- {
+ public static CheckResult getResult(IModInfo mod) {
return results.getOrDefault(mod, PENDING_CHECK);
}
-
}
diff --git a/fmlearlydisplay/build.gradle b/fmlearlydisplay/build.gradle
index 4cd94dc2d4..b0c3f3ec40 100644
--- a/fmlearlydisplay/build.gradle
+++ b/fmlearlydisplay/build.gradle
@@ -1,10 +1,14 @@
+import net.minecraftforge.gradleutils.PomUtils
+
plugins {
- id 'org.javamodularity.moduleplugin' version '1.8.7' apply false
- id 'org.cadixdev.licenser'
id 'java-library'
- id 'jacoco'
+ id 'maven-publish'
+ id 'org.cadixdev.licenser'
+ id 'net.minecraftforge.gradleutils'
}
+apply from: rootProject.file('build_shared.gradle')
+
import org.gradle.internal.os.OperatingSystem
switch (OperatingSystem.current()) {
case OperatingSystem.LINUX:
@@ -18,7 +22,10 @@ switch (OperatingSystem.current()) {
break
}
-java.withSourcesJar()
+java {
+ toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
+ withSourcesJar()
+}
dependencies {
compileOnly(libs.nulls)
@@ -44,12 +51,16 @@ test {
jar {
manifest {
attributes([
- 'Specification-Title': 'FMLEarlyDisplay',
+ 'Automatic-Module-Name': 'net.minecraftforge.earlydisplay',
+ 'Forge-Module-Layer': 'boot'
+ ] as LinkedHashMap)
+ attributes([
+ 'Specification-Title': 'FML Early Display',
'Specification-Vendor': 'Forge Development LLC',
'Specification-Version': '1',
'Implementation-Title': 'FML Early Display',
- 'Implementation-Version': '1.0',
- 'Implementation-Vendor': 'Forge'
+ 'Implementation-Vendor': 'Forge Development LLC',
+ 'Implementation-Version': '1.0'
] as LinkedHashMap, 'net/minecraftforge/fml/earlydisplay/')
}
}
@@ -60,9 +71,22 @@ tasks.withType(JavaCompile) {
license {
header = rootProject.file('LICENSE-header.txt')
- include 'net/minecraftforge/'
}
-publishing.publications.mavenJava(MavenPublication) {
- from components.java
+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 {
+ maven gradleutils.publishingForgeMaven
+ }
}
\ No newline at end of file
diff --git a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java
index 0db07ad722..c1c72c45f0 100644
--- a/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java
+++ b/fmlearlydisplay/src/main/java/net/minecraftforge/fml/earlydisplay/DisplayWindow.java
@@ -114,11 +114,13 @@ public class DisplayWindow implements ImmediateWindowProvider {
public String name() {
return "fmlearlywindow";
}
+
@Override
public Runnable initialize(String[] arguments) {
+ String mcVersion = FMLLoader.versionInfo().mcVersion();
+ String forgeVersion = FMLLoader.versionInfo().forgeVersion();
+
final OptionParser parser = new OptionParser();
- var mcversionopt = parser.accepts("fml.mcVersion").withRequiredArg().ofType(String.class);
- var forgeversionopt = parser.accepts("fml.forgeVersion").withRequiredArg().ofType(String.class);
var widthopt = parser.accepts("width")
.withRequiredArg().ofType(Integer.class)
.defaultsTo(FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_WIDTH));
@@ -133,7 +135,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_WIDTH, winWidth);
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_HEIGHT, winHeight);
fbScale = FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_FBSCALE);
- if (System.getenv("FML_EARLY_WINDOW_DARK")!= null) {
+ if (System.getenv("FML_EARLY_WINDOW_DARK") != null) {
this.colourScheme = ColourScheme.BLACK;
} else {
try {
@@ -148,10 +150,9 @@ public class DisplayWindow implements ImmediateWindowProvider {
}
this.maximized = parsed.has(maximizedopt) || FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_MAXIMIZED);
- var forgeVersion = parsed.valueOf(forgeversionopt);
- StartupNotificationManager.modLoaderConsumer().ifPresent(c->c.accept("Forge loading "+ forgeVersion));
+ StartupNotificationManager.modLoaderConsumer().ifPresent(c->c.accept("Forge loading " + forgeVersion));
performanceInfo = new PerformanceInfo();
- return start(parsed.valueOf(mcversionopt), forgeVersion);
+ return start(mcVersion, forgeVersion);
}
private static final long MINFRAMETIME = TimeUnit.MILLISECONDS.toNanos(10); // This is the FPS cap on the window - note animation is capped at 20FPS via the tickTimer
@@ -229,11 +230,11 @@ public class DisplayWindow implements ImmediateWindowProvider {
crashElegantly("An error occurred initializing a font for rendering. "+t.getMessage());
}
this.elements = new ArrayList<>(Arrays.asList(
- RenderElement.anvil(font),
- RenderElement.logMessageOverlay(font),
- RenderElement.forgeVersionOverlay(font, mcVersion+"-"+forgeVersion.split("-")[0]),
- RenderElement.performanceBar(font),
- RenderElement.progressBars(font)
+ RenderElement.anvil(font),
+ RenderElement.logMessageOverlay(font),
+ RenderElement.forgeVersionOverlay(font, mcVersion + "-" + forgeVersion),
+ RenderElement.performanceBar(font),
+ RenderElement.progressBars(font)
));
var date = Calendar.getInstance();
@@ -285,6 +286,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
public Runnable start(@Nullable String mcVersion, final String forgeVersion) {
renderScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
final var thread = Executors.defaultThreadFactory().newThread(r);
+ thread.setName("EarlyDisplay");
thread.setDaemon(true);
return thread;
});
diff --git a/fmlloader/build.gradle b/fmlloader/build.gradle
index 7f9ae834a7..0720146f6b 100644
--- a/fmlloader/build.gradle
+++ b/fmlloader/build.gradle
@@ -1,12 +1,14 @@
+import net.minecraftforge.gradleutils.PomUtils
+
plugins {
- id 'com.github.ben-manes.versions'
- id 'org.javamodularity.moduleplugin' version '1.8.3' apply false
- id 'org.cadixdev.licenser'
id 'java-library'
- id 'jacoco'
+ id 'maven-publish'
+ id 'org.cadixdev.licenser'
+ id 'net.minecraftforge.gradleutils'
}
-dependencyUpdates.rejectVersionIf { isNonStable(it.candidate.version) }
+apply from: rootProject.file('build_shared.gradle')
+
configurations.forEach{ it.transitive = false }
dependencies {
@@ -41,28 +43,25 @@ dependencies {
testRuntimeOnly(libs.bootstrap)
}
-task sourcesJar(type: Jar) {
- archiveClassifier = 'sources'
- from sourceSets.main.allSource
+java {
+ toolchain.languageVersion = JavaLanguageVersion.of(JAVA_VERSION)
+ withSourcesJar()
}
-ext {
- MANIFESTS = [
- 'net/minecraftforge/fml/loading/': [
- 'Specification-Title': 'FMLLoader',
- 'Specification-Vendor': 'Forge Development LLC',
- 'Specification-Version': '1',
- 'Implementation-Title': 'FML Loader',
- 'Implementation-Version': '1.0',
- 'Implementation-Vendor': 'Forge'
- ] as LinkedHashMap
- ]
-}
-
-jar.doFirst {
- manifest.attributes['Automatic-Module-Name'] = project.name
- MANIFESTS.each { pkg, values ->
- manifest.attributes(values, pkg)
+tasks.named('jar', Jar).configure {
+ manifest {
+ attributes([
+ 'Automatic-Module-Name': 'net.minecraftforge.fmlloader',
+ 'Forge-Module-Layer': 'boot'
+ ] as LinkedHashMap)
+ attributes([
+ 'Specification-Title': 'FMLLoader',
+ 'Specification-Vendor': 'Forge Development LLC',
+ 'Specification-Version': '1',
+ 'Implementation-Title': 'FMLLoader',
+ 'Implementation-Vendor': 'Forge Development LLC',
+ 'Implementation-Version': FORGE_VERSION
+ ] as LinkedHashMap, 'net/minecraftforge/fml/loading/')
}
}
@@ -72,16 +71,36 @@ tasks.withType(JavaCompile) {
license {
header = rootProject.file('LICENSE-header.txt')
-
- include 'net/minecraftforge/'
}
-artifacts {
- archives jar
- archives sourcesJar
+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 {
+ maven gradleutils.publishingForgeMaven
+ }
}
-publishing.publications.mavenJava(MavenPublication) {
- from components.java
- artifact sourcesJar
-}
\ No newline at end of file
+tasks.register('writeForgeVersionJson') {
+ doLast {
+ file('src/main/resources/forge_version.json').json = [
+ 'forge': FORGE_VERSION,
+ 'mc': MC_VERSION,
+ 'mcp': MCP_VERSION
+ ] as LinkedHashMap
+ }
+}
+
+tasks.named('generateResources').configure {
+ dependsOn('writeForgeVersionJson')
+}
diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ClasspathTransformerDiscoverer.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/ClasspathTransformerDiscoverer.java
deleted file mode 100644
index 6b8bbf1dfd..0000000000
--- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/ClasspathTransformerDiscoverer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) Forge Development LLC and contributors
- * SPDX-License-Identifier: LGPL-2.1-only
- */
-
-package net.minecraftforge.fml.loading;
-
-import cpw.mods.modlauncher.api.NamedPath;
-import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService;
-import org.apache.logging.log4j.LogManager;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.*;
-
-public class ClasspathTransformerDiscoverer implements ITransformerDiscoveryService {
-
- private final List legacyClasspath = Arrays.stream(System.getProperty("legacyClassPath", "").split(File.pathSeparator)).map(Path::of).toList();
-
- @Override
- public List candidates(Path gameDirectory) {
- return Collections.emptyList();
- }
-
- @Override
- public List candidates(final Path gameDirectory, final String launchTarget) {
- if (launchTarget != null && launchTarget.contains("dev")) {
- this.scan(gameDirectory);
- }
- return List.copyOf(found);
- }
-
- private final static List found = new ArrayList<>();
-
- public static List allExcluded() {
- return found.stream().map(np->np.paths()[0]).toList();
- }
-
- private void scan(final Path gameDirectory) {
- try {
- locateTransformers("META-INF/services/cpw.mods.modlauncher.api.ITransformationService");
- locateTransformers("META-INF/services/net.minecraftforge.forgespi.locating.IModLocator");
- } catch (IOException e) {
- LogManager.getLogger().error("Error during discovery of transform services from the classpath", e);
- }
- }
-
- private void locateTransformers(String resource) throws IOException {
- final Enumeration resources = ClassLoader.getSystemClassLoader().getResources(resource);
- while (resources.hasMoreElements()) {
- URL url = resources.nextElement();
- Path path = ClasspathLocatorUtils.findJarPathFor(resource, url.toString(), url);
- if (legacyClasspath.stream().anyMatch(path::equals) || !Files.exists(path) || Files.isDirectory(path))
- continue;
- found.add(new NamedPath(path.toUri().toString(), path));
- }
- }
-}
diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java
index d5f7c79430..1d45c19f75 100644
--- a/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java
+++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java
@@ -8,8 +8,6 @@ package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.*;
-import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
-import cpw.mods.modlauncher.util.ServiceLoaderUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
@@ -24,27 +22,29 @@ import org.slf4j.Logger;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import java.util.Set;
import java.util.function.BiFunction;
-import java.util.stream.Collectors;
-
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
-public class FMLLoader
-{
+public class FMLLoader {
private static final Logger LOGGER = LogUtils.getLogger();
private static AccessTransformerService accessTransformer;
private static ModDiscoverer modDiscoverer;
private static ICoreModProvider coreModProvider;
- private static ILaunchPluginService eventBus;
private static LanguageLoadingProvider languageLoadingProvider;
private static Dist dist;
private static String naming;
private static LoadingModList loadingModList;
private static RuntimeDistCleaner runtimeDistCleaner;
private static Path gamePath;
- private static VersionInfo versionInfo;
+ private static VersionInfo versionInfo = VersionInfo.detect();
private static String launchHandlerName;
private static CommonLaunchHandler commonLaunchHandler;
public static Runnable progressWindowTick;
@@ -53,80 +53,74 @@ public class FMLLoader
private static boolean production;
private static IModuleLayerManager moduleLayerManager;
- static void onInitialLoad(IEnvironment environment, Set otherServices) throws IncompatibleEnvironmentException
- {
- final String version = LauncherVersion.getVersion();
- LOGGER.debug(CORE,"FML {} loading", version);
- final Package modLauncherPackage = ITransformationService.class.getPackage();
- LOGGER.debug(CORE,"FML found ModLauncher version : {}", modLauncherPackage.getImplementationVersion());
- if (!modLauncherPackage.isCompatibleWith("4.0")) {
- LOGGER.error(CORE, "Found incompatible ModLauncher specification : {}, version {} from {}", modLauncherPackage.getSpecificationVersion(), modLauncherPackage.getImplementationVersion(), modLauncherPackage.getImplementationVendor());
- throw new IncompatibleEnvironmentException("Incompatible modlauncher found "+modLauncherPackage.getSpecificationVersion());
- }
+ static void onInitialLoad(IEnvironment env, Set otherServices) throws IncompatibleEnvironmentException {
+ LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
+ LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
- accessTransformer = (AccessTransformerService) environment.findLaunchPlugin("accesstransformer").orElseThrow(()-> {
- LOGGER.error(CORE, "Access Transformer library is missing, we need this to run");
- return new IncompatibleEnvironmentException("Missing AccessTransformer, cannot run");
- });
-
- final Package atPackage = accessTransformer.getClass().getPackage();
- LOGGER.debug(CORE,"FML found AccessTransformer version : {}", atPackage.getImplementationVersion());
- if (!atPackage.isCompatibleWith("1.0")) {
- LOGGER.error(CORE, "Found incompatible AccessTransformer specification : {}, version {} from {}", atPackage.getSpecificationVersion(), atPackage.getImplementationVersion(), atPackage.getImplementationVendor());
- throw new IncompatibleEnvironmentException("Incompatible accesstransformer found "+atPackage.getSpecificationVersion());
- }
-
- eventBus = environment.findLaunchPlugin("eventbus").orElseThrow(()-> {
- LOGGER.error(CORE, "Event Bus library is missing, we need this to run");
- return new IncompatibleEnvironmentException("Missing EventBus, cannot run");
- });
-
- final Package eventBusPackage = eventBus.getClass().getPackage();
- LOGGER.debug(CORE,"FML found EventBus version : {}", eventBusPackage.getImplementationVersion());
- if (!eventBusPackage.isCompatibleWith("1.0")) {
- LOGGER.error(CORE, "Found incompatible EventBus specification : {}, version {} from {}", eventBusPackage.getSpecificationVersion(), eventBusPackage.getImplementationVersion(), eventBusPackage.getImplementationVendor());
- throw new IncompatibleEnvironmentException("Incompatible eventbus found "+eventBusPackage.getSpecificationVersion());
- }
-
- runtimeDistCleaner = (RuntimeDistCleaner)environment.findLaunchPlugin("runtimedistcleaner").orElseThrow(()-> {
- LOGGER.error(CORE, "Dist Cleaner is missing, we need this to run");
- return new IncompatibleEnvironmentException("Missing DistCleaner, cannot run!");
- });
- LOGGER.debug(CORE, "Found Runtime Dist Cleaner");
-
- var coreModProviders = ServiceLoaderUtils.streamWithErrorHandling(ServiceLoader.load(FMLLoader.class.getModule().getLayer(), ICoreModProvider.class), sce -> LOGGER.error(CORE, "Failed to load a coremod library, expect problems", sce)).toList();
-
- if (coreModProviders.isEmpty()) {
- LOGGER.error(CORE, "Found no coremod provider. Cannot run");
- throw new IncompatibleEnvironmentException("No coremod library found");
- } else if (coreModProviders.size() > 1) {
- LOGGER.error(CORE, "Found multiple coremod providers : {}. Cannot run", coreModProviders.stream().map(p -> p.getClass().getName()).collect(Collectors.toList()));
- throw new IncompatibleEnvironmentException("Multiple coremod libraries found");
- }
-
- coreModProvider = coreModProviders.get(0);
- final Package coremodPackage = coreModProvider.getClass().getPackage();
- LOGGER.debug(CORE,"FML found CoreMod version : {}", coremodPackage.getImplementationVersion());
-
-
- LOGGER.debug(CORE, "Found ForgeSPI package implementation version {}", Environment.class.getPackage().getImplementationVersion());
- LOGGER.debug(CORE, "Found ForgeSPI package specification {}", Environment.class.getPackage().getSpecificationVersion());
- if (Integer.parseInt(Environment.class.getPackage().getSpecificationVersion()) < 2) {
- LOGGER.error(CORE, "Found an out of date ForgeSPI implementation: {}, loading cannot continue", Environment.class.getPackage().getSpecificationVersion());
- throw new IncompatibleEnvironmentException("ForgeSPI is out of date, we cannot continue");
- }
+ checkPackage(ITransformationService.class, "4.0", "ModLauncher");
+ accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
+ /*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
+ runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
+ coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
+ LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING"));
+ checkPackage(Environment.class, "2.0", "ForgeSPI");
try {
- Class.forName("com.electronwill.nightconfig.core.Config", false, environment.getClass().getClassLoader());
- Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, environment.getClass().getClassLoader());
+ Class.forName("com.electronwill.nightconfig.core.Config", false, env.getClass().getClassLoader());
+ Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, env.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
LOGGER.error(CORE, "Failed to load NightConfig");
throw new IncompatibleEnvironmentException("Missing NightConfig");
}
}
- static void setupLaunchHandler(final IEnvironment environment, final Map arguments)
- {
+ private static T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException {
+ @SuppressWarnings("unchecked")
+ var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> {
+ LOGGER.error(CORE, "{} library is missing, we need this to run", name);
+ return new IncompatibleEnvironmentException("Missing " + name + ", cannot run");
+ });
+ checkPackage(plugin.getClass(), version, name);
+ return plugin;
+ }
+
+ private static void checkPackage(Class> cls, String version, String name) throws IncompatibleEnvironmentException {
+ var pkg = cls.getPackage();
+ var info = JarVersionLookupHandler.getInfo(pkg);
+ LOGGER.debug(CORE, "Found {} version: {}", name, info.impl().version().orElse("MISSING"));
+
+ if (!pkg.isCompatibleWith(version)) {
+ LOGGER.error(CORE, "Found incompatible {} specification: {}, version {} from {}", name,
+ info.spec().version().orElse("MISSING"),
+ info.impl().version().orElse("MISSING"),
+ info.impl().vendor().orElse("MISSING")
+ );
+ throw new IncompatibleEnvironmentException("Incompatible " + name + " found " + info.spec().version().orElse("MISSING"));
+ }
+ }
+
+ private static T getSingleService(Class clazz, String name) throws IncompatibleEnvironmentException {
+ var providers = new ArrayList();
+ for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) {
+ try {
+ providers.add(itr.next());
+ } catch (ServiceConfigurationError e) {
+ LOGGER.error(CORE, "Failed to load a " + name + " library, expect problems", e);
+ }
+ }
+
+ if (providers.isEmpty()) {
+ LOGGER.error(CORE, "Found no {} provider. Cannot run", name);
+ throw new IncompatibleEnvironmentException("No " + name + " library found");
+ } else if (providers.size() > 1) {
+ LOGGER.error(CORE, "Found multiple {} providers: {}. Cannot run", name, providers.stream().map(p -> p.getClass().getName()).toList());
+ throw new IncompatibleEnvironmentException("Multiple " + name + " libraries found");
+ }
+
+ return providers.get(0);
+ }
+
+ static void setupLaunchHandler(final IEnvironment environment, final Map arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
final Optional launchHandler = environment.findLaunchHandler(launchTarget);
@@ -136,7 +130,7 @@ public class FMLLoader
throw new RuntimeException("Missing launch handler: " + launchTarget);
}
- // TODO: What the fuck is the point of using a service if you require a specific concrete class
+ // TODO: [FML][Loader] What the fuck is the point of using a service if you require a specific concrete class
if (!(launchHandler.get() instanceof CommonLaunchHandler)) {
LOGGER.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName());
throw new RuntimeException("Incompatible launch handler found");
@@ -149,16 +143,12 @@ public class FMLLoader
dist = commonLaunchHandler.getDist();
production = commonLaunchHandler.isProduction();
- versionInfo = new VersionInfo(arguments);
-
accessTransformer.getExtension().accept(Pair.of(naming, "srg"));
- LOGGER.debug(CORE,"Received command line version data : {}", versionInfo);
-
runtimeDistCleaner.getExtension().accept(dist);
}
- public static List beginModScan(final Map arguments)
- {
+
+ public static List beginModScan(final Map arguments) {
LOGGER.debug(SCAN,"Scanning for Mod Locators");
modDiscoverer = new ModDiscoverer(arguments);
modValidator = modDiscoverer.discoverMods();
@@ -178,8 +168,7 @@ public class FMLLoader
return coreModProvider;
}
- public static LanguageLoadingProvider getLanguageLoadingProvider()
- {
+ public static LanguageLoadingProvider getLanguageLoadingProvider() {
return languageLoadingProvider;
}
@@ -191,31 +180,26 @@ public class FMLLoader
return commonLaunchHandler;
}
- public static void addAccessTransformer(Path atPath, ModFile modName)
- {
+ public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
- public static Dist getDist()
- {
+ public static Dist getDist() {
return dist;
}
- public static void beforeStart(ModuleLayer gameLayer)
- {
+ public static void beforeStart(ModuleLayer gameLayer) {
ImmediateWindowHandler.acceptGameLayer(gameLayer);
ImmediateWindowHandler.updateProgress("Launching minecraft");
progressWindowTick.run();
}
- public static LoadingModList getLoadingModList()
- {
+ public static LoadingModList getLoadingModList() {
return loadingModList;
}
- public static Path getGamePath()
- {
+ public static Path getGamePath() {
return gamePath;
}
@@ -232,7 +216,7 @@ public class FMLLoader
}
public static List