Compare commits

..
47 Commits
Author SHA1 Message Date
Jonathing f31519b6bb 1.20.4 RB 2
https://forums.minecraftforge.net/topic/154388-forge-492-minecraft-1204/
2025-03-04 15:51:32 -08:00
Jonathing f715248a1e Bump SecureModules to 2.2.21, fixes crash caused by previous jline version bump. (#10488) 2025-03-04 14:26:48 -08:00
Jonathing e1bc30a04b Add missed license headers (#10478) 2025-03-04 12:56:27 -08:00
JonathingandLexManos 85ab903cd1 Speed up mod annotation scanning by ~30% (#10469)
Co-authored-by: LexManos <[email protected]>
2025-03-04 12:56:19 -08:00
Jonathing 530c7c4eb5 Add '#forge:chorus_additionally_grows_on' tag for similar mechanics to '#minecraft:azalea_grows_on' but for chorus (#10462) 2025-03-04 12:56:06 -08:00
Jonathing 3c740e488d Bump dependencies, most notably EventBus (#10388)
- CoreMods 5.2.4 -> 5.2.6
- EventBus 6.2.8 -> 6.2.27
    - Reduced memory usage
    - Further performance improvements
    - Fixed EventBus#39, unregistered listeners are now immediately reclaimable by the GC
- Apache MavenArtifact 3.8.5 -> 3.8.8
- BootStrap 2.1.0 -> 2.1.8
- JLine 3.12.1 -> 3.25.1
    - Better OSX Support
2025-02-21 12:05:39 -08:00
Jonathing 03d07a9621 Fix damageItem's game test not using onBreak callback correctly (#10452) 2025-02-18 13:38:04 -08:00
Jonathing 90dc29b1ef Cache this.useItem before running item break logic, Fixes #10344 (#10375) 2025-02-18 12:42:17 -08:00
Jonathing eae9d72dd8 Add fast graphics render type to block model jsons (#10398)
Make modded leaves behave like vanilla leaves by default (Fixes #10389)
2025-02-18 12:28:13 -08:00
Jonathing 7ac8903a3b Fix corrupted and invalidly symlinked worlds crashing on level select (#10438) 2025-02-18 12:24:23 -08:00
Jonathing bd96ff8777 Backport even more future ResourceLocation methods (#10427) 2025-02-18 12:02:06 -08:00
Jonathing ebfd92e0e1 Fix incorrect method reference in TntBlock.explode() (#10330) 2025-02-18 12:01:42 -08:00
Jonathing 43288f79e3 Fix VillagerTypeTestMod not working (#10426) 2025-02-18 12:01:28 -08:00
Jonathing dbd7da6885 Fix issue with shields not disabling correctly (#10320) 2025-01-27 19:12:47 -08:00
Jonathing bb98165ee8 Fix issues in VillagerTrades.EmeraldsForVillagerTypeItem related to custom Villager Types (#10358)
Add VillagerType#registerBiomeType
Co-authored-by: Joseph T. McQuigg <[email protected]>
2025-01-27 19:11:52 -08:00
Jonathing 6a1f1acc42 Update Gradle to 8.12.1 (#10356)
Make IntelliJ download sources automatically in MDK
2025-01-27 14:38:53 -08:00
JonathingandLexManos a982445295 GameTestHelper additions (#10343)
Co-authored-by: LexManos <[email protected]>
2025-01-27 14:38:18 -08:00
Jonathing 89919519ac Fix non-passengers being tickable without checking canUpdate() (#10303) 2025-01-22 13:22:52 -08:00
Jonathing 4d592ba5ac Fix finalizeSpawn's return value not being used correctly (#10302) 2025-01-22 13:22:44 -08:00
Jonathing 5657e6542b Fix boat travel distance being incorrect (#10292) 2025-01-04 19:54:20 -08:00
JonathingandJames Mitchell c1c327ce11 Add a way to render tooltips from Formatted text and TooltipComponents elements (#10056)
Co-authored-by: James Mitchell <[email protected]>
2025-01-04 13:03:32 -08:00
Jonathing 142f07cbad Bump CoreMods to 5.2.4 (#10264) 2024-12-23 17:25:49 -08:00
Jonathing c4f18dfa4b Allow mipmap lowering to be disabled (#10253) 2024-12-23 17:25:38 -08:00
Jonathing 9f5a6d716e Add optional fix of use item duration, disabled by default (#10247) 2024-12-23 17:15:38 -08:00
JonathingandPaint_Ninja 984cedda5c Simplify memory usage display on loading screen (#10234)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 17:15:27 -08:00
JonathingandPaint_Ninja cc4a431711 Deprecate @ObjectHolder, add a couple of fast-paths (#10229)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 17:03:01 -08:00
JonathingandPaint_Ninja ee07bcac57 Skip Vanilla classes for the CapabilityTokenSubclass transformer (#10222)
Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 16:53:23 -08:00
JonathingandPaint_Ninja b1cc694453 Skip Forge classes in the RuntimeEnumExtender transformer (#10217)
Mod classes are still transformed as usual

Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 16:38:24 -08:00
JonathingandPaint_Ninja 838ab9e1a5 Skip processing Forge classes in RuntimeDistCleaner (#10209)
Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 16:23:54 -08:00
Jonathing 99a7fcd8bd Bump CoreMods to 5.2 (#10129)
Full Changelog: https://gist.github.com/Jonathing/c3ad28b2a048ac839a7baba5417ee870

The key features are:
- ES6 language support
- Thoroughly updated ASMAPI, with full documentation
- Bug fixes (some optional for backwards-compatibility)
- Partial internal code cleanup
- Updated Nashorn to 15.4
- Request CoreMods to not apply fix for ASMAPI.findFirstInstructionBefore by default
2024-11-08 17:40:18 -08:00
Paint_Ninja 3535dcdbb3 Use the new fire() and Result#isAllowed/isDenied/isDefault methods from EventBus (backport of #10028 to 1.20.4) (#10097) 2024-10-06 18:39:59 -07:00
Paint_Ninjaandandan42 d7ccecefe0 Remove unneeded boat patch (backport of #10061 to 1.20.4) (#10087)
Co-authored-by: andan42 <[email protected]>
2024-10-06 18:39:52 -07:00
Paint_NinjaandDaniel Norris d3e9cfaaba Change tick event to have pre/post classes (backport of #9890 to 1.20.4) (#10090)
Co-authored-by: Daniel Norris <[email protected]>
2024-09-12 14:36:27 +01:00
Paint_Ninja 7134b93427 Backport some Vanilla ResourceLocation methods (backport of #10084 to 1.20.4) (#10098) 2024-09-12 14:35:54 +01:00
Paint_Ninja 61694447b2 Minor cleanup to ModListScreen and VersionChecker (backport of #9988 to 1.20.4) (#10089) 2024-09-12 14:03:49 +01:00
Paint_Ninja 561f3ee534 Cleanup FML Bindings (backport of #10004 to 1.20.4) (#10088) 2024-09-12 14:03:35 +01:00
Paint_NinjaandRealMangoRage d0fea9cf76 Optionally supply FMLJavaModLoadingContext as a param to mod constructors (backport of #10074 to 1.20.4) (#10099)
Co-authored-by: RealMangoRage <[email protected]>
2024-09-12 14:03:01 +01:00
Paint_Ninja dd866ed53e Add missed @user_jvm_args.txt to run.bat (backport of 40a0a16 to 1.20.4) (#10093) 2024-09-10 13:56:55 +01:00
LexManos 54f5e1213a Make HangingSignBlockEntity useable with custom BlockEntityTypes. #10038 2024-07-05 13:42:41 -07:00
Edouard127andLexManos 9d4f283e6b Unlock wrapped registries when firing register events. (#10036)
Co-authored-by: LexManos <[email protected]>
2024-07-02 10:56:10 -07:00
Jonathingandthedarkcolour 28d4205a97 Choose default JarJar mod file type based on parent JAR Closes #9939 (#10022)
Co-authored-by: thedarkcolour <[email protected]>
2024-06-28 22:21:47 -07:00
JonathingandVen d0d1f1d782 Fixed falling block entities not rendering as moving blocks (#10006) (#10017)
Co-authored-by: Ven <[email protected]>
2024-06-28 22:04:56 -07:00
LexManos 397ceac0b6 1.20.4 RB 1
https://forums.minecraftforge.net/topic/149456-forge-491-minecraft-1204/
2024-06-03 13:23:22 -07:00
LexManos 1b7665cdaa Fix LevelSettings ignoring data configuration. Close #9938 2024-06-03 12:46:09 -07:00
LexManos 70f96ef64e Fix erroneous patch in FireBlock. Closes #9996 2024-06-03 12:38:03 -07:00
Paint_Ninja 0cf4446352 [1.20.4] Add config option for optionally disabling non-Forge mods.toml detection (#9943) 2024-05-30 23:50:19 +01:00
LexManos b8270cd9ff Filter paths discovered by ServiceProvider in ClasspathLocator. Closes #9899 2024-05-09 09:53:36 -07:00
1243 changed files with 31305 additions and 27182 deletions

No files matched your search

+2 -2
View File
@@ -36,8 +36,8 @@ project {
buildType(PullRequestCompatibility)
params {
text("docker_jdk_version", "21", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_gradle_version", "8.7", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_jdk_version", "17", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_gradle_version", "7.5.1", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_main_branch", "1.20.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_branch_spec", """
+:refs/heads/(main*)
+2 -2
View File
@@ -7,8 +7,8 @@ plugins {
id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)'
id 'eclipse'
id 'de.undercouch.download' version '5.4.0'
id 'net.minecraftforge.gradle.patcher' version '[6.0.22,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.22,6.2)' apply false
id 'net.minecraftforge.gradle.patcher' version '[6.0.16,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.16,6.2)' apply false
id 'net.minecraftforge.gradlejarsigner' version '1.0.4'
id 'org.barfuin.gradle.taskinfo' version '2.1.0'
}
+3 -3
View File
@@ -4,9 +4,9 @@ repositories {
}
dependencies {
implementation 'org.ow2.asm:asm:9.7'
implementation 'org.ow2.asm:asm-tree:9.7'
implementation 'net.minecraftforge:srgutils:0.5.10'
implementation 'org.ow2.asm:asm:9.6'
implementation 'org.ow2.asm:asm-tree:9.6'
implementation 'net.minecraftforge:srgutils:0.5.+'
implementation 'commons-io:commons-io:2.13.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r'
@@ -10,13 +10,11 @@ import java.util.zip.ZipFile
abstract class BundleList extends DefaultTask {
@InputFiles abstract ConfigurableFileCollection getConfig()
@InputFiles abstract ConfigurableFileCollection getConfigExtra()
@InputFile abstract RegularFileProperty getServerBundle()
@OutputFile abstract RegularFileProperty getOutput()
BundleList() {
config.setFrom(project.configurations.installer)
configExtra.setFrom(project.configurations.installerextra)
output.convention(project.layout.buildDirectory.file("$name/output.list"))
configure {
dependsOn(project.tasks.universalJar)
@@ -34,13 +32,6 @@ abstract class BundleList extends DefaultTask {
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
}
resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts
for (def dep : resolved) {
def info = Util.getMavenInfoFromDep(dep)
//println("$dep.file.sha1\t$info.name\t$info.path")
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
}
var packed = (AbstractArchiveTask) project.tasks.universalJar
var info = Util.getMavenInfoFromTask(packed)
def file = packed.archiveFile.get().asFile
@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
@Internal
@Override
protected Object getData() {
return matches.toSorted(Comparator.naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
return matches.toSorted(Comparator.<String>naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
}
}
@@ -24,7 +24,6 @@ abstract class LauncherJson extends DefaultTask {
dependsOn(project.tasks.universalJar)
input.from(project.tasks.universalJar.archiveFile)
input.from(project.configurations.installer)
input.from(project.configurations.installerextra)
configure {
def mc = project.rootProject.ext.MC_VERSION
def forge = project.rootProject.ext.FORGE_VERSION
@@ -89,7 +88,6 @@ abstract class LauncherJson extends DefaultTask {
]
])
json.libraries.addAll(getArtifacts(project.configurations.installerextra).values())
json.libraries.addAll(getArtifacts(project.configurations.installer).values())
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
}
@@ -140,7 +140,7 @@ abstract class CheckPatches extends CheckTask {
final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-')
if (!prevLineChange && !nextLineChange) {
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath \n$prevLine\n$line\n${lines[i+1]}", false)
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath", false)
}
}
-9
View File
@@ -61,13 +61,4 @@ eclipse.classpath.file.whenMerged {
def src = entries.find { it.path == 'src/main/java' }
if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
src.entryAttributes['ignore_optional_problems'] = 'true'
}
tasks.named('genPatches').configure {
onlyIf { false }
}
tasks.named('extractRangeMap').configure {
onlyIf { false }
tool = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
}
+102 -103
View File
@@ -12,9 +12,9 @@ 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.FilterNewJar
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
@@ -46,7 +46,6 @@ jarSigner.autoDetect('forge')
applyPatches {
level 'WARNING'
failOnError = UPDATING != 'true'
}
sourceSets {
@@ -89,21 +88,16 @@ ext {
final String MAVEN_PATH = ext.MAVEN_PATH
final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.3'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.0'
final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6'
final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
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 }
bootstrap { transitive = false }
installer {
extendsFrom(bootstrap)
transitive = false
}
installerextra {
extendsFrom(bootstrap)
transitive = false
}
api.extendsFrom(installer)
}
@@ -117,11 +111,10 @@ dependencies {
bootstrap(libs.unsafe) // Needed by securemodules
bootstrap(libs.bundles.asm) // Needed by securemodules
implementation(libs.jopt.simple) { version { strictly '5.0.4' } }
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)
@@ -142,16 +135,10 @@ dependencies {
installer(project(':lowcodelanguage'))
installer(project(':mclanguage'))
installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off")
runtimeOnly(libs.bootstrap)
runtimeOnly(libs.bootstrap.dev)
}
tasks.named('extractRangeMap').configure {
tool = S2S_TOOL
}
patcher {
excs.from file("$rootDir/src/main/resources/forge.exc")
parent = project(':mcp')
@@ -180,7 +167,6 @@ patcher {
forge_client_test {
parent runs.forge_client
source sourceSets.test
}
forge_server {
@@ -189,7 +175,6 @@ patcher {
forge_server_test {
parent runs.forge_server
source sourceSets.test
}
forge_server_gametest {
@@ -198,7 +183,6 @@ patcher {
forge_server_gametest_test {
parent runs.forge_server_gametest
source sourceSets.test
}
forge_data {
@@ -214,7 +198,6 @@ patcher {
}
forge_data_test {
source sourceSets.test
args '--launchTarget', 'forge_dev_data',
'--mod', '.+',
'--all',
@@ -225,6 +208,7 @@ patcher {
'--assetsDir', downloadAssets.output,
'--assetIndex', "{asset_index}"
}
}
}
@@ -378,15 +362,33 @@ tasks.register('extractInheritance', ExtractInheritance) {
Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).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 ->
return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
&& insn.getOpcode().equals(Opcodes.INVOKEVIRTUAL)
'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
&& insn.getOpcode() === Opcodes.INVOKEVIRTUAL
&& insn.name == 'm_6518_'
&& insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;';
&& insn.desc == '(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) {
@@ -426,34 +428,43 @@ tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks.
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("createClientOfficial", RenameJar) {
tasks.register("createClientSRG", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadClientMappings.output
dependsOn(downloadClientRaw, downloadClientMappings)
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/createClientOfficial/output.jar")
output = file("build/createClientSRG/output.jar")
}
tasks.register("createServerOfficial", RenameJar) {
tasks.register("createServerSRG", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadServerMappings.output
dependsOn(downloadServerMappings)
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/createServerOfficial/output.jar")
output = file("build/createServerSRG/output.jar")
}
tasks.named('genClientBinPatches').configure {
tool = BINPATCH_TOOL
cleanJar = createClientOfficial.output
dirtyJar = jar.archiveFile
cleanJar = createClientSRG.output
}
tasks.named('genServerBinPatches').configure {
tool = BINPATCH_TOOL
cleanJar = createServerOfficial.output
dirtyJar = jar.archiveFile
cleanJar = createServerSRG.output
}
tasks.named('genJoinedBinPatches').configure {
tool = BINPATCH_TOOL
@@ -461,13 +472,13 @@ tasks.named('genJoinedBinPatches').configure {
}
tasks.register('applyClientBinPatches', ApplyBinPatches) {
tool = BINPATCH_TOOL
clean = createClientOfficial.output
clean = createClientSRG.output
patch = genClientBinPatches.output
args.addAll(['--data', '--unpatched'])
}
tasks.register('applyServerBinPatches', ApplyBinPatches) {
tool = BINPATCH_TOOL
clean = createServerOfficial.output
clean = createServerSRG.output
patch = genServerBinPatches.output
args.addAll(['--data', '--unpatched'])
}
@@ -483,10 +494,10 @@ tasks.register('createServerShimClasspath', BundleList) {
tasks.register('createServerShimConfig') {
ext.output = file('build/libs/bootstrap-shim.properties')
doLast {
var cfg = new CleanProperties()
cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg['Java-Version'] = '21'
cfg['Arguments'] = '--launchTarget forge_server'
def cfg = new CleanProperties()
cfg."Main-Class" = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg."Java-Version" = '17'
cfg."Arguments" = "--launchTarget forge_server"
cfg.store(output)
}
}
@@ -512,7 +523,7 @@ tasks.register('checkAll') {
group = 'checks'
}
tasks.register('checkAllAndFix') {
dependsOn 'findFinalizeSpawnTargets', 'checkLicenses'
dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses'
group = 'checks'
}
@@ -626,12 +637,15 @@ tasks.register('installerJson', InstallerJson) {
// 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(createClientOfficial, createServerOfficial)
input.from(createClientOfficial.output, createServerOfficial.output)
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)
@@ -658,13 +672,21 @@ tasks.register('installerJson', InstallerJson) {
server: "'${extractMCPConfigMappings.output.sha1}'"
],
MOJMAPS: [
client: "[net.minecraft:client:${MC_VERSION}:mappings@tsrg]",
server: "[net.minecraft:server:${MC_VERSION}:mappings@tsrg]"
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]"
@@ -673,13 +695,13 @@ tasks.register('installerJson', InstallerJson) {
client: "'${downloadClientRaw.dest.sha1}'",
server: "'${extractServer.output.get().asFile.sha1}'"
],
MC_OFF: [
client: "[net.minecraft:client:${MC_VERSION}:official]",
server: "[net.minecraft:server:${MC_VERSION}:official]"
MC_SRG: [
client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]",
server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]"
],
MC_OFF_SHA: [
client: "'${createClientOfficial.output.get().asFile.sha1}'",
server: "'${createServerOfficial.output.get().asFile.sha1}'"
MC_SRG_SHA: [
client: "'${createClientSRG.output.get().asFile.sha1}'",
server: "'${createServerSRG.output.get().asFile.sha1}'"
],
BINPATCH: [
client: '/data/client.lzma',
@@ -771,18 +793,31 @@ tasks.register('installerJson', InstallerJson) {
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_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
'--output', '{MC_SRG}',
'--names', '{MERGED_MAPPINGS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
],
outputs: [
'{MC_OFF}': '{MC_OFF_SHA}'
'{MC_SRG}': '{MC_SRG_SHA}'
]
], [
sides: ['client'],
@@ -790,18 +825,18 @@ tasks.register('installerJson', InstallerJson) {
classpath: getClasspath(project, libs, FART),
args: [
'--input', '{MINECRAFT_JAR}',
'--output', '{MC_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
'--output', '{MC_SRG}',
'--names', '{MERGED_MAPPINGS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
],
outputs: [
'{MC_OFF}': '{MC_OFF_SHA}'
'{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_OFF}',
'--clean', '{MC_SRG}',
'--output', '{PATCHED}',
'--apply', '{BINPATCH}',
'--data', '--unpatched'
@@ -816,27 +851,6 @@ tasks.register('installerJson', InstallerJson) {
}
}
tasks.register('officialClassesOnly', Zip).configure {
dependsOn(jar)
destinationDirectory = file('build/libs')
archiveClassifier = 'official-classes'
from zipTree(jar.archiveFile).matching {
include '**/*.class'
exclude 'mcp/**'
}
}
tasks.named('filterJarNew').configure {
dependsOn('officialClassesOnly')
input = officialClassesOnly.archiveFile
}
tasks.register('filterJarNewSRG', FilterNewJar).configure {
input = reobfJar.output
srg = filterJarNew.srg
blacklist = filterJarNew.blacklist
}
tasks.named('universalJar').configure {
dependsOn downloadCrowdin
from zipTree(downloadCrowdin.dest).matching {
@@ -868,20 +882,6 @@ tasks.named('universalJar').configure {
jarSigner.sign(it)
}
tasks.register('universalJarSrg', Jar).configure {
from zipTree(filterJarNewSRG.output)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from zipTree(universalJar.archiveFile)
destinationDirectory = file('build/libs')
archiveClassifier = 'universal-srg'
manifest.from(universalJar.manifest)
jarSigner.sign(it)
}
tasks.named('userdevConfig').configure {
universal = "$project.group:$project.name:$project.version:universal-srg@jar"
}
tasks.register('installerJar', InstallerJar) {
fat = !System.env.TEAMCITY_VERSION
//offline = true
@@ -1068,7 +1068,6 @@ tasks.named('javadoc', Javadoc).configure {
publishing {
publications.register('mavenJava', MavenPublication).configure {
artifact universalJar
artifact universalJarSrg
artifact installerJar
artifact mdkZip
artifact userdevJar
@@ -1080,8 +1079,8 @@ publishing {
name = project.name
description = 'Modifactions to Minecraft to enable mod developers.'
url = 'https://github.com/MinecraftForge/MinecraftForge'
gradleutils.pom.setGitHubDetails(pom, 'MinecraftForge')
license gradleutils.pom.Licenses.LGPLv2_1
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
license PomUtils.Licenses.LGPLv2_1
}
}
@@ -1091,5 +1090,5 @@ publishing {
}
// Make sure we run bin compat checking during local testing.
if ((!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) && CHECK_COMPATIBILITY == "true")
if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') }
+8
View File
@@ -74,3 +74,11 @@ eclipse {
// Run when importing the project
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject
}
idea {
module {
// IntelliJ IDEA does not do this by itself anymore...
downloadJavadoc = true
downloadSources = true
}
}
+25 -6
View File
@@ -2,16 +2,15 @@
MinecraftForge
=============
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.20.6-&query=$.promos["1.20.6-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download]
[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=1.20.6-&query=$.promos["1.20.6-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.20.4-&query=$.promos["1.20.4-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download]
[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=1.20.4-&query=$.promos["1.20.4-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
)][Download] [![Discord](https://img.shields.io/discord/313125603924639766.svg?color=%237289da&label=Discord&logo=discord&logoColor=%237289da)][Discord] [![Support](https://img.shields.io/badge/Patreon-Support-orange.svg?logo=Patreon)][Patreon]
Forge is a free, open-source modding API all of your favourite mods use!
| Version | Support |
|---------| ------------- |
| 1.20.x | Active |
| 1.19.x | Legacy |
| Version | Support |
|--------------|-----------------------------|
| All versions | [Supported][Support-Policy] |
* [Download]
* [Forum]
@@ -31,6 +30,19 @@ You can download the installer for the *Recommended Build* or the
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
## Required Java Versions
We require the version of Java that Minecraft requires, which is currently:
| Minecraft | Java |
|---------------|-------------------|
| 1.20.6+ | [21][Adoptium-21] |
| 1.18 - 1.20.4 | [17][Adoptium-17] |
| 1.17.1 | [16][Adoptium-16] |
| 1.16.5- | [8][Adoptium-8] |
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
# Creating Mods
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
@@ -63,8 +75,15 @@ Please ensure you have a valid email address associated with your GitHub account
[Download]: https://files.minecraftforge.net/
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
[Adoptium-8]: https://adoptium.net/temurin/releases/?version=8
[Jarfix]: https://johann.loefflmann.net/en/software/jarfix/index.html
[Forum]: https://forums.minecraftforge.net/
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
[Support-Policy]: https://forums.minecraftforge.net/topic/144690-new-tiered-support-policy
[Discord]: https://discord.minecraftforge.net/
@@ -9,41 +9,35 @@ 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;
/**
* Used to allow access to certain things from the game layer
*/
public class Bindings {
private static final Bindings INSTANCE = new Bindings();
private Bindings() {}
private final IBindingsProvider provider;
private Bindings() {
var providers = new ArrayList<IBindingsProvider>(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);
}
/**
* The provider of the bindings
* @implNote May also throw a {@link ServiceConfigurationError}
*/
private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
/**
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
*/
public static Supplier<IEventBus> getForgeBus() {
return INSTANCE.provider.getForgeBusSupplier();
return PROVIDER.getForgeBusSupplier();
}
public static Supplier<I18NParser> getMessageParser() {
return INSTANCE.provider.getMessageParser();
return PROVIDER.getMessageParser();
}
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
return INSTANCE.provider.getConfigConfiguration();
return PROVIDER.getConfigConfiguration();
}
}
@@ -16,7 +16,8 @@ import net.minecraftforge.api.distmarker.Dist;
*
* @see Dist
*/
public enum LogicalSide {
public enum LogicalSide
{
/**
* The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
* viewpoint.
@@ -26,7 +27,6 @@ public enum LogicalSide {
* @see Dist#CLIENT
*/
CLIENT,
/**
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
* on the level.
@@ -41,14 +41,16 @@ public enum LogicalSide {
/**
* {@return if this logical side is the server}
*/
public boolean isServer() {
public boolean isServer()
{
return !isClient();
}
/**
* {@return if the logical side is the client}
*/
public boolean isClient() {
public boolean isClient()
{
return this == CLIENT;
}
}
@@ -8,9 +8,7 @@ package net.minecraftforge.fml;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.loading.FMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
@@ -19,28 +17,45 @@ public class ModLoadingContext
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
private ModContainer activeContainer;
private Object languageExtension;
private ModLoadingStage stage;
/**
* @deprecated Use the context provided by your language loader in your mod's constructor.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static ModLoadingContext get() {
return context.get();
}
private ModContainer activeContainer;
/**
* @deprecated Going to be moved to ForgeHooks for internal use.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public void setActiveContainer(final ModContainer container) {
this.activeContainer = container;
this.languageExtension = container == null ? null : container.contextExtension.get();
}
/**
* Going to be moved to ForgeHooks for internal use.
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public ModContainer getActiveContainer() {
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
}
@Deprecated(forRemoval = true, since = "1.21.1")
public String getActiveNamespace() {
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
}
public ModContainer getContainer() {
return getActiveContainer();
}
/**
* Register an {@link IExtensionPoint} with the mod container.
* @param point The extension point to register
@@ -48,7 +63,7 @@ public class ModLoadingContext
* @param <T> The type signature of the extension operator
*/
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
getActiveContainer().registerExtensionPoint(point, extension);
getContainer().registerExtensionPoint(point, extension);
}
/**
@@ -57,7 +72,7 @@ public class ModLoadingContext
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
*/
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
getActiveContainer().registerDisplayTest(() -> displayTest);
getContainer().registerDisplayTest(() -> displayTest);
}
/**
@@ -66,7 +81,7 @@ public class ModLoadingContext
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
*/
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
getActiveContainer().registerDisplayTest(displayTest);
getContainer().registerDisplayTest(displayTest);
}
/**
@@ -76,7 +91,7 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
*/
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
/**
@@ -86,29 +101,29 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
*/
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getActiveContainer().getModId());
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
return;
}
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer()));
getContainer().addConfig(new ModConfig(type, spec, getContainer()));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getActiveContainer().getModId(), fileName);
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
return;
}
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName));
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
}
@@ -67,9 +67,7 @@ public class ConfigFileTypeHandler {
}
private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
if (!Files.isDirectory(file.getParent())) {
Files.createDirectories(file.getParent());
}
Files.createDirectories(file.getParent());
Path p = defaultConfigPath.resolve(modConfig.getFileName());
if (Files.exists(p)) {
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
@@ -13,10 +13,10 @@ import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
public class PerformanceInfo {
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
private final boolean showCPUUsage;
private final OperatingSystemMXBean osBean;
private final MemoryMXBean memoryBean;
private float memory;
private String text;
@@ -24,15 +24,14 @@ public class PerformanceInfo {
PerformanceInfo() {
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
memoryBean = ManagementFactory.getMemoryMXBean();
}
void update() {
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage();
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
memory = (float) heapusage.getUsed() / heapusage.getMax();
if (!showCPUUsage) {
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20);
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
return;
}
@@ -44,7 +43,7 @@ public class PerformanceInfo {
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
}
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB %s".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20, cpuText);
text = "Memory: %d/%dMB (%.1f%%) %s".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f, cpuText);
}
String text() {
+1 -1
View File
@@ -37,7 +37,7 @@ dependencies {
implementation(libs.jimfs)
implementation(libs.log4j.core)
annotationProcessor(libs.bundles.log4j)
annotationProcessor(libs.log4j.core)
testCompileOnly(libs.nulls)
testRuntimeOnly(libs.bootstrap)
@@ -36,9 +36,9 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
*/
public class CapabilityTokenSubclass implements ILaunchPluginService {
private final String FUNC_NAME = "getType";
private final String FUNC_DESC = "()Ljava/lang/String;";
private final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
private static final String FUNC_NAME = "getType";
private static final String FUNC_DESC = "()Ljava/lang/String;";
private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
@@ -51,7 +51,14 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
}
@Override
@@ -75,7 +82,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9)
{
Deque<String> stack = new ArrayDeque<>();
final Deque<String> stack = new ArrayDeque<>();
@Override
public void visitClassType(final String name)
@@ -113,7 +120,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
}
}
private static class Holder {
private static final class Holder {
String value;
}
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -35,7 +36,11 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
new VanillaObjectHolderData("net.minecraft.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toMap(VanillaObjectHolderData::holderClass, Function.identity()));
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final Set<String> VANILLA_OBJECT_HOLDER_CLASSES = VANILLA_OBJECT_HOLDERS.keySet().stream()
.map(it -> it.replace('.', '/'))
.collect(Collectors.toUnmodifiableSet());
private static final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final int PUBLIC_STATIC_FINAL_FLAGS = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
@Override
public String name() {
@@ -46,13 +51,29 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
// Let's skip processing classes that definitely don't have object holders
String internalName = classType.getInternalName();
// Forge classes that aren't in the debug package (that package is used for tests)
if (internalName.startsWith("net/minecraftforge/") && !internalName.substring(18).contains("debug"))
return NAY;
// Vanilla classes that don't have object holders
if (internalName.startsWith("com/mojang/"))
return NAY;
// ...except specific ones we added to the VANILLA_OBJECT_HOLDERS map
if (internalName.startsWith("net/minecraft/") && !VANILLA_OBJECT_HOLDER_CLASSES.contains(internalName))
return NAY;
return YAY;
}
private boolean hasHolder(List<AnnotationNode> lst)
{
private boolean hasHolder(List<AnnotationNode> lst) {
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
@@ -76,10 +97,9 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
{
final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final
@@ -89,7 +109,7 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
if (VANILLA_OBJECT_HOLDERS.containsKey(classType.getClassName())) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L")).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL;
@@ -28,15 +28,16 @@ import org.slf4j.Logger;
public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger();
private final Type STRING = Type.getType(String.class);
private final Type ENUM = Type.getType(Enum.class);
private final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private final String NAME_DESC = Type.getMethodDescriptor(STRING);
private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
private static final Type STRING = Type.getType(String.class);
private static final Type ENUM = Type.getType(Enum.class);
private static final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private static final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private static final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private static final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
private static final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
private static final int FLAGS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
@Override
public String name() {
@@ -47,9 +48,15 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
}
@Override
@@ -58,25 +65,24 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return ComputeFlags.NO_REWRITE;
Type array = Type.getType("[" + classType.getDescriptor());
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) {
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE;
}
Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor();
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
//Static methods named "create" with first argument as a string
List<MethodNode> candidates = classNode.methods.stream()
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
.collect(Collectors.toList());
.toList();
if (candidates.isEmpty()) {
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
}
candidates.forEach(mtd ->
for (var mtd : candidates)
{
Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING)) {
@@ -108,8 +114,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE;
for (int x = 1; x < args.length; x++)
ctrArgs[1 + x] = args[x];
System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
@@ -231,7 +236,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
ins.load(vars, classType);
ins.areturn(classType);
}
});
}
return ComputeFlags.COMPUTE_FRAMES;
}
@@ -39,6 +39,7 @@ public class FMLConfig
EARLY_WINDOW_SQUIR("earlyWindowSquir", Boolean.FALSE, "Squir?"),
EARLY_WINDOW_SHOW_CPU("earlyWindowShowCPU", Boolean.FALSE, "Whether to show CPU usage stats in early window"),
EARLY_WINDOW_LOG_HELP_MSG("earlyWindowLogHelpMessage", Boolean.TRUE, "Whether to log a help message on first attempt, to aid troubleshooting. This setting should automatically disable itself after a successful launch"),
DETECT_NON_FORGE_MODS_TOML("detectNonForgeModsToml", Boolean.TRUE, "Attempt to detect non-Forge mods from their mods.toml to show a friendlier error message. This is a best-effort feature - disable if it causes issues."),
;
private final String entry;
@@ -57,6 +57,9 @@ public class FMLLoader {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
// Allows us to communicate properties with other services through ModLauncher
setupBlackboardKeys();
checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
@@ -120,6 +123,12 @@ public class FMLLoader {
return providers.get(0);
}
private static void setupBlackboardKeys() {
LOGGER.debug(CORE, "Requesting CoreMods to not apply the fix for ASMAPI.findFirstInstructionBefore by default");
var blackboardKey = TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "coremods.use_old_findFirstInstructionBefore", Boolean.class);
Launcher.INSTANCE.blackboard().<Boolean>computeIfAbsent(blackboardKey, k -> true);
}
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
@@ -77,7 +77,7 @@ public class MCPNamingService implements INameMappingService {
}
private static void loadMappings(final String mappingFileName, BiConsumer<String, String> mapStore) {
URL path = MCPNamingService.class.getClassLoader().getResource(mappingFileName);
URL path = ClassLoader.getSystemResource(mappingFileName); //We EXPLICITLY go through the SystemClassLoader here because this is dev-time only. And will be on the root classpath.
if (path == null)
return;
@@ -57,17 +57,11 @@ public class RuntimeDistCleaner implements ILaunchPluginService
throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST);
}
if (!FMLEnvironment.production && hasOnlyInWithModAnnotation(classNode.visibleAnnotations))
{
LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
throw new RuntimeException("Found @OnlyIn on @Mod class "+ classNode.name + " - this is not allowed as it causes crashes. Remove the OnlyIn and consider setting clientSideOnly=true in the root of your mods.toml instead");
}
if (classNode.interfaces != null )
{
unpack(classNode.visibleAnnotations).stream()
.filter(ann->Objects.equals(ann.desc, ONLYIN))
.filter(ann-> ann.values.contains("_interface"))
.filter(ann->ann.values.indexOf("_interface") != -1)
.filter(ann->!Objects.equals(((String[])ann.values.get(ann.values.indexOf("value") + 1))[1], DIST))
.map(ann -> ((Type)ann.values.get(ann.values.indexOf("_interface") + 1)).getInternalName())
.forEach(intf -> {
@@ -143,78 +137,22 @@ public class RuntimeDistCleaner implements ILaunchPluginService
}
@SuppressWarnings("unchecked")
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns)
{
if (anns == null)
{
return Collections.emptyList();
}
List<AnnotationNode> unpacked = new ArrayList<>();
for (var annotationNode : anns)
{
if (Objects.equals(annotationNode.desc, ONLYINS))
{
unpacked.add(annotationNode);
if (annotationNode.values != null)
{
List<AnnotationNode> subNodes = (List<AnnotationNode>) annotationNode.values.get(annotationNode.values.indexOf("value") + 1);
if (subNodes != null)
{
unpacked.addAll(subNodes);
}
}
}
}
return unpacked;
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns) {
if (anns == null) return Collections.emptyList();
List<AnnotationNode> ret = anns.stream().filter(ann->Objects.equals(ann.desc, ONLYIN)).collect(Collectors.toList());
anns.stream().filter(ann->Objects.equals(ann.desc, ONLYINS) && ann.values != null)
.map( ann -> (List<AnnotationNode>)ann.values.get(ann.values.indexOf("value") + 1))
.filter(v -> v != null)
.forEach(v -> v.forEach(ret::add));
return ret;
}
private boolean remove(final List<AnnotationNode> anns, final String side)
private static boolean remove(final List<AnnotationNode> anns, final String side)
{
var onlyIns = unpack(anns);
for (var onlyIn : onlyIns)
{
if (!Objects.equals(onlyIn.desc, ONLYINS) || onlyIn.values.contains("_interface"))
{
continue;
}
if (!Objects.equals(((String[])onlyIn.values.get(onlyIn.values.indexOf("value") + 1))[1], side))
{
return true;
}
}
return false;
}
private boolean hasOnlyInWithModAnnotation(final List<AnnotationNode> anns)
{
if (anns == null)
{
return false;
}
var foundModAnnotation = false;
var foundOnlyIn = false;
for (var ann : anns)
{
if (ann.desc.equals("Lnet/minecraftforge/fml/common/Mod;"))
{
foundModAnnotation = true;
} else if (Objects.equals(ann.desc, ONLYIN) || Objects.equals(ann.desc, ONLYINS))
{
foundOnlyIn = true;
}
}
return foundModAnnotation && foundOnlyIn;
return unpack(anns).stream().
filter(ann->Objects.equals(ann.desc, ONLYIN)).
filter(ann->ann.values.indexOf("_interface") == -1).
anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side));
}
@SuppressWarnings("unchecked")
@@ -231,9 +169,15 @@ public class RuntimeDistCleaner implements ILaunchPluginService
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/"))
return NAY;
return YAY;
}
private static class LambdaGatherer extends MethodVisitor {
@@ -18,7 +18,6 @@ import net.minecraftforge.forgespi.locating.IModProvider;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
@@ -37,11 +36,10 @@ public abstract class AbstractModProvider implements IModProvider {
protected static final String MODS_TOML = "META-INF/mods.toml";
protected IModLocator.ModFileOrException createMod(Path path) {
return createMod(path, false);
return this.createMod(path, getDefaultJarModType());
}
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown) {
protected IModLocator.ModFileOrException createMod(Path path, String defaultType) {
var mjm = new ModJarMetadata();
var sj = SecureJar.from(
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
@@ -51,20 +49,18 @@ public abstract class AbstractModProvider implements IModProvider {
IModFile mod;
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
if (type == null)
type = getDefaultJarModType();
type = defaultType;
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
mod = new ModFile(sj, this, ModFileParser::modsTomlParser);
if (mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
LOGGER.error(LogMarkers.SCAN, "Unable to load file \"{}\" because its mods.toml is requesting an invalid javafml loaderVersion (use \"*\" if you want to allow all versions) and is missing a forge modId dependency declaration (see the sample mods.toml in the MDK).", path);
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("File \"%s\" is not a Forge mod and cannot be loaded. Look for a Forge version of this mod or consider alternative mods.".formatted(mod.getFileName())));
}
} else if (type != null) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path);
mod = new ModFile(sj, this, this::manifestParser, type);
} else if (ignoreUnknown) {
return null;
} else
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
@@ -83,7 +83,14 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
final Path pathInFS = zipFS.getPath("/");
return Optional.of(createMod(pathInFS).file());
final IModFile.Type parentType = file.getType();
final String modType;
if (parentType == IModFile.Type.LIBRARY || parentType == IModFile.Type.LANGPROVIDER) {
modType = IModFile.Type.LIBRARY.name();
} else {
modType = IModFile.Type.GAMELIBRARY.name();
}
return Optional.of(createMod(pathInFS, modType).file());
} catch (Exception e) {
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.base.Strings;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.forgespi.language.IConfigurable;
@@ -48,6 +49,9 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
@ApiStatus.Internal
public static final String NOT_A_FORGE_MOD_PROP = "__FORGE__not_a_forge_mod";
@ApiStatus.Internal
public static final boolean DETECT_NON_FORGE_MODS_TOML = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.DETECT_NON_FORGE_MODS_TOML);
private final IConfigurable config;
private final ModFile modFile;
private final URL issueURL;
@@ -75,7 +79,8 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
this.languageSpecs = new ArrayList<>(List.of(new LanguageSpec(modLoader, modLoaderVersion)));
// if true, this might not be a Forge mod
boolean maybeNotAForgeMod = modLoader.equals(JAVAFML)
boolean maybeNotAForgeMod = DETECT_NON_FORGE_MODS_TOML
&& modLoader.equals(JAVAFML)
&& modLoaderVersion.hasRestrictions() // if loaderVersion is not "*"
&& modLoaderVerStr.equals(MAYBE_NOT_JAVAFML_VER); // if loaderVersion is exactly "[2,)"
@@ -214,7 +214,7 @@ public class ModInfo implements IModInfo, IConfigurable {
this.owner = owner;
this.modId = config.<String>getConfigElement("modId")
.orElseThrow(()->new InvalidModFileException("Missing required field modid in dependency", getOwningFile()));
if (this.modId.equals("forge")) {
if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && this.modId.equals("forge")) {
var fileProps = owner.getOwningFile().getFileProperties();
// Checking containsKey to avoid a possible exception if the property is not present (due to Collections.emptyMap())
if (!fileProps.isEmpty() && fileProps.containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
@@ -226,7 +226,7 @@ public class ModInfo implements IModInfo, IConfigurable {
var mandatory = config.<Boolean>getConfigElement("mandatory");
if (mandatory.isPresent()) {
this.mandatory = mandatory.get();
} else if (owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
} else if (ModFileInfo.DETECT_NON_FORGE_MODS_TOML && owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
this.mandatory = true;
} else {
throw new InvalidModFileException("Missing required field mandatory in dependency", getOwningFile());
@@ -16,7 +16,6 @@ import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
@@ -43,21 +42,11 @@ public class ModsFolderLocator extends AbstractModProvider implements IModLocato
public List<IModLocator.ModFileOrException> scanMods() {
LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder);
var excluded = ModDirTransformerDiscoverer.allExcluded();
try {
var ret = new ArrayList<IModLocator.ModFileOrException>();
var files = Files.list(this.modFolder).toList();
for (var file : files) {
var name = file.getFileName().toString().toLowerCase(Locale.ROOT);
if (excluded.contains(file) || !name.endsWith(SUFFIX))
continue;
var mod = this.createMod(file, true);
if (mod == null) {
LOGGER.debug(LogMarkers.SCAN, "Found unknown jar file {} ignoring", file);
} else {
ret.add(mod);
}
}
return ret;
try (var stream = Files.list(this.modFolder)) {
return stream.filter(path -> !excluded.contains(path) && path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(SUFFIX))
.sorted(Comparator.comparing(path -> path.getFileName().toString().toLowerCase(Locale.ROOT)))
.map(this::createMod)
.toList();
} catch (IOException e) {
return sneak(e);
}
@@ -48,7 +48,7 @@ class Scanner {
try (InputStream in = Files.newInputStream(path)){
ModClassVisitor mcv = new ModClassVisitor();
ClassReader cr = new ClassReader(in);
cr.accept(mcv, 0);
cr.accept(mcv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
mcv.buildData(result.getClasses(), result.getAnnotations());
} catch (IOException | IllegalArgumentException e) {
// mark path bad
@@ -15,7 +15,7 @@ abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
super(type, "forge_");
}
@Override public String getNaming() { return "mcp"; }
@Override public String getNaming() { return "srg"; }
@Override public boolean isProduction() { return true; }
public static class Client extends ForgeProdLaunchHandler {
+4 -9
View File
@@ -4,14 +4,9 @@ org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
org.gradle.parallel=true
JAVA_VERSION=21
MC_VERSION=1.20.6
JAVA_VERSION=17
MC_VERSION=1.20.4
MC_NEXT_VERSION=1.21
MCP_VERSION=20240429.135109
MCP_VERSION=20231207.112700
MAPPING_CHANNEL=official
MAPPING_VERSION=1.20.6
// Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false
// Set to true to allow for fuzzy patching. Useful during updateing
UPDATING=false
MAPPING_VERSION=1.20.4
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+13 -9
View File
@@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -130,10 +131,13 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -198,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@@ -6,7 +6,6 @@
package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.Mod;
@@ -20,21 +19,19 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Type;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Automatic eventbus subscriber - reads {@link EventBusSubscriber}
* annotations and passes the class instances to the {@link nBus}
* annotations and passes the class instances to the {@link Bus}
* defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/
public class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.class);
private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class);
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
if (scanData == null) return;
@@ -44,11 +41,6 @@ public class AutomaticEventSubscriber {
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
.toList();
var onlyIns = FMLEnvironment.production ? Collections.emptySet() : scanData.getAnnotations().stream()
.filter(data -> ONLY_IN_TYPE.equals(data.annotationType()))
.map(data -> data.clazz().getClassName())
.collect(Collectors.toSet());
var modids = scanData.getAnnotations().stream()
.filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
@@ -57,10 +49,6 @@ public class AutomaticEventSubscriber {
var defaultBus = new EnumData(null, "FORGE");
for (var data : targets) {
if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) {
throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead");
}
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId);
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
public class FMLJavaModLoadingContext
public class FMLJavaModLoadingContext extends ModLoadingContext
{
private final FMLModContainer container;
@@ -24,11 +24,18 @@ public class FMLJavaModLoadingContext
return container.getEventBus();
}
@Override
public FMLModContainer getContainer() {
return container;
}
/**
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
* @return The FMLJavaMod language specific extension from the ModLoadingContext
*
* @deprecated use {@link FMLJavaModLoadingContext} in your mod constructor
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static FMLJavaModLoadingContext get() {
return ModLoadingContext.get().extension();
}
@@ -21,6 +21,7 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Optional;
@@ -32,6 +33,7 @@ public class FMLModContainer extends ModContainer {
private final IEventBus eventBus;
private Object modInstance;
private final Class<?> modClass;
private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this);
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) {
super(info);
@@ -40,9 +42,7 @@ public class FMLModContainer extends ModContainer {
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this);
this.contextExtension = () -> contextExtension;
this.contextExtension = () -> context;
try {
var moduleName = info.getOwningFile().moduleName();
@@ -63,7 +63,13 @@ public class FMLModContainer extends ModContainer {
private void constructMod() {
try {
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
this.modInstance = modClass.getDeclaredConstructor().newInstance();
Constructor<?> constructor;
try {
constructor = modClass.getDeclaredConstructor(context.getClass());
} catch (NoSuchMethodException | SecurityException exception) {
constructor = modClass.getDeclaredConstructor();
}
this.modInstance = constructor.getParameterCount() == 0 ? constructor.newInstance() : constructor.newInstance(context);
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
} catch (Throwable e) {
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
+19 -13
View File
@@ -2,7 +2,7 @@ plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0.24,6.2)'
id 'net.minecraftforge.gradle' version '[6.0.16,6.2)'
}
version = mod_version
@@ -12,8 +12,8 @@ base {
archivesName = mod_id
}
// Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
minecraft {
@@ -31,9 +31,6 @@ minecraft {
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
// Tell FG to not automtically create the reobf tasks, as we now use Official mappings at runtime, If you don't use them at dev time then you'll have to fix your reobf yourself.
reobf = false
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
// In most cases, it is not necessary to enable.
@@ -127,11 +124,11 @@ dependencies {
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
// Example mod dependency with JEI
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}"
// runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}"
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
@@ -141,9 +138,6 @@ dependencies {
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
// Hack fix for now, force jopt-simple to be exactly 5.0.4 because Mojang ships that version, but some transitive dependencies request 6.0+
implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } }
}
// This block of code expands all declared replace properties in the specified resource targets.
@@ -177,8 +171,16 @@ tasks.named('jar', Jar).configure {
'Implementation-Vendor' : mod_authors
])
}
// This is the preferred method to reobfuscate your jar file
finalizedBy 'reobfJar'
}
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing:
// tasks.named('publish').configure {
// dependsOn 'reobfJar'
// }
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
@@ -197,6 +199,10 @@ tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IntelliJ no longer downloads javadocs and sources by default.
// This tells Gradle to force IDEA to do it.
idea.module { downloadJavadoc = downloadSources = true }
eclipse {
// Run everytime eclipse builds the code
//autoBuildTasks genEclipseRuns
@@ -18,7 +18,6 @@ import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
@@ -51,7 +50,7 @@ public class ExampleMod
// Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
.alwaysEdible().nutrition(1).saturationModifier(2f).build())));
.alwaysEat().nutrition(1).saturationMod(2f).build())));
// Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder()
@@ -61,9 +60,9 @@ public class ExampleMod
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());
public ExampleMod()
public ExampleMod(FMLJavaModLoadingContext context)
{
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus modEventBus = context.getModEventBus();
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
@@ -82,7 +81,7 @@ public class ExampleMod
modEventBus.addListener(this::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);
context.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
}
private void commonSetup(final FMLCommonSetupEvent event)
@@ -1,55 +1,56 @@
--- a/com/mojang/blaze3d/pipeline/RenderTarget.java
+++ b/com/mojang/blaze3d/pipeline/RenderTarget.java
@@ -106,7 +_,10 @@
GlStateManager._texParameter(3553, 34892, 0);
GlStateManager._texParameter(3553, 10242, 33071);
GlStateManager._texParameter(3553, 10243, 33071);
+ if (!stencilEnabled)
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, null);
+ else
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
}
@@ -113,7 +_,10 @@
GlStateManager._texParameter(3553, 34892, 0);
GlStateManager._texParameter(3553, 10242, 33071);
GlStateManager._texParameter(3553, 10243, 33071);
+ if (!stencilEnabled)
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, (IntBuffer)null);
+ else
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
}
this.setFilterMode(9728, true);
@@ -116,8 +_,13 @@
GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, null);
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
- if (this.useDepth) {
+ if (this.useDepth && !stencilEnabled) {
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
+ } else if(this.useDepth && net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ } else if (this.useDepth) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
}
this.setFilterMode(9728);
@@ -124,7 +_,14 @@
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
if (this.useDepth) {
+ if(!stencilEnabled)
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
+ else if(net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ } else {
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
+ }
}
this.checkStatus();
@@ -280,5 +_,26 @@
public int getDepthTextureId() {
return this.depthBufferId;
+ }
this.checkStatus();
@@ -292,4 +_,27 @@
public int getDepthTextureId() {
return this.depthBufferId;
}
+
+ private boolean stencilEnabled = false;
+ /**
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
+ * Modders must call this directly to set things up.
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
+ * <b>Make sure to call this on the main render thread!</b>
+ */
+ public void enableStencil() {
+ if (stencilEnabled) return;
+ stencilEnabled = true;
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
+ }
+ /*================================ FORGE START ================================================*/
+ private boolean stencilEnabled = false;
+ /**
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
+ * Modders must call this directly to set things up.
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
+ * <b>Make sure to call this on the main render thread!</b>
+ */
+ public void enableStencil() {
+ if(stencilEnabled) return;
+ stencilEnabled = true;
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
+ }
+
+ /**
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
+ * If not, and a modder wishes it to be, they must call enableStencil.
+ */
+ public boolean isStencilEnabled() {
+ return this.stencilEnabled;
}
+ /**
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
+ * If not, and a modder wishes it to be, they must call enableStencil.
+ */
+ public boolean isStencilEnabled() {
+ return this.stencilEnabled;
+ }
+ /*================================ FORGE END ================================================*/
}
@@ -1,20 +1,19 @@
--- a/com/mojang/blaze3d/platform/GlStateManager.java
+++ b/com/mojang/blaze3d/platform/GlStateManager.java
@@ -493,9 +_,17 @@
}
}
@@ -501,9 +_,16 @@
+ /* Stores the last values sent into glMultiTexCoord2f */
+ public static float lastBrightnessX = 0.0f;
+ public static float lastBrightnessY = 0.0f;
+
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
RenderSystem.assertOnRenderThreadOrInit();
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
+ if (p_84161_ == GL13.GL_TEXTURE1) {
+ lastBrightnessX = p_84162_;
+ lastBrightnessY = p_84163_;
+ }
}
}
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
+ /* Stores the last values sent into glMultiTexCoord2f */
+ public static float lastBrightnessX = 0.0f;
+ public static float lastBrightnessY = 0.0f;
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
RenderSystem.assertOnRenderThreadOrInit();
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
+ if (p_84161_ == GL13.GL_TEXTURE1) {
+ lastBrightnessX = p_84162_;
+ lastBrightnessY = p_84163_;
+ }
}
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
@@ -1,30 +1,28 @@
--- a/com/mojang/blaze3d/platform/Window.java
+++ b/com/mojang/blaze3d/platform/Window.java
@@ -82,7 +_,8 @@
GLFW.glfwWindowHint(139267, 2);
GLFW.glfwWindowHint(139272, 204801);
GLFW.glfwWindowHint(139270, 1);
- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) {
if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
@@ -94,6 +_,7 @@
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
+ }
@@ -81,7 +_,8 @@
GLFW.glfwWindowHint(139267, 2);
GLFW.glfwWindowHint(139272, 204801);
GLFW.glfwWindowHint(139270, 1);
- this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) {
if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
@@ -93,6 +_,7 @@
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
+ }
GLFW.glfwMakeContextCurrent(this.window);
GL.createCapabilities();
@@ -242,6 +_,9 @@
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) {
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w -> this.framebufferWidth = w, h -> this.framebufferHeight = h);
+ }
}
GLFW.glfwMakeContextCurrent(this.window);
GL.createCapabilities();
@@ -242,6 +_,7 @@
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth==0) net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w->this.framebufferWidth=w, h->this.framebufferHeight=h);
}
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
@@ -1,18 +1,17 @@
--- a/com/mojang/blaze3d/vertex/BufferBuilder.java
+++ b/com/mojang/blaze3d/vertex/BufferBuilder.java
@@ -389,6 +_,15 @@
return MemoryUtil.memSlice(this.buffer, p_231170_, p_231171_ - p_231170_);
}
+ public void putBulkData(ByteBuffer buffer) {
+ ensureCapacity(buffer.limit() + this.format.getVertexSize());
+ this.buffer.position(this.nextElementByte);
+ this.buffer.put(buffer);
+ this.buffer.position(0);
+ this.vertices += buffer.limit() / this.format.getVertexSize();
+ this.nextElementByte += buffer.limit();
+ }
@@ -477,4 +_,14 @@
this.sorting = p_277855_;
}
}
+
@OnlyIn(Dist.CLIENT)
public static record DrawState(
VertexFormat format, int vertexCount, int indexCount, VertexFormat.Mode mode, VertexFormat.IndexType indexType, boolean indexOnly, boolean sequentialIndex
+ // Forge start
+ public void putBulkData(ByteBuffer buffer) {
+ ensureCapacity(buffer.limit() + this.format.getVertexSize());
+ this.buffer.position(this.nextElementByte);
+ this.buffer.put(buffer);
+ this.buffer.position(0);
+ this.vertices += buffer.limit() / this.format.getVertexSize();
+ this.nextElementByte += buffer.limit();
+ }
}
@@ -1,11 +1,11 @@
--- a/com/mojang/blaze3d/vertex/PoseStack.java
+++ b/com/mojang/blaze3d/vertex/PoseStack.java
@@ -13,7 +_,7 @@
import org.joml.Vector3f;
@@ -11,7 +_,7 @@
import org.joml.Quaternionf;
@OnlyIn(Dist.CLIENT)
-public class PoseStack {
+public class PoseStack implements net.minecraftforge.client.extensions.IForgePoseStack {
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), p_85848_ -> {
Matrix4f matrix4f = new Matrix4f();
Matrix3f matrix3f = new Matrix3f();
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), (p_85848_) -> {
Matrix4f matrix4f = new Matrix4f();
Matrix3f matrix3f = new Matrix3f();
@@ -1,11 +1,11 @@
--- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
+++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
@@ -47,7 +_,7 @@
@Override
public void endVertex() {
Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz));
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F));
vector4f.rotateY((float) Math.PI);
vector4f.rotateX((float) (-Math.PI / 2));
@@ -46,7 +_,7 @@
public void endVertex() {
Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz));
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F));
vector4f.rotateY((float)Math.PI);
vector4f.rotateX((-(float)Math.PI / 2F));
@@ -1,24 +1,38 @@
--- a/com/mojang/blaze3d/vertex/VertexConsumer.java
+++ b/com/mojang/blaze3d/vertex/VertexConsumer.java
@@ -13,7 +_,7 @@
@@ -14,7 +_,7 @@
import org.lwjgl.system.MemoryStack;
@OnlyIn(Dist.CLIENT)
-public interface VertexConsumer {
+public interface VertexConsumer extends net.minecraftforge.client.extensions.IForgeVertexConsumer {
VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_);
VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_);
VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_);
@@ -142,10 +_,11 @@
f5 = afloat[k] * p_85992_;
}
VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_);
@@ -64,6 +_,10 @@
}
- int l = aint[k];
+ int l = applyBakedLighting(aint[k], bytebuffer);
float f9 = bytebuffer.getFloat(16);
float f10 = bytebuffer.getFloat(20);
Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F));
+ applyBakedNormals(vector3f, bytebuffer, p_85988_.normal());
this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, p_335371_, f9, f10, p_85993_, l, vector3f.x(), vector3f.y(), vector3f.z());
default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, int[] p_86002_, int p_86003_, boolean p_86004_) {
+ putBulkData(p_85996_, p_85997_, p_85998_, p_85999_, p_86000_, p_86001_, 1, p_86002_, p_86003_, p_86004_);
+ }
+
+ default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, float alpha, int[] p_86002_, int p_86003_, boolean p_86004_) {
float[] afloat = new float[]{p_85998_[0], p_85998_[1], p_85998_[2], p_85998_[3]};
int[] aint = new int[]{p_86002_[0], p_86002_[1], p_86002_[2], p_86002_[3]};
int[] aint1 = p_85997_.getVertices();
@@ -99,11 +_,13 @@
f5 = afloat[k] * p_86001_;
}
}
- int l = aint[k];
+ int l = applyBakedLighting(p_86002_[k], bytebuffer);
float f9 = bytebuffer.getFloat(16);
float f10 = bytebuffer.getFloat(20);
Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F));
- this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, 1.0F, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
+ applyBakedNormals(vector3f, bytebuffer, p_85996_.normal());
+ float vertexAlpha = p_86004_ ? alpha * (float) (bytebuffer.get(15) & 255) / 255.0F : alpha;
+ this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, vertexAlpha, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
}
}
@@ -1,21 +1,14 @@
--- a/com/mojang/blaze3d/vertex/VertexFormat.java
+++ b/com/mojang/blaze3d/vertex/VertexFormat.java
@@ -12,7 +_,7 @@
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
-public class VertexFormat {
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
private final ImmutableList<VertexFormatElement> elements;
private final ImmutableMap<String, VertexFormatElement> elementMapping;
private final IntList offsets = new IntArrayList();
@@ -113,6 +_,9 @@
return vertexbuffer;
}
@@ -176,4 +_,11 @@
return i;
}
}
+
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
+ public int getOffset(int index) { return offsets.getInt(index); }
@OnlyIn(Dist.CLIENT)
public static enum IndexType {
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
+ public int getOffset(int index) { return offsets.getInt(index); }
+ public boolean hasPosition() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.POSITION); }
+ public boolean hasNormal() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.NORMAL); }
+ public boolean hasColor() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.COLOR); }
+ public boolean hasUV(int which) { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == which); }
}
@@ -0,0 +1,13 @@
--- a/com/mojang/blaze3d/vertex/VertexFormatElement.java
+++ b/com/mojang/blaze3d/vertex/VertexFormatElement.java
@@ -90,6 +_,10 @@
this.usage.clearBufferState(this.index, p_166964_);
}
+ public int getElementCount() {
+ return count;
+ }
+
@OnlyIn(Dist.CLIENT)
public static enum Type {
FLOAT(4, "Float", 5126),
@@ -1,31 +1,31 @@
--- a/com/mojang/math/Transformation.java
+++ b/com/mojang/math/Transformation.java
@@ -13,7 +_,7 @@
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector3fc;
-public final class Transformation {
+public final class Transformation implements net.minecraftforge.common.extensions.IForgeTransformation {
private final Matrix4f matrix;
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create(
p_269604_ -> p_269604_.group(
@@ -169,5 +_,19 @@
vector3f1.lerp(p_175938_.getScale(), p_175939_);
quaternionf1.slerp(p_175938_.getRightRotation(), p_175939_);
return new Transformation(vector3f, quaternionf, vector3f1, quaternionf1);
+ }
private final Matrix4f matrix;
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create((p_269604_) -> {
return p_269604_.group(ExtraCodecs.VECTOR3F.fieldOf("translation").forGetter((p_269599_) -> {
@@ -156,6 +_,19 @@
public int hashCode() {
return Objects.hash(this.matrix);
}
+
+ private Matrix3f normalTransform = null;
+ public Matrix3f getNormalMatrix() {
+ checkNormalTransform();
+ return normalTransform;
+ }
+
+ private void checkNormalTransform() {
+ if (normalTransform == null) {
+ normalTransform = new Matrix3f(matrix);
+ normalTransform.invert();
+ normalTransform.transpose();
+ }
}
}
+ }
public Transformation slerp(Transformation p_175938_, float p_175939_) {
Vector3f vector3f = this.getTranslation();
@@ -1,9 +1,10 @@
--- a/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
+++ b/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
@@ -71,6 +_,15 @@
}
@@ -61,6 +_,15 @@
return Component.empty().append(this.lines.title).append(": ").append(this.lines.detail);
}
@Override
+ @Override
+ public boolean keyPressed(int key, int scanCode, int modifiers) {
+ if (key == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) {
+ minecraft.setScreen(this.nextScreen);
@@ -12,7 +13,6 @@
+ return super.keyPressed(key, scanCode, modifiers);
+ }
+
+ @Override
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
@@ -1,48 +1,48 @@
--- a/net/minecraft/CrashReport.java
+++ b/net/minecraft/CrashReport.java
@@ -59,14 +_,9 @@
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
- p_127520_.append("Stacktrace:\n");
-
- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
- p_127520_.append("\t").append("at ").append(stacktraceelement);
- p_127520_.append("\n");
- }
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
- p_127520_.append("Stacktrace:\n");
-
- for(StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
- p_127520_.append("\t").append("at ").append((Object)stacktraceelement);
- p_127520_.append("\n");
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
}
- }
-
- p_127520_.append("\n");
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
}
for (CrashReportCategory crashreportcategory : this.details) {
for(CrashReportCategory crashreportcategory : this.details) {
@@ -74,6 +_,7 @@
p_127520_.append("\n\n");
}
p_127520_.append("\n\n");
}
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
this.systemReport.appendToCrashReportString(p_127520_);
}
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
this.systemReport.appendToCrashReportString(p_127520_);
}
@@ -93,18 +_,7 @@
throwable.setStackTrace(this.exception.getStackTrace());
}
throwable.setStackTrace(this.exception.getStackTrace());
}
- String s;
- try {
- stringwriter = new StringWriter();
- printwriter = new PrintWriter(stringwriter);
- throwable.printStackTrace(printwriter);
- s = stringwriter.toString();
- } finally {
- IOUtils.closeQuietly((Writer)stringwriter);
- IOUtils.closeQuietly((Writer)printwriter);
- }
- String s;
- try {
- stringwriter = new StringWriter();
- printwriter = new PrintWriter(stringwriter);
- throwable.printStackTrace(printwriter);
- s = stringwriter.toString();
- } finally {
- IOUtils.closeQuietly((Writer)stringwriter);
- IOUtils.closeQuietly((Writer)printwriter);
- }
-
- return s;
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
}
- return s;
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
}
public String getFriendlyReport() {
public String getFriendlyReport() {
@@ -1,37 +1,38 @@
--- a/net/minecraft/CrashReportCategory.java
+++ b/net/minecraft/CrashReportCategory.java
@@ -112,8 +_,10 @@
if (astacktraceelement.length <= 0) {
return 0;
} else {
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
+ int len = astacktraceelement.length - 3 - p_128149_;
+ if (len <= 0) len = astacktraceelement.length;
+ this.stackTrace = new StackTraceElement[len];
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
return this.stackTrace.length;
}
}
@@ -160,16 +_,16 @@
@@ -102,8 +_,10 @@
if (astacktraceelement.length <= 0) {
return 0;
} else {
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
+ int len = astacktraceelement.length - 3 - p_128149_;
+ if (len <= 0) len = astacktraceelement.length;
+ this.stackTrace = new StackTraceElement[len];
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
return this.stackTrace.length;
}
}
@@ -147,17 +_,17 @@
if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:");
if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:");
-
- for (StackTraceElement stacktraceelement : this.stackTrace) {
- p_128169_.append("\n\tat ");
- p_128169_.append(stacktraceelement);
- }
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
}
}
- for(StackTraceElement stacktraceelement : this.stackTrace) {
- p_128169_.append("\n\tat ");
- p_128169_.append((Object)stacktraceelement);
- }
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
}
public StackTraceElement[] getStacktrace() {
return this.stackTrace;
+ }
}
public StackTraceElement[] getStacktrace() {
return this.stackTrace;
+ }
+
+ public void applyStackTrace(Throwable t) {
+ this.stackTrace = t.getStackTrace();
}
+ public void applyStackTrace(Throwable t) {
+ this.stackTrace = t.getStackTrace();
}
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
@@ -1,10 +1,10 @@
--- a/net/minecraft/SharedConstants.java
+++ b/net/minecraft/SharedConstants.java
@@ -181,6 +_,7 @@
}
@@ -215,6 +_,7 @@
}
static {
+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified
ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION);
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
static {
+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified
ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION);
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
@@ -1,11 +1,23 @@
--- a/net/minecraft/Util.java
+++ b/net/minecraft/Util.java
@@ -267,7 +_,7 @@
.getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion()))
.getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) {
- LOGGER.error("No data fixer registered for {}", p_137553_);
+ LOGGER.debug("No data fixer registered for {}", p_137553_);
if (SharedConstants.IS_RUNNING_IN_IDE) {
throw illegalargumentexception;
}
@@ -180,6 +_,11 @@
return 255;
}
+ // We add these inner classes to compensate for Mojang's missing inner classes and shift the anonymous class index.
+ // This allows us to obfuscate subsequent anonymous inner classes correctly.
+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT1 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } };
+ @SuppressWarnings("unused") private static java.util.function.LongSupplier INNER_CLASS_SHIFT2 = new java.util.function.LongSupplier() { public long getAsLong() { return 0; } };
+
public static ExecutorService backgroundExecutor() {
return BACKGROUND_EXECUTOR;
}
@@ -254,7 +_,7 @@
try {
type = DataFixers.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())).getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) {
- LOGGER.error("No data fixer registered for {}", (Object)p_137553_);
+ LOGGER.debug("No data fixer registered for {}", (Object)p_137553_);
if (SharedConstants.IS_RUNNING_IN_IDE) {
throw illegalargumentexception;
}
@@ -1,15 +1,15 @@
--- a/net/minecraft/advancements/Advancement.java
+++ b/net/minecraft/advancements/Advancement.java
@@ -214,7 +_,11 @@
}
@@ -171,7 +_,11 @@
}
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_));
+ return save(p_138390_, new ResourceLocation(p_138391_));
+ }
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
- AdvancementHolder advancementholder = this.build(new ResourceLocation(p_138391_));
+ return save(p_138390_, new ResourceLocation(p_138391_));
+ }
+
+ public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, ResourceLocation id) {
+ AdvancementHolder advancementholder = this.build(id);
p_138390_.accept(advancementholder);
return advancementholder;
}
+ public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, ResourceLocation id) {
+ AdvancementHolder advancementholder = this.build(id);
p_138390_.accept(advancementholder);
return advancementholder;
}
@@ -1,10 +1,11 @@
--- a/net/minecraft/advancements/AdvancementRewards.java
+++ b/net/minecraft/advancements/AdvancementRewards.java
@@ -40,6 +_,7 @@
LootParams lootparams = new LootParams.Builder(p_9990_.serverLevel())
.withParameter(LootContextParams.THIS_ENTITY, p_9990_)
.withParameter(LootContextParams.ORIGIN, p_9990_.position())
+ .withLuck(p_9990_.getLuck())
.create(LootContextParamSets.ADVANCEMENT_REWARD);
boolean flag = false;
@@ -27,7 +_,7 @@
public void grant(ServerPlayer p_9990_) {
p_9990_.giveExperiencePoints(this.experience);
- LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).create(LootContextParamSets.ADVANCEMENT_REWARD);
+ LootParams lootparams = (new LootParams.Builder(p_9990_.serverLevel())).withParameter(LootContextParams.THIS_ENTITY, p_9990_).withParameter(LootContextParams.ORIGIN, p_9990_.position()).withLuck(p_9990_.getLuck()).create(LootContextParamSets.ADVANCEMENT_REWARD); // Forge: Add luck to LootContext
boolean flag = false;
for(ResourceLocation resourcelocation : this.loot) {
@@ -0,0 +1,11 @@
--- a/net/minecraft/advancements/critereon/ItemPredicate.java
+++ b/net/minecraft/advancements/critereon/ItemPredicate.java
@@ -45,7 +_,7 @@
return false;
} else {
if (!this.enchantments.isEmpty()) {
- Map<Enchantment, Integer> map = EnchantmentHelper.deserializeEnchantments(p_45050_.getEnchantmentTags());
+ Map<Enchantment, Integer> map = p_45050_.getAllEnchantments();
for(EnchantmentPredicate enchantmentpredicate : this.enchantments) {
if (!enchantmentpredicate.containedIn(map)) {
@@ -1,21 +1,21 @@
--- a/net/minecraft/client/Camera.java
+++ b/net/minecraft/client/Camera.java
@@ -227,6 +_,18 @@
return this.partialTickTime;
}
@@ -212,6 +_,18 @@
return this.partialTickTime;
}
+ public void setAnglesInternal(float yaw, float pitch) {
+ this.yRot = yaw;
+ this.xRot = pitch;
+ }
+ public void setAnglesInternal(float yaw, float pitch) {
+ this.yRot = yaw;
+ this.xRot = pitch;
+ }
+
+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() {
+ if (!this.initialized)
+ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
+ else
+ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position);
+ }
+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() {
+ if (!this.initialized)
+ return net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
+ else
+ return this.level.getBlockState(this.blockPosition).getStateAtViewpoint(this.level, this.blockPosition, this.position);
+ }
+
@OnlyIn(Dist.CLIENT)
public static class NearPlane {
final Vec3 forward;
@OnlyIn(Dist.CLIENT)
public static class NearPlane {
final Vec3 forward;
@@ -2,9 +2,9 @@
+++ b/net/minecraft/client/ClientBrandRetriever.java
@@ -10,6 +_,6 @@
@DontObfuscate
public static String getClientModName() {
- return "vanilla";
+ return net.minecraftforge.internal.BrandingControl.getClientBranding();
}
@DontObfuscate
public static String getClientModName() {
- return "vanilla";
+ return net.minecraftforge.internal.BrandingControl.getClientBranding();
}
}
@@ -1,20 +1,20 @@
--- a/net/minecraft/client/ClientRecipeBook.java
+++ b/net/minecraft/client/ClientRecipeBook.java
@@ -65,7 +_,7 @@
Recipe<?> recipe = recipeholder.value();
if (!recipe.isSpecial() && !recipe.isIncomplete()) {
RecipeBookCategories recipebookcategories = getCategory(recipeholder);
- String s = recipe.getGroup();
+ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty.
if (s.isEmpty()) {
map.computeIfAbsent(recipebookcategories, p_90645_ -> Lists.newArrayList()).add(ImmutableList.of(recipeholder));
} else {
@@ -125,6 +_,8 @@
} else if (recipetype == RecipeType.SMITHING) {
return RecipeBookCategories.SMITHING;
} else {
+ var categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType)recipetype, p_299041_);
+ if (categories != null) return categories;
LOGGER.warn(
"Unknown recipe category: {}/{}",
LogUtils.defer(() -> BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType())),
@@ -56,7 +_,7 @@
Recipe<?> recipe = recipeholder.value();
if (!recipe.isSpecial() && !recipe.isIncomplete()) {
RecipeBookCategories recipebookcategories = getCategory(recipeholder);
- String s = recipe.getGroup();
+ String s = recipe.getGroup().isEmpty() ? recipeholder.id().toString() : recipe.getGroup(); // FORGE: Group value defaults to the recipe's ID if the recipe's explicit group is empty.
if (s.isEmpty()) {
map.computeIfAbsent(recipebookcategories, (p_90645_) -> {
return Lists.newArrayList();
@@ -144,6 +_,8 @@
} else if (recipetype == RecipeType.SMITHING) {
return RecipeBookCategories.SMITHING;
} else {
+ RecipeBookCategories categories = net.minecraftforge.client.RecipeBookManager.findCategories((RecipeType) recipetype, p_299041_);
+ if (categories != null) return categories;
LOGGER.warn("Unknown recipe category: {}/{}", LogUtils.defer(() -> {
return BuiltInRegistries.RECIPE_TYPE.getKey(recipe.getType());
}), LogUtils.defer(p_299041_::id));
@@ -1,183 +1,182 @@
--- a/net/minecraft/client/KeyMapping.java
+++ b/net/minecraft/client/KeyMapping.java
@@ -14,9 +_,9 @@
@@ -13,9 +_,9 @@
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
-public class KeyMapping implements Comparable<KeyMapping> {
+public class KeyMapping implements Comparable<KeyMapping>, net.minecraftforge.client.extensions.IForgeKeyMapping {
private static final Map<String, KeyMapping> ALL = Maps.newHashMap();
- private static final Map<InputConstants.Key, KeyMapping> MAP = Maps.newHashMap();
+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup();
private static final Set<String> CATEGORIES = Sets.newHashSet();
public static final String CATEGORY_MOVEMENT = "key.categories.movement";
public static final String CATEGORY_MISC = "key.categories.misc";
@@ -42,14 +_,14 @@
private int clickCount;
private static final Map<String, KeyMapping> ALL = Maps.newHashMap();
- private static final Map<InputConstants.Key, KeyMapping> MAP = Maps.newHashMap();
+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup();
private static final Set<String> CATEGORIES = Sets.newHashSet();
public static final String CATEGORY_MOVEMENT = "key.categories.movement";
public static final String CATEGORY_MISC = "key.categories.misc";
@@ -41,7 +_,7 @@
private int clickCount;
public static void click(InputConstants.Key p_90836_) {
- KeyMapping keymapping = MAP.get(p_90836_);
+ for (KeyMapping keymapping : MAP.getAll(p_90836_))
if (keymapping != null) {
keymapping.clickCount++;
}
}
public static void click(InputConstants.Key p_90836_) {
- KeyMapping keymapping = MAP.get(p_90836_);
+ for (KeyMapping keymapping : MAP.getAll(p_90836_))
if (keymapping != null) {
++keymapping.clickCount;
}
@@ -49,7 +_,7 @@
}
public static void set(InputConstants.Key p_90838_, boolean p_90839_) {
- KeyMapping keymapping = MAP.get(p_90838_);
+ for (KeyMapping keymapping : MAP.getAll(p_90838_))
if (keymapping != null) {
keymapping.setDown(p_90839_);
}
@@ -100,7 +_,7 @@
}
public static void set(InputConstants.Key p_90838_, boolean p_90839_) {
- KeyMapping keymapping = MAP.get(p_90838_);
+ for (KeyMapping keymapping : MAP.getAll(p_90838_))
if (keymapping != null) {
keymapping.setDown(p_90839_);
}
@@ -105,7 +_,7 @@
}
public boolean isDown() {
- return this.isDown;
+ return this.isDown && isConflictContextAndModifierActive();
}
public boolean isDown() {
- return this.isDown;
+ return this.isDown && isConflictContextAndModifierActive();
}
public String getCategory() {
@@ -136,7 +_,16 @@
public int compareTo(KeyMapping p_90841_) {
return this.category.equals(p_90841_.category)
? I18n.get(this.name).compareTo(I18n.get(p_90841_.name))
- : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category));
+ : compareSort(this.category, p_90841_.category);
+ }
+
+ private static int compareSort(String c1, String c2) {
+ Integer o1 = CATEGORY_SORT_ORDER.get(c1);
+ Integer o2 = CATEGORY_SORT_ORDER.get(c2);
+ if (o1 == null && o2 != null) return 1;
+ if (o1 != null && o2 == null) return -1;
+ if (o1 == null && o2 == null) return I18n.get(c1).compareTo(I18n.get(c2));
+ return o1.compareTo(o2);
}
public String getCategory() {
@@ -139,7 +_,13 @@
}
public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -145,6 +_,20 @@
}
public int compareTo(KeyMapping p_90841_) {
- return this.category.equals(p_90841_.category) ? I18n.get(this.name).compareTo(I18n.get(p_90841_.name)) : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category));
+ if (this.category.equals(p_90841_.category)) return I18n.get(this.name).compareTo(I18n.get(p_90841_.name));
+ Integer tCat = CATEGORY_SORT_ORDER.get(this.category);
+ Integer oCat = CATEGORY_SORT_ORDER.get(p_90841_.category);
+ if (tCat == null && oCat != null) return 1;
+ if (tCat != null && oCat == null) return -1;
+ if (tCat == null && oCat == null) return I18n.get(this.category).compareTo(I18n.get(p_90841_.category));
+ return tCat.compareTo(oCat);
}
public boolean same(KeyMapping p_90851_) {
+ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) {
+ var keyModifier = getKeyModifier();
+ var otherKeyModifier = p_90851_.getKeyModifier();
+ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) {
+ return true;
+ } else if (getKey().equals(p_90851_.getKey())) {
+ // IN_GAME key contexts have a conflict when at least one modifier is NONE.
+ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E.
+ // GUI and other key contexts do not have this limitation.
+ return keyModifier == otherKeyModifier ||
+ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) &&
+ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE));
+ }
public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -150,6 +_,20 @@
}
public boolean same(KeyMapping p_90851_) {
+ if (getKeyConflictContext().conflicts(p_90851_.getKeyConflictContext()) || p_90851_.getKeyConflictContext().conflicts(getKeyConflictContext())) {
+ net.minecraftforge.client.settings.KeyModifier keyModifier = getKeyModifier();
+ net.minecraftforge.client.settings.KeyModifier otherKeyModifier = p_90851_.getKeyModifier();
+ if (keyModifier.matches(p_90851_.getKey()) || otherKeyModifier.matches(getKey())) {
+ return true;
+ } else if (getKey().equals(p_90851_.getKey())) {
+ // IN_GAME key contexts have a conflict when at least one modifier is NONE.
+ // For example: If you hold shift to crouch, you can still press E to open your inventory. This means that a Shift+E hotkey is in conflict with E.
+ // GUI and other key contexts do not have this limitation.
+ return keyModifier == otherKeyModifier ||
+ (getKeyConflictContext().conflicts(net.minecraftforge.client.settings.KeyConflictContext.IN_GAME) &&
+ (keyModifier == net.minecraftforge.client.settings.KeyModifier.NONE || otherKeyModifier == net.minecraftforge.client.settings.KeyModifier.NONE));
+ }
return this.key.equals(p_90851_.key);
}
+ }
return this.key.equals(p_90851_.key);
}
@@ -163,11 +_,13 @@
}
@@ -170,11 +_,13 @@
}
public Component getTranslatedKeyMessage() {
+ return getKeyModifier().getCombinedName(key, () -> {
return this.key.getDisplayName();
+ });
}
public Component getTranslatedKeyMessage() {
+ return getKeyModifier().getCombinedName(key, () -> {
return this.key.getDisplayName();
+ });
}
public boolean isDefault() {
- return this.key.equals(this.defaultKey);
+ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier();
}
public boolean isDefault() {
- return this.key.equals(this.defaultKey);
+ return this.key.equals(this.defaultKey) && getKeyModifier() == getDefaultKeyModifier();
}
public String saveString() {
@@ -176,5 +_,88 @@
public String saveString() {
@@ -183,5 +_,89 @@
public void setDown(boolean p_90846_) {
this.isDown = p_90846_;
+ }
public void setDown(boolean p_90846_) {
this.isDown = p_90846_;
+ }
+
+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL;
+ /****************** Forge Start *****************************/
+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL;
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category);
+ }
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) {
+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category);
+ }
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) {
+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category);
+ }
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category);
+ }
+
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) {
+ this.name = description;
+ this.key = keyCode;
+ this.defaultKey = keyCode;
+ this.category = category;
+ /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) {
+ this.name = description;
+ this.key = keyCode;
+ this.defaultKey = keyCode;
+ this.category = category;
+ this.keyConflictContext = keyConflictContext;
+ this.keyModifier = keyModifier;
+ this.keyModifierDefault = keyModifier;
+ if (this.keyModifier.matches(keyCode))
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this);
+ MAP.put(keyCode, this);
+ CATEGORIES.add(category);
+ }
+
+ @Override
+ public InputConstants.Key getKey() {
+ return this.key;
+ }
+
+ @Override
+ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) {
+ this.keyConflictContext = keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() {
+ return keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() {
+ return keyModifierDefault;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() {
+ return keyModifier;
+ }
+
+ @Override
+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ MAP.remove(this);
+
+ if (keyModifier == null)
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key);
+ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+
+ this.key = keyCode;
+ this.keyModifier = keyModifier;
+ this.keyModifierDefault = keyModifier;
+ if (this.keyModifier.matches(keyCode))
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this);
+
+ MAP.put(keyCode, this);
+ CATEGORIES.add(category);
+ }
+
+ @Override
+ public InputConstants.Key getKey() {
+ return this.key;
+ }
+
+ @Override
+ public void setKeyConflictContext(net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext) {
+ this.keyConflictContext = keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.IKeyConflictContext getKeyConflictContext() {
+ return keyConflictContext;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getDefaultKeyModifier() {
+ return keyModifierDefault;
+ }
+
+ @Override
+ public net.minecraftforge.client.settings.KeyModifier getKeyModifier() {
+ return keyModifier;
+ }
+
+ @Override
+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ MAP.remove(this);
+
+ if (keyModifier == null)
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.key);
+ if (keyModifier == null || keyCode == InputConstants.UNKNOWN || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+
+ this.key = keyCode;
+ this.keyModifier = keyModifier;
+
+ MAP.put(keyCode, this);
}
}
}
@@ -1,39 +1,50 @@
--- a/net/minecraft/client/KeyboardHandler.java
+++ b/net/minecraft/client/KeyboardHandler.java
@@ -410,9 +_,9 @@
Screen.wrapScreenError(() -> {
if (p_90897_ == 1 || p_90897_ == 2) {
screen.afterKeyboardAction();
- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(aboolean, screen, p_90895_, p_90896_, p_90898_);
} else if (p_90897_ == 0) {
- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(aboolean, screen, p_90895_, p_90896_, p_90898_);
}
}, "keyPressed event handler", screen.getClass().getCanonicalName());
if (aboolean[0]) {
@@ -481,20 +_,21 @@
}
}
}
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
}
}
@@ -397,11 +_,15 @@
Screen.wrapScreenError(() -> {
if (p_90897_ != 1 && p_90897_ != 2) {
if (p_90897_ == 0) {
- aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPre(screen, p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = screen.keyReleased(p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleasedPost(screen, p_90895_, p_90896_, p_90898_);
}
} else {
screen.afterKeyboardAction();
- aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPre(screen, p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = screen.keyPressed(p_90895_, p_90896_, p_90898_);
+ if (!aboolean[0]) aboolean[0] = net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressedPost(screen, p_90895_, p_90896_, p_90898_);
}
private void charTyped(long p_90890_, int p_90891_, int p_90892_) {
if (p_90890_ == this.minecraft.getWindow().getWindow()) {
- GuiEventListener guieventlistener = this.minecraft.screen;
+ Screen guieventlistener = this.minecraft.screen;
if (guieventlistener != null && this.minecraft.getOverlay() == null) {
if (Character.charCount(p_90891_) == 1) {
Screen.wrapScreenError(
- () -> guieventlistener.charTyped((char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()
+ () -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, (char)p_90891_, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName()
);
} else {
for (char c0 : Character.toChars(p_90891_)) {
- Screen.wrapScreenError(() -> guieventlistener.charTyped(c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(guieventlistener, c0, p_90892_), "charTyped event handler", guieventlistener.getClass().getCanonicalName());
}
}
}, "keyPressed event handler", screen.getClass().getCanonicalName());
@@ -478,21 +_,26 @@
}
}
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
}
}
private void charTyped(long p_90890_, int p_90891_, int p_90892_) {
if (p_90890_ == this.minecraft.getWindow().getWindow()) {
- GuiEventListener guieventlistener = this.minecraft.screen;
+ Screen guieventlistener = this.minecraft.screen;
if (guieventlistener != null && this.minecraft.getOverlay() == null) {
if (Character.charCount(p_90891_) == 1) {
Screen.wrapScreenError(() -> {
- guieventlistener.charTyped((char)p_90891_, p_90892_);
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, (char)p_90891_, p_90892_)) return;
+ if (guieventlistener.charTyped((char)p_90891_, p_90892_)) return;
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, (char)p_90891_, p_90892_);
}, "charTyped event handler", guieventlistener.getClass().getCanonicalName());
} else {
for(char c0 : Character.toChars(p_90891_)) {
Screen.wrapScreenError(() -> {
- guieventlistener.charTyped(c0, p_90892_);
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPre(guieventlistener, c0, p_90892_)) return;
+ if (guieventlistener.charTyped(c0, p_90892_)) return;
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTypedPost(guieventlistener, c0, p_90892_);
}, "charTyped event handler", guieventlistener.getClass().getCanonicalName());
}
}
@@ -1,452 +1,447 @@
--- a/net/minecraft/client/Minecraft.java
+++ b/net/minecraft/client/Minecraft.java
@@ -259,7 +_,7 @@
@@ -254,7 +_,7 @@
import org.slf4j.Logger;
@OnlyIn(Dist.CLIENT)
-public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler {
+public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft {
static Minecraft instance;
private static final Logger LOGGER = LogUtils.getLogger();
public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX;
static Minecraft instance;
private static final Logger LOGGER = LogUtils.getLogger();
public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX;
@@ -438,7 +_,6 @@
}
}, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", this.user.getName());
- LOGGER.debug("(Session ID is {})", this.user.getSessionId());
this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat;
@@ -475,15 +_,15 @@
}
}
}, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", (Object)this.user.getName());
- LOGGER.debug("(Session ID is {})", (Object)this.user.getSessionId());
this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat;
@@ -474,15 +_,15 @@
}
this.window.setFramerateLimit(this.options.framerateLimit().get());
+ // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window.getWindow());
this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window.getWindow());
RenderSystem.initRenderer(this.options.glDebugVerbosity, false);
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F);
this.mainRenderTarget.clear(ON_OSX);
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
+ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager);
this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode);
@@ -542,6 +_,7 @@
this.entityRenderDispatcher = new EntityRenderDispatcher(this, this.textureManager, this.itemRenderer, this.blockRenderer, this.font, this.options, this.entityModels);
this.resourceManager.registerReloadListener(this.entityRenderDispatcher);
this.particleEngine = new ParticleEngine(this.level, this.textureManager);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine);
this.resourceManager.registerReloadListener(this.particleEngine);
this.paintingTextures = new PaintingTextureManager(this.textureManager);
this.resourceManager.registerReloadListener(this.paintingTextures);
@@ -554,13 +_,18 @@
this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers);
this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener());
this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers);
+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent());
this.resourceManager.registerReloadListener(this.levelRenderer);
- this.createSearchTrees();
+ // Forge: We delay this to allow registration of modded creative mode tabs
+ //this.createSearchTrees();
this.resourceManager.registerReloadListener(this.searchRegistry);
this.gpuWarnlistManager = new GpuWarnlistManager();
this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies);
this.gui = new Gui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
RealmsClient realmsclient = RealmsClient.create(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
@@ -584,6 +_,7 @@
this.options.fullscreen().set(this.window.isFullscreen());
}
this.window.setFramerateLimit(this.options.framerateLimit().get());
+ // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window.getWindow());
this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window.getWindow());
RenderSystem.initRenderer(this.options.glDebugVerbosity, false);
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.mainRenderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F);
this.mainRenderTarget.clear(ON_OSX);
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
+ net.minecraftforge.client.loading.ClientModLoader.begin(this, this.resourcePackRepository, this.resourceManager);
this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode);
@@ -538,10 +_,13 @@
this.gameRenderer = new GameRenderer(this, this.entityRenderDispatcher.getItemInHandRenderer(), this.resourceManager, this.renderBuffers);
this.resourceManager.registerReloadListener(this.gameRenderer.createReloadListener());
this.levelRenderer = new LevelRenderer(this, this.entityRenderDispatcher, this.blockEntityRenderDispatcher, this.renderBuffers);
+ net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RenderLevelStageEvent.RegisterStageEvent());
this.resourceManager.registerReloadListener(this.levelRenderer);
- this.createSearchTrees();
+ // Forge: We delay this to allow registration of modded creative mode tabs
+ // this.createSearchTrees();
this.resourceManager.registerReloadListener(this.searchRegistry);
this.particleEngine = new ParticleEngine(this.level, this.textureManager);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine);
this.resourceManager.registerReloadListener(this.particleEngine);
this.paintingTextures = new PaintingTextureManager(this.textureManager);
this.resourceManager.registerReloadListener(this.paintingTextures);
@@ -552,7 +_,10 @@
this.gpuWarnlistManager = new GpuWarnlistManager();
this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies);
- this.gui = new Gui(this, this.itemRenderer);
+ this.gui = new net.minecraftforge.client.gui.overlay.ForgeGui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
RealmsClient realmsclient = RealmsClient.create(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
@@ -572,6 +_,7 @@
TinyFileDialogs.tinyfd_messageBox("Minecraft", stringbuilder.toString(), "ok", "error", false);
}
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setDefaultErrorCallback();
@@ -604,16 +_,17 @@
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
this.setOverlay(
- new LoadingOverlay(
- this, reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay(
+ () -> this, () -> reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
if (SharedConstants.IS_RUNNING_IN_IDE) {
this.selfTest();
}
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setDefaultErrorCallback();
@@ -592,7 +_,7 @@
ReloadInstance reloadinstance = this.resourceManager.createReload(Util.backgroundExecutor(), this, RESOURCE_RELOAD_INITIAL_TASK, list);
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
- this.setOverlay(new LoadingOverlay(this, reloadinstance, (p_296164_) -> {
+ this.setOverlay(net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay(() -> this, () -> reloadinstance, (p_296164_) -> {
Util.ifElse(p_296164_, (p_296162_) -> {
this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie);
}, () -> {
@@ -602,8 +_,10 @@
this.reloadStateTracker.finishReload();
this.onResourceLoadFinished(minecraft$gameloadcookie);
+ net.minecraftforge.client.loading.ClientModLoader.completeModLoading();
}), false
- )
+ ).get()
);
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path());
}
@@ -702,6 +_,7 @@
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) {
stringbuilder.append("*");
+ stringbuilder.append(" Forge");
}
this.reloadStateTracker.finishReload();
this.onResourceLoadFinished(minecraft$gameloadcookie);
+ if (net.minecraftforge.client.loading.ClientModLoader.completeModLoading())
+ return; // Do not overwrite the error screen if there are errors
});
- }, false));
+ }, false).get());
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.path());
}
stringbuilder.append(" ");
@@ -701,7 +_,7 @@
private String createTitle() {
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) {
- stringbuilder.append("*");
+ stringbuilder.append('*').append(" Forge");
}
stringbuilder.append(" ");
@@ -725,6 +_,8 @@
}
}
private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) {
+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam.
+ return UserApiService.OFFLINE;
return p_193587_.user.user.getType() != User.Type.MSA
? UserApiService.OFFLINE
: p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
@@ -735,7 +_,7 @@
}
private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) {
+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam.
+ return UserApiService.OFFLINE;
return p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
}
private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
- if (this.resourcePackRepository.getSelectedIds().size() > 1) {
+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any.
this.clearResourcePacksOnError(p_91240_, null, p_299515_);
} else {
Util.throwAsRuntime(p_91240_);
@@ -817,9 +_,12 @@
}
@@ -733,7 +_,7 @@
}
public void createSearchTrees() {
+ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys();
+ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys();
+ for (var nameSearchKey : nameSearchKeys.values())
this.searchRegistry
.register(
- SearchRegistry.CREATIVE_NAMES,
+ nameSearchKey,
p_231451_ -> new FullTextSearchTree<>(
p_325272_ -> p_325272_.getTooltipLines(Item.TooltipContext.EMPTY, null, TooltipFlag.Default.NORMAL.asCreative())
.stream()
@@ -829,8 +_,9 @@
p_231451_
)
);
+ for (var tagSearchKey : tagSearchKeys.values())
this.searchRegistry
- .register(SearchRegistry.CREATIVE_TAGS, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_));
+ .register(tagSearchKey, p_231430_ -> new IdSearchTree<>(p_231353_ -> p_231353_.getTags().map(TagKey::location), p_231430_));
this.searchRegistry
.register(
SearchRegistry.RECIPE_COLLECTIONS,
@@ -854,9 +_,12 @@
p_301514_
)
);
- CreativeModeTabs.searchTab().setSearchTreeBuilder(p_255439_ -> {
- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_);
- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_);
+ nameSearchKeys.forEach((tab, nameSearchKey) -> {
+ var tagSearchKey = tagSearchKeys.get(tab);
+ tab.setSearchTreeBuilder(contents -> {
+ this.populateSearchTree(nameSearchKey, contents);
+ this.populateSearchTree(tagSearchKey, contents);
+ });
});
}
private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
- if (this.resourcePackRepository.getSelectedIds().size() > 1) {
+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any.
this.clearResourcePacksOnError(p_91240_, (Component)null, p_299515_);
} else {
Util.throwAsRuntime(p_91240_);
@@ -819,7 +_,10 @@
}
@@ -1039,12 +_,6 @@
LOGGER.error("setScreen called from non-game thread");
}
public void createSearchTrees() {
- this.searchRegistry.register(SearchRegistry.CREATIVE_NAMES, (p_231451_) -> {
+ var nameSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKeys();
+ var tagSearchKeys = net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKeys();
+ for (var nameSearchKey : nameSearchKeys.values())
+ this.searchRegistry.register(nameSearchKey, (p_231451_) -> {
return new FullTextSearchTree<>((p_210797_) -> {
return p_210797_.getTooltipLines((Player)null, TooltipFlag.Default.NORMAL.asCreative()).stream().map((p_231455_) -> {
return ChatFormatting.stripFormatting(p_231455_.getString()).trim();
@@ -830,7 +_,8 @@
return Stream.of(BuiltInRegistries.ITEM.getKey(p_91317_.getItem()));
}, p_231451_);
});
- this.searchRegistry.register(SearchRegistry.CREATIVE_TAGS, (p_231430_) -> {
+ for (var tagSearchKey : tagSearchKeys.values())
+ this.searchRegistry.register(tagSearchKey, (p_231430_) -> {
return new IdSearchTree<>((p_231353_) -> {
return p_231353_.getTags().map(TagKey::location);
}, p_231430_);
@@ -850,9 +_,12 @@
});
}, p_301514_);
});
- CreativeModeTabs.searchTab().setSearchTreeBuilder((p_255439_) -> {
- this.populateSearchTree(SearchRegistry.CREATIVE_NAMES, p_255439_);
- this.populateSearchTree(SearchRegistry.CREATIVE_TAGS, p_255439_);
+ nameSearchKeys.forEach((tab, nameSearchKey) -> {
+ var tagSearchKey = tagSearchKeys.get(tab);
+ tab.setSearchTreeBuilder(contents -> {
+ this.populateSearchTree(nameSearchKey, contents);
+ this.populateSearchTree(tagSearchKey, contents);
+ });
});
}
- if (this.screen != null) {
- this.screen.removed();
- } else {
- this.setLastInputType(InputType.NONE);
- }
@@ -1054,10 +_,6 @@
LOGGER.error("setScreen called from non-game thread");
}
- if (this.screen != null) {
- this.screen.removed();
- }
-
if (p_91153_ == null && this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
} else {
@@ -1058,6 +_,23 @@
}
if (p_91153_ == null && this.clientLevelTeardownInProgress) {
throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
} else {
@@ -1071,6 +_,19 @@
}
}
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.screen;
+ if (p_91153_ != null) {
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return;
+ p_91153_ = event;
+ }
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.screen;
+ if (p_91153_ != null) {
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return;
+ p_91153_ = event;
+ }
+
+ if (p_91153_ != old) {
+ if (old != null) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.removed();
+ } else {
+ this.setLastInputType(InputType.NONE);
+ }
+ }
+ if (old != null && p_91153_ != old) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.removed();
+ }
+
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1204,9 +_,12 @@
this.mouseHandler.handleAccumulatedMovement();
this.profiler.pop();
if (!this.noRender) {
+ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick);
this.profiler.popPush("gameRenderer");
this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_);
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick);
}
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1218,9 +_,12 @@
RenderSystem.enableCull();
this.profiler.pop();
if (!this.noRender) {
+ this.realPartialTick = this.pause ? this.pausePartialTick : this.timer.partialTick; // Cache this since pause is volatile
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickStart(this.realPartialTick);
this.profiler.popPush("gameRenderer");
this.gameRenderer.render(this.pause ? this.pausePartialTick : this.timer.partialTick, i, p_91384_);
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onRenderTickEnd(this.realPartialTick);
}
if (this.fpsPieResults != null) {
@@ -1240,7 +_,7 @@
boolean flag1 = this.hasSingleplayerServer()
&& (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen())
&& !this.singleplayerServer.isPublished();
- if (this.pause != flag1) {
+ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) {
if (flag1) {
this.pausePartialTick = this.timer.partialTick;
} else {
@@ -1248,6 +_,7 @@
}
if (this.fpsPieResults != null) {
@@ -1254,7 +_,8 @@
this.window.setErrorSection("Post render");
++this.frames;
boolean flag1 = this.hasSingleplayerServer() && (this.screen != null && this.screen.isPauseScreen() || this.overlay != null && this.overlay.isPauseScreen()) && !this.singleplayerServer.isPublished();
- if (this.pause != flag1) {
+ if (this.pause != flag1 && !net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePre(flag1)) {
+
if (flag1) {
this.pausePartialTick = this.timer.partialTick;
} else {
@@ -1262,6 +_,7 @@
}
this.pause = flag1;
+ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1);
}
this.pause = flag1;
+ net.minecraftforge.client.ForgeHooksClient.onClientPauseChangePost(flag1);
}
long l = Util.getNanos();
@@ -1340,10 +_,12 @@
this.window.setGuiScale((double)i);
if (this.screen != null) {
this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
}
long l = Util.getNanos();
@@ -1341,10 +_,12 @@
this.window.setGuiScale((double)i);
if (this.screen != null) {
this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
}
RenderTarget rendertarget = this.getMainRenderTarget();
rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX);
+ if (this.gameRenderer != null)
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove();
}
@@ -1619,6 +_,7 @@
}
RenderTarget rendertarget = this.getMainRenderTarget();
rendertarget.resize(this.window.getWidth(), this.window.getHeight(), ON_OSX);
+ if (this.gameRenderer != null)
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove();
}
@@ -1618,6 +_,7 @@
}
public void stop() {
+ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown();
this.running = false;
}
public void stop() {
+ if (this.isRunning()) net.minecraftforge.event.ForgeEventFactory.onGameShuttingDown();
this.running = false;
}
@@ -1647,10 +_,18 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.particleEngine.crack(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1678,6 +_,8 @@
return false;
} else {
boolean flag = false;
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!inputEvent.isCanceled())
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1685,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1698,8 +_,10 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.particleEngine.crack(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1679,6 +_,8 @@
return false;
} else {
boolean flag = false;
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!inputEvent.isCanceled())
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1686,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1699,8 +_,10 @@
}
this.player.resetAttackStrengthTicker();
+ net.minecraftforge.common.ForgeHooks.onEmptyLeftClick(this.player);
}
+ if (inputEvent.shouldSwingHand())
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
}
@@ -1716,6 +_,11 @@
}
for(InteractionHand interactionhand : InteractionHand.values()) {
+ var inputEvent = net.minecraftforge.client.ForgeHooksClient.onClickInput(1, this.options.keyUse, interactionhand);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand);
+ return;
+ }
ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return;
@@ -1736,7 +_,7 @@
}
this.player.resetAttackStrengthTicker();
+ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player);
}
if (interactionresult.consumesAction()) {
- if (interactionresult.shouldSwing()) {
+ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
}
+ if (inputEvent.shouldSwingHand())
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
@@ -1748,7 +_,7 @@
int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1.consumesAction()) {
- if (interactionresult1.shouldSwing()) {
+ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1764,6 +_,9 @@
}
}
+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS))
+ net.minecraftforge.common.ForgeHooks.onEmptyClick(this.player, interactionhand);
+
if (!itemstack.isEmpty()) {
InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand);
if (interactionresult2.consumesAction()) {
@@ -1795,6 +_,8 @@
--this.rightClickDelay;
}
+ net.minecraftforge.event.ForgeEventFactory.onPreClientTick();
+
this.profiler.push("gui");
this.chatListener.tick();
this.gui.tick(this.pause);
@@ -1887,6 +_,7 @@
this.tutorial.tick();
+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true);
try {
this.level.tick(() -> {
return true;
@@ -1902,6 +_,7 @@
throw new ReportedException(crashreport);
}
@@ -1715,6 +_,12 @@
}
+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true);
}
for (InteractionHand interactionhand : InteractionHand.values()) {
+ var inputEvent = net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(1, this.options.keyUse, interactionhand);
+ if (inputEvent.isCanceled()) {
+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand);
+ return;
+ }
this.profiler.popPush("animateTick");
@@ -1921,6 +_,8 @@
this.profiler.popPush("keyboard");
this.keyboardHandler.tick();
this.profiler.pop();
+
ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return;
@@ -1735,7 +_,7 @@
}
+ net.minecraftforge.event.ForgeEventFactory.onPostClientTick();
}
if (interactionresult.consumesAction()) {
- if (interactionresult.shouldSwing()) {
+ if (interactionresult.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
}
private boolean isMultiplayerServer() {
@@ -2112,6 +_,7 @@
}
@@ -1747,7 +_,7 @@
int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1.consumesAction()) {
- if (interactionresult1.shouldSwing()) {
+ if (interactionresult1.shouldSwing() && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.gameMode.hasInfiniteItems())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1763,6 +_,9 @@
}
}
public void setLevel(ClientLevel p_91157_) {
+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
ProgressScreen progressscreen = new ProgressScreen(true);
progressscreen.progressStartNoAbort(Component.translatable("connect.joining"));
this.updateScreenAndTick(progressscreen);
@@ -2146,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null;
this.gameRenderer.resetData();
+ net.minecraftforge.client.ForgeHooksClient.firePlayerLogout(this.gameMode, this.player);
this.gameMode = null;
this.narrator.clear();
this.clientLevelTeardownInProgress = true;
@@ -2153,6 +_,7 @@
try {
this.updateScreenAndTick(p_91321_);
if (this.level != null) {
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
if (integratedserver != null) {
this.profiler.push("waitForServer");
+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS))
+ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, interactionhand);
+
if (!itemstack.isEmpty()) {
InteractionResult interactionresult2 = this.gameMode.useItem(this.player, interactionhand);
if (interactionresult2.consumesAction()) {
@@ -1793,6 +_,8 @@
this.rightClickDelay--;
}
@@ -2165,6 +_,7 @@
+ net.minecraftforge.event.ForgeEventFactory.onPreClientTick();
+
this.profiler.push("gui");
this.chatListener.tick();
this.gui.tick(this.pause);
@@ -1877,6 +_,7 @@
this.gui.onDisconnected();
this.isLocalServer = false;
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
}
this.tutorial.tick();
this.level = null;
@@ -2313,6 +_,7 @@
+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true);
try {
this.level.tick(() -> true);
} catch (Throwable throwable) {
@@ -1890,6 +_,7 @@
throw new ReportedException(crashreport);
}
+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true);
private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.ForgeHooksClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return;
boolean flag = this.player.getAbilities().instabuild;
BlockEntity blockentity = null;
HitResult.Type hitresult$type = this.hitResult.getType();
@@ -2325,10 +_,7 @@
}
this.profiler.popPush("animateTick");
@@ -1909,6 +_,7 @@
this.profiler.popPush("keyboard");
this.keyboardHandler.tick();
this.profiler.pop();
+ net.minecraftforge.event.ForgeEventFactory.onPostClientTick();
}
Block block = blockstate.getBlock();
- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate);
- if (itemstack.isEmpty()) {
- return;
- }
+ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player);
private boolean isMultiplayerServer() {
@@ -2105,6 +_,7 @@
}
public void setLevel(ClientLevel p_91157_, ReceivingLevelScreen.Reason p_335893_) {
+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
this.updateScreenAndTick(new ReceivingLevelScreen(() -> false, p_335893_));
this.level = p_91157_;
this.updateLevelInEngines(p_91157_);
@@ -2142,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null;
this.gameRenderer.resetData();
+ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogout(this.gameMode, this.player);
this.gameMode = null;
this.narrator.clear();
this.clientLevelTeardownInProgress = true;
@@ -2149,6 +_,7 @@
try {
this.updateScreenAndTick(p_335030_);
if (this.level != null) {
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
if (integratedserver != null) {
this.profiler.push("waitForServer");
@@ -2161,6 +_,7 @@
this.gui.onDisconnected();
this.isLocalServer = false;
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
if (flag && Screen.hasControlDown() && blockstate.hasBlockEntity()) {
blockentity = this.level.getBlockEntity(blockpos);
@@ -2339,7 +_,7 @@
}
this.level = null;
@@ -2307,6 +_,7 @@
Entity entity = ((EntityHitResult)this.hitResult).getEntity();
- itemstack = entity.getPickResult();
+ itemstack = entity.getPickedResult(this.hitResult);
if (itemstack == null) {
return;
}
@@ -2904,6 +_,19 @@
private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInput(2, this.options.keyPickItem, InteractionHand.MAIN_HAND).isCanceled()) return;
boolean flag = this.player.getAbilities().instabuild;
BlockEntity blockentity = null;
HitResult.Type hitresult$type = this.hitResult.getType();
@@ -2319,7 +_,7 @@
}
Block block = blockstate.getBlock();
- itemstack = block.getCloneItemStack(this.level, blockpos, blockstate);
+ itemstack = blockstate.getCloneItemStack(this.hitResult, this.level, blockpos, this.player);
if (itemstack.isEmpty()) {
return;
}
@@ -2333,7 +_,7 @@
}
Entity entity = ((EntityHitResult)this.hitResult).getEntity();
- itemstack = entity.getPickResult();
+ itemstack = entity.getPickedResult(this.hitResult);
if (itemstack == null) {
return;
}
@@ -2931,6 +_,19 @@
@Nullable
public static String getLauncherBrand() {
return System.getProperty("minecraft.launcher.brand");
+ }
public void updateMaxMipLevel(int p_91313_) {
this.modelManager.updateMaxMipLevel(p_91313_);
+ }
+
+ public ItemColors getItemColors() {
+ return this.itemColors;
+ }
+ public ItemColors getItemColors() {
+ return this.itemColors;
+ }
+
+ public SearchRegistry getSearchTreeManager() {
+ return this.searchRegistry;
+ }
+ public SearchRegistry getSearchTreeManager() {
+ return this.searchRegistry;
+ }
+
+ private float realPartialTick;
+ public float getPartialTick() {
+ return this.realPartialTick;
}
+ private float realPartialTick;
+ public float getPartialTick() {
+ return this.realPartialTick;
}
@OnlyIn(Dist.CLIENT)
public EntityModelSet getEntityModels() {
@@ -1,73 +1,86 @@
--- a/net/minecraft/client/MouseHandler.java
+++ b/net/minecraft/client/MouseHandler.java
@@ -74,6 +_,7 @@
this.activeButton = -1;
this.activeButton = -1;
}
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
boolean[] aboolean = new boolean[]{false};
if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) {
@@ -87,11 +_,19 @@
if (flag) {
screen.afterMouseAction();
Screen.wrapScreenError(() -> {
- aboolean[0] = screen.mouseClicked(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.minecraft.screen.mouseClicked(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseClicked event handler", screen.getClass().getCanonicalName());
} else {
Screen.wrapScreenError(() -> {
- aboolean[0] = screen.mouseReleased(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.minecraft.screen.mouseReleased(d0, d1, i);
+ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseReleased event handler", screen.getClass().getCanonicalName());
}
}
@@ -116,6 +_,7 @@
}
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
}
@@ -129,8 +_,10 @@
if (this.minecraft.screen != null) {
double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2);
this.minecraft.screen.afterMouseAction();
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return;
+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2);
} else if (this.minecraft.player != null) {
if (this.accumulatedScrollX != 0.0D && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) {
this.accumulatedScrollX = 0.0D;
@@ -151,6 +_,7 @@
this.accumulatedScrollX -= (double)j;
this.accumulatedScrollY -= (double)i;
int k = i == 0 ? -j : i;
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return;
if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k);
@@ -219,7 +_,9 @@
double d2 = (p_91563_ - this.xpos) * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d3 = (p_91564_ - this.ypos) * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
Screen.wrapScreenError(() -> {
- screen.mouseDragged(d0, d1, this.activeButton, d2, d3);
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPre(screen, d0, d1, this.activeButton, d2, d3)) return;
+ if (screen.mouseDragged(d0, d1, this.activeButton, d2, d3)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPost(screen, d0, d1, this.activeButton, d2, d3);
}, "mouseDragged event handler", screen.getClass().getCanonicalName());
}
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
boolean[] aboolean = new boolean[]{false};
if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) {
@@ -86,9 +_,9 @@
Screen screen = this.minecraft.screen;
if (flag) {
screen.afterMouseAction();
- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseClicked(d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(aboolean, screen, d0, d1, i), "mouseClicked event handler", screen.getClass().getCanonicalName());
} else {
- Screen.wrapScreenError(() -> aboolean[0] = screen.mouseReleased(d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(aboolean, screen, d0, d1, i), "mouseReleased event handler", screen.getClass().getCanonicalName());
}
}
}
@@ -111,6 +_,7 @@
}
}
}
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
}
@@ -302,6 +_,14 @@
@@ -124,7 +_,9 @@
if (this.minecraft.screen != null) {
double d3 = this.xpos * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d4 = this.ypos * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2);
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return;
+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return;
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2);
this.minecraft.screen.afterMouseAction();
} else if (this.minecraft.player != null) {
if (this.accumulatedScrollX != 0.0 && Math.signum(d1) != Math.signum(this.accumulatedScrollX)) {
@@ -146,6 +_,7 @@
this.accumulatedScrollX -= (double)j;
this.accumulatedScrollY -= (double)i;
int k = i == 0 ? -j : i;
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return;
if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-k);
@@ -216,7 +_,7 @@
if (this.activeButton != -1 && this.mousePressedTime > 0.0) {
double d4 = this.accumulatedDX * (double)this.minecraft.getWindow().getGuiScaledWidth() / (double)this.minecraft.getWindow().getScreenWidth();
double d5 = this.accumulatedDY * (double)this.minecraft.getWindow().getGuiScaledHeight() / (double)this.minecraft.getWindow().getScreenHeight();
- Screen.wrapScreenError(() -> screen.mouseDragged(d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName());
+ Screen.wrapScreenError(() -> net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, d2, d3, this.activeButton, d4, d5), "mouseDragged event handler", screen.getClass().getCanonicalName());
}
screen.afterMouseMove();
@@ -283,6 +_,14 @@
public double ypos() {
return this.ypos;
+ }
public double ypos() {
return this.ypos;
+ }
+
+ public double getXVelocity() {
+ return this.accumulatedDX;
+ }
+ public double getXVelocity() {
+ return this.accumulatedDX;
+ }
+
+ public double getYVelocity() {
+ return this.accumulatedDY;
}
+ public double getYVelocity() {
+ return this.accumulatedDY;
}
public void setIgnoreFirstMove() {
public void setIgnoreFirstMove() {
@@ -1,97 +1,95 @@
--- a/net/minecraft/client/Options.java
+++ b/net/minecraft/client/Options.java
@@ -680,7 +_,8 @@
},
new OptionInstance.LazyEnum<>(
() -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(),
- p_232011_ -> Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_)
+ // FORGE: fix incorrect string comparison - PR #8767
+ p_232011_ -> Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_)
? Optional.empty()
: Optional.of(p_232011_),
Codec.STRING
@@ -1044,6 +_,7 @@
}
@@ -509,7 +_,8 @@
}, new OptionInstance.LazyEnum<>(() -> {
return Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList();
}, (p_232011_) -> {
- return Minecraft.getInstance().isRunning() && p_232011_ != "" && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_);
+ // FORGE: fix incorrect string comparison - PR #8767
+ return Minecraft.getInstance().isRunning() && (p_232011_ == null || !p_232011_.isEmpty()) && !Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().contains(p_232011_) ? Optional.empty() : Optional.of(p_232011_);
}, Codec.STRING), "", (p_299350_) -> {
SoundManager soundmanager = Minecraft.getInstance().getSoundManager();
soundmanager.reload();
@@ -841,6 +_,7 @@
}
public Options(Minecraft p_92138_, File p_92139_) {
+ setForgeKeybindProperties();
this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L;
@@ -1178,12 +_,22 @@
p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra);
this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility);
p_168428_.process("menuBackgroundBlurriness", this.menuBackgroundBlurriness);
+ processOptionsForge(p_168428_);
+ }
public Options(Minecraft p_92138_, File p_92139_) {
+ setForgeKeybindProperties();
this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = p_92138_.is64Bit();
@@ -964,11 +_,20 @@
p_168428_.process("telemetryOptInExtra", this.telemetryOptInExtra);
this.onboardAccessibility = p_168428_.process("onboardAccessibility", this.onboardAccessibility);
+ // FORGE: split off to allow reloading options after mod loading is done
+ private void processOptionsForge(Options.FieldAccess p_168428_) {
for (KeyMapping keymapping : this.keyMappings) {
- String s = keymapping.saveString();
+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : "");
String s1 = p_168428_.process("key_" + keymapping.getName(), s);
if (!s.equals(s1)) {
keymapping.setKey(InputConstants.getKey(s1));
+ if (s1.indexOf(':') != -1) {
+ String[] pts = s1.split(":");
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0]));
+ } else {
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1));
+ }
+ processOptionsForge(p_168428_);
+ }
+ // FORGE: split off to allow reloading options after mod loading is done
+ private void processOptionsForge(Options.FieldAccess p_168428_)
+ {
for(KeyMapping keymapping : this.keyMappings) {
- String s = keymapping.saveString();
+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : "");
String s1 = p_168428_.process("key_" + keymapping.getName(), s);
if (!s.equals(s1)) {
- keymapping.setKey(InputConstants.getKey(s1));
+ if (s1.indexOf(':') != -1) {
+ String[] pts = s1.split(":");
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0]));
+ } else
+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1));
}
}
@@ -987,6 +_,9 @@
}
public void load() {
+ this.load(false);
+ }
+ public void load(boolean limited) {
try {
if (!this.optionsFile.exists()) {
return;
@@ -1015,7 +_,8 @@
}
}
}
@@ -1201,6 +_,10 @@
}
- this.processOptions(new Options.FieldAccess() {
+ java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsForge : this::processOptions;
+ processor.accept(new Options.FieldAccess() {
@Nullable
private String getValueOrNull(String p_168459_) {
return compoundtag1.contains(p_168459_) ? compoundtag1.getString(p_168459_) : null;
@@ -1188,6 +_,7 @@
}
public void load() {
+ load(false);
+ }
public void broadcastOptions() {
+ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted.
if (this.minecraft.player != null) {
this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation()));
}
@@ -1246,6 +_,23 @@
}
p_92146_.setSelected(set);
+ }
+
+ public void load(boolean limited) {
try {
if (!this.optionsFile.exists()) {
return;
@@ -1228,7 +_,8 @@
}
}
+ private void setForgeKeybindProperties() {
+ net.minecraftforge.client.settings.KeyConflictContext inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME;
+ keyUp.setKeyConflictContext(inGame);
+ keyLeft.setKeyConflictContext(inGame);
+ keyDown.setKeyConflictContext(inGame);
+ keyRight.setKeyConflictContext(inGame);
+ keyJump.setKeyConflictContext(inGame);
+ keyShift.setKeyConflictContext(inGame);
+ keySprint.setKeyConflictContext(inGame);
+ keyAttack.setKeyConflictContext(inGame);
+ keyChat.setKeyConflictContext(inGame);
+ keyPlayerList.setKeyConflictContext(inGame);
+ keyCommand.setKeyConflictContext(inGame);
+ keyTogglePerspective.setKeyConflictContext(inGame);
+ keySmoothCamera.setKeyConflictContext(inGame);
}
- this.processOptions(
+ java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsForge : this::processOptions;
+ processor.accept(
new Options.FieldAccess() {
@Nullable
private String getValueOrNull(String p_168459_) {
@@ -1422,6 +_,7 @@
}
public void broadcastOptions() {
+ if (net.minecraftforge.client.loading.ClientModLoader.isLoading()) return; //Don't save settings before mods add keybindigns and the like to prevent them from being deleted.
if (this.minecraft.player != null) {
this.minecraft.player.connection.send(new ServerboundClientInformationPacket(this.buildPlayerInformation()));
}
@@ -1544,6 +_,23 @@
public static Component genericValueLabel(Component p_231901_, int p_231902_) {
return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_)));
+ }
+
+ private void setForgeKeybindProperties() {
+ var inGame = net.minecraftforge.client.settings.KeyConflictContext.IN_GAME;
+ keyUp.setKeyConflictContext(inGame);
+ keyLeft.setKeyConflictContext(inGame);
+ keyDown.setKeyConflictContext(inGame);
+ keyRight.setKeyConflictContext(inGame);
+ keyJump.setKeyConflictContext(inGame);
+ keyShift.setKeyConflictContext(inGame);
+ keySprint.setKeyConflictContext(inGame);
+ keyAttack.setKeyConflictContext(inGame);
+ keyChat.setKeyConflictContext(inGame);
+ keyPlayerList.setKeyConflictContext(inGame);
+ keyCommand.setKeyConflictContext(inGame);
+ keyTogglePerspective.setKeyConflictContext(inGame);
+ keySmoothCamera.setKeyConflictContext(inGame);
}
@OnlyIn(Dist.CLIENT)
public CameraType getCameraType() {
@@ -6,40 +6,34 @@
@OnlyIn(Dist.CLIENT)
-public enum RecipeBookCategories {
+public enum RecipeBookCategories implements net.minecraftforge.common.IExtensibleEnum {
CRAFTING_SEARCH(new ItemStack(Items.COMPASS)),
CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)),
CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)),
@@ -38,7 +_,7 @@
public static final List<RecipeBookCategories> CRAFTING_CATEGORIES = ImmutableList.of(
CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE
);
- public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = ImmutableMap.of(
+ public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories(ImmutableMap.of(
CRAFTING_SEARCH,
ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE),
FURNACE_SEARCH,
@@ -47,7 +_,7 @@
ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC),
SMOKER_SEARCH,
ImmutableList.of(SMOKER_FOOD)
- );
+ ));
private final List<ItemStack> itemIcons;
CRAFTING_SEARCH(new ItemStack(Items.COMPASS)),
CRAFTING_BUILDING_BLOCKS(new ItemStack(Blocks.BRICKS)),
CRAFTING_REDSTONE(new ItemStack(Items.REDSTONE)),
@@ -36,7 +_,7 @@
public static final List<RecipeBookCategories> BLAST_FURNACE_CATEGORIES = ImmutableList.of(BLAST_FURNACE_SEARCH, BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC);
public static final List<RecipeBookCategories> FURNACE_CATEGORIES = ImmutableList.of(FURNACE_SEARCH, FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC);
public static final List<RecipeBookCategories> CRAFTING_CATEGORIES = ImmutableList.of(CRAFTING_SEARCH, CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE);
- public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = ImmutableMap.of(CRAFTING_SEARCH, ImmutableList.of(CRAFTING_EQUIPMENT, CRAFTING_BUILDING_BLOCKS, CRAFTING_MISC, CRAFTING_REDSTONE), FURNACE_SEARCH, ImmutableList.of(FURNACE_FOOD, FURNACE_BLOCKS, FURNACE_MISC), BLAST_FURNACE_SEARCH, ImmutableList.of(BLAST_FURNACE_BLOCKS, BLAST_FURNACE_MISC), SMOKER_SEARCH, ImmutableList.of(SMOKER_FOOD));
+ public static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = net.minecraftforge.client.RecipeBookManager.getAggregateCategories();
private final List<ItemStack> itemIcons;
private RecipeBookCategories(final ItemStack... p_92267_) {
@@ -60,10 +_,15 @@
case FURNACE -> FURNACE_CATEGORIES;
case BLAST_FURNACE -> BLAST_FURNACE_CATEGORIES;
case SMOKER -> SMOKER_CATEGORIES;
+ default -> net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_);
};
}
private RecipeBookCategories(ItemStack... p_92267_) {
@@ -59,7 +_,7 @@
list = SMOKER_CATEGORIES;
break;
default:
- throw new IncompatibleClassChangeError();
+ return net.minecraftforge.client.RecipeBookManager.getCustomCategoriesOrEmpty(p_92270_);
}
public List<ItemStack> getIconItems() {
return this.itemIcons;
+ }
return list;
@@ -67,5 +_,9 @@
public List<ItemStack> getIconItems() {
return this.itemIcons;
+ }
+
+ public static RecipeBookCategories create(String name, ItemStack... icons) {
+ throw new IllegalStateException("Enum not extended");
}
+ public static RecipeBookCategories create(String name, ItemStack... icons) {
+ throw new IllegalStateException("Enum not extended");
}
}
@@ -1,30 +1,29 @@
--- a/net/minecraft/client/Screenshot.java
+++ b/net/minecraft/client/Screenshot.java
@@ -54,14 +_,24 @@
file2 = new File(file1, p_92307_);
}
@@ -56,13 +_,23 @@
file2 = new File(file1, p_92307_);
}
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenshot(nativeimage, file2);
+ if (event.isCanceled()) {
+ p_92311_.accept(event.getCancelMessage());
+ return;
+ }
+ final File target = event.getScreenshotFile();
+ net.minecraftforge.client.event.ScreenshotEvent event = net.minecraftforge.client.ForgeHooksClient.onScreenshot(nativeimage, file2);
+ if (event.isCanceled()) {
+ p_92311_.accept(event.getCancelMessage());
+ return;
+ }
+ final File target = event.getScreenshotFile();
+
Util.ioPool()
.execute(
() -> {
try {
- nativeimage.writeToFile(file2);
- Component component = Component.literal(file2.getName())
+ nativeimage.writeToFile(target);
+ Component component = Component.literal(target.getName())
.withStyle(ChatFormatting.UNDERLINE)
- .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath())));
+ .withStyle(p_168608_ -> p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath())));
+ if (event.getResultMessage() != null)
+ p_92311_.accept(event.getResultMessage());
+ else
p_92311_.accept(Component.translatable("screenshot.success", component));
} catch (Exception exception) {
LOGGER.warn("Couldn't save screenshot", (Throwable)exception);
Util.ioPool().execute(() -> {
try {
- nativeimage.writeToFile(file2);
+ nativeimage.writeToFile(target);
Component component = Component.literal(file2.getName()).withStyle(ChatFormatting.UNDERLINE).withStyle((p_168608_) -> {
- return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file2.getAbsolutePath()));
+ return p_168608_.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, target.getAbsolutePath()));
});
- p_92311_.accept(Component.translatable("screenshot.success", component));
+ if (event.getResultMessage() != null)
+ p_92311_.accept(event.getResultMessage());
+ else
+ p_92311_.accept(Component.translatable("screenshot.success", component));
} catch (Exception exception) {
LOGGER.warn("Couldn't save screenshot", (Throwable)exception);
p_92311_.accept(Component.translatable("screenshot.failure", exception.getMessage()));
@@ -1,21 +1,19 @@
--- a/net/minecraft/client/ToggleKeyMapping.java
+++ b/net/minecraft/client/ToggleKeyMapping.java
@@ -17,7 +_,7 @@
@Override
public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) {
- if (p_92534_) {
+ if (p_92534_ && isConflictContextAndModifierActive()) {
super.setDown(!this.isDown());
}
} else {
@@ -27,5 +_,9 @@
@@ -16,7 +_,7 @@
protected void reset() {
super.setDown(false);
+ }
+
+ @Override public boolean isDown() {
+ return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean());
}
}
public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) {
- if (p_92534_) {
+ if (p_92534_ && isConflictContextAndModifierActive()) {
super.setDown(!this.isDown());
}
} else {
@@ -24,6 +_,7 @@
}
}
+ @Override public boolean isDown() { return this.isDown && (isConflictContextAndModifierActive() || needsToggle.getAsBoolean()); }
protected void reset() {
super.setDown(false);
@@ -1,44 +1,44 @@
--- a/net/minecraft/client/color/block/BlockColors.java
+++ b/net/minecraft/client/color/block/BlockColors.java
@@ -29,7 +_,8 @@
@@ -28,7 +_,8 @@
@OnlyIn(Dist.CLIENT)
public class BlockColors {
private static final int DEFAULT = -1;
- private final IdMapper<BlockColor> blockColors = new IdMapper<>(32);
+ // Forge: Use registry delegate as non-Vanilla block ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Block>, BlockColor> blockColors = new java.util.HashMap<>(32);
private final Map<Block, Set<Property<?>>> coloringStates = Maps.newHashMap();
private static final int DEFAULT = -1;
- private final IdMapper<BlockColor> blockColors = new IdMapper<>(32);
+ // FORGE: Use registry delegate as non-Vanilla block ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Block>, BlockColor> blockColors = new java.util.HashMap<>();
private final Map<Block, Set<Property<?>>> coloringStates = Maps.newHashMap();
public static BlockColors createDefault() {
@@ -91,11 +_,12 @@
}, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockcolors.addColoringState(StemBlock.AGE, Blocks.MELON_STEM, Blocks.PUMPKIN_STEM);
blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> p_92597_ != null && p_92598_ != null ? -14647248 : -9321636, Blocks.LILY_PAD);
+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors);
return blockcolors;
}
public static BlockColors createDefault() {
@@ -80,11 +_,12 @@
blockcolors.register((p_92596_, p_92597_, p_92598_, p_92599_) -> {
return p_92597_ != null && p_92598_ != null ? 2129968 : 7455580;
}, Blocks.LILY_PAD);
+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors);
return blockcolors;
}
public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock()));
if (blockcolor != null) {
return blockcolor.getColor(p_92583_, null, null, 0);
} else {
@@ -105,13 +_,15 @@
}
public int getColor(BlockState p_92583_, Level p_92584_, BlockPos p_92585_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92583_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92583_.getBlock()));
if (blockcolor != null) {
return blockcolor.getColor(p_92583_, (BlockAndTintGetter)null, (BlockPos)null, 0);
} else {
@@ -94,13 +_,15 @@
}
public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock()));
return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_);
}
public int getColor(BlockState p_92578_, @Nullable BlockAndTintGetter p_92579_, @Nullable BlockPos p_92580_, int p_92581_) {
- BlockColor blockcolor = this.blockColors.byId(BuiltInRegistries.BLOCK.getId(p_92578_.getBlock()));
+ BlockColor blockcolor = this.blockColors.get(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(p_92578_.getBlock()));
return blockcolor == null ? -1 : blockcolor.getColor(p_92578_, p_92579_, p_92580_, p_92581_);
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */
+ @Deprecated
public void register(BlockColor p_92590_, Block... p_92591_) {
for (Block block : p_92591_) {
- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block));
+ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_);
}
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */
+ @Deprecated
public void register(BlockColor p_92590_, Block... p_92591_) {
for(Block block : p_92591_) {
- this.blockColors.addMapping(p_92590_, BuiltInRegistries.BLOCK.getId(block));
+ this.blockColors.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), p_92590_);
}
}
@@ -1,35 +1,35 @@
--- a/net/minecraft/client/color/item/ItemColors.java
+++ b/net/minecraft/client/color/item/ItemColors.java
@@ -26,7 +_,8 @@
@@ -25,7 +_,8 @@
@OnlyIn(Dist.CLIENT)
public class ItemColors {
private static final int DEFAULT = -1;
- private final IdMapper<ItemColor> itemColors = new IdMapper<>(32);
+ // Forge: Use registry delegate as non-Vanilla item ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Item>, ItemColor> itemColors = new java.util.HashMap<>(32);
private static final int DEFAULT = -1;
- private final IdMapper<ItemColor> itemColors = new IdMapper<>(32);
+ // FORGE: Use registry delegate as non-Vanilla item ids are not constant
+ private final java.util.Map<net.minecraft.core.Holder.Reference<Item>, ItemColor> itemColors = new java.util.HashMap<>();
public static ItemColors createDefault(BlockColors p_92684_) {
ItemColors itemcolors = new ItemColors();
@@ -105,17 +_,20 @@
: FastColor.ARGB32.opaque(p_325310_.getOrDefault(DataComponents.MAP_COLOR, MapItemColor.DEFAULT).rgb()),
Items.FILLED_MAP
);
+ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_);
return itemcolors;
}
public static ItemColors createDefault(BlockColors p_92684_) {
ItemColors itemcolors = new ItemColors();
@@ -88,17 +_,20 @@
itemcolors.register((p_232352_, p_232353_) -> {
return p_232353_ == 0 ? -1 : MapItem.getColor(p_232352_);
}, Items.FILLED_MAP);
+ net.minecraftforge.client.ForgeHooksClient.onItemColorsInit(itemcolors, p_92684_);
return itemcolors;
}
public int getColor(ItemStack p_92677_, int p_92678_) {
- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem()));
+ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem()));
return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_);
}
public int getColor(ItemStack p_92677_, int p_92678_) {
- ItemColor itemcolor = this.itemColors.byId(BuiltInRegistries.ITEM.getId(p_92677_.getItem()));
+ ItemColor itemcolor = this.itemColors.get(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(p_92677_.getItem()));
return itemcolor == null ? -1 : itemcolor.getColor(p_92677_, p_92678_);
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */
+ @Deprecated
public void register(ItemColor p_92690_, ItemLike... p_92691_) {
for (ItemLike itemlike : p_92691_) {
- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem()));
+ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_);
}
}
}
+ /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Item} */
+ @Deprecated
public void register(ItemColor p_92690_, ItemLike... p_92691_) {
for(ItemLike itemlike : p_92691_) {
- this.itemColors.addMapping(p_92690_, Item.getId(itemlike.asItem()));
+ this.itemColors.put(net.minecraftforge.registries.ForgeRegistries.ITEMS.getDelegateOrThrow(itemlike.asItem()), p_92690_);
}
}
@@ -6,15 +6,15 @@
@OnlyIn(Dist.CLIENT)
-public class Font {
+public class Font implements net.minecraftforge.client.extensions.IForgeFont {
private static final float EFFECT_DEPTH = 0.01F;
private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F);
public static final int ALPHA_CUTOFF = 8;
@@ -322,6 +_,8 @@
public StringSplitter getSplitter() {
return this.splitter;
}
private static final float EFFECT_DEPTH = 0.01F;
private static final Vector3f SHADOW_OFFSET = new Vector3f(0.0F, 0.0F, 0.03F);
public static final int ALPHA_CUTOFF = 8;
@@ -202,6 +_,8 @@
public StringSplitter getSplitter() {
return this.splitter;
}
+
+ @Override public Font self() { return this; }
+ @Override public Font self() { return this; }
@OnlyIn(Dist.CLIENT)
public static enum DisplayMode {
@OnlyIn(Dist.CLIENT)
public static enum DisplayMode {
@@ -1,84 +1,77 @@
--- a/net/minecraft/client/gui/Gui.java
+++ b/net/minecraft/client/gui/Gui.java
@@ -131,7 +_,7 @@
public float vignetteBrightness = 1.0F;
private int toolHighlightTimer;
private ItemStack lastToolHighlight = ItemStack.EMPTY;
- private final DebugScreenOverlay debugOverlay;
+ protected DebugScreenOverlay debugOverlay;
private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList;
@@ -320,7 +_,7 @@
Window window = this.minecraft.getWindow();
int i = Mth.floor(this.minecraft.mouseHandler.xpos() * (double)window.getGuiScaledWidth() / (double)window.getScreenWidth());
int j = Mth.floor(this.minecraft.mouseHandler.ypos() * (double)window.getGuiScaledHeight() / (double)window.getScreenHeight());
- this.chat.render(p_329202_, this.tickCount, i, j, false);
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(p_329202_, this.chat, window, i, j, this.tickCount);
}
}
public float vignetteBrightness = 1.0F;
protected int toolHighlightTimer;
protected ItemStack lastToolHighlight = ItemStack.EMPTY;
- protected final DebugScreenOverlay debugOverlay;
+ protected DebugScreenOverlay debugOverlay;
protected final SubtitleOverlay subtitleOverlay;
protected final SpectatorGui spectatorGui;
protected final PlayerTabOverlay tabList;
@@ -454,6 +_,8 @@
@@ -444,6 +_,8 @@
for(MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
MobEffect mobeffect = mobeffectinstance.getEffect();
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue;
if (mobeffectinstance.showIcon()) {
int i = this.screenWidth;
int j = 1;
@@ -482,6 +_,7 @@
}
}
for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
Holder<MobEffect> holder = mobeffectinstance.getEffect();
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue;
if (mobeffectinstance.showIcon()) {
int i = p_282812_.guiWidth();
int j = 1;
@@ -473,6 +_,7 @@
}
}
+ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue;
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(mobeffect);
int i1 = j;
float f1 = f;
@@ -602,16 +_,21 @@
}
+ if (renderer.renderGuiIcon(mobeffectinstance, this, p_282812_, i, j, 0, f)) continue;
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(holder);
int l1 = i;
int i1 = j;
@@ -635,6 +_,10 @@
}
private void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
public void renderSelectedItemName(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+
+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) {
this.minecraft.getProfiler().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color());
@@ -642,9 +_,10 @@
mutablecomponent.withStyle(ChatFormatting.ITALIC);
}
+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) {
this.minecraft.getProfiler().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
- MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color);
+ MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().getStyleModifier());
if (this.lastToolHighlight.hasCustomHoverName()) {
mutablecomponent.withStyle(ChatFormatting.ITALIC);
}
- int i = this.getFont().width(mutablecomponent);
+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent);
+ int i = this.getFont().width(highlightTip);
int j = (p_283501_.guiWidth() - i) / 2;
- int k = p_283501_.guiHeight() - 59;
+ int k = p_283501_.guiHeight() - Math.max(yShift, 59);
if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14;
}
@@ -657,6 +_,13 @@
if (l > 0) {
p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0));
p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24));
+ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME);
+ if (font == null) {
+ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24));
+ } else {
+ j = (p_283501_.guiWidth() - font.width(highlightTip)) / 2;
+ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24));
+ }
}
}
- int i = this.getFont().width(mutablecomponent);
+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent);
+ int i = this.getFont().width(highlightTip);
int j = (this.screenWidth - i) / 2;
- int k = this.screenHeight - 59;
+ int k = this.screenHeight - Math.max(yShift, 59);
if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14;
}
@@ -623,7 +_,13 @@
@@ -1155,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelected();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
- } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) {
+ } else if (this.lastToolHighlight.isEmpty() || !itemstack.is(this.lastToolHighlight.getItem()) || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) || !itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName()))) {
this.toolHighlightTimer = (int)(40.0 * this.minecraft.options.notificationDisplayTime().get());
} else if (this.toolHighlightTimer > 0) {
this.toolHighlightTimer--;
if (l > 0) {
p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(0));
- p_283501_.drawString(this.getFont(), mutablecomponent, j, k, 16777215 + (l << 24));
+ Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME);
+ if (font == null) {
+ p_283501_.drawString(this.getFont(), highlightTip, j, k, 16777215 + (l << 24));
+ } else {
+ j = (this.screenWidth - font.width(highlightTip)) / 2;
+ p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24));
+ }
}
}
@@ -1080,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelected();
if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0;
- } else if (!this.lastToolHighlight.isEmpty() && itemstack.is(this.lastToolHighlight.getItem()) && itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) {
+ } else if (!this.lastToolHighlight.isEmpty() && itemstack.getItem() == this.lastToolHighlight.getItem() && (itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) && itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName())))) {
if (this.toolHighlightTimer > 0) {
--this.toolHighlightTimer;
}
@@ -1,138 +1,147 @@
--- a/net/minecraft/client/gui/GuiGraphics.java
+++ b/net/minecraft/client/gui/GuiGraphics.java
@@ -56,7 +_,7 @@
@@ -55,7 +_,7 @@
import org.joml.Vector2ic;
@OnlyIn(Dist.CLIENT)
-public class GuiGraphics {
+public class GuiGraphics implements net.minecraftforge.client.extensions.IForgeGuiGraphics {
public static final float MAX_GUI_Z = 10000.0F;
public static final float MIN_GUI_Z = -10000.0F;
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
@@ -280,6 +_,11 @@
}
public static final float MAX_GUI_Z = 10000.0F;
public static final float MIN_GUI_Z = -10000.0F;
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
@@ -271,6 +_,11 @@
}
public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) {
+ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_);
+ }
public int drawString(Font p_283343_, @Nullable String p_281896_, int p_283569_, int p_283418_, int p_281560_, boolean p_282130_) {
+ return this.drawString(p_283343_, p_281896_, (float)p_283569_, (float)p_283418_, p_281560_, p_282130_);
+ }
+
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) {
if (p_281896_ == null) {
return 0;
} else {
@@ -306,6 +_,11 @@
}
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_283343_, @Nullable String p_281896_, float p_283569_, float p_283418_, int p_281560_, boolean p_282130_) {
if (p_281896_ == null) {
return 0;
} else {
@@ -285,6 +_,11 @@
}
public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) {
+ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_);
+ }
public int drawString(Font p_282636_, FormattedCharSequence p_281596_, int p_281586_, int p_282816_, int p_281743_, boolean p_282394_) {
+ return this.drawString(p_282636_, p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_);
+ }
+
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) {
int i = p_282636_.drawInBatch(
p_281596_,
(float)p_281586_,
@@ -872,6 +_,7 @@
CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item");
CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered");
crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_281675_.getItem()));
+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem())));
crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_281675_.getComponents()));
crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_281675_.hasFoil()));
throw new ReportedException(crashreport);
@@ -912,16 +_,26 @@
+ // Forge: Add float variant for x,y coordinates
+ public int drawString(Font p_282636_, FormattedCharSequence p_281596_, float p_281586_, float p_282816_, int p_281743_, boolean p_282394_) {
int i = p_282636_.drawInBatch(p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_, this.pose.last().pose(), this.bufferSource, Font.DisplayMode.NORMAL, 0, 15728880);
this.flushIfUnmanaged();
return i;
@@ -515,6 +_,7 @@
crashreportcategory.setDetail("Item Type", () -> {
return String.valueOf((Object)p_281675_.getItem());
});
+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(p_281675_.getItem())));
crashreportcategory.setDetail("Item Damage", () -> {
return String.valueOf(p_281675_.getDamageValue());
});
@@ -562,18 +_,26 @@
}
this.pose.popPose();
+ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_);
}
}
+
+ private ItemStack tooltipStack = ItemStack.EMPTY;
public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) {
+ this.tooltipStack = p_282781_;
this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderTooltip(Font font, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, ItemStack stack, int mouseX, int mouseY) {
+ this.tooltipStack = stack;
+ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_283128_, List<Component> p_282716_, Optional<TooltipComponent> p_281682_, int p_283678_, int p_281696_) {
- List<ClientTooltipComponent> list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Collectors.toList());
- p_281682_.ifPresent((p_282969_) -> {
- list.add(1, ClientTooltipComponent.create(p_282969_));
- });
+ List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_);
this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE);
}
@@ -582,7 +_,22 @@
}
public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_);
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_);
+ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE);
+ }
+
+ public void renderComponentTooltip(Font font, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderComponentTooltipFromElements(Font font, List<com.mojang.datafixers.util.Either<FormattedText, TooltipComponent>> elements, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponentsFromElements(stack, elements, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_282192_, List<? extends FormattedCharSequence> p_282297_, int p_281680_, int p_283325_) {
@@ -595,11 +_,13 @@
private void renderTooltipInternal(Font p_282675_, List<ClientTooltipComponent> p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) {
if (!p_282615_.isEmpty()) {
+ net.minecraftforge.client.event.RenderTooltipEvent.Pre preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_);
+ if (preEvent.isCanceled()) return;
int i = 0;
int j = p_282615_.size() == 1 ? -2 : 0;
for(ClientTooltipComponent clienttooltipcomponent : p_282615_) {
- int k = clienttooltipcomponent.getWidth(p_282675_);
+ int k = clienttooltipcomponent.getWidth(preEvent.getFont());
if (k > i) {
i = k;
}
@@ -609,20 +_,21 @@
this.pose.popPose();
+ net.minecraftforge.client.ItemDecoratorHandler.of(p_283349_).render(this, p_282005_, p_283349_, p_282641_, p_282146_);
}
}
+
+ private ItemStack tooltipStack = ItemStack.EMPTY;
int i2 = i;
int j2 = j;
- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2);
+ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2);
int l = vector2ic.x();
int i1 = vector2ic.y();
this.pose.pushPose();
int j1 = 400;
this.drawManaged(() -> {
- TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400);
+ net.minecraftforge.client.event.RenderTooltipEvent.Color colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd());
});
this.pose.translate(0.0F, 0.0F, 400.0F);
int k1 = i1;
public void renderTooltip(Font p_282308_, ItemStack p_282781_, int p_282687_, int p_282292_) {
+ this.tooltipStack = p_282781_;
this.renderTooltip(p_282308_, Screen.getTooltipFromItem(this.minecraft, p_282781_), p_282781_.getTooltipImage(), p_282687_, p_282292_);
+ this.tooltipStack = ItemStack.EMPTY;
+ }
+
+ public void renderTooltip(Font font, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, ItemStack stack, int mouseX, int mouseY) {
+ this.tooltipStack = stack;
+ this.renderTooltip(font, textComponents, tooltipComponent, mouseX, mouseY);
+ this.tooltipStack = ItemStack.EMPTY;
}
for(int l1 = 0; l1 < p_282615_.size(); ++l1) {
ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1);
- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource);
+ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource);
k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0);
}
public void renderTooltip(Font p_283128_, List<Component> p_282716_, Optional<TooltipComponent> p_281682_, int p_283678_, int p_281696_) {
- List<ClientTooltipComponent> list = p_282716_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList());
- p_281682_.ifPresent(p_325321_ -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(p_325321_)));
+ List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_282716_, p_281682_, p_283678_, guiWidth(), guiHeight(), p_283128_);
this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE);
}
@@ -630,7 +_,7 @@
@@ -930,7 +_,15 @@
}
public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
- this.renderTooltip(p_282739_, Lists.transform(p_281832_, Component::getVisualOrderText), p_282191_, p_282446_);
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_281832_, p_282191_, guiWidth(), guiHeight(), p_282739_);
+ this.renderTooltipInternal(p_282739_, components, p_282191_, p_282446_, DefaultTooltipPositioner.INSTANCE);
+ }
+
+ public void renderComponentTooltip(Font font, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE);
+ this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(Font p_282192_, List<? extends FormattedCharSequence> p_282297_, int p_281680_, int p_283325_) {
@@ -949,11 +_,13 @@
private void renderTooltipInternal(Font p_282675_, List<ClientTooltipComponent> p_282615_, int p_283230_, int p_283417_, ClientTooltipPositioner p_282442_) {
if (!p_282615_.isEmpty()) {
+ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, this, p_283230_, p_283417_, guiWidth(), guiHeight(), p_282615_, p_282675_, p_282442_);
+ if (preEvent.isCanceled()) return;
int i = 0;
int j = p_282615_.size() == 1 ? -2 : 0;
for (ClientTooltipComponent clienttooltipcomponent : p_282615_) {
- int k = clienttooltipcomponent.getWidth(p_282675_);
+ int k = clienttooltipcomponent.getWidth(preEvent.getFont());
if (k > i) {
i = k;
}
@@ -963,18 +_,21 @@
int i2 = i;
int j2 = j;
- Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), p_283230_, p_283417_, i2, j2);
+ Vector2ic vector2ic = p_282442_.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i2, j2);
int l = vector2ic.x();
int i1 = vector2ic.y();
this.pose.pushPose();
int j1 = 400;
- this.drawManaged(() -> TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400));
+ this.drawManaged(() -> {
+ var colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282615_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i2, j2, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd());
+ });
this.pose.translate(0.0F, 0.0F, 400.0F);
int k1 = i1;
for (int l1 = 0; l1 < p_282615_.size(); l1++) {
ClientTooltipComponent clienttooltipcomponent1 = p_282615_.get(l1);
- clienttooltipcomponent1.renderText(p_282675_, l, k1, this.pose.last().pose(), this.bufferSource);
+ clienttooltipcomponent1.renderText(preEvent.getFont(), l, k1, this.pose.last().pose(), this.bufferSource);
k1 += clienttooltipcomponent1.getHeight() + (l1 == 0 ? 2 : 0);
}
@@ -982,7 +_,7 @@
for (int k2 = 0; k2 < p_282615_.size(); k2++) {
ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2);
- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this);
+ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this);
k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0);
}
for(int k2 = 0; k2 < p_282615_.size(); ++k2) {
ClientTooltipComponent clienttooltipcomponent2 = p_282615_.get(k2);
- clienttooltipcomponent2.renderImage(p_282675_, l, k1, this);
+ clienttooltipcomponent2.renderImage(preEvent.getFont(), l, k1, this);
k1 += clienttooltipcomponent2.getHeight() + (k2 == 0 ? 2 : 0);
}
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/components/AbstractButton.java
+++ b/net/minecraft/client/gui/components/AbstractButton.java
@@ -32,7 +_,7 @@
RenderSystem.enableDepthTest();
p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
- int i = this.active ? 16777215 : 10526880;
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24);
}
@@ -29,7 +_,7 @@
RenderSystem.enableDepthTest();
p_281670_.blitSprite(SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
p_281670_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
- int i = this.active ? 16777215 : 10526880;
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24);
}
@@ -1,28 +1,22 @@
--- a/net/minecraft/client/gui/components/AbstractWidget.java
+++ b/net/minecraft/client/gui/components/AbstractWidget.java
@@ -255,6 +_,25 @@
this.focused = p_93693_;
}
@@ -233,6 +_,19 @@
this.focused = p_93693_;
}
+ // Forge start
+ public static final int UNSET_FG_COLOR = -1;
+ public static final int UNSET_FG_COLOR = -1;
+ protected int packedFGColor = UNSET_FG_COLOR;
+ public int getFGColor() {
+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor;
+ return this.active ? 16777215 : 10526880; // White : Light Grey
+ }
+ public void setFGColor(int color) {
+ this.packedFGColor = color;
+ }
+ public void clearFGColor() {
+ this.packedFGColor = UNSET_FG_COLOR;
+ }
+
+ protected int packedFGColor = UNSET_FG_COLOR;
+
+ public int getFGColor() {
+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor;
+ return this.active ? 16777215 : 10526880; // White : Light Grey
+ }
+
+ public void setFGColor(int color) {
+ this.packedFGColor = color;
+ }
+
+ public void clearFGColor() {
+ this.packedFGColor = UNSET_FG_COLOR;
+ }
+ // Forge end
+
@Override
public NarratableEntry.NarrationPriority narrationPriority() {
if (this.isFocused()) {
public NarratableEntry.NarrationPriority narrationPriority() {
if (this.isFocused()) {
return NarratableEntry.NarrationPriority.FOCUSED;
@@ -1,20 +1,20 @@
--- a/net/minecraft/client/gui/components/BossHealthOverlay.java
+++ b/net/minecraft/client/gui/components/BossHealthOverlay.java
@@ -63,13 +_,16 @@
@@ -36,13 +_,16 @@
for (LerpingBossEvent lerpingbossevent : this.events.values()) {
int k = i / 2 - 91;
+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight);
+ if (!event.isCanceled()) {
this.drawBar(p_283175_, k, j, lerpingbossevent);
Component component = lerpingbossevent.getName();
int l = this.minecraft.font.width(component);
int i1 = i / 2 - l / 2;
int j1 = j - 9;
p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215);
- j += 10 + 9;
+ }
+ j += event.getIncrement();
if (j >= p_283175_.guiHeight() / 3) {
break;
}
for(LerpingBossEvent lerpingbossevent : this.events.values()) {
int k = i / 2 - 91;
+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(p_283175_, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight);
+ if (!event.isCanceled()) {
this.drawBar(p_283175_, k, j, lerpingbossevent);
Component component = lerpingbossevent.getName();
int l = this.minecraft.font.width(component);
int i1 = i / 2 - l / 2;
int j1 = j - 9;
p_283175_.drawString(this.minecraft.font, component, i1, j1, 16777215);
- j += 10 + 9;
+ }
+ j += event.getIncrement();
if (j >= p_283175_.guiHeight() / 3) {
break;
}
@@ -1,31 +1,29 @@
--- a/net/minecraft/client/gui/components/Button.java
+++ b/net/minecraft/client/gui/components/Button.java
@@ -31,6 +_,12 @@
this.createNarration = p_259552_;
}
@@ -30,6 +_,11 @@
this.createNarration = p_259552_;
}
+ // Forge (GH-9238)
+ protected Button(Builder builder) {
+ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration);
+ this.setTooltip(builder.tooltip);
+ }
+ protected Button(Builder builder) {
+ this(builder.x, builder.y, builder.width, builder.height, builder.message, builder.onPress, builder.createNarration);
+ setTooltip(builder.tooltip); // Forge: Make use of the Builder tooltip
+ }
+
@Override
public void onPress() {
this.onPress.onPress(this);
@@ -95,9 +_,12 @@
}
public void onPress() {
this.onPress.onPress(this);
}
@@ -93,9 +_,11 @@
}
public Button build() {
- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration);
- button.setTooltip(this.tooltip);
- return button;
+ return build(Button::new);
+ }
public Button build() {
- Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration);
- button.setTooltip(this.tooltip);
- return button;
+ return build(Button::new);
+ }
+
+ // Forge (GH-9238)
+ public Button build(java.util.function.Function<Builder, Button> builder) {
+ return builder.apply(this);
}
}
+ public Button build(java.util.function.Function<Builder, Button> builder) {
+ return builder.apply(this);
}
}
@@ -1,99 +1,92 @@
--- a/net/minecraft/client/gui/components/DebugScreenOverlay.java
+++ b/net/minecraft/client/gui/components/DebugScreenOverlay.java
@@ -101,9 +_,9 @@
@Nullable
private CompletableFuture<LevelChunk> serverChunk;
private boolean renderDebug;
- private boolean renderProfilerChart;
- private boolean renderFpsCharts;
- private boolean renderNetworkCharts;
+ protected boolean renderProfilerChart;
+ protected boolean renderFpsCharts;
+ protected boolean renderNetworkCharts;
private final LocalSampleLogger frameTimeLogger = new LocalSampleLogger(1);
private final LocalSampleLogger tickTimeLogger = new LocalSampleLogger(TpsDebugDimensions.values().length);
private final LocalSampleLogger pingLogger = new LocalSampleLogger(1);
@@ -129,14 +_,18 @@
this.clientChunk = null;
}
@@ -95,9 +_,9 @@
@Nullable
private CompletableFuture<LevelChunk> serverChunk;
private boolean renderDebug;
- private boolean renderProfilerChart;
- private boolean renderFpsCharts;
- private boolean renderNetworkCharts;
+ protected boolean renderProfilerChart;
+ protected boolean renderFpsCharts;
+ protected boolean renderNetworkCharts;
private final SampleLogger frameTimeLogger = new SampleLogger();
private final SampleLogger tickTimeLogger = new SampleLogger();
private final SampleLogger pingLogger = new SampleLogger();
@@ -124,14 +_,18 @@
this.clientChunk = null;
}
- public void render(GuiGraphics p_281427_) {
- this.minecraft.getProfiler().push("debug");
+ protected void update() {
Entity entity = this.minecraft.getCameraEntity();
this.block = entity.pick(20.0, 0.0F, false);
this.liquid = entity.pick(20.0, 0.0F, true);
- p_281427_.drawManaged(() -> {
+ }
- public void render(GuiGraphics p_281427_) {
- this.minecraft.getProfiler().push("debug");
+ protected void update() {
Entity entity = this.minecraft.getCameraEntity();
this.block = entity.pick(20.0D, 0.0F, false);
this.liquid = entity.pick(20.0D, 0.0F, true);
- p_281427_.drawManaged(() -> {
- this.drawGameInformation(p_281427_);
- this.drawSystemInformation(p_281427_);
+ }
+
+ protected void drawText(GuiGraphics p_281427_) {
this.drawGameInformation(p_281427_);
this.drawSystemInformation(p_281427_);
+ }
+ protected void drawText(GuiGraphics p_281427_) {
+ this.drawGameInformation(p_281427_);
+ this.drawSystemInformation(p_281427_);
+ }
+
+ protected void drawFPSCharts(GuiGraphics p_281427_) {
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
int j = i / 2;
@@ -146,7 +_,9 @@
this.tpsChart.drawChart(p_281427_, i - k, k);
}
+ protected void drawFPSCharts(GuiGraphics p_281427_) {
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
int j = i / 2;
@@ -141,7 +_,9 @@
this.tpsChart.drawChart(p_281427_, i - k, k);
}
+ }
}
+ }
+ protected void drawNetworkCharts(GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -157,12 +_,21 @@
int j1 = this.pingChart.getWidth(i1);
this.pingChart.drawChart(p_281427_, l - j1, j1);
}
+ }
+ protected void drawNetworkCharts(GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -152,17 +_,32 @@
int j1 = this.pingChart.getWidth(i1);
this.pingChart.drawChart(p_281427_, l - j1, j1);
}
+ }
+
+ public void render(GuiGraphics p_281427_) {
+ this.minecraft.getProfiler().push("debug");
+ this.update();
+ p_281427_.drawManaged(() -> {
+ this.drawText(p_281427_);
+ this.drawFPSCharts(p_281427_);
+ this.drawNetworkCharts(p_281427_);
});
this.minecraft.getProfiler().pop();
}
+ public void render(GuiGraphics p_281427_) {
+ this.minecraft.getProfiler().push("debug");
+ this.update();
+ p_281427_.drawManaged(() -> {
+ this.drawText(p_281427_);
+ this.drawFPSCharts(p_281427_);
+ this.drawNetworkCharts(p_281427_);
- protected void drawGameInformation(GuiGraphics p_281525_) {
- List<String> list = this.getGameInformation();
+ protected List<String> getOverlayHelp() {
+ List<String> list = Lists.newArrayList();
list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add(
@@ -176,11 +_,18 @@
+ (this.renderNetworkCharts ? " visible" : " hidden")
);
list.add("For help: press F3 + Q");
- this.renderLines(p_281525_, list, true);
+ return list;
+ }
});
this.minecraft.getProfiler().pop();
}
- protected void drawGameInformation(GuiGraphics p_281525_) {
- List<String> list = this.getGameInformation();
+ protected List<String> getOverlayHelp() {
+ List<String> list = Lists.newArrayList();
list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add("Debug charts: [F3+1] Profiler " + (this.renderProfilerChart ? "visible" : "hidden") + "; [F3+2] " + (flag ? "FPS + TPS " : "FPS ") + (this.renderFpsCharts ? "visible" : "hidden") + "; [F3+3] " + (!this.minecraft.isLocalServer() ? "Bandwidth + Ping" : "Ping") + (this.renderNetworkCharts ? " visible" : " hidden"));
list.add("For help: press F3 + Q");
+ return list;
+ }
+
+ protected void drawGameInformation(GuiGraphics p_281525_) {
+ List<String> list = this.getGameInformation();
+ list.addAll(this.getOverlayHelp());
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281525_, minecraft.getWindow(), minecraft.getFrameTime(), list, true);
+ this.renderLines(p_281525_, list, true);
}
this.renderLines(p_281525_, list, true);
}
protected void drawSystemInformation(GuiGraphics p_281261_) {
List<String> list = this.getSystemInformation();
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281261_, minecraft.getWindow(), minecraft.getFrameTime(), list, false);
this.renderLines(p_281261_, list, false);
}
@@ -451,6 +_,7 @@
list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf((Object)BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
@@ -529,6 +_,7 @@
list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
return list;
return list;
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/components/toasts/ToastComponent.java
+++ b/net/minecraft/client/gui/components/toasts/ToastComponent.java
@@ -97,6 +_,7 @@
}
@@ -101,6 +_,7 @@
}
public void addToast(Toast p_94923_) {
+ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return;
this.queued.add(p_94923_);
}
public void addToast(Toast p_94923_) {
+ if (net.minecraftforge.client.ForgeHooksClient.onToastAdd(p_94923_)) return;
this.queued.add(p_94923_);
}
@@ -1,10 +1,11 @@
--- a/net/minecraft/client/gui/screens/ChatScreen.java
+++ b/net/minecraft/client/gui/screens/ChatScreen.java
@@ -89,6 +_,7 @@
return true;
} else if (p_95591_ == 257 || p_95591_ == 335) {
this.handleChatInput(this.input.getValue(), true);
+ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened.
this.minecraft.setScreen(null);
return true;
} else if (p_95591_ == 265) {
@@ -225,7 +_,7 @@
this.minecraft.player.connection.sendChat(p_242400_);
}
- return true;
+ return minecraft.screen == this; // FORGE: Prevent closing the screen if another screen has been opened.
}
}
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/screens/ConnectScreen.java
+++ b/net/minecraft/client/gui/screens/ConnectScreen.java
@@ -102,6 +_,8 @@
}
@@ -85,6 +_,8 @@
}
if (optional.isEmpty()) {
+ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost());
+ net.minecraftforge.network.DualStackUtils.logInitialPreferences();
p_251955_.execute(
() -> p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE))
);
if (optional.isEmpty()) {
+ ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.getHost());
+ net.minecraftforge.network.DualStackUtils.logInitialPreferences();
p_251955_.execute(() -> {
p_251955_.setScreen(new DisconnectedScreen(ConnectScreen.this.parent, ConnectScreen.this.connectFailedTitle, ConnectScreen.UNKNOWN_HOST_MESSAGE));
});
@@ -1,18 +1,18 @@
--- a/net/minecraft/client/gui/screens/LoadingOverlay.java
+++ b/net/minecraft/client/gui/screens/LoadingOverlay.java
@@ -131,6 +_,7 @@
}
@@ -132,6 +_,7 @@
}
if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
+ this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback
try {
this.reload.checkExceptions();
this.onFinish.accept(Optional.empty());
@@ -138,7 +_,6 @@
this.onFinish.accept(Optional.of(throwable));
}
if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
+ this.fadeOutStart = Util.getMillis(); // Moved up to guard against inf loops caused by callback
try {
this.reload.checkExceptions();
this.onFinish.accept(Optional.empty());
@@ -139,7 +_,6 @@
this.onFinish.accept(Optional.of(throwable));
}
- this.fadeOutStart = Util.getMillis();
if (this.minecraft.screen != null) {
this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight());
}
- this.fadeOutStart = Util.getMillis();
if (this.minecraft.screen != null) {
this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight());
}
@@ -1,20 +1,25 @@
--- a/net/minecraft/client/gui/screens/MenuScreens.java
+++ b/net/minecraft/client/gui/screens/MenuScreens.java
@@ -41,11 +_,16 @@
private static final Map<MenuType<?>, MenuScreens.ScreenConstructor<?, ?>> SCREENS = Maps.newHashMap();
@@ -41,6 +_,10 @@
private static final Map<MenuType<?>, MenuScreens.ScreenConstructor<?, ?>> SCREENS = Maps.newHashMap();
public static <T extends AbstractContainerMenu> void create(MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
+ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_));
+ }
public static <T extends AbstractContainerMenu> void create(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
+ getScreenFactory(p_96202_, p_96203_, p_96204_, p_96205_).ifPresent(f -> f.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_));
+ }
+
+ public static <T extends AbstractContainerMenu> java.util.Optional<ScreenConstructor<T, ?>> getScreenFactory(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
MenuScreens.ScreenConstructor<T, ?> screenconstructor = getConstructor(p_96202_);
if (screenconstructor == null) {
LOGGER.warn("Failed to create screen for menu type: {}", BuiltInRegistries.MENU.getKey(p_96202_));
+ return java.util.Optional.empty();
} else {
+ public static <T extends AbstractContainerMenu> java.util.Optional<ScreenConstructor<T, ?>> getScreenFactory(@Nullable MenuType<T> p_96202_, Minecraft p_96203_, int p_96204_, Component p_96205_) {
if (p_96202_ == null) {
LOGGER.warn("Trying to open invalid screen with name: {}", (Object)p_96205_.getString());
} else {
@@ -48,9 +_,10 @@
if (screenconstructor == null) {
LOGGER.warn("Failed to create screen for menu type: {}", (Object)BuiltInRegistries.MENU.getKey(p_96202_));
} else {
- screenconstructor.fromPacket(p_96205_, p_96202_, p_96203_, p_96204_);
+ return java.util.Optional.of(screenconstructor);
}
}
}
}
+ return java.util.Optional.empty();
}
@Nullable
@@ -0,0 +1,17 @@
--- a/net/minecraft/client/gui/screens/OptionsScreen.java
+++ b/net/minecraft/client/gui/screens/OptionsScreen.java
@@ -150,6 +_,14 @@
p_283520_.drawCenteredString(this.font, this.title, this.width / 2, 15, 16777215);
}
+ @Override
+ public void onClose() {
+ // We need to consider 2 potential parent screens here:
+ // 1. From the main menu, in which case display the main menu
+ // 2. From the pause menu, in which case exit back to game
+ this.minecraft.setScreen(this.lastScreen instanceof PauseScreen ? null : this.lastScreen);
+ }
+
private Button openScreenButton(Component p_261565_, Supplier<Screen> p_262119_) {
return Button.builder(p_261565_, (p_280808_) -> {
this.minecraft.setScreen(p_262119_.get());
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -86,6 +_,7 @@
} else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this)));
}
+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2);
@@ -87,6 +_,7 @@
} else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, SocialInteractionsScreen::new));
}
+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2);
Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT;
this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, p_280815_ -> {
Component component = this.minecraft.isLocalServer() ? RETURN_TO_MENU : CommonComponents.GUI_DISCONNECT;
this.disconnectButton = gridlayout$rowhelper.addChild(Button.builder(component, (p_280815_) -> {
@@ -1,61 +1,74 @@
--- a/net/minecraft/client/gui/screens/Screen.java
+++ b/net/minecraft/client/gui/screens/Screen.java
@@ -204,7 +_,7 @@
}
@@ -207,7 +_,7 @@
}
public void onClose() {
- this.minecraft.setScreen(null);
+ this.minecraft.popGuiLayer();
}
public void onClose() {
- this.minecraft.setScreen((Screen)null);
+ this.minecraft.popGuiLayer();
}
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -320,8 +_,10 @@
this.width = p_96608_;
this.height = p_96609_;
if (!this.initialized) {
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget)))
this.init();
this.setInitialFocus();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
} else {
this.repositionElements();
}
@@ -334,8 +_,10 @@
protected void rebuildWidgets() {
this.clearWidgets();
this.clearFocus();
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget)))
this.init();
this.setInitialFocus();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
}
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -319,7 +_,10 @@
this.width = p_96608_;
this.height = p_96609_;
if (!this.initialized) {
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) {
this.init();
+ }
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
} else {
this.repositionElements();
}
@@ -332,7 +_,10 @@
protected void rebuildWidgets() {
this.clearWidgets();
this.clearFocus();
+ if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Pre(this, this.children, this::addEventWidget, this::removeWidget))) {
this.init();
+ }
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.Init.Post(this, this.children, this::addEventWidget, this::removeWidget));
}
@Override
@@ -362,6 +_,7 @@
public List<? extends GuiEventListener> children() {
@@ -354,6 +_,7 @@
public void renderBackground(GuiGraphics p_283688_, int p_299421_, int p_298679_, float p_297268_) {
if (this.minecraft.level != null) {
this.renderTransparentBackground(p_283688_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_283688_));
} else {
this.renderDirtBackground(p_283688_);
}
@@ -369,6 +_,7 @@
int i = 32;
p_282281_.blit(BACKGROUND_LOCATION, 0, 0, 0, 0.0F, 0.0F, this.width, this.height, 32, 32);
p_282281_.setColor(1.0F, 1.0F, 1.0F, 1.0F);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundRendered(this, p_282281_));
}
this.renderBlurredBackground(p_297268_);
this.renderMenuBackground(p_283688_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_);
}
public boolean isPauseScreen() {
@@ -462,6 +_,10 @@
public void onFilesDrop(List<Path> p_96591_) {
}
protected void renderBlurredBackground(float p_336041_) {
@@ -492,6 +_,19 @@
}
public void onFilesDrop(List<Path> p_96591_) {
+ }
+ public Minecraft getMinecraft() {
+ return this.minecraft;
+ }
+
+ @Nullable
+ public Minecraft getMinecraft() {
+ return minecraft;
+ }
private void scheduleNarration(long p_169381_, boolean p_169382_) {
this.nextNarrationTime = Util.getMillis() + p_169381_;
if (p_169382_) {
@@ -632,5 +_,13 @@
this.index = p_169425_;
this.priority = p_169426_;
}
+ }
+
+ private void addEventWidget(GuiEventListener guiEventListener) {
+ if (guiEventListener instanceof Renderable r)
+ this.renderables.add(r);
+ if (guiEventListener instanceof NarratableEntry ne)
+ this.narratables.add(ne);
+ this.children.add(guiEventListener);
}
private void scheduleNarration(long p_169381_, boolean p_169382_) {
+ private void addEventWidget(GuiEventListener b) {
+ if (b instanceof Renderable r)
+ this.renderables.add(r);
+ if (b instanceof NarratableEntry ne)
+ this.narratables.add(ne);
+ children.add(b);
}
}
@@ -1,64 +1,67 @@
--- a/net/minecraft/client/gui/screens/TitleScreen.java
+++ b/net/minecraft/client/gui/screens/TitleScreen.java
@@ -61,6 +_,7 @@
@Nullable
private TitleScreen.WarningLabel warningLabel;
private final LogoRenderer logoRenderer;
+ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification;
@@ -63,6 +_,7 @@
@Nullable
private TitleScreen.WarningLabel warningLabel;
private final LogoRenderer logoRenderer;
+ private net.minecraftforge.client.gui.TitleScreenModUpdateIndicator modUpdateNotification;
public TitleScreen() {
this(false);
@@ -116,11 +_,15 @@
int j = this.width - i - 2;
int k = 24;
int l = this.height / 4 + 48;
+ Button modButton = null;
if (this.minecraft.isDemo()) {
this.createDemoMenuOptions(l, 24);
} else {
this.createNormalMenuOptions(l, 24);
+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this)))
+ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build());
}
+ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton);
public TitleScreen() {
this(false);
@@ -113,11 +_,15 @@
int j = this.width - i - 2;
int k = 24;
int l = this.height / 4 + 48;
+ Button modButton = null;
if (this.minecraft.isDemo()) {
this.createDemoMenuOptions(l, 24);
} else {
this.createNormalMenuOptions(l, 24);
+ modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this)))
+ .pos(this.width / 2 - 100, l + 24 * 2).size(98, 20).build());
}
+ modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton);
SpriteIconButton spriteiconbutton = this.addRenderableWidget(
CommonButtons.language(
@@ -171,7 +_,7 @@
}).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build()).active = flag;
this.addRenderableWidget(
Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this)))
- .bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20)
+ .bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20)
.tooltip(tooltip)
.build()
)
@@ -281,6 +_,7 @@
this.warningLabel.render(p_282860_, i);
}
SpriteIconButton spriteiconbutton = this.addRenderableWidget(CommonButtons.language(20, (p_280830_) -> {
this.minecraft.setScreen(new LanguageSelectScreen(this, this.minecraft.options, this.minecraft.getLanguageManager()));
@@ -163,7 +_,7 @@
}).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 1, 200, 20).tooltip(tooltip).build())).active = flag;
(this.addRenderableWidget(Button.builder(Component.translatable("menu.online"), (p_210872_) -> {
this.realmsButtonClicked();
- }).bounds(this.width / 2 - 100, p_96764_ + p_96765_ * 2, 200, 20).tooltip(tooltip).build())).active = flag;
+ }).bounds(this.width / 2 + 2, p_96764_ + p_96765_ * 2, 98, 20).tooltip(tooltip).build())).active = flag;
}
+ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i);
if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) {
this.splash.render(p_282860_, this.width, this.font, i);
}
@@ -296,11 +_,19 @@
s = s + I18n.get("menu.modded");
}
@Nullable
@@ -243,6 +_,7 @@
this.warningLabel.render(p_282860_, i);
}
- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i);
+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) ->
+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i)
+ );
+ net.minecraftforge.client.ForgeHooksClient.renderMainMenu(this, p_282860_, this.font, this.width, this.height, i);
if (this.splash != null && !this.minecraft.options.hideSplashTexts().get()) {
this.splash.render(p_282860_, this.width, this.font, i);
}
@@ -258,7 +_,14 @@
s = s + I18n.get("menu.modded");
}
- p_282860_.drawString(this.font, s, 2, this.height - 10, 16777215 | i);
+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brdline, brd) ->
+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), 16777215 | i)
+ );
+
+ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) ->
+ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i)
+ );
+ net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brdline, brd) ->
+ p_282860_.drawString(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), 16777215 | i)
+ );
+
if (this.realmsNotificationsEnabled() && f >= 1.0F) {
RenderSystem.enableDepthTest();
this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
+ if (f >= 1.0f) this.modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
}
for(GuiEventListener guieventlistener : this.children()) {
if (guieventlistener instanceof AbstractWidget) {
@@ -271,6 +_,7 @@
RenderSystem.enableDepthTest();
this.realmsNotificationsScreen.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
+ if (f1 >= 1.0f) modUpdateNotification.render(p_282860_, p_281753_, p_283539_, p_282628_);
}
}
@@ -1,37 +1,37 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
@@ -37,6 +_,7 @@
private int maxY = Integer.MIN_VALUE;
private float fade;
private boolean centered;
+ private int page;
private int maxY = Integer.MIN_VALUE;
private float fade;
private boolean centered;
+ private int page;
public AdvancementTab(
Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_
@@ -53,6 +_,15 @@
this.addWidget(this.root, p_297568_.holder());
}
public AdvancementTab(Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_) {
this.minecraft = p_97145_;
@@ -51,6 +_,15 @@
this.addWidget(this.root, p_297568_.holder());
}
+ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) {
+ this(mc, screen, type, index, adv, info);
+ this.page = page;
+ }
+ public AdvancementTab(Minecraft mc, AdvancementsScreen screen, AdvancementTabType type, int index, int page, AdvancementNode adv, DisplayInfo info) {
+ this(mc, screen, type, index, adv, info);
+ this.page = page;
+ }
+
+ public int getPage() {
+ return this.page;
+ }
+ public int getPage() {
+ return page;
+ }
+
public AdvancementTabType getType() {
return this.type;
}
@@ -146,8 +_,8 @@
return null;
} else {
for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) {
- if (p_97173_ < advancementtabtype.getMax()) {
- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get());
+ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) {
+ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get());
}
public AdvancementTabType getType() {
return this.type;
}
@@ -145,8 +_,8 @@
return null;
} else {
for(AdvancementTabType advancementtabtype : AdvancementTabType.values()) {
- if (p_97173_ < advancementtabtype.getMax()) {
- return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_, p_299876_, optional.get());
+ if ((p_97173_ % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) {
+ return new AdvancementTab(p_97171_, p_97172_, advancementtabtype, p_97173_ % AdvancementTabType.MAX_TABS, p_97173_ / AdvancementTabType.MAX_TABS, p_299876_, optional.get());
}
p_97173_ -= advancementtabtype.getMax();
p_97173_ -= advancementtabtype.getMax();
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementTabType.java
@@ -69,6 +_,7 @@
5
);
@@ -13,6 +_,7 @@
LEFT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top_selected"), new ResourceLocation("advancements/tab_left_middle_selected"), new ResourceLocation("advancements/tab_left_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_left_top"), new ResourceLocation("advancements/tab_left_middle"), new ResourceLocation("advancements/tab_left_bottom")), 32, 28, 5),
RIGHT(new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top_selected"), new ResourceLocation("advancements/tab_right_middle_selected"), new ResourceLocation("advancements/tab_right_bottom_selected")), new AdvancementTabType.Sprites(new ResourceLocation("advancements/tab_right_top"), new ResourceLocation("advancements/tab_right_middle"), new ResourceLocation("advancements/tab_right_bottom")), 32, 28, 5);
+ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum();
private final AdvancementTabType.Sprites selectedSprites;
private final AdvancementTabType.Sprites unselectedSprites;
private final int width;
+ public static final int MAX_TABS = java.util.Arrays.stream(values()).mapToInt(e -> e.max).sum();
private final AdvancementTabType.Sprites selectedSprites;
private final AdvancementTabType.Sprites unselectedSprites;
private final int width;
@@ -1,60 +1,74 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
@@ -49,6 +_,7 @@
@Nullable
private AdvancementTab selectedTab;
private boolean isScrolling;
+ private static int tabPage, maxPages;
@@ -42,6 +_,7 @@
@Nullable
private AdvancementTab selectedTab;
private boolean isScrolling;
+ private static int tabPage, maxPages;
public AdvancementsScreen(ClientAdvancements p_97340_) {
this(p_97340_, null);
@@ -62,6 +_,19 @@
public AdvancementsScreen(ClientAdvancements p_97340_) {
super(GameNarrator.NO_TITLE);
@@ -58,7 +_,15 @@
} else {
this.advancements.setSelectedTab(this.selectedTab == null ? null : this.selectedTab.getRootNode().holder(), true);
}
-
+ if (this.tabs.size() > AdvancementTabType.MAX_TABS) {
+ int guiLeft = (this.width - 252) / 2;
+ int guiTop = (this.height - 140) / 2;
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> tabPage = Math.max(tabPage - 1, 0 ))
+ .pos(guiLeft, guiTop - 50).size(20, 20).build());
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> tabPage = Math.min(tabPage + 1, maxPages))
+ .pos(guiLeft + WINDOW_WIDTH - 20, guiTop - 50).size(20, 20).build());
+ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS;
+ }
}
@Override
protected void init() {
+ if (this.tabs.size() > AdvancementTabType.MAX_TABS) {
+ maxPages = this.tabs.size() / AdvancementTabType.MAX_TABS;
+ var pageLayout = new net.minecraft.client.gui.layouts.GridLayout();
+ var text = new net.minecraft.client.gui.components.StringWidget(Component.literal(String.format("%d / %d", maxPages + 1, maxPages + 1)), this.font);
+ var update = (java.util.function.Consumer<Boolean>)back -> {
+ tabPage = back ? Math.max(tabPage - 1, 0) : Math.min(tabPage + 1, maxPages);
+ text.setMessage(Component.literal(String.format("%d / %d", 1, maxPages + 1)));
+ };
+ pageLayout.addChild(Button.builder(Component.literal("<"), b -> update.accept(true)).size(20, 20).build(), 0, 0, pageLayout.defaultCellSetting().alignHorizontallyLeft());
+ pageLayout.addChild(text, 0, 1, pageLayout.defaultCellSetting().alignHorizontallyCenter());
+ pageLayout.addChild(Button.builder(Component.literal(">"), b -> update.accept(false)).size(20, 20).build(), 0, 2, pageLayout.defaultCellSetting().alignHorizontallyRight());
+ this.layout.addToHeader(pageLayout);
+ }
this.layout.addTitleHeader(TITLE, this.font);
this.tabs.clear();
this.selectedTab = null;
@@ -106,7 +_,7 @@
int j = (this.height - 140) / 2;
public void removed() {
@@ -76,7 +_,7 @@
int j = (this.height - 140) / 2;
for (AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break;
}
@@ -180,10 +_,12 @@
p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140);
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab);
for(AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break;
}
@@ -100,9 +_,15 @@
int i = (this.width - 252) / 2;
int j = (this.height - 140) / 2;
this.renderBackground(p_282589_, p_282255_, p_283354_, p_283123_);
+ if (maxPages != 0) {
+ net.minecraft.network.chat.Component page = Component.literal(String.format("%d / %d", tabPage + 1, maxPages + 1));
+ int width = this.font.width(page);
+ p_282589_.drawString(this.font, page.getVisualOrderText(), i + (252 / 2) - (width / 2), j - 44, -1);
+ }
this.renderInside(p_282589_, p_282255_, p_283354_, i, j);
this.renderWindow(p_282589_, i, j);
this.renderTooltips(p_282589_, p_282255_, p_283354_, i, j);
+ this.renderables.forEach(r -> r.render(p_282589_, p_282255_, p_283354_, p_283123_));
}
for (AdvancementTab advancementtab1 : this.tabs.values()) {
+ if (advancementtab1.getPage() == tabPage)
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
public boolean mouseDragged(double p_97347_, double p_97348_, int p_97349_, double p_97350_, double p_97351_) {
@@ -146,10 +_,12 @@
p_283395_.blit(WINDOW_LOCATION, p_281890_, p_282532_, 0, 0, 252, 140);
if (this.tabs.size() > 1) {
for(AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab);
}
for(AdvancementTab advancementtab1 : this.tabs.values()) {
+ if (advancementtab1.getPage() == tabPage)
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
}
}
@@ -169,7 +_,7 @@
if (this.tabs.size() > 1) {
for(AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_);
}
}
@@ -203,6 +_,7 @@
if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage)
if (advancementtab.isMouseOver(p_281519_, p_283371_, (double)p_283556_, (double)p_282458_)) {
p_282784_.renderTooltip(this.font, advancementtab.getTitle(), p_283556_, p_282458_);
}
}
@@ -1,43 +1,44 @@
--- a/net/minecraft/client/gui/screens/controls/KeyBindsList.java
+++ b/net/minecraft/client/gui/screens/controls/KeyBindsList.java
@@ -69,6 +_,11 @@
return 340;
}
@@ -64,7 +_,7 @@
}
+ @Override
+ protected int getScrollbarPosition() {
+ return super.getScrollbarPosition() + 20;
+ }
+
@OnlyIn(Dist.CLIENT)
public class CategoryEntry extends KeyBindsList.Entry {
final Component name;
@@ -153,9 +_,10 @@
this.name = p_193917_;
this.changeButton = Button.builder(p_193917_, p_269618_ -> {
KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_;
+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN);
KeyBindsList.this.resetMappingAndUpdateButtons();
})
- .bounds(0, 0, 75, 20)
+ .bounds(0, 0, 75 + 20 /* Forge: Add space */, 20)
.createNarration(
p_253311_ -> p_193916_.isUnbound()
? Component.translatable("narrator.controls.unbound", p_193917_)
@@ -163,6 +_,7 @@
)
.build();
this.resetButton = Button.builder(RESET_BUTTON_TITLE, p_325376_ -> {
+ this.key.setToDefault();
KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey());
KeyBindsList.this.resetMappingAndUpdateButtons();
}).bounds(0, 0, 50, 20).createNarration(p_253313_ -> Component.translatable("narrator.controls.reset", p_193917_)).build();
@@ -215,7 +_,7 @@
MutableComponent mutablecomponent = Component.empty();
if (!this.key.isUnbound()) {
for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) {
- if (keymapping != this.key && this.key.same(keymapping)) {
+ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G
if (this.hasCollision) {
mutablecomponent.append(", ");
}
protected int getScrollbarPosition() {
- return super.getScrollbarPosition() + 15;
+ return super.getScrollbarPosition() + 15 + 20;
}
public int getRowWidth() {
@@ -128,11 +_,13 @@
this.name = p_193917_;
this.changeButton = Button.builder(p_193917_, (p_269618_) -> {
KeyBindsList.this.keyBindsScreen.selectedKey = p_193916_;
+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.UNKNOWN);
KeyBindsList.this.resetMappingAndUpdateButtons();
- }).bounds(0, 0, 75, 20).createNarration((p_253311_) -> {
+ }).bounds(0, 0, 75 + 20 /* Forge: Add space */, 20).createNarration((p_253311_) -> {
return p_193916_.isUnbound() ? Component.translatable("narrator.controls.unbound", p_193917_) : Component.translatable("narrator.controls.bound", p_193917_, p_253311_.get());
}).build();
this.resetButton = Button.builder(Component.translatable("controls.reset"), (p_269616_) -> {
+ this.key.setToDefault();
KeyBindsList.this.minecraft.options.setKey(p_193916_, p_193916_.getDefaultKey());
KeyBindsList.this.resetMappingAndUpdateButtons();
}).bounds(0, 0, 50, 20).createNarration((p_253313_) -> {
@@ -144,7 +_,7 @@
public void render(GuiGraphics p_281805_, int p_281298_, int p_282357_, int p_281373_, int p_283433_, int p_281932_, int p_282224_, int p_282053_, boolean p_282605_, float p_281432_) {
int k = p_281373_ + 90 - KeyBindsList.this.maxNameWidth;
p_281805_.drawString(KeyBindsList.this.minecraft.font, this.name, k, p_282357_ + p_281932_ / 2 - 9 / 2, 16777215, false);
- this.resetButton.setX(p_281373_ + 190);
+ this.resetButton.setX(p_281373_ + 190 + 20);
this.resetButton.setY(p_282357_);
this.resetButton.render(p_281805_, p_282224_, p_282053_, p_281432_);
this.changeButton.setX(p_281373_ + 105);
@@ -173,7 +_,7 @@
MutableComponent mutablecomponent = Component.empty();
if (!this.key.isUnbound()) {
for(KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) {
- if (keymapping != this.key && this.key.same(keymapping)) {
+ if ((keymapping != this.key && this.key.same(keymapping)) || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G
if (this.hasCollision) {
mutablecomponent.append(", ");
}
@@ -1,46 +1,46 @@
--- a/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java
+++ b/net/minecraft/client/gui/screens/controls/KeyBindsScreen.java
@@ -33,7 +_,7 @@
this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft));
this.resetButton = Button.builder(Component.translatable("controls.resetAll"), p_269619_ -> {
for (KeyMapping keymapping : this.options.keyMappings) {
- keymapping.setKey(keymapping.getDefaultKey());
+ keymapping.setToDefault();
}
@@ -30,7 +_,7 @@
this.keyBindsList = this.addRenderableWidget(new KeyBindsList(this, this.minecraft));
this.resetButton = this.addRenderableWidget(Button.builder(Component.translatable("controls.resetAll"), (p_269619_) -> {
for(KeyMapping keymapping : this.options.keyMappings) {
- keymapping.setKey(keymapping.getDefaultKey());
+ keymapping.setToDefault();
}
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -70,11 +_,14 @@
public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) {
if (this.selectedKey != null) {
if (p_193987_ == 256) {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN);
this.options.setKey(this.selectedKey, InputConstants.UNKNOWN);
} else {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_));
this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_));
}
+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey()))
this.selectedKey = null;
this.lastKeySelection = Util.getMillis();
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -82,6 +_,19 @@
} else {
return super.keyPressed(p_193987_, p_193988_, p_193989_);
}
+ }
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -54,11 +_,13 @@
public boolean keyPressed(int p_193987_, int p_193988_, int p_193989_) {
if (this.selectedKey != null) {
if (p_193987_ == 256) {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.UNKNOWN);
this.options.setKey(this.selectedKey, InputConstants.UNKNOWN);
} else {
+ this.selectedKey.setKeyModifierAndCode(null, InputConstants.getKey(p_193987_, p_193988_));
this.options.setKey(this.selectedKey, InputConstants.getKey(p_193987_, p_193988_));
}
-
+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.selectedKey.getKey()))
this.selectedKey = null;
this.lastKeySelection = Util.getMillis();
this.keyBindsList.resetMappingAndUpdateButtons();
@@ -66,6 +_,19 @@
} else {
return super.keyPressed(p_193987_, p_193988_, p_193989_);
}
+ }
+
+ @Override
+ public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
+ // Forge: We wait for a second key above if the first press is a modifier
+ // but if they release the modifier then set it explicitly.
+ var key = InputConstants.getKey(keyCode, scanCode);
+ if (this.selectedKey != null && this.selectedKey.getKey() == key) {
+ this.selectedKey = null;
+ this.lastKeySelection = Util.getMillis();
+ this.keyBindsList.resetMappingAndUpdateButtons();
+ }
+ return super.keyReleased(keyCode, scanCode, modifiers);
}
+ @Override
+ public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
+ // Forge: We wait for a second key above if the first press is a modifier
+ // but if they release the modifier then set it explicitly.
+ var key = InputConstants.getKey(keyCode, scanCode);
+ if (this.selectedKey != null && this.selectedKey.getKey() == key) {
+ this.selectedKey = null;
+ this.lastKeySelection = Util.getMillis();
+ this.keyBindsList.resetMappingAndUpdateButtons();
+ }
+ return super.keyReleased(keyCode, scanCode, modifiers);
}
@Override
public void render(GuiGraphics p_282556_, int p_193992_, int p_193993_, float p_193994_) {
@@ -1,153 +1,188 @@
--- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
@@ -92,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
super.render(p_283479_, p_283661_, p_281248_, p_281886_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderBackground(this, p_283479_, p_283661_, p_281248_);
RenderSystem.disableDepthTest();
p_283479_.pose().pushPose();
p_283479_.pose().translate((float)i, (float)j, 0.0F);
@@ -108,12 +_,13 @@
int l = slot.x;
int i1 = slot.y;
if (this.hoveredSlot.isHighlightable()) {
- renderSlotHighlight(p_283479_, l, i1, 0);
+ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k));
}
@@ -90,6 +_,7 @@
int i = this.leftPos;
int j = this.topPos;
super.render(p_283479_, p_283661_, p_281248_, p_281886_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Background(this, p_283479_, p_283661_, p_281248_));
RenderSystem.disableDepthTest();
p_283479_.pose().pushPose();
p_283479_.pose().translate((float)i, (float)j, 0.0F);
@@ -106,12 +_,13 @@
int l = slot.x;
int i1 = slot.y;
if (this.hoveredSlot.isHighlightable()) {
- renderSlotHighlight(p_283479_, l, i1, 0);
+ renderSlotHighlight(p_283479_, l, i1, 0, getSlotColor(k));
}
}
}
}
this.renderLabels(p_283479_, p_283661_, p_281248_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderForeground(this, p_283479_, p_283661_, p_281248_);
ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem;
if (!itemstack.isEmpty()) {
int l1 = 8;
@@ -156,13 +_,17 @@
}
this.renderLabels(p_283479_, p_283661_, p_281248_);
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ContainerScreenEvent.Render.Foreground(this, p_283479_, p_283661_, p_281248_));
ItemStack itemstack = this.draggingItem.isEmpty() ? this.menu.getCarried() : this.draggingItem;
if (!itemstack.isEmpty()) {
int l1 = 8;
@@ -153,13 +_,16 @@
}
public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) {
- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_);
+ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433);
+ }
+
+ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) {
+ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_);
}
public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_) {
- p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, -2130706433, -2130706433, p_283504_);
+ renderSlotHighlight(p_283692_, p_281453_, p_281915_, p_283504_, -2130706433);
+ }
+ public static void renderSlotHighlight(GuiGraphics p_283692_, int p_281453_, int p_281915_, int p_283504_, int color) {
+ p_283692_.fillGradient(RenderType.guiOverlay(), p_281453_, p_281915_, p_281453_ + 16, p_281915_ + 16, color, color, p_283504_);
}
protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
ItemStack itemstack = this.hoveredSlot.getItem();
- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_);
+ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_);
}
}
protected void renderTooltip(GuiGraphics p_283594_, int p_282171_, int p_281909_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
ItemStack itemstack = this.hoveredSlot.getItem();
- p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), p_282171_, p_281909_);
+ p_283594_.renderTooltip(this.font, this.getTooltipFromContainerItem(itemstack), itemstack.getTooltipImage(), itemstack, p_282171_, p_281909_);
}
@@ -174,7 +_,8 @@
p_282567_.pose().pushPose();
p_282567_.pose().translate(0.0F, 0.0F, 232.0F);
p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
+ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT);
+ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
p_282567_.pose().popPose();
}
}
@@ -172,7 +_,8 @@
p_282567_.pose().pushPose();
p_282567_.pose().translate(0.0F, 0.0F, 232.0F);
p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
- p_282567_.renderItemDecorations(this.font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
+ var font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(p_281330_).getFont(p_281330_, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.ITEM_COUNT);
+ p_282567_.renderItemDecorations(font == null ? this.font : font, p_281330_, p_281772_, p_281689_ - (this.draggingItem.isEmpty() ? 0 : 8), p_282568_);
p_282567_.pose().popPose();
}
@@ -282,7 +_,8 @@
if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
@@ -280,7 +_,8 @@
if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
return true;
} else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems();
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.findSlot(p_97748_, p_97749_);
long i = Util.getMillis();
this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -291,6 +_,7 @@
int j = this.leftPos;
int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int l = -1;
if (slot != null) {
l = slot.index;
@@ -316,7 +_,7 @@
}
} else if (!this.isQuickCrafting) {
if (this.menu.getCarried().isEmpty()) {
- if (flag) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, l, p_97750_, ClickType.CLONE);
} else {
boolean flag2 = l != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344));
@@ -340,7 +_,7 @@
this.quickCraftingType = 0;
} else if (p_97750_ == 1) {
this.quickCraftingType = 1;
- } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2;
}
}
@@ -409,10 +_,13 @@
}
public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) {
+ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons
Slot slot = this.findSlot(p_97812_, p_97813_);
int i = this.leftPos;
int j = this.topPos;
boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_);
int k = -1;
if (slot != null) {
k = slot.index;
@@ -426,7 +_,7 @@
if (hasShiftDown()) {
if (!this.lastQuickMoved.isEmpty()) {
for(Slot slot2 : this.menu.slots) {
- if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.container == slot.container && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
+ if (slot2 != null && slot2.mayPickup(this.minecraft.player) && slot2.hasItem() && slot2.isSameInventory(slot) && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE);
}
}
@@ -489,7 +_,7 @@
this.slotClicked((Slot)null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT);
} else if (!this.menu.getCarried().isEmpty()) {
- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
} else {
boolean flag1 = k != -999 && (InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344));
@@ -540,34 +_,39 @@
}
public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {
+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_);
if (super.keyPressed(p_97765_, p_97766_, p_97767_)) {
return true;
- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
this.onClose();
return true;
} else {
- this.checkHotbarKeyPressed(p_97765_, p_97766_);
+ boolean handled = this.checkHotbarKeyPressed(p_97765_, p_97766_);// Forge MC-146650: Needs to return true when the key is handled
if (this.hoveredSlot != null && this.hoveredSlot.hasItem()) {
- if (this.minecraft.options.keyPickItem.matches(p_97765_, p_97766_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 0, ClickType.CLONE);
- } else if (this.minecraft.options.keyDrop.matches(p_97765_, p_97766_)) {
+ handled = true;
+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, hasControlDown() ? 1 : 0, ClickType.THROW);
+ handled = true;
}
+ } else if (this.minecraft.options.keyDrop.isActiveAndMatches(mouseKey)) {
+ handled = true; // Forge MC-146650: Emulate MC bug, so we don't drop from hotbar when pressing drop without hovering over a item.
}
- return true;
+ return handled;
}
}
protected boolean checkHotbarKeyPressed(int p_97806_, int p_97807_) {
if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null) {
- if (this.minecraft.options.keySwapOffhand.matches(p_97806_, p_97807_)) {
+ if (this.minecraft.options.keySwapOffhand.isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, 40, ClickType.SWAP);
return true;
} else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.gameMode.hasInfiniteItems();
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.findSlot(p_97748_, p_97749_);
long i = Util.getMillis();
this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -293,6 +_,7 @@
int j = this.leftPos;
int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int l = -1;
if (slot != null) {
l = slot.index;
@@ -318,7 +_,7 @@
}
} else if (!this.isQuickCrafting) {
if (this.menu.getCarried().isEmpty()) {
- if (flag) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, l, p_97750_, ClickType.CLONE);
} else {
boolean flag2 = l != -999
@@ -346,7 +_,7 @@
this.quickCraftingType = 0;
} else if (p_97750_ == 1) {
this.quickCraftingType = 1;
- } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2;
}
}
@@ -425,10 +_,13 @@
}
@Override
public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) {
+ super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons
Slot slot = this.findSlot(p_97812_, p_97813_);
int i = this.leftPos;
int j = this.topPos;
boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
+ InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_);
int k = -1;
if (slot != null) {
k = slot.index;
@@ -445,7 +_,7 @@
if (slot2 != null
&& slot2.mayPickup(this.minecraft.player)
&& slot2.hasItem()
- && slot2.container == slot.container
+ && slot2.isSameInventory(slot)
&& AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE);
}
@@ -509,7 +_,7 @@
for(int i = 0; i < 9; ++i) {
- if (this.minecraft.options.keyHotbarSlots[i].matches(p_97806_, p_97807_)) {
+ if (this.minecraft.options.keyHotbarSlots[i].isActiveAndMatches(InputConstants.getKey(p_97806_, p_97807_))) {
this.slotClicked(this.hoveredSlot, this.hoveredSlot.index, i, ClickType.SWAP);
return true;
}
@@ -602,6 +_,18 @@
this.slotClicked(null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT);
} else if (!this.menu.getCarried().isEmpty()) {
- if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
} else {
boolean flag1 = k != -999
@@ -568,9 +_,10 @@
@Override
public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {
+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_);
if (super.keyPressed(p_97765_, p_97766_, p_97767_)) {
return true;
- } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
this.onClose();
return true;
} else {
@@ -639,5 +_,17 @@
public void onClose() {
this.minecraft.player.closeContainer();
super.onClose();
+ }
public T getMenu() {
return this.menu;
+ }
+
+ @org.jetbrains.annotations.Nullable
+ public Slot getSlotUnderMouse() { return this.hoveredSlot; }
+ public int getGuiLeft() { return leftPos; }
+ public int getGuiTop() { return topPos; }
+ public int getXSize() { return imageWidth; }
+ public int getYSize() { return imageHeight; }
+ @org.jetbrains.annotations.Nullable
+ public Slot getSlotUnderMouse() { return this.hoveredSlot; }
+ public int getGuiLeft() { return leftPos; }
+ public int getGuiTop() { return topPos; }
+ public int getXSize() { return imageWidth; }
+ public int getYSize() { return imageHeight; }
+
+ protected int slotColor = -2130706433;
+ public int getSlotColor(int index) {
+ return slotColor;
}
}
+ protected int slotColor = -2130706433;
+ public int getSlotColor(int index) {
+ return slotColor;
}
public void onClose() {
@@ -1,291 +1,288 @@
--- a/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java
@@ -112,6 +_,8 @@
private boolean hasClickedOutside;
private final Set<TagKey<Item>> visibleTags = new HashSet<>();
private final boolean displayOperatorCreativeTab;
+ private final List<net.minecraftforge.client.gui.CreativeTabsScreenPage> pages = new java.util.ArrayList<>();
+ private net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>());
@@ -79,6 +_,8 @@
private boolean hasClickedOutside;
private final Set<TagKey<Item>> visibleTags = new HashSet<>();
private final boolean displayOperatorCreativeTab;
+ private final List<net.minecraftforge.client.gui.CreativeTabsScreenPage> pages = new java.util.ArrayList<>();
+ private net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>());
public CreativeModeInventoryScreen(Player p_259788_, FeatureFlagSet p_260074_, boolean p_259569_) {
super(new CreativeModeInventoryScreen.ItemPickerMenu(p_259788_), p_259788_.getInventory(), CommonComponents.EMPTY);
@@ -144,7 +_,7 @@
private void refreshCurrentTabContents(Collection<ItemStack> p_261591_) {
int i = this.menu.getRowIndexForScroll(this.scrollOffs);
this.menu.items.clear();
- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) {
+ if (selectedTab.hasSearchBar()) {
this.refreshSearchResults();
} else {
this.menu.items.addAll(p_261591_);
@@ -307,6 +_,35 @@
protected void init() {
if (this.minecraft.gameMode.hasInfiniteItems()) {
super.init();
+ this.pages.clear();
+ int tabIndex = 0;
+ List<CreativeModeTab> currentPage = new java.util.ArrayList<>();
+ for (CreativeModeTab sortedCreativeModeTab : net.minecraftforge.common.CreativeModeTabRegistry.getSortedCreativeModeTabs()) {
+ currentPage.add(sortedCreativeModeTab);
+ tabIndex++;
+ if (tabIndex == 10) {
+ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage));
+ currentPage = new java.util.ArrayList<>();
+ tabIndex = 0;
+ }
+ }
+ if (tabIndex != 0) {
public CreativeModeInventoryScreen(Player p_259788_, FeatureFlagSet p_260074_, boolean p_259569_) {
super(new CreativeModeInventoryScreen.ItemPickerMenu(p_259788_), p_259788_.getInventory(), CommonComponents.EMPTY);
@@ -112,7 +_,7 @@
private void refreshCurrentTabContents(Collection<ItemStack> p_261591_) {
int i = this.menu.getRowIndexForScroll(this.scrollOffs);
(this.menu).items.clear();
- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) {
+ if (selectedTab.hasSearchBar()) {
this.refreshSearchResults();
} else {
(this.menu).items.addAll(p_261591_);
@@ -266,6 +_,34 @@
protected void init() {
if (this.minecraft.gameMode.hasInfiniteItems()) {
super.init();
+ this.pages.clear();
+ int tabIndex = 0;
+ List<CreativeModeTab> currentPage = new java.util.ArrayList<>();
+ for (CreativeModeTab sortedCreativeModeTab : net.minecraftforge.common.CreativeModeTabRegistry.getSortedCreativeModeTabs()) {
+ currentPage.add(sortedCreativeModeTab);
+ tabIndex++;
+ if (tabIndex == 10) {
+ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage));
+ currentPage = new java.util.ArrayList<>();
+ tabIndex = 0;
+ }
+ if (this.pages.isEmpty()) {
+ this.currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>());
+ } else {
+ this.currentPage = this.pages.get(0);
+ }
+ if (this.pages.size() > 1) {
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> setCurrentPage(this.pages.get(Math.max(this.pages.indexOf(this.currentPage) - 1, 0)))).pos(leftPos, topPos - 50).size(20, 20).build());
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> setCurrentPage(this.pages.get(Math.min(this.pages.indexOf(this.currentPage) + 1, this.pages.size() - 1)))).pos(leftPos + imageWidth - 20, topPos - 50).size(20, 20).build());
+ }
+ this.currentPage = this.pages.stream().filter(page -> page.getVisibleTabs().contains(selectedTab)).findFirst().orElse(this.currentPage);
+ if (!this.currentPage.getVisibleTabs().contains(selectedTab)) {
+ selectedTab = this.currentPage.getVisibleTabs().get(0);
+ }
+
this.searchBox = new EditBox(this.font, this.leftPos + 82, this.topPos + 6, 80, 9, Component.translatable("itemGroup.search"));
this.searchBox.setMaxLength(50);
this.searchBox.setBordered(false);
@@ -353,7 +_,7 @@
public boolean charTyped(char p_98521_, int p_98522_) {
if (this.ignoreTextInput) {
return false;
- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
+ } else if (!selectedTab.hasSearchBar()) {
return false;
} else {
String s = this.searchBox.getValue();
@@ -372,7 +_,7 @@
@Override
public boolean keyPressed(int p_98547_, int p_98548_, int p_98549_) {
this.ignoreTextInput = false;
- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
+ if (!selectedTab.hasSearchBar()) {
if (this.minecraft.options.keyChat.matches(p_98547_, p_98548_)) {
this.ignoreTextInput = true;
this.selectTab(CreativeModeTabs.searchTab());
@@ -408,6 +_,7 @@
}
+ }
+ if (tabIndex != 0) {
+ this.pages.add(new net.minecraftforge.client.gui.CreativeTabsScreenPage(currentPage));
+ }
+ if (this.pages.isEmpty()) {
+ this.currentPage = new net.minecraftforge.client.gui.CreativeTabsScreenPage(new java.util.ArrayList<>());
+ } else {
+ this.currentPage = this.pages.get(0);
+ }
+ if (this.pages.size() > 1) {
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal("<"), b -> setCurrentPage(this.pages.get(Math.max(this.pages.indexOf(this.currentPage) - 1, 0)))).pos(leftPos, topPos - 50).size(20, 20).build());
+ addRenderableWidget(net.minecraft.client.gui.components.Button.builder(Component.literal(">"), b -> setCurrentPage(this.pages.get(Math.min(this.pages.indexOf(this.currentPage) + 1, this.pages.size() - 1)))).pos(leftPos + imageWidth - 20, topPos - 50).size(20, 20).build());
+ }
+ this.currentPage = this.pages.stream().filter(page -> page.getVisibleTabs().contains(selectedTab)).findFirst().orElse(this.currentPage);
+ if (!this.currentPage.getVisibleTabs().contains(selectedTab)) {
+ selectedTab = this.currentPage.getVisibleTabs().get(0);
+ }
this.searchBox = new EditBox(this.font, this.leftPos + 82, this.topPos + 6, 80, 9, Component.translatable("itemGroup.search"));
this.searchBox.setMaxLength(50);
this.searchBox.setBordered(false);
@@ -311,7 +_,7 @@
public boolean charTyped(char p_98521_, int p_98522_) {
if (this.ignoreTextInput) {
return false;
- } else if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
+ } else if (!selectedTab.hasSearchBar()) {
return false;
} else {
String s = this.searchBox.getValue();
@@ -329,7 +_,7 @@
private void refreshSearchResults() {
+ if (!selectedTab.hasSearchBar()) return;
this.menu.items.clear();
this.visibleTags.clear();
String s = this.searchBox.getValue();
@@ -417,10 +_,10 @@
SearchTree<ItemStack> searchtree;
if (s.startsWith("#")) {
s = s.substring(1);
- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_TAGS);
+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab));
this.updateVisibleTags(s);
} else {
- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_NAMES);
+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab));
public boolean keyPressed(int p_98547_, int p_98548_, int p_98549_) {
this.ignoreTextInput = false;
- if (selectedTab.getType() != CreativeModeTab.Type.SEARCH) {
+ if (!selectedTab.hasSearchBar()) {
if (this.minecraft.options.keyChat.matches(p_98547_, p_98548_)) {
this.ignoreTextInput = true;
this.selectTab(CreativeModeTabs.searchTab());
@@ -364,6 +_,7 @@
}
private void refreshSearchResults() {
+ if (!selectedTab.hasSearchBar()) return;
(this.menu).items.clear();
this.visibleTags.clear();
String s = this.searchBox.getValue();
@@ -373,10 +_,10 @@
SearchTree<ItemStack> searchtree;
if (s.startsWith("#")) {
s = s.substring(1);
- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_TAGS);
+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab));
this.updateVisibleTags(s);
} else {
- searchtree = this.minecraft.getSearchTree(SearchRegistry.CREATIVE_NAMES);
+ searchtree = this.minecraft.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab));
}
(this.menu).items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT)));
@@ -408,7 +_,8 @@
protected void renderLabels(GuiGraphics p_283168_, int p_281774_, int p_281466_) {
if (selectedTab.showTitle()) {
- p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, 4210752, false);
+ com.mojang.blaze3d.systems.RenderSystem.disableBlend();
+ p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, selectedTab.getLabelColor(), false);
}
}
@@ -418,7 +_,7 @@
double d0 = p_98531_ - (double)this.leftPos;
double d1 = p_98532_ - (double)this.topPos;
- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabClicked(creativemodetab, d0, d1)) {
return true;
}
@@ -439,7 +_,7 @@
double d1 = p_98623_ - (double)this.topPos;
this.scrolling = false;
this.menu.items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT)));
@@ -447,7 +_,8 @@
@Override
protected void renderLabels(GuiGraphics p_283168_, int p_281774_, int p_281466_) {
if (selectedTab.showTitle()) {
- p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, 4210752, false);
+ com.mojang.blaze3d.systems.RenderSystem.disableBlend();
+ p_283168_.drawString(this.font, selectedTab.getDisplayName(), 8, 6, selectedTab.getLabelColor(), false);
}
}
- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabClicked(creativemodetab, d0, d1)) {
this.selectTab(creativemodetab);
return true;
@@ -457,6 +_,7 @@
private void selectTab(CreativeModeTab p_98561_) {
CreativeModeTab creativemodetab = selectedTab;
selectedTab = p_98561_;
+ slotColor = p_98561_.getSlotColor();
this.quickCraftSlots.clear();
(this.menu).items.clear();
this.clearDraggingState();
@@ -533,13 +_,15 @@
this.originalSlots = null;
}
@@ -457,7 +_,7 @@
double d0 = p_98531_ - (double)this.leftPos;
double d1 = p_98532_ - (double)this.topPos;
- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) {
+ if (selectedTab.hasSearchBar()) {
this.searchBox.setVisible(true);
this.searchBox.setCanLoseFocus(false);
this.searchBox.setFocused(true);
if (creativemodetab != p_98561_) {
this.searchBox.setValue("");
}
+ this.searchBox.setWidth(selectedTab.getSearchBarWidth());
+ this.searchBox.setX(this.leftPos + (82 /*default left*/ + 89 /*default width*/) - this.searchBox.getWidth());
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabClicked(creativemodetab, d0, d1)) {
return true;
}
@@ -479,7 +_,7 @@
double d1 = p_98623_ - (double)this.topPos;
this.scrolling = false;
this.refreshSearchResults();
} else {
@@ -595,7 +_,7 @@
public void render(GuiGraphics p_283000_, int p_281317_, int p_282770_, float p_281295_) {
super.render(p_283000_, p_281317_, p_282770_, p_281295_);
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabClicked(creativemodetab, d0, d1)) {
this.selectTab(creativemodetab);
return true;
@@ -497,6 +_,7 @@
private void selectTab(CreativeModeTab p_98561_) {
CreativeModeTab creativemodetab = selectedTab;
selectedTab = p_98561_;
+ slotColor = p_98561_.getSlotColor();
this.quickCraftSlots.clear();
this.menu.items.clear();
this.clearDraggingState();
@@ -573,13 +_,15 @@
this.originalSlots = null;
}
- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) {
break;
}
@@ -605,13 +_,22 @@
p_283000_.renderTooltip(this.font, TRASH_SLOT_TOOLTIP, p_281317_, p_282770_);
}
- if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) {
+ if (selectedTab.hasSearchBar()) {
this.searchBox.setVisible(true);
this.searchBox.setCanLoseFocus(false);
this.searchBox.setFocused(true);
if (creativemodetab != p_98561_) {
this.searchBox.setValue("");
+ if (this.pages.size() != 1) {
+ Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size()));
+ p_283000_.pose().pushPose();
+ p_283000_.pose().translate(0F, 0F, 300F);
+ p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1);
+ p_283000_.pose().popPose();
+ }
+
+ com.mojang.blaze3d.systems.RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
this.renderTooltip(p_283000_, p_281317_, p_282770_);
}
public List<Component> getTooltipFromContainerItem(ItemStack p_281769_) {
boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot;
boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY;
- boolean flag2 = selectedTab.getType() == CreativeModeTab.Type.SEARCH;
+ boolean flag2 = selectedTab.hasSearchBar();
TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL;
TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default;
List<Component> list = p_281769_.getTooltipLines(this.minecraft.player, tooltipflag);
@@ -631,7 +_,7 @@
int i = 1;
for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(p_281769_)) {
+ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(p_281769_)) {
list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE));
}
+ this.searchBox.setWidth(selectedTab.getSearchBarWidth());
+ this.searchBox.setX(this.leftPos + (82 /*default left*/ + 89 /*default width*/) - this.searchBox.getWidth());
}
@@ -641,13 +_,13 @@
}
this.refreshSearchResults();
} else {
@@ -642,7 +_,15 @@
public void render(GuiGraphics p_283000_, int p_281317_, int p_282770_, float p_281295_) {
super.render(p_283000_, p_281317_, p_282770_, p_281295_);
protected void renderBg(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) {
- for(CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for(CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (creativemodetab != selectedTab) {
this.renderTabButton(p_282663_, creativemodetab);
}
}
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ if (this.pages.size() != 1) {
+ Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size()));
+ p_283000_.pose().pushPose();
+ p_283000_.pose().translate(0F, 0F, 300F);
+ p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1);
+ p_283000_.pose().popPose();
+ }
- p_282663_.blit(new ResourceLocation("textures/gui/container/creative_inventory/tab_" + selectedTab.getBackgroundSuffix()), this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight);
+ p_282663_.blit(selectedTab.getBackgroundLocation(), this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight);
this.searchBox.render(p_282663_, p_282089_, p_282249_, p_282504_);
int j = this.leftPos + 175;
int k = this.topPos + 18;
@@ -657,6 +_,7 @@
p_282663_.blitSprite(resourcelocation, j, k + (int)((float)(i - k - 17) * this.scrollOffs), 12, 15);
}
+ if (currentPage.getVisibleTabs().contains(selectedTab)) //Forge: only display tab selection when the selected tab is on the current page
this.renderTabButton(p_282663_, selectedTab);
if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) {
InventoryScreen.renderEntityInInventoryFollowsMouse(p_282663_, this.leftPos + 73, this.topPos + 6, this.leftPos + 105, this.topPos + 49, 20, 0.0625F, (float)p_282089_, (float)p_282249_, this.minecraft.player);
@@ -665,7 +_,7 @@
}
private int getTabX(CreativeModeTab p_260136_) {
- int i = p_260136_.column();
+ int i = currentPage.getColumn(p_260136_);
int j = 27;
int k = 27 * i;
if (p_260136_.isAlignedRight()) {
@@ -677,7 +_,7 @@
private int getTabY(CreativeModeTab p_260181_) {
int i = 0;
- if (p_260181_.row() == CreativeModeTab.Row.TOP) {
+ if (currentPage.isTop(p_260181_)) {
i -= 32;
} else {
i += this.imageHeight;
@@ -705,8 +_,8 @@
protected void renderTabButton(GuiGraphics p_283590_, CreativeModeTab p_283489_) {
boolean flag = p_283489_ == selectedTab;
- boolean flag1 = p_283489_.row() == CreativeModeTab.Row.TOP;
- int i = p_283489_.column();
+ boolean flag1 = currentPage.isTop(p_283489_);
+ int i = currentPage.getColumn(p_283489_);
int j = this.leftPos + this.getTabX(p_283489_);
int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4));
ResourceLocation[] aresourcelocation;
@@ -716,6 +_,7 @@
aresourcelocation = flag ? SELECTED_BOTTOM_TABS : UNSELECTED_BOTTOM_TABS;
}
+ com.mojang.blaze3d.systems.RenderSystem.enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border.
p_283590_.blitSprite(aresourcelocation[Mth.clamp(i, 0, aresourcelocation.length)], j, k, 26, 32);
p_283590_.pose().pushPose();
p_283590_.pose().translate(0.0F, 0.0F, 100.0F);
@@ -759,6 +_,14 @@
}
+ public net.minecraftforge.client.gui.CreativeTabsScreenPage getCurrentPage() {
+ return currentPage;
+ }
+
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) {
break;
}
@@ -654,6 +_,7 @@
p_283000_.renderTooltip(this.font, TRASH_SLOT_TOOLTIP, p_281317_, p_282770_);
}
+ com.mojang.blaze3d.systems.RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
this.renderTooltip(p_283000_, p_281317_, p_282770_);
}
@@ -661,7 +_,7 @@
public List<Component> getTooltipFromContainerItem(ItemStack p_281769_) {
boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot;
boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY;
- boolean flag2 = selectedTab.getType() == CreativeModeTab.Type.SEARCH;
+ boolean flag2 =selectedTab.hasSearchBar();
TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL;
TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default;
List<Component> list = p_281769_.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipflag);
@@ -680,7 +_,7 @@
int i = 1;
for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(p_281769_)) {
+ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(p_281769_)) {
list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE));
}
}
@@ -691,14 +_,14 @@
@Override
protected void renderBg(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) {
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (creativemodetab != selectedTab) {
this.renderTabButton(p_282663_, creativemodetab);
}
}
p_282663_.blit(
- new ResourceLocation("textures/gui/container/creative_inventory/tab_" + selectedTab.getBackgroundSuffix()),
+ selectedTab.getBackgroundLocation(),
this.leftPos,
this.topPos,
0,
@@ -715,6 +_,7 @@
p_282663_.blitSprite(resourcelocation, j, k + (int)((float)(i - k - 17) * this.scrollOffs), 12, 15);
}
+ if (currentPage.getVisibleTabs().contains(selectedTab)) //Forge: only display tab selection when the selected tab is on the current page
this.renderTabButton(p_282663_, selectedTab);
if (selectedTab.getType() == CreativeModeTab.Type.INVENTORY) {
InventoryScreen.renderEntityInInventoryFollowsMouse(
@@ -733,7 +_,7 @@
}
private int getTabX(CreativeModeTab p_260136_) {
- int i = p_260136_.column();
+ int i = currentPage.getColumn(p_260136_);
int j = 27;
int k = 27 * i;
if (p_260136_.isAlignedRight()) {
@@ -745,7 +_,7 @@
private int getTabY(CreativeModeTab p_260181_) {
int i = 0;
- if (p_260181_.row() == CreativeModeTab.Row.TOP) {
+ if (currentPage.isTop(p_260181_)) {
i -= 32;
} else {
i += this.imageHeight;
@@ -773,8 +_,8 @@
protected void renderTabButton(GuiGraphics p_283590_, CreativeModeTab p_283489_) {
boolean flag = p_283489_ == selectedTab;
- boolean flag1 = p_283489_.row() == CreativeModeTab.Row.TOP;
- int i = p_283489_.column();
+ boolean flag1 = currentPage.isTop(p_283489_);
+ int i = currentPage.getColumn(p_283489_);
int j = this.leftPos + this.getTabX(p_283489_);
int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4));
ResourceLocation[] aresourcelocation;
@@ -784,6 +_,7 @@
aresourcelocation = flag ? SELECTED_BOTTOM_TABS : UNSELECTED_BOTTOM_TABS;
}
+ com.mojang.blaze3d.systems.RenderSystem.enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border.
p_283590_.blitSprite(aresourcelocation[Mth.clamp(i, 0, aresourcelocation.length)], j, k, 26, 32);
p_283590_.pose().pushPose();
p_283590_.pose().translate(0.0F, 0.0F, 100.0F);
@@ -825,6 +_,14 @@
}
}
+ public net.minecraftforge.client.gui.CreativeTabsScreenPage getCurrentPage() {
+ return currentPage;
+ }
+ public void setCurrentPage(net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage) {
+ this.currentPage = currentPage;
+ }
+
+ public void setCurrentPage(net.minecraftforge.client.gui.CreativeTabsScreenPage currentPage) {
+ this.currentPage = currentPage;
+ }
@OnlyIn(Dist.CLIENT)
static class CustomCreativeSlot extends Slot {
public CustomCreativeSlot(Container p_98633_, int p_98634_, int p_98635_, int p_98636_) {
@@ -926,6 +_,22 @@
public boolean mayPickup(Player p_98665_) {
return this.target.mayPickup(p_98665_);
+ }
+
@OnlyIn(Dist.CLIENT)
static class CustomCreativeSlot extends Slot {
public CustomCreativeSlot(Container p_98633_, int p_98634_, int p_98635_, int p_98636_) {
@@ -1009,6 +_,22 @@
@Override
public boolean mayPickup(Player p_98665_) {
return this.target.mayPickup(p_98665_);
+ }
+ @Override
+ public int getSlotIndex() {
+ return this.target.getSlotIndex();
+ }
+
+ @Override
+ public int getSlotIndex() {
+ return this.target.getSlotIndex();
+ }
+ @Override
+ public boolean isSameInventory(Slot other) {
+ return this.target.isSameInventory(other);
+ }
+
+ @Override
+ public boolean isSameInventory(Slot other) {
+ return this.target.isSameInventory(other);
+ }
+
+ @Override
+ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) {
+ this.target.setBackground(atlas, sprite);
+ return this;
}
}
+ @Override
+ public Slot setBackground(ResourceLocation atlas, ResourceLocation sprite) {
+ this.target.setBackground(atlas, sprite);
+ return this;
}
}
}
@@ -1,44 +1,45 @@
--- a/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/EffectRenderingInventoryScreen.java
@@ -47,12 +_,16 @@
Collection<MobEffectInstance> collection = this.minecraft.player.getActiveEffects();
if (!collection.isEmpty() && j >= 32) {
boolean flag = j >= 120;
+ var event = net.minecraftforge.client.ForgeHooksClient.onScreenPotionSize(this, j, !flag, i);
+ if (event.isCanceled()) return;
+ flag = !event.isCompact();
+ i = event.getHorizontalOffset();
int k = 33;
if (collection.size() > 5) {
k = 132 / (collection.size() - 1);
}
@@ -45,12 +_,17 @@
Collection<MobEffectInstance> collection = this.minecraft.player.getActiveEffects();
if (!collection.isEmpty() && j >= 32) {
boolean flag = j >= 120;
+ var event = net.minecraftforge.client.ForgeHooksClient.onScreenPotionSize(this, j, !flag, i);
+ if (event.isCanceled()) return;
+ flag = !event.isCompact();
+ i = event.getHorizontalOffset();
int k = 33;
if (collection.size() > 5) {
k = 132 / (collection.size() - 1);
}
- Iterable<MobEffectInstance> iterable = Ordering.natural().sortedCopy(collection);
+ Iterable<MobEffectInstance> iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList();
this.renderBackgrounds(p_281945_, i, k, iterable, flag);
this.renderIcons(p_281945_, i, k, iterable, flag);
if (flag) {
@@ -98,6 +_,11 @@
int i = this.topPos;
- Iterable<MobEffectInstance> iterable = Ordering.natural().sortedCopy(collection);
+
+ Iterable<MobEffectInstance> iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().collect(java.util.stream.Collectors.toList());
this.renderBackgrounds(p_281945_, i, k, iterable, flag);
this.renderIcons(p_281945_, i, k, iterable, flag);
if (flag) {
@@ -96,6 +_,11 @@
int i = this.topPos;
for (MobEffectInstance mobeffectinstance : p_282642_) {
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (renderer.renderInventoryIcon(mobeffectinstance, this, p_282745_, p_282521_ + (p_281536_ ? 6 : 7), i, 0)) {
+ i += p_282291_;
+ continue;
+ }
Holder<MobEffect> holder = mobeffectinstance.getEffect();
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(holder);
p_282745_.blit(p_282521_ + (p_281536_ ? 6 : 7), i + 7, 0, 18, 18, textureatlassprite);
@@ -109,6 +_,11 @@
int i = this.topPos;
for(MobEffectInstance mobeffectinstance : p_282642_) {
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (renderer.renderInventoryIcon(mobeffectinstance, this, p_282745_, p_282521_ + (p_281536_ ? 6 : 7), i, 0)) {
+ i += p_282291_;
+ continue;
+ }
MobEffect mobeffect = mobeffectinstance.getEffect();
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.get(mobeffect);
p_282745_.blit(p_282521_ + (p_281536_ ? 6 : 7), i + 7, 0, 18, 18, textureatlassprite);
@@ -108,6 +_,11 @@
int i = this.topPos;
for (MobEffectInstance mobeffectinstance : p_281986_) {
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (renderer.renderInventoryText(mobeffectinstance, this, p_281462_, p_283484_, i, 0)) {
+ i += p_282057_;
+ continue;
+ }
Component component = this.getEffectName(mobeffectinstance);
p_281462_.drawString(this.font, component, p_283484_ + 10 + 18, i + 6, 16777215);
Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate());
for(MobEffectInstance mobeffectinstance : p_281986_) {
+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance);
+ if (renderer.renderInventoryText(mobeffectinstance, this, p_281462_, p_283484_, i, 0)) {
+ i += p_282057_;
+ continue;
+ }
Component component = this.getEffectName(mobeffectinstance);
p_281462_.drawString(this.font, component, p_283484_ + 10 + 18, i + 6, 16777215);
Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate());
@@ -1,28 +1,28 @@
--- a/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java
@@ -108,7 +_,7 @@
int l1 = 86 - this.font.width(s);
FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1);
int i2 = 6839882;
- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) {
+ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{
RenderSystem.enableBlend();
p_282430_.blitSprite(ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19);
p_282430_.blitSprite(DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16);
@@ -173,10 +_,13 @@
Enchantment enchantment = Enchantment.byId(this.menu.enchantClue[j]);
int l = this.menu.levelClue[j];
int i1 = j + 1;
- if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0 && l >= 0 && enchantment != null) {
+ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0) {
List<Component> list = Lists.newArrayList();
- list.add(Component.translatable("container.enchant.clue", enchantment.getFullname(l)).withStyle(ChatFormatting.WHITE));
- if (!flag) {
+ list.add((Component.translatable("container.enchant.clue", enchantment == null ? "" : enchantment.getFullname(l))).withStyle(ChatFormatting.WHITE));
+ if (enchantment == null) {
+ list.add(Component.literal(""));
+ list.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED));
+ } else if (!flag) {
list.add(CommonComponents.EMPTY);
if (this.minecraft.player.experienceLevel < k) {
list.add(Component.translatable("container.enchant.level.requirement", this.menu.costs[j]).withStyle(ChatFormatting.RED));
@@ -93,7 +_,7 @@
int l1 = 86 - this.font.width(s);
FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1);
int i2 = 6839882;
- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) {
+ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.getAbilities().instabuild) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels
p_282430_.blitSprite(ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19);
p_282430_.blitSprite(DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16);
p_282430_.drawWordWrap(this.font, formattedtext, j1, j + 16 + 19 * l, l1, (i2 & 16711422) >> 1);
@@ -154,10 +_,13 @@
Enchantment enchantment = Enchantment.byId((this.menu).enchantClue[j]);
int l = (this.menu).levelClue[j];
int i1 = j + 1;
- if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0 && l >= 0 && enchantment != null) {
+ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)p_282491_, (double)p_281953_) && k > 0) {
List<Component> list = Lists.newArrayList();
- list.add(Component.translatable("container.enchant.clue", enchantment.getFullname(l)).withStyle(ChatFormatting.WHITE));
- if (!flag) {
+ list.add((Component.translatable("container.enchant.clue", enchantment == null ? "" : enchantment.getFullname(l))).withStyle(ChatFormatting.WHITE));
+ if (enchantment == null) {
+ list.add(Component.literal(""));
+ list.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED));
+ } else if (!flag) {
list.add(CommonComponents.EMPTY);
if (this.minecraft.player.experienceLevel < k) {
list.add(Component.translatable("container.enchant.level.requirement", (this.menu).costs[j]).withStyle(ChatFormatting.RED));
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/HangingSignEditScreen.java
@@ -15,7 +_,7 @@
private static final Vector3f TEXT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F);
private static final int TEXTURE_WIDTH = 16;
private static final int TEXTURE_HEIGHT = 16;
- private final ResourceLocation texture = new ResourceLocation("textures/gui/hanging_signs/" + this.woodType.name() + ".png");
+ private final ResourceLocation texture = new ResourceLocation(this.woodType.name() + ".png").withPrefix("textures/gui/hanging_signs/"); // possibly unnecessary patch(?) -Paint_Ninja
private static final Vector3f TEXT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F);
private static final int TEXTURE_WIDTH = 16;
private static final int TEXTURE_HEIGHT = 16;
- private final ResourceLocation texture = new ResourceLocation("textures/gui/hanging_signs/" + this.woodType.name() + ".png");
+ private final ResourceLocation texture = new ResourceLocation(this.woodType.name() + ".png").withPrefix("textures/gui/hanging_signs/");
public HangingSignEditScreen(SignBlockEntity p_278017_, boolean p_277942_, boolean p_277778_) {
super(p_278017_, p_277942_, p_277778_, Component.translatable("hanging_sign.edit"));
public HangingSignEditScreen(SignBlockEntity p_278017_, boolean p_277942_, boolean p_277778_) {
super(p_278017_, p_277942_, p_277778_, Component.translatable("hanging_sign.edit"));
@@ -1,16 +1,16 @@
--- a/net/minecraft/client/gui/screens/inventory/MerchantScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/MerchantScreen.java
@@ -234,7 +_,12 @@
p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_, p_283601_);
} else {
p_281357_.renderItemDecorations(this.font, p_282046_, p_282403_, p_283601_, p_282046_.getCount() == 1 ? "1" : null);
- p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_ + 14, p_283601_, p_283466_.getCount() == 1 ? "1" : null);
+ // Forge: fixes Forge-8806, code for count rendering taken from GuiGraphics#renderGuiItemDecorations
+ p_281357_.pose().pushPose();
+ p_281357_.pose().translate(0.0F, 0.0F, 200.0F);
+ String count = p_283466_.getCount() == 1 ? "1" : String.valueOf(p_283466_.getCount());
+ font.drawInBatch(count, (float) (p_282403_ + 14) + 19 - 2 - font.width(count), (float)p_283601_ + 6 + 3, 0xFFFFFF, true, p_281357_.pose().last().pose(), p_281357_.bufferSource(), net.minecraft.client.gui.Font.DisplayMode.NORMAL, 0, 15728880, false);
+ p_281357_.pose().popPose();
p_281357_.pose().pushPose();
p_281357_.pose().translate(0.0F, 0.0F, 300.0F);
p_281357_.blitSprite(DISCOUNT_STRIKETHRUOGH_SPRITE, p_282403_ + 7, p_283601_ + 12, 0, 9, 2);
@@ -236,7 +_,12 @@
p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_, p_283601_);
} else {
p_281357_.renderItemDecorations(this.font, p_282046_, p_282403_, p_283601_, p_282046_.getCount() == 1 ? "1" : null);
- p_281357_.renderItemDecorations(this.font, p_283466_, p_282403_ + 14, p_283601_, p_283466_.getCount() == 1 ? "1" : null);
+ // Forge: fixes Forge-8806, code for count rendering taken from GuiGraphics#renderGuiItemDecorations
+ p_281357_.pose().pushPose();
+ p_281357_.pose().translate(0.0F, 0.0F, 200.0F);
+ String count = p_283466_.getCount() == 1 ? "1" : String.valueOf(p_283466_.getCount());
+ font.drawInBatch(count, (float) (p_282403_ + 14) + 19 - 2 - font.width(count), (float)p_283601_ + 6 + 3, 0xFFFFFF, true, p_281357_.pose().last().pose(), p_281357_.bufferSource(), net.minecraft.client.gui.Font.DisplayMode.NORMAL, 0, 15728880, false);
+ p_281357_.pose().popPose();
p_281357_.pose().pushPose();
p_281357_.pose().translate(0.0F, 0.0F, 300.0F);
p_281357_.blitSprite(DISCOUNT_STRIKETHRUOGH_SPRITE, p_282403_ + 7, p_283601_ + 12, 0, 9, 2);
@@ -1,11 +1,11 @@
--- a/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java
+++ b/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java
@@ -20,6 +_,8 @@
if (p_169951_ instanceof BundleTooltip bundletooltip) {
return new ClientBundleTooltip(bundletooltip.contents());
} else {
+ ClientTooltipComponent result = net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(p_169951_);
+ if (result != null) return result;
throw new IllegalArgumentException("Unknown TooltipComponent");
}
}
if (p_169951_ instanceof BundleTooltip) {
return new ClientBundleTooltip((BundleTooltip)p_169951_);
} else {
+ ClientTooltipComponent result = net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(p_169951_);
+ if (result != null) return result;
throw new IllegalArgumentException("Unknown TooltipComponent");
}
}
Loaded 100 of 1243 files, more files were not shown because too many files have changed in this diff. Show more