Compare commits

...
36 Commits
Author SHA1 Message Date
Jonathing 0bca349d64 1.21.1 RB 1
https://forums.minecraftforge.net/topic/154391-forge-521-minecraft-1211/
2025-03-04 15:49:44 -05:00
Jonathing 7a44626d5e Add #forge:chorus_additionally_grows_on tag for similiar mechanics to #minecraft:azalea_grows_on but for chorus (#10461) 2025-03-04 12:39:44 -08:00
JonathingandLexManos 30ec79b19e Speed up mod annotation scanning by ~30% (#10467)
Co-authored-by: LexManos <[email protected]>
2025-03-04 12:27:17 -08:00
Jonathing 0794e51f62 Add missed license headers (#10476) 2025-03-04 12:26:57 -08:00
JonathingandLexManos c86172db31 Redstone updates and gametests structure fixes (#10422)
Fix game test structure rotations being inconsistent (#10391)
Fix redstone update order not matching vanilla. (#10392)
Fix redstone updates for comparators going up/down incorrectly. Related: #9973
Make block pos assertions in GameTestHelper behave like in 1.21.3, thus fixing rotated tests functionality.
This can be disabled in the Forge config if you have old tests that this breaks. Tho it is recommended you update your tests.

---------
Co-authored-by: LexManos <[email protected]>
2025-03-04 12:26:42 -08:00
Jonathing ee14c0c911 Bump dependencies (#10386)
- 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
- NightConfig 3.7.3 -> 3.7.4
2025-02-17 18:46:48 -08:00
b3a4ac864f Re-introduce ItemStack Capabilities (#10363)
Co-authored-by: RealMangoRage <[email protected]>
Co-authored-by: LexManos <[email protected]>
2025-02-17 18:40:35 -08:00
Jonathing f9139a3002 Re-introduce IForgeItem.damageItem when an item takes damage, Fixes #10344 (#10373) 2025-02-17 18:35:26 -08:00
Jonathing 784693b7e5 Add updated tag context to AddReloadListenerEvent (#10421)
Fixes using custom tags in GlobalLootModifiers.
2025-02-17 18:28:07 -08:00
Jonathing 774048154f Add fast graphics render type to block model jsons (#10396)
Make modded leaves behave like vanilla leaves by default (Fixes #10389)
2025-02-17 18:22:26 -08:00
Jonathing 490e35ba8e Fix corrupted and invalidly symlinked worlds crashing on level select (#10420) 2025-02-17 18:18:10 -08:00
Jonathing 667a164430 Honor attacker shield disabling status (#10318) 2025-01-27 15:33:47 -08:00
Joseph T. McQuigg 0434d67016 Fix issues in VillagerTrades.EmeraldsForVillagerTypeItem related to custom Villager Types (#10300)
Co-authored-by: Joseph T. McQuigg <[email protected]>
2025-01-27 15:33:29 -08:00
JonathingandLexManos 02229557ed GameTestHelper additions (#10340)
Co-authored-by: LexManos <[email protected]>
2025-01-27 09:58:00 -08:00
Jonathing 79224a70e6 Update Gradle to 8.12.1 (#10354)
Automate IntelliJ download sources in MDK
2025-01-27 09:57:46 -08:00
Jonathing 5c9c8ce539 Fix JOpt Simple by bumping ModLauncher (#10349) 2025-01-27 09:57:09 -08:00
Jonathing c186c38113 Fix JOpt Simple needing a strict version requirement declaration (#10313) 2025-01-25 18:39:10 +00:00
Jonathing 1507717fae Fix incorrect method reference in TntBlock.explode() (#10328) 2025-01-25 18:38:43 +00:00
Jonathing 12c4233fac Bump dependencies (#10276)
- EventBus 6.2.8 -> 6.2.15
- Bootstrap 2.1.3 -> 2.1.8
- SecureModules 2.2.20 -> 2.2.21
- AccessTransformers 8.2.0 -> 8.2.1
- ModLauncher 10.2.2 -> 10.2.3
These bumps include further cleanup and optimisations.
2025-01-04 16:42:08 +00:00
Jonathing f331376d9d Simplify Title Screen Brandings (#10289) 2025-01-02 21:57:02 -08:00
Gabriel Harris-Rouquette b5b5064a4f Update jline for better darwin/arm64 support 2024-12-30 09:47:02 -08:00
JonathingandPaint_Ninja f4801960e7 Skip Vanilla classes for the CapabilityTokenSubclass transformer (#10224)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 23:10:40 -08:00
Jonathing 68c60c17e5 Bump CoreMods to 5.2.4 (#10266) 2024-12-23 15:47:22 -08:00
JonathingandPaint_Ninja 4a5f977691 Skip processing Forge classes in RuntimeDistCleaner (#10211)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 14:03:50 -08:00
JonathingandPaint_Ninja 896cfb38a3 Skip Forge classes in the RuntimeEnumExtender transformer (#10197) (#10219)
Mod classes are still transformed as usual

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 13:50:21 -08:00
JonathingandPaint_Ninja 185273022c Deprecate @ObjectHolder, add a couple of fast-paths (#10195) (#10231)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 13:40:29 -08:00
Jonathing eb65e1db51 Allow mipmap lowering to be disabled (#10255) 2024-12-23 13:30:30 -08:00
JonathingandPaint_Ninja 6a5c413a13 Simplify memory usage display on loading screen (#10236)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 13:30:01 -08:00
Jonathing 1b7b2b6ff1 Fix NightConfig FileWatcher causing dedicated server to hang when exiting (#10215) 2024-12-23 13:03:27 -08:00
Martijn van den Brand cb290f23f5 Pass player argument when firing OnDatapackSyncEvent (#10171) 2024-11-16 21:34:03 -08:00
Jonathing 6e8eaeeec9 Add optional fix of use item duration, disabled by default (#10151) 2024-11-10 13:17:08 -08:00
Jonathing 56c41f3ca8 Bump CoreMods to 5.2 (#10160)
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:41:02 -08:00
LexManos 0084b8cf48 Add proper support for JPMS in normal mods.toml mods (#10125)
Make FMLModContainer read and apply Add-Opens and Add-Exports manifest entries from mod files.
Forge is now the `net.minecraftforge.forge` module instead of `forge`

https://forums.minecraftforge.net/topic/153333-proper-java-module-support-in-forge-mods/
2024-11-04 17:11:56 -08:00
Paint_Ninja eb6c564ce4 Add more c fluid tags (#10137)
Replaces the existing `forge`-namespaced tags, which are now deprecated.
Adds `c:experience`
2024-11-04 18:21:54 +00:00
Paint_Ninja 618da273dc Add c:stripped_logs and c:stripped_woods tags (#10136) 2024-10-26 19:47:54 +01:00
Jonathing 074c0cdfd6 [1.21.1] Bump CoreMods and ASM (#10127)
CoreMods 5.1.13 changelog: https://gist.github.com/Jonathing/905d142447ecef670526ae27243adbba
2024-10-26 11:45:37 +01:00
135 changed files with 3341 additions and 339 deletions

No files matched your search

@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
@Internal
@Override
protected Object getData() {
return matches.toSorted(Comparator.naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
return matches.toSorted(Comparator.<String>naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
}
}
+1 -1
View File
@@ -117,7 +117,7 @@ dependencies {
bootstrap(libs.unsafe) // 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.api) // Needed by securemodules
+8
View File
@@ -75,3 +75,11 @@ eclipse {
// Run when importing the project
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject
}
idea {
module {
// IntelliJ IDEA does not do this by itself anymore...
downloadJavadoc = true
downloadSources = true
}
}
+25 -6
View File
@@ -2,16 +2,15 @@
MinecraftForge
=============
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.20.6-&query=$.promos["1.20.6-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download]
[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=1.20.6-&query=$.promos["1.20.6-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.21.1-&query=$.promos["1.21.1-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.21.1-&query=$.promos["1.21.1-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
)][Download] [![Discord](https://img.shields.io/discord/313125603924639766.svg?color=%237289da&label=Discord&logo=discord&logoColor=%237289da)][Discord] [![Support](https://img.shields.io/badge/Patreon-Support-orange.svg?logo=Patreon)][Patreon]
Forge is a free, open-source modding API all of your favourite mods use!
| Version | Support |
|---------| ------------- |
| 1.20.x | Active |
| 1.19.x | Legacy |
| Version | Support |
|--------------|-----------------------------|
| All versions | [Supported][Support-Policy] |
* [Download]
* [Forum]
@@ -31,6 +30,19 @@ You can download the installer for the *Recommended Build* or the
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
## Required Java Versions
We require the version of Java that Minecraft requires, which is currently:
| Minecraft | Java |
|---------------|-------------------|
| 1.20.6+ | [21][Adoptium-21] |
| 1.18 - 1.20.4 | [17][Adoptium-17] |
| 1.17.1 | [16][Adoptium-16] |
| 1.16.5- | [8][Adoptium-8] |
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
# Creating Mods
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
@@ -63,8 +75,15 @@ Please ensure you have a valid email address associated with your GitHub account
[Download]: https://files.minecraftforge.net/
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
[Adoptium-8]: https://adoptium.net/temurin/releases/?version=8
[Jarfix]: https://johann.loefflmann.net/en/software/jarfix/index.html
[Forum]: https://forums.minecraftforge.net/
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
[Support-Policy]: https://forums.minecraftforge.net/topic/144690-new-tiered-support-policy
[Discord]: https://discord.minecraftforge.net/
@@ -14,6 +14,7 @@ import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.fml.loading.FMLPaths;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
@@ -25,9 +26,66 @@ import static net.minecraftforge.fml.config.ConfigTracker.CONFIG;
public class ConfigFileTypeHandler {
private static final Logger LOGGER = LogUtils.getLogger();
static final ConfigFileTypeHandler TOML = new ConfigFileTypeHandler();
private static final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.getConfigValue(FMLConfig.ConfigValue.DEFAULT_CONFIG_PATH));
private static final ConfigFileTypeHandler CLIENT = new ConfigFileTypeHandler(ModConfig.Type.CLIENT);
private static final ConfigFileTypeHandler COMMON = new ConfigFileTypeHandler(ModConfig.Type.COMMON);
private static final ConfigFileTypeHandler SERVER = new ConfigFileTypeHandler(ModConfig.Type.SERVER);
private final @Nullable ModConfig.Type type;
private @Nullable FileWatcher watcher;
// exists for bin compat
public ConfigFileTypeHandler() {
this(null);
}
private ConfigFileTypeHandler(@Nullable ModConfig.Type type) {
this.type = type;
}
/**
* Gets the handler for the given {@link ModConfig.Type}.
*
* @param type The type to get the handler for
* @return The handler
*/
static ConfigFileTypeHandler get(ModConfig.Type type) {
return switch (type) {
case CLIENT -> CLIENT;
case COMMON -> COMMON;
case SERVER -> SERVER;
};
}
/**
* Gets the {@link FileWatcher} for this handler, creating it if it doesn't exist and/or has been stopped.
*
* @return The watcher
*
* @apiNote This is package-private so modders can't just call {@link FileWatcher#stop()} and fuck up everything.
*/
FileWatcher getWatcher() {
if (this.watcher == null) {
LOGGER.debug(CONFIG, "Starting watcher for handler: {}", this);
this.watcher = new FileWatcher();
}
return this.watcher;
}
/**
* Stops the {@link FileWatcher} for this handler, and sets it to null afterward. Use this instead of
* {@link FileWatcher#stop()}.
*/
void stopWatcher() {
if (this.watcher == null) return;
LOGGER.debug(CONFIG, "Stopping watcher for hander: {}", this);
this.watcher.stop();
this.watcher = null;
}
public Function<ModConfig, CommentedFileConfig> reader(Path configBasePath) {
return (c) -> {
final Path configPath = configBasePath.resolve(c.getFileName());
@@ -37,7 +95,7 @@ public class ConfigFileTypeHandler {
onFileNotFound((newfile, configFormat)-> setupConfigFile(c, newfile, configFormat)).
writingMode(WritingMode.REPLACE).
build();
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath.toString());
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath);
try
{
configData.load();
@@ -46,9 +104,9 @@ public class ConfigFileTypeHandler {
{
throw new ConfigLoadingException(c, ex);
}
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath.toString());
FileWatcher.defaultInstance().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath.toString());
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath);
this.getWatcher().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath);
return configData;
};
}
@@ -56,9 +114,9 @@ public class ConfigFileTypeHandler {
public void unload(Path configBasePath, ModConfig config) {
Path configPath = configBasePath.resolve(config.getFileName());
try {
FileWatcher.defaultInstance().removeWatch(configBasePath.resolve(config.getFileName()));
this.getWatcher().removeWatch(configPath);
} catch (RuntimeException e) {
LOGGER.error("Failed to remove config {} from tracker!", configPath.toString(), e);
LOGGER.error("Failed to remove config {} from tracker!", configPath, e);
}
}
@@ -109,6 +167,11 @@ public class ConfigFileTypeHandler {
}
}
@Override
public String toString() {
return "ConfigFileTypeHandler[" + (type != null ? type : "UNKNOWN") + "]";
}
private record ConfigWatcher(
ModConfig modConfig,
CommentedFileConfig commentedFileConfig,
@@ -8,6 +8,9 @@ package net.minecraftforge.fml.config;
import com.electronwill.nightconfig.core.CommentedConfig;
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
import com.mojang.logging.LogUtils;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.loading.FMLPaths;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
@@ -52,11 +55,24 @@ public class ConfigTracker {
}
}
// TODO: [FML] This is only called for the server (outside of forceUnload)
// rethink config implementation for eventual FML rewrite
public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
for (ModConfig config : this.configSets.get(type)) {
closeConfig(config, configBasePath);
}
ConfigFileTypeHandler.get(type).stopWatcher();
}
// If there is a better way to do this, please tell me. Because this is FUCKED
public void forceUnload() {
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
this.unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
// just in case server watcher is still alive somehow...
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
}
private static void openConfig(final ModConfig config, final Path configBasePath) {
@@ -30,7 +30,7 @@ public class ModConfig
this.spec = spec;
this.fileName = fileName;
this.container = container;
this.configHandler = ConfigFileTypeHandler.TOML;
this.configHandler = ConfigFileTypeHandler.get(type);
ConfigTracker.INSTANCE.trackConfig(this);
}
@@ -22,9 +22,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
@@ -302,13 +300,6 @@ public class DisplayWindow implements ImmediateWindowProvider {
}
private void crashElegantly(String errorDetails) {
String qrText;
try (var is = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/glfailure.txt")))) {
qrText = is.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
qrText = "";
}
StringBuilder msgBuilder = new StringBuilder(2000);
msgBuilder.append("Failed to initialize graphics window with current settings.\n");
msgBuilder.append("\n\n");
@@ -407,13 +398,13 @@ public class DisplayWindow implements ImmediateWindowProvider {
if (showHelpLog && versidx == 0) {
LOGGER.info("""
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
Possible solutions:
A) Make sure Minecraft is set to prefer high performance graphics in the OS and/or driver control panel
B) Check for driver updates on the graphics brand's website
C) Try reinstalling your graphics drivers
D) If still not working after trying all of the above, ask for further help on the Forge forums or Discord
You can safely ignore this message if the game starts up successfully.""");
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSIONS[versidx][0]); // we try our versions one at a time
@@ -612,10 +603,25 @@ public class DisplayWindow implements ImmediateWindowProvider {
@Override
public void updateModuleReads(final ModuleLayer layer) {
var fm = layer.findModule("forge").orElseThrow();
getClass().getModule().addReads(fm);
var clz = FMLLoader.getGameLayer().findModule("forge").map(l->Class.forName(l, "net.minecraftforge.client.loading.ForgeLoadingOverlay")).orElseThrow();
loadingOverlay = Arrays.stream(clz.getDeclaredMethods()).filter(m-> Modifier.isStatic(m.getModifiers()) && m.getName().equals("newInstance")).findFirst().orElseThrow();
final var FORGE_MODULE = "net.minecraftforge.forge";
var forge_module = layer.findModule(FORGE_MODULE).orElse(null);
if (forge_module == null)
throw new IllegalStateException("Could not find " + FORGE_MODULE + " in " + layer);
getClass().getModule().addReads(forge_module);
var clz = Class.forName(forge_module, "net.minecraftforge.client.loading.ForgeLoadingOverlay");
for (var mtd : clz.getDeclaredMethods()) {
if (Modifier.isStatic(mtd.getModifiers()) && "newInstance".equals(mtd.getName())) {
this.loadingOverlay = mtd;
break;
}
}
if (loadingOverlay == null)
throw new IllegalStateException("Could not find static newInstace method in " + clz.getName());
}
public int getFramebufferTextureId() {
@@ -13,10 +13,10 @@ import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
public class PerformanceInfo {
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
private final boolean showCPUUsage;
private final OperatingSystemMXBean osBean;
private final MemoryMXBean memoryBean;
private float memory;
private String text;
@@ -24,15 +24,14 @@ public class PerformanceInfo {
PerformanceInfo() {
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
memoryBean = ManagementFactory.getMemoryMXBean();
}
void update() {
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage();
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
memory = (float) heapusage.getUsed() / heapusage.getMax();
if (!showCPUUsage) {
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20);
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
return;
}
@@ -44,7 +43,7 @@ public class PerformanceInfo {
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
}
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB %s".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20, cpuText);
text = "Memory: %d/%dMB (%.1f%%) %s".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f, cpuText);
}
String text() {
@@ -50,7 +50,14 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
return isEmpty ? NAY : YAY;
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
}
@Override
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -35,6 +36,9 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
new VanillaObjectHolderData("net.minecraft.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toUnmodifiableMap(VanillaObjectHolderData::holderClass, Function.identity()));
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;
@@ -47,9 +51,26 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
// Let's skip processing classes that definitely don't have object holders
String internalName = classType.getInternalName();
// Forge classes that aren't in the debug package (that package is used for tests)
if (internalName.startsWith("net/minecraftforge/") && !internalName.substring(18).contains("debug"))
return NAY;
// Vanilla classes that don't have object holders
if (internalName.startsWith("com/mojang/"))
return NAY;
// ...except specific ones we added to the VANILLA_OBJECT_HOLDERS map
if (internalName.startsWith("net/minecraft/") && !VANILLA_OBJECT_HOLDER_CLASSES.contains(internalName))
return NAY;
return YAY;
}
private static boolean hasHolder(List<AnnotationNode> lst) {
@@ -48,9 +48,15 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
}
@Override
@@ -59,15 +65,14 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return ComputeFlags.NO_REWRITE;
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE;
Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor();
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) {
return ComputeFlags.NO_REWRITE;
}
//Static methods named "create" with first argument as a string
List<MethodNode> candidates = classNode.methods.stream()
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
@@ -54,6 +54,9 @@ public class FMLLoader {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
// Allows us to communicate properties with other services through ModLauncher
setupBlackboardKeys();
checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
@@ -118,6 +121,12 @@ public class FMLLoader {
return providers.get(0);
}
private static void setupBlackboardKeys() {
LOGGER.debug(CORE, "Requesting CoreMods to not apply the fix for ASMAPI.findFirstInstructionBefore by default");
var blackboardKey = TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "coremods.use_old_findFirstInstructionBefore", Boolean.class);
Launcher.INSTANCE.blackboard().<Boolean>computeIfAbsent(blackboardKey, k -> true);
}
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
@@ -140,7 +140,7 @@ public class ImmediateWindowHandler {
@Override
public void updateModuleReads(final ModuleLayer layer) {
var fm = layer.findModule("forge");
var fm = layer.findModule("net.minecraftforge.forge");
if (fm.isPresent()) {
getClass().getModule().addReads(fm.get());
var clz = fm.map(l -> Class.forName(l, "net.minecraftforge.client.loading.NoVizFallback")).orElseThrow();
@@ -203,7 +203,14 @@ public class RuntimeDistCleaner implements ILaunchPluginService {
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
return isEmpty ? NAY : YAY;
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/"))
return NAY;
return YAY;
}
private static class LambdaGatherer extends MethodVisitor {
@@ -135,7 +135,7 @@ public class UniqueModListBuilder
return modFile.getSecureJar().name();
}
return modFile.getModFileInfo().moduleName();
return modFile.getModFileInfo().getMods().get(0).getModId();
}
public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {}
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.JarMetadata;
import cpw.mods.jarhandling.SecureJar;
import net.minecraftforge.fml.loading.LogMarkers;
@@ -22,19 +23,25 @@ import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
import java.lang.module.InvalidModuleDescriptorException;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Version;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
@ApiStatus.Internal
public abstract class AbstractModProvider implements IModProvider {
private static final Logger LOGGER = LogUtils.getLogger();
protected static final String MODS_TOML = "META-INF/mods.toml";
private static final Logger LOGGER = LogUtils.getLogger();
protected static final String MODS_TOML = "META-INF/mods.toml";
protected static final String MODULE_INFO = "module-info.class";
protected IModLocator.ModFileOrException createMod(Path path) {
return createMod(path, false);
@@ -48,10 +55,12 @@ public abstract class AbstractModProvider implements IModProvider {
@Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) {
var mjm = new ModJarMetadata();
var sj = SecureJar.from(
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
path
);
SecureJar sj = null;
try {
sj = SecureJar.from(jar -> loadMetaFromJar(jar, mjm), path);
} catch (Throwable t) {
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + path + "\" - " + t.getMessage()));
}
IModFile mod;
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
@@ -61,6 +70,8 @@ public abstract class AbstractModProvider implements IModProvider {
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
mod = new ModFile(sj, this, ModFileParser::modsTomlParser);
// ModJarMetadata is only used when loading mods.toml mods as ModJarMetadata
mjm.setModFile(mod);
if (mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
LOGGER.error(LogMarkers.SCAN, "Unable to load file \"{}\" because its mods.toml is requesting an invalid javafml loaderVersion (use \"*\" if you want to allow all versions) and is missing a forge modId dependency declaration (see the sample mods.toml in the MDK).", path);
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("File \"%s\" is not a Forge mod and cannot be loaded. Look for a Forge version of this mod or consider alternative mods.".formatted(mod.getFileName())));
@@ -73,10 +84,54 @@ public abstract class AbstractModProvider implements IModProvider {
} else
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
mjm.setModFile(mod);
return new IModLocator.ModFileOrException(mod, null);
}
private static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) {
var info = jar.moduleDataProvider().open(MODULE_INFO).orElse(null);
if (info != null) {
try {
var desc = ModuleDescriptor.read(info, jar::getPackages);
var all = new HashSet<>(jar.getPackages());
all.removeAll(desc.packages());
if (!all.isEmpty()) {
var missing = all.stream().sorted().collect(Collectors.joining(", "));
LOGGER.error("Invalid module-info, missing packages " + missing);
throw new ModFileLoadingException("Invalid module-info, missing packages " + missing);
} else {
return new JarMetadata() {
@Override
public String name() {
return desc.name();
}
@Override
public String version() {
return desc.version().map(Version::toString).or(desc::rawVersion).orElse(null);
}
@Override
public ModuleDescriptor descriptor() {
return desc;
}
};
}
} catch (InvalidModuleDescriptorException | IOException e) {
LOGGER.error("Failed to parse " + jar.getPrimaryPath() + " module-info", e);
throw new ModFileLoadingException("Invalid module-info: " + e.getMessage());
} finally {
try {
info.close();
} catch (IOException e) {}
}
}
if (jar.moduleDataProvider().findFile(MODS_TOML).isEmpty())
return JarMetadata.from(jar, jar.getPrimaryPath());
return mjm;
}
protected IModFileInfo manifestParser(final IModFile mod) {
var mf = mod.getSecureJar().moduleDataProvider().getManifest().getMainAttributes();
var license = mf.getValue("LICENSE");
@@ -22,13 +22,11 @@ public final class MinecraftLocator extends AbstractModProvider implements IModL
@Override
public List<IModLocator.ModFileOrException> scanMods() {
var minecraft = FMLLoader.getLaunchHandler().getMinecraftPaths();
var paths = minecraft.toArray(Path[]::new);
// Minecraft itself.
var meta = new ModJarMetadata();
var mcjar = SecureJar.from(
jar -> meta,
minecraft.toArray(Path[]::new)
);
var mcjar = SecureJar.from(jar -> meta, paths);
var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML);
meta.setModFile(mc);
@@ -259,7 +259,7 @@ public class ModFileInfo implements IModFileInfo, IConfigurable {
@Override
public String moduleName() {
return getMods().get(0).getModId();
return this.modFile.getSecureJar().name();
}
@Override
@@ -9,49 +9,64 @@ import cpw.mods.jarhandling.JarMetadata;
import net.minecraftforge.forgespi.locating.IModFile;
import java.lang.module.ModuleDescriptor;
import java.util.Objects;
import org.jetbrains.annotations.ApiStatus;
@ApiStatus.Internal
public final class ModJarMetadata implements JarMetadata {
private static final String AUTOMATIC_MODULE_NAME = "Automatic-Module-Name";
private IModFile modFile;
private String name;
private String version;
private ModuleDescriptor descriptor;
ModJarMetadata() {
}
ModJarMetadata() { }
public void setModFile(IModFile file) {
this.modFile = file;
var mods = this.modFile.getModFileInfo().getMods();
if (!mods.isEmpty()) {
var main = mods.get(0);
this.name = main.getModId();
this.version = main.getVersion().toString();
}
var jar = file.getSecureJar();
var aname = jar.moduleDataProvider().getManifest().getMainAttributes().getValue(AUTOMATIC_MODULE_NAME);
if (aname != null)
this.name = aname;
}
@Override
public String name() {
return modFile.getModFileInfo().moduleName();
return this.name;
}
@Override
public String version() {
return modFile.getModFileInfo().versionString();
return this.version;
}
@Override
public ModuleDescriptor descriptor() {
if (descriptor != null) return descriptor;
if (descriptor != null)
return descriptor;
var bld = ModuleDescriptor.newAutomaticModule(name())
.version(version())
.packages(modFile.getSecureJar().getPackages());
modFile.getSecureJar().getProviders().stream()
.filter(p -> !p.providers().isEmpty())
.forEach(p -> bld.provides(p.serviceName(), p.providers()));
modFile.getModFileInfo().usesServices().forEach(bld::uses);
.version(version())
.packages(modFile.getSecureJar().getPackages());
for (var provider : modFile.getSecureJar().getProviders()) {
if (provider.providers().isEmpty())
continue;
bld.provides(provider.serviceName(), provider.providers());
}
descriptor = bld.build();
return descriptor;
}
public IModFile modFile() {
return modFile;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
@@ -46,7 +46,7 @@ record Scanner(ModFile fileToScan, ModFileScanData result) {
try (InputStream in = Files.newInputStream(path)) {
ModClassVisitor mcv = new ModClassVisitor();
ClassReader cr = new ClassReader(in);
cr.accept(mcv, 0);
cr.accept(mcv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
mcv.buildData(result.getClasses(), result.getAnnotations());
} catch (IOException | IllegalArgumentException e) {
// mark path bad
@@ -73,7 +73,7 @@ public abstract class CommonLaunchHandler implements ILaunchHandlerService {
protected static final LaunchType CLIENT = new LaunchType("client", "minecraft", "net.minecraft.client.main.Main", Dist.CLIENT, false);
protected static final LaunchType DATA = new LaunchType("data", "minecraft", "net.minecraft.data.Main", Dist.CLIENT, true);
protected static final LaunchType SERVER = new LaunchType("server", "minecraft", "net.minecraft.server.Main", Dist.DEDICATED_SERVER, false);
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "forge", "net.minecraftforge.gametest.GameTestMain", Dist.DEDICATED_SERVER, false);
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "net.minecraftforge.forge", "net.minecraftforge.gametest.GameTestMain", Dist.DEDICATED_SERVER, false);
protected void runTarget(String module, String target, final String[] arguments, final ModuleLayer layer) throws Throwable {
var mod = layer.findModule(module).orElse(null);
@@ -91,23 +91,24 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
// First lets find all class files, that have the @Mod annotation and map packages to modids.
var packages = findTestModPackages(path);
for (var entry : packages.entrySet()) {
var pkg = entry.getKey();
var pkg = entry.getKey() + '/';
var modids = entry.getValue();
// Find resource directories for every mod in this group
var resourcePaths = new LinkedHashSet<Path>();
var paths = new LinkedHashSet<Path>();
for (var modid : modids) {
var rsc = path.resolve(modid);
if (Files.exists(rsc))
resourcePaths.add(rsc);
paths.add(rsc);
}
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
buildModsToml(resourcePaths, modids, root);
buildPackMeta(resourcePaths, root);
buildModsToml(paths, modids, root);
buildPackMeta(paths, root);
moveModuleInfo(paths, root);
if (Files.exists(root))
resourcePaths.add(root);
paths.add(root);
// We want just the class files from the root of the input paths. So make a new union with a filter.
var classes = UnionHelper.newFileSystem(
@@ -121,14 +122,10 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
}, new Path[] { path }
);
// And we want the resources, and none of the classes, just in case things get kinda fucky and somehow a package overlaps a sub package {shading?}
var resources = UnionHelper.newFileSystem((name, base) -> !name.endsWith(".class"), resourcePaths.toArray(Path[]::new));
paths.addFirst(classes.getRootDirectories().iterator().next());
// Union of unions, Yay!
var union = UnionHelper.newFileSystem(null, new Path[] {
classes.getRootDirectories().iterator().next(),
resources.getRootDirectories().iterator().next()
});
var union = UnionHelper.newFileSystem(null, paths.stream().toArray(Path[]::new));
mod.add(union.getRootDirectories().iterator().next());
}
@@ -274,6 +271,25 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
}
}
private static void moveModuleInfo(Set<Path> paths, Path root) {
var existing = paths.stream()
.map(p -> p.resolve("module-info.dat"))
.filter(Files::exists)
.findFirst()
.orElse(null);
if (existing == null)
return;
var target = root.resolve("module-info.class");
try {
Files.createDirectories(target.getParent());
Files.copy(existing, target);
} catch (IOException e) {
throw new IllegalStateException("Failed to copy module-info.dat to memory: " + target, e);
}
}
@SuppressWarnings("unchecked")
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
throw (E)e;
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+13 -9
View File
@@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -130,10 +131,13 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -198,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Vendored
+10 -10
View File
@@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
+3 -1
View File
@@ -13,6 +13,8 @@ dependencies {
compileOnly(libs.nulls)
implementation(project(':fmlloader'))
implementation(project(':fmlcore'))
implementation(libs.unsafe)
implementation(libs.securemodules)
}
java {
@@ -57,7 +59,7 @@ publishing {
license PomUtils.Licenses.LGPLv2_1
}
}
repositories {
maven gradleutils.publishingForgeMaven
}
@@ -16,15 +16,21 @@ import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.language.ModFileScanData;
import net.minecraftforge.unsafe.UnsafeHacks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import cpw.mods.jarhandling.SecureJar;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Optional;
import java.util.jar.Attributes;
public class FMLModContainer extends ModContainer {
private static final Logger LOGGER = LogManager.getLogger();
@@ -47,14 +53,82 @@ public class FMLModContainer extends ModContainer {
var moduleName = info.getOwningFile().moduleName();
var module = gameLayer.findModule(moduleName)
.orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer));
openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar());
modClass = Class.forName(module, className);
LOGGER.trace(LOADING,"Loaded modclass {} with {}", modClass.getName(), modClass.getClassLoader());
LOGGER.debug(LOADING,"Loaded modclass {}/{} with {}", modClass.getModule().getName(), modClass.getName(), modClass.getClassLoader());
} catch (Throwable e) {
LOGGER.error(LOADING, "Failed to load class {}", className, e);
throw new ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e);
}
}
/**
* <pre>
* Reads the Add-Exports and Add-Opens attributes (see note) from a mod file and
* attempts to apply them. This differers from the JEP in two significant ways:
* 1) Instead of opening things to ALL-UNNAMED it instead only opens to the
* mod's module itself. Because I don't want other mods accidently relying
* on transitive behavior
* 2) It is read from all mods not just the executable jars.
*
* From <a href = "https://openjdk.org/jeps/261">JEP 261: Module System</a>
*
* Two new JDK-specific JAR-file manifest attributes are defined to correspond
* to the --add-exports and --add-opens command-line options:
* Add-Exports: &lt;module&gt;/&lt;package&gt;( &lt;module&gt;/&lt;package&gt;)*
* Add-Opens: &lt;module&gt;/&lt;package&gt;( &lt;module&gt;/&lt;package&gt;)*
*
* The value of each attribute is a space-separated list of slash-separated
* module-name/package-name pairs. A &gt;module&lt;/&gt;package&lt; pair in
* the value of an Add-Exports attribute has the same meaning as the
* command-line option --add-exports &gt;module&lt;/&gt;package&lt;=ALL-UNNAMED.
*
* A &gt;module&lt;/&gt;package&lt; pair in the value of an Add-Opens attribute has the
* same meaning as the command-line option --add-opens &gt;module&lt;/&gt;package&lt;=ALL-UNNAMED.
*
* Each attribute can occur at most once, in the main section of a MANIFEST.MF file.
* A particular pair can be listed more than once. If a specified module was not
* resolved, or if a specified package does not exist, then the corresponding pair
* is ignored.
*/
private static void openModules(ModuleLayer layer, Module self, SecureJar jar) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
var manifest = jar.moduleDataProvider().getManifest().getMainAttributes();
addOpenOrExports(layer, self, true, manifest);
addOpenOrExports(layer, self, false, manifest);
}
private static void addOpenOrExports(ModuleLayer layer, Module self, boolean open, Attributes attrs) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
var key = open ? "Add-Opens" : "Add-Exports";
var entry = attrs.getValue(key);
if (entry == null)
return;
for (var pair : entry.split(" ")) {
var pts = pair.trim().split("/");
if (pts.length == 2) {
var target = layer.findModule(pts[0]).orElse(null);
if (target == null || !target.getDescriptor().packages().contains(pts[1]))
continue;
addOpenOrExport(target, pts[1], self, open);
} else {
LOGGER.warn(LOADING, "Invalid {} entry in {}: {}", key, self.getName(), pair);
}
}
}
private static Method implAddExportsOrOpens;
private static void addOpenOrExport(Module target, String pkg, Module reader, boolean open) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
if (implAddExportsOrOpens == null) {
implAddExportsOrOpens = Module.class.getDeclaredMethod("implAddExportsOrOpens", String.class, Module.class, boolean.class, boolean.class);
UnsafeHacks.setAccessible(implAddExportsOrOpens);
}
LOGGER.info(LOADING, "{} {}/{} to {}", open ? "Opening" : "Exporting", target.getName(), pkg, reader.getName());
implAddExportsOrOpens.invoke(target, pkg, reader, open, /*syncVM*/true);
}
private static void onEventFailed(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) {
LOGGER.error(new EventBusErrorMessage(event, i, iEventListeners, throwable));
}
+4 -3
View File
@@ -141,9 +141,6 @@ dependencies {
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
// Hack fix for now, force jopt-simple to be exactly 5.0.4 because Mojang ships that version, but some transitive dependencies request 6.0+
implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } }
}
// This block of code expands all declared replace properties in the specified resource targets.
@@ -197,6 +194,10 @@ tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IntelliJ no longer downloads javadocs and sources by default.
// This tells Gradle to force IDEA to do it.
idea.module { downloadJavadoc = downloadSources = true }
eclipse {
// Run everytime eclipse builds the code
//autoBuildTasks genEclipseRuns
@@ -151,6 +151,14 @@
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1088,6 +_,7 @@
this.resourceManager.close();
FreeTypeUtil.destroy();
Util.shutdownExecutors();
+ net.minecraftforge.fml.config.ConfigTracker.INSTANCE.forceUnload();
} catch (Throwable throwable) {
LOGGER.error("Shutdown failure!", throwable);
throw throwable;
@@ -1155,9 +_,11 @@
this.mouseHandler.handleAccumulatedMovement();
this.profiler.pop();
@@ -52,7 +52,7 @@
public static RenderType getRenderType(ItemStack p_109280_, boolean p_109281_) {
Item item = p_109280_.getItem();
if (item instanceof BlockItem) {
@@ -390,11 +_,74 @@
@@ -390,11 +_,79 @@
}
public static RenderType getRenderLayer(FluidState p_109288_) {
@@ -65,6 +65,11 @@
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 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 -> {
@@ -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(since = "1.19")
+ @Deprecated(since = "1.21.4", forRemoval = true)
+ public static net.minecraftforge.client.ChunkRenderTypeSet getRenderLayers(BlockState state) {
+ Block block = state.getBlock();
+ 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(since = "1.19")
+ @Deprecated(since = "1.21.4", forRemoval = true)
+ 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().");
+ 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(since = "1.19")
+ @Deprecated(since = "1.21.4", forRemoval = true)
+ public static synchronized void setRenderLayer(Block block, java.util.function.Predicate<RenderType> 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(since = "1.19")
+ @Deprecated(since = "1.21.4", forRemoval = true)
+ public static synchronized void setRenderLayer(Block block, net.minecraftforge.client.ChunkRenderTypeSet layers) {
+ checkClientLoading();
+ BLOCK_RENDER_TYPES.put(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(block), layers);
@@ -5,7 +5,7 @@
int k1 = Mth.log2(j1);
int l1;
- 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);
l1 = k1;
} else {
@@ -1,74 +1,142 @@
--- a/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 ItemTransforms transforms;
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;
+ /** 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;
+ /** 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;
+ /** 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
+ 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);
+ }
+
+ /** @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(
List<BakedQuad> p_119489_,
@@ -35,7 +_,8 @@
Map<Direction, List<BakedQuad>> p_119490_,
@@ -35,7 +_,9 @@
boolean p_119493_,
TextureAtlasSprite p_119494_,
ItemTransforms p_119495_,
- 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.culledFaces = p_119490_;
@@ -45,6 +_,9 @@
@@ -45,6 +_,15 @@
this.particleIcon = p_119494_;
this.transforms = p_119495_;
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;
+ this.fabulousItemRenderTypes = !renderTypes.isEmpty() ? List.of(renderTypes.entityFabulous()) : null;
+
+ boolean hasRenderTypes = renderTypes != null && !renderTypes.isEmpty();
+ 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
@@ -87,6 +_,25 @@
@@ -87,6 +_,38 @@
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
+ 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
+ public List<net.minecraft.client.renderer.RenderType> getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) {
+ if (!fabulous) {
+ if (itemRenderTypes != null) {
+ return itemRenderTypes;
+ }
+ } else {
+ if (fabulousItemRenderTypes != null) {
+ return fabulousItemRenderTypes;
+ }
+ }
+ return BakedModel.super.getRenderTypes(itemStack, fabulous);
+ if (!fabulous) {
+ if (!net.minecraft.client.renderer.ItemBlockRenderTypes.isFancy()) {
+ if (itemRenderTypesFast != null)
+ return itemRenderTypesFast;
+ if (isRenderingCutout && itemStack.getItem() instanceof net.minecraft.world.item.BlockItem blockItem && blockItem.getBlock() instanceof net.minecraft.world.level.block.LeavesBlock)
+ return SOLID_BLOCK_ITEM;
+ }
+ if (itemRenderTypes != null)
+ return itemRenderTypes;
+ } else {
+ if (fabulousItemRenderTypes != null)
+ return fabulousItemRenderTypes;
+ }
+ return BakedModel.super.getRenderTypes(itemStack, fabulous);
+ }
+
@OnlyIn(Dist.CLIENT)
public static class Builder {
private final List<BakedQuad> unculledFaces = Lists.newArrayList();
@@ -133,12 +_,18 @@
@@ -133,12 +_,49 @@
return this;
}
+ 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) {
+ 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.renderTypesFast = renderTypesFast;
+ return this;
+ }
+
@@ -78,7 +146,8 @@
} else {
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.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
);
}
}
@@ -0,0 +1,14 @@
--- a/net/minecraft/core/Direction.java
+++ b/net/minecraft/core/Direction.java
@@ -47,6 +_,11 @@
private final Direction.AxisDirection axisDirection;
private final Vec3i normal;
private static final Direction[] VALUES = values();
+ // In vanilla updates are notified only on the horizontal plane, in Forge we also notify up and down
+ private static final List<Direction> UPDATE_ORDER = java.util.Collections.unmodifiableList(Stream.concat(Plane.HORIZONTAL.stream(), Plane.VERTICAL.stream()).toList());
+ public static final List<Direction> getUpdateOrder() {
+ return UPDATE_ORDER;
+ }
private static final Direction[] BY_3D_DATA = Arrays.stream(VALUES)
.sorted(Comparator.comparingInt(p_235687_ -> p_235687_.data3d))
.toArray(Direction[]::new);
@@ -9,3 +9,66 @@
private final GameTestInfo testInfo;
private boolean finalCheckAdded;
@@ -870,26 +_,30 @@
}
public BlockPos absolutePos(BlockPos p_177450_) {
- BlockPos blockpos = this.testInfo.getStructureBlockPos();
+ // Forge: Use IForgeGameTestInfo#getTestOrigin to account for rotations and to mimic 1.21.3 behavior
+ BlockPos blockpos = this.testInfo.getTestOrigin();
BlockPos blockpos1 = blockpos.offset(p_177450_);
return StructureTemplate.transform(blockpos1, Mirror.NONE, this.testInfo.getRotation(), blockpos);
}
public BlockPos relativePos(BlockPos p_177453_) {
- BlockPos blockpos = this.testInfo.getStructureBlockPos();
+ // Forge: Use IForgeGameTestInfo#getTestOrigin to account for rotations and to mimic 1.21.3 behavior
+ BlockPos blockpos = this.testInfo.getTestOrigin();
Rotation rotation = this.testInfo.getRotation().getRotated(Rotation.CLOCKWISE_180);
BlockPos blockpos1 = StructureTemplate.transform(p_177453_, Mirror.NONE, rotation, blockpos);
return blockpos1.subtract(blockpos);
}
public Vec3 absoluteVec(Vec3 p_177228_) {
- Vec3 vec3 = Vec3.atLowerCornerOf(this.testInfo.getStructureBlockPos());
- return StructureTemplate.transform(vec3.add(p_177228_), Mirror.NONE, this.testInfo.getRotation(), this.testInfo.getStructureBlockPos());
+ // Forge: Use IForgeGameTestInfo#getTestOrigin to account for rotations and to mimic 1.21.3 behavior
+ Vec3 vec3 = Vec3.atLowerCornerOf(this.testInfo.getTestOrigin());
+ return StructureTemplate.transform(vec3.add(p_177228_), Mirror.NONE, this.testInfo.getRotation(), this.testInfo.getTestOrigin());
}
public Vec3 relativeVec(Vec3 p_251543_) {
- Vec3 vec3 = Vec3.atLowerCornerOf(this.testInfo.getStructureBlockPos());
- return StructureTemplate.transform(p_251543_.subtract(vec3), Mirror.NONE, this.testInfo.getRotation(), this.testInfo.getStructureBlockPos());
+ // Forge: Use IForgeGameTestInfo#getTestOrigin to account for rotations and to mimic 1.21.3 behavior
+ Vec3 vec3 = Vec3.atLowerCornerOf(this.testInfo.getTestOrigin());
+ return StructureTemplate.transform(p_251543_.subtract(vec3), Mirror.NONE, this.testInfo.getRotation(), this.testInfo.getTestOrigin());
}
public Rotation getTestRotation() {
@@ -954,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) { }
+ });
}
}
@@ -0,0 +1,37 @@
--- a/net/minecraft/gametest/framework/GameTestInfo.java
+++ b/net/minecraft/gametest/framework/GameTestInfo.java
@@ -261,7 +_,7 @@
BlockPos blockpos = this.getOrCalculateNorthwestCorner();
this.structureBlockEntity = StructureUtils.prepareTestStructure(this, blockpos, this.getRotation(), this.level);
this.structureBlockPos = this.structureBlockEntity.getBlockPos();
- StructureUtils.addCommandBlockAndButtonToStartTest(this.structureBlockPos, new BlockPos(1, 0, -1), this.getRotation(), this.level);
+ StructureUtils.addCommandBlockAndButtonToStartTest(this.structureBlockPos, new BlockPos(1, 0, -1), Rotation.NONE, this.level); // Forge: The control blocks are always in the North West Corner
StructureUtils.encaseStructure(this.getStructureBounds(), this.level, !this.testFunction.skyAccess());
this.listeners.forEach(p_127630_ -> p_127630_.testStructureLoaded(this));
return this;
@@ -345,5 +_,25 @@
public void setNorthWestCorner(BlockPos p_328918_) {
this.northWestCorner = p_328918_;
+ }
+
+
+ // FORGE START
+
+ private final boolean useTestOrigin = net.minecraftforge.common.ForgeConfig.COMMON.fixGameTestBlockPosAsserts.get();
+
+ /**
+ * Forge: Gets the origin of the test structure based on the
+ * {@linkplain #getStructureBlockEntity() structure block entity}.
+ * <p>
+ * This is a backported method from 1.21.3 to fix how block positions are asserted.
+ *
+ * @return The origin of the test structure
+ *
+ * @see net.minecraftforge.common.ForgeConfig.Common#fixGameTestBlockPosAsserts
+ */
+ @SuppressWarnings("DataFlowIssue") // Nullability moment
+ public BlockPos getTestOrigin() {
+ return this.useTestOrigin ? StructureUtils.getStructureOrigin(this.getStructureBlockEntity()) : this.getStructureBlockPos();
}
}
@@ -0,0 +1,22 @@
--- a/net/minecraft/gametest/framework/ReportGameListener.java
+++ b/net/minecraft/gametest/framework/ReportGameListener.java
@@ -151,7 +_,7 @@
private static BlockPos getBeaconPos(GameTestInfo p_344999_) {
BlockPos blockpos = p_344999_.getStructureBlockPos();
BlockPos blockpos1 = new BlockPos(-1, -2, -1);
- return StructureTemplate.transform(blockpos.offset(blockpos1), Mirror.NONE, p_344999_.getRotation(), blockpos);
+ return blockpos.offset(blockpos1); // Forge: The control blocks are always in the North West Corner
}
private static void updateBeaconGlass(GameTestInfo p_343978_, Block p_344076_) {
@@ -167,8 +_,8 @@
ServerLevel serverlevel = p_177739_.getLevel();
BlockPos blockpos = p_177739_.getStructureBlockPos();
BlockPos blockpos1 = new BlockPos(-1, 0, -1);
- BlockPos blockpos2 = StructureTemplate.transform(blockpos.offset(blockpos1), Mirror.NONE, p_177739_.getRotation(), blockpos);
- serverlevel.setBlockAndUpdate(blockpos2, Blocks.LECTERN.defaultBlockState().rotate(p_177739_.getRotation()));
+ BlockPos blockpos2 = blockpos.offset(blockpos1); // Forge: The control blocks are always in the North West Corner
+ serverlevel.setBlockAndUpdate(blockpos2, Blocks.LECTERN.defaultBlockState());
BlockState blockstate = serverlevel.getBlockState(blockpos2);
ItemStack itemstack = createBook(p_177739_.getTestName(), p_177739_.isRequired(), p_177740_);
LecternBlock.tryPlaceBook(null, serverlevel, blockpos2, blockstate, itemstack);
@@ -0,0 +1,27 @@
--- a/net/minecraft/gametest/framework/StructureUtils.java
+++ b/net/minecraft/gametest/framework/StructureUtils.java
@@ -109,7 +_,8 @@
.getSize();
BoundingBox boundingbox = getStructureBoundingBox(p_311042_, vec3i, p_310584_);
BlockPos blockpos;
- if (p_310584_ == Rotation.NONE) {
+ // Forge: The control blocks are always in the North West Corner
+ if (true || p_310584_ == Rotation.NONE) {
blockpos = p_311042_;
} else if (p_310584_ == Rotation.CLOCKWISE_90) {
blockpos = p_311042_.offset(vec3i.getZ() - 1, 0, 0);
@@ -125,7 +_,13 @@
forceLoadChunks(boundingbox, p_312330_);
clearSpaceForStructure(boundingbox, p_312330_);
- return createStructureBlock(p_311701_, blockpos.below(), p_310584_, p_312330_);
+ var entity = createStructureBlock(p_311701_, blockpos.below(), p_310584_, p_312330_);
+ //Forge: We need to offset the structure so that it will load within bounds.
+ if (p_310584_ != Rotation.NONE) {
+ var rotated = StructureTemplate.getZeroPositionWithTransform(BlockPos.ZERO, Mirror.NONE, p_310584_, entity.getStructureSize().getX(), entity.getStructureSize().getZ());
+ entity.setStructurePos(rotated.offset(new BlockPos(0, 1, 0)));
+ }
+ return entity;
}
public static void encaseStructure(AABB p_330422_, ServerLevel p_331249_, boolean p_328180_) {
@@ -0,0 +1,15 @@
--- a/net/minecraft/gametest/framework/TestCommand.java
+++ b/net/minecraft/gametest/framework/TestCommand.java
@@ -311,7 +_,11 @@
return Optional.empty();
} else {
TestFunction testfunction = optional.get();
- GameTestInfo gametestinfo = new GameTestInfo(testfunction, structureblockentity.getRotation(), p_328153_, p_330368_);
+ // Forge: The rotation is stored in the structure block, and added in the GameTestInfo constructor.
+ // So reverse it to find the manually specified rotation so the test runs the same every time.
+ var steps = StructureUtils.getRotationStepsForRotation(structureblockentity.getRotation()) - StructureUtils.getRotationStepsForRotation(testfunction.rotation());
+ if (steps < 0) steps += 4;
+ GameTestInfo gametestinfo = new GameTestInfo(testfunction, StructureUtils.getRotationForRotationSteps(steps), p_328153_, p_330368_);
gametestinfo.setStructureBlockPos(p_332856_);
return !verifyStructureExists(p_328153_, gametestinfo.getStructureName()) ? Optional.empty() : Optional.of(gametestinfo);
}
@@ -26,7 +26,7 @@
p_326196_ -> {
ReloadableServerResources reloadableserverresources = new ReloadableServerResources(p_326196_.compositeAccess(), p_250212_, p_249301_, p_251126_);
+ 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(
- 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()
@@ -45,7 +45,7 @@
}
}
@@ -293,6 +_,11 @@
@@ -293,6 +_,13 @@
if (this.queryThreadGs4 != null) {
this.queryThreadGs4.stop();
}
@@ -54,6 +54,8 @@
+ this.dediLanPinger.interrupt();
+ this.dediLanPinger = null;
+ }
+
+ net.minecraftforge.fml.config.ConfigTracker.INSTANCE.forceUnload();
}
@Override
@@ -12,7 +12,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, null));
+ 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();
@@ -515,14 +515,12 @@
this.completeUsingItem();
}
}
@@ -3029,8 +_,12 @@
@@ -3029,8 +_,10 @@
public void startUsingItem(InteractionHand p_21159_) {
ItemStack itemstack = this.getItemInHand(p_21159_);
if (!itemstack.isEmpty() && !this.isUsingItem()) {
+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration(this));
+ if (duration <= 0) {
+ return;
+ }
+ if (duration < net.minecraftforge.common.ForgeConfig.SERVER.getUseItemDuration()) return;
this.useItem = itemstack;
- this.useItemRemaining = itemstack.getUseDuration(this);
+ this.useItemRemaining = duration;
@@ -0,0 +1,21 @@
--- a/net/minecraft/world/entity/npc/VillagerTrades.java
+++ b/net/minecraft/world/entity/npc/VillagerTrades.java
@@ -1360,6 +_,7 @@
private final int villagerXp;
public EmeraldsForVillagerTypeItem(int p_35669_, int p_35670_, int p_35671_, Map<VillagerType, Item> p_35672_) {
+ if (false) // FORGE: Modders can add custom villager types, so remove this validation
BuiltInRegistries.VILLAGER_TYPE.stream().filter(p_35680_ -> !p_35672_.containsKey(p_35680_)).findAny().ifPresent(p_327046_ -> {
throw new IllegalStateException("Missing trade for villager type: " + BuiltInRegistries.VILLAGER_TYPE.getKey(p_327046_));
});
@@ -1373,7 +_,9 @@
@Override
public MerchantOffer getOffer(Entity p_219685_, RandomSource p_219686_) {
if (p_219685_ instanceof VillagerDataHolder villagerdataholder) {
- ItemCost itemcost = new ItemCost(this.trades.get(villagerdataholder.getVillagerData().getType()), this.cost);
+ Item item = this.trades.get(villagerdataholder.getVillagerData().getType());
+ if (item == null) return null; // FORGE: Account for modded villager types by returning null if there is no trade
+ ItemCost itemcost = new ItemCost(item, this.cost);
return new MerchantOffer(itemcost, new ItemStack(Items.EMERALD), this.maxUses, this.villagerXp, 0.05F);
} else {
return null;
@@ -0,0 +1,12 @@
--- a/net/minecraft/world/entity/npc/VillagerType.java
+++ b/net/minecraft/world/entity/npc/VillagerType.java
@@ -69,4 +_,9 @@
public static VillagerType byBiome(Holder<Biome> p_204074_) {
return p_204074_.unwrapKey().map(BY_BIOME::get).orElse(PLAINS);
}
+
+ /** FORGE: Registers the VillagerType that will spawn in the given biome. This method should be called during FMLCommonSetupEvent using event.enqueueWork() */
+ public static void registerBiomeType(ResourceKey<Biome> biomeKey, VillagerType villagerType) {
+ BY_BIOME.put(biomeKey, villagerType);
+ }
}
@@ -129,7 +129,7 @@
protected void blockUsingShield(LivingEntity p_36295_) {
super.blockUsingShield(p_36295_);
- if (p_36295_.canDisableShield()) {
+ if (p_36295_.getMainHandItem().canDisableShield(this.useItem, this, p_36295_)) {
+ if (p_36295_.getWeaponItem().canDisableShield(this.useItem, this, p_36295_)) {
this.disableShield();
}
}
@@ -142,6 +142,19 @@
if (!this.level().isClientSide) {
this.awardStat(Stats.ITEM_USED.get(this.useItem.getItem()));
}
@@ -932,8 +_,11 @@
if (p_36383_ >= 3.0F) {
int i = 1 + Mth.floor(p_36383_);
InteractionHand interactionhand = this.getUsedItemHand();
+ // FORGE: cache this.useItem -- if this.stopUsingItem() is called, it will be set to ItemStack.EMPTY
+ ItemStack currentItem = this.useItem;
this.useItem.hurtAndBreak(i, this, getSlotForHand(interactionhand));
- if (this.useItem.isEmpty()) {
+ // FORGE: use cached item since this.useItem could be ItemStack.EMPTY
+ if (currentItem.isEmpty()) {
if (interactionhand == InteractionHand.MAIN_HAND) {
this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY);
} else {
@@ -950,10 +_,13 @@
@Override
protected void actuallyHurt(DamageSource p_36312_, float p_36313_) {
@@ -10,7 +10,7 @@
if (optional.isEmpty()) {
return InteractionResult.PASS;
} else {
@@ -113,5 +_,16 @@
@@ -113,5 +_,21 @@
private Optional<BlockState> getStripped(BlockState p_150691_) {
return Optional.ofNullable(STRIPPABLES.get(p_150691_.getBlock()))
.map(p_150689_ -> p_150689_.defaultBlockState().setValue(RotatedPillarBlock.AXIS, p_150691_.getValue(RotatedPillarBlock.AXIS)));
@@ -25,5 +25,10 @@
+ public static BlockState getAxeStrippingState(BlockState originalState) {
+ Block block = STRIPPABLES.get(originalState.getBlock());
+ return block != null ? block.defaultBlockState().setValue(RotatedPillarBlock.AXIS, originalState.getValue(RotatedPillarBlock.AXIS)) : null;
+ }
+
+ @Override
+ public boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker) {
+ return true;
}
}
@@ -5,10 +5,27 @@
import org.slf4j.Logger;
-public final class ItemStack implements DataComponentHolder {
+public final class ItemStack implements DataComponentHolder, net.minecraftforge.common.extensions.IForgeItemStack {
+public final class ItemStack extends net.minecraftforge.common.capabilities.CapabilityProvider<ItemStack> implements DataComponentHolder, net.minecraftforge.common.extensions.IForgeItemStack {
public static final Codec<Holder<Item>> ITEM_NON_AIR_CODEC = BuiltInRegistries.ITEM
.holderByNameCodec()
.validate(
@@ -251,13 +_,16 @@
}
private ItemStack(ItemLike p_331826_, int p_332766_, PatchedDataComponentMap p_333722_) {
+ super(ItemStack.class, true);
this.item = p_331826_.asItem();
this.count = p_332766_;
this.components = p_333722_;
this.getItem().verifyComponentsAfterLoad(this);
+ gatherCapabilities(() -> this.item.getCapabilityProvider(this));
}
private ItemStack(@Nullable Void p_282703_) {
+ super(ItemStack.class, false);
this.item = null;
this.components = new PatchedDataComponentMap(DataComponentMap.EMPTY);
}
@@ -347,13 +_,22 @@
}
@@ -33,6 +50,15 @@
if (player != null && interactionresult.indicateItemUse()) {
player.awardStat(Stats.ITEM_USED.get(item));
}
@@ -425,6 +_,8 @@
public void hurtAndBreak(int p_220158_, ServerLevel p_342197_, @Nullable ServerPlayer p_220160_, Consumer<Item> p_343361_) {
if (this.isDamageableItem()) {
if (p_220160_ == null || !p_220160_.hasInfiniteMaterials()) {
+ // FORGE: modify the base damage based on the item's impl of IForgeItem.damageItem
+ p_220158_ = this.damageItem(p_220158_, p_342197_, p_220160_, p_343361_);
if (p_220158_ > 0) {
p_220158_ = EnchantmentHelper.processDurabilityChange(p_342197_, this, p_220158_);
if (p_220158_ <= 0) {
@@ -453,7 +_,13 @@
p_41623_,
serverlevel,
@@ -41,7 +67,7 @@
+ p_341563_ -> {
+ if (p_41624_ instanceof Player player) {
+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, this, p_335324_);
+ player.stopUsingItem(); // Forge: fix MC-168573
+ if (player.getUseItem() == this) player.stopUsingItem(); // Forge: fix MC-168573
+ }
+ p_41624_.onEquippedItemBroken(p_341563_, p_335324_);
+ }
@@ -188,12 +188,12 @@
T t = p_261885_.tryCast(enderdragonpart);
if (t != null && p_261688_.test(t)) {
p_262071_.add(t);
@@ -972,16 +_,15 @@
@@ -972,17 +_,17 @@
public abstract Scoreboard getScoreboard();
public void updateNeighbourForOutputSignal(BlockPos p_46718_, Block p_46719_) {
- for (Direction direction : Direction.Plane.HORIZONTAL) {
+ for (Direction direction : Direction.values()) {
+ for (Direction direction : Direction.getUpdateOrder()) {
BlockPos blockpos = p_46718_.relative(direction);
if (this.hasChunkAt(blockpos)) {
BlockState blockstate = this.getBlockState(blockpos);
@@ -205,10 +205,13 @@
blockpos = blockpos.relative(direction);
blockstate = this.getBlockState(blockpos);
- if (blockstate.is(Blocks.COMPARATOR)) {
- this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false);
+ if (blockstate.getWeakChanges(this, blockpos)) {
this.neighborChanged(blockstate, blockpos, p_46719_, p_46718_, false);
+ // Forge: Use IForgeBlockState#onNeighborChange, the default impl redirects to Level#neighborChanged
+ blockstate.onNeighborChange(this, blockpos, p_46718_);
}
}
}
@@ -1092,6 +_,20 @@
}
@@ -1,6 +1,6 @@
--- a/net/minecraft/world/level/block/ChorusFlowerBlock.java
+++ b/net/minecraft/world/level/block/ChorusFlowerBlock.java
@@ -65,7 +_,7 @@
@@ -65,11 +_,11 @@
BlockPos blockpos = p_220982_.above();
if (p_220981_.isEmptyBlock(blockpos) && blockpos.getY() < p_220981_.getMaxBuildHeight()) {
int i = p_220980_.getValue(AGE);
@@ -9,6 +9,20 @@
boolean flag = false;
boolean flag1 = false;
BlockState blockstate = p_220981_.getBlockState(p_220982_.below());
- if (blockstate.is(Blocks.END_STONE)) {
+ if (blockstate.is(Blocks.END_STONE) || blockstate.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON)) {
flag = true;
} else if (blockstate.is(this.plant)) {
int j = 1;
@@ -77,7 +_,7 @@
for (int k = 0; k < 4; k++) {
BlockState blockstate1 = p_220981_.getBlockState(p_220982_.below(j + 1));
if (!blockstate1.is(this.plant)) {
- if (blockstate1.is(Blocks.END_STONE)) {
+ if (blockstate1.is(Blocks.END_STONE) || blockstate1.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON)) {
flag1 = true;
}
break;
@@ -121,6 +_,7 @@
} else {
this.placeDeadFlower(p_220981_, p_220982_);
@@ -17,3 +31,12 @@
}
}
}
@@ -157,7 +_,7 @@
@Override
protected boolean canSurvive(BlockState p_51683_, LevelReader p_51684_, BlockPos p_51685_) {
BlockState blockstate = p_51684_.getBlockState(p_51685_.below());
- if (!blockstate.is(this.plant) && !blockstate.is(Blocks.END_STONE)) {
+ if (!blockstate.is(this.plant) && !blockstate.is(Blocks.END_STONE) && !blockstate.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON)) {
if (!blockstate.isAir()) {
return false;
} else {
@@ -0,0 +1,36 @@
--- a/net/minecraft/world/level/block/ChorusPlantBlock.java
+++ b/net/minecraft/world/level/block/ChorusPlantBlock.java
@@ -50,7 +_,7 @@
BlockState blockstate5 = p_51711_.getBlockState(p_51712_.west());
Block block = p_312378_.getBlock();
return p_312378_.trySetValue(
- DOWN, Boolean.valueOf(blockstate.is(block) || blockstate.is(Blocks.CHORUS_FLOWER) || blockstate.is(Blocks.END_STONE))
+ DOWN, Boolean.valueOf(blockstate.is(block) || blockstate.is(Blocks.CHORUS_FLOWER) || blockstate.is(Blocks.END_STONE) || blockstate.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON))
)
.trySetValue(UP, Boolean.valueOf(blockstate1.is(block) || blockstate1.is(Blocks.CHORUS_FLOWER)))
.trySetValue(NORTH, Boolean.valueOf(blockstate2.is(block) || blockstate2.is(Blocks.CHORUS_FLOWER)))
@@ -65,7 +_,7 @@
p_51731_.scheduleTick(p_51732_, this, 1);
return super.updateShape(p_51728_, p_51729_, p_51730_, p_51731_, p_51732_, p_51733_);
} else {
- boolean flag = p_51730_.is(this) || p_51730_.is(Blocks.CHORUS_FLOWER) || p_51729_ == Direction.DOWN && p_51730_.is(Blocks.END_STONE);
+ boolean flag = p_51730_.is(this) || p_51730_.is(Blocks.CHORUS_FLOWER) || p_51729_ == Direction.DOWN && (p_51730_.is(Blocks.END_STONE) || p_51730_.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON));
return p_51728_.setValue(PROPERTY_BY_DIRECTION.get(p_51729_), Boolean.valueOf(flag));
}
}
@@ -91,13 +_,13 @@
}
BlockState blockstate2 = p_51725_.getBlockState(blockpos.below());
- if (blockstate2.is(this) || blockstate2.is(Blocks.END_STONE)) {
+ if (blockstate2.is(this) || blockstate2.is(Blocks.END_STONE) || blockstate2.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON)) {
return true;
}
}
}
- return blockstate.is(this) || blockstate.is(Blocks.END_STONE);
+ return blockstate.is(this) || blockstate.is(Blocks.END_STONE) || blockstate.is(net.minecraftforge.common.Tags.Blocks.CHORUS_ADDITIONALLY_GROWS_ON);
}
@Override
@@ -31,12 +31,12 @@
}
}
+ @Deprecated //Forge: Prefer using IForgeBlock#catchFire
+ @Deprecated //Forge: Prefer using IForgeBlock#onCaughtFire
public static void explode(Level p_57434_, BlockPos p_57435_) {
explode(p_57434_, p_57435_, null);
}
+ @Deprecated //Forge: Prefer using IForgeBlock#catchFire
+ @Deprecated //Forge: Prefer using IForgeBlock#onCaughtFire
private static void explode(Level p_57437_, BlockPos p_57438_, @Nullable LivingEntity p_57439_) {
if (!p_57437_.isClientSide) {
PrimedTnt primedtnt = new PrimedTnt(
@@ -1,13 +1,24 @@
--- a/net/minecraft/world/level/storage/LevelSummary.java
+++ b/net/minecraft/world/level/storage/LevelSummary.java
@@ -277,6 +_,10 @@
}
}
@@ -14,7 +_,7 @@
import net.minecraft.world.level.LevelSettings;
import org.apache.commons.lang3.StringUtils;
+ public boolean isLifecycleExperimental() {
+ return this.settings.getLifecycle().equals(com.mojang.serialization.Lifecycle.experimental());
-public class LevelSummary implements Comparable<LevelSummary> {
+public class LevelSummary implements Comparable<LevelSummary>, net.minecraftforge.common.extensions.IForgeLevelSummary {
public static final Component PLAY_WORLD = Component.translatable("selectWorld.select");
private final LevelSettings settings;
private final LevelVersion levelVersion;
@@ -275,6 +_,12 @@
public boolean canRecreate() {
return false;
}
+ }
+
+ // TODO Forge: Remove in 1.22. It is kept here for binary compatibility, but already exists in IForgeLevelSummary
+ @Deprecated(forRemoval = true, since = "1.21.4")
+ public boolean isLifecycleExperimental() {
+ return net.minecraftforge.common.extensions.IForgeLevelSummary.super.isLifecycleExperimental();
}
public static class SymlinkLevelSummary extends LevelSummary {
private static final Component MORE_INFO_BUTTON = Component.translatable("symlink_warning.more_info");
private static final Component INFO = Component.translatable("symlink_warning.title").withColor(-65536);
+10 -10
View File
@@ -24,33 +24,33 @@ dependencyResolutionManagement {
versionCatalogs {
libs {
library('forgespi', 'net.minecraftforge:forgespi:7.1.5') // Needs modlauncher
library('modlauncher', 'net.minecraftforge:modlauncher:10.2.2') // Needs securemodules
library('securemodules', 'net.minecraftforge:securemodules:2.2.20') // Needs unsafe
library('modlauncher', 'net.minecraftforge:modlauncher:10.2.4') // Needs securemodules
library('securemodules', 'net.minecraftforge:securemodules:2.2.21') // Needs unsafe
library('unsafe', 'net.minecraftforge:unsafe:0.9.2')
library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.0')
library('coremods', 'net.minecraftforge:coremods:5.1.6')
library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.2')
library('coremods', 'net.minecraftforge:coremods:5.2.6')
library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.4') // Needed by coremods, because the JRE no longer ships JS
library('eventbus', 'net.minecraftforge:eventbus:6.2.8')
library('eventbus', 'net.minecraftforge:eventbus:6.2.27')
library('typetools', 'net.jodah:typetools:0.6.3') // Needed by EventBus because of lambdas
library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0')
library('mixin', 'org.spongepowered:mixin:0.8.7')
library('nulls', 'org.jetbrains:annotations:24.1.0') // Got to have our null annotations!
library('slf4j-api', 'org.slf4j:slf4j-api:2.0.7')
library('maven-artifact', 'org.apache.maven:maven-artifact:3.8.5')
library('maven-artifact', 'org.apache.maven:maven-artifact:3.8.8')
// Google's InMemory File System. Used by ForgeDev Tests for now, but could be useful for a lot of things.
library('jimfs', 'com.google.jimfs:jimfs:1.3.0')
bundle('jimfs', ['guava', 'failureaccess'])
version('bootstrap', '2.1.3')
version('bootstrap', '2.1.8')
library('bootstrap', 'net.minecraftforge', 'bootstrap' ).versionRef('bootstrap') // Needs modlauncher
library('bootstrap-api', 'net.minecraftforge', 'bootstrap-api' ).versionRef('bootstrap')
library('bootstrap-dev', 'net.minecraftforge', 'bootstrap-dev' ).versionRef('bootstrap')
library('bootstrap-shim', 'net.minecraftforge', 'bootstrap-shim').versionRef('bootstrap')
// ASM it's used for so many of our hacks
version('asm', '9.7')
version('asm', '9.7.1')
library('asm', 'org.ow2.asm', 'asm' ).versionRef('asm')
library('asm-tree', 'org.ow2.asm', 'asm-tree' ).versionRef('asm')
library('asm-util', 'org.ow2.asm', 'asm-util' ).versionRef('asm')
@@ -60,14 +60,14 @@ dependencyResolutionManagement {
// Terminal Console Appender.. essentually make pretty colors in the console, but it's been a PITA
library('terminalconsoleappender', 'net.minecrell:terminalconsoleappender:1.2.0')
version('jline', '3.12.1')
version('jline', '3.25.1')
library('jline-reader', 'org.jline', 'jline-reader' ).versionRef('jline')
library('jline-terminal', 'org.jline', 'jline-terminal' ).versionRef('jline')
library('jline-terminal-jna', 'org.jline', 'jline-terminal-jna').versionRef('jline') // Colors and tab completeion
bundle('terminalconsoleappender', ['terminalconsoleappender', 'jline-reader', 'jline-terminal', 'jline-terminal-jna'])
// The core of our configuration system, it has many flaws, but it works for the most part
version('night-config', '3.7.3')
version('night-config', '3.7.4')
library('night-config-toml', 'com.electronwill.night-config', 'toml').versionRef('night-config')
library('night-config-core', 'com.electronwill.night-config', 'core').versionRef('night-config')
bundle('night-config', ['night-config-toml', 'night-config-core'])
@@ -1,37 +0,0 @@
{
"parent": "minecraft:story/root",
"criteria": {
"break_glass_with_fish": {
"conditions": {
"breakingBlock": {
"tag": "forge:glass"
},
"holdingItem": {
"tag": "criterion_test:fish"
}
},
"trigger": "criterion_test:criterion"
}
},
"display": {
"announce_to_chat": true,
"description": {
"text": "Fish wins!"
},
"frame": "task",
"hidden": false,
"icon": {
"item": "minecraft:cod"
},
"show_toast": true,
"title": {
"text": "Fish vs Glass"
}
},
"requirements": [
[
"break_glass_with_fish"
]
],
"sends_telemetry_event": false
}
@@ -1,10 +0,0 @@
{
"values": [
"minecraft:cod",
"minecraft:salmon",
"minecraft:tropical_fish",
"minecraft:pufferfish",
"minecraft:cooked_cod",
"minecraft:cooked_salmon"
]
}
@@ -0,0 +1,13 @@
{
"values": [
"minecraft:stripped_acacia_log",
"minecraft:stripped_bamboo_block",
"minecraft:stripped_birch_log",
"minecraft:stripped_cherry_log",
"minecraft:stripped_dark_oak_log",
"minecraft:stripped_jungle_log",
"minecraft:stripped_mangrove_log",
"minecraft:stripped_oak_log",
"minecraft:stripped_spruce_log"
]
}
@@ -0,0 +1,12 @@
{
"values": [
"minecraft:stripped_acacia_wood",
"minecraft:stripped_birch_wood",
"minecraft:stripped_cherry_wood",
"minecraft:stripped_dark_oak_wood",
"minecraft:stripped_jungle_wood",
"minecraft:stripped_mangrove_wood",
"minecraft:stripped_oak_wood",
"minecraft:stripped_spruce_wood"
]
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:beetroot_soup",
"required": false
}
]
}
@@ -0,0 +1,3 @@
{
"values": []
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:gaseous",
"required": false
}
]
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:mushroom_stew",
"required": false
}
]
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:potion",
"required": false
}
]
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:rabbit_stew",
"required": false
}
]
}
@@ -0,0 +1,8 @@
{
"values": [
{
"id": "#forge:suspicious_stew",
"required": false
}
]
}
@@ -0,0 +1,13 @@
{
"values": [
"minecraft:stripped_acacia_log",
"minecraft:stripped_bamboo_block",
"minecraft:stripped_birch_log",
"minecraft:stripped_cherry_log",
"minecraft:stripped_dark_oak_log",
"minecraft:stripped_jungle_log",
"minecraft:stripped_mangrove_log",
"minecraft:stripped_oak_log",
"minecraft:stripped_spruce_log"
]
}
@@ -0,0 +1,12 @@
{
"values": [
"minecraft:stripped_acacia_wood",
"minecraft:stripped_birch_wood",
"minecraft:stripped_cherry_wood",
"minecraft:stripped_dark_oak_wood",
"minecraft:stripped_jungle_wood",
"minecraft:stripped_mangrove_wood",
"minecraft:stripped_oak_wood",
"minecraft:stripped_spruce_wood"
]
}
@@ -0,0 +1,5 @@
{
"values": [
"#forge:end_stones"
]
}
@@ -350,7 +350,10 @@ public class ForgeHooksClient {
return LazyInit.INSTANCE;
}
// NO-OP method, kept for bin-compat. Used in TitleScreen.java
@Deprecated(forRemoval = true, since = "1.21.4")
public static void renderMainMenu(TitleScreen gui, GuiGraphics graphics, Font font, int width, int height, int alpha) {
/*
VersionChecker.Status status = getForgeVersionStatus();
if (status == VersionChecker.Status.BETA || status == VersionChecker.Status.BETA_OUTDATED) {
@@ -360,6 +363,7 @@ public class ForgeHooksClient {
line = Component.translatable("forge.update.beta.2");
graphics.drawCenteredString(font, line, width / 2, 4 + (font.lineHeight + 1), 0xFFFFFF | alpha);
}
*/
}
public static String forgeStatusLine;
@@ -10,8 +10,6 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
@@ -38,7 +36,6 @@ import java.util.function.Consumer;
* @see MouseInput
* @see KeyInput
*/
@OnlyIn(Dist.CLIENT)
public abstract class ScreenEvent extends Event {
private final Screen screen;
@@ -11,14 +11,11 @@ import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.client.loading.ClientModLoader;
import net.minecraftforge.api.distmarker.Dist;
@OnlyIn(Dist.CLIENT)
public class TitleScreenModUpdateIndicator extends Screen {
private static final ResourceLocation VERSION_CHECK_ICONS = ResourceLocation.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
@@ -25,15 +25,12 @@ import org.apache.logging.log4j.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.PackType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.ForgeConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.client.gui.LoadingErrorScreen;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.server.LanguageHook;
@OnlyIn(Dist.CLIENT)
public class ClientModLoader {
private static final Logger LOGGER = LogManager.getLogger();
private static boolean loading;
@@ -243,6 +243,7 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
private final ItemTransforms transforms;
private TextureAtlasSprite particle;
private RenderTypeGroup lastRenderTypes = RenderTypeGroup.EMPTY;
private RenderTypeGroup lastRenderTypesFast = RenderTypeGroup.EMPTY;
private Builder(boolean isAmbientOcclusion, boolean isGui3d, boolean isSideLit, TextureAtlasSprite particle, ItemOverrides overrides, ItemTransforms transforms)
{
@@ -256,27 +257,38 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
public void addLayer(BakedModel model)
{
flushQuads(null);
flushQuads(RenderTypeGroup.EMPTY, RenderTypeGroup.EMPTY);
children.add(model);
}
private void addLayer(RenderTypeGroup renderTypes, List<BakedQuad> quads)
{
var modelBuilder = IModelBuilder.of(isAmbientOcclusion, isSideLit, isGui3d, transforms, overrides, particle, renderTypes);
this.addLayer(renderTypes, RenderTypeGroup.EMPTY, quads);
}
private void addLayer(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, List<BakedQuad> quads)
{
var modelBuilder = IModelBuilder.of(isAmbientOcclusion, isSideLit, isGui3d, transforms, overrides, particle, renderTypes, renderTypesFast);
quads.forEach(modelBuilder::addUnculledFace);
children.add(modelBuilder.build());
}
private void flushQuads(RenderTypeGroup renderTypes)
{
this.flushQuads(renderTypes, RenderTypeGroup.EMPTY);
}
private void flushQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast)
{
if (!Objects.equals(renderTypes, lastRenderTypes))
{
if (!quads.isEmpty())
{
addLayer(lastRenderTypes, quads);
addLayer(lastRenderTypes, lastRenderTypesFast, quads);
quads.clear();
}
lastRenderTypes = renderTypes;
lastRenderTypesFast = renderTypesFast;
}
}
@@ -288,14 +300,24 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
public Builder addQuads(RenderTypeGroup renderTypes, BakedQuad... quadsToAdd)
{
flushQuads(renderTypes);
return this.addQuads(renderTypes, RenderTypeGroup.EMPTY, quadsToAdd);
}
public Builder addQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, BakedQuad... quadsToAdd)
{
flushQuads(renderTypes, renderTypesFast);
Collections.addAll(quads, quadsToAdd);
return this;
}
public Builder addQuads(RenderTypeGroup renderTypes, Collection<BakedQuad> quadsToAdd)
{
flushQuads(renderTypes);
return this.addQuads(renderTypes, RenderTypeGroup.EMPTY, quadsToAdd);
}
public Builder addQuads(RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast, Collection<BakedQuad> quadsToAdd)
{
flushQuads(renderTypes, renderTypesFast);
quads.addAll(quadsToAdd);
return this;
}
@@ -304,7 +326,7 @@ public class CompositeModel implements IUnbakedGeometry<CompositeModel>
{
if (!quads.isEmpty())
{
addLayer(lastRenderTypes, quads);
addLayer(lastRenderTypes, lastRenderTypesFast, quads);
}
var childrenBuilder = ImmutableMap.<String, BakedModel>builder();
var itemPassesBuilder = ImmutableList.<BakedModel>builder();
@@ -63,7 +63,7 @@ public class EmptyModel extends SimpleUnbakedGeometry<EmptyModel>
public Baked()
{
super(List.of(), Map.of(), false, false, false, UnitTextureAtlasSprite.INSTANCE, ItemTransforms.NO_TRANSFORMS, ItemOverrides.EMPTY, RenderTypeGroup.EMPTY);
super(List.of(), Map.of(), false, false, false, UnitTextureAtlasSprite.INSTANCE, ItemTransforms.NO_TRANSFORMS, ItemOverrides.EMPTY, RenderTypeGroup.EMPTY, RenderTypeGroup.EMPTY);
}
@Override
@@ -73,6 +73,12 @@ public class ExtendedBlockModelDeserializer extends BlockModel.Deserializer
model.customData.setRenderTypeHint(ResourceLocation.parse(renderTypeHintName));
}
if (jsonobject.has("render_type_fast"))
{
var renderTypeHintName = GsonHelper.getAsString(jsonobject, "render_type_fast");
model.customData.setRenderTypeFastHint(ResourceLocation.parse(renderTypeHintName));
}
if (jsonobject.has("visibility"))
{
JsonObject visibility = GsonHelper.getAsJsonObject(jsonobject, "visibility");
@@ -34,6 +34,19 @@ public interface IModelBuilder<T extends IModelBuilder<T>>
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides, particle, renderTypes);
}
static IModelBuilder<?> of(
boolean hasAmbientOcclusion,
boolean usesBlockLight,
boolean isGui3d,
ItemTransforms transforms,
ItemOverrides overrides,
TextureAtlasSprite particle,
RenderTypeGroup renderTypes,
RenderTypeGroup renderTypesFast
){
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides, particle, renderTypes, renderTypesFast);
}
/**
* Creates a new model builder that collects quads to the provided list, returning
* {@linkplain EmptyModel#BAKED an empty model} if you call {@link #build()}.
@@ -53,13 +66,22 @@ public interface IModelBuilder<T extends IModelBuilder<T>>
{
private final SimpleBakedModel.Builder builder;
private final RenderTypeGroup renderTypes;
private final RenderTypeGroup renderTypesFast;
private Simple(boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
ItemTransforms transforms, ItemOverrides overrides, TextureAtlasSprite particle,
RenderTypeGroup renderTypes)
{
this(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides, particle, renderTypes, RenderTypeGroup.EMPTY);
}
private Simple(boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
ItemTransforms transforms, ItemOverrides overrides, TextureAtlasSprite particle,
RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast)
{
this.builder = new SimpleBakedModel.Builder(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, overrides).particle(particle);
this.renderTypes = renderTypes;
this.renderTypesFast = renderTypesFast;
}
@Override
@@ -80,7 +102,7 @@ public interface IModelBuilder<T extends IModelBuilder<T>>
@Override
public BakedModel build()
{
return builder.renderTypes(renderTypes).build();
return builder.renderTypes(renderTypes, renderTypesFast).build();
}
}
@@ -43,11 +43,17 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
@Nullable
private ImmutableList<Material> textures;
private final Int2ObjectMap<ResourceLocation> renderTypeNames;
private final Int2ObjectMap<ResourceLocation> renderTypeFastNames;
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames)
{
this(textures, renderTypeNames, new Int2ObjectOpenHashMap<>());
}
private ItemLayerModel(@Nullable ImmutableList<Material> textures, Int2ObjectMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ResourceLocation> renderTypeFastNames) {
this.textures = textures;
this.renderTypeNames = renderTypeNames;
this.renderTypeFastNames = renderTypeFastNames;
}
@Override
@@ -79,7 +85,9 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
var quads = UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, modelState);
var renderTypeName = renderTypeNames.get(i);
var renderTypes = renderTypeName != null ? context.getRenderType(renderTypeName) : null;
builder.addQuads(renderTypes != null ? renderTypes : normalRenderTypes, quads);
var renderTypeFastName = renderTypeFastNames.get(i);
var renderTypesFast = renderTypeFastName != null ? context.getRenderType(renderTypeFastName) : null;
builder.addQuads(renderTypes != null ? renderTypes : normalRenderTypes, renderTypesFast != null ? renderTypesFast : RenderTypeGroup.EMPTY, quads);
}
return builder.build();
@@ -105,10 +113,27 @@ public class ItemLayerModel implements IUnbakedGeometry<ItemLayerModel>
}
}
return new ItemLayerModel(null, renderTypeNames);
var renderTypeFastNames = new Int2ObjectOpenHashMap<ResourceLocation>();
if (jsonObject.has("render_types_fast")) {
var renderTypes = jsonObject.getAsJsonObject("render_types_fast");
for (var entry : renderTypes.entrySet()) {
var renderType = ResourceLocation.parse(entry.getKey());
for (var layer : entry.getValue().getAsJsonArray())
if (renderTypeFastNames.put(layer.getAsInt(), renderType) != null)
throw new JsonParseException("Registered duplicate render type for layer " + layer);
}
}
return new ItemLayerModel(null, renderTypeNames, renderTypeFastNames);
}
protected void readLayerData(JsonObject jsonObject, String name, Int2ObjectOpenHashMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ForgeFaceData> layerData, boolean logWarning)
{
this.readLayerData(jsonObject, name, renderTypeNames, new Int2ObjectOpenHashMap<>(), layerData, logWarning);
}
@Deprecated(forRemoval = true, since = "1.21.4")
protected void readLayerData(JsonObject jsonObject, String name, Int2ObjectOpenHashMap<ResourceLocation> renderTypeNames, Int2ObjectOpenHashMap<ResourceLocation> renderTypeFastNames, Int2ObjectMap<ForgeFaceData> layerData, boolean logWarning)
{
if (!jsonObject.has(name))
{
@@ -250,6 +250,42 @@ public abstract class BlockStateProvider implements DataProvider {
models().cubeColumnHorizontal(name(block) + "_horizontal", side, end).renderType(renderType));
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, String renderType, String renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, blockTexture(block), renderType, renderTypeFast);
}
public void logBlockWithRenderTypeAndFast(RotatedPillarBlock block, String renderType, String renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, blockTexture(block), extend(blockTexture(block), "_top"), renderType, renderTypeFast);
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, ResourceLocation baseName, String renderType, String renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, extend(baseName, "_side"), extend(baseName, "_end"), renderType, renderTypeFast);
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, ResourceLocation side, ResourceLocation end, String renderType, String renderTypeFast) {
axisBlock(block,
models().cubeColumn(name(block), side, end).renderType(renderType, renderTypeFast),
models().cubeColumnHorizontal(name(block) + "_horizontal", side, end).renderType(renderType, renderTypeFast));
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, ResourceLocation renderType, ResourceLocation renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, blockTexture(block), renderType, renderTypeFast);
}
public void logBlockWithRenderType(RotatedPillarBlock block, ResourceLocation renderType, ResourceLocation renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, blockTexture(block), extend(blockTexture(block), "_top"), renderType, renderTypeFast);
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, ResourceLocation baseName, ResourceLocation renderType, ResourceLocation renderTypeFast) {
axisBlockWithRenderTypeAndFast(block, extend(baseName, "_side"), extend(baseName, "_end"), renderType, renderTypeFast);
}
public void axisBlockWithRenderTypeAndFast(RotatedPillarBlock block, ResourceLocation side, ResourceLocation end, ResourceLocation renderType, ResourceLocation renderTypeFast) {
axisBlock(block,
models().cubeColumn(name(block), side, end).renderType(renderType, renderTypeFast),
models().cubeColumnHorizontal(name(block) + "_horizontal", side, end).renderType(renderType, renderTypeFast));
}
public void axisBlock(RotatedPillarBlock block, ModelFile vertical, ModelFile horizontal) {
getVariantBuilder(block)
.partialState().with(RotatedPillarBlock.AXIS, Axis.Y)
@@ -381,6 +417,38 @@ public abstract class BlockStateProvider implements DataProvider {
stairsBlockInternalWithRenderType(block, name + "_stairs", side, bottom, top, renderType);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, ResourceLocation texture, String renderType, String renderTypeFast) {
stairsBlockWithRenderTypeAndFast(block, texture, texture, texture, renderType, renderTypeFast);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, String name, ResourceLocation texture, String renderType, String renderTypeFast) {
stairsBlockWithRenderTypeAndFast(block, name, texture, texture, texture, renderType, renderTypeFast);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, ResourceLocation side, ResourceLocation bottom, ResourceLocation top, String renderType, String renderTypeFast) {
stairsBlockInternalWithRenderTypeAndFast(block, key(block).toString(), side, bottom, top, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top, String renderType, String renderTypeFast) {
stairsBlockInternalWithRenderTypeAndFast(block, name + "_stairs", side, bottom, top, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
stairsBlockWithRenderTypeAndFast(block, texture, texture, texture, renderType, renderTypeFast);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, String name, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
stairsBlockWithRenderTypeAndFast(block, name, texture, texture, texture, renderType, renderTypeFast);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, ResourceLocation side, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
stairsBlockInternalWithRenderTypeAndFast(block, key(block).toString(), side, bottom, top, renderType, renderTypeFast);
}
public void stairsBlockWithRenderTypeAndFast(StairBlock block, String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
stairsBlockInternalWithRenderTypeAndFast(block, name + "_stairs", side, bottom, top, renderType, renderTypeFast);
}
private void stairsBlockInternal(StairBlock block, String baseName, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
ModelFile stairs = models().stairs(baseName, side, bottom, top);
ModelFile stairsInner = models().stairsInner(baseName + "_inner", side, bottom, top);
@@ -395,6 +463,13 @@ public abstract class BlockStateProvider implements DataProvider {
stairsBlock(block, stairs, stairsInner, stairsOuter);
}
private void stairsBlockInternalWithRenderTypeAndFast(StairBlock block, String baseName, ResourceLocation side, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
ModelFile stairs = models().stairs(baseName, side, bottom, top).renderType(renderType, renderTypeFast);
ModelFile stairsInner = models().stairsInner(baseName + "_inner", side, bottom, top).renderType(renderType, renderTypeFast);
ModelFile stairsOuter = models().stairsOuter(baseName + "_outer", side, bottom, top).renderType(renderType, renderTypeFast);
stairsBlock(block, stairs, stairsInner, stairsOuter);
}
public void stairsBlock(StairBlock block, ModelFile stairs, ModelFile stairsInner, ModelFile stairsOuter) {
getVariantBuilder(block)
.forAllStatesExcept(state -> {
@@ -532,6 +607,32 @@ public abstract class BlockStateProvider implements DataProvider {
models().fenceSide(name + "_fence_side", texture).renderType(renderType));
}
public void fenceBlockWithRenderTypeAndFast(FenceBlock block, ResourceLocation texture, String renderType, String renderTypeFast) {
String baseName = key(block).toString();
fourWayBlock(block,
models().fencePost(baseName + "_post", texture).renderType(renderType, renderTypeFast),
models().fenceSide(baseName + "_side", texture).renderType(renderType, renderTypeFast));
}
public void fenceBlockWithRenderTypeAndFast(FenceBlock block, String name, ResourceLocation texture, String renderType, String renderTypeFast) {
fourWayBlock(block,
models().fencePost(name + "_fence_post", texture).renderType(renderType, renderTypeFast),
models().fenceSide(name + "_fence_side", texture).renderType(renderType, renderTypeFast));
}
public void fenceBlockWithRenderTypeAndFast(FenceBlock block, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
String baseName = key(block).toString();
fourWayBlock(block,
models().fencePost(baseName + "_post", texture).renderType(renderType, renderTypeFast),
models().fenceSide(baseName + "_side", texture).renderType(renderType, renderTypeFast));
}
public void fenceBlockWithRenderTypeAndFast(FenceBlock block, String name, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
fourWayBlock(block,
models().fencePost(name + "_fence_post", texture).renderType(renderType, renderTypeFast),
models().fenceSide(name + "_fence_side", texture).renderType(renderType, renderTypeFast));
}
public void fenceGateBlock(FenceGateBlock block, ResourceLocation texture) {
fenceGateBlockInternal(block, key(block).toString(), texture);
}
@@ -556,6 +657,22 @@ public abstract class BlockStateProvider implements DataProvider {
fenceGateBlockInternalWithRenderType(block, name + "_fence_gate", texture, renderType);
}
public void fenceGateBlockWithRenderTypeAndFast(FenceGateBlock block, ResourceLocation texture, String renderType, String renderTypeFast) {
fenceGateBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void fenceGateBlockWithRenderTypeAndFast(FenceGateBlock block, String name, ResourceLocation texture, String renderType, String renderTypeFast) {
fenceGateBlockInternalWithRenderTypeAndFast(block, name + "_fence_gate", texture, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void fenceGateBlockWithRenderTypeAndFast(FenceGateBlock block, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
fenceGateBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, renderType, renderTypeFast);
}
public void fenceGateBlockWithRenderTypeAndFast(FenceGateBlock block, String name, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
fenceGateBlockInternalWithRenderTypeAndFast(block, name + "_fence_gate", texture, renderType, renderTypeFast);
}
private void fenceGateBlockInternal(FenceGateBlock block, String baseName, ResourceLocation texture) {
ModelFile gate = models().fenceGate(baseName, texture);
ModelFile gateOpen = models().fenceGateOpen(baseName + "_open", texture);
@@ -572,6 +689,14 @@ public abstract class BlockStateProvider implements DataProvider {
fenceGateBlock(block, gate, gateOpen, gateWall, gateWallOpen);
}
private void fenceGateBlockInternalWithRenderTypeAndFast(FenceGateBlock block, String baseName, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
ModelFile gate = models().fenceGate(baseName, texture).renderType(renderType, renderTypeFast);
ModelFile gateOpen = models().fenceGateOpen(baseName + "_open", texture).renderType(renderType, renderTypeFast);
ModelFile gateWall = models().fenceGateWall(baseName + "_wall", texture).renderType(renderType, renderTypeFast);
ModelFile gateWallOpen = models().fenceGateWallOpen(baseName + "_wall_open", texture).renderType(renderType, renderTypeFast);
fenceGateBlock(block, gate, gateOpen, gateWall, gateWallOpen);
}
public void fenceGateBlock(FenceGateBlock block, ModelFile gate, ModelFile gateOpen, ModelFile gateWall, ModelFile gateWallOpen) {
getVariantBuilder(block).forAllStatesExcept(state -> {
ModelFile model = gate;
@@ -613,6 +738,22 @@ public abstract class BlockStateProvider implements DataProvider {
wallBlockInternalWithRenderType(block, name + "_wall", texture, renderType);
}
public void wallBlockWithRenderTypeAndFast(WallBlock block, ResourceLocation texture, String renderType, String renderTypeFast) {
wallBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void wallBlockWithRenderTypeAndFast(WallBlock block, String name, ResourceLocation texture, String renderType, String renderTypeFast) {
wallBlockInternalWithRenderTypeAndFast(block, name + "_wall", texture, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void wallBlockWithRenderTypeAndFast(WallBlock block, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
wallBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, renderType, renderTypeFast);
}
public void wallBlockWithRenderTypeAndFast(WallBlock block, String name, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
wallBlockInternalWithRenderTypeAndFast(block, name + "_wall", texture, renderType, renderTypeFast);
}
private void wallBlockInternal(WallBlock block, String baseName, ResourceLocation texture) {
wallBlock(block, models().wallPost(baseName + "_post", texture),
models().wallSide(baseName + "_side", texture),
@@ -625,6 +766,12 @@ public abstract class BlockStateProvider implements DataProvider {
models().wallSideTall(baseName + "_side_tall", texture).renderType(renderType));
}
private void wallBlockInternalWithRenderTypeAndFast(WallBlock block, String baseName, ResourceLocation texture, ResourceLocation renderType, ResourceLocation renderTypeFast) {
wallBlock(block, models().wallPost(baseName + "_post", texture).renderType(renderType, renderTypeFast),
models().wallSide(baseName + "_side", texture).renderType(renderType, renderTypeFast),
models().wallSideTall(baseName + "_side_tall", texture).renderType(renderType, renderTypeFast));
}
public static final ImmutableMap<Direction, Property<WallSide>> WALL_PROPS = ImmutableMap.<Direction, Property<WallSide>>builder()
.put(Direction.EAST, BlockStateProperties.EAST_WALL)
.put(Direction.NORTH, BlockStateProperties.NORTH_WALL)
@@ -677,6 +824,22 @@ public abstract class BlockStateProvider implements DataProvider {
paneBlockInternalWithRenderType(block, name + "_pane", pane, edge, renderType);
}
public void paneBlockWithRenderTypeAndFast(IronBarsBlock block, ResourceLocation pane, ResourceLocation edge, String renderType, String renderTypeFast) {
paneBlockInternalWithRenderTypeAndFast(block, key(block).toString(), pane, edge, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void paneBlockWithRenderTypeAndFast(IronBarsBlock block, String name, ResourceLocation pane, ResourceLocation edge, String renderType, String renderTypeFast) {
paneBlockInternalWithRenderTypeAndFast(block, name + "_pane", pane, edge, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void paneBlockWithRenderTypeAndFast(IronBarsBlock block, ResourceLocation pane, ResourceLocation edge, ResourceLocation renderType, ResourceLocation renderTypeFast) {
paneBlockInternalWithRenderTypeAndFast(block, key(block).toString(), pane, edge, renderType, renderTypeFast);
}
public void paneBlockWithRenderTypeAndFast(IronBarsBlock block, String name, ResourceLocation pane, ResourceLocation edge, ResourceLocation renderType, ResourceLocation renderTypeFast) {
paneBlockInternalWithRenderTypeAndFast(block, name + "_pane", pane, edge, renderType, renderTypeFast);
}
private void paneBlockInternal(IronBarsBlock block, String baseName, ResourceLocation pane, ResourceLocation edge) {
ModelFile post = models().panePost(baseName + "_post", pane, edge);
ModelFile side = models().paneSide(baseName + "_side", pane, edge);
@@ -695,6 +858,15 @@ public abstract class BlockStateProvider implements DataProvider {
paneBlock(block, post, side, sideAlt, noSide, noSideAlt);
}
private void paneBlockInternalWithRenderTypeAndFast(IronBarsBlock block, String baseName, ResourceLocation pane, ResourceLocation edge, ResourceLocation renderType, ResourceLocation renderTypeFast) {
ModelFile post = models().panePost(baseName + "_post", pane, edge).renderType(renderType, renderTypeFast);
ModelFile side = models().paneSide(baseName + "_side", pane, edge).renderType(renderType, renderTypeFast);
ModelFile sideAlt = models().paneSideAlt(baseName + "_side_alt", pane, edge).renderType(renderType, renderTypeFast);
ModelFile noSide = models().paneNoSide(baseName + "_noside", pane).renderType(renderType, renderTypeFast);
ModelFile noSideAlt = models().paneNoSideAlt(baseName + "_noside_alt", pane).renderType(renderType, renderTypeFast);
paneBlock(block, post, side, sideAlt, noSide, noSideAlt);
}
public void paneBlock(IronBarsBlock block, ModelFile post, ModelFile side, ModelFile sideAlt, ModelFile noSide, ModelFile noSideAlt) {
MultiPartBlockStateBuilder builder = getMultipartBuilder(block)
.part().modelFile(post).addModel().end();
@@ -734,6 +906,22 @@ public abstract class BlockStateProvider implements DataProvider {
doorBlockInternalWithRenderType(block, name + "_door", bottom, top, renderType);
}
public void doorBlockWithRenderTypeAndFast(DoorBlock block, ResourceLocation bottom, ResourceLocation top, String renderType, String renderTypeFast) {
doorBlockInternalWithRenderTypeAndFast(block, key(block).toString(), bottom, top, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void doorBlockWithRenderTypeAndFast(DoorBlock block, String name, ResourceLocation bottom, ResourceLocation top, String renderType, String renderTypeFast) {
doorBlockInternalWithRenderTypeAndFast(block, name + "_door", bottom, top, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void doorBlockWithRenderTypeAndFast(DoorBlock block, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
doorBlockInternalWithRenderTypeAndFast(block, key(block).toString(), bottom, top, renderType, renderTypeFast);
}
public void doorBlockWithRenderTypeAndFast(DoorBlock block, String name, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
doorBlockInternalWithRenderTypeAndFast(block, name + "_door", bottom, top, renderType, renderTypeFast);
}
private void doorBlockInternal(DoorBlock block, String baseName, ResourceLocation bottom, ResourceLocation top) {
ModelFile bottomLeft = models().doorBottomLeft(baseName + "_bottom_left", bottom, top);
ModelFile bottomLeftOpen = models().doorBottomLeftOpen(baseName + "_bottom_left_open", bottom, top);
@@ -758,6 +946,18 @@ public abstract class BlockStateProvider implements DataProvider {
doorBlock(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen);
}
private void doorBlockInternalWithRenderTypeAndFast(DoorBlock block, String baseName, ResourceLocation bottom, ResourceLocation top, ResourceLocation renderType, ResourceLocation renderTypeFast) {
ModelFile bottomLeft = models().doorBottomLeft(baseName + "_bottom_left", bottom, top).renderType(renderType, renderTypeFast);
ModelFile bottomLeftOpen = models().doorBottomLeftOpen(baseName + "_bottom_left_open", bottom, top).renderType(renderType, renderTypeFast);
ModelFile bottomRight = models().doorBottomRight(baseName + "_bottom_right", bottom, top).renderType(renderType, renderTypeFast);
ModelFile bottomRightOpen = models().doorBottomRightOpen(baseName + "_bottom_right_open", bottom, top).renderType(renderType, renderTypeFast);
ModelFile topLeft = models().doorTopLeft(baseName + "_top_left", bottom, top).renderType(renderType, renderTypeFast);
ModelFile topLeftOpen = models().doorTopLeftOpen(baseName + "_top_left_open", bottom, top).renderType(renderType, renderTypeFast);
ModelFile topRight = models().doorTopRight(baseName + "_top_right", bottom, top).renderType(renderType, renderTypeFast);
ModelFile topRightOpen = models().doorTopRightOpen(baseName + "_top_right_open", bottom, top).renderType(renderType, renderTypeFast);
doorBlock(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen);
}
public void doorBlock(DoorBlock block, ModelFile bottomLeft, ModelFile bottomLeftOpen, ModelFile bottomRight, ModelFile bottomRightOpen, ModelFile topLeft, ModelFile topLeftOpen, ModelFile topRight, ModelFile topRightOpen) {
getVariantBuilder(block).forAllStatesExcept(state -> {
int yRot = ((int) state.getValue(DoorBlock.FACING).toYRot()) + 90;
@@ -824,6 +1024,22 @@ public abstract class BlockStateProvider implements DataProvider {
trapdoorBlockInternalWithRenderType(block, name + "_trapdoor", texture, orientable, renderType);
}
public void trapdoorBlockWithRenderTypeAndFast(TrapDoorBlock block, ResourceLocation texture, boolean orientable, String renderType, String renderTypeFast) {
trapdoorBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, orientable, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void trapdoorBlockWithRenderTypeAndFast(TrapDoorBlock block, String name, ResourceLocation texture, boolean orientable, String renderType, String renderTypeFast) {
trapdoorBlockInternalWithRenderTypeAndFast(block, name + "_trapdoor", texture, orientable, ResourceLocation.tryParse(renderType), ResourceLocation.tryParse(renderTypeFast));
}
public void trapdoorBlockWithRenderTypeAndFast(TrapDoorBlock block, ResourceLocation texture, boolean orientable, ResourceLocation renderType, ResourceLocation renderTypeFast) {
trapdoorBlockInternalWithRenderTypeAndFast(block, key(block).toString(), texture, orientable, renderType, renderTypeFast);
}
public void trapdoorBlockWithRenderTypeAndFast(TrapDoorBlock block, String name, ResourceLocation texture, boolean orientable, ResourceLocation renderType, ResourceLocation renderTypeFast) {
trapdoorBlockInternalWithRenderTypeAndFast(block, name + "_trapdoor", texture, orientable, renderType, renderTypeFast);
}
private void trapdoorBlockInternal(TrapDoorBlock block, String baseName, ResourceLocation texture, boolean orientable) {
ModelFile bottom = orientable ? models().trapdoorOrientableBottom(baseName + "_bottom", texture) : models().trapdoorBottom(baseName + "_bottom", texture);
ModelFile top = orientable ? models().trapdoorOrientableTop(baseName + "_top", texture) : models().trapdoorTop(baseName + "_top", texture);
@@ -838,6 +1054,13 @@ public abstract class BlockStateProvider implements DataProvider {
trapdoorBlock(block, bottom, top, open, orientable);
}
private void trapdoorBlockInternalWithRenderTypeAndFast(TrapDoorBlock block, String baseName, ResourceLocation texture, boolean orientable, ResourceLocation renderType, ResourceLocation renderTypeFast) {
ModelFile bottom = orientable ? models().trapdoorOrientableBottom(baseName + "_bottom", texture).renderType(renderType, renderTypeFast) : models().trapdoorBottom(baseName + "_bottom", texture).renderType(renderType, renderTypeFast);
ModelFile top = orientable ? models().trapdoorOrientableTop(baseName + "_top", texture).renderType(renderType, renderTypeFast) : models().trapdoorTop(baseName + "_top", texture).renderType(renderType, renderTypeFast);
ModelFile open = orientable ? models().trapdoorOrientableOpen(baseName + "_open", texture).renderType(renderType, renderTypeFast) : models().trapdoorOpen(baseName + "_open", texture).renderType(renderType, renderTypeFast);
trapdoorBlock(block, bottom, top, open, orientable);
}
public void trapdoorBlock(TrapDoorBlock block, ModelFile bottom, ModelFile top, ModelFile open, boolean orientable) {
getVariantBuilder(block).forAllStatesExcept(state -> {
int xRot = 0;
@@ -60,6 +60,7 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
protected final ExistingFileHelper existingFileHelper;
protected String renderType = null;
protected String renderTypeFast = null;
protected boolean ambientOcclusion = true;
protected GuiLight guiLight = null;
@@ -149,12 +150,17 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
}
/**
* Set the render type for this model.
* Set the render type for this model. Any render types to be used must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent RegisterNamedRenderTypesEvent}.
* <p>
* Consider using {@linkplain #renderType(String, String)} if you need to set a render type for
* {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}.
*
* @param renderType the render type. Must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent}
* @param renderType the render type
* @return this builder
* @throws NullPointerException if {@code renderType} is {@code null}
*
* @throws NullPointerException if {@code renderType} is {@code null}
* @see #renderType(String, String)
*/
public T renderType(String renderType) {
Preconditions.checkNotNull(renderType, "Render type must not be null");
@@ -162,16 +168,55 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
}
/**
* Set the render type for this model.
* Set the render types for this model. Any render types to be used must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent RegisterNamedRenderTypesEvent}.
*
* @param renderType the render type. Must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent}
* @param renderType the render type for {@linkplain net.minecraft.client.GraphicsStatus#FANCY fancy graphics}
* @param renderTypeFast the render type for {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}
* @return this builder
* @throws NullPointerException if {@code renderType} is {@code null}
*
* @throws NullPointerException if {@code renderType} is {@code null}
*/
public T renderType(String renderType, String renderTypeFast) {
Preconditions.checkNotNull(renderType, "Render type must not be null");
return renderType(ResourceLocation.parse(renderType), ResourceLocation.parse(renderTypeFast));
}
/**
* Set the render type for this model. Any render types to be used must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent RegisterNamedRenderTypesEvent}.
* <p>
* Consider using {@linkplain #renderType(ResourceLocation, ResourceLocation)} if you need to set a render type for
* {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}.
*
* @param renderType the render type
* @return this builder
*
* @throws NullPointerException if {@code renderType} is {@code null}
* @see #renderType(ResourceLocation, ResourceLocation)
*/
public T renderType(ResourceLocation renderType) {
Preconditions.checkNotNull(renderType, "Render type must not be null");
this.renderType = renderType.toString();
this.renderTypeFast = null;
return self();
}
/**
* Set the render types for this model. Any render types to be used must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent RegisterNamedRenderTypesEvent}.
*
* @param renderType the render type for {@linkplain net.minecraft.client.GraphicsStatus#FANCY fancy graphics}
* @param renderTypeFast the render type for {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics}
* @return this builder
*
* @throws NullPointerException if {@code renderType} is {@code null}
*/
public T renderType(ResourceLocation renderType, ResourceLocation renderTypeFast) {
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(renderTypeFast, "Fast graphics render type must not be null");
this.renderType = renderType.toString();
this.renderTypeFast = renderType.toString();
return self();
}
@@ -366,7 +366,8 @@ public abstract class ModelProvider<T extends ModelBuilder<T>> implements DataPr
}
public T leaves(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/leaves", "all", texture);
return singleTexture(name, BLOCK_FOLDER + "/leaves", "all", texture)
.renderType("cutout_mipped", "solid");
}
/**
@@ -34,6 +34,7 @@ public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoad
private final Int2ObjectMap<ForgeFaceData> faceData = new Int2ObjectOpenHashMap<>();
private final Map<ResourceLocation, IntSet> renderTypes = new LinkedHashMap<>();
private final Map<ResourceLocation, IntSet> renderTypesFast = new LinkedHashMap<>();
private final IntSet layersWithRenderTypes = new IntOpenHashSet();
protected ItemLayerModelBuilder(T parent, ExistingFileHelper existingFileHelper)
@@ -116,6 +117,23 @@ public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoad
return renderType(asLoc, layers);
}
public ItemLayerModelBuilder<T> renderType(String renderType, String renderTypeFast, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(renderTypeFast, "Fast graphics render type must not be null");
ResourceLocation asLoc;
if (renderType.contains(":"))
asLoc = ResourceLocation.parse(renderType);
else
asLoc = parent.getLocation().withPath(renderType);
ResourceLocation asLocFast;
if (renderTypeFast.contains(":"))
asLocFast = ResourceLocation.parse(renderTypeFast);
else
asLocFast = parent.getLocation().withPath(renderTypeFast);
return renderType(asLoc, asLocFast, layers);
}
/**
* Set the render type for a set of layers.
*
@@ -145,6 +163,25 @@ public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoad
return this;
}
public ItemLayerModelBuilder<T> renderType(ResourceLocation renderType, ResourceLocation renderTypeFast, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(renderTypeFast, "Fast graphics render type must not be null");
Preconditions.checkNotNull(layers, "Layers must not be null");
Preconditions.checkArgument(layers.length > 0, "At least one layer must be specified");
Preconditions.checkArgument(Arrays.stream(layers).allMatch(i -> i >= 0), "All layers must be >= 0");
var alreadyAssigned = Arrays.stream(layers).filter(layersWithRenderTypes::contains).toArray();
Preconditions.checkArgument(alreadyAssigned.length == 0, "Attempted to re-assign layer render types: " + Arrays.toString(alreadyAssigned));
var renderTypeLayers = renderTypes.computeIfAbsent(renderType, $ -> new IntOpenHashSet());
var renderTypeFastLayers = renderTypesFast.computeIfAbsent(renderType, $ -> new IntOpenHashSet());
Arrays.stream(layers).forEach(layer -> {
renderTypeLayers.add(layer);
renderTypeFastLayers.add(layer);
layersWithRenderTypes.add(layer);
});
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
@@ -171,6 +208,14 @@ public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoad
});
json.add("render_types", renderTypes);
JsonObject renderTypesFast = new JsonObject();
this.renderTypesFast.forEach((renderTypeFast, layers) -> {
JsonArray array = new JsonArray();
layers.intStream().sorted().forEach(array::add);
renderTypesFast.add(renderTypeFast.toString(), array);
});
json.add("render_types_fast", renderTypesFast);
return json;
}
}
@@ -41,6 +41,8 @@ public class BlockGeometryBakingContext implements IGeometryBakingContext
private Transformation rootTransform;
@Nullable
private ResourceLocation renderTypeHint;
@Nullable
private ResourceLocation renderTypeFastHint;
private boolean gui3d = true;
@ApiStatus.Internal
@@ -137,11 +139,25 @@ public class BlockGeometryBakingContext implements IGeometryBakingContext
return owner.parent != null ? owner.parent.customData.getRenderTypeHint() : null;
}
@Nullable
@Override
public ResourceLocation getRenderTypeFastHint()
{
if (renderTypeFastHint != null)
return renderTypeFastHint;
return owner.parent != null ? owner.parent.customData.getRenderTypeFastHint() : null;
}
public void setRenderTypeHint(ResourceLocation renderTypeHint)
{
this.renderTypeHint = renderTypeHint;
}
public void setRenderTypeFastHint(ResourceLocation renderTypeFastHint)
{
this.renderTypeFastHint = renderTypeFastHint;
}
public void setGui3d(boolean gui3d)
{
this.gui3d = gui3d;
@@ -153,6 +169,7 @@ public class BlockGeometryBakingContext implements IGeometryBakingContext
this.rootTransform = other.rootTransform;
this.visibilityData.copyFrom(other.visibilityData);
this.renderTypeHint = other.renderTypeHint;
this.renderTypeFastHint = other.renderTypeFastHint;
this.gui3d = other.gui3d;
}
@@ -75,6 +75,13 @@ public interface IGeometryBakingContext
@Nullable
ResourceLocation getRenderTypeHint();
/**
* @return a hint of the {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics} render type this model
* should use. Custom loaders may ignore this.
*/
@Nullable
default ResourceLocation getRenderTypeFastHint() { return null; }
/**
* Queries the visibility of a component of this model.
*
@@ -91,4 +98,20 @@ public interface IGeometryBakingContext
{
return NamedRenderTypeManager.get(name);
}
/**
* {@return a {@link RenderTypeGroup} from the {@link #getRenderTypeHint()}, or the empty group if not found.}
*/
default RenderTypeGroup getRenderType() {
var hint = getRenderTypeHint();
return hint == null ? RenderTypeGroup.EMPTY : getRenderType(hint);
}
/**
* {@return a {@link RenderTypeGroup} from the {@link #getRenderTypeHint()}, or the empty group if not found.}
*/
default RenderTypeGroup getRenderTypeFast() {
var hint = getRenderTypeFastHint();
return hint == null ? RenderTypeGroup.EMPTY : getRenderType(hint);
}
}
@@ -28,10 +28,8 @@ public abstract class SimpleUnbakedGeometry<T extends SimpleUnbakedGeometry<T>>
{
TextureAtlasSprite particle = spriteGetter.apply(context.getMaterial("particle"));
var renderTypeHint = context.getRenderTypeHint();
var renderTypes = renderTypeHint != null ? context.getRenderType(renderTypeHint) : RenderTypeGroup.EMPTY;
IModelBuilder<?> builder = IModelBuilder.of(context.useAmbientOcclusion(), context.useBlockLight(), context.isGui3d(),
context.getTransforms(), overrides, particle, renderTypes);
context.getTransforms(), overrides, particle, context.getRenderType(), context.getRenderTypeFast());
addQuads(context, builder, baker, spriteGetter, modelState);
@@ -54,6 +54,8 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
private final Transformation rootTransform;
@Nullable
private final ResourceLocation renderTypeHint;
@Nullable
private final ResourceLocation renderTypeFastHint;
private final BiPredicate<String, Boolean> visibilityTest;
private StandaloneGeometryBakingContext(ResourceLocation modelName, Predicate<String> materialCheck,
@@ -62,6 +64,18 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
ItemTransforms transforms, Transformation rootTransform,
@Nullable ResourceLocation renderTypeHint,
BiPredicate<String, Boolean> visibilityTest)
{
this(modelName, materialCheck, materialLookup, isGui3d, useBlockLight, useAmbientOcclusion,
transforms, rootTransform, renderTypeHint, null, visibilityTest);
}
private StandaloneGeometryBakingContext(ResourceLocation modelName, Predicate<String> materialCheck,
Function<String, Material> materialLookup, boolean isGui3d,
boolean useBlockLight, boolean useAmbientOcclusion,
ItemTransforms transforms, Transformation rootTransform,
@Nullable ResourceLocation renderTypeHint,
@Nullable ResourceLocation renderTypeFastHint,
BiPredicate<String, Boolean> visibilityTest)
{
this.modelName = modelName;
this.materialCheck = materialCheck;
@@ -72,6 +86,7 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
this.transforms = transforms;
this.rootTransform = rootTransform;
this.renderTypeHint = renderTypeHint;
this.renderTypeFastHint = renderTypeFastHint;
this.visibilityTest = visibilityTest;
}
@@ -130,6 +145,12 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
return renderTypeHint;
}
@Nullable
@Override
public ResourceLocation getRenderTypeFastHint() {
return renderTypeFastHint;
}
@Override
public boolean isComponentVisible(String component, boolean fallback)
{
@@ -158,6 +179,8 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
private Transformation rootTransform = Transformation.identity();
@Nullable
private ResourceLocation renderTypeHint;
@Nullable
private ResourceLocation renderTypeFastHint;
private BiPredicate<String, Boolean> visibilityTest = (c, def) -> def;
private Builder()
@@ -174,6 +197,7 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
this.transforms = parent.getTransforms();
this.rootTransform = parent.getRootTransform();
this.renderTypeHint = parent.getRenderTypeHint();
this.renderTypeFastHint = parent.getRenderTypeFastHint();
this.visibilityTest = parent::isComponentVisible;
}
@@ -229,6 +253,14 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
public Builder withRenderTypeHint(ResourceLocation renderTypeHint)
{
this.renderTypeHint = renderTypeHint;
this.renderTypeFastHint = null;
return this;
}
public Builder withRenderTypeHint(ResourceLocation renderTypeHint, ResourceLocation renderTypeFastHint)
{
this.renderTypeHint = renderTypeHint;
this.renderTypeFastHint = renderTypeFastHint;
return this;
}
@@ -240,7 +272,7 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext
public StandaloneGeometryBakingContext build(ResourceLocation modelName)
{
return new StandaloneGeometryBakingContext(modelName, materialCheck, materialLookup, isGui3d, useBlockLight, useAmbientOcclusion, transforms, rootTransform, renderTypeHint, visibilityTest);
return new StandaloneGeometryBakingContext(modelName, materialCheck, materialLookup, isGui3d, useBlockLight, useAmbientOcclusion, transforms, rootTransform, renderTypeHint, renderTypeFastHint, visibilityTest);
}
}
}
@@ -29,6 +29,8 @@ public class ForgeConfig {
public final BooleanValue advertiseDedicatedServerToLan;
public final BooleanValue useItemWithDurationZero;
Server(ForgeConfigSpec.Builder builder) {
builder.comment("Server configuration settings")
.push("server");
@@ -61,8 +63,17 @@ public class ForgeConfig {
.translation("forge.configgui.advertiseDedicatedServerToLan")
.define("advertiseDedicatedServerToLan", true);
useItemWithDurationZero = builder
.comment("Set this to true to enable living entities to use items with durations of 0. Fixes being able to use Eyes of Ender repeatedly by holding down the use button. Disabled by default as it could change interactions with items of existing mods.")
.translation("forge.configgui.useItemWithDurationZero")
.define("useItemWithDurationZero", false);
builder.pop();
}
public final int getUseItemDuration() {
return useItemWithDurationZero.get() ? 0 : 1;
}
}
/**
@@ -77,6 +88,8 @@ public class ForgeConfig {
public final ForgeConfigSpec.EnumValue<MigrationHelperMode> migrationHelperMode;
public final ForgeConfigSpec.BooleanValue fixGameTestBlockPosAsserts;
Common(ForgeConfigSpec.Builder builder) {
builder.comment("General configuration settings")
.push("general");
@@ -86,6 +99,13 @@ public class ForgeConfig {
.translation("forge.configgui.migrationHelperMode")
.defineEnum("logLegacyTagWarnings", MigrationHelperMode.OFF);
fixGameTestBlockPosAsserts = builder
.comment("""
Set this to true to fix BlockPos assertions in game tests to account for rotations and generally behave as they would in 1.21.3.
This is kept in the common config so that development environments that rely on old behavior do not need to continuously set this in a server config.""")
.translation("forge.configgui.fixGameTestBlockPosAsserts")
.define("fixGameTestBlockPosAsserts", true);
builder.pop();
}
}
@@ -106,6 +126,8 @@ public class ForgeConfig {
public final BooleanValue stabilizeDirectionGetNearest;
public final BooleanValue allowMipmapLowering;
Client(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings, mostly things related to rendering")
@@ -147,6 +169,11 @@ public class ForgeConfig {
.translation("forge.configgui.stabilizeDirectionGetNearest")
.define("stabilizeDirectionGetNearest", true);
allowMipmapLowering = builder
.comment("When enabled, Forge will allow mipmaps to be lowered in real-time. This is the default behavior in vanilla. Use this if you experience issues with resource packs that use textures lower than 8x8.")
.translation("forge.configgui.allowMipmapLowering")
.define("allowMipmapLowering", false);
builder.pop();
}
@@ -159,6 +186,10 @@ public class ForgeConfig {
public final boolean showLoadWarnings() {
return clientSpec.isLoaded() ? showLoadWarnings.get() : showLoadWarnings.getDefault();
}
public final boolean allowMipmapLowering() {
return clientSpec.isLoaded() ? allowMipmapLowering.get() : allowMipmapLowering.getDefault();
}
}
static final ForgeConfigSpec clientSpec;
@@ -101,7 +101,7 @@ public class ForgeInternalHandler {
@SubscribeEvent
public void onResourceReload(AddReloadListenerEvent event) {
INSTANCE = new LootModifierManager(event.getRegistryAccess());
INSTANCE = new LootModifierManager(event.getRegistries());
event.addListener(INSTANCE);
}
@@ -246,6 +246,12 @@ public final class TagConventionMappings {
//region Fluids
legacyToCommon(Registries.FLUID, forgeRl("milk"), Tags.Fluids.MILK),
legacyToCommon(Registries.FLUID, forgeRl("gaseous"), Tags.Fluids.GASEOUS),
legacyToCommon(Registries.FLUID, forgeRl("potion"), Tags.Fluids.POTION),
legacyToCommon(Registries.FLUID, forgeRl("suspicious_stew"), Tags.Fluids.SUSPICIOUS_STEW),
legacyToCommon(Registries.FLUID, forgeRl("mushroom_stew"), Tags.Fluids.MUSHROOM_STEW),
legacyToCommon(Registries.FLUID, forgeRl("rabbit_stew"), Tags.Fluids.RABBIT_STEW),
legacyToCommon(Registries.FLUID, forgeRl("beetroot_soup"), Tags.Fluids.BEETROOT_SOUP),
//endregion
//region Biomes
@@ -55,6 +55,7 @@ public class Tags {
public static final TagKey<Block> CHESTS_ENDER = forgeTag("chests/ender");
public static final TagKey<Block> CHESTS_TRAPPED = forgeTag("chests/trapped");
public static final TagKey<Block> CHORUS_ADDITIONALLY_GROWS_ON = forgeTag("chorus_additionally_grows_on");
public static final TagKey<Block> COBBLESTONE_NORMAL = forgeTag("cobblestone/normal");
public static final TagKey<Block> COBBLESTONE_INFESTED = forgeTag("cobblestone/infested");
public static final TagKey<Block> COBBLESTONE_MOSSY = forgeTag("cobblestone/mossy");
@@ -243,6 +244,8 @@ public class Tags {
public static final TagKey<Block> STORAGE_BLOCKS_REDSTONE = cTag("storage_blocks/redstone");
public static final TagKey<Block> STORAGE_BLOCKS_SLIME = cTag("storage_blocks/slime");
public static final TagKey<Block> STORAGE_BLOCKS_WHEAT = cTag("storage_blocks/wheat");
public static final TagKey<Block> STRIPPED_LOGS = cTag("stripped_logs");
public static final TagKey<Block> STRIPPED_WOODS = cTag("stripped_woods");
public static final TagKey<Block> VILLAGER_JOB_SITES = cTag("villager_job_sites");
//endregion
@@ -775,6 +778,8 @@ public class Tags {
public static final TagKey<Item> STORAGE_BLOCKS_SLIME = cTag("storage_blocks/slime");
public static final TagKey<Item> STORAGE_BLOCKS_WHEAT = cTag("storage_blocks/wheat");
public static final TagKey<Item> STRINGS = cTag("strings");
public static final TagKey<Item> STRIPPED_LOGS = cTag("stripped_logs");
public static final TagKey<Item> STRIPPED_WOODS = cTag("stripped_woods");
public static final TagKey<Item> VILLAGER_JOB_SITES = cTag("villager_job_sites");
// Tools and Armors
@@ -1064,39 +1069,6 @@ public class Tags {
private static void init() {}
//region `forge` tags for Forge-specific tags
/**
* Holds all fluids that are gaseous at room temperature.
*/
public static final TagKey<Fluid> GASEOUS = forgeTag("gaseous");
/**
* Holds all fluids related to potions. The effects of the potion fluid should be read from NBT.
* The effects and color of the potion fluid should be read from {@link net.minecraft.core.component.DataComponents#POTION_CONTENTS}
* component that people should be attaching to the fluidstack of this fluid.<br></br>
* (Standard unit for potions is 250mb per bottle)
*/
public static final TagKey<Fluid> POTION = forgeTag("potion");
/**
* Holds all fluids related to Suspicious Stew.
* The effects of the suspicious stew fluid should be read from {@link net.minecraft.core.component.DataComponents#SUSPICIOUS_STEW_EFFECTS}
* component that people should be attaching to the fluidstack of this fluid.<br></br>
* (Standard unit for suspicious stew is 250mb per bowl)
*/
public static final TagKey<Fluid> SUSPICIOUS_STEW = forgeTag("suspicious_stew");
/**
* Holds all fluids related to Mushroom Stew.<br></br>
* (Standard unit for mushroom stew is 250mb per bowl)
*/
public static final TagKey<Fluid> MUSHROOM_STEW = forgeTag("mushroom_stew");
/**
* Holds all fluids related to Rabbit Stew.<br></br>
* (Standard unit for rabbit stew is 250mb per bowl)
*/
public static final TagKey<Fluid> RABBIT_STEW = forgeTag("rabbit_stew");
/**
* Holds all fluids related to Beetroot Soup.<br></br>
* (Standard unit for beetroot soup is 250mb per bowl)
*/
public static final TagKey<Fluid> BEETROOT_SOUP = forgeTag("beetroot_soup");
//endregion
//region `c` tags for common conventions
@@ -1116,11 +1088,50 @@ public class Tags {
* Holds all fluids related to milk.
*/
public static final TagKey<Fluid> MILK = cTag("milk");
/**
* Holds all fluids that are gaseous at room temperature.
*/
public static final TagKey<Fluid> GASEOUS = cTag("gaseous");
/**
* Holds all fluids related to honey.<br></br>
* (Standard unit for honey bottle is 250mb per bottle)
*/
public static final TagKey<Fluid> HONEY = cTag("honey");
/**
* Holds all fluids related to experience.
* <p>(Standard unit for experience is 20mb per 1 experience. However, extraction from Bottle o' Enchanting
* should yield 250mb while smashing yields less)</p>
*/
public static final TagKey<Fluid> EXPERIENCE = cTag("experience");
/**
* Holds all fluids related to potions. The effects of the potion fluid should be read from NBT.
* The effects and color of the potion fluid should be read from {@link net.minecraft.core.component.DataComponents#POTION_CONTENTS}
* component that people should be attaching to the fluidstack of this fluid.
* <p>(Standard unit for potions is 250mb per bottle)</p>
*/
public static final TagKey<Fluid> POTION = cTag("potion");
/**
* Holds all fluids related to Suspicious Stew.
* The effects of the suspicious stew fluid should be read from {@link net.minecraft.core.component.DataComponents#SUSPICIOUS_STEW_EFFECTS}
* component that people should be attaching to the fluidstack of this fluid.
* <p>(Standard unit for suspicious stew is 250mb per bowl)</p>
*/
public static final TagKey<Fluid> SUSPICIOUS_STEW = cTag("suspicious_stew");
/**
* Holds all fluids related to Mushroom Stew.
* <p>(Standard unit for mushroom stew is 250mb per bowl)</p>
*/
public static final TagKey<Fluid> MUSHROOM_STEW = cTag("mushroom_stew");
/**
* Holds all fluids related to Rabbit Stew.<br></br>
* <p>(Standard unit for rabbit stew is 250mb per bowl)</p>
*/
public static final TagKey<Fluid> RABBIT_STEW = cTag("rabbit_stew");
/**
* Holds all fluids related to Beetroot Soup.
* <p>(Standard unit for beetroot soup is 250mb per bowl)</p>
*/
public static final TagKey<Fluid> BEETROOT_SOUP = cTag("beetroot_soup");
/**
* Tag that holds all fluids that recipe viewers should not show to users.
*/
@@ -1130,10 +1141,6 @@ public class Tags {
private static TagKey<Fluid> cTag(String name) {
return FluidTags.create(ResourceLocation.fromNamespaceAndPath("c", name));
}
private static TagKey<Fluid> forgeTag(String name) {
return FluidTags.create(ResourceLocation.fromNamespaceAndPath("forge", name));
}
}
public static class Enchantments {
@@ -55,6 +55,8 @@ public final class ForgeBlockTagsProvider extends BlockTagsProvider {
tag(CHESTS_WOODEN)
.add(Blocks.CHEST, Blocks.TRAPPED_CHEST)
.addOptionalTag(forgeTagKey("chests/wooden"));
tag(CHORUS_ADDITIONALLY_GROWS_ON)
.addTag(END_STONES);
tag(CLUSTERS).add(Blocks.AMETHYST_CLUSTER);
tag(COBBLESTONES)
.addTags(COBBLESTONE_NORMAL, COBBLESTONE_INFESTED, COBBLESTONE_MOSSY, COBBLESTONE_DEEPSLATE)
@@ -216,6 +218,14 @@ public final class ForgeBlockTagsProvider extends BlockTagsProvider {
.addOptionalTag(forgeTagKey("storage_blocks/redstone"));
tag(STORAGE_BLOCKS_SLIME).add(Blocks.SLIME_BLOCK);
tag(STORAGE_BLOCKS_WHEAT).add(Blocks.HAY_BLOCK);
tag(Tags.Blocks.STRIPPED_LOGS).add(
Blocks.STRIPPED_ACACIA_LOG, Blocks.STRIPPED_BAMBOO_BLOCK, Blocks.STRIPPED_BIRCH_LOG,
Blocks.STRIPPED_CHERRY_LOG, Blocks.STRIPPED_DARK_OAK_LOG, Blocks.STRIPPED_JUNGLE_LOG,
Blocks.STRIPPED_MANGROVE_LOG, Blocks.STRIPPED_OAK_LOG, Blocks.STRIPPED_SPRUCE_LOG);
tag(Tags.Blocks.STRIPPED_WOODS).add(
Blocks.STRIPPED_ACACIA_WOOD, Blocks.STRIPPED_BIRCH_WOOD, Blocks.STRIPPED_CHERRY_WOOD,
Blocks.STRIPPED_DARK_OAK_WOOD, Blocks.STRIPPED_JUNGLE_WOOD, Blocks.STRIPPED_MANGROVE_WOOD,
Blocks.STRIPPED_OAK_WOOD, Blocks.STRIPPED_SPRUCE_WOOD);
tag(VILLAGER_JOB_SITES).add(
Blocks.BARREL, Blocks.BLAST_FURNACE, Blocks.BREWING_STAND, Blocks.CARTOGRAPHY_TABLE,
Blocks.CAULDRON, Blocks.WATER_CAULDRON, Blocks.LAVA_CAULDRON, Blocks.POWDER_SNOW_CAULDRON,
@@ -33,13 +33,14 @@ public final class ForgeFluidTagsProvider extends FluidTagsProvider {
tag(WATER).add(net.minecraft.world.level.material.Fluids.WATER).add(net.minecraft.world.level.material.Fluids.FLOWING_WATER);
tag(LAVA).add(net.minecraft.world.level.material.Fluids.LAVA).add(net.minecraft.world.level.material.Fluids.FLOWING_LAVA);
tag(MILK).addOptional(ForgeMod.MILK.getId()).addOptional(ForgeMod.FLOWING_MILK.getId());
tag(GASEOUS);
tag(GASEOUS).addOptionalTag(forgeTagKey("gaseous"));
tag(HONEY);
tag(POTION);
tag(SUSPICIOUS_STEW);
tag(MUSHROOM_STEW);
tag(RABBIT_STEW);
tag(BEETROOT_SOUP);
tag(EXPERIENCE);
tag(POTION).addOptionalTag(forgeTagKey("potion"));
tag(SUSPICIOUS_STEW).addOptionalTag(forgeTagKey("suspicious_stew"));
tag(MUSHROOM_STEW).addOptionalTag(forgeTagKey("mushroom_stew"));
tag(RABBIT_STEW).addOptionalTag(forgeTagKey("rabbit_stew"));
tag(BEETROOT_SOUP).addOptionalTag(forgeTagKey("beetroot_soup"));
tag(HIDDEN_FROM_RECIPE_VIEWERS);
// Backwards compat definitions for pre-1.21 legacy `forge:` tags.
@@ -47,6 +48,12 @@ public final class ForgeFluidTagsProvider extends FluidTagsProvider {
tag(forgeTagKey("milk"))
.addOptional(ForgeMod.MILK.getId())
.addOptional(ForgeMod.FLOWING_MILK.getId());
tag(forgeTagKey("gaseous"));
tag(forgeTagKey("potion"));
tag(forgeTagKey("suspicious_stew"));
tag(forgeTagKey("mushroom_stew"));
tag(forgeTagKey("rabbit_stew"));
tag(forgeTagKey("beetroot_soup"));
}
private static TagKey<Fluid> forgeTagKey(String path) {
@@ -326,6 +326,8 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
tag(Tags.Items.STRINGS)
.add(Items.STRING)
.addOptionalTag(forgeItemTagKey("strings"));
copy(Tags.Blocks.STRIPPED_LOGS, Tags.Items.STRIPPED_LOGS);
copy(Tags.Blocks.STRIPPED_WOODS, Tags.Items.STRIPPED_WOODS);
tag(Tags.Items.VILLAGER_JOB_SITES).add(
Items.BARREL, Items.BLAST_FURNACE, Items.BREWING_STAND, Items.CARTOGRAPHY_TABLE,
Items.CAULDRON, Items.COMPOSTER, Items.FLETCHING_TABLE, Items.GRINDSTONE,
@@ -5,49 +5,117 @@
package net.minecraftforge.common.extensions;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import com.mojang.authlib.GameProfile;
import io.netty.channel.embedded.EmbeddedChannel;
import net.minecraft.core.BlockPos;
import net.minecraft.gametest.framework.GameTestAssertException;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.game.GameProtocols;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
public interface IForgeGameTestHelper {
private GameTestHelper self() {
return (GameTestHelper)this;
return (GameTestHelper) this;
}
default void say(String message) {
this.say(message, Style.EMPTY);
}
default void say(String message, Style style) {
var component = ForgeI18n.getPattern(message) != null ? Component.translatable(message) : Component.literal(message);
this.say(component.withStyle(style));
}
default void say(Component component) {
this.self().getLevel().players().forEach(p -> p.sendSystemMessage(component));
}
default void assertTrue(boolean value, Supplier<String> message) {
if (!value)
throw new GameTestAssertException(message.get());
if (!value)
throw new GameTestAssertException(message.get());
}
default void assertFalse(boolean value, Supplier<String> message) {
if (value)
throw new GameTestAssertException(message.get());
if (value)
throw new GameTestAssertException(message.get());
}
default <N> void assertValueEqual(N expected, N actual, String name, String message) {
this.assertValueEqual(expected, actual, name, () -> message);
}
default <N> void assertValueEqual(N expected, N actual, String name, Supplier<String> message) {
if (!Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, expected, actual));
}
default <N> void assertValueEqual(N[] expected, N[] actual, String name, String message) {
this.assertValueEqual(expected, actual, name, () -> message);
}
default <N> void assertValueEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to be %s, but was %s".formatted(message.get(), name, Arrays.toString(expected), Arrays.toString(actual)));
}
default <N> void assertValueNotEqual(N expected, N actual, String name, String message) {
this.assertValueNotEqual(expected, actual, name, () -> message);
}
default <N> void assertValueNotEqual(N expected, N actual, String name, Supplier<String> message) {
if (Objects.equals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, expected));
}
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, String message) {
this.assertValueNotEqual(expected, actual, name, () -> message);
}
default <N> void assertValueNotEqual(N[] expected, N[] actual, String name, Supplier<String> message) {
if (!Objects.deepEquals(expected, actual))
throw new GameTestAssertException("%s -- Expected %s to NOT be %s, but was".formatted(message.get(), name, Arrays.toString(expected)));
}
default <E> Registry<E> registryLookup(ResourceKey<? extends Registry<? extends E>> registryKey) {
return this.self().getLevel().registryAccess().registryOrThrow(registryKey);
}
default ServerPlayer makeMockServerPlayer() {
var level = self().getLevel();
var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"), false);
var player = new ServerPlayer(level.getServer(), level, cookie.gameProfile(), cookie.clientInformation()) {
public boolean isSpectator() {
return false;
}
public boolean isSpectator() {
return false;
}
public boolean isCreative() {
return true;
}
public boolean isCreative() {
return true;
}
};
var connection = new Connection(PacketFlow.SERVERBOUND);
var channel = new EmbeddedChannel(connection);
@@ -58,4 +126,218 @@ public interface IForgeGameTestHelper {
connection.setupInboundProtocol(info, listener);
return player;
}
/**
* Registers an event listener that will be unregistered when the test is finished running.
*/
default <E extends Event> void addEventListener(Consumer<E> consumer) {
MinecraftForge.EVENT_BUS.addListener(consumer);
self().addCleanup(success -> MinecraftForge.EVENT_BUS.unregister(consumer));
}
/**
* Registers an event listener that will be unregistered when the test is finished running.
*/
default void registerEventListener(Object handler) {
MinecraftForge.EVENT_BUS.register(handler);
self().addCleanup(success -> MinecraftForge.EVENT_BUS.unregister(handler));
}
/**
* Creates a floor of stone blocks at the bottom of the test area.
*/
default void makeFloor() {
makeFloor(Blocks.STONE);
}
/**
* Creates a floor of the specified block under the test area.
*/
default void makeFloor(Block block) {
makeFloor(block, -1);
}
/**
* Creates a floor of the specified block at the specified height.
*/
default void makeFloor(Block block, int height) {
var bounds = self().getBounds();
var pos = new BlockPos.MutableBlockPos();
for (int x = 0; x < (int) bounds.getXsize(); x++) {
for (int y = 0; y < (int) bounds.getZsize(); y++) {
pos.set(x, height, y);
if (self().getBlockState(pos).is(Blocks.AIR))
self().setBlock(pos, block);
}
}
}
default BlockState setAndAssertBlock(int x, int y, int z, Block block) {
return this.setAndAssertBlock(x, y, z, block.defaultBlockState());
}
default BlockState setAndAssertBlock(int x, int y, int z, BlockState state) {
return this.setAndAssertBlock(new BlockPos(x, y, z), state);
}
default BlockState setAndAssertBlock(BlockPos pos, Block block) {
return this.setAndAssertBlock(pos, block.defaultBlockState());
}
default BlockState setAndAssertBlock(BlockPos pos, BlockState state) {
this.assertTrue(
this.self().getLevel().setBlock(this.self().absolutePos(pos), state, Block.UPDATE_ALL),
() -> "Failed to set block at pos %s : %s".formatted(pos, state.getBlock())
);
return state;
}
default <T> Flag<T> flag(String name) {
return new Flag<>(name);
}
default IntFlag intFlag(String name) {
return new IntFlag(name);
}
default BoolFlag boolFlag(String name) {
return new BoolFlag(name);
}
public static class Flag<T> {
private final String name;
@Nullable
protected T value = null;
public Flag(String name) {
this.name = name;
}
public void set(T value) {
this.value = value;
}
@Nullable
public T get() {
return this.value;
}
public void assertUnset() {
this.assertUnset((Supplier<String>) null);
}
public void assertUnset(String message) {
this.assertUnset(message != null ? () -> message : null);
}
public void assertUnset(Supplier<String> message) {
if (this.value != null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be null, but was " + this.value);
}
}
public void assertSet() {
this.assertSet((Supplier<String>) null);
}
public void assertSet(String message) {
this.assertSet(message != null ? () -> message : null);
}
public void assertSet(Supplier<String> message) {
if (this.value == null) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Flag " + name + " was never set");
}
}
public void assertEquals(T expected) {
this.assertEquals(expected, (Supplier<String>) null);
}
public void assertEquals(T expected, String message) {
this.assertEquals(expected, message != null ? () -> message : null);
}
public void assertEquals(T expected, Supplier<String> message) {
assertSet(message);
if (expected != null && !expected.equals(this.value)) {
String s = message != null ? message.get() + " -- " : "";
throw new GameTestAssertException(s + "Expected " + name + " to be " + expected + ", but was " + this.value);
}
}
}
public static class IntFlag extends Flag<Long> {
public IntFlag(String name) {
super(name);
}
public void set(long value) {
super.set(value);
}
public byte getByte() {
return this.value == null ? -1 : this.value.byteValue();
}
public int getInt() {
return this.value == null ? -1 : this.value.intValue();
}
public long getLong() {
return this.value == null ? -1 : this.value.longValue();
}
public void assertEquals(int expected) {
super.assertEquals((long) expected);
}
public void assertEquals(long expected) {
super.assertEquals(expected);
}
public void assertEquals(int expected, String message) {
super.assertEquals((long) expected, message);
}
public void assertEquals(long expected, String message) {
super.assertEquals(expected, message);
}
public void assertEquals(int expected, Supplier<String> message) {
super.assertEquals((long) expected, message);
}
public void assertEquals(long expected, Supplier<String> message) {
super.assertEquals(expected, message);
}
}
public static class BoolFlag extends Flag<Boolean> {
public BoolFlag(String name) {
super(name);
}
public void set(boolean value) {
super.set(value);
}
public boolean getBool() {
return this.value != null && this.value;
}
public void assertEquals(boolean expected) {
super.assertEquals(expected);
}
public void assertEquals(boolean expected, String message) {
super.assertEquals(expected, message);
}
public void assertEquals(boolean expected, Supplier<String> message) {
super.assertEquals(expected, message);
}
}
}
@@ -7,6 +7,8 @@ package net.minecraftforge.common.extensions;
import java.util.function.Consumer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.*;
@@ -33,6 +35,7 @@ import net.minecraft.world.level.Level;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.ToolAction;
import net.minecraftforge.common.ToolActions;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.registries.IForgeRegistry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -478,7 +481,7 @@ public interface IForgeItem {
* @return True if this ItemStack can disable the shield in question.
*/
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker) {
return this instanceof AxeItem;
return attacker.canDisableShield();
}
/**
@@ -500,6 +503,25 @@ public interface IForgeItem {
*/
default void onHorseArmorTick(ItemStack stack, Level level, Mob horse) { }
/**
* Called when this item is to be damaged, such as use a tool being used or a shield blocking damage. The damage
* parameter has not yet been processed, so enchantments are not taken into account.
*
* @param stack The processed amount of damage the item will take
* @param damage The amount of damage the item will take before processing
* @param level The level where the damage is taking place
* @param player The player holding the item
* @param onBroken The callback for when an item is broken (use this if you plan on cancelling damage that will
* break an item)
* @return The amount of damage the item should take, after processing
*
* @apiNote If the item stack is not {@linkplain ItemStack#isDamageableItem() damageable} or the player
* {@linkplain Player#hasInfiniteMaterials() has infinite materials}, this method will not be called.
*/
default int damageItem(ItemStack stack, int damage, ServerLevel level, @Nullable ServerPlayer player, Consumer<Item> onBroken) {
return damage;
}
/**
* Called when an item entity for this stack is destroyed. Note: The {@link ItemStack} can be retrieved from the item entity.
*
@@ -606,4 +628,12 @@ public interface IForgeItem {
default boolean canGrindstoneRepair(ItemStack stack) {
return false;
}
/**
* @return The Default Capability Provider for this item, if any, accounting for the given itemstack.
*/
@Nullable
default ICapabilityProvider getCapabilityProvider(ItemStack stack) {
return null;
}
}
@@ -5,6 +5,8 @@
package net.minecraftforge.common.extensions;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.player.Inventory;
@@ -33,6 +35,8 @@ import net.minecraftforge.common.ToolActions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Consumer;
/*
* Extension added to ItemStack that bounces to ItemSack sensitive Item methods. Typically this is just for convince.
*/
@@ -376,6 +380,25 @@ public interface IForgeItemStack {
return self().getItem().getSweepHitBox(self(), player, target);
}
/**
* Called when this item is to be damaged, such as use a tool being used or a shield blocking damage. The damage
* parameter has not yet been processed, so enchantments are not taken into account.
*
* @param damage The amount of damage the item will take before processing
* @param level The level where the damage is taking place
* @param player The player holding the item
* @param onBroken The callback for when an item is broken (use this if you plan on cancelling damage that will
* break an item)
* @return The amount of damage the item should take
*
* @apiNote If the item stack is not {@linkplain ItemStack#isDamageableItem() damageable} or the player
* {@linkplain Player#hasInfiniteMaterials() has infinite materials}, this method will not be called.
* @see IForgeItem#damageItem(ItemStack, int, ServerLevel, ServerPlayer, Consumer)
*/
default int damageItem(int damage, ServerLevel level, @Nullable ServerPlayer player, Consumer<Item> onBroken) {
return self().getItem().damageItem(self(), damage, level, player, onBroken);
}
/**
* Called when an item entity for this stack is destroyed. Note: The {@link ItemStack} can be retrieved from the item entity.
*
@@ -0,0 +1,27 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.extensions;
import net.minecraft.world.level.storage.LevelSummary;
public interface IForgeLevelSummary {
private LevelSummary self() {
return (LevelSummary) this;
}
/**
* Checks if the Forge lifecycle of this level is experimental. This is used to render the experimental warning
* tooltip on the level select screen.
*
* @return {@code true} if the level is experimental
*/
default boolean isLifecycleExperimental() {
// NOTE: Because CorruptedLevelSummary and SymlinkLevelSummary can have null settings, we need to check it
var settings = this.self().getSettings();
return settings != null && settings.getLifecycle().equals(com.mojang.serialization.Lifecycle.experimental());
}
}
@@ -9,6 +9,7 @@ import java.io.IOException;
import java.util.*;
import com.mojang.serialization.JsonOps;
import net.minecraft.core.HolderLookup;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -31,10 +32,16 @@ public class LootModifierManager extends SimpleJsonResourceReloadListener {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final String FOLDER = "loot_modifiers";
private final RegistryAccess registries;
private final HolderLookup.Provider registries;
private Map<ResourceLocation, IGlobalLootModifier> modifiers = ImmutableMap.of();
/** @deprecated Use {@link #LootModifierManager(HolderLookup.Provider)} */
@Deprecated(forRemoval = true, since = "1.21.1")
public LootModifierManager(RegistryAccess registries) {
this((HolderLookup.Provider) registries);
}
public LootModifierManager(HolderLookup.Provider registries) {
super(GSON, FOLDER);
this.registries = registries;
}
@@ -6,6 +6,7 @@
package net.minecraftforge.event;
import com.google.common.collect.ImmutableList;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.server.ReloadableServerResources;
import net.minecraft.util.profiling.ProfilerFiller;
@@ -30,10 +31,24 @@ import java.util.concurrent.Executor;
public class AddReloadListenerEvent extends Event {
private final List<PreparableReloadListener> listeners = new ArrayList<>();
private final ReloadableServerResources serverResources;
private final HolderLookup.Provider registries;
@Deprecated(forRemoval = true, since = "1.21.4")
private final RegistryAccess registryAccess;
/** @deprecated Does not provide additional context. Use {@link #AddReloadListenerEvent(ReloadableServerResources, HolderLookup.Provider, RegistryAccess)} instead. */
@Deprecated(forRemoval = true, since = "1.21.4")
public AddReloadListenerEvent(ReloadableServerResources serverResources, RegistryAccess registryAccess) {
this(serverResources, registryAccess, registryAccess);
}
public AddReloadListenerEvent(
ReloadableServerResources serverResources,
HolderLookup.Provider registries,
@Deprecated(forRemoval = true, since = "1.21.4") RegistryAccess registryAccess
) {
this.serverResources = serverResources;
this.registries = registries;
this.registryAccess = registryAccess;
}
@@ -63,22 +78,26 @@ public class AddReloadListenerEvent extends Event {
return serverResources.getConditionContext();
}
/**
* @return A holder lookup provider containing the registries with updated tags.
*
* @see net.minecraft.server.ReloadableServerResources#registryLookup
*/
public HolderLookup.Provider getRegistries() {
return registries;
}
/**
* Provides access to the loaded registries associated with these server resources.
* All built-in and dynamic registries are loaded and frozen by this point.
* @return The RegistryAccess context for the currently active reload.
* @deprecated Does not contain updated tags. Use {@link #getRegistries()} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.4")
public RegistryAccess getRegistryAccess() {
return registryAccess;
}
private static class WrappedStateAwareListener implements PreparableReloadListener {
private final PreparableReloadListener wrapped;
private WrappedStateAwareListener(final PreparableReloadListener wrapped) {
this.wrapped = wrapped;
}
private record WrappedStateAwareListener(PreparableReloadListener wrapped) implements PreparableReloadListener {
@Override
public CompletableFuture<Void> reload(final PreparationBarrier stage, final ResourceManager resourceManager, final ProfilerFiller preparationsProfiler, final ProfilerFiller reloadProfiler, final Executor backgroundExecutor, final Executor gameExecutor) {
if (ModLoader.isLoadingStateValid())
@@ -86,5 +105,10 @@ public class AddReloadListenerEvent extends Event {
else
return CompletableFuture.completedFuture(null);
}
@Override
public String getName() {
return wrapped.getName();
}
}
}
@@ -14,6 +14,7 @@ import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.MinecraftForge;
@@ -722,10 +723,15 @@ public final class ForgeEventFactory {
return fire(new SleepFinishedTimeEvent(level, newTime, minTime)).getNewTime();
}
@Deprecated(forRemoval = true, since = "1.21.4")
public static List<PreparableReloadListener> onResourceReload(ReloadableServerResources serverResources, RegistryAccess registryAccess) {
return fire(new AddReloadListenerEvent(serverResources, registryAccess)).getListeners();
}
public static List<PreparableReloadListener> onResourceReload(ReloadableServerResources serverResources, HolderLookup.Provider registries, @Deprecated(forRemoval = true, since = "1.21.4") RegistryAccess registryAccess) {
return fire(new AddReloadListenerEvent(serverResources, registries, registryAccess)).getListeners();
}
public static void onCommandRegister(CommandDispatcher<CommandSourceStack> dispatcher, Commands.CommandSelection environment, CommandBuildContext context) {
post(new RegisterCommandsEvent(dispatcher, environment, context));
}
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more