Compare commits

...
105 Commits
Author SHA1 Message Date
berkay8987 8bdaec882b Fix missing forge config UI translation keys (#10915) 2026-11-02 18:07:47 -08:00
LexManos 243490d780 Add protection against large network channel lists 2026-10-14 20:22:01 -07:00
LexManos ddf327d367 Fix legacy object holders not being fired in the registry specific codepath
Better optimize the scanning for object holders by unrolling streams.
2026-10-13 09:55:15 -07:00
BonsUnleashedandLexManos 82696a8a76 Store object holder handlers per registry name (#10899)
Co-authored-by: LexManos <[email protected]>
2026-10-12 17:51:51 -07:00
LexManos 56abf84881 Fix generic errors in new Eclipse compiler 2026-10-12 17:48:05 -07:00
Meme Man 71d814ffa6 Update equality check for RegistryObject to include RegistryObject#key. (#10856) 2026-07-21 11:16:17 -07:00
Matt b7efb8287b Toml parsing errors are now visible in the latest log (#10844) 2026-07-09 13:26:59 -07:00
Matt e85be8a621 Add support for multiple access transformer configs. 2026-03-23 11:18:49 -07:00
Jonathing 94a540437d Migrate the MDK to ForgeGradle 7
Backport of d29524b to 1.20.6
2026-03-18 23:17:25 +00:00
Paint_Ninja fac1237023 Skip processing vanilla classes in RuntimeDistCleaner when running on a client
Backport of #10682 to 1.20.6
2026-03-17 21:05:41 +00:00
Paint_Ninja 0081a4dee8 Bump ASM and EventBus
- ASM 9.9.1 for Java 26 support
- EventBus 6.2.33 for Event#cancel() convenience method and further performance improvements
2026-03-17 21:03:33 +00:00
LexManos be1a061bd2 Mark applyServerBinpatches as a dependency of BundleList. Fixes: #10729 2025-12-04 09:23:51 -08:00
LexManos e64aaa5e9d Migrate to Github Actions 2025-12-02 15:06:48 -08:00
Paint_Ninja 4a5b7af2dc Bump ASM to 9.8 for Java 25 runtime support 2025-09-22 11:55:32 +01:00
Matt cc4a4a62b4 Add ForgeLayeredDraw & AddGuiOverlayLayersEvent as API for gui overlay management. (#10584) 2025-07-27 10:27:13 -07:00
Jonathing 2ce54f1855 1.20.6 RB 2
https://forums.minecraftforge.net/topic/154389-forge-502-minecraft-1206/
2025-03-04 16:02:43 -05:00
JonathingandLexManos 8897351a80 Speed up mod annotation scanning by ~30% (#10468)
Co-authored-by: LexManos <[email protected]>
2025-03-04 12:49:08 -08:00
Jonathing b0b34c638e Add missed license headers (#10477) 2025-03-04 12:48:54 -08:00
Jonathing 212da42d6e Add '#forge:chorus_additionally_grows_on' tag for similar mechanics to '#minecraft:azalea_grows_on' but for chorus (#10455) 2025-03-04 12:48:41 -08:00
Jonathing fe616ffe20 Fix damageItem's game test not using onBreak callback correctly (#10451) 2025-02-18 13:18:58 -08:00
Jonathing dba4691cd3 Bump dependencies, most notably EventBus (#10387)
- SecureModules 2.2.19 -> 2.2.21
  - Dev time performance improvements
- CoreMods 5.2.4 -> 5.2.6
- EventBus 6.2.15 -> 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.3 -> 2.1.8
  - Dev time performance improvements
2025-02-17 19:50:56 -08:00
00fc008f7f Re-introduce ItemStack Capabilities (#10364)
Co-authored-by: RealMangoRage <[email protected]>
Co-authored-by: LexManos <[email protected]>
2025-02-17 19:45:45 -08:00
LexManos e23fc25a6c Fix compile error in test helper. 2025-02-17 19:37:45 -08:00
Jonathing b8bbf950a9 Re-introduce IForgeItem.damageItem when an item takes damage, Fixes #10344 (#10374) 2025-02-17 19:09:58 -08:00
JonathingandLexManos 208adc1109 Add updated tag context to AddReloadListenerEvent (#10440)
Fixes using custom tags in GlobalLootModifiers.
Fix Global Loot Modifier deserialization not having registry access

---------
Co-authored-by: LexManos <[email protected]>
2025-02-17 19:08:18 -08:00
Jonathing 60904744b9 Add fast graphics render type to block model jsons (#10397)
Make modded leaves behave like vanilla leaves by default (Fixes #10389)
2025-02-17 18:59:16 -08:00
Jonathing ac5141c97c Fix corrupted and invalidly symlinked worlds crashing on level select (#10437) 2025-02-17 18:58:32 -08:00
Jonathing 0b1eefc6d5 Backport even more future ResourceLocation methods (#10405) 2025-02-17 18:58:17 -08:00
Jonathing 3de4e38d10 Fix issue with shields not disabling correctly (#10319) 2025-01-27 17:18:06 -08:00
Joseph T. McQuigg 384fe451fc Fix issues in VillagerTrades.EmeraldsForVillagerTypeItem related to custom Villager Types (#10310)
Add VillagerType#registerBiomeType
2025-01-27 17:17:23 -08:00
JonathingandLexManos 6a78310a52 GameTestHelper additions (#10341)
Co-authored-by: LexManos <[email protected]>
2025-01-27 14:36:37 -08:00
Jonathing 4305f6de49 Update Gradle to 8.12.1 (#10355)
Set IntelliJ to download sources automatically in MDK
2025-01-27 14:36:21 -08:00
Jonathing 9d64011438 Fix JOpt Simple by bumping ModLauncher (#10350) 2025-01-27 14:35:41 -08:00
Jonathing a0a71c6c53 Fix JOpt Simple needing a strict version requirement declaration (#10314) 2025-01-25 18:52:12 +00:00
Jonathing 7060036589 Fix incorrect method reference in TntBlock.explode() (#10329) 2025-01-25 18:51:46 +00:00
JonathingandJames Mitchell 97e6b96cbb Add a way to render tooltips from Formatted text and TooltipComponents elements (#10056) (#10291)
Co-authored-by: James Mitchell <[email protected]>
2025-01-04 14:35:14 -08:00
Jonathing 915d8a8f7d Bump CoreMods to 5.2.4 (#10265) 2024-12-23 16:12:20 -08:00
JonathingandPaint_Ninja 69037051ab Deprecate @ObjectHolder, add a couple of fast-paths (#10230)
Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 15:15:05 -08:00
Jonathing 1fe85f5396 Add optional fix of use item duration, disabled by default (#10248) 2024-12-23 15:04:45 -08:00
JonathingandPaint_Ninja 5693e5d11a Simplify memory usage display on loading screen (#10235)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 15:04:31 -08:00
Jonathing da2f435810 Allow mipmap lowering to be disabled (#10254) 2024-12-23 14:53:51 -08:00
JonathingandPaint_Ninja c24aff8a53 Skip Vanilla classes for the CapabilityTokenSubclass transformer (#10223)
Skip Vanilla classes for the CapabilityTokenSubclass transformer
Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 14:44:43 -08:00
JonathingandPaint_Ninja d38ce3d794 Skip Forge classes in the RuntimeEnumExtender transformer (#10218)
Mod classes are still transformed as usual
Cherry-pick a few optimizations from HEAD

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 14:32:40 -08:00
JonathingandPaint_Ninja 87b4f6367a [1.20.6] Skip processing Forge classes in RuntimeDistCleaner (#10210)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 14:16:31 -08:00
Martijn van den Brand b81e7dfe73 Pass player argument when firing OnDatapackSyncEvent (#10172) 2024-11-17 01:01:43 -08:00
Jonathing 9d02da81cf Bump CoreMods to 5.2 (#10161)
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
- Request CoreMods to not apply fix for ASMAPI.findFirstInstructionBefore by default
2024-11-08 12:52:47 -08:00
Jonathing 5b1ab8b40b Bump CoreMods 5.1.13 and ASM 9.7.1 (#10128) 2024-10-27 18:17:53 -07:00
Paint_Ninjaandandan42 542db422ad Remove unneeded boat patch (backport of #10061 to 1.20.6) (#10086)
Co-authored-by: andan42 <[email protected]>
2024-10-06 18:27:38 -07:00
Paint_Ninja ac10315810 Use the new methods in EventBus (backport of #10028 to 1.20.6) (#10091)
Adds `fire()` and Result#isAllowed/isDenied/isDefault from EventBus
2024-09-12 14:34:23 +01:00
Paint_Ninja 8006e4ff48 Backport some Vanilla 1.21 ResourceLocation methods (#10084) 2024-09-12 14:32:28 +01:00
Paint_Ninja dd8e7ffd16 Optionally supply FMLJavaModLoadingContext as a param to mod constructors (backport of #10074 to 1.20.6) (#10083) 2024-09-12 14:01:15 +01:00
LexManos 976d710c10 Fix highlighted item tooltip rendering twice. Closes #10112 2024-09-11 10:27:53 -07:00
Paint_Ninja 1b44cda8ed Add missed @user_jvm_args.txt to run.bat (backport of 40a0a16 to 1.20.6) (#10092) 2024-09-10 13:56:48 +01:00
Martijn van den Brand 10bc7b8e2e Fire OnDatapackSyncEvent when a player joins a server (#10077) 2024-08-22 14:37:58 -07:00
LexManos 333a8e16ad Fix network channels not initializing during server transfers. Closes #10067 2024-08-17 13:06:27 -07:00
Martijn van den Brand 0554de0251 Fix onPlaceItemIntoWorld always resetting item stack when in creative mode (#10048) 2024-07-18 13:03:23 -07:00
Martijn van den Brand 845f315c47 Fix matrix stack translations for RenderHighlightEvent (#10051) 2024-07-18 13:03:09 -07:00
LexManos c6f3726b6d Make HangingSignBlockEntity useable with custom BlockEntityTypes. #10038 2024-07-05 11:05:21 -07:00
Jonathingandthedarkcolour 46ea9fca8e Choose default JarJar mod file type based on parent JAR Closes #9939 (#10021)
Co-authored-by: thedarkcolour <[email protected]>
2024-06-28 16:43:01 -07:00
JonathingandVen 0f2dac73ea Fixed falling block entities not rendering as moving blocks (#10006)
Co-authored-by: Ven <[email protected]>
2024-06-28 16:29:35 -07:00
Daniel Norris 576c61cf7d Fix conditional checking swallowing decoding errors when loading registry entries from datapacks. Fixes #9995 2024-06-19 15:15:48 -07:00
LexManos 5eb5c34636 Fix ClientTickEvent not firing properly. 2024-06-13 17:11:04 -07:00
Daniel Norris 8f17370cb7 Change tick event to have pre/post classes (#9890) 2024-06-13 15:07:48 -07:00
LexManos bc0c89ff69 Fix Bogged and Wolf armor not being shearable by custom shears. Closes #10005 2024-06-13 14:40:46 -07:00
Paint_Ninja 3d9e12a71d Cleanup FML Bindings (#10004) 2024-06-05 09:57:42 -07:00
LexManos cdeb786877 Fix NPE when calling ForgeHooks.getDefaultCreatorModId(ItemStack) on Spawn Eggs. Closes #10002 2024-06-04 15:48:07 -07:00
LexManos ff7085b95b Fix boat travel distance being incorrect. Closes #9997 2024-06-03 17:31:51 -07:00
LexManos 16dde4d551 1.20.6 RB 1
https://forums.minecraftforge.net/topic/149458-forge-501-minecraft-1206/
2024-06-03 13:15:55 -07:00
Paint_Ninja 60661350c6 Fix minor typo in MDK build.gradle 2024-06-03 20:53:10 +01:00
LexManos 7ee4a44c75 Fire EntityInteractSpecific on server side. Closes #9984 2024-06-03 12:33:53 -07:00
LexManos f22894cf70 Unlock wrapped registries when firing register events. 2024-06-03 12:31:59 -07:00
Paint_Ninja a3fce36942 Update Bootstrap to improve the Java version check error message (#9990) 2024-05-30 23:51:44 +01:00
Paint_Ninja 549dbe7df4 Minor cleanup to ModListScreen and VersionChecker (#9988) 2024-05-30 23:51:25 +01:00
Daniel Norris 5505e472aa Prevent the @OnlyIn being misused on @EventBusSubscriber and @Mod annotated classes (#9891) 2024-05-30 23:51:09 +01:00
Mysticdrew c2c7f9b656 Fix CustomizeGuiOverlayEvent.DebugText and CustomizeGuiOverlayEvent.Chat not being fired. (#9982) 2024-05-24 08:33:52 -07:00
LexManos fd8a0f9c8b Actually fix creative tab count, IDE didn't save the file before regenning patches. 2024-05-23 09:08:51 -07:00
LexManos 0ac873e296 Move Creative Inventory page count to fix issue with partially transparent tooltips. Closes #9983 2024-05-22 12:14:38 -07:00
LexManos 38b5b678cb Make OpenContainer and SpawnEntity packets process on main game thread. 2024-05-21 11:02:44 -07:00
LexManos 9a2bc1e7c2 Add File.exists check to ConfigFileTypeHandler. Closes #9976 2024-05-21 11:02:43 -07:00
RealMangoRage 95b49bedbc Fix crash when reloading a world that uses custom placed features. Closes #9979 2024-05-20 23:23:45 -07:00
LexManos 7c36115e3d Fix NPE in HurtByTargetGoal when mods set targets to null. Closes #7853 2024-05-20 16:21:17 -07:00
R0b0Li0n c037e6aca1 Fix RenderHandEvent firing with incorrect hand and item for offhand items. (#9977) 2024-05-20 11:50:09 -07:00
Mysticdrew e8f1b7ed6d Fix screen layering and re-add the test. (#9978) 2024-05-20 11:49:41 -07:00
RealMangoRage 5da16e6719 Add GatherComponentsEvent (#9944) 2024-05-14 23:02:58 -07:00
LexManos f0a82d79a6 Fix powered rails not propogating correctly. 2024-05-14 22:43:27 -07:00
LexManos 2b3a4137e1 Remove ICustomPacket and add PayloadChannel. (#9972)
New PayloadChannel that uses the vanilla payload Type for packet distinction
Implement the minecraft:register/unregister channels using the new PayloadChannel
New generic channel builder function allowing people to implement channels however they want.
2024-05-14 08:36:42 -07:00
LexManos 640c206117 Implement entity aware armor model and texture hooks. Closes #9960 2024-05-12 17:07:45 -07:00
LexManos 59a7bbdb57 Fix finalizeSpawn's return value not being used correctly. Closes #9964 2024-05-12 13:48:20 -07:00
LexManos be7ad14b4b Fix Biome patch change that caused our field redirect coremod to not function correctly. 2024-05-12 11:21:49 -07:00
LexManos c700b4ea9d Make RegistryObject.getHolder lazy, Should help cases where vanilla registries use holders from other vanilla registries. Closes #9961 2024-05-12 10:53:10 -07:00
LexManos dffa3dd4c9 Ignore jar files in the mods folder that are not Forge mods. Closes #9968 2024-05-12 03:36:22 -07:00
LexManos 4b934809c4 Fix canceling MobSpawnEvent.FinalizeSpawn causing a NPE closes #9971 2024-05-11 23:05:19 -07:00
LexManos ddf76db9b3 Fix potion brewing having arguments reversed. Closes #9970 2024-05-10 14:55:38 -07:00
LexManos 64d6b4f76a Fix Melons/Pumpkins not growing correctly. 2024-05-10 10:39:13 -07:00
Paint_Ninja 58012bfb17 Some patch cleanup (#9951) 2024-05-09 18:07:41 +01:00
LexManos 0cad6b14d9 Filter paths discovered by ServiceProvider in ClasspathLocator. Closes #9899 2024-05-09 09:39:25 -07:00
8848294210 Update SimpleChannel to make StreamCodecs easier (#9959)
Rework networking so that RegistryFriendlyByteBuf is useable for modders
Simple support for StreamCodec in SimpleChannel
Codecify all Forge packets
Make simpler builder pattern for SimpleChannel. Will eventually deprecate the old MessageBuilder as it's verbose and poorly written.

Co-authored-by: MrCrayfish <[email protected]>
Co-authored-by: Paint_Ninja <[email protected]>
2024-05-07 22:53:14 -07:00
LexManos 0e28336fc0 Fix shields not working correctly. Fixes #9966 2024-05-06 18:56:20 -07:00
LexManos 968fa9eeb5 Fix RenderTarget stencil patch location. Fixes #9965 2024-05-06 09:33:27 -07:00
EnZaXD 43768ea328 Add ModelLayers patch back (#9962) 2024-05-05 09:15:05 -07:00
LexManos 0e829630da Fix canApplyAtEnchantingTable null pointer, Closes #9956
Bump SecureModules for package info and multi-release jar fixes.
2024-05-03 14:10:17 -07:00
Paint_Ninja 0467d71466 Remove zombie chance config options (#9950) 2024-05-01 22:27:28 +01:00
Paint_Ninja 115eb5e4c8 Remove deprecated compressLanIPv6Addresses config option (#9949)
LAN IPv6 addresses are always compressed these days, so this config option is redundant
2024-05-01 22:27:16 +01:00
LexManos a7345372fd Fix custom payloads not being handled on the server in the game state. Closes #9948
Fix villagers not opening trade guis. Closes #9946
2024-05-01 13:16:41 -07:00
LexManos bd714b2f76 Fix MDK by bumping FG and disabling reobf tasks
Fix LAN server IPs being duplicated
Fix connecting to vanilla servers due to misapplied patch.
2024-05-01 11:28:43 -07:00
264 changed files with 7030 additions and 2208 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: Publish
on:
push:
branches: [ '1.20.x' ]
permissions:
contents: read
jobs:
build:
uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main
with:
java: 21
gradle_setup: './gradlew setup'
gradle_tasks: 'build publish'
artifact_name: 'forge'
secrets:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
PROMOTE_ARTIFACT_WEBHOOK: ${{ secrets.PROMOTE_ARTIFACT_WEBHOOK }}
PROMOTE_ARTIFACT_USERNAME: ${{ secrets.PROMOTE_ARTIFACT_USERNAME }}
PROMOTE_ARTIFACT_PASSWORD: ${{ secrets.PROMOTE_ARTIFACT_PASSWORD }}
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
SIGN_KEY_ALIAS: ${{ secrets.SIGN_KEY_ALIAS }}
SIGN_KEY_PASSWORD: ${{ secrets.SIGN_KEY_PASSWORD }}
SIGN_KEYSTORE_PASSWORD: ${{ secrets.SIGN_KEYSTORE_PASSWORD }}
SIGN_KEYSTORE_DATA: ${{ secrets.SIGN_KEYSTORE_DATA }}
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
name: Upload payload name: Upload payload
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/upload-artifact@v3 # Payload artifact is consumed in Actionable - uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
with: with:
name: payload name: payload
path: ${{ github.event_path }} path: ${{ github.event_path }}
@@ -7,7 +7,7 @@ jobs:
name: Upload payload name: Upload payload
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/upload-artifact@v3 # Payload artifact is consumed in Actionable - uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
with: with:
name: payload name: payload
path: ${{ github.event_path }} path: ${{ github.event_path }}
-104
View File
@@ -1,104 +0,0 @@
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<name>MinecraftForge_Forge Config DSL Script</name>
<groupId>MinecraftForge_Forge</groupId>
<artifactId>MinecraftForge_Forge_dsl</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jetbrains-all</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>teamcity-server</id>
<url>https://teamcity.minecraftforge.net/app/dsl-plugins-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>JetBrains</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>${basedir}</sourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration/>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>teamcity-configs-maven-plugin</artifactId>
<version>${teamcity.dsl.version}</version>
<configuration>
<format>kotlin</format>
<dstDir>target/generated-configs</dstDir>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin</artifactId>
<version>${teamcity.dsl.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-plugins</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-runtime</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
-193
View File
@@ -1,193 +0,0 @@
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.projectFeatures.githubIssues
import jetbrains.buildServer.configs.kotlin.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2021.2"
project {
buildType(Build)
buildType(BuildSecondaryBranches)
buildType(PullRequests)
buildType(PullRequestChecks)
buildType(PullRequestCompatibility)
params {
text("docker_jdk_version", "21", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_gradle_version", "8.7", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_main_branch", "1.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*)
+:refs/heads/(master*)
+:refs/heads/(develop|release|staging|main|master)
+:refs/heads/(1.*)
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
text("github_repository_name", "MinecraftForge", label = "The github repository name. Used to connect to it in VCS Roots.", description = "This is the repository slug on github. So for example `MinecraftForge` or `MinecraftForge`. It is interpolated into the global VCS Roots.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("env.PUBLISHED_JAVA_ARTIFACT_ID", "forge", label = "Published artifact id", description = "The maven coordinate artifact id that has been published by this build. Can not be empty.", allowEmpty = false)
text("env.PUBLISHED_JAVA_GROUP", "net.minecraftforge", label = "Published group", description = "The maven coordinate group that has been published by this build. Can not be empty.", allowEmpty = false)
//These are references and not actually keys
password("env.CROWDIN_KEY", "credentialsJSON:a3102dbe-805d-4177-9f54-3d2c2eb08fd5", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_URL", "credentialsJSON:a7ae1c82-8058-4061-8d12-7f6bc2618d2e", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_PASSWORD", "credentialsJSON:d7b964e3-a1fd-47a8-b892-6f601fe47479", display = ParameterDisplay.HIDDEN)
text("additional_publishing_gradle_parameters", "-PcrowdinKey=%env.CROWDIN_KEY% -PkeystoreKeyPass=%env.KEYSTORE_PASSWORD% -PkeystoreStorePass=%env.KEYSTORE_PASSWORD% -Pkeystore=%env.KEYSTORE_URL%", label = "Additional gradle parameters for publish", description = "Contains the additional gradle parameters used during publishing.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
checkbox("should_execute_build", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
checkbox("should_execute_test", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
}
features {
githubIssues {
id = "MinecraftForge_MinecraftForge__IssueTracker"
displayName = "MinecraftForge/MinecraftForge"
repositoryURL = "https://github.com/MinecraftForge/MinecraftForge"
}
}
}
object Build : BuildType({
templates(AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"), AbsoluteId("MinecraftForge_PublishProjectUsingGradle"), AbsoluteId("MinecraftForge_TriggersStaticFilesWebpageGenerator"))
id("MinecraftForge_MinecraftForge__Build")
name = "Build"
description = "Builds and Publishes the main branches of the project."
})
object BuildSecondaryBranches : BuildType({
templates(AbsoluteId("MinecraftForge_ExcludesBuildingDefaultBranch"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__BuildSecondaryBranches")
name = "Build - Secondary Branches"
description = "Builds and Publishes the secondary branches of the project."
params {
text("git_branch_spec", """
+:refs/heads/(*)
-:refs/heads/noci*
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequests : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequests")
name = "Pull Requests"
description = "Builds pull requests for the project"
params {
checkbox("should_execute_build", "true", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
text(
"gradle_build_task",
"assemble",
label = "Gradle build task to execute during build",
description = "Determines the build task that is executed to build the project.",
display = ParameterDisplay.HIDDEN,
allowEmpty = false
)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestChecks : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestChecks")
name = "Pull Requests (Checks)"
description = "Checks pull requests for the project"
steps {
gradle {
name = "Check"
id = "RUNNER_10_Check"
tasks = "checkAll"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestCompatibility : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestCompatibility")
name = "Pull Requests (Compatibility)"
description = "Validates binary compatibility for pull requests made to the project"
steps {
gradle {
name = "Validate"
id = "RUNNER_10_Compatibility"
tasks = "checkJarCompatibility"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
-65
View File
@@ -1,65 +0,0 @@
Minecraft Forge: Credits/Thank You
Forge is a set of tools and modifications to the Minecraft base game code to assist
mod developers in creating new and exciting content. It has been in development for
several years now, but I would like to take this time thank a few people who have
helped it along its way.
First, the people who originally created the Forge projects way back in Minecraft
alpha. Eloraam of RedPower, and SpaceToad of Buildcraft, without their acceptiance
of me taking over the project, who knows what Minecraft modding would be today.
Secondly, someone who has worked with me, and developed some of the core features
that allow modding to be as functional, and as simple as it is, cpw. For developing
FML, which stabilized the client and server modding ecosystem. As well as the base
loading system that allows us to modify Minecraft's code as elegently as possible.
Mezz, who has stepped up as the issue and pull request manager. Helping to keep me
sane as well as guiding the community into creating better additions to Forge.
Searge, Bspks, Fesh0r, ProfMobious, and all the rest over on the MCP team {of which
I am a part}. For creating some of the core tools needed to make Minecraft modding
both possible, and as stable as can be.
On that note, here is some specific information of the MCP data we use:
* Minecraft Coder Pack (MCP) *
Forge Mod Loader and Minecraft Forge have permission to distribute and automatically
download components of MCP and distribute MCP data files. This permission is not
transitive and others wishing to redistribute the Minecraft Forge source independently
should seek permission of MCP or remove the MCP data files and request their users
to download MCP separately.
And lastly, the countless community members who have spent time submitting bug reports,
pull requests, and just helping out the community in general. Thank you.
--LexManos
=========================================================================
This is Forge Mod Loader.
You can find the source code at all times at https://github.com/MinecraftForge/MinecraftForge/tree/1.12.x/src/main/java/net/minecraftforge/fml
This minecraft mod is a clean open source implementation of a mod loader for minecraft servers
and minecraft clients.
The code is authored by cpw.
It began by partially implementing an API defined by the client side ModLoader, authored by Risugami.
https://www.minecraftforum.net/topic/75440-
This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader.
It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge.
https://minecraftforge.net/
Additionally, it contains an implementation of topological sort based on that
published at http://keithschwarz.com/interesting/code/?dir=topological-sort
It also contains code from the Maven project for performing versioned dependency
resolution. http://maven.apache.org/
It also contains a partial repackaging of the javaxdelta library from http://sourceforge.net/projects/javaxdelta/
with credit to it's authors.
Forge Mod Loader downloads components from the Minecraft Coder Pack
(http://mcp.ocean-labs.de/index.php/Main_Page) with kind permission from the MCP team.
+3 -3
View File
@@ -4,9 +4,9 @@ repositories {
} }
dependencies { dependencies {
implementation 'org.ow2.asm:asm:9.7' implementation 'org.ow2.asm:asm:9.9.1'
implementation 'org.ow2.asm:asm-tree:9.7' implementation 'org.ow2.asm:asm-tree:9.9.1'
implementation 'net.minecraftforge:srgutils:0.5.10' implementation 'net.minecraftforge:srgutils:0.6.2'
implementation 'commons-io:commons-io:2.13.0' implementation 'commons-io:commons-io:2.13.0'
implementation 'com.google.code.gson:gson:2.10.1' implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r' implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r'
@@ -21,6 +21,8 @@ abstract class BundleList extends DefaultTask {
configure { configure {
dependsOn(project.tasks.universalJar) dependsOn(project.tasks.universalJar)
inputs.file(project.tasks.universalJar.archiveFile) inputs.file(project.tasks.universalJar.archiveFile)
dependsOn(project.tasks.applyServerBinPatches)
inputs.file(project.tasks.applyServerBinPatches.output)
} }
} }
@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
@Internal @Internal
@Override @Override
protected Object getData() { 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.')}()
} }
} }
@@ -140,7 +140,7 @@ abstract class CheckPatches extends CheckTask {
final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-') final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-')
if (!prevLineChange && !nextLineChange) { if (!prevLineChange && !nextLineChange) {
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath", false) 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)
} }
} }
+22 -12
View File
@@ -78,7 +78,6 @@ final String SPEC_VERSION = gradleutils.gitInfo.tag
final def MCP_ARTIFACT = project(':mcp').mcp.config.get() final def MCP_ARTIFACT = project(':mcp').mcp.config.get()
final List<File> EXTRA_TXTS = [ final List<File> EXTRA_TXTS = [
rootProject.file('CREDITS.txt'),
rootProject.file('LICENSE.txt'), rootProject.file('LICENSE.txt'),
rootProject.tasks.createChangelog.outputFile rootProject.tasks.createChangelog.outputFile
] ]
@@ -117,7 +116,7 @@ dependencies {
bootstrap(libs.unsafe) // Needed by securemodules bootstrap(libs.unsafe) // Needed by securemodules
bootstrap(libs.bundles.asm) // Needed by securemodules bootstrap(libs.bundles.asm) // Needed by securemodules
implementation(libs.jopt.simple) { version { strictly '5.0.4' } } implementation(libs.jopt.simple)
installer(libs.bootstrap) installer(libs.bootstrap)
installer(libs.bootstrap.api) // Needed by securemodules installer(libs.bootstrap.api) // Needed by securemodules
@@ -180,6 +179,7 @@ patcher {
forge_client_test { forge_client_test {
parent runs.forge_client parent runs.forge_client
source sourceSets.test
} }
forge_server { forge_server {
@@ -188,6 +188,7 @@ patcher {
forge_server_test { forge_server_test {
parent runs.forge_server parent runs.forge_server
source sourceSets.test
} }
forge_server_gametest { forge_server_gametest {
@@ -196,6 +197,7 @@ patcher {
forge_server_gametest_test { forge_server_gametest_test {
parent runs.forge_server_gametest parent runs.forge_server_gametest
source sourceSets.test
} }
forge_data { forge_data {
@@ -211,6 +213,7 @@ patcher {
} }
forge_data_test { forge_data_test {
source sourceSets.test
args '--launchTarget', 'forge_dev_data', args '--launchTarget', 'forge_dev_data',
'--mod', '.+', '--mod', '.+',
'--all', '--all',
@@ -221,7 +224,6 @@ patcher {
'--assetsDir', downloadAssets.output, '--assetsDir', downloadAssets.output,
'--assetIndex', "{asset_index}" '--assetIndex', "{asset_index}"
} }
} }
} }
@@ -480,10 +482,10 @@ tasks.register('createServerShimClasspath', BundleList) {
tasks.register('createServerShimConfig') { tasks.register('createServerShimConfig') {
ext.output = file('build/libs/bootstrap-shim.properties') ext.output = file('build/libs/bootstrap-shim.properties')
doLast { doLast {
def cfg = new CleanProperties() var cfg = new CleanProperties()
cfg."Main-Class" = 'net.minecraftforge.bootstrap.ForgeBootstrap' cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg."Java-Version" = '17' cfg['Java-Version'] = '21'
cfg."Arguments" = "--launchTarget forge_server" cfg['Arguments'] = '--launchTarget forge_server'
cfg.store(output) cfg.store(output)
} }
} }
@@ -918,23 +920,31 @@ tasks.register('installerJar', InstallerJar) {
jarSigner.sign(it) jarSigner.sign(it)
} }
final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) {
gradleVersion = '9.3.1'
}
tasks.register('mdkZip', Zip) { tasks.register('mdkZip', Zip) {
dependsOn mdkGradleWrapper
archiveBaseName = project.name archiveBaseName = project.name
archiveClassifier = 'mdk' archiveClassifier = 'mdk'
archiveVersion = project.version archiveVersion = project.version
destinationDirectory = file('build/libs') destinationDirectory = file('build/libs')
from rootProject.file('gradlew') from mdkGradleWrapper.map(Wrapper.&getScriptFile)
from rootProject.file('gradlew.bat') from mdkGradleWrapper.map(Wrapper.&getBatchScript)
from(EXTRA_TXTS) from(EXTRA_TXTS)
from(rootProject.file('gradle/')){ into('gradle/wrapper/') {
into('gradle/') from mdkGradleWrapper.map(Wrapper.&getJarFile)
from mdkGradleWrapper.map(Wrapper.&getPropertiesFile)
} }
from(rootProject.file('mdk/')){ from(rootProject.file('mdk/')){
rootProject.file('mdk/gitignore.txt').eachLine{ rootProject.file('mdk/gitignore.txt').eachLine {
if (!it.trim().isEmpty() && !it.trim().startsWith('#')) if (!it.trim().isEmpty() && !it.trim().startsWith('#'))
exclude it exclude it
} }
filter(ReplaceTokens, tokens: [ filter(ReplaceTokens, tokens: [
FORGE_VERSION: FORGE_VERSION, FORGE_VERSION: FORGE_VERSION,
FORGE_GROUP: project.group, FORGE_GROUP: project.group,
+8
View File
@@ -74,3 +74,11 @@ eclipse {
// Run when importing the project // Run when importing the project
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject 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 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.2-&query=$.promos["1.20.2-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download] [![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.3-&query=$.promos["1.20.3-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo= [![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=
)][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] )][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! Forge is a free, open-source modding API all of your favourite mods use!
| Version | Support | | Version | Support |
|---------| ------------- | |--------------|-----------------------------|
| 1.20.x | Active | | All versions | [Supported][Support-Policy] |
| 1.19.x | Legacy |
* [Download] * [Download]
* [Forum] * [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]. 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 # Creating Mods
[See the "Getting Started" section in the Forge Documentation][Getting-Started]. [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/ [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/ [Forum]: https://forums.minecraftforge.net/
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/ [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/ [Discord]: https://discord.minecraftforge.net/
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
for file in $(find repo | grep --invert-match -e md5 -e sha | grep -e .jar -e .zip); do
file_path=$(realpath $file)
file_name=$(basename $file)
echo "$file_name"
files=$(unzip -l $file | awk '{print $4}')
for f in $files; do
out="_actual/$file_name/$f"
parent=$(dirname "$out")
echo $out
if [ ! -d "$parent" ]; then
mkdir -p "$parent"
fi
if [[ $f == *.class ]]; then
javap -v -p jar:file://$file_path!/$f | tail -n +4 >$out.txt
elif [[ $f != */ && $f != "Name" && $f != "----" ]]; then
unzip -o -q $file $f -d _actual/$file_name
fi
done
done
@@ -9,41 +9,35 @@ import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.config.IConfigEvent; import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.FMLLoader;
import java.util.ArrayList;
import java.util.ServiceConfigurationError; import java.util.ServiceConfigurationError;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.function.Supplier; import java.util.function.Supplier;
/**
* Used to allow access to certain things from the game layer
*/
public class Bindings { public class Bindings {
private static final Bindings INSTANCE = new Bindings(); private Bindings() {}
private final IBindingsProvider provider; /**
* The provider of the bindings
private Bindings() { * @implNote May also throw a {@link ServiceConfigurationError}
var providers = new ArrayList<IBindingsProvider>(1); */
for (var itr = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class).iterator(); itr.hasNext(); ) { private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
try { .findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
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);
}
/**
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
*/
public static Supplier<IEventBus> getForgeBus() { public static Supplier<IEventBus> getForgeBus() {
return INSTANCE.provider.getForgeBusSupplier(); return PROVIDER.getForgeBusSupplier();
} }
public static Supplier<I18NParser> getMessageParser() { public static Supplier<I18NParser> getMessageParser() {
return INSTANCE.provider.getMessageParser(); return PROVIDER.getMessageParser();
} }
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() { public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
return INSTANCE.provider.getConfigConfiguration(); return PROVIDER.getConfigConfiguration();
} }
} }
@@ -16,8 +16,7 @@ import net.minecraftforge.api.distmarker.Dist;
* *
* @see 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 * The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
* viewpoint. * viewpoint.
@@ -27,6 +26,7 @@ public enum LogicalSide
* @see Dist#CLIENT * @see Dist#CLIENT
*/ */
CLIENT, CLIENT,
/** /**
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic * The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
* on the level. * on the level.
@@ -41,16 +41,14 @@ public enum LogicalSide
/** /**
* {@return if this logical side is the server} * {@return if this logical side is the server}
*/ */
public boolean isServer() public boolean isServer() {
{
return !isClient(); return !isClient();
} }
/** /**
* {@return if the logical side is the client} * {@return if the logical side is the client}
*/ */
public boolean isClient() public boolean isClient() {
{
return this == CLIENT; return this == CLIENT;
} }
} }
@@ -19,28 +19,45 @@ public class ModLoadingContext
{ {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new); private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
private ModContainer activeContainer;
private Object languageExtension; private Object languageExtension;
private ModLoadingStage stage; 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() { public static ModLoadingContext get() {
return context.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) { public void setActiveContainer(final ModContainer container) {
this.activeContainer = container; this.activeContainer = container;
this.languageExtension = container == null ? null : container.contextExtension.get(); this.languageExtension = container == null ? null : container.contextExtension.get();
} }
/**
* Going to be moved to ForgeHooks for internal use.
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public ModContainer getActiveContainer() { public ModContainer getActiveContainer() {
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer; return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
} }
@Deprecated(forRemoval = true, since = "1.21.1")
public String getActiveNamespace() { public String getActiveNamespace() {
return activeContainer == null ? "minecraft" : activeContainer.getNamespace(); return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
} }
public ModContainer getContainer() {
return getActiveContainer();
}
/** /**
* Register an {@link IExtensionPoint} with the mod container. * Register an {@link IExtensionPoint} with the mod container.
* @param point The extension point to register * @param point The extension point to register
@@ -48,7 +65,7 @@ public class ModLoadingContext
* @param <T> The type signature of the extension operator * @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) { 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 +74,7 @@ public class ModLoadingContext
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register * @param displayTest The {@link IExtensionPoint.DisplayTest} to register
*/ */
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) { public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
getActiveContainer().registerDisplayTest(() -> displayTest); getContainer().registerDisplayTest(() -> displayTest);
} }
/** /**
@@ -66,7 +83,7 @@ public class ModLoadingContext
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register * @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
*/ */
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) { public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
getActiveContainer().registerDisplayTest(displayTest); getContainer().registerDisplayTest(displayTest);
} }
/** /**
@@ -76,7 +93,7 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate) * @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
*/ */
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) { public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest)); getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
} }
/** /**
@@ -86,32 +103,31 @@ public class ModLoadingContext
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate) * @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
*/ */
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) { 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) { public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty()) if (spec.isEmpty())
{ {
// This handles the case where a mod tries to register a config, without any options configured inside it. // This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getActiveContainer().getModId()); LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
return; 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) { public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
if (spec.isEmpty()) if (spec.isEmpty())
{ {
// This handles the case where a mod tries to register a config, without any options configured inside it. // This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getActiveContainer().getModId(), fileName); LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
return; return;
} }
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName)); getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T extension() { public <T> T extension() {
return (T)languageExtension; return (T)languageExtension;
@@ -48,8 +48,8 @@ public class VersionChecker {
BETA(), BETA(),
BETA_OUTDATED(6, true, true); BETA_OUTDATED(6, true, true);
final int sheetOffset; private final int sheetOffset;
final boolean draw, animated; private final boolean draw, animated;
Status() { Status() {
this(0, false, false); this(0, false, false);
@@ -72,6 +72,10 @@ public class VersionChecker {
public boolean isAnimated() { public boolean isAnimated() {
return animated; return animated;
} }
public boolean isOutdated() {
return this == OUTDATED || this == BETA_OUTDATED;
}
} }
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {} public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {}
@@ -211,7 +215,7 @@ public class VersionChecker {
LOGGER.warn("Failed to process update information", e); LOGGER.warn("Failed to process update information", e);
status = FAILED; status = FAILED;
} }
results.put(mod, new CheckResult(status, target, changes, display_url)); RESULTS.put(mod, new CheckResult(status, target, changes, display_url));
} }
}.start(); }.start();
} }
@@ -226,10 +230,10 @@ public class VersionChecker {
return ret; return ret;
} }
private static Map<IModInfo, CheckResult> results = new ConcurrentHashMap<>(); private static final Map<IModInfo, CheckResult> RESULTS = new ConcurrentHashMap<>();
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null); private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
public static CheckResult getResult(IModInfo mod) { public static CheckResult getResult(IModInfo mod) {
return results.getOrDefault(mod, PENDING_CHECK); return RESULTS.getOrDefault(mod, PENDING_CHECK);
} }
} }
@@ -67,7 +67,9 @@ public class ConfigFileTypeHandler {
} }
private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException { private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
Files.createDirectories(file.getParent()); if (!Files.isDirectory(file.getParent())) {
Files.createDirectories(file.getParent());
}
Path p = defaultConfigPath.resolve(modConfig.getFileName()); Path p = defaultConfigPath.resolve(modConfig.getFileName());
if (Files.exists(p)) { if (Files.exists(p)) {
LOGGER.info(CONFIG, "Loading default config file from path {}", 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; import java.lang.management.MemoryUsage;
public class PerformanceInfo { public class PerformanceInfo {
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
private final boolean showCPUUsage; private final boolean showCPUUsage;
private final OperatingSystemMXBean osBean; private final OperatingSystemMXBean osBean;
private final MemoryMXBean memoryBean;
private float memory; private float memory;
private String text; private String text;
@@ -24,15 +24,14 @@ public class PerformanceInfo {
PerformanceInfo() { PerformanceInfo() {
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU); showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null; osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
memoryBean = ManagementFactory.getMemoryMXBean();
} }
void update() { void update() {
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage(); final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
memory = (float) heapusage.getUsed() / heapusage.getMax(); memory = (float) heapusage.getUsed() / heapusage.getMax();
if (!showCPUUsage) { 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; return;
} }
@@ -44,7 +43,7 @@ public class PerformanceInfo {
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f); 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() { String text() {
@@ -36,9 +36,9 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
*/ */
public class CapabilityTokenSubclass implements ILaunchPluginService { public class CapabilityTokenSubclass implements ILaunchPluginService {
private final String FUNC_NAME = "getType"; private static final String FUNC_NAME = "getType";
private final String FUNC_DESC = "()Ljava/lang/String;"; private static 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 CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
@Override @Override
public String name() { public String name() {
@@ -51,7 +51,14 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
@Override @Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) 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 @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. SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9) reader.accept(new SignatureVisitor(Opcodes.ASM9)
{ {
Deque<String> stack = new ArrayDeque<>(); final Deque<String> stack = new ArrayDeque<>();
@Override @Override
public void visitClassType(final String name) 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; String value;
} }
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; 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.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent") new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toMap(VanillaObjectHolderData::holderClass, Function.identity())); ).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 @Override
public String name() { public String name() {
@@ -46,13 +51,29 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class); private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override @Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
{ if (isEmpty)
return isEmpty ? NAY : YAY; 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)); 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(); final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects //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 //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; int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final 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! 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; int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; f.access &= ~Opcodes.ACC_FINAL;
@@ -28,15 +28,16 @@ import org.slf4j.Logger;
public class RuntimeEnumExtender implements ILaunchPluginService { public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private final Type STRING = Type.getType(String.class); private static final Type STRING = Type.getType(String.class);
private final Type ENUM = Type.getType(Enum.class); private static final Type ENUM = Type.getType(Enum.class);
private final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;"); private static 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 static 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 static 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 static 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 static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private final String NAME_DESC = Type.getMethodDescriptor(STRING); private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, 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 @Override
public String name() { public String name() {
@@ -47,9 +48,15 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class); private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override @Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
{ if (isEmpty)
return isEmpty ? NAY : YAY; return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
} }
@Override @Override
@@ -58,25 +65,24 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if ((classNode.access & Opcodes.ACC_ENUM) == 0) if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return ComputeFlags.NO_REWRITE; return ComputeFlags.NO_REWRITE;
Type array = Type.getType("[" + classType.getDescriptor()); if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
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())) {
return ComputeFlags.NO_REWRITE; 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 //Static methods named "create" with first argument as a string
List<MethodNode> candidates = classNode.methods.stream() List<MethodNode> candidates = classNode.methods.stream()
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create")) .filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
.collect(Collectors.toList()); .toList();
if (candidates.isEmpty()) { if (candidates.isEmpty()) {
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName()); throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
} }
candidates.forEach(mtd -> for (var mtd : candidates)
{ {
Type[] args = Type.getArgumentTypes(mtd.desc); Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING)) { if (args.length == 0 || !args[0].equals(STRING)) {
@@ -108,8 +114,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
Type[] ctrArgs = new Type[args.length + 1]; Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING; ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE; ctrArgs[1] = Type.INT_TYPE;
for (int x = 1; x < args.length; x++) System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
ctrArgs[1 + x] = args[x];
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs); String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
@@ -231,7 +236,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
ins.load(vars, classType); ins.load(vars, classType);
ins.areturn(classType); ins.areturn(classType);
} }
}); }
return ComputeFlags.COMPUTE_FRAMES; return ComputeFlags.COMPUTE_FRAMES;
} }
@@ -57,6 +57,9 @@ public class FMLLoader {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo); LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion()); LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
// Allows us to communicate properties with other services through ModLauncher
setupBlackboardKeys();
checkPackage(ITransformationService.class, "4.0", "ModLauncher"); checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer"); accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus"); /*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
@@ -120,6 +123,12 @@ public class FMLLoader {
return providers.get(0); 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) { static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING"); final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget); arguments.put("launchTarget", launchTarget);
@@ -181,7 +190,7 @@ public class FMLLoader {
} }
public static void addAccessTransformer(Path atPath, ModFile modName) { public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath()); LOGGER.debug(SCAN, "Adding Access Transformer {} in {}", atPath, modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName()); accessTransformer.offerResource(atPath, modName.getFileName());
} }
@@ -5,12 +5,14 @@
package net.minecraftforge.fml.loading; package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils; import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler; import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModFile; import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo; import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import org.slf4j.Logger;
import java.net.URL; import java.net.URL;
import java.nio.file.Files; import java.nio.file.Files;
@@ -30,6 +32,7 @@ import java.util.stream.Collectors;
*/ */
public class LoadingModList public class LoadingModList
{ {
private static final Logger LOGGER = LogUtils.getLogger();
private static LoadingModList INSTANCE; private static LoadingModList INSTANCE;
private final List<ModFileInfo> modFiles; private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList; private final List<ModInfo> sortedList;
@@ -78,9 +81,22 @@ public class LoadingModList
public void addAccessTransformers() public void addAccessTransformers()
{ {
modFiles.stream() var errors = new ArrayList<EarlyLoadingException.ExceptionData>();
.map(ModFileInfo::getFile) for (ModFileInfo modFile : modFiles) {
.forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod))); ModFile mod = modFile.getFile();
for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message);
} else {
FMLLoader.addAccessTransformer(at, mod);
}
}
}
if (!errors.isEmpty()) {
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
} }
public void addForScanning(BackgroundScanHandler backgroundScanHandler) public void addForScanning(BackgroundScanHandler backgroundScanHandler)
@@ -10,6 +10,8 @@ import cpw.mods.jarhandling.SecureJar;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils; import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import cpw.mods.modlauncher.api.NamedPath; import cpw.mods.modlauncher.api.NamedPath;
import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService; import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService;
import org.jetbrains.annotations.ApiStatus;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.IOException; import java.io.IOException;
@@ -20,6 +22,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ApiStatus.Internal
public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService { public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final Set<String> SERVICES = Set.of( private static final Set<String> SERVICES = Set.of(
@@ -76,4 +79,15 @@ public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService
.filter(SERVICES::contains) .filter(SERVICES::contains)
.forEach(s -> found.add(new NamedPath(s, path))); .forEach(s -> found.add(new NamedPath(s, path)));
} }
public static boolean isServiceProvider(Path path) {
var jar = SecureJar.from(path);
for (var providers : jar.moduleDataProvider().descriptor().provides()) {
if (SERVICES.contains(providers.service()))
return true;
}
return false;
}
} }
@@ -34,8 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.Marker; import org.slf4j.Marker;
import org.slf4j.MarkerFactory; import org.slf4j.MarkerFactory;
public class RuntimeDistCleaner implements ILaunchPluginService public final class RuntimeDistCleaner implements ILaunchPluginService {
{
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM"); private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
private static String DIST; private static String DIST;
@@ -57,11 +56,17 @@ public class RuntimeDistCleaner implements ILaunchPluginService
throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST); throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST);
} }
if (!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 ) if (classNode.interfaces != null )
{ {
unpack(classNode.visibleAnnotations).stream() unpack(classNode.visibleAnnotations).stream()
.filter(ann->Objects.equals(ann.desc, ONLYIN)) .filter(ann->Objects.equals(ann.desc, ONLYIN))
.filter(ann->ann.values.indexOf("_interface") != -1) .filter(ann-> ann.values.contains("_interface"))
.filter(ann->!Objects.equals(((String[])ann.values.get(ann.values.indexOf("value") + 1))[1], DIST)) .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()) .map(ann -> ((Type)ann.values.get(ann.values.indexOf("_interface") + 1)).getInternalName())
.forEach(intf -> { .forEach(intf -> {
@@ -137,22 +142,78 @@ public class RuntimeDistCleaner implements ILaunchPluginService
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns) { 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()); if (anns == null)
anns.stream().filter(ann->Objects.equals(ann.desc, ONLYINS) && ann.values != null) {
.map( ann -> (List<AnnotationNode>)ann.values.get(ann.values.indexOf("value") + 1)) return Collections.emptyList();
.filter(v -> v != null) }
.forEach(v -> v.forEach(ret::add));
return ret; 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 boolean remove(final List<AnnotationNode> anns, final String side) private static boolean remove(final List<AnnotationNode> anns, final String side)
{ {
return unpack(anns).stream(). var onlyIns = unpack(anns);
filter(ann->Objects.equals(ann.desc, ONLYIN)).
filter(ann->ann.values.indexOf("_interface") == -1). for (var onlyIn : onlyIns)
anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side)); {
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 static 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;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -169,9 +230,19 @@ public class RuntimeDistCleaner implements ILaunchPluginService
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class); private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override @Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
{ if (isEmpty)
return isEmpty ? NAY : YAY; return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/"))
return NAY;
// No Vanilla classes use @OnlyIn(Dist.SERVER), so we can skip them entirely when we're running on a client
if (FMLEnvironment.dist.isClient() && (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/")))
return NAY;
return YAY;
} }
private static class LambdaGatherer extends MethodVisitor { private static class LambdaGatherer extends MethodVisitor {
@@ -8,7 +8,6 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.JarMetadata; import cpw.mods.jarhandling.JarMetadata;
import cpw.mods.jarhandling.SecureJar; import cpw.mods.jarhandling.SecureJar;
import net.minecraftforge.fml.loading.EarlyLoadingException;
import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.IConfigurable; import net.minecraftforge.forgespi.language.IConfigurable;
import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.language.IModFileInfo;
@@ -19,6 +18,7 @@ import net.minecraftforge.forgespi.locating.IModProvider;
import net.minecraftforge.forgespi.locating.ModFileLoadingException; import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.IOException; import java.io.IOException;
@@ -37,6 +37,16 @@ public abstract class AbstractModProvider implements IModProvider {
protected static final String MODS_TOML = "META-INF/mods.toml"; protected static final String MODS_TOML = "META-INF/mods.toml";
protected IModLocator.ModFileOrException createMod(Path path) { protected IModLocator.ModFileOrException createMod(Path path) {
return createMod(path, false);
}
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown) {
return createMod(path, false, getDefaultJarModType());
}
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) {
var mjm = new ModJarMetadata(); var mjm = new ModJarMetadata();
var sj = SecureJar.from( var sj = SecureJar.from(
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path), jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
@@ -46,7 +56,7 @@ public abstract class AbstractModProvider implements IModProvider {
IModFile mod; IModFile mod;
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE); var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
if (type == null) if (type == null)
type = getDefaultJarModType(); type = defaultType;
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) { if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path); LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
@@ -58,6 +68,8 @@ public abstract class AbstractModProvider implements IModProvider {
} else if (type != null) { } else if (type != null) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path); LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path);
mod = new ModFile(sj, this, this::manifestParser, type); mod = new ModFile(sj, this, this::manifestParser, type);
} else if (ignoreUnknown) {
return null;
} else } else
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path)); return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.fml.loading.ModDirTransformerDiscoverer;
import net.minecraftforge.forgespi.locating.IModLocator; import net.minecraftforge.forgespi.locating.IModLocator;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@@ -71,8 +72,11 @@ public class ClasspathLocator extends AbstractModProvider implements IModLocator
} }
var ret = new ArrayList<ModFileOrException>(); var ret = new ArrayList<ModFileOrException>();
for (var path : claimed) for (var path : claimed) {
ret.add(createMod(path)); // Filter out anything found by the ServiceLoader
if (!ModDirTransformerDiscoverer.isServiceProvider(path))
ret.add(createMod(path));
}
return ret; return ret;
} }
@@ -83,7 +83,14 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile); final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs); final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
final Path pathInFS = zipFS.getPath("/"); 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, false, modType).file());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName()); LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName()); final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
@@ -52,6 +52,7 @@ public class ModFile implements IModFile {
private CompletableFuture<ModFileScanData> futureScanResult; private CompletableFuture<ModFileScanData> futureScanResult;
private List<CoreModFile> coreMods; private List<CoreModFile> coreMods;
private Path accessTransformer; private Path accessTransformer;
private List<Path> accessTransformers = Collections.emptyList();
static final Attributes.Name TYPE = new Attributes.Name("FMLModType"); static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
private SecureJar.Status securityStatus; private SecureJar.Status securityStatus;
@@ -94,9 +95,15 @@ public class ModFile implements IModFile {
public List<IModInfo> getModInfos() { public List<IModInfo> getModInfos() {
return modFileInfo.getMods(); return modFileInfo.getMods();
} }
/** @deprecated Use {@link #getAccessTransformers()} instead*/
@Deprecated(forRemoval=true, since="1.21.11")
public Optional<Path> getAccessTransformer() { public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(Files.exists(accessTransformer) ? accessTransformer : null); return Optional.ofNullable(accessTransformer);
}
public List<Path> getAccessTransformers() {
return accessTransformers;
} }
public boolean identifyMods() { public boolean identifyMods() {
@@ -105,7 +112,28 @@ public class ModFile implements IModFile {
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders()); LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
this.coreMods = ModFileParser.getCoreMods(this); this.coreMods = ModFileParser.getCoreMods(this);
this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath())); this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath()));
this.accessTransformer = findResource("META-INF", "accesstransformer.cfg"); List<String> cfg;
// Note: Some mods may have invalid tomls copied from other projects.
// Unfortunately we must protect against those landmines.
try {
cfg = this.modFileInfo.getConfig().<List<String>>getConfigElement("accessTransformers").orElse(null);
} catch (Exception e) {
cfg = null;
LOGGER.warn("{} contains an invalid 'accessTransformers' TOML entry. Should be e.g. accessTransformers = [\"META-INF/accesstransformer.cfg\", \"META-INF/extra_at.cfg\"] or accessTransformers = [] for no ATs. Falling back to default.", this.getFileName());
}
if (cfg == null) {
var path = findResource("META-INF", "accesstransformer.cfg");
if (Files.exists(path)) {
this.accessTransformer = path;
this.accessTransformers = List.of(path);
}
} else if (!cfg.isEmpty()) {
var paths = new ArrayList<Path>(cfg.size());
for (var path : cfg) {
paths.add(getSecureJar().getPath(path.replace("\\","/")));
}
this.accessTransformers = List.copyOf(paths);
}
return true; return true;
} }
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.loading.moddiscovery; package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.file.FileConfig; import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
@@ -13,6 +14,7 @@ import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.ModFileFactory; import net.minecraftforge.forgespi.locating.ModFileFactory;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -31,6 +33,7 @@ public class ModFileParser {
return parser.build(modFile); return parser.build(modFile);
} }
// Note: Although @Nullable, several other places in FML assume ModFileInfo is not null. Keep this in mind
public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) { public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) {
ModFile modFile = (ModFile) imodFile; ModFile modFile = (ModFile) imodFile;
LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath()); LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath());
@@ -41,10 +44,15 @@ public class ModFileParser {
} }
final FileConfig fileConfig = FileConfig.builder(modsjson).build(); final FileConfig fileConfig = FileConfig.builder(modsjson).build();
fileConfig.load(); try {
fileConfig.close(); fileConfig.load();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig); fileConfig.close();
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile); final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
} catch (ParsingException e) {
LOGGER.error("Mod candidate {} contains a corrupt or misconfigured toml.", modFile.getFileName());
throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains a corrupt or misconfigured toml.");
}
} }
protected static List<CoreModFile> getCoreMods(final ModFile modFile) { protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
@@ -16,6 +16,7 @@ import org.slf4j.Logger;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@@ -42,11 +43,21 @@ public class ModsFolderLocator extends AbstractModProvider implements IModLocato
public List<IModLocator.ModFileOrException> scanMods() { public List<IModLocator.ModFileOrException> scanMods() {
LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder); LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder);
var excluded = ModDirTransformerDiscoverer.allExcluded(); var excluded = ModDirTransformerDiscoverer.allExcluded();
try (var stream = Files.list(this.modFolder)) { try {
return stream.filter(path -> !excluded.contains(path) && path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(SUFFIX)) var ret = new ArrayList<IModLocator.ModFileOrException>();
.sorted(Comparator.comparing(path -> path.getFileName().toString().toLowerCase(Locale.ROOT))) var files = Files.list(this.modFolder).toList();
.map(this::createMod) for (var file : files) {
.toList(); 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;
} catch (IOException e) { } catch (IOException e) {
return sneak(e); return sneak(e);
} }
@@ -48,7 +48,7 @@ class Scanner {
try (InputStream in = Files.newInputStream(path)){ try (InputStream in = Files.newInputStream(path)){
ModClassVisitor mcv = new ModClassVisitor(); ModClassVisitor mcv = new ModClassVisitor();
ClassReader cr = new ClassReader(in); 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()); mcv.buildData(result.getClasses(), result.getAnnotations());
} catch (IOException | IllegalArgumentException e) { } catch (IOException | IllegalArgumentException e) {
// mark path bad // mark path bad
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists 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 networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+13 -9
View File
@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} 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. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -130,10 +131,13 @@ location of your Java installation."
fi fi
else else
JAVACMD=java 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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # 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 ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # 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" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac 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. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command:
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# shell script including quotes and variable substitutions, so put them in # and any embedded shellness will be escaped.
# double quotes to make sure that they get re-expanded; and # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# * put everything else in single quotes, so that it's not re-expanded. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
Vendored
+10 -10
View File
@@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.javafmlmod; package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.Logging; import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
@@ -19,19 +20,21 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Automatic eventbus subscriber - reads {@link EventBusSubscriber} * 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} * defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/ */
public class AutomaticEventSubscriber { public class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class); private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.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) { public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
if (scanData == null) return; if (scanData == null) return;
@@ -41,6 +44,11 @@ public class AutomaticEventSubscriber {
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType())) .filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
.toList(); .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() var modids = scanData.getAnnotations().stream()
.filter(data -> MOD_TYPE.equals(data.annotationType())) .filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value"))); .collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
@@ -49,6 +57,10 @@ public class AutomaticEventSubscriber {
var defaultBus = new EnumData(null, "FORGE"); var defaultBus = new EnumData(null, "FORGE");
for (var data : targets) { 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()); var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId); modId = value(data, "modid", modId);
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.ModLoadingContext;
public class FMLJavaModLoadingContext public class FMLJavaModLoadingContext extends ModLoadingContext
{ {
private final FMLModContainer container; private final FMLModContainer container;
@@ -24,11 +24,18 @@ public class FMLJavaModLoadingContext
return container.getEventBus(); return container.getEventBus();
} }
@Override
public FMLModContainer getContainer() {
return container;
}
/** /**
* Helper to get the right instance from the {@link ModLoadingContext} correctly. * Helper to get the right instance from the {@link ModLoadingContext} correctly.
* @return The FMLJavaMod language specific extension from the ModLoadingContext * @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() { public static FMLJavaModLoadingContext get() {
return ModLoadingContext.get().extension(); 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.Marker;
import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.MarkerManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -32,6 +33,7 @@ public class FMLModContainer extends ModContainer {
private final IEventBus eventBus; private final IEventBus eventBus;
private Object modInstance; private Object modInstance;
private final Class<?> modClass; private final Class<?> modClass;
private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this);
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) { public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) {
super(info); super(info);
@@ -40,9 +42,7 @@ public class FMLModContainer extends ModContainer {
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod); activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build(); this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self())); this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this); this.contextExtension = () -> context;
this.contextExtension = () -> contextExtension;
try { try {
var moduleName = info.getOwningFile().moduleName(); var moduleName = info.getOwningFile().moduleName();
@@ -63,7 +63,13 @@ public class FMLModContainer extends ModContainer {
private void constructMod() { private void constructMod() {
try { try {
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName()); 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()); LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
} catch (Throwable e) { } catch (Throwable e) {
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the // When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
+29 -179
View File
@@ -1,212 +1,62 @@
// This is a minimal setup of a Forge mod workspace.
// For complex examples (including AccessTransformers, Jar-in-Jar, and Mixin), see our examples repository.
// https://github.com/MinecraftForge/MDKExamples
plugins { plugins {
id 'eclipse' id 'java'
id 'idea' id 'idea'
id 'maven-publish' id 'eclipse'
id 'net.minecraftforge.gradle' version '[6.0.16,6.2)' id 'net.minecraftforge.gradle' version '[7.0.3,8)'
} }
version = mod_version version = '1.0.0'
group = mod_group_id group = 'com.example.examplemod'
base {
archivesName = mod_id
}
// Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21. // Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21) java.toolchain.languageVersion = JavaLanguageVersion.of(21)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" // Include generated resources
sourceSets.main.resources { srcDir 'src/generated/resources' }
minecraft { minecraft {
// The mappings can be changed at any time and must be in the following format. mappings channel: 'official', version: '@MC_VERSION@'
// Channel: Version:
// official MCVersion Official field/method names from Mojang mapping files
// parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official
//
// You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started
//
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
// In most cases, it is not necessary to enable.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game.
// It is REQUIRED to be set to true for this template to function.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// When true, this property will add the folder name of all declared run configurations to generated IDE run configurations.
// The folder name can be set on a run configuration using the "folderName" property.
// By default, the folder name of a run configuration is the name of the Gradle project containing it.
// generateRunFolders = true
// This property enables access transformers for use in development.
// They will be applied to the Minecraft artifact.
// The access transformer file can be anywhere in the project.
// However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge.
// This default location is a best practice to automatically put the file in the right place in the final jar.
// See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs { runs {
// applies to all the run configs below
configureEach { configureEach {
workingDirectory project.file('run') workingDir = layout.projectDirectory.dir('run')
// Recommended logging data for a userdev environment systemProperty 'forge.enabledGameTestNamespaces', 'examplemod'
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
} }
client { register('client')
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
}
server { register('server') {
property 'forge.enabledGameTestNamespaces', mod_id
args '--nogui' args '--nogui'
} }
// This run config launches GameTestServer and runs all registered gametests, then exits. register('gameTestServer')
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
property 'forge.enabledGameTestNamespaces', mod_id
}
data { register('data') {
// example of overriding the workingDirectory set in configureEach above workingDir = layout.projectDirectory.dir('run-data')
workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. args '--mod', 'examplemod', '--all', '--output', layout.projectDirectory.dir('src/generated/resources'), '--existing', layout.projectDirectory.dir('src/main/resources')
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
} }
} }
} }
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories { repositories {
// Put repositories for dependencies here minecraft.mavenizer(it) // In Kotlin, it = this
// ForgeGradle automatically adds the Forge maven and Maven Central for you maven fg.forgeMaven
maven fg.minecraftLibsMaven
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so. mavenCentral()
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
} }
dependencies { dependencies {
// Specify the version of Minecraft to use. implementation minecraft.dependency('net.minecraftforge:forge:@MC_VERSION@-@FORGE_VERSION@')
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact.
// The "userdev" classifier will be requested and setup by ForgeGradle.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
// Example mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}"
// runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}"
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
// Hack fix for now, force jopt-simple to be exactly 5.0.4 because Mojang ships that version, but some transtive 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.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.named('processResources', ProcessResources).configure {
var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range,
loader_version_range: loader_version_range,
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
}
}
// Example for how to get properties into the manifest for reading at runtime.
tasks.named('jar', Jar).configure {
manifest {
attributes([
'Specification-Title' : mod_id,
'Specification-Vendor' : mod_authors,
'Specification-Version' : '1', // We are version 1 of ourselves
'Implementation-Title' : project.name,
'Implementation-Version' : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors
])
}
}
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
register('mavenJava', MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file://${project.projectDir}/mcmodsrepo"
}
}
} }
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation // Use the UTF-8 charset for Java compilation
} // This is done by default in Java 18+, but this ensures it no matter the Java or Gradle version
options.encoding = 'UTF-8'
eclipse {
// Run everytime eclipse builds the code
//autoBuildTasks genEclipseRuns
// Run when importing the project
synchronizationTasks 'genEclipseRuns'
}
// Merge the resources and classes into the same directory.
// This is done because java expects modules to be in a single directory.
// And if we have it in multiple we have to do performance intensive hacks like having the UnionFileSystem
// This will eventually be migrated to ForgeGradle so modders don't need to manually do it. But that is later.
sourceSets.each {
def dir = layout.buildDirectory.dir("sourcesSets/$it.name")
it.output.resourcesDir = dir
it.java.destinationDirectory = dir
} }
+6 -16
View File
@@ -1,13 +1,11 @@
Source installation information for modders Source installation information for modders
------------------------------------------- -------------------------------------------
This code follows the Minecraft Forge installation methodology. It will apply This code follows the Minecraft Forge installation methodology. It will apply
some small patches to the vanilla MCP source code, giving you and it access some small patches to the vanilla MCP source code, giving you and it access
to some of the data and functions you need to build a successful mod. to some of the data and functions you need to build a successful mod.
Note also that the patches are built against "un-renamed" MCP source code (aka Please note that this example MDK is a simple showcase for the most basic of mods.
SRG Names) - this means that you will not be able to read them directly against To see more examples see our dedicated examples repository under the "Additional Resources" section.
normal code.
Setup Process: Setup Process:
============================== ==============================
@@ -17,30 +15,22 @@ Step 1: Open your command-line and browse to the folder where you extracted the
Step 2: You're left with a choice. Step 2: You're left with a choice.
If you prefer to use Eclipse: If you prefer to use Eclipse:
1. Run the following command: `./gradlew genEclipseRuns` 1. Run the following command: `./gradlew genEclipseRuns`
2. Open Eclipse, Import > Existing Gradle Project > Select Folder 2. Open Eclipse, Import > Existing Gradle Project > Select Folder
or run `gradlew eclipse` to generate the project. or run `gradlew eclipse` to generate the project.
If you prefer to use IntelliJ: If you prefer to use IntelliJ:
1. Open IDEA, and import project. 1. Open IDEA, and import project.
2. Select your build.gradle file and have it import. 2. Select your build.gradle file and have it import.
3. Run the following command: `./gradlew genIntellijRuns` 3. Use the run tasks located under the "Slime Launcher" Gradle task group.
4. Refresh the Gradle Project in IDEA if required.
If at any point you are missing libraries in your IDE, or you've run into problems you can If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
(this does not affect your code) and then start the process again. (this does not affect your code) and then start the process again.
Mapping Names:
=============================
By default, the MDK is configured to use the official mapping names from Mojang for methods and fields
in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this
license, if you do not agree with it you can change your mapping names to other crowdsourced names in your
build.gradle. For the latest license text, refer to the mapping file itself, or the reference copy here:
https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
Additional Resources: Additional Resources:
========================= =========================
Community Documentation: https://docs.minecraftforge.net/en/latest/gettingstarted/ Community Documentation: https://docs.minecraftforge.net/en/latest/gettingstarted/
Additional Examples: https://github.com/MinecraftForge/MDKExamples
LexManos' Install Video: https://youtu.be/8VEdtQLuLO0 LexManos' Install Video: https://youtu.be/8VEdtQLuLO0
Forge Forums: https://forums.minecraftforge.net/ Forge Forums: https://forums.minecraftforge.net/
Forge Discord: https://discord.minecraftforge.net/ Forge Discord: https://discord.minecraftforge.net/
+1
View File
@@ -22,4 +22,5 @@ eclipse
run run
# Files from Forge MDK # Files from Forge MDK
forge_README.txt
forge*changelog.txt forge*changelog.txt
+7 -57
View File
@@ -1,59 +1,9 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties. org.gradle.caching=true
# This is required to provide enough memory for the Minecraft decompilation process. org.gradle.parallel=true
org.gradle.jvmargs=-Xmx3G org.gradle.configureondemand=true
org.gradle.daemon=false
org.gradle.configuration-cache=true
org.gradle.configuration-cache.parallel=true
org.gradle.configuration-cache.problems=warn
## Environment Properties net.minecraftforge.gradle.merge-source-sets=true
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=@MC_VERSION@
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[@MC_VERSION@,@MC_NEXT_VERSION@)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=@FORGE_VERSION@
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[@FORGE_SPEC_VERSION@,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[@FORGE_SPEC_VERSION@,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=@MAPPING_CHANNEL@
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=@MAPPING_VERSION@
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=examplemod
# The human-readable display name for the mod.
mod_name=Example Mod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=1.0.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.example.examplemod
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=YourNameHere, OtherNameHere
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Example mod description.\nNewline characters can be used and will be replaced properly.
+3 -11
View File
@@ -1,13 +1,5 @@
pluginManagement { plugins {
repositories { id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
gradlePluginPortal()
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
}
}
} }
plugins { rootProject.name = 'examplemod'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0'
}
@@ -18,7 +18,6 @@ import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
@@ -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 output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build()); }).build());
public ExampleMod() public ExampleMod(FMLJavaModLoadingContext context)
{ {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus modEventBus = context.getModEventBus();
// Register the commonSetup method for modloading // Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup); modEventBus.addListener(this::commonSetup);
@@ -82,7 +81,7 @@ public class ExampleMod
modEventBus.addListener(this::addCreative); modEventBus.addListener(this::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us // 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) private void commonSetup(final FMLCommonSetupEvent event)
+36 -66
View File
@@ -1,73 +1,43 @@
# This is an example mods.toml file. It contains the data relating to the loading mods. # See https://docs.minecraftforge.net/en/1.21.x/gettingstarted/modfiles/#modstoml
# There are several mandatory fields (#mandatory), and many more that are optional (#optional). # There are lots of things you can do with the mods.toml, and not all fields are included with this MDK
# The overall format is standard TOML format, v0.5.0. # References: https://github.com/MinecraftForge/MDKExamples
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or Open to LAN),
# set this to true, and Forge will set the correct displayTest for you and skip loading your mod on dedicated servers.
#clientSideOnly=true #optional - defaults to false if absent
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# A text field displayed in the mod UI
authors="${mod_authors}" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component.
# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value.
# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself.
#displayTest="MATCH_VERSION" # if nothing is specified, MATCH_VERSION is the default when clientSideOnly=false, otherwise IGNORE_ALL_VERSION when clientSideOnly=true (#optional)
# The description text for the mod (multi line!) (#mandatory) modLoader="javafml"
description='''${mod_description}''' loaderVersion="[@FORGE_SPEC_VERSION@,)"
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. license="All Rights Reserved"
[[dependencies.${mod_id}]] #optional #issueTrackerURL="https://github.com/MyOrganization/MyMod/" #optional
# the modid of the dependency #clientSideOnly=true #optional, default=false
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified [[mods]]
mandatory=true #mandatory modId="examplemod"
# The version range of the dependency version="1.0.0"
versionRange="${forge_version_range}" #mandatory displayName="Example Mod"
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory #updateJSONURL="https://example.com/updates.json" #optional
# BEFORE - This mod is loaded BEFORE the dependency #displayURL="https://example.com/" #optional
# AFTER - This mod is loaded AFTER the dependency #logoFile="examplemod.png" #optional
#credits="" #optional
authors="YourNameHere, OtherNameHere" #optional
#displayTest="MATCH_VERSION" #optional, default=MATCH_VERSION when not clientSideOnly, else IGNORE_ALL_VERSION
# Access Transformers
# Optional, if not specified Forge will attempt to find the default META-INF/accesstransformer.cfg and silently continue if not found. May default to an empty list in a future MC.
# If you specify AT path strings in this list, Forge will attempt to load each of them and throw errors for any that aren't found.
# Specifying an empty list when your mod has no ATs is recommended to opt-out of the default for slightly better loading performance.
#accessTransformers = []
description='''Example mod description.
Newline characters can be used like this, and rendered on the mods screen properly.'''
[[dependencies.examplemod]] #recommended
modId="forge"
mandatory=true
versionRange="[@FORGE_SPEC_VERSION@,)"
ordering="NONE" ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH" side="BOTH"
# Here's another dependency
[[dependencies.${mod_id}]] [[dependencies.examplemod]] #recommended
modId="minecraft" modId="minecraft"
mandatory=true mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version versionRange="[@MC_VERSION@,@MC_NEXT_VERSION@,)"
versionRange="${minecraft_version_range}"
ordering="NONE" ordering="NONE"
side="BOTH" side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"
@@ -1,13 +1,18 @@
--- a/com/mojang/blaze3d/pipeline/RenderTarget.java --- a/com/mojang/blaze3d/pipeline/RenderTarget.java
+++ b/com/mojang/blaze3d/pipeline/RenderTarget.java +++ b/com/mojang/blaze3d/pipeline/RenderTarget.java
@@ -113,11 +_,19 @@ @@ -106,7 +_,10 @@
GlStateManager._bindTexture(this.colorTextureId); GlStateManager._texParameter(3553, 34892, 0);
GlStateManager._texParameter(3553, 10242, 33071); GlStateManager._texParameter(3553, 10242, 33071);
GlStateManager._texParameter(3553, 10243, 33071); GlStateManager._texParameter(3553, 10243, 33071);
+ if (!stencilEnabled) + 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);
}
this.setFilterMode(9728, true);
@@ -116,8 +_,13 @@
GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, null); GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, 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);
GlStateManager._glBindFramebuffer(36160, this.frameBufferId); GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0); GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
- if (this.useDepth) { - if (this.useDepth) {
@@ -1,16 +1,21 @@
--- a/com/mojang/blaze3d/vertex/VertexFormat.java --- a/com/mojang/blaze3d/vertex/VertexFormat.java
+++ b/com/mojang/blaze3d/vertex/VertexFormat.java +++ b/com/mojang/blaze3d/vertex/VertexFormat.java
@@ -114,6 +_,13 @@ @@ -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; return vertexbuffer;
} }
+
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; } + public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
+ public int getOffset(int index) { return offsets.getInt(index); } + 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); }
+
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static enum IndexType { public static enum IndexType {
SHORT(5123, 2),
@@ -9,6 +9,59 @@
private final SubtitleOverlay subtitleOverlay; private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui; private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList; private final PlayerTabOverlay tabList;
@@ -150,7 +_,7 @@
private long healthBlinkTime;
private float autosaveIndicatorValue;
private float lastAutosaveIndicatorValue;
- private final LayeredDraw layers = new LayeredDraw();
+ private final LayeredDraw layers = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.VANILLA_ROOT, net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.COMBINE_LIST);
private float scopeScale;
public Gui(Minecraft p_330021_) {
@@ -162,16 +_,16 @@
this.bossOverlay = new BossHealthOverlay(p_330021_);
this.subtitleOverlay = new SubtitleOverlay(p_330021_);
this.resetTitleTimes();
- LayeredDraw layereddraw = new LayeredDraw()
+ LayeredDraw layereddraw = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.PRE_SLEEP_STACK, net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.PRE_LIST)
.add(this::renderCameraOverlays)
.add(this::renderCrosshair)
.add(this::renderHotbarAndDecorations)
.add(this::renderExperienceLevel)
.add(this::renderEffects)
- .add((p_325313_, p_325314_) -> this.bossOverlay.render(p_325313_));
- LayeredDraw layereddraw1 = new LayeredDraw()
+ .add((p_325313_, p_342678_) -> this.bossOverlay.render(p_325313_));
+ LayeredDraw layereddraw1 = new net.minecraftforge.client.gui.overlay.ForgeLayeredDraw(net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.POST_SLEEP_STACK,net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.POST_LIST)
.add(this::renderDemoOverlay)
- .add((p_325315_, p_325316_) -> {
+ .add((p_325315_, p_344521_) -> {
if (this.debugOverlay.showDebugScreen()) {
this.debugOverlay.render(p_325315_);
}
@@ -181,11 +_,12 @@
.add(this::renderTitle)
.add(this::renderChat)
.add(this::renderTabList)
- .add((p_325317_, p_325318_) -> this.subtitleOverlay.render(p_325317_));
+ .add((p_325317_, p_342874_) -> this.subtitleOverlay.render(p_325317_));
this.layers
.add(layereddraw, () -> !p_330021_.options.hideGui)
.add(this::renderSleepOverlay)
.add(layereddraw1, () -> !p_330021_.options.hideGui);
+ ((net.minecraftforge.client.gui.overlay.ForgeLayeredDraw) layers).resolveLayers();
}
public void resetTitleTimes() {
@@ -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);
}
}
@@ -444,6 +_,8 @@ @@ -444,6 +_,8 @@
for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) { for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
@@ -37,30 +90,28 @@
this.minecraft.getProfiler().push("selectedItemName"); this.minecraft.getProfiler().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { 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().color());
@@ -642,9 +_,10 @@ @@ -642,9 +_,13 @@
mutablecomponent.withStyle(ChatFormatting.ITALIC); mutablecomponent.withStyle(ChatFormatting.ITALIC);
} }
- int i = this.getFont().width(mutablecomponent); - int i = this.getFont().width(mutablecomponent);
+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent); + Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent);
+ int i = this.getFont().width(highlightTip); + 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)
+ font = this.getFont();
+ int i = font.width(highlightTip);
int j = (p_283501_.guiWidth() - i) / 2; int j = (p_283501_.guiWidth() - i) / 2;
- int k = p_283501_.guiHeight() - 59; - int k = p_283501_.guiHeight() - 59;
+ int k = p_283501_.guiHeight() - Math.max(yShift, 59); + int k = p_283501_.guiHeight() - Math.max(yShift, 59);
if (!this.minecraft.gameMode.canHurtPlayer()) { if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14; k += 14;
} }
@@ -657,6 +_,13 @@ @@ -656,7 +_,7 @@
if (l > 0) { if (l > 0) {
p_283501_.fill(j - 2, k - 2, j + i + 2, k + 9 + 2, this.minecraft.options.getBackgroundColor(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)); - 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); + p_283501_.drawString(font, highlightTip, j, k, 16777215 + (l << 24));
+ 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));
+ }
} }
} }
@@ -70,7 +70,7 @@
this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE); this.renderTooltipInternal(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.INSTANCE);
} }
@@ -930,7 +_,15 @@ @@ -930,7 +_,22 @@
} }
public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) { public void renderComponentTooltip(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
@@ -83,6 +83,13 @@
+ this.tooltipStack = stack; + this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font); + List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, guiWidth(), guiHeight(), font);
+ this.renderTooltipInternal(font, components, mouseX, mouseY, DefaultTooltipPositioner.INSTANCE); + 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; + this.tooltipStack = ItemStack.EMPTY;
} }
@@ -69,7 +69,7 @@
list.add(""); list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null; boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add( list.add(
@@ -176,7 +_,12 @@ @@ -176,11 +_,18 @@
+ (this.renderNetworkCharts ? " visible" : " hidden") + (this.renderNetworkCharts ? " visible" : " hidden")
); );
list.add("For help: press F3 + Q"); list.add("For help: press F3 + Q");
@@ -79,10 +79,16 @@
+ protected void drawGameInformation(GuiGraphics p_281525_) { + protected void drawGameInformation(GuiGraphics p_281525_) {
+ List<String> list = this.getGameInformation(); + List<String> list = this.getGameInformation();
+ list.addAll(this.getOverlayHelp()); + 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_) { 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);
}
@@ -529,6 +_,7 @@ @@ -529,6 +_,7 @@
list.add(""); list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity"); list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
@@ -146,19 +146,11 @@
this.refreshSearchResults(); this.refreshSearchResults();
} else { } else {
@@ -642,7 +_,7 @@ @@ -642,7 +_,15 @@
public void render(GuiGraphics p_283000_, int p_281317_, int p_282770_, float p_281295_) { 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_); super.render(p_283000_, p_281317_, p_282770_, p_281295_);
- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { - for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) {
+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) {
if (this.checkTabHovering(p_283000_, creativemodetab, p_281317_, p_282770_)) {
break;
}
@@ -653,7 +_,15 @@
&& this.isHovering(this.destroyItemSlot.x, this.destroyItemSlot.y, 16, 16, (double)p_281317_, (double)p_282770_)) {
p_283000_.renderTooltip(this.font, TRASH_SLOT_TOOLTIP, p_281317_, p_282770_);
}
+ if (this.pages.size() != 1) { + if (this.pages.size() != 1) {
+ Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size())); + Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size()));
+ p_283000_.pose().pushPose(); + p_283000_.pose().pushPose();
@@ -166,6 +158,14 @@
+ p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1); + p_283000_.drawString(font, page.getVisualOrderText(), leftPos + (imageWidth / 2) - (font.width(page) / 2), topPos - 44, -1);
+ p_283000_.pose().popPose(); + p_283000_.pose().popPose();
+ } + }
+
+ 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); + com.mojang.blaze3d.systems.RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
this.renderTooltip(p_283000_, p_281317_, p_282770_); this.renderTooltip(p_283000_, p_281317_, p_282770_);
@@ -0,0 +1,18 @@
--- a/net/minecraft/client/model/geom/ModelLayers.java
+++ b/net/minecraft/client/model/geom/ModelLayers.java
@@ -228,11 +_,13 @@
}
public static ModelLayerLocation createSignModelName(WoodType p_171292_) {
- return createLocation("sign/" + p_171292_.name(), "main");
+ ResourceLocation location = new ResourceLocation(p_171292_.name());
+ return new ModelLayerLocation(new ResourceLocation(location.getNamespace(), "sign/" + location.getPath()), "main");
}
public static ModelLayerLocation createHangingSignModelName(WoodType p_252225_) {
- return createLocation("hanging_sign/" + p_252225_.name(), "main");
+ ResourceLocation location = new ResourceLocation(p_252225_.name());
+ return new ModelLayerLocation(new ResourceLocation(location.getNamespace(), "hanging_sign/" + location.getPath()), "main");
}
public static Stream<ModelLayerLocation> getKnownLocations() {
@@ -4,7 +4,7 @@
@Override @Override
public void handleCustomPayload(ClientboundCustomPayloadPacket p_298103_) { public void handleCustomPayload(ClientboundCustomPayloadPacket p_298103_) {
+ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_, this.connection)) return; + if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_.payload(), this.connection)) return;
CustomPacketPayload custompacketpayload = p_298103_.payload(); CustomPacketPayload custompacketpayload = p_298103_.payload();
if (!(custompacketpayload instanceof DiscardedPayload)) { if (!(custompacketpayload instanceof DiscardedPayload)) {
PacketUtils.ensureRunningOnSameThread(p_298103_, this, this.minecraft); PacketUtils.ensureRunningOnSameThread(p_298103_, this, this.minecraft);
@@ -31,13 +31,13 @@
0.0F, 0.0F,
1000.0F, 1000.0F,
- 21000.0F - 21000.0F
+ 21000.0f + net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()
); );
RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z);
Matrix4fStack matrix4fstack = RenderSystem.getModelViewStack(); Matrix4fStack matrix4fstack = RenderSystem.getModelViewStack();
matrix4fstack.pushMatrix(); matrix4fstack.pushMatrix();
- matrix4fstack.translation(0.0F, 0.0F, -11000.0F); - matrix4fstack.translation(0.0F, 0.0F, -11000.0F);
+ matrix4fstack.translation(0.0F, 0.0F, 1000F - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); + matrix4fstack.translation(0.0F, 0.0F, 10000F - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane());
RenderSystem.applyModelViewMatrix(); RenderSystem.applyModelViewMatrix();
Lighting.setupFor3DItems(); Lighting.setupFor3DItems();
GuiGraphics guigraphics = new GuiGraphics(this.minecraft, this.renderBuffers.bufferSource()); GuiGraphics guigraphics = new GuiGraphics(this.minecraft, this.renderBuffers.bufferSource());
@@ -52,7 +52,7 @@
public static RenderType getRenderType(ItemStack p_109280_, boolean p_109281_) { public static RenderType getRenderType(ItemStack p_109280_, boolean p_109281_) {
Item item = p_109280_.getItem(); Item item = p_109280_.getItem();
if (item instanceof BlockItem) { if (item instanceof BlockItem) {
@@ -391,11 +_,74 @@ @@ -391,11 +_,79 @@
} }
public static RenderType getRenderLayer(FluidState p_109288_) { public static RenderType getRenderLayer(FluidState p_109288_) {
@@ -65,6 +65,11 @@
renderCutout = p_109292_; renderCutout = p_109292_;
+ } + }
+ +
+ /** Forge: Check if we are running in {@linkplain net.minecraft.client.Minecraft#useFancyGraphics() fancy graphics} to account for fast graphics render types */
+ public static boolean isFancy() {
+ return renderCutout;
+ }
+
+ private static final net.minecraftforge.client.ChunkRenderTypeSet CUTOUT_MIPPED = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.cutoutMipped()); + private static final net.minecraftforge.client.ChunkRenderTypeSet CUTOUT_MIPPED = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.cutoutMipped());
+ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.solid()); + private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.solid());
+ private static final Map<net.minecraft.core.Holder.Reference<Block>, net.minecraftforge.client.ChunkRenderTypeSet> BLOCK_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_BLOCK.size(), 0.5F), map -> { + private static final Map<net.minecraft.core.Holder.Reference<Block>, net.minecraftforge.client.ChunkRenderTypeSet> BLOCK_RENDER_TYPES = Util.make(new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(TYPE_BY_BLOCK.size(), 0.5F), map -> {
@@ -81,7 +86,7 @@
+ }); + });
+ +
+ /** @deprecated Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */ + /** @deprecated Use {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)}. */
+ @Deprecated(since = "1.19") + @Deprecated(since = "1.21.4", forRemoval = true)
+ public static net.minecraftforge.client.ChunkRenderTypeSet getRenderLayers(BlockState state) { + public static net.minecraftforge.client.ChunkRenderTypeSet getRenderLayers(BlockState state) {
+ Block block = state.getBlock(); + Block block = state.getBlock();
+ if (block instanceof LeavesBlock) { + if (block instanceof LeavesBlock) {
@@ -92,20 +97,20 @@
+ } + }
+ +
+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ + /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */
+ @Deprecated(since = "1.19") + @Deprecated(since = "1.21.4", forRemoval = true)
+ public static void setRenderLayer(Block block, RenderType type) { + public static void setRenderLayer(Block block, RenderType type) {
+ com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers()."); + com.google.common.base.Preconditions.checkArgument(type.getChunkLayerId() >= 0, "The argument must be a valid chunk render type returned by RenderType#chunkBufferLayers().");
+ setRenderLayer(block, net.minecraftforge.client.ChunkRenderTypeSet.of(type)); + setRenderLayer(block, net.minecraftforge.client.ChunkRenderTypeSet.of(type));
+ } + }
+ +
+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ + /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */
+ @Deprecated(since = "1.19") + @Deprecated(since = "1.21.4", forRemoval = true)
+ public static synchronized void setRenderLayer(Block block, java.util.function.Predicate<RenderType> predicate) { + public static synchronized void setRenderLayer(Block block, java.util.function.Predicate<RenderType> predicate) {
+ setRenderLayer(block, createSetFromPredicate(predicate)); + setRenderLayer(block, createSetFromPredicate(predicate));
+ } + }
+ +
+ /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */ + /** @deprecated Set your render type in your block model's JSON (eg. {@code "render_type": "cutout"}) or override {@link net.minecraft.client.resources.model.BakedModel#getRenderTypes(BlockState, net.minecraft.util.RandomSource, net.minecraftforge.client.model.data.ModelData)} */
+ @Deprecated(since = "1.19") + @Deprecated(since = "1.21.4", forRemoval = true)
+ public static synchronized void setRenderLayer(Block block, net.minecraftforge.client.ChunkRenderTypeSet layers) { + public static synchronized void setRenderLayer(Block block, net.minecraftforge.client.ChunkRenderTypeSet layers) {
+ checkClientLoading(); + checkClientLoading();
+ BLOCK_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), layers); + BLOCK_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), layers);
@@ -11,7 +11,7 @@
if (iteminhandrenderer$handrenderselection.renderOffHand) { if (iteminhandrenderer$handrenderselection.renderOffHand) {
float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F; float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F;
float f7 = 1.0F - Mth.lerp(p_109315_, this.oOffHandHeight, this.offHandHeight); float f7 = 1.0F - Mth.lerp(p_109315_, this.oOffHandHeight, this.offHandHeight);
+ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f6, f7, this.mainHandItem)) + if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, p_109316_, p_109317_, p_109319_, p_109315_, f1, f6, f7, this.offHandItem))
this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, p_109316_, p_109317_, p_109319_); this.renderArmWithItem(p_109318_, p_109315_, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, p_109316_, p_109317_, p_109319_);
} }
@@ -123,13 +123,13 @@
profilerfiller.popPush("outline"); profilerfiller.popPush("outline");
BlockPos blockpos1 = ((BlockHitResult)hitresult).getBlockPos(); BlockPos blockpos1 = ((BlockHitResult)hitresult).getBlockPos();
BlockState blockstate = this.level.getBlockState(blockpos1); BlockState blockstate = this.level.getBlockState(blockpos1);
+ if (!net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_254120_, multibuffersource$buffersource)) + if (!net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, posestack, multibuffersource$buffersource))
if (!blockstate.isAir() && this.level.getWorldBorder().isWithinBounds(blockpos1)) { if (!blockstate.isAir() && this.level.getWorldBorder().isWithinBounds(blockpos1)) {
VertexConsumer vertexconsumer2 = multibuffersource$buffersource.getBuffer(RenderType.lines()); VertexConsumer vertexconsumer2 = multibuffersource$buffersource.getBuffer(RenderType.lines());
this.renderHitOutline(posestack, vertexconsumer2, p_109604_.getEntity(), d0, d1, d2, blockpos1, blockstate); this.renderHitOutline(posestack, vertexconsumer2, p_109604_.getEntity(), d0, d1, d2, blockpos1, blockstate);
} }
+ } else if (hitresult != null && hitresult.getType() == HitResult.Type.ENTITY) { + } else if (hitresult != null && hitresult.getType() == HitResult.Type.ENTITY) {
+ net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, p_254120_, multibuffersource$buffersource); + net.minecraftforge.client.ForgeHooksClient.onDrawHighlight(this, p_109604_, hitresult, p_109601_, posestack, multibuffersource$buffersource);
} }
this.minecraft.debugRenderer.render(posestack, multibuffersource$buffersource, d0, d1, d2); this.minecraft.debugRenderer.render(posestack, multibuffersource$buffersource, d0, d1, d2);
@@ -7,7 +7,7 @@
- if (this.shouldShowName(p_114485_)) { - if (this.shouldShowName(p_114485_)) {
- this.renderNameTag(p_114485_, p_114485_.getDisplayName(), p_114488_, p_114489_, p_114490_, p_114487_); - this.renderNameTag(p_114485_, p_114485_.getDisplayName(), p_114488_, p_114489_, p_114490_, p_114487_);
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.fireRenderNameTagEvent(p_114485_, p_114485_.getDisplayName(), this, p_114488_, p_114489_, p_114490_, p_114487_); + var event = net.minecraftforge.client.event.ForgeEventFactoryClient.fireRenderNameTagEvent(p_114485_, p_114485_.getDisplayName(), this, p_114488_, p_114489_, p_114490_, p_114487_);
+ if (event.getResult() != net.minecraftforge.eventbus.api.Event.Result.DENY && (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || this.shouldShowName(p_114485_))) { + if (!event.getResult().isDenied() && (event.getResult().isAllowed() || this.shouldShowName(p_114485_))) {
+ this.renderNameTag(p_114485_, event.getContent(), p_114488_, p_114489_, p_114490_, p_114487_); + this.renderNameTag(p_114485_, event.getContent(), p_114488_, p_114489_, p_114490_, p_114487_);
} }
} }
@@ -1,11 +1,12 @@
--- a/net/minecraft/client/renderer/entity/FallingBlockRenderer.java --- a/net/minecraft/client/renderer/entity/FallingBlockRenderer.java
+++ b/net/minecraft/client/renderer/entity/FallingBlockRenderer.java +++ b/net/minecraft/client/renderer/entity/FallingBlockRenderer.java
@@ -34,20 +_,25 @@ @@ -34,20 +_,26 @@
p_114637_.pushPose(); p_114637_.pushPose();
BlockPos blockpos = BlockPos.containing(p_114634_.getX(), p_114634_.getBoundingBox().maxY, p_114634_.getZ()); BlockPos blockpos = BlockPos.containing(p_114634_.getX(), p_114634_.getBoundingBox().maxY, p_114634_.getZ());
p_114637_.translate(-0.5, 0.0, -0.5); p_114637_.translate(-0.5, 0.0, -0.5);
+ var model = this.dispatcher.getBlockModel(blockstate); + var model = this.dispatcher.getBlockModel(blockstate);
+ for (var renderType : model.getRenderTypes(blockstate, RandomSource.create(blockstate.getSeed(p_114634_.getStartPos())), net.minecraftforge.client.model.data.ModelData.EMPTY)) { + for (var renderType : model.getRenderTypes(blockstate, RandomSource.create(blockstate.getSeed(p_114634_.getStartPos())), net.minecraftforge.client.model.data.ModelData.EMPTY)) {
+ renderType = net.minecraftforge.client.RenderTypeHelper.getMovingBlockRenderType(renderType);
this.dispatcher this.dispatcher
.getModelRenderer() .getModelRenderer()
.tesselateBlock( .tesselateBlock(
@@ -1,5 +1,14 @@
--- a/net/minecraft/client/renderer/entity/layers/ElytraLayer.java --- a/net/minecraft/client/renderer/entity/layers/ElytraLayer.java
+++ b/net/minecraft/client/renderer/entity/layers/ElytraLayer.java +++ b/net/minecraft/client/renderer/entity/layers/ElytraLayer.java
@@ -23,7 +_,7 @@
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
-public class ElytraLayer<T extends LivingEntity, M extends EntityModel<T>> extends RenderLayer<T, M> {
+public class ElytraLayer<T extends LivingEntity, M extends EntityModel<T>> extends RenderLayer<T, M> implements net.minecraftforge.client.extensions.IForgeElytraLayer<T> {
public static final ResourceLocation WINGS_LOCATION = new ResourceLocation("textures/entity/elytra.png");
private final ElytraModel<T> elytraModel;
@@ -45,7 +_,7 @@ @@ -45,7 +_,7 @@
float p_116960_ float p_116960_
) { ) {
@@ -22,34 +31,3 @@
} }
p_116951_.pushPose(); p_116951_.pushPose();
@@ -68,5 +_,30 @@
this.elytraModel.renderToBuffer(p_116951_, vertexconsumer, p_116953_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F);
p_116951_.popPose();
}
+ }
+
+ /**
+ * Determines if the ElytraLayer should render.
+ * ItemStack and Entity are provided for modder convenience,
+ * For example, using the same ElytraLayer for multiple custom Elytra.
+ *
+ * @param stack The Elytra ItemStack
+ * @param entity The entity being rendered.
+ * @return If the ElytraLayer should render.
+ */
+ public boolean shouldRender(ItemStack stack, T entity) {
+ return stack.getItem() == Items.ELYTRA;
+ }
+
+ /**
+ * Gets the texture to use with this ElytraLayer.
+ * This assumes the vanilla Elytra model.
+ *
+ * @param stack The Elytra ItemStack.
+ * @param entity The entity being rendered.
+ * @return The texture.
+ */
+ public ResourceLocation getElytraTexture(ItemStack stack, T entity) {
+ return WINGS_LOCATION;
}
}
@@ -0,0 +1,87 @@
--- a/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java
+++ b/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java
@@ -66,6 +_,7 @@
if (armoritem.getEquipmentSlot() == p_117122_) {
this.getParentModel().copyPropertiesTo(p_117124_);
this.setPartVisibility(p_117124_, p_117122_);
+ net.minecraft.client.model.Model model = getArmorModelHook(p_117121_, itemstack, p_117122_, p_117124_);
boolean flag = this.usesInnerModel(p_117122_);
ArmorMaterial armormaterial = armoritem.getMaterial().value();
int i = itemstack.is(ItemTags.DYEABLE) ? DyedItemColor.getOrDefault(itemstack, -6265536) : -1;
@@ -83,17 +_,17 @@
f1 = 1.0F;
f2 = 1.0F;
}
-
- this.renderModel(p_117119_, p_117120_, p_117123_, p_117124_, f, f1, f2, armormaterial$layer.texture(flag));
+ var texture = net.minecraftforge.client.ForgeHooksClient.getArmorTexture(p_117121_, itemstack, p_117122_, armormaterial$layer, flag);
+ this.renderModel(p_117119_, p_117120_, p_117123_, model, f, f1, f2, texture);
}
ArmorTrim armortrim = itemstack.get(DataComponents.TRIM);
if (armortrim != null) {
- this.renderTrim(armoritem.getMaterial(), p_117119_, p_117120_, p_117123_, armortrim, p_117124_, flag);
+ this.renderTrim(armoritem.getMaterial(), p_117119_, p_117120_, p_117123_, armortrim, model, flag);
}
if (itemstack.hasFoil()) {
- this.renderGlint(p_117119_, p_117120_, p_117123_, p_117124_);
+ this.renderGlint(p_117119_, p_117120_, p_117123_, model);
}
}
}
@@ -122,11 +_,15 @@
}
}
+ private void renderModel(PoseStack p_289664_, MultiBufferSource p_289689_, int p_289681_, A p_289658_, float p_289678_, float p_289674_, float p_289693_, ResourceLocation p_328978_) {
+ renderModel(p_289664_, p_289689_, p_289681_, (net.minecraft.client.model.Model)p_289658_, p_289678_, p_289674_, p_289693_, p_328978_);
+ }
+
private void renderModel(
PoseStack p_289664_,
MultiBufferSource p_289689_,
int p_289681_,
- A p_289658_,
+ net.minecraft.client.model.Model p_289658_,
float p_289678_,
float p_289674_,
float p_289693_,
@@ -136,8 +_,12 @@
p_289658_.renderToBuffer(p_289664_, vertexconsumer, p_289681_, OverlayTexture.NO_OVERLAY, p_289678_, p_289674_, p_289693_, 1.0F);
}
+ private void renderTrim(Holder<ArmorMaterial> p_331988_, PoseStack p_289687_, MultiBufferSource p_289643_, int p_289683_, ArmorTrim p_289692_, A p_289663_, boolean p_289651_) {
+ renderTrim(p_331988_, p_289687_, p_289643_, p_289683_, p_289692_, (net.minecraft.client.model.Model)p_289663_, p_289651_);
+ }
+
private void renderTrim(
- Holder<ArmorMaterial> p_331988_, PoseStack p_289687_, MultiBufferSource p_289643_, int p_289683_, ArmorTrim p_289692_, A p_289663_, boolean p_289651_
+ Holder<ArmorMaterial> p_331988_, PoseStack p_289687_, MultiBufferSource p_289643_, int p_289683_, ArmorTrim p_289692_, net.minecraft.client.model.Model p_289663_, boolean p_289651_
) {
TextureAtlasSprite textureatlassprite = this.armorTrimAtlas.getSprite(p_289651_ ? p_289692_.innerTexture(p_331988_) : p_289692_.outerTexture(p_331988_));
VertexConsumer vertexconsumer = textureatlassprite.wrap(p_289643_.getBuffer(Sheets.armorTrimsSheet(p_289692_.pattern().value().decal())));
@@ -145,6 +_,10 @@
}
private void renderGlint(PoseStack p_289673_, MultiBufferSource p_289654_, int p_289649_, A p_289659_) {
+ renderGlint(p_289673_, p_289654_, p_289649_, (net.minecraft.client.model.Model)p_289659_);
+ }
+
+ private void renderGlint(PoseStack p_289673_, MultiBufferSource p_289654_, int p_289649_, net.minecraft.client.model.Model p_289659_) {
p_289659_.renderToBuffer(p_289673_, p_289654_.getBuffer(RenderType.armorEntityGlint()), p_289649_, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F);
}
@@ -154,5 +_,12 @@
private boolean usesInnerModel(EquipmentSlot p_117129_) {
return p_117129_ == EquipmentSlot.LEGS;
+ }
+
+ /**
+ * Hook to allow item-sensitive armor model. for HumanoidArmorLayer.
+ */
+ protected net.minecraft.client.model.Model getArmorModelHook(T entity, ItemStack itemStack, EquipmentSlot slot, A model) {
+ return net.minecraftforge.client.ForgeHooksClient.getArmorModel(entity, itemStack, slot, model);
}
}
@@ -5,7 +5,7 @@
int k1 = Mth.log2(j1); int k1 = Mth.log2(j1);
int l1; int l1;
- if (k1 < p_261919_) { - if (k1 < p_261919_) {
+ if (false) { // Forge: Do not lower the mipmap level + if (k1 < p_261919_ && net.minecraftforge.common.ForgeConfig.CLIENT.allowMipmapLowering()) { // Forge: Do not lower the mipmap level
LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, p_261919_, k1, j1); LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, p_261919_, k1, j1);
l1 = k1; l1 = k1;
} else { } else {
@@ -1,74 +1,142 @@
--- a/net/minecraft/client/resources/model/SimpleBakedModel.java --- a/net/minecraft/client/resources/model/SimpleBakedModel.java
+++ b/net/minecraft/client/resources/model/SimpleBakedModel.java +++ b/net/minecraft/client/resources/model/SimpleBakedModel.java
@@ -26,6 +_,15 @@ @@ -26,7 +_,32 @@
protected final TextureAtlasSprite particleIcon; protected final TextureAtlasSprite particleIcon;
protected final ItemTransforms transforms; protected final ItemTransforms transforms;
protected final ItemOverrides overrides; protected final ItemOverrides overrides;
-
+ /** Forge: Block render types to be used with {@linkplain net.minecraft.client.GraphicsStatus#FANCY fancy graphics} */
+ protected final net.minecraftforge.client.ChunkRenderTypeSet blockRenderTypes; + protected final net.minecraftforge.client.ChunkRenderTypeSet blockRenderTypes;
+ /** Forge: Block render types to be used with {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics} */
+ protected final net.minecraftforge.client.ChunkRenderTypeSet blockRenderTypesFast;
+ /** Forge: Item render types to be used with {@linkplain net.minecraft.client.GraphicsStatus#FANCY fancy graphics} */
+ protected final List<net.minecraft.client.renderer.RenderType> itemRenderTypes; + protected final List<net.minecraft.client.renderer.RenderType> itemRenderTypes;
+ /** Forge: Item render types to be used with {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics} */
+ protected final List<net.minecraft.client.renderer.RenderType> itemRenderTypesFast;
+ /** Forge: Item render types to be used with {@linkplain net.minecraft.client.GraphicsStatus#FABULOUS fabulous graphics} */
+ protected final List<net.minecraft.client.renderer.RenderType> fabulousItemRenderTypes; + protected final List<net.minecraft.client.renderer.RenderType> fabulousItemRenderTypes;
+ /** Forge: If this model's {@linkplain #blockRenderTypes block render types} are rendering cutout, to account for older leaves model JSONs */
+ protected final boolean isRenderingCutout;
+ +
+ /** @deprecated Forge: Use {@linkplain #SimpleBakedModel(List, Map, boolean, boolean, boolean, TextureAtlasSprite, ItemTransforms, ItemOverrides, net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/ + /** @deprecated Forge: Use {@linkplain #SimpleBakedModel(List, Map, boolean, boolean, boolean, TextureAtlasSprite, ItemTransforms, ItemOverrides, net.minecraftforge.client.RenderTypeGroup, net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/
+ @Deprecated + @Deprecated
+ public SimpleBakedModel(List<BakedQuad> p_119489_, Map<Direction, List<BakedQuad>> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_) { + public SimpleBakedModel(List<BakedQuad> p_119489_, Map<Direction, List<BakedQuad>> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_) {
+ this(p_119489_, p_119490_, p_119491_, p_119492_, p_119493_, p_119494_, p_119495_, p_119496_, net.minecraftforge.client.RenderTypeGroup.EMPTY); + this(p_119489_, p_119490_, p_119491_, p_119492_, p_119493_, p_119494_, p_119495_, p_119496_, net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ } + }
+
+ /** @deprecated Forge: Use {@linkplain #SimpleBakedModel(List, Map, boolean, boolean, boolean, TextureAtlasSprite, ItemTransforms, ItemOverrides, net.minecraftforge.client.RenderTypeGroup, net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup for fast graphics} **/
+ @Deprecated(forRemoval = true, since = "1.21.4")
+ public SimpleBakedModel(List<BakedQuad> p_119489_, Map<Direction, List<BakedQuad>> p_119490_, boolean p_119491_, boolean p_119492_, boolean p_119493_, TextureAtlasSprite p_119494_, ItemTransforms p_119495_, ItemOverrides p_119496_, net.minecraftforge.client.RenderTypeGroup renderTypes) {
+ this(p_119489_, p_119490_, p_119491_, p_119492_, p_119493_, p_119494_, p_119495_, p_119496_, renderTypes, net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ }
+
+ /** Constructor with {@link net.minecraftforge.client.RenderTypeGroup RenderTypeGroup} for fancy and fast graphics. Preferred over {@link net.minecraft.client.renderer.ItemBlockRenderTypes#setRenderLayer(net.minecraft.world.level.block.Block, net.minecraft.client.renderer.RenderType) ItemBlockRenderTypes.setRenderLayer(Block, RenderType)}. */
public SimpleBakedModel( public SimpleBakedModel(
List<BakedQuad> p_119489_, List<BakedQuad> p_119489_,
@@ -35,7 +_,8 @@ Map<Direction, List<BakedQuad>> p_119490_,
@@ -35,7 +_,9 @@
boolean p_119493_, boolean p_119493_,
TextureAtlasSprite p_119494_, TextureAtlasSprite p_119494_,
ItemTransforms p_119495_, ItemTransforms p_119495_,
- ItemOverrides p_119496_ - ItemOverrides p_119496_
+ ItemOverrides p_119496_, + ItemOverrides p_119496_,
+ net.minecraftforge.client.RenderTypeGroup renderTypes + net.minecraftforge.client.RenderTypeGroup renderTypes,
+ net.minecraftforge.client.RenderTypeGroup renderTypesFast
) { ) {
this.unculledFaces = p_119489_; this.unculledFaces = p_119489_;
this.culledFaces = p_119490_; this.culledFaces = p_119490_;
@@ -45,6 +_,9 @@ @@ -45,6 +_,15 @@
this.particleIcon = p_119494_; this.particleIcon = p_119494_;
this.transforms = p_119495_; this.transforms = p_119495_;
this.overrides = p_119496_; this.overrides = p_119496_;
+ this.blockRenderTypes = !renderTypes.isEmpty() ? net.minecraftforge.client.ChunkRenderTypeSet.of(renderTypes.block()) : null; +
+ this.itemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entity()) : null; + boolean hasRenderTypes = renderTypes != null && !renderTypes.isEmpty();
+ this.fabulousItemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entityFabulous()) : null; + boolean hasRenderTypesFast = renderTypesFast != null && !renderTypesFast.isEmpty();
+ this.blockRenderTypes = hasRenderTypes ? net.minecraftforge.client.ChunkRenderTypeSet.of(renderTypes.block()) : null;
+ this.blockRenderTypesFast = hasRenderTypesFast ? net.minecraftforge.client.ChunkRenderTypeSet.of(renderTypesFast.block()) : null;
+ this.itemRenderTypes = hasRenderTypes ? List.of(renderTypes.entity()) : null;
+ this.itemRenderTypesFast = hasRenderTypesFast ? List.of(renderTypesFast.entity()) : null;
+ this.fabulousItemRenderTypes = hasRenderTypes ? List.of(renderTypes.entityFabulous()) : null;
+ this.isRenderingCutout = hasRenderTypes && (renderTypes.block() == net.minecraft.client.renderer.RenderType.cutout() || renderTypes.block() == net.minecraft.client.renderer.RenderType.cutoutMipped());
} }
@Override @Override
@@ -87,6 +_,25 @@ @@ -87,6 +_,38 @@
return this.overrides; return this.overrides;
} }
+ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID_BLOCK = net.minecraftforge.client.ChunkRenderTypeSet.of(net.minecraft.client.renderer.RenderType.solid());
+ private static final List<net.minecraft.client.renderer.RenderType> SOLID_BLOCK_ITEM = List.of(net.minecraft.client.renderer.RenderType.solid());
+
+ @Override + @Override
+ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource rand, net.minecraftforge.client.model.data.ModelData data) { + public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(BlockState state, RandomSource rand, net.minecraftforge.client.model.data.ModelData data) {
+ return blockRenderTypes != null ? blockRenderTypes : BakedModel.super.getRenderTypes(state, rand, data); + if (!net.minecraft.client.renderer.ItemBlockRenderTypes.isFancy()) {
+ if (blockRenderTypesFast != null)
+ return blockRenderTypesFast;
+ if (isRenderingCutout && state.getBlock() instanceof net.minecraft.world.level.block.LeavesBlock)
+ return SOLID_BLOCK;
+ }
+ return blockRenderTypes != null ? blockRenderTypes : BakedModel.super.getRenderTypes(state, rand, data);
+ } + }
+ +
+ @Override + @Override
+ public List<net.minecraft.client.renderer.RenderType> getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) { + public List<net.minecraft.client.renderer.RenderType> getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) {
+ if (!fabulous) { + if (!fabulous) {
+ if (itemRenderTypes != null) { + if (!net.minecraft.client.renderer.ItemBlockRenderTypes.isFancy()) {
+ return itemRenderTypes; + if (itemRenderTypesFast != null)
+ } + return itemRenderTypesFast;
+ } else { + if (isRenderingCutout && itemStack.getItem() instanceof net.minecraft.world.item.BlockItem blockItem && blockItem.getBlock() instanceof net.minecraft.world.level.block.LeavesBlock)
+ if (fabulousItemRenderTypes != null) { + return SOLID_BLOCK_ITEM;
+ return fabulousItemRenderTypes; + }
+ } + if (itemRenderTypes != null)
+ } + return itemRenderTypes;
+ return BakedModel.super.getRenderTypes(itemStack, fabulous); + } else {
+ if (fabulousItemRenderTypes != null)
+ return fabulousItemRenderTypes;
+ }
+ return BakedModel.super.getRenderTypes(itemStack, fabulous);
+ } + }
+ +
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public static class Builder { public static class Builder {
private final List<BakedQuad> unculledFaces = Lists.newArrayList(); private final List<BakedQuad> unculledFaces = Lists.newArrayList();
@@ -133,12 +_,18 @@ @@ -133,12 +_,49 @@
return this; return this;
} }
+ private net.minecraftforge.client.RenderTypeGroup renderTypes = net.minecraftforge.client.RenderTypeGroup.EMPTY; + private net.minecraftforge.client.RenderTypeGroup renderTypes = net.minecraftforge.client.RenderTypeGroup.EMPTY;
+ private net.minecraftforge.client.RenderTypeGroup renderTypesFast = net.minecraftforge.client.RenderTypeGroup.EMPTY;
+
+ /**
+ * Sets the render type to be used for this model, and will be used for any graphics setting.
+ * <p>
+ * If you need to set a specific render type for
+ * {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}, consider using
+ * {@link #renderTypes(net.minecraftforge.client.RenderTypeGroup, net.minecraftforge.client.RenderTypeGroup)
+ * renderTypes(RenderTypeGroup, RenderTypeGroup)} instead which allows choosing render types for both fancy and
+ * fast graphics.
+ *
+ * @apiNote If this model is for {@linkplain net.minecraft.world.level.block.LeavesBlock leaves} and if the
+ * given render type is either {@linkplain net.minecraft.client.renderer.RenderType#cutout() cutout} or
+ * {@linkplain net.minecraft.client.renderer.RenderType#cutoutMipped() cutout mipped}, it will be overridden
+ * with {@linkplain net.minecraft.client.renderer.RenderType#solid() solid} when fast graphics is enabled.
+ * @see #renderTypes(net.minecraftforge.client.RenderTypeGroup, net.minecraftforge.client.RenderTypeGroup)
+ * renderTypes(RenderTypeGroup, RenderTypeGroup)
+ */
+ public SimpleBakedModel.Builder renderTypes(net.minecraftforge.client.RenderTypeGroup renderTypes) { + public SimpleBakedModel.Builder renderTypes(net.minecraftforge.client.RenderTypeGroup renderTypes) {
+ return this.renderTypes(renderTypes, net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ }
+
+ /**
+ * Sets the render types to be used for this model: one for
+ * {@linkplain net.minecraft.client.GraphicsStatus#FANCY fancy graphics} and one for
+ * {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}.
+ *
+ * @see #renderTypes(net.minecraftforge.client.RenderTypeGroup)
+ */
+ public SimpleBakedModel.Builder renderTypes(net.minecraftforge.client.RenderTypeGroup renderTypes, net.minecraftforge.client.RenderTypeGroup renderTypesFast) {
+ this.renderTypes = renderTypes; + this.renderTypes = renderTypes;
+ this.renderTypesFast = renderTypesFast;
+ return this; + return this;
+ } + }
+ +
@@ -78,7 +146,8 @@
} else { } else {
return new SimpleBakedModel( return new SimpleBakedModel(
- this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides - this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides
+ this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides, this.renderTypes + // Forge: Account for render types in model JSONs
+ this.unculledFaces, this.culledFaces, this.hasAmbientOcclusion, this.usesBlockLight, this.isGui3d, this.particleIcon, this.transforms, this.overrides, this.renderTypes, this.renderTypesFast
); );
} }
} }
@@ -9,10 +9,11 @@
this.socket.setSoTimeout(5000); this.socket.setSoTimeout(5000);
this.socket.joinGroup(this.pingGroup); this.socket.joinGroup(this.pingGroup);
} }
@@ -89,6 +_,11 @@ @@ -88,7 +_,11 @@
String s = LanServerPinger.parseMotd(p_120097_);
String s1 = LanServerPinger.parseAddress(p_120097_); String s1 = LanServerPinger.parseAddress(p_120097_);
if (s1 != null) { if (s1 != null) {
s1 = p_120098_.getHostAddress() + ":" + s1; - s1 = p_120098_.getHostAddress() + ":" + s1;
+ if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) { + if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) {
+ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1; + s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1;
+ } else { + } else {
@@ -35,12 +35,16 @@
} }
return this; return this;
@@ -435,5 +_,20 @@ @@ -435,5 +_,24 @@
@Override @Override
public HolderLookup.RegistryLookup<T> asLookup() { public HolderLookup.RegistryLookup<T> asLookup() {
return this.lookup; return this.lookup;
+ } + }
+ +
+ public boolean isIntrusive() {
+ return this.unregisteredIntrusiveHolders != null;
+ }
+
+ private static final Set<ResourceLocation> KNOWN = new java.util.LinkedHashSet<>(); + private static final Set<ResourceLocation> KNOWN = new java.util.LinkedHashSet<>();
+ public static Set<ResourceLocation> getKnownRegistries() { + public static Set<ResourceLocation> getKnownRegistries() {
+ return java.util.Collections.unmodifiableSet(KNOWN); + return java.util.Collections.unmodifiableSet(KNOWN);
@@ -9,3 +9,29 @@
private final GameTestInfo testInfo; private final GameTestInfo testInfo;
private boolean finalCheckAdded; private boolean finalCheckAdded;
@@ -933,5 +_,25 @@
if (either.right().isPresent()) {
this.fail("Failed to set biome for test");
}
+ }
+
+ /**
+ * Adds a cleanup handler that will be called when the test is done, pass or fail.
+ */
+ public void addCleanup(Consumer<Boolean> handler) {
+ this.testInfo.addListener(new GameTestListener() {
+ @Override
+ public void testPassed(GameTestInfo info, GameTestRunner runner) {
+ handler.accept(true);
+ }
+
+ @Override
+ public void testFailed(GameTestInfo info, GameTestRunner runner) {
+ handler.accept(false);
+ }
+
+ @Override public void testStructureLoaded(GameTestInfo info) { }
+ @Override public void testAddedForRerun(GameTestInfo oldInfo, GameTestInfo newInfo, GameTestRunner runner) { }
+ });
}
}
@@ -1,15 +1,20 @@
--- a/net/minecraft/network/Connection.java --- a/net/minecraft/network/Connection.java
+++ b/net/minecraft/network/Connection.java +++ b/net/minecraft/network/Connection.java
@@ -107,9 +_,12 @@ @@ -107,9 +_,17 @@
private volatile Component delayedDisconnect; private volatile Component delayedDisconnect;
@Nullable @Nullable
BandwidthDebugMonitor bandwidthDebugMonitor; BandwidthDebugMonitor bandwidthDebugMonitor;
+ private java.util.function.Consumer<Connection> activationHandler; + private java.util.function.Consumer<Connection> activationHandler;
+ private final net.minecraftforge.common.util.PacketLogger packetLogger; + private final net.minecraftforge.common.util.PacketLogger packetLogger = new net.minecraftforge.common.util.PacketLogger(this);
+ private ProtocolInfo<?> outboundProtocol = null;
+ private ProtocolInfo<?> inboundProtocol = null;
public Connection(PacketFlow p_129482_) { public Connection(PacketFlow p_129482_) {
this.receiving = p_129482_; this.receiving = p_129482_;
+ this.packetLogger = new net.minecraftforge.common.util.PacketLogger(this); + if (this.receiving == PacketFlow.SERVERBOUND)
+ this.inboundProtocol = INITIAL_PROTOCOL;
+ else
+ this.outboundProtocol = INITIAL_PROTOCOL;
} }
@Override @Override
@@ -29,14 +34,23 @@
genericsFtw(p_129488_, packetlistener); genericsFtw(p_129488_, packetlistener);
} catch (RunningOnDifferentThreadException runningondifferentthreadexception) { } catch (RunningOnDifferentThreadException runningondifferentthreadexception) {
} catch (RejectedExecutionException rejectedexecutionexception) { } catch (RejectedExecutionException rejectedexecutionexception) {
@@ -249,6 +_,7 @@ @@ -218,6 +_,7 @@
p_326044_ -> p_326044_.pipeline().addAfter("encoder", "unbundler", packetbundleunpacker) if (p_333271_.flow() != this.getReceiving()) {
); throw new IllegalStateException("Invalid inbound protocol: " + p_333271_.id());
} } else {
+ unconfiguredpipelinehandler$outboundconfigurationtask = unconfiguredpipelinehandler$outboundconfigurationtask.andThen(f -> this.protocol = p_329145_.id()); + this.inboundProtocol = p_333271_;
this.packetListener = p_330962_;
boolean flag = p_329145_.id() == ConnectionProtocol.LOGIN; this.disconnectListener = null;
syncAfterConfigurationChange(this.channel.writeAndFlush(unconfiguredpipelinehandler$outboundconfigurationtask.andThen(p_326048_ -> this.sendLoginDisconnect = flag))); UnconfiguredPipelineHandler.InboundConfigurationTask unconfiguredpipelinehandler$inboundconfigurationtask = UnconfiguredPipelineHandler.setupInboundProtocol(
@@ -241,6 +_,8 @@
} else {
UnconfiguredPipelineHandler.OutboundConfigurationTask unconfiguredpipelinehandler$outboundconfigurationtask = UnconfiguredPipelineHandler.setupOutboundProtocol(
p_329145_
+ ).andThen(
+ f -> this.outboundProtocol = p_329145_
);
BundlerInfo bundlerinfo = p_329145_.bundlerInfo();
if (bundlerinfo != null) {
@@ -290,7 +_,8 @@ @@ -290,7 +_,8 @@
this.disconnectListener = p_330656_; this.disconnectListener = p_330656_;
this.runOnceConnected(p_326042_ -> { this.runOnceConnected(p_326042_ -> {
@@ -81,7 +95,7 @@
new Bootstrap().group(LOCAL_WORKER_GROUP.get()).handler(new ChannelInitializer<Channel>() { new Bootstrap().group(LOCAL_WORKER_GROUP.get()).handler(new ChannelInitializer<Channel>() {
@Override @Override
protected void initChannel(Channel p_332618_) { protected void initChannel(Channel p_332618_) {
@@ -616,6 +_,15 @@ @@ -616,6 +_,22 @@
public float getAverageSentPackets() { public float getAverageSentPackets() {
return this.averageSentPackets; return this.averageSentPackets;
@@ -91,9 +105,16 @@
+ return this.channel; + return this.channel;
+ } + }
+ +
+ private ConnectionProtocol protocol = INITIAL_PROTOCOL.id();
+ public ConnectionProtocol getProtocol() { + public ConnectionProtocol getProtocol() {
+ return protocol; + return outboundProtocol != null ? outboundProtocol.id() : inboundProtocol.id();
+ }
+
+ public ProtocolInfo<?> getInboundProtocolInfo() {
+ return this.inboundProtocol;
+ }
+
+ public ProtocolInfo<?> getOutputboundProtocolInfo() {
+ return this.outboundProtocol;
} }
public void setBandwidthLogger(LocalSampleLogger p_333554_) { public void setBandwidthLogger(LocalSampleLogger p_333554_) {
@@ -0,0 +1,11 @@
--- a/net/minecraft/network/FriendlyByteBuf.java
+++ b/net/minecraft/network/FriendlyByteBuf.java
@@ -1589,4 +_,8 @@
public boolean release(int p_130347_) {
return this.source.release(p_130347_);
}
+
+ public FriendlyByteBuf wrap(ByteBuf data) {
+ return new FriendlyByteBuf(data);
+ }
}
@@ -0,0 +1,14 @@
--- a/net/minecraft/network/RegistryFriendlyByteBuf.java
+++ b/net/minecraft/network/RegistryFriendlyByteBuf.java
@@ -16,6 +_,11 @@
return this.registryAccess;
}
+ @Override
+ public RegistryFriendlyByteBuf wrap(ByteBuf data) {
+ return new RegistryFriendlyByteBuf(data, this.registryAccess);
+ }
+
public static Function<ByteBuf, RegistryFriendlyByteBuf> decorator(RegistryAccess p_336066_) {
return p_328649_ -> new RegistryFriendlyByteBuf(p_328649_, p_336066_);
}
@@ -1,20 +1,20 @@
--- a/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java --- a/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java
+++ b/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java
@@ -32,7 +_,7 @@ @@ -35,7 +_,7 @@
import net.minecraft.network.protocol.common.custom.WorldGenAttemptDebugPayload; public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ClientCommonPacketListener> {
import net.minecraft.resources.ResourceLocation;
-public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ClientCommonPacketListener> {
+public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ClientCommonPacketListener>, net.minecraftforge.network.ICustomPacket<ClientboundCustomPayloadPacket> {
private static final int MAX_PAYLOAD_SIZE = 1048576; private static final int MAX_PAYLOAD_SIZE = 1048576;
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundCustomPayloadPacket> GAMEPLAY_STREAM_CODEC = CustomPacketPayload.<RegistryFriendlyByteBuf>codec( public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundCustomPayloadPacket> GAMEPLAY_STREAM_CODEC = CustomPacketPayload.<RegistryFriendlyByteBuf>codec(
p_330149_ -> DiscardedPayload.codec(p_330149_, 1048576), - p_330149_ -> DiscardedPayload.codec(p_330149_, 1048576),
@@ -77,4 +_,8 @@ + p_330149_ -> net.minecraftforge.common.ForgeHooks.getCustomPayloadCodec(p_330149_, 1048576),
public void handle(ClientCommonPacketListener p_299773_) { Util.make(
p_299773_.handleCustomPayload(this); Lists.newArrayList(
} new CustomPacketPayload.TypeAndCodec<>(BrandPayload.TYPE, BrandPayload.STREAM_CODEC),
+ @@ -64,7 +_,7 @@
+ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; } )
+ @Override public ResourceLocation getName() { return payload.type().id(); } .map(ClientboundCustomPayloadPacket::new, ClientboundCustomPayloadPacket::payload);
+ @Override public int getIndex() { return 0; } public static final StreamCodec<FriendlyByteBuf, ClientboundCustomPayloadPacket> CONFIG_STREAM_CODEC = CustomPacketPayload.<FriendlyByteBuf>codec(
} - p_331803_ -> DiscardedPayload.codec(p_331803_, 1048576),
+ p_331803_ -> net.minecraftforge.common.ForgeHooks.getCustomPayloadCodec(p_331803_, 1048576),
List.of(new CustomPacketPayload.TypeAndCodec<>(BrandPayload.TYPE, BrandPayload.STREAM_CODEC))
)
.map(ClientboundCustomPayloadPacket::new, ClientboundCustomPayloadPacket::payload);
@@ -1,20 +1,11 @@
--- a/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java --- a/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java
+++ b/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java
@@ -12,7 +_,7 @@ @@ -15,7 +_,7 @@
import net.minecraft.network.protocol.common.custom.DiscardedPayload; public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ServerCommonPacketListener> {
import net.minecraft.resources.ResourceLocation;
-public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ServerCommonPacketListener> {
+public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet<ServerCommonPacketListener>, net.minecraftforge.network.ICustomPacket<ServerboundCustomPayloadPacket> {
private static final int MAX_PAYLOAD_SIZE = 32767; private static final int MAX_PAYLOAD_SIZE = 32767;
public static final StreamCodec<FriendlyByteBuf, ServerboundCustomPayloadPacket> STREAM_CODEC = CustomPacketPayload.<FriendlyByteBuf>codec( public static final StreamCodec<FriendlyByteBuf, ServerboundCustomPayloadPacket> STREAM_CODEC = CustomPacketPayload.<FriendlyByteBuf>codec(
p_335203_ -> DiscardedPayload.codec(p_335203_, 32767), - p_335203_ -> DiscardedPayload.codec(p_335203_, 32767),
@@ -29,4 +_,8 @@ + p_335203_ -> net.minecraftforge.common.ForgeHooks.getCustomPayloadCodec(p_335203_, 32767),
public void handle(ServerCommonPacketListener p_297991_) { Util.make(Lists.newArrayList(new CustomPacketPayload.TypeAndCodec<>(BrandPayload.TYPE, BrandPayload.STREAM_CODEC)), p_334419_ -> {
p_297991_.handleCustomPayload(this); })
} )
+
+ @Override public @org.jetbrains.annotations.Nullable FriendlyByteBuf getInternalData() { return payload instanceof DiscardedPayload dc ? dc.data() : null; }
+ @Override public ResourceLocation getName() { return payload.type().id(); }
+ @Override public int getIndex() { return 0; }
}
@@ -1,30 +0,0 @@
--- a/net/minecraft/network/protocol/common/custom/DiscardedPayload.java
+++ b/net/minecraft/network/protocol/common/custom/DiscardedPayload.java
@@ -4,18 +_,24 @@
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
-public record DiscardedPayload(ResourceLocation id) implements CustomPacketPayload {
+public record DiscardedPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomPacketPayload {
public static <T extends FriendlyByteBuf> StreamCodec<T, DiscardedPayload> codec(ResourceLocation p_328904_, int p_334650_) {
return CustomPacketPayload.codec((p_330619_, p_329210_) -> {
+ if (p_330619_.data != null) {
+ p_329210_.writeBytes(p_330619_.data.slice());
+ }
}, p_333509_ -> {
int i = p_333509_.readableBytes();
if (i >= 0 && i <= p_334650_) {
- p_333509_.skipBytes(i);
- return new DiscardedPayload(p_328904_);
+ return new DiscardedPayload(p_328904_, new FriendlyByteBuf(p_333509_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than " + p_334650_ + " bytes");
}
});
+ }
+
+ public DiscardedPayload(ResourceLocation id) {
+ this(id, null);
}
@Override
@@ -1,30 +0,0 @@
--- a/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java
+++ b/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java
@@ -8,7 +_,7 @@
import net.minecraft.network.protocol.login.custom.DiscardedQueryPayload;
import net.minecraft.resources.ResourceLocation;
-public record ClientboundCustomQueryPacket(int transactionId, CustomQueryPayload payload) implements Packet<ClientLoginPacketListener> {
+public record ClientboundCustomQueryPacket(int transactionId, CustomQueryPayload payload) implements Packet<ClientLoginPacketListener>, net.minecraftforge.network.ICustomPacket<ClientboundCustomQueryPacket> {
public static final StreamCodec<FriendlyByteBuf, ClientboundCustomQueryPacket> STREAM_CODEC = Packet.codec(
ClientboundCustomQueryPacket::write, ClientboundCustomQueryPacket::new
);
@@ -25,8 +_,7 @@
private static DiscardedQueryPayload readUnknownPayload(ResourceLocation p_299981_, FriendlyByteBuf p_297706_) {
int i = p_297706_.readableBytes();
if (i >= 0 && i <= 1048576) {
- p_297706_.skipBytes(i);
- return new DiscardedQueryPayload(p_299981_);
+ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes");
}
@@ -46,4 +_,8 @@
public void handle(ClientLoginPacketListener p_134754_) {
p_134754_.handleCustomQuery(this);
}
+
+ @Override public int getIndex() { return transactionId(); }
+ @Override public ResourceLocation getName() { return this.payload.id(); }
+ @org.jetbrains.annotations.Nullable @Override public FriendlyByteBuf getInternalData() { return ((DiscardedQueryPayload)this.payload).data(); }
}
@@ -1,30 +0,0 @@
--- a/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java
+++ b/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java
@@ -8,7 +_,7 @@
import net.minecraft.network.protocol.login.custom.CustomQueryAnswerPayload;
import net.minecraft.network.protocol.login.custom.DiscardedQueryAnswerPayload;
-public record ServerboundCustomQueryAnswerPacket(int transactionId, @Nullable CustomQueryAnswerPayload payload) implements Packet<ServerLoginPacketListener> {
+public record ServerboundCustomQueryAnswerPacket(int transactionId, @Nullable CustomQueryAnswerPayload payload) implements Packet<ServerLoginPacketListener>, net.minecraftforge.network.ICustomPacket<ServerboundCustomQueryAnswerPacket> {
public static final StreamCodec<FriendlyByteBuf, ServerboundCustomQueryAnswerPacket> STREAM_CODEC = Packet.codec(
ServerboundCustomQueryAnswerPacket::write, ServerboundCustomQueryAnswerPacket::read
);
@@ -26,8 +_,7 @@
private static CustomQueryAnswerPayload readUnknownPayload(FriendlyByteBuf p_299934_) {
int i = p_299934_.readableBytes();
if (i >= 0 && i <= 1048576) {
- p_299934_.skipBytes(i);
- return DiscardedQueryAnswerPayload.INSTANCE;
+ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes");
}
@@ -46,4 +_,8 @@
public void handle(ServerLoginPacketListener p_298492_) {
p_298492_.handleCustomQueryPacket(this);
}
+
+ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.payload instanceof DiscardedQueryAnswerPayload dc ? dc.data() : null; }
+ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.NetworkInitialization.LOGIN_NAME; }
+ @Override public int getIndex() { return transactionId(); }
}
@@ -1,21 +1,26 @@
--- a/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java
+++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryAnswerPayload.java
@@ -2,10 +_,17 @@ @@ -2,10 +_,22 @@
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
-public record DiscardedQueryAnswerPayload() implements CustomQueryAnswerPayload { -public record DiscardedQueryAnswerPayload() implements CustomQueryAnswerPayload {
+public record DiscardedQueryAnswerPayload(@javax.annotation.Nullable FriendlyByteBuf data) implements CustomQueryAnswerPayload { +public record DiscardedQueryAnswerPayload(
+ @javax.annotation.Nullable FriendlyByteBuf data,
+ java.util.function.Consumer<FriendlyByteBuf> encoder
+) implements CustomQueryAnswerPayload {
public static final DiscardedQueryAnswerPayload INSTANCE = new DiscardedQueryAnswerPayload(); public static final DiscardedQueryAnswerPayload INSTANCE = new DiscardedQueryAnswerPayload();
+ public DiscardedQueryAnswerPayload() { + public DiscardedQueryAnswerPayload() {
+ this(null); + this(null, buf -> {});
+ } + }
+ +
@Override @Override
public void write(FriendlyByteBuf p_299186_) { public void write(FriendlyByteBuf p_299186_) {
+ if (this.data != null) { + if (this.data != null) {
+ p_299186_.writeBytes(this.data.slice()); + p_299186_.writeBytes(this.data.slice());
+ } else {
+ encoder.accept(p_299186_);
+ } + }
} }
} }
@@ -1,23 +1,25 @@
--- a/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java --- a/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java
+++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java +++ b/net/minecraft/network/protocol/login/custom/DiscardedQueryPayload.java
@@ -3,12 +_,18 @@ @@ -3,9 +_,21 @@
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
-public record DiscardedQueryPayload(ResourceLocation id) implements CustomQueryPayload { -public record DiscardedQueryPayload(ResourceLocation id) implements CustomQueryPayload {
+public record DiscardedQueryPayload(ResourceLocation id, @org.jetbrains.annotations.Nullable FriendlyByteBuf data) implements CustomQueryPayload { +public record DiscardedQueryPayload(ResourceLocation id,
+ @org.jetbrains.annotations.Nullable FriendlyByteBuf data,
+ java.util.function.Consumer<net.minecraft.network.FriendlyByteBuf> encoder
+) implements CustomQueryPayload {
+ public DiscardedQueryPayload(ResourceLocation id) { + public DiscardedQueryPayload(ResourceLocation id) {
+ this(id, null); + this(id, null, buf -> {});
+ } + }
+ +
@Override @Override
public void write(FriendlyByteBuf p_299949_) { public void write(FriendlyByteBuf p_299949_) {
+ if (this.data != null) { + if (this.data != null) {
+ p_299949_.writeBytes(this.data.slice()); + p_299949_.writeBytes(this.data.slice());
+ } else {
+ encoder.accept(p_299949_);
+ } + }
} }
- @Override @Override
public ResourceLocation id() {
return this.id;
}
@@ -1,10 +1,12 @@
--- a/net/minecraft/network/syncher/EntityDataSerializers.java --- a/net/minecraft/network/syncher/EntityDataSerializers.java
+++ b/net/minecraft/network/syncher/EntityDataSerializers.java +++ b/net/minecraft/network/syncher/EntityDataSerializers.java
@@ -121,15 +_,16 @@ @@ -120,16 +_,18 @@
public static final EntityDataSerializer<Quaternionf> QUATERNION = EntityDataSerializer.forValueType(ByteBufCodecs.QUATERNIONF);
public static void registerSerializer(EntityDataSerializer<?> p_135051_) { public static void registerSerializer(EntityDataSerializer<?> p_135051_) {
+ int id =
SERIALIZERS.add(p_135051_); SERIALIZERS.add(p_135051_);
+ if (SERIALIZERS.add(p_135051_) >= 256) throw new RuntimeException("Vanilla DataSerializer ID limit exceeded"); + if (id >= 256) throw new RuntimeException("Vanilla DataSerializer ID limit exceeded");
} }
@Nullable @Nullable
@@ -39,6 +39,15 @@
); );
return dataresult.map(p_326149_ -> Pair.of((HolderSet<E>)p_326149_, (T)p_326147_.getSecond())); return dataresult.map(p_326149_ -> Pair.of((HolderSet<E>)p_326149_, (T)p_326147_.getSecond()));
} }
@@ -90,7 +_,7 @@
}
private <T> DataResult<Pair<HolderSet<E>, T>> decodeWithoutRegistry(DynamicOps<T> p_206671_, T p_206672_) {
- return this.elementCodec.listOf().decode(p_206671_, p_206672_).flatMap(p_206666_ -> {
+ return this.homogenousListCodec.decode(p_206671_, p_206672_).flatMap(p_206666_ -> { // Forge: Match encodeWithoutRegistry's use of the homogenousListCodec
List<Holder.Direct<E>> list = new ArrayList<>();
for (Holder<E> holder : p_206666_.getFirst()) {
@@ -106,6 +_,9 @@ @@ -106,6 +_,9 @@
} }
@@ -46,17 +46,26 @@
RegistryOps<JsonElement> p_332135_, RegistryOps<JsonElement> p_332135_,
ResourceKey<E> p_332850_, ResourceKey<E> p_332850_,
Resource p_335244_, Resource p_335244_,
@@ -197,7 +_,14 @@ @@ -197,7 +_,23 @@
) throws IOException { ) throws IOException {
try (Reader reader = p_335244_.openAsReader()) { try (Reader reader = p_335244_.openAsReader()) {
JsonElement jsonelement = JsonParser.parseReader(reader); JsonElement jsonelement = JsonParser.parseReader(reader);
- DataResult<E> dataresult = p_333909_.parse(p_332135_, jsonelement); - DataResult<E> dataresult = p_333909_.parse(p_332135_, jsonelement);
+ +
+ var result = p_333909_.decode(p_332135_, jsonelement); + var result = p_333909_.decode(p_332135_, jsonelement);
+ if (result.result().map(p -> p.getFirst()).isEmpty()) { +
+ LOGGER.debug("Skipping {} conditions not met", p_332850_); + if (result.isError()) {
+ return; + LOGGER.error("Couldn't parse data file {}: {}", p_332850_, result.error().get().message());
+ throw new IllegalStateException("Couldn't parse data file " + p_332850_ + ": " + result.error().get().message());
+ } + }
+
+ var mappedResult = result.result().map(a -> a.getFirst());
+
+ if (mappedResult.get().isEmpty()) {
+ LOGGER.debug("Skipping {} conditions not met", p_332850_);
+ return;
+ }
+
+ DataResult<E> dataresult = result.map(p -> p.mapFirst(Optional::get)).map(p -> p.getFirst()); + DataResult<E> dataresult = result.map(p -> p.mapFirst(Optional::get)).map(p -> p.getFirst());
+ +
E e = dataresult.getOrThrow(); E e = dataresult.getOrThrow();
@@ -1,5 +1,29 @@
--- a/net/minecraft/resources/ResourceLocation.java --- a/net/minecraft/resources/ResourceLocation.java
+++ b/net/minecraft/resources/ResourceLocation.java +++ b/net/minecraft/resources/ResourceLocation.java
@@ -38,6 +_,8 @@
this.path = p_249394_;
}
+ /** @deprecated Forge: Consider using {@link #fromNamespaceAndPath(String, String)} instead, as Mojang made this constructor private in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public ResourceLocation(String p_135811_, String p_135812_) {
this(assertValidNamespace(p_135811_, p_135812_), assertValidPath(p_135811_, p_135812_), null);
}
@@ -46,10 +_,14 @@
this(p_135814_[0], p_135814_[1]);
}
+ /** @deprecated Forge: Consider using {@link #parse(String)} instead, as Mojang made this constructor private in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public ResourceLocation(String p_135809_) {
this(decompose(p_135809_, ':'));
}
+ /** @deprecated Forge: Consider using {@link #bySeparator(String, char)} instead, as Mojang removed this method in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public static ResourceLocation of(String p_135823_, char p_135824_) {
return new ResourceLocation(decompose(p_135823_, p_135824_));
}
@@ -147,6 +_,12 @@ @@ -147,6 +_,12 @@
return i; return i;
} }
@@ -13,3 +37,55 @@
public String toDebugFileName() { public String toDebugFileName() {
return this.toString().replace('/', '_').replace(':', '_'); return this.toString().replace('/', '_').replace(':', '_');
} }
@@ -278,6 +_,51 @@
public JsonElement serialize(ResourceLocation p_135855_, Type p_135856_, JsonSerializationContext p_135857_) {
return new JsonPrimitive(p_135855_.toString());
+ }
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #ResourceLocation(String, String)}. */
+ public static ResourceLocation fromNamespaceAndPath(String namespace, String path) {
+ return new ResourceLocation(namespace, path);
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #ResourceLocation(String)}. */
+ public static ResourceLocation parse(String location) {
+ return new ResourceLocation(location);
+ }
+
+ /**
+ * Forge: This is a backported method from 1.21, and acts as an alternative to using {@link #parse(String)}. If you
+ * know for sure you are going to be using the {@linkplain #DEFAULT_NAMESPACE default namespace}
+ * ({@code "minecraft"}), use this.
+ */
+ public static ResourceLocation withDefaultNamespace(String path) {
+ return new ResourceLocation(DEFAULT_NAMESPACE, assertValidPath(DEFAULT_NAMESPACE, path), null);
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #of(String, char)}. */
+ public static ResourceLocation bySeparator(String location, char separator) {
+ return of(location, separator);
+ }
+
+ /**
+ * Forge: This is a backported method from 1.21, and is the same as {@link #bySeparator(String, char)} but returns
+ * {@code null} if a resource location cannot be created.
+ */
+ public static @Nullable ResourceLocation tryBySeparator(String location, char separator) {
+ int i = location.indexOf(separator);
+ if (i >= 0) {
+ String s = location.substring(i + 1);
+ if (!isValidPath(s)) {
+ return null;
+ } else if (i != 0) {
+ String s1 = location.substring(0, i);
+ return isValidNamespace(s1) ? new ResourceLocation(s1, s, null) : null;
+ } else {
+ return new ResourceLocation(DEFAULT_NAMESPACE, s, null);
+ }
+ } else {
+ return isValidPath(location) ? new ResourceLocation(DEFAULT_NAMESPACE, location, null) : null;
}
}
}
@@ -26,7 +26,7 @@
p_326196_ -> { p_326196_ -> {
ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_326196_.compositeAccess(), p_250212_, p_249301_, p_251126_); ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_326196_.compositeAccess(), p_250212_, p_249301_, p_251126_);
+ var listeners = new java.util.ArrayList<>(reloadableserverresources.listeners()); + var listeners = new java.util.ArrayList<>(reloadableserverresources.listeners());
+ listeners.addAll(net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, p_330376_.compositeAccess())); + listeners.addAll(net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, reloadableserverresources.registryLookup, p_330376_.compositeAccess()));
return SimpleReloadInstance.create( return SimpleReloadInstance.create(
- p_248588_, reloadableserverresources.listeners(), p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled() - p_248588_, reloadableserverresources.listeners(), p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled()
+ p_248588_, listeners, p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled() + p_248588_, listeners, p_249136_, p_249601_, DATA_RELOAD_INITIAL_TASK, LOGGER.isDebugEnabled()
@@ -75,6 +75,14 @@
} }
} }
@@ -738,6 +_,7 @@
p_8648_.tickCount++;
this.getProfiler().push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(p_8648_.getType()).toString());
profilerfiller.incrementCounter("tickNonPassenger");
+ if (p_8648_.canUpdate())
p_8648_.tick();
this.getProfiler().pop();
@@ -755,6 +_,7 @@ @@ -755,6 +_,7 @@
ProfilerFiller profilerfiller = this.getProfiler(); ProfilerFiller profilerfiller = this.getProfiler();
profilerfiller.push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(p_8664_.getType()).toString()); profilerfiller.push(() -> BuiltInRegistries.ENTITY_TYPE.getKey(p_8664_.getType()).toString());
@@ -14,7 +14,7 @@
@Override @Override
public void die(DamageSource p_9035_) { public void die(DamageSource p_9035_) {
+ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_9035_)) return; + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, p_9035_)) return;
this.gameEvent(GameEvent.ENTITY_DIE); this.gameEvent(GameEvent.ENTITY_DIE);
boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES); boolean flag = this.level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES);
if (flag) { if (flag) {
@@ -5,7 +5,7 @@
public void handleBlockBreakAction(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) { public void handleBlockBreakAction(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) {
+ var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(player, p_215120_, p_215122_, p_215121_); + var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(player, p_215120_, p_215122_, p_215121_);
+ if (event.isCanceled() || (!this.isCreative() && event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY)) { + if (event.isCanceled() || (!this.isCreative() && event.getResult().isDenied())) {
+ return; + return;
+ } + }
if (!this.player.canInteractWithBlock(p_215120_, 1.0)) { if (!this.player.canInteractWithBlock(p_215120_, 1.0)) {
@@ -4,7 +4,7 @@
@Override @Override
public void handleCustomPayload(ServerboundCustomPayloadPacket p_300164_) { public void handleCustomPayload(ServerboundCustomPayloadPacket p_300164_) {
+ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_, this.connection); + net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_.payload(), this.connection);
} }
@Override @Override
@@ -1,17 +1,5 @@
--- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java --- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java +++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -437,9 +_,11 @@
}
entity.absMoveTo(d3, d4, d5, f, f1);
+ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving
boolean flag3 = serverlevel.noCollision(entity, entity.getBoundingBox().deflate(0.0625));
if (flag && (flag2 || !flag3)) {
entity.absMoveTo(d0, d1, d2, f, f1);
+ this.player.absMoveTo(d3, d4, d5, this.player.getYRot(), this.player.getXRot()); // Forge - Resync player position on vehicle moving
this.send(new ClientboundMoveVehiclePacket(entity));
return;
}
@@ -1005,9 +_,10 @@ @@ -1005,9 +_,10 @@
switch (serverboundplayeractionpacket$action) { switch (serverboundplayeractionpacket$action) {
case SWAP_ITEM_WITH_OFFHAND: case SWAP_ITEM_WITH_OFFHAND:
@@ -37,3 +25,20 @@
PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(p_296589_.mask()); PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(p_296589_.mask());
this.broadcastChatMessage(playerchatmessage1); this.broadcastChatMessage(playerchatmessage1);
}); });
@@ -1516,7 +_,7 @@
@Override
public void onInteraction(InteractionHand p_143682_, Vec3 p_143683_) {
- this.performInteraction(p_143682_, (p_143686_, p_143687_, p_143688_) -> p_143687_.interactAt(p_143686_, p_143683_, p_143688_));
+ this.performInteraction(p_143682_, (p_143686_, p_143687_, p_143688_) -> net.minecraftforge.common.ForgeHooks.onInteractEntityAt(p_143687_, p_143686_, p_143683_, p_143688_));
}
@Override
@@ -1797,6 +_,7 @@
@Override
public void handleCustomPayload(ServerboundCustomPayloadPacket p_329963_) {
+ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_329963_.payload(), this.connection);
}
@Override
@@ -8,6 +8,14 @@
public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess<RegistryLayer> p_251844_, PlayerDataStorage p_203844_, int p_203845_) { public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess<RegistryLayer> p_251844_, PlayerDataStorage p_203844_, int p_203845_) {
this.server = p_203842_; this.server = p_203842_;
@@ -199,6 +_,7 @@
servergamepacketlistenerimpl.send(new ClientboundChangeDifficultyPacket(leveldata.getDifficulty(), leveldata.isDifficultyLocked()));
servergamepacketlistenerimpl.send(new ClientboundPlayerAbilitiesPacket(p_11263_.getAbilities()));
servergamepacketlistenerimpl.send(new ClientboundSetCarriedItemPacket(p_11263_.getInventory().selected));
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, p_11263_));
servergamepacketlistenerimpl.send(new ClientboundUpdateRecipesPacket(this.server.getRecipeManager().getOrderedRecipes()));
this.sendPlayerPermissionLevel(p_11263_);
p_11263_.getStats().markAllDirty();
@@ -267,6 +_,7 @@ @@ -267,6 +_,7 @@
} }
@@ -129,9 +129,9 @@
} }
public boolean canBeAffected(MobEffectInstance p_21197_) { public boolean canBeAffected(MobEffectInstance p_21197_) {
+ var event = net.minecraftforge.event.ForgeEventFactory.onLivingEffectCanApply(this, p_21197_); + var eventResult = net.minecraftforge.event.ForgeEventFactory.onLivingEffectCanApply(this, p_21197_).getResult();
+ if (event.getResult() != net.minecraftforge.eventbus.api.Event.Result.DEFAULT) { + if (!eventResult.isDefault()) {
+ return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW; + return eventResult.isAllowed();
+ } + }
if (this.getType().is(EntityTypeTags.IMMUNE_TO_INFESTED)) { if (this.getType().is(EntityTypeTags.IMMUNE_TO_INFESTED)) {
return !p_21197_.is(MobEffects.INFESTED); return !p_21197_.is(MobEffects.INFESTED);
@@ -220,7 +220,7 @@
} }
public void die(DamageSource p_21014_) { public void die(DamageSource p_21014_) {
+ if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, p_21014_)) return; + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, p_21014_)) return;
if (!this.isRemoved() && !this.dead) { if (!this.isRemoved() && !this.dead) {
Entity entity = p_21014_.getEntity(); Entity entity = p_21014_.getEntity();
LivingEntity livingentity = this.getKillCredit(); LivingEntity livingentity = this.getKillCredit();
@@ -252,7 +252,7 @@
this.dropExperience(); this.dropExperience();
+ +
+ var drops = captureDrops(null); + var drops = captureDrops(null);
+ if (!net.minecraftforge.common.ForgeHooks.onLivingDrops(this, p_21192_, drops, i, lastHurtByPlayerTime > 0)) { + if (!net.minecraftforge.event.ForgeEventFactory.onLivingDrops(this, p_21192_, drops, i, lastHurtByPlayerTime > 0)) {
+ drops.forEach(e -> level().addFreshEntity(e)); + drops.forEach(e -> level().addFreshEntity(e));
+ } + }
} }
@@ -439,7 +439,7 @@
@Override @Override
public void tick() { public void tick() {
+ if (net.minecraftforge.common.ForgeHooks.onLivingTick(this)) return; + if (net.minecraftforge.event.ForgeEventFactory.onLivingTick(this)) return;
super.tick(); super.tick();
this.updatingUsingItem(); this.updatingUsingItem();
this.updateSwimAmount(); this.updateSwimAmount();
@@ -524,14 +524,12 @@
this.completeUsingItem(); this.completeUsingItem();
} }
} }
@@ -3032,8 +_,12 @@ @@ -3032,8 +_,10 @@
public void startUsingItem(InteractionHand p_21159_) { public void startUsingItem(InteractionHand p_21159_) {
ItemStack itemstack = this.getItemInHand(p_21159_); ItemStack itemstack = this.getItemInHand(p_21159_);
if (!itemstack.isEmpty() && !this.isUsingItem()) { if (!itemstack.isEmpty() && !this.isUsingItem()) {
+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration()); + int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration());
+ if (duration <= 0) { + if (duration < net.minecraftforge.common.ForgeConfig.SERVER.getUseItemDuration()) return;
+ return;
+ }
this.useItem = itemstack; this.useItem = itemstack;
- this.useItemRemaining = itemstack.getUseDuration(); - this.useItemRemaining = itemstack.getUseDuration();
+ this.useItemRemaining = duration; + this.useItemRemaining = duration;
@@ -586,7 +584,7 @@
Item item = this.useItem.getItem(); Item item = this.useItem.getItem();
- return item.getUseAnimation(this.useItem) != UseAnim.BLOCK ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5; - return item.getUseAnimation(this.useItem) != UseAnim.BLOCK ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5;
+ boolean canBlock = this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK); + boolean canBlock = this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK);
+ return canBlock ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5; + return !canBlock ? false : item.getUseDuration(this.useItem) - this.useItemRemaining >= 5;
} else { } else {
return false; return false;
} }
@@ -1,10 +1,18 @@
--- a/net/minecraft/world/entity/Shearable.java --- a/net/minecraft/world/entity/Shearable.java
+++ b/net/minecraft/world/entity/Shearable.java +++ b/net/minecraft/world/entity/Shearable.java
@@ -2,6 +_,7 @@ @@ -2,8 +_,14 @@
import net.minecraft.sounds.SoundSource; import net.minecraft.sounds.SoundSource;
+/** @deprecated Use {@link net.minecraftforge.common.IForgeShearable} */ -public interface Shearable {
public interface Shearable { +public interface Shearable extends net.minecraftforge.common.IForgeShearable {
+ /** @deprecated Use {@link net.minecraftforge.common.IForgeShearable#onSheared} */
void shear(SoundSource p_21749_); void shear(SoundSource p_21749_);
+ /** @deprecated Use {@link net.minecraftforge.common.IForgeShearable#isShearable} */
boolean readyForShearing();
+
+ default boolean isShearable(net.minecraft.world.item.ItemStack item, net.minecraft.world.level.Level level, net.minecraft.core.BlockPos pos) {
+ return readyForShearing();
+ }
}
@@ -0,0 +1,13 @@
--- a/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java
+++ b/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java
@@ -84,6 +_,10 @@
}
mob = (Mob)iterator.next();
+ // Fix NPE if modders do things vanilla doesn't expect. https://github.com/MinecraftForge/MinecraftForge/issues/7853
+ if (this.mob.getLastHurtByMob() == null)
+ return;
+
if (this.mob != mob
&& mob.getTarget() == null
&& (!(this.mob instanceof TamableAnimal) || ((TamableAnimal)this.mob).getOwner() == ((TamableAnimal)mob).getOwner())
@@ -1,14 +1,5 @@
--- a/net/minecraft/world/entity/animal/MushroomCow.java --- a/net/minecraft/world/entity/animal/MushroomCow.java
+++ b/net/minecraft/world/entity/animal/MushroomCow.java +++ b/net/minecraft/world/entity/animal/MushroomCow.java
@@ -42,7 +_,7 @@
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gameevent.GameEvent;
-public class MushroomCow extends Cow implements Shearable, VariantHolder<MushroomCow.MushroomType> {
+public class MushroomCow extends Cow implements Shearable, VariantHolder<MushroomCow.MushroomType>, net.minecraftforge.common.IForgeShearable {
private static final EntityDataAccessor<String> DATA_TYPE = SynchedEntityData.defineId(MushroomCow.class, EntityDataSerializers.STRING);
private static final int MUTATE_CHANCE = 1024;
private static final String TAG_STEW_EFFECTS = "stew_effects";
@@ -108,7 +_,7 @@ @@ -108,7 +_,7 @@
this.playSound(soundevent, 1.0F, 1.0F); this.playSound(soundevent, 1.0F, 1.0F);
@@ -55,7 +46,7 @@
} }
@Override @Override
@@ -255,6 +_,17 @@ @@ -255,6 +_,12 @@
} }
return mushroomcow$mushroomtype2; return mushroomcow$mushroomtype2;
@@ -65,11 +56,6 @@
+ public java.util.List<ItemStack> onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { + public java.util.List<ItemStack> onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) {
+ this.gameEvent(GameEvent.SHEAR, player); + this.gameEvent(GameEvent.SHEAR, player);
+ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS); + return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS);
+ }
+
+ @Override
+ public boolean isShearable(ItemStack item, Level world, BlockPos pos) {
+ return readyForShearing();
} }
public static enum MushroomType implements StringRepresentable { public static enum MushroomType implements StringRepresentable {
@@ -1,14 +1,5 @@
--- a/net/minecraft/world/entity/animal/Sheep.java --- a/net/minecraft/world/entity/animal/Sheep.java
+++ b/net/minecraft/world/entity/animal/Sheep.java +++ b/net/minecraft/world/entity/animal/Sheep.java
@@ -62,7 +_,7 @@
import net.minecraft.world.level.storage.loot.BuiltInLootTables;
import net.minecraft.world.level.storage.loot.LootTable;
-public class Sheep extends Animal implements Shearable {
+public class Sheep extends Animal implements Shearable, net.minecraftforge.common.IForgeShearable {
private static final int EAT_ANIMATION_TICKS = 40;
private static final EntityDataAccessor<Byte> DATA_WOOL_ID = SynchedEntityData.defineId(Sheep.class, EntityDataSerializers.BYTE);
private static final Map<DyeColor, ItemLike> ITEM_BY_DYE = Util.make(Maps.newEnumMap(DyeColor.class), p_29841_ -> {
@@ -208,7 +_,7 @@ @@ -208,7 +_,7 @@
@Override @Override
public InteractionResult mobInteract(Player p_29853_, InteractionHand p_29854_) { public InteractionResult mobInteract(Player p_29853_, InteractionHand p_29854_) {
@@ -44,18 +35,13 @@
if (itementity != null) { if (itementity != null) {
itementity.setDeltaMovement( itementity.setDeltaMovement(
itementity.getDeltaMovement() itementity.getDeltaMovement()
@@ -375,5 +_,15 @@ @@ -375,5 +_,10 @@
craftingcontainer.setItem(0, new ItemStack(DyeItem.byColor(p_29832_))); craftingcontainer.setItem(0, new ItemStack(DyeItem.byColor(p_29832_)));
craftingcontainer.setItem(1, new ItemStack(DyeItem.byColor(p_29833_))); craftingcontainer.setItem(1, new ItemStack(DyeItem.byColor(p_29833_)));
return craftingcontainer; return craftingcontainer;
+ } + }
+ +
+ @Override + @Override
+ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) {
+ return readyForShearing();
+ }
+
+ @Override
+ public java.util.List<ItemStack> onSheared(@Nullable Player player, ItemStack item, Level world, BlockPos pos, int fortune) { + public java.util.List<ItemStack> onSheared(@Nullable Player player, ItemStack item, Level world, BlockPos pos, int fortune) {
+ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS); + return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS);
} }
@@ -36,16 +36,11 @@
this.shear(SoundSource.PLAYERS); this.shear(SoundSource.PLAYERS);
this.gameEvent(GameEvent.SHEAR, p_29920_); this.gameEvent(GameEvent.SHEAR, p_29920_);
if (!this.level().isClientSide) { if (!this.level().isClientSide) {
@@ -189,4 +_,21 @@ @@ -189,4 +_,16 @@
public Vec3 getLeashOffset() { public Vec3 getLeashOffset() {
return new Vec3(0.0, (double)(0.75F * this.getEyeHeight()), (double)(this.getBbWidth() * 0.4F)); return new Vec3(0.0, (double)(0.75F * this.getEyeHeight()), (double)(this.getBbWidth() * 0.4F));
} }
+ +
+ @Override
+ public boolean isShearable(@org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos) {
+ return readyForShearing();
+ }
+
+ @org.jetbrains.annotations.NotNull + @org.jetbrains.annotations.NotNull
+ @Override + @Override
+ public java.util.List<ItemStack> onSheared(@Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) { + public java.util.List<ItemStack> onSheared(@Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) {
@@ -1,5 +1,33 @@
--- a/net/minecraft/world/entity/animal/Wolf.java --- a/net/minecraft/world/entity/animal/Wolf.java
+++ b/net/minecraft/world/entity/animal/Wolf.java +++ b/net/minecraft/world/entity/animal/Wolf.java
@@ -86,7 +_,7 @@
import net.minecraft.world.level.pathfinder.PathType;
import net.minecraft.world.phys.Vec3;
-public class Wolf extends TamableAnimal implements NeutralMob, VariantHolder<Holder<WolfVariant>> {
+public class Wolf extends TamableAnimal implements NeutralMob, VariantHolder<Holder<WolfVariant>>, net.minecraftforge.common.IForgeShearable {
private static final EntityDataAccessor<Boolean> DATA_INTERESTED_ID = SynchedEntityData.defineId(Wolf.class, EntityDataSerializers.BOOLEAN);
private static final EntityDataAccessor<Integer> DATA_COLLAR_COLOR = SynchedEntityData.defineId(Wolf.class, EntityDataSerializers.INT);
private static final EntityDataAccessor<Integer> DATA_REMAINING_ANGER_TIME = SynchedEntityData.defineId(Wolf.class, EntityDataSerializers.INT);
@@ -450,16 +_,11 @@
this.setBodyArmorItem(itemstack.copyWithCount(1));
itemstack.consume(1, p_30412_);
return InteractionResult.SUCCESS;
- } else if (itemstack.is(Items.SHEARS)
+ } else if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)
&& this.isOwnedBy(p_30412_)
&& this.hasArmor()
&& (!EnchantmentHelper.hasBindingCurse(this.getBodyArmorItem()) || p_30412_.isCreative())) {
- itemstack.hurtAndBreak(1, p_30412_, getSlotForHand(p_30413_));
- this.playSound(SoundEvents.ARMOR_UNEQUIP_WOLF);
- ItemStack itemstack1 = this.getBodyArmorItem();
- this.setBodyArmorItem(ItemStack.EMPTY);
- this.spawnAtLocation(itemstack1);
- return InteractionResult.SUCCESS;
+ return InteractionResult.PASS;
} else if (ArmorMaterials.ARMADILLO.value().repairIngredient().get().test(itemstack)
&& this.isInSittingPose()
&& this.hasArmor()
@@ -498,7 +_,7 @@ @@ -498,7 +_,7 @@
} }
@@ -9,3 +37,28 @@
this.tame(p_336244_); this.tame(p_336244_);
this.navigation.stop(); this.navigation.stop();
this.setTarget(null); this.setTarget(null);
@@ -650,6 +_,24 @@
return true;
}
+ }
+
+ @Override
+ public boolean isShearable(ItemStack item, Level world, BlockPos pos) {
+ return this.hasArmor();
+ }
+
+ @Override
+ public java.util.List<ItemStack> onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, BlockPos pos, int fortune) {
+ if (!this.hasArmor() || (player != null && !this.isOwnedBy(player)) ||
+ (EnchantmentHelper.hasBindingCurse(this.getBodyArmorItem()) && (player == null || !player.isCreative()))
+ )
+ return java.util.Collections.emptyList();
+
+ this.playSound(SoundEvents.ARMOR_UNEQUIP_WOLF);
+ var armor = this.getBodyArmorItem();
+ this.setBodyArmorItem(ItemStack.EMPTY);
+ return java.util.List.of(armor);
}
@Override
@@ -0,0 +1,49 @@
--- a/net/minecraft/world/entity/monster/Bogged.java
+++ b/net/minecraft/world/entity/monster/Bogged.java
@@ -74,7 +_,7 @@
@Override
protected InteractionResult mobInteract(Player p_335303_, InteractionHand p_335145_) {
ItemStack itemstack = p_335303_.getItemInHand(p_335145_);
- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) {
+ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: move to onSheared
this.shear(SoundSource.PLAYERS);
this.gameEvent(GameEvent.SHEAR, p_335303_);
if (!this.level().isClientSide) {
@@ -129,12 +_,20 @@
@Override
public void shear(SoundSource p_332421_) {
- this.level().playSound(null, this, SoundEvents.BOGGED_SHEAR, p_332421_, 1.0F, 1.0F);
- this.spawnShearedMushrooms();
+ shearInternal(p_332421_).stream().forEach(stack -> this.spawnAtLocation(stack, this.getBbHeight()));
+ }
+
+ @Override
+ public java.util.List<ItemStack> onSheared(@org.jetbrains.annotations.Nullable Player player, @org.jetbrains.annotations.NotNull ItemStack item, Level world, net.minecraft.core.BlockPos pos, int fortune) {
+ this.gameEvent(GameEvent.SHEAR, player);
+ return shearInternal(player == null ? SoundSource.BLOCKS : SoundSource.PLAYERS);
+ }
+
+ private java.util.List<ItemStack> shearInternal(SoundSource sound) {
+ this.level().playSound(null, this, SoundEvents.BOGGED_SHEAR, sound, 1.0F, 1.0F);
this.setSheared(true);
- }
- private void spawnShearedMushrooms() {
+ var ret = new java.util.ArrayList<ItemStack>();
if (this.level() instanceof ServerLevel serverlevel && serverlevel.getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) {
LootTable loottable = serverlevel.getServer().reloadableRegistries().getLootTable(BuiltInLootTables.BOGGED_SHEAR);
LootParams lootparams = new LootParams.Builder(serverlevel)
@@ -143,9 +_,11 @@
.create(LootContextParamSets.SHEARING);
for (ItemStack itemstack : loottable.getRandomItems(lootparams)) {
- this.spawnAtLocation(itemstack);
+ ret.add(itemstack);
}
}
+
+ return ret;
}
@Override
@@ -1,14 +1,12 @@
--- a/net/minecraft/world/entity/monster/Spider.java --- a/net/minecraft/world/entity/monster/Spider.java
+++ b/net/minecraft/world/entity/monster/Spider.java +++ b/net/minecraft/world/entity/monster/Spider.java
@@ -121,7 +_,12 @@ @@ -121,7 +_,10 @@
@Override @Override
public boolean canBeAffected(MobEffectInstance p_33809_) { public boolean canBeAffected(MobEffectInstance p_33809_) {
- return p_33809_.is(MobEffects.POISON) ? false : super.canBeAffected(p_33809_); - return p_33809_.is(MobEffects.POISON) ? false : super.canBeAffected(p_33809_);
+ if (p_33809_.getEffect() == MobEffects.POISON) { + if (p_33809_.getEffect() == MobEffects.POISON) {
+ net.minecraftforge.event.entity.living.MobEffectEvent.Applicable event = new net.minecraftforge.event.entity.living.MobEffectEvent.Applicable(this, p_33809_); + return net.minecraftforge.event.ForgeEventFactory.onLivingEffectCanApply(this, p_33809_).getResult().isAllowed();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event);
+ return event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW;
+ } + }
+ return super.canBeAffected(p_33809_); + return super.canBeAffected(p_33809_);
} }
@@ -36,9 +36,9 @@
+ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); + var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE));
+ +
+ Zombie zombie = null; + Zombie zombie = null;
+ if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW) { + if (event.getResult().isAllowed()) {
+ zombie = event.getCustomSummonedAid() != null ? event.getCustomSummonedAid() : EntityType.ZOMBIE.create(this.level()); + zombie = event.getCustomSummonedAid() != null ? event.getCustomSummonedAid() : EntityType.ZOMBIE.create(this.level());
+ } else if (event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && vanilla) { + } else if (vanilla && event.getResult().isDefault()) {
+ zombie = EntityType.ZOMBIE.create(this.level()); + zombie = EntityType.ZOMBIE.create(this.level());
+ } + }
+ +
@@ -73,21 +73,3 @@
if (!this.isSilent()) { if (!this.isSilent()) {
p_219160_.levelEvent(null, 1026, this.blockPosition(), 0); p_219160_.levelEvent(null, 1026, this.blockPosition(), 0);
} }
@@ -487,7 +_,7 @@
}
public static boolean getSpawnAsBabyOdds(RandomSource p_219163_) {
- return p_219163_.nextFloat() < 0.05F;
+ return p_219163_.nextFloat() < net.minecraftforge.common.ForgeConfig.SERVER.zombieBabyChance.get();
}
protected void handleAttributes(float p_34340_) {
@@ -510,7 +_,7 @@
}
protected void randomizeReinforcementsChance() {
- this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * 0.1F);
+ this.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(this.random.nextDouble() * net.minecraftforge.common.ForgeConfig.SERVER.zombieBaseSummonChance.get());
}
@Override
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff. Show more