Compare commits

..
154 Commits
Author SHA1 Message Date
Matt c974df523e Update MDK to use FG7 (#10923) 2026-11-08 09:39:33 -08:00
LexManos d13dd327bd Fix legacy object holders not being fired in the registry specific codepath
Better optimize the scanning for object holders by unrolling streams.
2026-10-13 09:21:04 -07:00
BonsUnleashedandLexManos 216cc50162 Store object holder handlers per registry name (#10899)
Co-authored-by: LexManos <[email protected]>
2026-10-12 18:46:47 -07:00
BonsUnleashed 0ec923d730 Group the status ping channels by mod once instead of filtering per mod (#10893) 2026-10-02 13:19:02 -07:00
BonsUnleashed 8418bad66d Skip the MessageFormat parse in ForgeI18n for strings with no format syntax (#10894) 2026-10-02 13:18:40 -07:00
LexManos ae3c937073 Explicitly make heap copy of ClientboundCustomPayloadPacket's Data. Closes #10861 2026-10-02 13:07:53 -07:00
Owen 3c3f496015 Fix BlockElements not properly saving forge_data when writing to json (#10877) 2026-08-19 10:05:11 -07:00
Meme Man 22d0c94c82 Update equality check for RegistryObject to include RegistryObject#key. (#10854) 2026-07-21 11:25:36 -07:00
Matt 77785cb181 Toml parsing errors are now visible in the latest log (#10846) 2026-07-09 13:44:19 -07:00
Matt 9130c27d05 Add support for multiple access transformer configs. Backport (#10760) (#10786) 2026-04-10 08:05:36 -07:00
LexManos 1b26f0c967 [no ci] Bump ForgeGradle, disable clean project. Closes #10802 2026-04-01 09:49:22 -07:00
embeddedt 723799cdb8 Fix HandshakeHandler potentially skipping last packet (#10787) 2026-03-19 22:38:11 -07:00
Paint_Ninja 64caebe63c Skip processing vanilla classes in RuntimeDistCleaner when running on a client
Backport of #10682 to 1.20.1. Also bumped ASM to 9.9.1 for Java 26 support
2026-03-17 21:21:26 +00:00
embeddedt 8dffec4dbc Bump EventBus to 6.2.32 (#10744)
Brings all the improvements made to EventBus 6 over the past 2+ years to Forge 1.20.1. Highlights:
- Lower memory usage, faster event posting and listener registration (EventBus#98, #85, #84, #70, #65, #64, #62, #60)
- EventBus#fire(), Event#cancel() and Event.Result convenience methods (EventBus#57, #94, e2a19cb)
- New monitor phase for read-only event listeners that want to run last (EventBus c510e2c)
- Fixed memory leak after unregistering listeners in some cases (EventBus#65, #39)
- Factors in bus phase tracking and event class modifiers (final/sealed) to enable further optimisations (EventBus#98, #85, #70)
2026-01-20 21:29:49 +00:00
LexManos d6b2bf7ca3 Re-trigger build due to Github Actions Issue 2026-01-16 18:28:04 -08:00
MattandLexManos e7629d5ae4 Optimize memory allocation for checking entity fluid collisions. Backport of #10745
Co-authored-by: LexManos <[email protected]>
2026-01-16 13:13:06 -08:00
LexManos 7187d8d97f Migrate to Github Actions 2025-12-02 15:17:12 -08:00
LexManos f20ab8e6ce Fix loading ImmediateWindowHandler services from the wrong Module Layer. Closes #10719
Fix errors not logging to log files when early loading screen errors.
Fix generics compile issue in ConctendatedListView.
2025-11-23 20:37:18 -08:00
Yuri 1837d8c36c Allow loading ImmediateWindowProvider from mods dir (#10718) 2025-11-21 09:57:56 -08:00
Jonathing 132704e5f2 Work around mixins targeting IForgePlayer#canReach (#10680) 2025-10-09 15:50:41 -07:00
embeddedt e9ce8a6cc6 Bump ASM to 9.8 for Java 25 runtime support (#10664) 2025-09-19 18:57:32 -07:00
Jonathing 350bfa51e1 Optimize fix for MC-176559 (#10649) 2025-09-01 20:22:28 -07:00
Jonathing ddb5f6c749 Ignore item equality when checking shouldCauseBlockBreakReset, fixes #10645 (#10646) 2025-08-26 12:29:48 -07:00
Joseph T. McQuigg d00f5c4013 Allow command suggestions/autocomplete to search all modded paths at once without namespace provided (#10595) 2025-08-03 09:55:59 -07:00
Jenny Mei f4e8c6b67e Fix ServerChatEvent thread not using correct class loader. (#10591) 2025-08-01 13:25:26 -07:00
Jonathing 6c4f5e2865 Fix ignitedByLava making blocks permanently flammable (#10570) 2025-07-16 09:18:45 -07:00
LexManos d1071fd0f8 Add back magic number to make mixin happy. 2025-06-28 22:30:12 -07:00
LexManos 064e2fed48 Fix container screens closing when opened with an extended REACH attribute. Fixes #10560
Also fixes cases where creative mode effected reach incorrectly.
2025-06-11 14:23:16 -07:00
JonathingandLexManos f36781652c Deprecate EntityRenderersEvent.AddLayers functions that hard case to LivingEntityRenderers as the backing maps do not guarantee that type. (#10513)
Co-authored-by: LexManos <[email protected]>
2025-05-22 00:47:40 -07:00
Jonathing 753d68d20b 1.20.1 RB 4
https://forums.minecraftforge.net/topic/154387-forge-474-minecraft-1201/
2025-03-04 17:36:12 -05:00
Jonathing 4cd832fc4d Fix ForgeDev's test runs not working due to dead test mod (#10483) 2025-03-04 13:53:12 -08:00
Jonathing 8f074e1da1 Cache this.useItem before running item break logic, Fixes #10344 (#10376) 2025-03-04 13:30:10 -08:00
JonathingandLexManos 1596190810 Speed up mod annotation scanning by ~30% (#10470)
Co-authored-by: LexManos <[email protected]>
2025-03-04 13:26:07 -08:00
Jonathing 1fa795a103 Add missed license headers (#10479) 2025-03-04 13:25:58 -08:00
Jonathing fcbd3593f6 Add '#forge:chorus_additionally_grows_on' tag for similar mechanics to '#minecraft:azalea_grows_on' but for chorus (#10456) 2025-03-04 13:25:47 -08:00
Jonathing 68a8d3b830 Fix cancelling ProjectileImpactEvent still firing onBlockHit (#10481) 2025-03-04 12:11:11 -08:00
Jonathing 783c8b7d2b Honor attacker shield disabling status (#10321) 2025-02-18 14:58:43 -08:00
Jonathing dd2591b5f3 Add fast graphics render type to block model jsons (#10393)
Make modded leaves behave like vanilla leaves by default (Fixes #10389)
2025-02-18 13:40:12 -08:00
Jonathing 4cf787d7dd Fix invalidly symlinked worlds crashing on level select (#10439) 2025-02-18 13:14:12 -08:00
Jonathing b805fa74f8 Backport even more future ResourceLocation methods (#10428) 2025-02-18 13:13:58 -08:00
Jonathing fa109380f7 Ensure NetworkConstants is loaded before mod construction (#10407) 2025-02-06 10:49:59 -08:00
Jonathing 59979642e9 Account for problematic mixins in VillagerTrades.EmeraldsForVillagerTypeItem (#10402) 2025-02-05 09:04:56 -08:00
Jonathing 90e8fb1c33 Fix incorrect method reference in TntBlock.explode() 2025-01-27 20:20:30 -08:00
Joseph T. McQuigg f09c6d0a8e Fix issues in VillagerTrades.EmeraldsForVillagerTypeItem related to custom Villager Types (#10315)
Add VillagerType#registerBiomeType
Signed-off-by: Joseph T. McQuigg <[email protected]>
2025-01-27 20:20:08 -08:00
Paint_NinjaandJonathing 56eb44f1cb Add clientSideOnly feature to mods.toml (#10085) (backport of #9804 to 1.20.1)
Co-authored-by: Jonathing <[email protected]>
2025-01-23 20:30:03 +00:00
Jonathing 2e7e537029 Fix non-passengers being tickable without checking canUpdate() (#10304) 2025-01-22 13:36:57 -08:00
Jonathing b9600a27dc Fix finalizeSpawn's return value not being used correctly (#10301) 2025-01-22 13:36:49 -08:00
Jonathing d736300566 Bump CoreMods to 5.2.4 (#10263) 2024-12-23 19:34:27 -08:00
Jonathing fea0d014b8 Allow mipmap lowering to be disabled (#10252) 2024-12-23 19:34:19 -08:00
Jonathing ea355d9bb6 Add optional fix of use item duration, disabled by default (#10246) 2024-12-23 19:15:03 -08:00
JonathingandPaint_Ninja a5293855d6 Backport some Vanilla 1.21 ResourceLocation methods (#10241)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 18:57:33 -08:00
JonathingandPaint_Ninja 4ab4dacf6c Simplify memory usage display on loading screen (#10233)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 18:57:04 -08:00
JonathingandPaint_Ninja 442f4723c8 Deprecate @ObjectHolder, add a couple of fast-paths (#10228)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 18:56:46 -08:00
JonathingandPaint_Ninja 12682da09a Skip Vanilla classes for the CapabilityTokenSubclass transformer (#10221)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 18:39:58 -08:00
JonathingandPaint_Ninja da4112efa9 Skip Forge classes in the RuntimeEnumExtender transformer (#10216)
Mod classes are still transformed as usual

Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 18:06:02 -08:00
JonathingandPaint_Ninja ca6094c73d Skip processing Forge classes in RuntimeDistCleaner (#10208)
Co-authored-by: Paint_Ninja <[email protected]>
2024-12-23 17:49:22 -08:00
Jonathing 9f4d3ef1d7 Disable clean on TeamCity (#10258) 2024-12-23 17:30:33 -08:00
Jonathing 622e560b21 Bump CoreMods to 5.2 (#10130)
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
- Updated ASM to 9.7.1
- Updated Nashorn to 15.4
2024-11-08 17:58:50 -08:00
Paint_Ninjaandandan42 f7e5db7149 Remove unneeded boat patch (backport of #10061 to 1.20.1) (#10096)
Co-authored-by: andan42 <[email protected]>
2024-10-06 18:52:29 -07:00
Paint_NinjaandRealMangoRage 29986615fe Optionally supply FMLJavaModLoadingContext as a param to mod constructors (backport of #10074 to 1.20.1) (#10100)
Co-authored-by: RealMangoRage <[email protected]>
2024-09-12 14:06:42 +01:00
Paint_Ninja e615774a0e Minor cleanup to ModListScreen and VersionChecker (backport of #9988 to 1.20.1) (#10095) 2024-09-12 14:06:20 +01:00
Paint_Ninja 9779f8eaad Cleanup FML Bindings (backport of #10004 to 1.20.1) (#10094) 2024-09-12 14:06:08 +01:00
Paint_Ninja e643bbb764 Early display fixes/workarounds for buggy drivers. Backport of #9921 to 1.20.1 (#10073) 2024-08-20 13:07:49 -07:00
James Mitchell 25bc8679b5 Add a way to render tooltips from Formatted text and TooltipComponents elements (#10055)
Backport of #10056 for 1.20.1
2024-08-16 22:51:00 +01:00
Thomas Kern 361e99805e Make HangingSignBlockEntity useable with custom BlockEntityTypes. #10038 2024-07-05 14:22:36 -07:00
Edouard127andLexManos 0d3921efb5 Unlock wrapped registries when firing register events. (#10035)
Co-authored-by: LexManos <[email protected]>
2024-07-02 11:09:00 -07:00
Jonathingandthedarkcolour 7eee9dcbcd Choose default JarJar mod file type based on parent JAR (#10023)
Co-authored-by: thedarkcolour <[email protected]>
2024-06-28 22:55:31 -07:00
JonathingandVen 3098f463a0 Fixed falling block entities not rendering as moving blocks (#10006) (#10018)
Co-authored-by: Ven <[email protected]>
2024-06-28 22:36:07 -07:00
LexManos 862d557279 Fix boat travel distance being incorrect. Closes #9997 #9999 2024-06-04 10:35:59 -07:00
LexManos e1f057278d 1.20.1 RB 3
https://forums.minecraftforge.net/topic/139825-forge-473-minecraft-1201/
2024-06-03 13:36:29 -07:00
LexManos 6bbe2c64a9 Bump gradle to 8.8 2024-06-03 13:17:20 -07:00
LexManos 684cd96e32 Bump gradle and java runtime version on team city 2024-06-03 13:00:13 -07:00
LexManos 1f4e13fce0 Fix LevelSettings ignoring data configuration. Close #9938 2024-06-03 12:50:43 -07:00
LexManos 55ad9e6d7d Fix erroneous patch in FireBlock. Closes #9996 2024-06-03 12:50:30 -07:00
Paint_Ninja 5c8d1618bc Fix early window crash when parsing options.txt (#9934)
Backport of #9933
2024-05-09 23:16:13 +01:00
Paint_Ninja a6f5057840 Prevent mixins from crashing the game when there are missing mods (#9916)
1.20.1 backport of 49.0.14
2024-05-08 22:06:39 +01:00
Paint_NinjaandJ-RAP 1b0360928f Fix NPE when acceptableValues in defineInList() does not allow nulls, backport of #9903 (#9907)
Co-authored-by: J-RAP <[email protected]>
2024-04-18 21:22:11 +01:00
Paint_Ninja 921771bd11 Fix Crowdin (#9929) 2024-04-18 21:05:13 +01:00
Paint_Ninja 089bb1fc84 Optimise capabilities a tad, backport of #9886 (#9911) 2024-04-18 20:33:15 +01:00
Paint_Ninja 602f1ef947 Add helper method to OnDatapackSyncEvent, backport of #9901 (#9919) 2024-04-18 20:32:29 +01:00
Paint_Ninja 3b18e003f6 Add CPU usage config option to early window, hide by default, backport of #9866 (#9915) 2024-04-18 20:32:05 +01:00
Paint_NinjaandDennis C c33f2d1be6 Fix slightly offset mods screen link positioning, backport of #9860 (#9861)
Co-authored-by: Dennis C <[email protected]>
2024-04-18 20:31:40 +01:00
Paint_Ninja 022116141c Make common config screen registration tasks easier, backport of #9884 (#9912) 2024-04-18 20:31:01 +01:00
Joseph T. McQuigg a8b243c0cd Add Leaves method to ModelProvider.java (#9889) 2024-04-04 13:54:13 +01:00
Paint_Ninja c22355cc45 [1.20.1] Bump CoreMods and ASM (#9897)
- CoreMods 5.1.2 -> 5.1.6
- ASM 9.6 -> 9.7
2024-04-04 13:52:49 +01:00
J-RAP 74bc36307e Bump some deps (#9880)
- CoreMods 5.0.1 -> 5.1.2
- ASM 9.5 -> 9.6
- Installer 2.1 -> 2.2
- Installer tools 1.3.0 -> 1.4.1
2024-03-10 21:22:53 +00:00
LexManos 88d2dc6c8f Fix missing patch for Item.onInventoryTick. Closes #9812 2024-01-13 12:38:56 -08:00
Paint_Ninja de13ba8ab8 Make common DisplayTest registration tasks easier (#9823) 2023-12-27 09:13:37 -08:00
Paint_Ninja 4f838a87d4 Optimise ForgeConfigSpec and make Range public (#9824)
Backport of #9810 to 1.20.1
2023-12-19 13:24:07 -08:00
J.T. McQuigg 70d700e630 Datagen addOptionalTag/s methods that allow passing the TagKey itself instead of passing the location (#9807) (#9808) 2023-12-04 22:25:14 -08:00
Paint_Ninja 78fffcf45a Update VersionSupportMatrix.java (#9805) 2023-11-29 11:12:12 -08:00
J-RAP cdba403ab6 Backport of Registries optimization, now uses fastutils collections to minimize boxing 2023-11-29 11:11:55 -08:00
LexManos 6821d7b1cc Fix patch offset 2023-11-28 21:19:54 -08:00
LexManos 9524ce4580 Fix fire related mobs not taking enough freezing damage. Closes #9686 2023-11-28 20:10:28 -08:00
LexManos f2bbeab3b9 Fix TagLoader error not printing tag name correctly. Closes #9693 2023-11-28 20:09:47 -08:00
LexManos 4a8adf5465 Fix LoadingErrorScreen inner headers are not centered. Closes #9687 2023-11-28 20:08:59 -08:00
LexManos f5fa2f2a57 Rework KeyModifiers system to properly allow keybinds to be triggered when multiple modifiers are pressed.
Fix setting keybinds whel using keyboard inputs to select the menu. Closes #9793
2023-11-28 20:07:44 -08:00
LexManos b33e168969 Fix KeyModifiers not being properly taken into account. Closes #9806 2023-11-28 19:56:02 -08:00
Paint_Ninjaandembeddedt 1f6e1ff257 Don't turn off VSync when rendering from Minecraft context (#9801)
Co-authored-by: embeddedt <[email protected]>
2023-11-26 16:57:11 -08:00
Paint_Ninja 7f8897141e Fix rare crash with early display window, fixes MinecraftForge#9673 (#9799) 2023-11-26 16:24:45 -08:00
LexManos b9a097c9e1 Fix tag loading being unordered. Closes #9774 2023-11-13 08:50:07 -08:00
LexManos 62f00266c5 Fix misaligned patch in RegistryDataLoader 2023-11-10 11:26:16 -08:00
Paint_Ninja 6986cd7ab3 Backport CrashReportAnalyser to 1.20.1 (#9757) 2023-11-02 12:45:49 -07:00
Paint_Ninja e7051b3484 Minor MDK changes (#9752) 2023-11-02 12:45:39 -07:00
Paint_NinjaandSu5eD f667d25d0b Improve mod description formatting in mods screen (#9769)
Co-authored-by: Su5eD <[email protected]>
2023-11-02 12:45:29 -07:00
Paint_Ninja 48d72fb7c6 [1.20.1] Improve mod loading error message for errors inside mod constructors (#9707) 2023-09-28 00:20:40 -07:00
LexManos 2fb2bbeed0 1.20.1 RB 2023-09-21 10:17:41 -07:00
Paint_Ninjaanddhyces 12d24df4f6 Keep order of sources in PackRepository (#9702)
Co-authored-by: dhyces <[email protected]>
2023-09-02 16:21:06 -07:00
Paint_Ninja e69f5e262a Fix DelegatingPackResources searching resource path twice (#9697) 2023-08-30 14:10:17 -07:00
Paint_Ninjaandmalte0811 23cee57d88 Fix Level leak in debug HUD (#9699)
Co-authored-by: malte0811 <[email protected]>
2023-08-30 14:09:51 -07:00
Paint_Ninja ab70bde1d6 Fix PlayerSpawnPhantomsEvent not being fired (#9689) 2023-08-11 10:42:31 -07:00
Meldexun f65381fbff Enhance LivingBreathEvent and LivingDrownEvent. Closes #9680
Also remove 3.5MB of useless data from the installer.
2023-07-24 14:42:24 -07:00
LexManos b680d09359 Partially revert LazyOptional changes, now no longer internally uses weak references. 2023-07-22 08:57:25 -07:00
LexManos 7969daf81a Make LazyOptional's internal references to invalidation listeners use WeakReference, and allow modders to unregister themselves. Closes #8805 2023-07-21 23:46:26 -07:00
LexManos f157567d2a Revert EntityEvent.Size changes to before #9018 was called. (#9679)
Kept newly added methods for binary compatibility but deprecated them all for removal.
The entire pose/eye/size system needs to be reevaluated and address some of Mojang's changes.
However this should fix any bugs that pulling that PR may of caused.
2023-07-21 23:44:01 -07:00
Kovak 93a615e900 Add a config option to restore the calculate all normals behavior in case some setups require old broken behavior. (#9670) 2023-07-19 14:46:05 -07:00
Kovak 7c84249996 Fix rounding errors on models with 45 degree normals by favoring one Direction (#9669)
Should fix flickering issues when breaking custom models and having our vanilla solution disabled.
2023-07-19 14:44:28 -07:00
RealMangoRage 881725c7d5 Moved ForgeHooksClient.onCreativeModeTabBuildContents to ForgeHooks to fix #9662 2023-07-19 11:18:45 -07:00
LexManos 2745531f08 Fix tag removal functionality that broke during the 1.19 update. Closes #9053 and #8949 2023-07-19 10:26:55 -07:00
LexManos bcdd44aece Replace string with forge tag in vanilla recipes. Closes #9062 2023-07-19 00:02:11 -07:00
LexManos bad5b1b5d4 Fix new brain hooks not persisting active activities. 2023-07-18 23:50:27 -07:00
Kovak 30f255d76c Fix breaking overlay flickering on campfires by using vanilla method to calculate block normals. (#9664) 2023-07-17 18:10:12 -07:00
LexManos ebb316a15c Cleanup usages of static imports and build script so that our build doesn't spam useless error like messages.
So that it is easier to see real errors.
Add compatibility checking to standard testing tasks.
2023-07-17 17:26:28 -07:00
LegoMaster3650 e6bb7eecbd Added Action value to PlayerInteractEvent.LeftClickEvent to expose what action fired the event. #9175 2023-07-17 10:57:10 -07:00
Jonathan Colmenares c66f70d6c2 Fix parameter names in IForgeDimensionSpecialEffects.adjustLightmapColors to better describe what they are. (#9656) 2023-07-17 09:38:05 -07:00
Jonathan Colmenares 26adf4da44 Re-add EntityEvent.Size methods to maintain bincompat 2023-07-17 07:50:18 -07:00
mgaray99 30d0a630d6 Added LivingMakeBrainEvent, to allow a consistent way for modders to manipulate entity Brains. #9292 2023-07-15 12:37:42 -07:00
JustRed23 00ad61b4ae Add LivingSwapHandItemsEvent 2023-07-15 11:15:57 -07:00
brandon3055 09bc73d5cd Fixed FluidUtil#tryFillContainer returning invalid result when simulating #9358 2023-07-15 10:51:17 -07:00
Jonathan Colmenares 1ee53c0464 Re-add in-game mod menu (#9652) 2023-07-15 10:45:34 -07:00
LexManos 16863c8d3b Fix Entity eye height for multipart entities. 2023-07-15 10:45:21 -07:00
Random832 150e8281ae Fix conflicting keybindings not having the correct click count set. #9360 2023-07-15 09:28:47 -07:00
Kovak 4385eb2155 Fix the Emissive Rendering for Experimental Light Pipeline (#9651) 2023-07-15 08:07:37 -07:00
RealMangoRage 5c40bef28e Fixed AdvancementsScreen.java.patch buttons not rendering (#9649) 2023-07-14 19:06:17 -07:00
ChampionAsh5357 55aa419100 Properly Handle Fluid Updates while in a Boat #9428 2023-07-14 19:05:27 -07:00
SilverDavid a4bef82836 New hook in IClientBlockExtensions to handle enabling tinting on breaking particles. #9446 2023-07-14 16:08:24 -07:00
LexManos b741df5f18 Fix invalid index when ticking itemstacks in a player nventory by adding a new onInventoryTick event. Closes #9453 2023-07-14 15:42:13 -07:00
LexManos 0c81a71308 Make the FireworkShapes enum extensible (Closes #9486) 2023-07-14 14:01:32 -07:00
Technici4n ea7f755a11 Add EmptyEnergyStorage (#9487) 2023-07-14 11:40:16 -07:00
Paint_Ninja d947d35eb1 Support IPv6 address compression for logged IPs 2023-07-14 11:14:56 -07:00
Sara Freimer 5271ef79fe Make item name rendering and status bar rendering respect additional gui overlays being rendered by mods (#9648) 2023-07-14 10:17:43 -07:00
Meldexun b7131824f0 Fix EyeHeight event being fired twice (#9647) 2023-07-14 10:09:48 -07:00
DBotThePony 3e624db4f8 Add PlayerSpawnPhantomsEvent, utilized to block or forcefully allow PhantomSpawner to spawn phantoms (#9644) 2023-07-14 07:20:21 -07:00
Nathan fc7af96bde Fix creative mode screen not correctly using CreativeModeTab::getTabsImage (#9627) 2023-07-14 07:10:49 -07:00
Paint_Ninja b1965db30b Add option to advertise dedicated servers to LAN. 2023-07-14 05:58:10 -07:00
LexManos 8df5a80725 Fix entity eye height loop. 2023-07-14 05:57:50 -07:00
ChampionAsh5357 d9043298d3 Particle Description Data Provider. 2023-07-13 19:34:53 -07:00
Meldexun e91ff9a5a6 Add LivingBreatheEvent and LivingDrownEvent (#9525) 2023-07-13 19:19:40 -07:00
Meldexun 77fb08713f Fix entity size event not being fired, changed it to split eye height and size calculations. (#9535) 2023-07-13 19:16:17 -07:00
bconlon 2c965fac90 AlterGroundEvent for modifying block placement performed by AlterGroundDecorator (#9637) 2023-07-13 17:29:03 -07:00
JustRed23 2f229c5bb1 Change ProjectileHitEvent to return a result instead of being cancelable. Closes #9642 2023-07-13 17:21:13 -07:00
noeppi_noeppi 54b08d2711 Replace static import with regular one to fix S2S and non-official mappings. (#9633) 2023-07-11 11:26:02 -07:00
Su5eD 46f641a502 Add missing null check for TagsProvider#existingFileHelper (#9638) 2023-07-11 11:25:39 -07:00
Sara Freimer 6304cb655b Add GuiGraphics helpers for blitNineSliced and blitRepeating that support specifying a custom texture size (#9641) 2023-07-10 22:03:47 +02:00
273 changed files with 6597 additions and 2559 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: Publish
on:
push:
branches: [ '1.20.1' ]
permissions:
contents: read
jobs:
build:
uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main
with:
java: 17
gradle_setup: './gradlew setup'
gradle_tasks: 'build publish'
artifact_name: 'forge'
secrets:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
PROMOTE_ARTIFACT_WEBHOOK: ${{ secrets.PROMOTE_ARTIFACT_WEBHOOK }}
PROMOTE_ARTIFACT_USERNAME: ${{ secrets.PROMOTE_ARTIFACT_USERNAME }}
PROMOTE_ARTIFACT_PASSWORD: ${{ secrets.PROMOTE_ARTIFACT_PASSWORD }}
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
SIGN_KEY_ALIAS: ${{ secrets.SIGN_KEY_ALIAS }}
SIGN_KEY_PASSWORD: ${{ secrets.SIGN_KEY_PASSWORD }}
SIGN_KEYSTORE_PASSWORD: ${{ secrets.SIGN_KEYSTORE_PASSWORD }}
SIGN_KEYSTORE_DATA: ${{ secrets.SIGN_KEYSTORE_DATA }}
-104
View File
@@ -1,104 +0,0 @@
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<name>MinecraftForge_Forge Config DSL Script</name>
<groupId>MinecraftForge_Forge</groupId>
<artifactId>MinecraftForge_Forge_dsl</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jetbrains-all</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>teamcity-server</id>
<url>https://teamcity.minecraftforge.net/app/dsl-plugins-repository</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>JetBrains</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>${basedir}</sourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration/>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>teamcity-configs-maven-plugin</artifactId>
<version>${teamcity.dsl.version}</version>
<configuration>
<format>kotlin</format>
<dstDir>target/generated-configs</dstDir>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin</artifactId>
<version>${teamcity.dsl.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-plugins</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-runtime</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
-208
View File
@@ -1,208 +0,0 @@
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.projectFeatures.githubIssues
import jetbrains.buildServer.configs.kotlin.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2021.2"
project {
buildType(Build)
buildType(BuildSecondaryBranches)
buildType(PullRequests)
buildType(PullRequestChecks)
buildType(PullRequestCompatibility)
params {
text("docker_jdk_version", "17", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("docker_gradle_version", "7.5.1", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_main_branch", "1.20.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("git_branch_spec", """
+:refs/heads/(main*)
+:refs/heads/(master*)
+:refs/heads/(develop|release|staging|main|master)
+:refs/heads/(1.*)
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
text("github_repository_name", "MinecraftForge", label = "The github repository name. Used to connect to it in VCS Roots.", description = "This is the repository slug on github. So for example `MinecraftForge` or `MinecraftForge`. It is interpolated into the global VCS Roots.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
text("env.PUBLISHED_JAVA_ARTIFACT_ID", "forge", label = "Published artifact id", description = "The maven coordinate artifact id that has been published by this build. Can not be empty.", allowEmpty = false)
text("env.PUBLISHED_JAVA_FML_ARTIFACT_ID", "fmlonly", label = "Published fmlonly artifact id", description = "The maven coordinate artifact id for fml only that has been published by this build. Can not be empty.", allowEmpty = false)
text("env.PUBLISHED_JAVA_FML_ARTIFACT_VERSION", "0.0.0-SNAPSHOT", label = "Published fmlonly artifact version", description = "The version for fml only that has been published by this build. Can not be empty.", allowEmpty = false)
text("env.PUBLISHED_JAVA_GROUP", "net.minecraftforge", label = "Published group", description = "The maven coordinate group that has been published by this build. Can not be empty.", allowEmpty = false)
//These are references and not actually keys
password("env.CROWDIN_KEY", "credentialsJSON:a3102dbe-805d-4177-9f54-3d2c2eb08fd5", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_URL", "credentialsJSON:a7ae1c82-8058-4061-8d12-7f6bc2618d2e", display = ParameterDisplay.HIDDEN)
password("env.KEYSTORE_PASSWORD", "credentialsJSON:d7b964e3-a1fd-47a8-b892-6f601fe47479", display = ParameterDisplay.HIDDEN)
text("additional_publishing_gradle_parameters", "-PcrowdinKey=%env.CROWDIN_KEY% -PkeystoreKeyPass=%env.KEYSTORE_PASSWORD% -PkeystoreStorePass=%env.KEYSTORE_PASSWORD% -Pkeystore=%env.KEYSTORE_URL%", label = "Additional gradle parameters for publish", description = "Contains the additional gradle parameters used during publishing.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
checkbox("should_execute_build", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
checkbox("should_execute_test", "false", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
}
features {
githubIssues {
id = "MinecraftForge_MinecraftForge__IssueTracker"
displayName = "MinecraftForge/MinecraftForge"
repositoryURL = "https://github.com/MinecraftForge/MinecraftForge"
}
}
}
object Build : BuildType({
templates(AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"), AbsoluteId("MinecraftForge_PublishProjectUsingGradle"), AbsoluteId("MinecraftForge_TriggersStaticFilesWebpageGenerator"))
id("MinecraftForge_MinecraftForge__Build")
name = "Build"
description = "Builds and Publishes the main branches of the project."
features {
feature {
id = "trigger_fml_only_files_generator"
type = "triggerBuildFeature"
param("triggers", "MinecraftForge_FilesGenerator_GeneratePages")
param("parameters", """
env.PUBLISHED_JAVA_FML_ARTIFACT_ID~env.PUBLISHED_JAVA_ARTIFACT_ID
env.PUBLISHED_JAVA_FML_ARTIFACT_VERSION~env.PUBLISHED_JAVA_ARTIFACT_VERSION
env.PUBLISHED_JAVA_GROUP
""".trimIndent())
}
}
})
object BuildSecondaryBranches : BuildType({
templates(AbsoluteId("MinecraftForge_ExcludesBuildingDefaultBranch"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_BuildMainBranches"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__BuildSecondaryBranches")
name = "Build - Secondary Branches"
description = "Builds and Publishes the secondary branches of the project."
params {
text("git_branch_spec", """
+:refs/heads/(*)
-:refs/heads/noci*
""".trimIndent(), label = "The branch specification of the repository", description = "By default all main branches are build by the configuration. Modify this value to adapt the branches build.", display = ParameterDisplay.HIDDEN, allowEmpty = true)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequests : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"), AbsoluteId("MinecraftForge_BuildUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequests")
name = "Pull Requests"
description = "Builds pull requests for the project"
params {
checkbox("should_execute_build", "true", label = "Should build", description = "Indicates if the build task should be executed.", display = ParameterDisplay.HIDDEN,
checked = "true", unchecked = "false")
text(
"gradle_build_task",
"assemble",
label = "Gradle build task to execute during build",
description = "Determines the build task that is executed to build the project.",
display = ParameterDisplay.HIDDEN,
allowEmpty = false
)
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestChecks : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestChecks")
name = "Pull Requests (Checks)"
description = "Checks pull requests for the project"
steps {
gradle {
name = "Check"
id = "RUNNER_10_Check"
tasks = "checkAll"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
object PullRequestCompatibility : BuildType({
templates(AbsoluteId("MinecraftForge_BuildPullRequests"), AbsoluteId("MinecraftForge_SetupGradleUtilsCiEnvironmen"), AbsoluteId("MinecraftForge_BuildWithDiscordNotifications"), AbsoluteId("MinecraftForge_SetupProjectUsingGradle"))
id("MinecraftForge_MinecraftForge__PullRequestCompatibility")
name = "Pull Requests (Compatibility)"
description = "Validates binary compatibility for pull requests made to the project"
steps {
gradle {
name = "Validate"
id = "RUNNER_10_Compatibility"
tasks = "checkJarCompatibility"
gradleParams = "--continue %gradle_custom_args%"
enableStacktrace = true
dockerImage = "%docker_gradle_image%"
dockerRunParameters = """
-v "/opt/cache/agent/gradle:/home/gradle/.gradle"
-v "/opt/cache/shared/gradle:/home/gradle/rocache:ro"
--network=host
-u 1000:1000
%docker_additional_args%
""".trimIndent()
}
}
vcs {
branchFilter = """
+:*
-:1.*
-:<default>
""".trimIndent()
}
})
Vendored
-125
View File
@@ -1,125 +0,0 @@
@Library('forge-shared-library')_
pipeline {
options {
disableConcurrentBuilds()
}
agent {
docker {
image 'gradle:7-jdk16'
//args '-v forgegc:/home/gradle/.gradle_cache/'
}
}
environment {
GRADLE_ARGS = '--no-daemon --console=plain' // No daemon for now as FG3 kinda derps. //'-Dorg.gradle.daemon.idletimeout=5000'
DISCORD_WEBHOOK = credentials('forge-discord-jenkins-webhook')
DISCORD_PREFIX = "Job: Forge Branch: ${BRANCH_NAME} Build: #${BUILD_NUMBER}"
JENKINS_HEAD = 'https://wiki.jenkins-ci.org/download/attachments/2916393/headshot.png'
}
stages {
stage('notify_start') {
when {
not {
changeRequest()
}
}
steps {
discordSend(
title: "${DISCORD_PREFIX} Started",
successful: true,
result: 'ABORTED', //White border
thumbnail: JENKINS_HEAD,
webhookURL: DISCORD_WEBHOOK
)
}
}
/*
stage('pull_cache') {
steps {
sh 'cp -r /home/gradle/.gradle_cache/jdks/ /home/gradle/.gradle/jdks/'
sh 'cp -r /home/gradle/.gradle_cache/wrapper/ /home/gradle/.gradle/wrapper/'
sh 'cp -r /home/gradle/.gradle_cache/caches/ /home/gradle/.gradle/caches/'
}
}
*/
stage('setup') {
steps {
withGradle {
sh './gradlew ${GRADLE_ARGS} --refresh-dependencies --continue setup'
}
script {
env.MYVERSION = sh(returnStdout: true, script: './gradlew :forge:properties -q | grep "^version:" | cut -d" " -f2').trim()
env.FMLONLY_VERSION = sh(returnStdout: true, script: './gradlew :fmlonly:properties -q | grep "^version:" | cut -d" " -f2').trim()
}
}
}
stage('changelog') {
when {
not {
changeRequest()
}
}
steps {
writeChangelog(currentBuild, 'build/changelog.txt')
}
}
stage('publish') {
when {
not {
changeRequest()
}
}
environment {
CROWDIN = credentials('forge-crowdin')
KEYSTORE = credentials('forge-jenkins-keystore-old')
KEYSTORE_KEYPASS = credentials('forge-jenkins-keystore-old-keypass')
KEYSTORE_STOREPASS = credentials('forge-jenkins-keystore-old-keypass')
}
steps {
withCredentials([usernamePassword(credentialsId: 'maven-forge-user', usernameVariable: 'MAVEN_USER', passwordVariable: 'MAVEN_PASSWORD')]) {
withGradle {
sh './gradlew ${GRADLE_ARGS} publish -PkeystoreKeyPass=${KEYSTORE_KEYPASS} -PkeystoreStorePass=${KEYSTORE_STOREPASS} -Pkeystore=${KEYSTORE} -PcrowdinKey=${CROWDIN}'
}
}
}
post {
success {
build job: 'filegenerator', parameters: [string(name: 'COMMAND', value: "promote net.minecraftforge:forge ${env.MYVERSION} latest")], propagate: false, wait: false
build job: 'filegenerator', parameters: [string(name: 'COMMAND', value: "promote net.minecraftforge:fmlonly ${env.FMLONLY_VERSION} latest")], propagate: false, wait: false
}
}
}
stage('test_publish_pr') { //Publish to local repo to test full process, but don't include credentials so it can't sign/publish to maven
when {
changeRequest()
}
environment {
CROWDIN = credentials('forge-crowdin')
}
steps {
withGradle {
sh './gradlew ${GRADLE_ARGS} publish -PcrowdinKey=${CROWDIN}'
}
}
}
}
post {
always {
script {
archiveArtifacts artifacts: 'projects/forge/build/libs/**/*.*', fingerprint: true, onlyIfSuccessful: true, allowEmptyArchive: true
if (env.CHANGE_ID == null) { // This is unset for non-PRs
discordSend(
title: "${DISCORD_PREFIX} Finished ${currentBuild.currentResult}",
description: '```\n' + getChanges(currentBuild) + '\n```',
successful: currentBuild.resultIsBetterOrEqualTo("SUCCESS"),
result: currentBuild.currentResult,
thumbnail: JENKINS_HEAD,
webhookURL: DISCORD_WEBHOOK
)
}
}
}
}
}
+97 -69
View File
@@ -1,3 +1,4 @@
import de.undercouch.gradle.tasks.download.Download
import groovy.json.JsonBuilder
import net.minecraftforge.forge.tasks.checks.CheckATs
import net.minecraftforge.forge.tasks.checks.CheckExcs
@@ -24,16 +25,18 @@ import org.objectweb.asm.Opcodes
plugins {
id 'org.cadixdev.licenser' version '0.6.1'
id 'com.github.ben-manes.versions' version '0.46.0'
id 'net.minecraftforge.gradleutils' version '2.+'
id 'net.minecraftforge.gradleutils' version '[2.2,2.3)'
id 'eclipse'
id 'idea'
id 'de.undercouch.download' version '5.4.0'
id 'net.minecraftforge.gradle.patcher' version '[6.0.6,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.6,6.2)' apply false
id 'net.minecraftforge.gradle.patcher' version '[6.0.52,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.52,6.2)' apply false
}
Util.init() //Init all our extension methods!
ext {
HAS_CLEAN = findProject(':clean') != null
JAR_SIGNER = null
if (project.hasProperty('keystore')) {
JAR_SIGNER = [
@@ -52,13 +55,13 @@ ext {
SPI_VERSION = '7.0.1'
MERGETOOL_VERSION = '1.1.5'
ACCESSTRANSFORMERS_VERSION = '8.0.4'
COREMODS_VERSION = '5.0.1'
EVENTBUS_VERSION = '6.0.5'
COREMODS_VERSION = '5.2.4'
EVENTBUS_VERSION = '6.2.33'
MODLAUNCHER_VERSION = '10.0.9'
SECUREJARHANDLER_VERSION = '2.1.10'
BOOTSTRAPLAUNCHER_VERSION = '1.1.2'
ASM_VERSION = '9.5'
INSTALLER_VERSION = '2.1.+'
ASM_VERSION = '9.9.1'
INSTALLER_VERSION = '2.2.+'
MIXIN_VERSION = '0.8.5'
TERMINALCONSOLEAPPENDER_VERSION = '1.2.0'
JLINE_VERSION = '3.12.+'
@@ -84,7 +87,7 @@ ext {
FORGE_VERSION = VERSION.substring(MC_VERSION.length() + 1)
BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.1.1:fatjar'
INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.3.0'
INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.1'
JAR_SPLITTER = 'net.minecraftforge:jarsplitter:1.1.4'
FART = 'net.minecraftforge:ForgeAutoRenamingTool:0.1.22:all'
MIN_TAG_FOR_CHANGELOG = '41.0'
@@ -209,6 +212,11 @@ subprojects {
maven gradleutils.getPublishingForgeMaven()
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
options.warnings = false // Shutup deprecated for removal warnings
}
}
project(':mcp') {
@@ -220,45 +228,47 @@ project(':mcp') {
}
}
project(':clean') {
evaluationDependsOn(':mcp')
apply plugin: 'net.minecraftforge.gradle.patcher'
tasks.withType(AbstractPublishToMaven.class).forEach{tsk -> tsk.enabled = false } // We don't want to publish anything
if (HAS_CLEAN) {
project(':clean') {
evaluationDependsOn(':mcp')
apply plugin: 'net.minecraftforge.gradle.patcher'
tasks.withType(AbstractPublishToMaven.class).forEach{tsk -> tsk.enabled = false } // We don't want to publish anything
dependencies {
implementation 'net.minecraftforge:forgespi:' + SPI_VERSION
}
dependencies {
implementation 'net.minecraftforge:forgespi:' + SPI_VERSION
}
patcher {
parent = project(':mcp')
mcVersion = MC_VERSION
patchedSrc = file('src/main/java')
patcher {
parent = project(':mcp')
mcVersion = MC_VERSION
patchedSrc = file('src/main/java')
mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
runs {
clean_client {
client true
taskName 'clean_client'
ideaModule "${rootProject.name}.${project.name}.main"
runs {
clean_client {
client true
taskName 'clean_client'
ideaModule "${rootProject.name}.${project.name}.main"
main 'net.minecraft.client.main.Main'
workingDirectory project.file('run')
main 'net.minecraft.client.main.Main'
workingDirectory project.file('run')
args '--gameDir', '.'
args '--version', MC_VERSION
args '--assetsDir', downloadAssets.output
args '--assetIndex', '{asset_index}'
args '--accessToken', '0'
}
args '--gameDir', '.'
args '--version', MC_VERSION
args '--assetsDir', downloadAssets.output
args '--assetIndex', '{asset_index}'
args '--accessToken', '0'
}
clean_server {
client false
taskName 'clean_server'
ideaModule "${rootProject.name}.${project.name}.main"
clean_server {
client false
taskName 'clean_server'
ideaModule "${rootProject.name}.${project.name}.main"
main 'net.minecraft.server.Main'
workingDirectory project.file('run')
main 'net.minecraft.server.Main'
workingDirectory project.file('run')
}
}
}
}
@@ -296,7 +306,7 @@ def sharedDeps = {
installer "org.jline:jline-reader:${JLINE_VERSION}" // Dep of TerminalConsoleAppender
installer "org.jline:jline-terminal:${JLINE_VERSION}" // Dep of TerminalConsoleAppender
installer "org.spongepowered:mixin:${MIXIN_VERSION}"
installer 'org.openjdk.nashorn:nashorn-core:15.3'
installer 'org.openjdk.nashorn:nashorn-core:15.4'
installer "net.minecraftforge:JarJarSelector:${JARJAR_VERSION}"
installer "net.minecraftforge:JarJarMetadata:${JARJAR_VERSION}"
@@ -349,7 +359,7 @@ def sharedFmlonlyForge = { Project prj ->
}
prj.task([type: DownloadMavenArtifact], 'downloadInstaller') {
artifact = "net.minecraftforge:installer:${INSTALLER_VERSION}:shrunk"
artifact = "net.minecraftforge:installer:${INSTALLER_VERSION}:fatjar"
changing = true
}
@@ -881,15 +891,14 @@ project(':fmlonly') {
}
project(':forge') {
evaluationDependsOn(':clean')
evaluationDependsOn(HAS_CLEAN ? ':clean' : ':mcp')
apply plugin: 'java-library'
apply plugin: 'net.minecraftforge.gradle.patcher'
apply plugin: 'org.cadixdev.licenser'
applyPatches {
verbose = true
//failOnError = false
}
level 'WARNING'
}
sourceSets {
main {
@@ -962,12 +971,14 @@ project(':forge') {
patcher {
excs.from file("$rootDir/src/main/resources/forge.exc")
parent = project(':clean')
parent = project(HAS_CLEAN ? ':clean' : ':mcp')
patches = file("$rootDir/patches/minecraft")
patchedSrc = file('src/main/java')
srgPatches = true
accessTransformers.from file("$rootDir/src/main/resources/META-INF/accesstransformer.cfg")
sideAnnotationStrippers.from file("$rootDir/src/main/resources/forge.sas")
mappings channel: MAPPING_CHANNEL, version: MAPPING_VERSION
mcVersion = MC_VERSION
runs {
forge_client {
@@ -1173,9 +1184,12 @@ project(':forge') {
]
}
task crowdin(type: Crowdin) {
key = project.hasProperty('crowdinKey') ? project.crowdinKey : null
//TODO: Merge our english.json?
tasks.register('downloadCrowdin', Download) {
src 'https://files.minecraftforge.net/crowdin.zip'
dest file('build/crowdin.zip')
useETag 'all'
onlyIfModified true
quiet true
}
sharedFmlonlyForge.call(project)
@@ -1586,9 +1600,12 @@ project(':forge') {
from extraTxts
// add crowdin locales
from { crowdin.output.present && crowdin.output.get().asFile.exists() ? zipTree(crowdin.output) : null}
dependsOn crowdin
duplicatesStrategy = 'exclude'
from zipTree(downloadCrowdin.dest).matching {
include 'assets/forge/lang/*.json'
}
dependsOn downloadCrowdin
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
doFirst {
MANIFESTS.each{ pkg, values ->
@@ -1615,6 +1632,12 @@ project(':forge') {
}
}
final mdkGradleWrapper = tasks.register('mdkGradleWrapper', Wrapper) {
gradleVersion = "9.8.2"
scriptFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradlew")
jarFile = layout.buildDirectory.dir("wrapper/" + gradleVersion + "/gradle/wrapper/gradle-wrapper.jar")
}
task makeMdk(type: Zip) {
archiveBaseName = project.name
archiveClassifier = 'mdk'
@@ -1624,8 +1647,9 @@ project(':forge') {
from rootProject.file('gradlew')
from rootProject.file('gradlew.bat')
from extraTxts
from(rootProject.file('gradle/')){
into('gradle/')
into('gradle/wrapper/') {
from mdkGradleWrapper.map(Wrapper.&getJarFile)
from mdkGradleWrapper.map(Wrapper.&getPropertiesFile)
}
from(rootProject.file('mdk/')){
rootProject.file('mdk/gitignore.txt').eachLine{
@@ -1775,32 +1799,36 @@ project(':forge') {
}
// Since we need the modules in the bootstrap, we need to make sure they are compiled before we do each run
afterEvaluate { prepareRuns.dependsOn(PACKED_DEPS) }
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// Make sure we run bin compat checking during local testing.
if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
publish.dependsOn(':forge:checkJarCompatibility')
}
//evaluationDependsOnChildren()
task setup() { //These must be strings so that we can do lazy resolution. Else we need evaluationDependsOnChildren above
dependsOn ':clean:extractMapped'
if (HAS_CLEAN)
dependsOn ':clean:extractMapped'
if (symlinkValid)
dependsOn ':fmlonly:extractMapped'
dependsOn ':forge:extractMapped'
}
task doChecks {
dependsOn ':forge:checkJarCompatibility'
dependsOn ':forge:publish'
}
if (symlinkValid)
project.gradle.startParameter.excludedTaskNames.add(':fmlonly:genPatches')
project.gradle.startParameter.excludedTaskNames.add(':clean:genPatches')
//Also output FMLOnly when building a version.
if (System.env.TEAMCITY_VERSION) {
//Only setup the CI environment if and only if the environment variables are set.
tasks.configureTeamCity {
doLast {
println "##teamcity[buildNumber '${project(':forge').version}']"
println "##teamcity[setParameter name='env.PUBLISHED_JAVA_ARTIFACT_VERSION' value='${project(':forge').version}']"
println "##teamcity[setParameter name='env.PUBLISHED_JAVA_FML_ARTIFACT_VERSION' value='${project(':fmlonly').version}']"
}
if (HAS_CLEAN)
project.gradle.startParameter.excludedTaskNames.add(':clean:genPatches')
idea {
module {
// IntelliJ IDEA does not do this by itself anymore...
downloadJavadoc = true
downloadSources = true
}
}
+3 -3
View File
@@ -4,9 +4,9 @@ repositories {
}
dependencies {
implementation 'org.ow2.asm:asm:9.5'
implementation 'org.ow2.asm:asm-tree:9.5'
implementation 'net.minecraftforge:srgutils:0.5.+'
implementation 'org.ow2.asm:asm:9.9.1'
implementation 'org.ow2.asm:asm-tree:9.9.1'
implementation 'net.minecraftforge:srgutils:0.6.5'
implementation 'commons-io:commons-io:2.12.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r'
@@ -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.stream().sorted().toList() ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
}
}
+30 -11
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.1&query=$.promos["1.20.1-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download]
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.20.1-&query=$.promos["1.20.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.20.1-&query=$.promos["1.20.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]
@@ -27,10 +26,23 @@ You can download the installer for the *Recommended Build* or the
*Latest build* there. Latest builds may have newer features but may be
more unstable as a result. The installer will attempt to install Forge
into your vanilla launcher environment, where you can then create a new
profile using that version and play the game!
profile using that version and play the game!
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,14 +75,21 @@ 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/
[Documentation]: https://docs.minecraftforge.net/
[Getting-Started]: https://docs.minecraftforge.net/en/latest/gettingstarted/
[ForgeDev]: https://docs.minecraftforge.net/en/latest/forgedev/
[Pull-Requests]: https://docs.minecraftforge.net/en/latest/forgedev/#making-changes-and-pull-requests
[Documentation]: https://docs.minecraftforge.net/en/1.20.1/
[Getting-Started]: https://docs.minecraftforge.net/en/1.20.1/gettingstarted/
[ForgeDev]: https://docs.minecraftforge.net/en/1.20.1/forgedev/
[Pull-Requests]: https://docs.minecraftforge.net/en/1.20.1/forgedev/#making-changes-and-pull-requests
[Patreon]: https://www.patreon.com/MinecraftForge
[Patreon]: https://www.patreon.com/LexManos
@@ -5,36 +5,39 @@
package net.minecraftforge.fml;
import cpw.mods.modlauncher.util.ServiceLoaderUtils;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.loading.FMLLoader;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.function.Supplier;
/**
* Used to allow access to certain things from the game layer
*/
public class Bindings {
private static final Bindings INSTANCE = new Bindings();
private Bindings() {}
private final IBindingsProvider provider;
private Bindings() {
final var providers = ServiceLoaderUtils.streamServiceLoader(()->ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class), sce->{}).toList();
if (providers.size() != 1) {
throw new IllegalStateException("Could not find bindings provider");
}
this.provider = providers.get(0);
}
/**
* The provider of the bindings
* @implNote May also throw a {@link ServiceConfigurationError}
*/
private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
/**
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
*/
public static Supplier<IEventBus> getForgeBus() {
return INSTANCE.provider.getForgeBusSupplier();
return PROVIDER.getForgeBusSupplier();
}
public static Supplier<I18NParser> getMessageParser() {
return INSTANCE.provider.getMessageParser();
return PROVIDER.getMessageParser();
}
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
return INSTANCE.provider.getConfigConfiguration();
return PROVIDER.getConfigConfiguration();
}
}
@@ -95,5 +95,24 @@ public interface IExtensionPoint<T extends Record>
@SuppressWarnings("JavadocReference") // reference to NetworkConstants, ForgeHooksClient
record DisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) implements IExtensionPoint<DisplayTest> {
public static final String IGNORESERVERONLY = "OHNOES\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31";
/**
* Ignores any version information coming from the server - use for server only mods
*/
public static final Supplier<DisplayTest> IGNORE_SERVER_VERSION = () -> new DisplayTest(IGNORESERVERONLY, (remoteVersion, isFromServer) -> true);
/**
* Ignores all information and provides no information
*/
public static final Supplier<DisplayTest> IGNORE_ALL_VERSION = () -> new DisplayTest("", (remoteVersion, isFromServer) -> true);
/**
* An optional alternative to {@link #DisplayTest(Supplier, BiPredicate)} which accepts a constant version string
* instead of a {@link Supplier}.
* <p>Internally, the provided version string is wrapped in a Supplier for you.</p>
*/
public DisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
this(() -> version, remoteVersionTest);
}
}
}
@@ -9,6 +9,7 @@ import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import net.minecraftforge.forgespi.language.IModInfo;
@@ -21,6 +22,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -58,15 +60,16 @@ public abstract class ModContainer
this.modInfo = info;
this.modLoadingStage = ModLoadingStage.CONSTRUCT;
final String displayTestString = info.getConfig().<String>getConfigElement("displayTest").orElse("MATCH_VERSION"); // missing defaults to DEFAULT type
final String displayTestString = info.getConfig().<String>getConfigElement("displayTest")
.orElseGet(() -> (Boolean) info.getOwningFile().getFileProperties().getOrDefault(ModFileInfo.CLIENT_SIDE_ONLY_PROP, Boolean.FALSE) ? "IGNORE_ALL_VERSION" : "MATCH_VERSION");
Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) {
case "MATCH_VERSION" -> // default displaytest checks for version string match
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
(incoming, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
() -> new IExtensionPoint.DisplayTest(() -> IExtensionPoint.DisplayTest.IGNORESERVERONLY, (incoming, isNetwork) -> true);
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
() -> new IExtensionPoint.DisplayTest(() -> "", (incoming, isNetwork) -> true);
IExtensionPoint.DisplayTest.IGNORE_ALL_VERSION;
case "NONE" -> null; // NO display test at all - use this if you're going to do your own display test
default -> // any other value throws an exception
throw new IllegalArgumentException("Invalid displayTest value supplied in mods.toml");
@@ -145,6 +148,22 @@ public abstract class ModContainer
extensionPoints.put(point, extension);
}
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> displayTest);
}
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
registerExtensionPoint(IExtensionPoint.DisplayTest.class, displayTest);
}
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void addConfig(final ModConfig modConfig) {
configs.put(modConfig.getType(), modConfig);
}
@@ -8,38 +8,54 @@ package net.minecraftforge.fml;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.loading.FMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
public class ModLoadingContext
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
private ModContainer activeContainer;
private Object languageExtension;
private ModLoadingStage stage;
/**
* @deprecated Use the context provided by your language loader in your mod's constructor.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static ModLoadingContext get() {
return context.get();
}
private ModContainer activeContainer;
/**
* @deprecated Going to be moved to ForgeHooks for internal use.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public void setActiveContainer(final ModContainer container) {
this.activeContainer = container;
this.languageExtension = container == null ? null : container.contextExtension.get();
}
/**
* Going to be moved to ForgeHooks for internal use.
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public ModContainer getActiveContainer() {
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
}
@Deprecated(forRemoval = true, since = "1.21.1")
public String getActiveNamespace() {
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
}
public ModContainer getContainer() {
return getActiveContainer();
}
/**
* Register an {@link IExtensionPoint} with the mod container.
* @param point The extension point to register
@@ -47,29 +63,67 @@ public class ModLoadingContext
* @param <T> The type signature of the extension operator
*/
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
getActiveContainer().registerExtensionPoint(point, extension);
getContainer().registerExtensionPoint(point, extension);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)}.</p>
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
*/
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
getContainer().registerDisplayTest(() -> displayTest);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest supplier with {@link #registerExtensionPoint(Class, Supplier)}.</p>
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
*/
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
getContainer().registerDisplayTest(displayTest);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
* creates the DisplayTest instance for you using the provided parameters.</p>
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
*/
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
* creates the DisplayTest instance for you using the provided parameters.</p>
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
*/
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getActiveContainer().getModId());
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
return;
}
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer()));
getContainer().addConfig(new ModConfig(type, spec, getContainer()));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getActiveContainer().getModId(), fileName);
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
return;
}
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName));
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
}
@@ -51,8 +51,8 @@ public class VersionChecker
BETA(),
BETA_OUTDATED(6, true);
final int sheetOffset;
final boolean draw, animated;
private final int sheetOffset;
private final boolean draw, animated;
Status()
{
@@ -91,6 +91,9 @@ public class VersionChecker
return animated;
}
public boolean isOutdated() {
return this == OUTDATED || this == BETA_OUTDATED;
}
}
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {}
@@ -257,7 +260,7 @@ public class VersionChecker
LOGGER.warn("Failed to process update information", e);
status = FAILED;
}
results.put(mod, new CheckResult(status, target, changes, display_url));
RESULTS.put(mod, new CheckResult(status, target, changes, display_url));
}
}.start();
}
@@ -273,12 +276,12 @@ public class VersionChecker
return ret;
}
private static Map<IModInfo, CheckResult> results = new ConcurrentHashMap<>();
private static final Map<IModInfo, CheckResult> RESULTS = new ConcurrentHashMap<>();
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
public static CheckResult getResult(IModInfo mod)
{
return results.getOrDefault(mod, PENDING_CHECK);
return RESULTS.getOrDefault(mod, PENDING_CHECK);
}
}
@@ -14,9 +14,7 @@ import net.minecraftforge.fml.loading.ImmediateWindowProvider;
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.PointerBuffer;
import org.lwjgl.glfw.GLFWImage;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.tinyfd.TinyFileDialogs;
@@ -30,9 +28,8 @@ import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
@@ -40,15 +37,16 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
@@ -78,7 +76,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY");
private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true);
private ColourScheme colourScheme;
private ColourScheme colourScheme = ColourScheme.RED;
private ElementShader elementShader;
private RenderElement.DisplayContext context;
@@ -86,6 +84,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
private int framecount;
private EarlyFramebuffer framebuffer;
private ScheduledFuture<?> windowTick;
private ScheduledFuture<?> initializationFuture;
private PerformanceInfo performanceInfo;
private ScheduledFuture<?> performanceTick;
@@ -134,13 +133,17 @@ public class DisplayWindow implements ImmediateWindowProvider {
this.colourScheme = ColourScheme.BLACK;
} else {
try {
var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Paths.get("options.txt")));
var options = optionLines.stream().map(l -> l.split(":")).filter(a -> a.length == 2).collect(Collectors.toMap(a -> a[0], a -> a[1]));
var colourScheme = Boolean.parseBoolean(options.getOrDefault("darkMojangStudiosBackground", "false"));
this.colourScheme = colourScheme ? ColourScheme.BLACK : ColourScheme.RED;
} catch (IOException ioe) {
// No options
this.colourScheme = ColourScheme.RED; // default to red colourscheme
// check the options file for the colour scheme
var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt")));
var keyName = "darkMojangStudiosBackground:";
for (String line : optionLines) {
if (line.startsWith(keyName)) {
this.colourScheme = line.startsWith("true", keyName.length()) ? ColourScheme.BLACK : ColourScheme.RED;
break;
}
}
} catch (IOException e) {
this.colourScheme = ColourScheme.RED; // fallback to red colourScheme
}
}
this.maximized = parsed.has(maximizedopt) || FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_MAXIMIZED);
@@ -225,7 +228,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
LOGGER.error("Crash during font initialization", t);
crashElegantly("An error occurred initializing a font for rendering. "+t.getMessage());
}
this.elements = new ArrayList<>(Arrays.asList(
this.elements = new ArrayList<>(List.of(
RenderElement.anvil(font),
RenderElement.logMessageOverlay(font),
RenderElement.forgeVersionOverlay(font, mcVersion+"-"+forgeVersion.split("-")[0]),
@@ -264,7 +267,6 @@ public class DisplayWindow implements ImmediateWindowProvider {
public void render(int alpha) {
var currentVAO = glGetInteger(GL_VERTEX_ARRAY_BINDING);
var currentFB = glGetInteger(GL_READ_FRAMEBUFFER_BINDING);
glfwSwapInterval(0);
glViewport(0, 0, this.context.scaledWidth(), this.context.scaledHeight());
RenderElement.globalAlpha = alpha;
framebuffer.activate();
@@ -287,7 +289,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
return thread;
});
initWindow(mcVersion);
renderScheduler.schedule(() -> initRender(mcVersion, forgeVersion), 1, TimeUnit.MILLISECONDS);
this.initializationFuture = renderScheduler.schedule(() -> initRender(mcVersion, forgeVersion), 1, TimeUnit.MILLISECONDS);
return this::periodicTick;
}
@@ -360,14 +362,15 @@ public class DisplayWindow implements ImmediateWindowProvider {
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
if (mcVersion != null) {
// this emulates what we would get without early progress window
// as vanilla never sets these, so GLFW uses the first window title
// set them explicitly to avoid it using "FML early loading progress" as the class
String vanillaWindowTitle = "Minecraft* " + mcVersion;
glfwWindowHintString(GLFW_X11_CLASS_NAME, vanillaWindowTitle);
glfwWindowHintString(GLFW_X11_INSTANCE_NAME, vanillaWindowTitle);
}
String vanillaWindowTitle = "Minecraft* ";
if (mcVersion != null) vanillaWindowTitle += mcVersion;
// this emulates what we would get without early progress window
// as vanilla never sets these, so GLFW uses the first window title
// set them explicitly to avoid it using "FML early loading progress" as the class
glfwWindowHintString(GLFW_X11_CLASS_NAME, vanillaWindowTitle);
glfwWindowHintString(GLFW_X11_INSTANCE_NAME, vanillaWindowTitle);
long primaryMonitor = glfwGetPrimaryMonitor();
if (primaryMonitor == 0) {
@@ -389,7 +392,8 @@ public class DisplayWindow implements ImmediateWindowProvider {
}, 10, TimeUnit.SECONDS);
int versidx = 0;
var skipVersions = FMLConfig.<String>getListConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SKIP_GL_VERSIONS);
final String[] lastGLError=new String[GL_VERSIONS.length];
boolean showHelpLog = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG);
final String[] lastGLError = new String[GL_VERSIONS.length];
do {
final var glVersionToTry = GL_VERSIONS[versidx][0] + "." + GL_VERSIONS[versidx][1];
if (skipVersions.contains(glVersionToTry)) {
@@ -398,11 +402,23 @@ public class DisplayWindow implements ImmediateWindowProvider {
continue;
}
LOGGER.info("Trying GL version " + glVersionToTry);
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
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GL_VERSIONS[versidx][1]);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
window = glfwCreateWindow(winWidth, winHeight, "Minecraft: Forge Loading...", 0L, 0L);
window = glfwCreateWindow(winWidth, winHeight, vanillaWindowTitle, 0L, 0L);
var erridx = versidx;
handleLastGLFWError((error, description) -> lastGLError[erridx] = String.format("Trying %d.%d: GLFW error: [0x%X]%s", GL_VERSIONS[erridx][0], GL_VERSIONS[erridx][1], error, description));
if (lastGLError[versidx] != null) {
@@ -430,6 +446,9 @@ public class DisplayWindow implements ImmediateWindowProvider {
this.glVersion = gotVersion;
this.window = window;
if (showHelpLog)
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG, false);
int[] x = new int[1];
int[] y = new int[1];
glfwGetMonitorPos(primaryMonitor, x, y);
@@ -447,19 +466,19 @@ public class DisplayWindow implements ImmediateWindowProvider {
glfwSetWindowPos(window, (vidmode.width() - this.winWidth) / 2 + monitorX, (vidmode.height() - this.winHeight) / 2 + monitorY);
// Attempt setting the icon
int[] channels = new int[1];
try (var glfwImgBuffer = GLFWImage.create(MemoryUtil.getAllocator().malloc(GLFWImage.SIZEOF), 1)) {
final ByteBuffer imgBuffer;
try (GLFWImage glfwImages = GLFWImage.malloc()) {
imgBuffer = STBHelper.loadImageFromClasspath("forge_logo.png", 20000, x, y, channels);
glfwImgBuffer.put(glfwImages.set(x[0], y[0], imgBuffer));
glfwSetWindowIcon(window, glfwImgBuffer);
STBImage.stbi_image_free(imgBuffer);
}
} catch (NullPointerException e) {
System.err.println("Failed to load forge logo");
}
handleLastGLFWError((error, description) -> LOGGER.debug(String.format("Suppressing GLFW icon error: [0x%X]%s", error, description)));
// int[] channels = new int[1];
// try (var glfwImgBuffer = GLFWImage.create(MemoryUtil.getAllocator().malloc(GLFWImage.SIZEOF), 1)) {
// final ByteBuffer imgBuffer;
// try (GLFWImage glfwImages = GLFWImage.malloc()) {
// imgBuffer = STBHelper.loadImageFromClasspath("forge_logo.png", 20000, x, y, channels);
// glfwImgBuffer.put(glfwImages.set(x[0], y[0], imgBuffer));
// glfwSetWindowIcon(window, glfwImgBuffer);
// STBImage.stbi_image_free(imgBuffer);
// }
// } catch (NullPointerException e) {
// System.err.println("Failed to load forge logo");
// }
// handleLastGLFWError((error, description) -> LOGGER.debug(String.format("Suppressing GLFW icon error: [0x%X]%s", error, description)));
glfwSetFramebufferSizeCallback(window, this::fbResize);
glfwSetWindowPosCallback(window, this::winMove);
@@ -518,6 +537,16 @@ public class DisplayWindow implements ImmediateWindowProvider {
* @return the Window we own.
*/
public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitorSupplier) {
// wait for the window to actually be initialized
try {
this.initializationFuture.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
Thread.dumpStack();
crashElegantly("We seem to be having trouble initializing the window, waited for 30 seconds");
}
// we have to spin wait for the window ticker
ImmediateWindowHandler.updateProgress("Initializing Game Graphics");
while (!this.windowTick.isDone()) {
@@ -584,8 +613,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
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();
var methods = Arrays.stream(clz.getMethods()).filter(m-> Modifier.isStatic(m.getModifiers())).collect(Collectors.toMap(Method::getName, Function.identity()));
loadingOverlay = methods.get("newInstance");
loadingOverlay = Arrays.stream(clz.getMethods()).filter(m-> Modifier.isStatic(m.getModifiers()) && m.getName().equals("newInstance")).findFirst().orElseThrow();
}
public int getFramebufferTextureId() {
@@ -6,35 +6,44 @@
package net.minecraftforge.fml.earlydisplay;
import com.sun.management.OperatingSystemMXBean;
import net.minecraftforge.fml.loading.FMLConfig;
import java.lang.management.ManagementFactory;
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;
float memory;
private String text;
PerformanceInfo() {
osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
memoryBean = ManagementFactory.getMemoryMXBean();
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
}
void update() {
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage();
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
memory = (float) heapusage.getUsed() / heapusage.getMax();
if (!showCPUUsage) {
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
return;
}
var cpuLoad = osBean.getProcessCpuLoad();
String cpuText;
if (cpuLoad == -1) {
cpuText = String.format("*CPU: %.1f%%", osBean.getCpuLoad() * 100f);
cpuText = "*CPU: %.1f%%".formatted(osBean.getCpuLoad() * 100f);
} else {
cpuText = String.format("CPU: %.1f%%", cpuLoad * 100f);
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
}
text = String.format("Heap: %d/%d MB (%.1f%%) OffHeap: %d MB %s", 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() {
@@ -34,11 +34,14 @@ public class RenderElement {
};
}
}
@FunctionalInterface
interface TextureRenderer {
void accept(SimpleBufferBuilder bb, DisplayContext context, int[] size, int frame);
}
@FunctionalInterface
interface Initializer extends Supplier<Renderer> {}
@FunctionalInterface
interface TextGenerator {
void accept(SimpleBufferBuilder bb, SimpleFont fh, DisplayContext ctx);
}
@@ -201,14 +204,17 @@ public class RenderElement {
bar.then(label).accept(buffer, context, frameNumber);
}
@FunctionalInterface
interface ColourFunction {
int colour(int frame);
}
@FunctionalInterface
interface ProgressDisplay {
float[] progress(int frame);
}
@FunctionalInterface
interface BarPosition {
int[] location(DisplayContext context);
}
@@ -280,7 +286,7 @@ public class RenderElement {
if (num < min) {
return min;
} else {
return num > max ? max : num;
return Math.min(num, max);
}
}
@@ -288,7 +294,7 @@ public class RenderElement {
if (num < min) {
return min;
} else {
return num > max ? max : num;
return Math.min(num, max);
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

+1 -1
View File
@@ -77,7 +77,7 @@ jar.doFirst {
}
tasks.withType(JavaCompile) {
options.compilerArgs << '-Xlint:unchecked'
options.compilerArgs << '-Xlint:-unchecked'
}
license {
@@ -36,9 +36,9 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
*/
public class CapabilityTokenSubclass implements ILaunchPluginService {
private final String FUNC_NAME = "getType";
private final String FUNC_DESC = "()Ljava/lang/String;";
private final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
private static final String FUNC_NAME = "getType";
private static final String FUNC_DESC = "()Ljava/lang/String;";
private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
@@ -51,7 +51,14 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY;
return YAY;
}
@Override
@@ -75,7 +82,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9)
{
Deque<String> stack = new ArrayDeque<>();
final Deque<String> stack = new ArrayDeque<>();
@Override
public void visitClassType(final String name)
@@ -113,7 +120,7 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
}
}
private static class Holder {
private static final class Holder {
String value;
}
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -35,7 +36,11 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
new VanillaObjectHolderData("net.minecraft.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toMap(VanillaObjectHolderData::holderClass, Function.identity()));
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final Set<String> VANILLA_OBJECT_HOLDER_CLASSES = VANILLA_OBJECT_HOLDERS.keySet().stream()
.map(it -> it.replace('.', '/'))
.collect(Collectors.toUnmodifiableSet());
private static final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final int PUBLIC_STATIC_FINAL_FLAGS = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
@Override
public String name() {
@@ -46,13 +51,30 @@ 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")
&& !internalName.equals("net/minecraftforge/common/crafting/ConditionalRecipe"))
return NAY;
// Vanilla classes that don't have object holders
if (internalName.startsWith("com/mojang/"))
return NAY;
// ...except specific ones we added to the VANILLA_OBJECT_HOLDERS map
if (internalName.startsWith("net/minecraft/") && !VANILLA_OBJECT_HOLDER_CLASSES.contains(internalName))
return NAY;
return YAY;
}
private boolean hasHolder(List<AnnotationNode> lst)
{
private boolean hasHolder(List<AnnotationNode> lst) {
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
@@ -75,10 +97,9 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
{
final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final
@@ -88,7 +109,7 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
if (VANILLA_OBJECT_HOLDERS.containsKey(classType.getClassName())) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L")).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL;
@@ -30,15 +30,16 @@ import org.slf4j.MarkerFactory;
public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger();
private final Type STRING = Type.getType(String.class);
private final Type ENUM = Type.getType(Enum.class);
private final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private final String NAME_DESC = Type.getMethodDescriptor(STRING);
private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
private static final Type STRING = Type.getType(String.class);
private static final Type ENUM = Type.getType(Enum.class);
private static final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
private static final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private static final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private static final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
private static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
private static final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
private static final int FLAGS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
@Override
public String name() {
@@ -49,9 +50,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
@@ -60,25 +67,24 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return ComputeFlags.NO_REWRITE;
Type array = Type.getType("[" + classType.getDescriptor());
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) {
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE;
}
Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor();
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
//Static methods named "create" with first argument as a string
List<MethodNode> candidates = classNode.methods.stream()
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
.collect(Collectors.toList());
.toList();
if (candidates.isEmpty()) {
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
}
candidates.forEach(mtd ->
for (var mtd : candidates)
{
Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING)) {
@@ -110,8 +116,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE;
for (int x = 1; x < args.length; x++)
ctrArgs[1 + x] = args[x];
System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
@@ -233,7 +238,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
ins.load(vars, classType);
ins.areturn(classType);
}
});
}
return ComputeFlags.COMPUTE_FRAMES;
}
@@ -36,7 +36,9 @@ public class FMLConfig
EARLY_WINDOW_FBSCALE("earlyWindowFBScale", 1, "Early window framebuffer scale"),
EARLY_WINDOW_MAXIMIZED("earlyWindowMaximized", Boolean.FALSE, "Early window starts maximized"),
EARLY_WINDOW_SKIP_GL_VERSIONS("earlyWindowSkipGLVersions", List.of(), "Skip specific GL versions, may help with buggy graphics card drivers"),
EARLY_WINDOW_SQUIR("earlyWindowSquir", Boolean.FALSE, "Squir?")
EARLY_WINDOW_SQUIR("earlyWindowSquir", Boolean.FALSE, "Squir?"),
EARLY_WINDOW_SHOW_CPU("earlyWindowShowCPU", Boolean.FALSE, "Whether to show CPU usage stats in early window"),
EARLY_WINDOW_LOG_HELP_MSG("earlyWindowLogHelpMessage", Boolean.TRUE, "Whether to log a help message on first attempt, to aid troubleshooting. This setting should automatically disable itself after a successful launch"),
;
private final String entry;
@@ -65,6 +65,9 @@ public class FMLLoader
throw new IncompatibleEnvironmentException("Incompatible modlauncher found "+modLauncherPackage.getSpecificationVersion());
}
// Allows us to communicate properties with other services through ModLauncher
setupBlackboardKeys();
accessTransformer = (AccessTransformerService) environment.findLaunchPlugin("accesstransformer").orElseThrow(()-> {
LOGGER.error(CORE, "Access Transformer library is missing, we need this to run");
return new IncompatibleEnvironmentException("Missing AccessTransformer, cannot run");
@@ -126,6 +129,12 @@ public class FMLLoader
}
}
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");
@@ -193,7 +202,7 @@ public class FMLLoader
public static void addAccessTransformer(Path atPath, ModFile modName)
{
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
LOGGER.debug(SCAN, "Adding Access Transformer in {} in {}", atPath, modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
@@ -5,6 +5,8 @@
package net.minecraftforge.fml.loading;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IModuleLayerManager;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
import org.apache.logging.log4j.LogManager;
@@ -23,28 +25,44 @@ public class ImmediateWindowHandler {
private static ProgressMeter earlyProgress;
public static void load(final String launchTarget, final String[] arguments) {
final var serviceLayer = Launcher.INSTANCE.findLayerManager()
.flatMap(manager -> manager.getLayer(IModuleLayerManager.Layer.SERVICE))
.orElse(null);
final var providerName = FMLConfig.getConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER);
if (!List.of("forgeclient", "forgeclientuserdev", "forgeclientdev").contains(launchTarget)) {
provider = new DummyProvider();
LOGGER.info("ImmediateWindowProvider not loading because launch target is {}", launchTarget);
} else if (!FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_CONTROL)) {
provider = new DummyProvider();
LOGGER.info("ImmediateWindowProvider not loading because splash screen is disabled");
} else if (providerName == null) {
LOGGER.info("ImmediateWindowProvider not loading because splash screen provider is null");
} else if (serviceLayer == null) {
LOGGER.error("Failed to find service layer for ImmediateWindowProvider");
} else {
final var providername = FMLConfig.getConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER);
LOGGER.info("Loading ImmediateWindowProvider {}", providername);
final var maybeProvider = ServiceLoader.load(ImmediateWindowProvider.class)
.stream()
.map(ServiceLoader.Provider::get)
.filter(p -> Objects.equals(p.name(), providername))
.findFirst();
provider = maybeProvider.or(() -> {
LOGGER.info("Failed to find ImmediateWindowProvider {}, disabling", providername);
return Optional.of(new DummyProvider());
}).orElseThrow();
LOGGER.info("Loading ImmediateWindowProvider {}", providerName);
for (var itr = ServiceLoader.load(serviceLayer, ImmediateWindowProvider.class).iterator(); itr.hasNext(); ) {
try {
var srvc = itr.next();
if (providerName.equals(srvc.name())) {
provider = new Wrapper(srvc);
break;
}
} catch (ServiceConfigurationError e) {
LOGGER.error("Failed to initalize ImmediateWindowProvider Service", e);
}
}
if (provider == null)
LOGGER.info("Failed to find ImmediateWindowProvider {}, disabling", providerName);
}
// Only update config if the provider isn't the dummy provider
if (!Objects.equals(provider.name(), "dummyprovider"))
if (provider != null)
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_PROVIDER, provider.name());
else
provider = new DummyProvider();
FMLLoader.progressWindowTick = provider.initialize(arguments);
earlyProgress = StartupNotificationManager.addProgressBar("EARLY", 0);
earlyProgress.label("Bootstrapping Minecraft");
@@ -78,6 +96,7 @@ public class ImmediateWindowHandler {
public static String getGLVersion() {
return provider.getGLVersion();
}
public static void updateProgress(final String message) {
earlyProgress.label(message);
}
@@ -156,4 +175,94 @@ public class ImmediateWindowHandler {
// NOOP
}
}
// We create a wrapper because we want to log errors to the log files, which not all paths of ModLauncher do. Little dirty, but works for now.
private static class Wrapper implements ImmediateWindowProvider {
private final ImmediateWindowProvider delegate;
private Wrapper(ImmediateWindowProvider delegate) {
this.delegate = delegate;
}
public String name() {
try {
return delegate.name();
} catch (Throwable t) {
LOGGER.error("Failed to call provider.name", t);
throw t;
}
}
public Runnable initialize(String[] arguments) {
try {
return delegate.initialize(arguments);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.initialize", t);
throw t;
}
}
public void updateFramebufferSize(IntConsumer width, IntConsumer height) {
try {
delegate.updateFramebufferSize(width, height);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.updateFramebufferSize", t);
throw t;
}
}
public long setupMinecraftWindow(IntSupplier width, IntSupplier height, Supplier<String> title, LongSupplier monitor) {
try {
return delegate.setupMinecraftWindow(width, height, title, monitor);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.setupMinecraftWindow", t);
throw t;
}
}
public boolean positionWindow(Optional<Object> monitor, IntConsumer widthSetter, IntConsumer heightSetter, IntConsumer xSetter, IntConsumer ySetter) {
try {
return delegate.positionWindow(monitor, widthSetter, heightSetter, xSetter, ySetter);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.positionWindow", t);
throw t;
}
}
public <T> Supplier<T> loadingOverlay(Supplier<?> mc, Supplier<?> ri, Consumer<Optional<Throwable>> ex, boolean fade) {
try {
return delegate.loadingOverlay(mc, ri, ex, fade);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.loadingOverlay", t);
throw t;
}
}
public void updateModuleReads(ModuleLayer layer) {
try {
delegate.updateModuleReads(layer);
} catch (Throwable t) {
LOGGER.error("Failed to call provider.updateModuleReads", t);
throw t;
}
}
public void periodicTick() {
try {
delegate.periodicTick();
} catch (Throwable t) {
LOGGER.error("Failed to call provider.periodicTick", t);
throw t;
}
}
public String getGLVersion() {
try {
return delegate.getGLVersion();
} catch (Throwable t) {
LOGGER.error("Failed to call provider.getGLVersion", t);
throw t;
}
}
}
}
@@ -5,12 +5,14 @@
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import org.slf4j.Logger;
import java.net.URL;
import java.nio.file.Files;
@@ -30,6 +32,7 @@ import java.util.stream.Collectors;
*/
public class LoadingModList
{
private static final Logger LOGGER = LogUtils.getLogger();
private static LoadingModList INSTANCE;
private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList;
@@ -78,9 +81,22 @@ public class LoadingModList
public void addAccessTransformers()
{
modFiles.stream()
.map(ModFileInfo::getFile)
.forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod)));
var errors = new ArrayList<EarlyLoadingException.ExceptionData>();
for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile();
for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message);
} else {
FMLLoader.addAccessTransformer(at, mod);
}
}
}
if (!errors.isEmpty()) {
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler)
@@ -28,7 +28,8 @@ public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService
private static final Set<String> SERVICES = Set.of(
"cpw.mods.modlauncher.api.ITransformationService",
"net.minecraftforge.forgespi.locating.IModLocator",
"net.minecraftforge.forgespi.locating.IDependencyLocator"
"net.minecraftforge.forgespi.locating.IDependencyLocator",
"net.minecraftforge.fml.loading.ImmediateWindowProvider"
);
@Override
@@ -34,8 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class RuntimeDistCleaner implements ILaunchPluginService
{
public final class RuntimeDistCleaner implements ILaunchPluginService {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
private static String DIST;
@@ -61,7 +60,7 @@ public class RuntimeDistCleaner implements ILaunchPluginService
{
unpack(classNode.visibleAnnotations).stream()
.filter(ann->Objects.equals(ann.desc, ONLYIN))
.filter(ann->ann.values.indexOf("_interface") != -1)
.filter(ann-> ann.values.contains("_interface"))
.filter(ann->!Objects.equals(((String[])ann.values.get(ann.values.indexOf("value") + 1))[1], DIST))
.map(ann -> ((Type)ann.values.get(ann.values.indexOf("_interface") + 1)).getInternalName())
.forEach(intf -> {
@@ -147,11 +146,11 @@ public class RuntimeDistCleaner implements ILaunchPluginService
return ret;
}
private boolean remove(final List<AnnotationNode> anns, final String side)
private static boolean remove(final List<AnnotationNode> anns, final String side)
{
return unpack(anns).stream().
filter(ann->Objects.equals(ann.desc, ONLYIN)).
filter(ann->ann.values.indexOf("_interface") == -1).
filter(ann-> !ann.values.contains("_interface")).
anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side));
}
@@ -169,9 +168,19 @@ public class RuntimeDistCleaner implements ILaunchPluginService
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
{
return isEmpty ? NAY : YAY;
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraftforge/"))
return NAY;
// No Vanilla classes use @OnlyIn(Dist.SERVER), so we can skip them entirely when we're running on a client
if (FMLEnvironment.dist.isClient() && (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/")))
return NAY;
return YAY;
}
private static class LambdaGatherer extends MethodVisitor {
@@ -18,12 +18,15 @@ import java.util.function.BiPredicate;
public class VersionSupportMatrix {
private static final HashMap<String, List<ArtifactVersion>> overrideVersions = new HashMap<>();
static {
final ArtifactVersion version = new DefaultArtifactVersion(FMLLoader.versionInfo().mcVersion());
if (MavenVersionAdapter.createFromVersionSpec("[1.19.2]").containsVersion(version)) {
// 1.19.2 is Compatible with 1.19.1
add("languageloader.javafml", "42");
add("mod.minecraft", "1.19.1");
add("mod.forge", "42.0.9");
// final ArtifactVersion version = new DefaultArtifactVersion(FMLLoader.versionInfo().mcVersion());
// if (MavenVersionAdapter.createFromVersionSpec("[1.19.2]").containsVersion(version)) {
// // 1.19.2 is Compatible with 1.19.1
// add("languageloader.javafml", "42");
// add("mod.minecraft", "1.19.1");
// add("mod.forge", "42.0.9");
// }
if (FMLLoader.versionInfo().mcVersion().equals("1.20.1")) {
add("mod.forge", "47.1.79");
}
}
private static void add(String key, String value) {
@@ -34,6 +34,11 @@ public abstract class AbstractModProvider implements IModProvider
protected static final String MANIFEST = "META-INF/MANIFEST.MF";
protected IModLocator.ModFileOrException createMod(Path... path) {
return this.createMod(getDefaultJarModType(), path);
}
// FORGE: Backporting artifact, the defaultType must be the first parameter since path is varargs
protected IModLocator.ModFileOrException createMod(String defaultType, Path... path) {
var mjm = new ModJarMetadata();
var sj = SecureJar.from(
Manifest::new,
@@ -45,7 +50,7 @@ public abstract class AbstractModProvider implements IModProvider
IModFile mod;
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
if (type == null) {
type = getDefaultJarModType();
type = defaultType;
}
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
@@ -81,7 +81,14 @@ public class JarInJarDependencyLocator extends AbstractJarFileDependencyLocator
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
final Path pathInFS = zipFS.getPath("/");
return Optional.of(createMod(pathInFS).file());
final IModFile.Type parentType = file.getType();
final String modType;
if (parentType == IModFile.Type.LIBRARY || parentType == IModFile.Type.LANGPROVIDER) {
modType = IModFile.Type.LIBRARY.name();
} else {
modType = IModFile.Type.GAMELIBRARY.name();
}
return Optional.of(createMod(modType, pathInFS).file());
}
catch (Exception e)
{
@@ -12,6 +12,7 @@ import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IModuleLayerManager;
import cpw.mods.modlauncher.util.ServiceLoaderUtils;
import net.minecraftforge.fml.loading.EarlyLoadingException;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.fml.loading.UniqueModListBuilder;
@@ -21,6 +22,7 @@ import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.locating.IDependencyLocator;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.IModLocator;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.util.ArrayList;
@@ -67,6 +69,7 @@ public class ModDiscoverer {
List<EarlyLoadingException.ExceptionData> discoveryErrorData = new ArrayList<>();
boolean successfullyLoadedMods = true;
List<IModFileInfo> brokenFiles = new ArrayList<>();
boolean distIsDedicatedServer = FMLLoader.getDist().isDedicatedServer();
ImmediateWindowHandler.updateProgress("Discovering mod files");
//Loop all mod locators to get the prime mods to load from.
for (IModLocator locator : modLocatorList) {
@@ -85,8 +88,24 @@ public class ModDiscoverer {
if (!badModFiles.isEmpty()) {
LOGGER.error(LogMarkers.SCAN, "Locator {} returned {} files which is are not ModFile instances! They will be skipped!", locator, badModFiles.size());
brokenFiles.addAll(badModFiles.stream().map(IModFile::getModFileInfo).toList());
locatedFiles.removeAll(badModFiles);
}
locatedFiles.removeAll(badModFiles);
if (distIsDedicatedServer) {
var clientOnlyModFiles = locatedFiles.stream()
.filter(file -> {
// some mod files can have null infos, like javafml, mclanguage, lowcode, and fmlcore
@Nullable var info = file.getModFileInfo();
return info != null && (Boolean) info.getFileProperties().getOrDefault(ModFileInfo.CLIENT_SIDE_ONLY_PROP, Boolean.FALSE);
})
.toList();
if (!clientOnlyModFiles.isEmpty()) {
LOGGER.warn(LogMarkers.SCAN, "Locator {} returned {} files which are client-side-only mods, but we're on a dedicated server. They will be skipped!", locator, clientOnlyModFiles.size());
locatedFiles.removeAll(clientOnlyModFiles);
}
}
LOGGER.debug(LogMarkers.SCAN, "Locator {} found {} valid mod files", locator, locatedFiles.size());
handleLocatedFiles(loadedFiles, locatedFiles);
} catch (InvalidModFileException imfe) {
@@ -28,6 +28,8 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Collections;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
@@ -60,6 +62,7 @@ public class ModFile implements IModFile {
private CompletableFuture<ModFileScanData> futureScanResult;
private List<CoreModFile> coreMods;
private Path accessTransformer;
private List<Path> accessTransformers = Collections.emptyList();
static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
private SecureJar.Status securityStatus;
@@ -104,7 +107,11 @@ public class ModFile implements IModFile {
}
public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(Files.exists(accessTransformer) ? accessTransformer : null);
return Optional.ofNullable(accessTransformer);
}
public List<Path> getAccessTransformers() {
return accessTransformers;
}
public boolean identifyMods() {
@@ -113,7 +120,28 @@ public class ModFile implements IModFile {
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
this.coreMods = ModFileParser.getCoreMods(this);
this.coreMods.forEach(mi-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {}", mi.getPath()));
this.accessTransformer = findResource("META-INF", "accesstransformer.cfg");
List<String> cfg;
// Note: Some mods may have invalid tomls copied from other projects.
// Unfortunately we must protect against those landmines.
try {
cfg = this.modFileInfo.getConfig().<List<String>>getConfigElement("accessTransformers").orElse(null);
} catch (Exception e) {
cfg = null;
LOGGER.warn("{} contains an invalid 'accessTransformers' TOML entry. Should be e.g. accessTransformers = [\"META-INF/accesstransformer.cfg\", \"META-INF/extra_at.cfg\"] or accessTransformers = [] for no ATs. Falling back to default.", this.getFileName());
}
if (cfg == null) {
var path = findResource("META-INF", "accesstransformer.cfg");
if (Files.exists(path)) {
this.accessTransformer = path;
this.accessTransformers = List.of(path);
}
} else if (!cfg.isEmpty()) {
var paths = new ArrayList<Path>(cfg.size());
for (var path : cfg) {
paths.add(getSecureJar().getPath(path.replace('\\', '/')));
}
this.accessTransformers = List.copyOf(paths);
}
return true;
}
@@ -29,6 +29,7 @@ import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -50,6 +51,10 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
private final String license;
private final List<String> usesServices;
public static final String CLIENT_SIDE_ONLY_PROP = "__FORGE_clientSideOnly";
private static final Map<String, Object> CLIENT_SIDE_ONLY_MAP = Map.of(CLIENT_SIDE_ONLY_PROP, Boolean.TRUE);
ModFileInfo(final ModFile modFile, final IConfigurable config, Consumer<IModFileInfo> configFileConsumer)
{
this.modFile = modFile;
@@ -68,10 +73,23 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
.orElse("");
this.showAsResourcePack = config.<Boolean>getConfigElement("showAsResourcePack")
.orElse(false);
boolean clientSideOnly = config.<Boolean>getConfigElement("clientSideOnly")
.orElse(false);
this.usesServices = config.<List<String>>getConfigElement("services")
.orElse(List.of());
this.properties = config.<Map<String, Object>>getConfigElement("properties")
.orElse(Collections.emptyMap());
var maybeProps = config.<Map<String, Object>>getConfigElement("properties");
if (clientSideOnly) {
if (maybeProps.isPresent()) {
this.properties = new HashMap<>(maybeProps.get());
this.properties.put(CLIENT_SIDE_ONLY_PROP, Boolean.TRUE);
} else {
this.properties = CLIENT_SIDE_ONLY_MAP;
}
} else {
this.properties = maybeProps.orElse(Collections.emptyMap());
}
this.modFile.setFileProperties(this.properties);
this.issueURL = config.<String>getConfigElement("issueTrackerURL")
.map(StringUtils::toURL)
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.logging.LogUtils;
@@ -13,6 +14,7 @@ import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.ModFileFactory;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.slf4j.Logger;
import java.io.IOException;
@@ -22,7 +24,6 @@ import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ModFileParser {
private static final Logger LOGGER = LogUtils.getLogger();
@@ -41,10 +42,15 @@ public class ModFileParser {
}
final FileConfig fileConfig = FileConfig.builder(modsjson).build();
fileConfig.load();
fileConfig.close();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
try {
fileConfig.load();
fileConfig.close();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
} catch (ParsingException e) {
LOGGER.error("Mod candidate {} contains a corrupt or misconfigured toml.", modFile.getFileName());
throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains a corrupt or misconfigured toml.");
}
}
protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
@@ -80,7 +80,8 @@ public class ModInfo implements IModInfo, IConfigurable
this.displayName = config.<String>getConfigElement("displayName")
.orElse(this.modId);
this.description = config.<String>getConfigElement("description")
.orElse("MISSING DESCRIPTION");
.orElse("MISSING DESCRIPTION")
.replace("\r\n", "\n").stripIndent();
this.logoFile = Optional.ofNullable(config.<String>getConfigElement("logoFile")
.orElseGet(() -> ownFile.flatMap(mf -> mf.<String>getConfigElement("logoFile"))
.orElse(null)));
@@ -205,7 +206,7 @@ public class ModInfo implements IModInfo, IConfigurable
private final boolean mandatory;
private final Ordering ordering;
private final DependencySide side;
private Optional<URL> referralUrl;
private final Optional<URL> referralUrl;
public ModVersion(final IModInfo owner, final IConfigurable config) {
this.owner = owner;
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.SecureJar;
import cpw.mods.modlauncher.api.IModuleLayerManager;
import cpw.mods.modlauncher.api.ITransformationService;
import net.minecraftforge.fml.loading.*;
@@ -26,14 +27,17 @@ public class ModValidator {
private final Map<IModFile.Type, List<ModFile>> modFiles;
private final List<ModFile> candidatePlugins;
private final List<ModFile> candidateMods;
private final List<ModFile> gameLibraries;
private LoadingModList loadingModList;
private List<IModFile> brokenFiles;
private final List<IModFile> brokenFiles;
private final List<EarlyLoadingException.ExceptionData> discoveryErrorData;
public ModValidator(final Map<IModFile.Type, List<ModFile>> modFiles, final List<IModFileInfo> brokenFiles, final List<EarlyLoadingException.ExceptionData> discoveryErrorData) {
this.modFiles = modFiles;
this.candidateMods = lst(modFiles.get(IModFile.Type.MOD));
this.candidateMods.addAll(lst(modFiles.get(IModFile.Type.GAMELIBRARY)));
this.gameLibraries = lst(modFiles.get(IModFile.Type.GAMELIBRARY));
this.candidateMods.addAll(this.gameLibraries);
this.candidatePlugins = lst(modFiles.get(IModFile.Type.LANGPROVIDER));
this.candidatePlugins.addAll(lst(modFiles.get(IModFile.Type.LIBRARY)));
this.discoveryErrorData = discoveryErrorData;
@@ -55,8 +59,7 @@ public class ModValidator {
@NotNull
private List<ModFile> validateFiles(final List<ModFile> mods) {
final List<ModFile> brokenFiles = new ArrayList<>();
for (Iterator<ModFile> iterator = mods.iterator(); iterator.hasNext(); )
{
for (Iterator<ModFile> iterator = mods.iterator(); iterator.hasNext();) {
ModFile modFile = iterator.next();
if (!modFile.getProvider().isValid(modFile) || !modFile.identifyMods()) {
LOGGER.warn(LogMarkers.SCAN, "File {} has been ignored - it is invalid", modFile.getFilePath());
@@ -72,7 +75,26 @@ public class ModValidator {
}
public ITransformationService.Resource getModResources() {
return new ITransformationService.Resource(IModuleLayerManager.Layer.GAME, this.candidateMods.stream().map(IModFile::getSecureJar).toList());
var mods = new ArrayList<SecureJar>();
// Add only the valid mods that we will be attempting to load.
// If any detectable error happens during the sorting process {missing deps, duplicates,
// This helps prevent coremods/mixins from screwing up us displaying the error screens that the sorting/validation is trying to display.
// This won't fix them all as they are still loaded and will still apply but it might help
for (var info : this.loadingModList.getModFiles())
mods.add(info.getFile().getSecureJar());
// Add any game libraries, this *may* be duplicates, depending on the state of the sorting. But until I get around to re-writing
// that clusterfuck of a system, have this simple de-duplication. Order of resource is important, but i'm unsure if duplication is
// so might as well waste a few cycles on checking. Still faster then converting from a set to a list.
// Ideally we would explicitly list out which mods to load {forge and MC being the only ones} but some coremods could require extra things.
// So try game libraries as well
for (var lib : this.gameLibraries) {
var jar = lib.getSecureJar();
if (!mods.contains(jar))
mods.add(jar);
}
return new ITransformationService.Resource(IModuleLayerManager.Layer.GAME, mods);
}
private List<EarlyLoadingException.ExceptionData> validateLanguages() {
@@ -45,7 +45,7 @@ public class Scanner {
try (InputStream in = Files.newInputStream(path)){
ModClassVisitor mcv = new ModClassVisitor();
ClassReader cr = new ClassReader(in);
cr.accept(mcv, 0);
cr.accept(mcv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
mcv.buildData(result.getClasses(), result.getAnnotations());
} catch (IOException | IllegalArgumentException e) {
// mark path bad
@@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
public final class ProgressMeter {
private final String name;
private final int steps;
private AtomicInteger current;
private final AtomicInteger current;
private Message label;
public ProgressMeter(String name, int steps, int current, Message label) {
+1
View File
@@ -1,4 +1,5 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+6 -5
View File
@@ -85,9 +85,6 @@ done
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# 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"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -144,7 +141,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=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -152,7 +149,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=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -197,6 +194,10 @@ if "$cygwin" || "$msys" ; then
done
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
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
public class FMLJavaModLoadingContext
public class FMLJavaModLoadingContext extends ModLoadingContext
{
private final FMLModContainer container;
@@ -24,11 +24,18 @@ public class FMLJavaModLoadingContext
return container.getEventBus();
}
@Override
public FMLModContainer getContainer() {
return container;
}
/**
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
* @return The FMLJavaMod language specific extension from the ModLoadingContext
*
* @deprecated use {@link FMLJavaModLoadingContext} in your mod constructor
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static FMLJavaModLoadingContext get() {
return ModLoadingContext.get().extension();
}
@@ -21,6 +21,9 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Optional;
public class FMLModContainer extends ModContainer
@@ -31,6 +34,7 @@ public class FMLModContainer extends ModContainer
private final IEventBus eventBus;
private Object modInstance;
private final Class<?> modClass;
private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this);
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer)
{
@@ -40,8 +44,7 @@ public class FMLModContainer extends ModContainer
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this);
this.contextExtension = () -> contextExtension;
this.contextExtension = () -> context;
try
{
var layer = gameLayer.findModule(info.getOwningFile().moduleName()).orElseThrow();
@@ -65,11 +68,22 @@ public class FMLModContainer extends ModContainer
try
{
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
this.modInstance = modClass.getDeclaredConstructor().newInstance();
Constructor<?> constructor;
try {
constructor = modClass.getDeclaredConstructor(context.getClass());
} catch (NoSuchMethodException | SecurityException exception) {
constructor = modClass.getDeclaredConstructor();
}
this.modInstance = constructor.getParameterCount() == 0 ? constructor.newInstance() : constructor.newInstance(context);
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
}
catch (Throwable e)
{
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
// actual exception from the mod loading error screen.
if (e instanceof InvocationTargetException wrapped)
e = Objects.requireNonNullElse(wrapped.getCause(), e); // unwrap the exception
LOGGER.error(LOADING,"Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.getName(), e);
throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass);
}
+7 -7
View File
@@ -16,19 +16,19 @@ Step 1: Open your command-line and browse to the folder where you extracted the
Step 2: You're left with a choice.
If you prefer to use Eclipse:
1. Run the following command: `gradlew genEclipseRuns` (`./gradlew genEclipseRuns` if you are on Mac/Linux)
1. Run the following command: `./gradlew genEclipseRuns`
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
or run `gradlew eclipse` to generate the project.
If you prefer to use IntelliJ:
1. Open IDEA, and import project.
2. Select your build.gradle file and have it import.
3. Run the following command: `gradlew genIntellijRuns` (`./gradlew genIntellijRuns` if you are on Mac/Linux)
3. Run the following command: `./gradlew genIntellijRuns`
4. Refresh the Gradle Project in IDEA if required.
If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
{this does not affect your code} and then start the process again.
(this does not affect your code) and then start the process again.
Mapping Names:
=============================
@@ -40,7 +40,7 @@ https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
Additional Resources:
=========================
Community Documentation: https://mcforge.readthedocs.io/en/latest/gettingstarted/
LexManos' Install Video: https://www.youtube.com/watch?v=8VEdtQLuLO0
Forge Forum: https://forums.minecraftforge.net/
Forge Discord: https://discord.gg/UvedJ9m
Community Documentation: https://docs.minecraftforge.net/en/1.20.1/gettingstarted/
LexManos' Install Video: https://youtu.be/8VEdtQLuLO0
Forge Forums: https://forums.minecraftforge.net/
Forge Discord: https://discord.minecraftforge.net/
+93 -132
View File
@@ -1,156 +1,87 @@
// Don't see a feature you're wanting to use?
// See our MDKExamples repository for minimal examples for features like JarInJar
// https://github.com/MinecraftForge/MDKExamples
plugins {
id 'eclipse'
id 'idea'
id 'java'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0,6.2)'
id 'net.minecraftforge.gradle' version '[7.0,8)'
id 'net.minecraftforge.renamer' version '1.1.8+' // Required on all versions which use SRG maps at runtime.
}
version = mod_version
group = mod_group_id
base {
archivesName = mod_id
}
version = '1.0'
group = 'com.example'
base.archivesName = 'examplemod'
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
println "Java: ${providers.systemProperty('java.version').get()}, " +
"JVM: ${providers.systemProperty('java.vm.version').get()} (${providers.systemProperty('java.vendor').get()}), " +
"Arch: ${providers.systemProperty('os.arch').get()}"
minecraft {
// The mappings can be changed at any time and must be in the following format.
// Channel: Version:
// official MCVersion Official field/method names from Mojang mapping files
// parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official
//
// You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started
//
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version
// Declare which mappings to use
mappings channel: mapping_channel, version: minecraft_version
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
// In most cases, it is not necessary to enable.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// Access Transformer files may now be automatically detected, or explicitly declared.
// Setting the below flag will cause ForgeGradle to look for META-INF/accesstransformer.cfg
// Alternatively, provide it a file(<path>) or files(<paths>) for explicitly declared files. If you use any
// explicitly declared access transformers, all transformers must be also declared in the mods.toml
// accessTransformer = true
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game.
// It is REQUIRED to be set to true for this template to function.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// When true, this property will add the folder name of all declared run configurations to generated IDE run configurations.
// The folder name can be set on a run configuration using the "folderName" property.
// By default, the folder name of a run configuration is the name of the Gradle project containing it.
// generateRunFolders = true
// This property enables access transformers for use in development.
// They will be applied to the Minecraft artifact.
// The access transformer file can be anywhere in the project.
// However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge.
// This default location is a best practice to automatically put the file in the right place in the final jar.
// See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
// applies to all the run configs below
configureEach {
workingDirectory project.file('run')
workingDir.convention layout.projectDirectory.dir('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
//systemProperty 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
"${mod_id}" {
source sourceSets.main
}
}
//args "-mixin.config=${mod_id}.mixins.json"
}
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
register('client') {
systemProperty 'forge.enabledGameTestNamespaces', mod_id
}
server {
property 'forge.enabledGameTestNamespaces', mod_id
register('server') {
systemProperty 'forge.enabledGameTestNamespaces', mod_id
args '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
property 'forge.enabledGameTestNamespaces', mod_id
register('gameTestServer') {
systemProperty 'forge.enabledGameTestNamespaces', mod_id
}
data {
// example of overriding the workingDirectory set in configureEach above
workingDirectory project.file('run-data')
register('data') {
workingDir = layout.projectDirectory.dir('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
args '--mod', mod_id, '--all', '--output', layout.projectDirectory.dir('src/generated/resources'), '--existing', layout.projectDirectory.dir('src/main/resources')
}
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories {
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
minecraft.mavenizer(it)
maven fg.forgeMaven
maven fg.minecraftLibsMaven
// Needed for JEI
// maven { url = 'https://maven.blamejared.com/' }
}
dependencies {
// Specify the version of Minecraft to use.
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact.
// The "userdev" classifier will be requested and setup by ForgeGradle.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
// Minecraft/Forge itself
implementation minecraft.dependency("net.minecraftforge:forge:$minecraft_version-$forge_version")
// A 3rd party mod, which needs to be deobfuscated from SRG names to the mappings we're using
// implementation renamer.dependency('mezz.jei:jei-1.20.1-forge:15.20.0.129')
// annotationProcessor 'org.spongepowered:mixin:0.8.7:processor'
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.named('processResources', ProcessResources).configure {
tasks.named('processResources', ProcessResources) {
var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range,
@@ -158,15 +89,15 @@ tasks.named('processResources', ProcessResources).configure {
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
inputs.property('replaceProperties', replaceProperties)
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
expand replaceProperties
}
}
// Example for how to get properties into the manifest for reading at runtime.
tasks.named('jar', Jar).configure {
tasks.named('jar', Jar) {
manifest {
attributes([
'Specification-Title' : mod_id,
@@ -174,34 +105,64 @@ tasks.named('jar', Jar).configure {
'Specification-Version' : '1', // We are version 1 of ourselves
'Implementation-Title' : project.name,
'Implementation-Version' : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors,
'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
'Implementation-Vendor' : mod_authors
])
//attributes['MixinConfigs'] = "${mod_id}.mixins.json"
}
// This is the preferred method to reobfuscate your jar file
finalizedBy 'reobfJar'
// This artifact will not be renamed. While this will not launch in production
// the artifact may be helpful for other developers if your mod is used as a library.
// By assigning this archive classifier, jar file name will end in '-unobfuscated'
// e.g. 'examplemod-1.0-unobfuscated.jar'
archiveClassifier = 'unobfuscated'
}
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing:
// tasks.named('publish').configure {
// dependsOn 'reobfJar'
// }
// Set the default mappings file to our default minecraft dependency
// This must be done after `minecraft.dependency('coords')` has been done so that gradle knows what dependency we want
// This mapping will be used by default for all renamer tasks, including deobfuscating dependencies
// You can still override each specific task, this is just to save repeating yourself in your buildscript.
renamer.mappings.from minecraft.dependency.toSrgFile
// If you are choosing to use mixins, you must give Renamer the additional information for it to handle the refmaps.
//renamer.enableMixinRefmaps {
// config "${mod_id}.mixins.json"
// refMap "${mod_id}.refmap.json"
//}
// Creates a task named 'renameJar'
renamer.classes(tasks.named('jar', Jar)) {
// This artifact will be remapped according to the provided mappings file
// Setting the classifier to '' will attach no extra details to the file name.
// e.g. 'examplemod-1.0.jar'
archiveClassifier = ''
// Unless set globally like above, You need to point to the mappings you wish to apply, typically this is
// the Mapped names to SRG for older versions.
// ForgeGradle/Mavenizer generate these files for the dependencies you declare. So you can use the helper.
// Or you can specify the file or dependency if you host them yourself.
// map.from minecraft.dependency.toSrgFile
// The mixin AP does not include all annotated entries, instead containing some in the augmented mappings.
// So, if you are using mixins or have dependencies which use them, uncomment the below line to tell renamer
// that the generated mappings are available. See the MDKExample for more details.
// mappings renamer.mixin.generatedMappings
}
// Example configuration to allow publishing using the maven-publish plugin
// We recommend publishing all of your artifacts to publicly accessible maven so that others can easily consume them as dependencies
publishing {
publications {
register('mavenJava', MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file://${project.projectDir}/mcmodsrepo"
}
// Publishing to a local folder makes it easy to see exactly what you would publish to a real server
maven { url = layout.projectDirectory.dir('repo').asFile.toURI() }
}
publications.register('mavenJava', MavenPublication) {
from components.java // Publish the normal jar
artifact renameJar // Publish the renamed jar in addition
}
}
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 IntelliJ to do it.
idea.module { downloadJavadoc = downloadSources = true }
+16 -13
View File
@@ -1,25 +1,29 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.configuration-cache=true
org.gradle.configuration-cache.parallel=true
org.gradle.configuration-cache.problems=warn
net.minecraftforge.gradle.merge-source-sets=true
## Environment Properties
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=@MC_VERSION@
minecraft_version=1.20.1
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[@MC_VERSION@,@MC_NEXT_VERSION@)
minecraft_version_range=[1.20.1, 1.20.2)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=@FORGE_VERSION@
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[@FORGE_SPEC_VERSION@,)
forge_version_range=[47,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[@FORGE_SPEC_VERSION@,)
loader_version_range=[47,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# The default set of supported mapping channels are ["official", "parchment"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
@@ -31,12 +35,11 @@ loader_version_range=[@FORGE_SPEC_VERSION@,)
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=@MAPPING_CHANNEL@
# Unlike in FG6, Parchment no longer requires the Librarian plugin to be set up.
mapping_channel=official
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=@MAPPING_VERSION@
mapping_version=1.20.1
## Mod Properties
+3 -11
View File
@@ -1,13 +1,5 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0'
}
rootProject.name = 'examplemod'
@@ -18,7 +18,6 @@ import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
@@ -61,9 +60,9 @@ public class ExampleMod
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());
public ExampleMod()
public ExampleMod(FMLJavaModLoadingContext context)
{
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus modEventBus = context.getModEventBus();
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
@@ -82,7 +81,7 @@ public class ExampleMod
modEventBus.addListener(this::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);
context.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
}
private void commonSetup(final FMLCommonSetupEvent event)
+11 -2
View File
@@ -12,6 +12,9 @@ loaderVersion="${loader_version_range}" #mandatory This is typically bumped ever
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or Open to LAN),
# set this to true, and Forge will set the correct displayTest for you and skip loading your mod on dedicated servers.
#clientSideOnly=true #optional - defaults to false if absent
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
@@ -36,7 +39,13 @@ authors="${mod_authors}" #optional
# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component.
# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value.
# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself.
#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional)
#displayTest="MATCH_VERSION" # if nothing is specified, MATCH_VERSION is the default when clientSideOnly=false, otherwise IGNORE_ALL_VERSION when clientSideOnly=true (#optional)
# Access Transformers
# Optional, if not specified Forge will attempt to find the default META-INF/accesstransformer.cfg and silently continue if not found. May default to an empty list in a future MC.
# If you specify AT path strings in this list, Forge will attempt to load each of them and throw errors for any that aren't found.
# Specifying an empty list when your mod has no ATs is recommended to opt-out of the default for slightly better loading performance.
#accessTransformers = []
# The description text for the mod (multi line!) (#mandatory)
description='''${mod_description}'''
@@ -67,4 +76,4 @@ description='''${mod_description}'''
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"
#openGLVersion="[3.2,)"
@@ -0,0 +1,11 @@
--- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
+++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
@@ -46,7 +_,7 @@
public void m_5752_() {
Vector3f vector3f = this.f_85869_.transform(new Vector3f(this.f_85876_, this.f_85877_, this.f_85878_));
- Direction direction = Direction.m_122372_(vector3f.x(), vector3f.y(), vector3f.z());
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
Vector4f vector4f = this.f_85868_.transform(new Vector4f(this.f_85870_, this.f_85871_, this.f_85872_, 1.0F));
vector4f.rotateY((float)Math.PI);
vector4f.rotateX((-(float)Math.PI / 2F));
@@ -1,6 +1,6 @@
--- a/net/minecraft/CrashReport.java
+++ b/net/minecraft/CrashReport.java
@@ -57,14 +_,8 @@
@@ -57,14 +_,9 @@
if (this.f_127506_ != null && this.f_127506_.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
@@ -12,6 +12,7 @@
- }
-
- p_127520_.append("\n");
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.f_127501_, this.f_127506_));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.f_127506_));
}
@@ -12,6 +12,15 @@
private static final Set<String> f_90811_ = Sets.newHashSet();
public static final String f_167805_ = "key.categories.movement";
public static final String f_167806_ = "key.categories.misc";
@@ -41,7 +_,7 @@
private int f_90818_;
public static void m_90835_(InputConstants.Key p_90836_) {
- KeyMapping keymapping = f_90810_.get(p_90836_);
+ for (KeyMapping keymapping : f_90810_.getAll(p_90836_))
if (keymapping != null) {
++keymapping.f_90818_;
}
@@ -49,7 +_,7 @@
}
@@ -81,12 +90,12 @@
}
public String m_90865_() {
@@ -184,4 +_,84 @@
@@ -183,5 +_,88 @@
public void m_7249_(boolean p_90846_) {
this.f_90817_ = p_90846_;
}
+ }
+
+ /****************** Forge Start *****************************/
+ private net.minecraftforge.client.settings.KeyModifier keyModifierDefault = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.KeyModifier keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ private net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext = net.minecraftforge.client.settings.KeyConflictContext.UNIVERSAL;
@@ -156,13 +165,17 @@
+ }
+
+ @Override
+ public void setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ this.f_90816_ = keyCode;
+ if (keyModifier.matches(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ public void setKeyModifierAndCode(@org.jetbrains.annotations.Nullable net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode) {
+ f_90810_.remove(this);
+
+ if (keyModifier == null)
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.getModifier(this.f_90816_);
+ if (keyModifier == null || keyCode == InputConstants.f_84822_ || net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(keyCode))
+ keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+
+ this.f_90816_ = keyCode;
+ this.keyModifier = keyModifier;
+
+ f_90810_.put(keyCode, this);
+ }
+ /****************** Forge End *****************************/
}
}
@@ -1,25 +1,5 @@
--- a/net/minecraft/client/KeyboardHandler.java
+++ b/net/minecraft/client/KeyboardHandler.java
@@ -329,7 +_,9 @@
}
}
- if (p_90897_ == 1 && (!(this.f_90867_.f_91080_ instanceof KeyBindsScreen) || ((KeyBindsScreen)screen).f_193976_ <= Util.m_137550_() - 20L)) {
+
+ if ((!(this.f_90867_.f_91080_ instanceof KeyBindsScreen) || ((KeyBindsScreen)screen).f_193976_ <= Util.m_137550_() - 20L)) {
+ if (p_90897_ == 1) {
if (this.f_90867_.f_91066_.f_92105_.m_90832_(p_90895_, p_90896_)) {
this.f_90867_.m_91268_().m_85438_();
this.f_90867_.f_91066_.m_231829_().m_231514_(this.f_90867_.m_91268_().m_85440_());
@@ -347,6 +_,8 @@
});
return;
}
+ } else if (p_90897_ == 0 /*GLFW_RELEASE*/ && this.f_90867_.f_91080_ instanceof KeyBindsScreen)
+ ((KeyBindsScreen)this.f_90867_.f_91080_).f_193975_ = null; //Forge: Unset pure modifiers.
}
if (this.f_90867_.m_240477_().m_93316_()) {
@@ -369,11 +_,15 @@
Screen.m_96579_(() -> {
if (p_90897_ != 1 && p_90897_ != 2) {
@@ -120,7 +120,7 @@
StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (m_193589_().m_184597_()) {
- stringbuilder.append("*");
+ stringbuilder.append(' ').append(net.minecraftforge.forge.snapshots.ForgeSnapshotsMod.BRANDING_NAME).append('*');
+ stringbuilder.append("* ").append(net.minecraftforge.forge.snapshots.ForgeSnapshotsMod.BRANDING_NAME);
}
stringbuilder.append(" ");
@@ -17,8 +17,14 @@
TextureAtlasSprite textureatlassprite = mobeffecttexturemanager.m_118732_(mobeffect);
int i1 = j;
float f1 = f;
@@ -574,12 +_,13 @@
@@ -572,16 +_,21 @@
}
public void m_280295_(GuiGraphics p_283501_) {
+ renderSelectedItemName(p_283501_, 0);
+ }
+
+ public void renderSelectedItemName(GuiGraphics p_283501_, int yShift) {
this.f_92986_.m_91307_().m_6180_("selectedItemName");
if (this.f_92993_ > 0 && !this.f_92994_.m_41619_()) {
- MutableComponent mutablecomponent = Component.m_237119_().m_7220_(this.f_92994_.m_41786_()).m_130940_(this.f_92994_.m_41791_().f_43022_);
@@ -31,8 +37,11 @@
+ Component highlightTip = this.f_92994_.getHighlightTip(mutablecomponent);
+ int i = this.m_93082_().m_92852_(highlightTip);
int j = (this.f_92977_ - i) / 2;
int k = this.f_92978_ - 59;
- int k = this.f_92978_ - 59;
+ int k = this.f_92978_ - Math.max(yShift, 59);
if (!this.f_92986_.f_91072_.m_105205_()) {
k += 14;
}
@@ -593,7 +_,13 @@
if (l > 0) {
@@ -33,6 +33,26 @@
int i = p_282636_.m_272191_(p_281596_, (float)p_281586_, (float)p_282816_, p_281743_, p_282394_, this.f_279612_.m_85850_().m_252922_(), this.f_279627_, Font.DisplayMode.NORMAL, 0, 15728880);
this.m_286081_();
return i;
@@ -405,6 +_,10 @@
}
public void m_280543_(ResourceLocation p_283059_, int p_283575_, int p_283192_, int p_281790_, int p_283642_, int p_282691_, int p_281912_, int p_281728_, int p_282324_) {
+ blitRepeating(p_283059_, p_283575_, p_283192_, p_281790_, p_283642_, p_282691_, p_281912_, p_281728_, p_282324_, 256, 256);
+ }
+
+ public void blitRepeating(ResourceLocation p_283059_, int p_283575_, int p_283192_, int p_281790_, int p_283642_, int p_282691_, int p_281912_, int p_281728_, int p_282324_, int textureWidth, int textureHeight) {
int i = p_283575_;
int j;
@@ -417,7 +_,7 @@
for(IntIterator intiterator1 = m_280358_(p_283642_, p_282324_); intiterator1.hasNext(); l += i1) {
i1 = intiterator1.nextInt();
int j1 = (p_282324_ - i1) / 2;
- this.m_280218_(p_283059_, i, l, p_282691_ + k, p_281912_ + j1, j, i1);
+ this.m_280163_(p_283059_, i, l, p_282691_ + k, p_281912_ + j1, j, i1, textureWidth, textureHeight);
}
}
@@ -477,6 +_,7 @@
crashreportcategory.m_128165_("Item Type", () -> {
return String.valueOf((Object)p_281675_.m_41720_());
@@ -72,7 +92,7 @@
this.m_280497_(p_283128_, list, p_283678_, p_281696_, DefaultTooltipPositioner.f_262752_);
}
@@ -544,7 +_,15 @@
@@ -544,7 +_,22 @@
}
public void m_280666_(Font p_282739_, List<Component> p_281832_, int p_282191_, int p_282446_) {
@@ -85,6 +105,13 @@
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, m_280182_(), m_280206_(), font);
+ this.m_280497_(font, components, mouseX, mouseY, DefaultTooltipPositioner.f_262752_);
+ this.tooltipStack = ItemStack.f_41583_;
+ }
+
+ public void renderComponentTooltipFromElements(Font font, List<com.mojang.datafixers.util.Either<FormattedText, TooltipComponent>> elements, int mouseX, int mouseY, ItemStack stack) {
+ this.tooltipStack = stack;
+ List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponentsFromElements(stack, elements, mouseX, m_280182_(), m_280206_(), font);
+ this.m_280497_(font, components, mouseX, mouseY, DefaultTooltipPositioner.f_262752_);
+ this.tooltipStack = ItemStack.f_41583_;
}
@@ -0,0 +1,10 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -82,6 +_,7 @@
} else {
gridlayout$rowhelper.m_264139_(this.m_262456_(f_262254_, SocialInteractionsScreen::new));
}
+ gridlayout$rowhelper.m_264108_(Button.m_253074_(Component.m_237115_("fml.menu.mods"), button -> this.f_96541_.m_91152_(new net.minecraftforge.client.gui.ModListScreen(this))).m_252780_(f_262268_).m_253136_(), 2);
Component component = this.f_96541_.m_91090_() ? f_262217_ : f_262246_;
this.f_252482_ = gridlayout$rowhelper.m_264108_(Button.m_253074_(component, (p_280815_) -> {
@@ -34,7 +34,7 @@
this.f_97334_.m_104401_(advancementtab.m_97182_(), true);
break;
}
@@ -98,6 +_,11 @@
@@ -98,9 +_,15 @@
int i = (this.f_96543_ - 252) / 2;
int j = (this.f_96544_ - 140) / 2;
this.m_280273_(p_282589_);
@@ -46,6 +46,10 @@
this.m_97373_(p_282589_, p_282255_, p_283354_, i, j);
this.m_280088_(p_282589_, i, j);
this.m_280355_(p_282589_, p_282255_, p_283354_, i, j);
+ super.m_88315_(p_282589_, p_282255_, p_283354_, p_283123_);
}
public boolean m_7979_(double p_97347_, double p_97348_, int p_97349_, double p_97350_, double p_97351_) {
@@ -135,10 +_,12 @@
p_283395_.m_280218_(f_97329_, p_281890_, p_282532_, 0, 0, 252, 140);
if (this.f_97335_.size() > 1) {
@@ -9,9 +9,11 @@
}
public int m_5759_() {
@@ -129,10 +_,11 @@
@@ -128,11 +_,13 @@
this.f_193911_ = p_193917_;
this.f_193912_ = Button.m_253074_(p_193917_, (p_269618_) -> {
KeyBindsList.this.f_193858_.f_193975_ = p_193916_;
+ p_193916_.setKeyModifierAndCode(null, com.mojang.blaze3d.platform.InputConstants.f_84822_);
KeyBindsList.this.m_269130_();
- }).m_252987_(0, 0, 75, 20).m_252778_((p_253311_) -> {
+ }).m_252987_(0, 0, 75 + 20 /* Forge: Add space */, 20).m_252778_((p_253311_) -> {
@@ -13,14 +13,34 @@
public boolean m_7933_(int p_193987_, int p_193988_, int p_193989_) {
if (this.f_193975_ != null) {
if (p_193987_ == 256) {
+ this.f_193975_.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.getActiveModifier(), InputConstants.f_84822_);
+ this.f_193975_.setKeyModifierAndCode(null, InputConstants.f_84822_);
this.f_96282_.m_92159_(this.f_193975_, InputConstants.f_84822_);
} else {
+ this.f_193975_.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.getActiveModifier(), InputConstants.m_84827_(p_193987_, p_193988_));
+ this.f_193975_.setKeyModifierAndCode(null, InputConstants.m_84827_(p_193987_, p_193988_));
this.f_96282_.m_92159_(this.f_193975_, InputConstants.m_84827_(p_193987_, p_193988_));
}
+ if(!net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.f_193975_.getKey()))
+ if (p_193987_ == 256 || !net.minecraftforge.client.settings.KeyModifier.isKeyCodeModifier(this.f_193975_.getKey()))
this.f_193975_ = null;
this.f_193976_ = Util.m_137550_();
this.f_193977_.m_269130_();
@@ -67,6 +_,19 @@
} else {
return super.m_7933_(p_193987_, p_193988_, p_193989_);
}
+ }
+
+ @Override
+ public boolean m_7920_(int keyCode, int scanCode, int modifiers) {
+ // Forge: We wait for a second key above if the first press is a modifier
+ // but if they release the modifier then set it explicitly.
+ var key = InputConstants.m_84827_(keyCode, scanCode);
+ if (this.f_193975_ != null && this.f_193975_.getKey() == key) {
+ this.f_193975_ = null;
+ this.f_193976_ = Util.m_137550_();
+ this.f_193977_.m_269130_();
+ }
+ return super.m_7920_(keyCode, scanCode, modifiers);
}
public void m_88315_(GuiGraphics p_282556_, int p_193992_, int p_193993_, float p_193994_) {
@@ -187,7 +187,7 @@
list1.add(i++, creativemodetab.m_40786_().m_6881_().m_130940_(ChatFormatting.BLUE));
}
}
@@ -639,13 +_,13 @@
@@ -639,21 +_,22 @@
}
protected void m_7286_(GuiGraphics p_282663_, float p_282504_, int p_282089_, int p_282249_) {
@@ -203,8 +203,10 @@
this.f_98510_.m_88315_(p_282663_, p_282089_, p_282249_, p_282504_);
int j = this.f_97735_ + 175;
int k = this.f_97736_ + 18;
@@ -654,6 +_,7 @@
p_282663_.m_280218_(f_98504_, j, k + (int)((float)(i - k - 17) * this.f_98508_), 232 + (this.m_98631_() ? 0 : 12), 0, 12, 15);
int i = k + 112;
if (f_98507_.m_40791_()) {
- p_282663_.m_280218_(f_98504_, j, k + (int)((float)(i - k - 17) * this.f_98508_), 232 + (this.m_98631_() ? 0 : 12), 0, 12, 15);
+ p_282663_.m_280218_(f_98507_.getTabsImage(), j, k + (int)((float)(i - k - 17) * this.f_98508_), 232 + (this.m_98631_() ? 0 : 12), 0, 12, 15);
}
+ if (currentPage.getVisibleTabs().contains(f_98507_)) //Forge: only display tab selection when the selected tab is on the current page
@@ -240,14 +242,16 @@
int j = i * 26;
int k = 0;
int l = this.f_97735_ + this.m_258094_(p_283489_);
@@ -720,6 +_,7 @@
@@ -720,7 +_,8 @@
i1 += this.f_97727_ - 4;
}
- p_283590_.m_280218_(f_98504_, l, i1, j, k, 26, 32);
+ com.mojang.blaze3d.systems.RenderSystem.enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border.
p_283590_.m_280218_(f_98504_, l, i1, j, k, 26, 32);
+ p_283590_.m_280218_(p_283489_.getTabsImage(), l, i1, j, k, 26, 32);
p_283590_.m_280168_().m_85836_();
p_283590_.m_280168_().m_252880_(0.0F, 0.0F, 100.0F);
l += 5;
@@ -763,6 +_,14 @@
}
@@ -23,7 +23,7 @@
BlockState blockstate = this.f_105189_.f_91073_.m_8055_(p_105270_);
this.f_105189_.m_91301_().m_120581_(this.f_105189_.f_91073_, p_105270_, blockstate, 1.0F);
this.m_233729_(this.f_105189_.f_91073_, (p_233757_) -> {
+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105270_, p_105271_).isCanceled())
+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled())
this.m_105267_(p_105270_);
return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105270_, p_105271_, p_233757_);
});
@@ -31,7 +31,7 @@
if (this.f_105196_) {
this.f_105190_.m_104955_(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, this.f_105191_, p_105271_));
}
+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105270_, p_105271_);
+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105270_, p_105271_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK);
BlockState blockstate1 = this.f_105189_.f_91073_.m_8055_(p_105270_);
this.f_105189_.m_91301_().m_120581_(this.f_105189_.f_91073_, p_105270_, blockstate1, 0.0F);
@@ -60,7 +60,7 @@
BlockState blockstate1 = this.f_105189_.f_91073_.m_8055_(p_105284_);
this.f_105189_.m_91301_().m_120581_(this.f_105189_.f_91073_, p_105284_, blockstate1, 1.0F);
this.m_233729_(this.f_105189_.f_91073_, (p_233753_) -> {
+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105284_, p_105285_).isCanceled())
+ if (!net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105284_, p_105285_, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK).isCanceled())
this.m_105267_(p_105284_);
return new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, p_105284_, p_105285_, p_233753_);
});
@@ -75,7 +75,7 @@
++this.f_105194_;
this.f_105189_.m_91301_().m_120581_(this.f_105189_.f_91073_, p_105284_, blockstate, Mth.m_14036_(this.f_105193_, 0.0F, 1.0F));
+ if (net.minecraftforge.common.ForgeHooks.onLeftClickBlock(this.f_105189_.f_91074_, p_105284_, p_105285_).getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return true;
+ if (net.minecraftforge.common.ForgeHooks.onClientMineHold(this.f_105189_.f_91074_, p_105284_, p_105285_).getUseItem() == net.minecraftforge.eventbus.api.Event.Result.DENY) return true;
if (this.f_105193_ >= 1.0F) {
this.f_105196_ = false;
this.m_233729_(this.f_105189_.f_91073_, (p_233739_) -> {
@@ -88,12 +88,15 @@
}
public void m_105287_() {
@@ -262,7 +_,7 @@
@@ -262,7 +_,10 @@
private boolean m_105281_(BlockPos p_105282_) {
ItemStack itemstack = this.f_105189_.f_91074_.m_21205_();
- return p_105282_.equals(this.f_105191_) && ItemStack.m_150942_(itemstack, this.f_105192_);
+ return p_105282_.equals(this.f_105191_) && ItemStack.m_150942_(itemstack, this.f_105192_) && !f_105192_.shouldCauseBlockBreakReset(itemstack);
+ // FORGE: Remove this method call, but keep the bytecode intact for hacks that target it
+ if (Boolean.FALSE)
+ ItemStack.m_150942_(itemstack, this.f_105192_);
+ return p_105282_.equals(this.f_105191_) && !f_105192_.shouldCauseBlockBreakReset(itemstack);
}
private void m_105297_() {
@@ -0,0 +1,31 @@
--- a/net/minecraft/client/particle/FireworkParticles.java
+++ b/net/minecraft/client/particle/FireworkParticles.java
@@ -172,7 +_,7 @@
} else {
for(int i = 0; i < this.f_106752_.size(); ++i) {
CompoundTag compoundtag = this.f_106752_.m_128728_(i);
- if (FireworkRocketItem.Shape.m_41237_(compoundtag.m_128445_("Type")) == FireworkRocketItem.Shape.LARGE_BALL) {
+ if (FireworkRocketItem.Shape.getShape(compoundtag) == FireworkRocketItem.Shape.LARGE_BALL) {
flag1 = true;
break;
}
@@ -192,7 +_,7 @@
if (this.f_106754_ % 2 == 0 && this.f_106752_ != null && this.f_106754_ / 2 < this.f_106752_.size()) {
int k = this.f_106754_ / 2;
CompoundTag compoundtag1 = this.f_106752_.m_128728_(k);
- FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.m_41237_(compoundtag1.m_128445_("Type"));
+ FireworkRocketItem.Shape fireworkrocketitem$shape = FireworkRocketItem.Shape.getShape(compoundtag1);
boolean flag4 = compoundtag1.m_128471_("Trail");
boolean flag2 = compoundtag1.m_128471_("Flicker");
int[] aint = compoundtag1.m_128465_("Colors");
@@ -201,6 +_,10 @@
aint = new int[]{DyeColor.BLACK.m_41070_()};
}
+ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(fireworkrocketitem$shape);
+ if (factory != null)
+ factory.build(this, flag4, flag2, aint, aint1);
+ else
switch (fireworkrocketitem$shape) {
case SMALL_BALL:
default:
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/particle/Particle.java
+++ b/net/minecraft/client/particle/Particle.java
@@ -226,4 +_,12 @@
@@ -226,4 +_,16 @@
public Optional<ParticleGroup> m_142654_() {
return Optional.empty();
}
@@ -11,5 +11,9 @@
+ */
+ public boolean shouldCull() {
+ return true;
+ }
+
+ public net.minecraft.world.phys.Vec3 getPos() {
+ return new net.minecraft.world.phys.Vec3(this.f_107212_, this.f_107213_, this.f_107214_);
+ }
}
@@ -1,5 +1,14 @@
--- a/net/minecraft/client/particle/TerrainParticle.java
+++ b/net/minecraft/client/particle/TerrainParticle.java
@@ -28,7 +_,7 @@
this.f_107227_ = 0.6F;
this.f_107228_ = 0.6F;
this.f_107229_ = 0.6F;
- if (!p_172458_.m_60713_(Blocks.f_50440_)) {
+ if (net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_172458_).areBreakingParticlesTinted(p_172458_, p_172451_, p_172459_)) {
int i = Minecraft.m_91087_().m_91298_().m_92577_(p_172458_, p_172451_, p_172459_, 0);
this.f_107227_ *= (float)(i >> 16 & 255) / 255.0F;
this.f_107228_ *= (float)(i >> 8 & 255) / 255.0F;
@@ -69,7 +_,13 @@
public static class Provider implements ParticleProvider<BlockParticleOption> {
public Particle m_6966_(BlockParticleOption p_108304_, ClientLevel p_108305_, double p_108306_, double p_108307_, double p_108308_, double p_108309_, double p_108310_, double p_108311_) {
@@ -52,16 +52,23 @@
public static RenderType m_109279_(ItemStack p_109280_, boolean p_109281_) {
Item item = p_109280_.m_41720_();
if (item instanceof BlockItem) {
@@ -365,8 +_,73 @@
@@ -365,11 +_,79 @@
}
public static RenderType m_109287_(FluidState p_109288_) {
- RenderType rendertype = f_109276_.get(p_109288_.m_76152_());
+ RenderType rendertype = FLUID_RENDER_TYPES.get(net.minecraftforge.registries.ForgeRegistries.FLUIDS.getDelegateOrThrow(p_109288_.m_76152_()));
return rendertype != null ? rendertype : RenderType.m_110451_();
}
public static void m_109291_(boolean p_109292_) {
f_109277_ = p_109292_;
+ }
+
+ // FORGE START
+ /** 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 f_109277_;
+ }
+
+ private static final net.minecraftforge.client.ChunkRenderTypeSet CUTOUT_MIPPED = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.m_110457_());
+ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID = net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.m_110451_());
@@ -79,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.m_60734_();
+ if (block instanceof LeavesBlock) {
@@ -90,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);
@@ -125,5 +132,4 @@
+ private static net.minecraftforge.client.ChunkRenderTypeSet createSetFromPredicate(java.util.function.Predicate<RenderType> predicate) {
+ return net.minecraftforge.client.ChunkRenderTypeSet.of(RenderType.m_110506_().stream().filter(predicate).toArray(RenderType[]::new));
}
public static void m_109291_(boolean p_109292_) {
}
@@ -5,7 +5,7 @@
}
- return new BakedQuad(aint, p_111603_.f_111355_, direction, p_111604_, p_111608_);
+ net.minecraftforge.client.ForgeHooksClient.fillNormal(aint, direction);
+ net.minecraftforge.client.ForgeHooksClient.fillNormal(aint, direction, p_111603_.getFaceData().calculateNormals());
+ var data = p_111603_.getFaceData();
+ var quad = new BakedQuad(aint, p_111603_.f_111355_, direction, p_111604_, p_111608_, data.ambientOcclusion());
+ if (!net.minecraftforge.client.model.ForgeFaceData.DEFAULT.equals(data)) {
@@ -1,13 +1,15 @@
--- a/net/minecraft/client/renderer/entity/FallingBlockRenderer.java
+++ b/net/minecraft/client/renderer/entity/FallingBlockRenderer.java
@@ -34,7 +_,9 @@
@@ -34,7 +_,11 @@
p_114637_.m_85836_();
BlockPos blockpos = BlockPos.m_274561_(p_114634_.m_20185_(), p_114634_.m_20191_().f_82292_, p_114634_.m_20189_());
p_114637_.m_85837_(-0.5D, 0.0D, -0.5D);
- this.f_234617_.m_110937_().m_234379_(level, this.f_234617_.m_110910_(blockstate), blockstate, blockpos, p_114637_, p_114638_.m_6299_(ItemBlockRenderTypes.m_109293_(blockstate)), false, RandomSource.m_216327_(), blockstate.m_60726_(p_114634_.m_31978_()), OverlayTexture.f_118083_);
+ var model = this.f_234617_.m_110910_(blockstate);
+ for (var renderType : model.getRenderTypes(blockstate, RandomSource.m_216335_(blockstate.m_60726_(p_114634_.m_31978_())), net.minecraftforge.client.model.data.ModelData.EMPTY))
+ for (var renderType : model.getRenderTypes(blockstate, RandomSource.m_216335_(blockstate.m_60726_(p_114634_.m_31978_())), net.minecraftforge.client.model.data.ModelData.EMPTY)) {
+ renderType = net.minecraftforge.client.RenderTypeHelper.getMovingBlockRenderType(renderType);
+ this.f_234617_.m_110937_().tesselateBlock(level, model, blockstate, blockpos, p_114637_, p_114638_.m_6299_(renderType), false, RandomSource.m_216327_(), blockstate.m_60726_(p_114634_.m_31978_()), OverlayTexture.f_118083_, net.minecraftforge.client.model.data.ModelData.EMPTY, renderType);
+ }
p_114637_.m_85849_();
super.m_7392_(p_114634_, p_114635_, p_114636_, p_114637_, p_114638_, p_114639_);
}
@@ -5,7 +5,7 @@
int k1 = Mth.m_14173_(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
f_244357_.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.f_244500_, p_261919_, k1, j1);
l1 = k1;
} else {
@@ -1,39 +1,81 @@
--- a/net/minecraft/client/resources/model/SimpleBakedModel.java
+++ b/net/minecraft/client/resources/model/SimpleBakedModel.java
@@ -26,8 +_,17 @@
@@ -26,8 +_,44 @@
protected final TextureAtlasSprite f_119485_;
protected final ItemTransforms f_119486_;
protected final ItemOverrides f_119487_;
+ /** 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_,
+ 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,
+ net.minecraftforge.client.RenderTypeGroup renderTypesFast
+ ) {
this.f_119480_ = p_119489_;
this.f_119481_ = p_119490_;
this.f_119482_ = p_119491_;
@@ -36,6 +_,9 @@
@@ -36,6 +_,15 @@
this.f_119485_ = p_119494_;
this.f_119486_ = p_119495_;
this.f_119487_ = 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.m_110463_() || renderTypes.block() == net.minecraft.client.renderer.RenderType.m_110457_());
}
public List<BakedQuad> m_213637_(@Nullable BlockState p_235054_, @Nullable Direction p_235055_, RandomSource p_235056_) {
@@ -70,6 +_,25 @@
@@ -70,6 +_,40 @@
return this.f_119487_;
}
+ private static final net.minecraftforge.client.ChunkRenderTypeSet SOLID_BLOCK = net.minecraftforge.client.ChunkRenderTypeSet.of(net.minecraft.client.renderer.RenderType.m_110451_());
+ private static final List<net.minecraft.client.renderer.RenderType> SOLID_BLOCK_ITEM = List.of(net.minecraft.client.renderer.RenderType.m_110451_());
+
+ @Override
+ public net.minecraftforge.client.ChunkRenderTypeSet getRenderTypes(@org.jetbrains.annotations.NotNull BlockState state, @org.jetbrains.annotations.NotNull RandomSource rand, @org.jetbrains.annotations.NotNull net.minecraftforge.client.model.data.ModelData data) {
+ if (!net.minecraft.client.renderer.ItemBlockRenderTypes.isFancy()) {
+ if (blockRenderTypesFast != null)
+ return blockRenderTypesFast;
+ if (isRenderingCutout && state.m_60734_() instanceof net.minecraft.world.level.block.LeavesBlock)
+ return SOLID_BLOCK;
+ }
+ if (blockRenderTypes != null)
+ return blockRenderTypes;
+ return BakedModel.super.getRenderTypes(state, rand, data);
@@ -42,11 +84,17 @@
+ @Override
+ public List<net.minecraft.client.renderer.RenderType> getRenderTypes(net.minecraft.world.item.ItemStack itemStack, boolean fabulous) {
+ if (!fabulous) {
+ if (!net.minecraft.client.renderer.ItemBlockRenderTypes.isFancy()) {
+ if (itemRenderTypesFast != null)
+ return itemRenderTypesFast;
+ if (isRenderingCutout && itemStack.m_41720_() instanceof net.minecraft.world.item.BlockItem blockItem && blockItem.m_40614_() instanceof net.minecraft.world.level.block.LeavesBlock)
+ return SOLID_BLOCK_ITEM;
+ }
+ if (itemRenderTypes != null)
+ return itemRenderTypes;
+ return itemRenderTypes;
+ } else {
+ if (fabulousItemRenderTypes != null)
+ return fabulousItemRenderTypes;
+ return fabulousItemRenderTypes;
+ }
+ return BakedModel.super.getRenderTypes(itemStack, fabulous);
+ }
@@ -54,22 +102,50 @@
@OnlyIn(Dist.CLIENT)
public static class Builder {
private final List<BakedQuad> f_119508_ = Lists.newArrayList();
@@ -116,11 +_,17 @@
@@ -116,11 +_,45 @@
return this;
}
+ /** @deprecated Forge: Use {@linkplain #build(net.minecraftforge.client.RenderTypeGroup) variant with RenderTypeGroup} **/
+ @Deprecated
public BakedModel m_119533_() {
+ return build(net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ return build(net.minecraftforge.client.RenderTypeGroup.EMPTY, net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ }
+
+ /**
+ * Builds with the render type to be used for this model, which 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 #build(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 #build(net.minecraftforge.client.RenderTypeGroup, net.minecraftforge.client.RenderTypeGroup)
+ * renderTypes(RenderTypeGroup, RenderTypeGroup)
+ */
+ public BakedModel build(net.minecraftforge.client.RenderTypeGroup renderTypes) {
+ return this.build(renderTypes, net.minecraftforge.client.RenderTypeGroup.EMPTY);
+ }
+
+ /**
+ * Builds with 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 #build(net.minecraftforge.client.RenderTypeGroup)
+ */
+ public BakedModel build(net.minecraftforge.client.RenderTypeGroup renderTypes, net.minecraftforge.client.RenderTypeGroup renderTypesFast) {
if (this.f_119512_ == null) {
throw new RuntimeException("Missing particle!");
} else {
- return new SimpleBakedModel(this.f_119508_, this.f_119509_, this.f_119511_, this.f_119513_, this.f_119514_, this.f_119512_, this.f_119515_, this.f_119510_);
+ return new SimpleBakedModel(this.f_119508_, this.f_119509_, this.f_119511_, this.f_119513_, this.f_119514_, this.f_119512_, this.f_119515_, this.f_119510_, renderTypes);
+ // Forge: Account for render types in model JSONs
+ return new SimpleBakedModel(this.f_119508_, this.f_119509_, this.f_119511_, this.f_119513_, this.f_119514_, this.f_119512_, this.f_119515_, this.f_119510_, renderTypes, renderTypesFast);
}
}
}
@@ -9,21 +9,13 @@
this.f_120088_.setSoTimeout(5000);
this.f_120088_.joinGroup(this.f_120087_);
}
@@ -87,7 +_,19 @@
@@ -87,7 +_,11 @@
String s = LanServerPinger.m_120111_(p_120097_);
String s1 = LanServerPinger.m_120116_(p_120097_);
if (s1 != null) {
- s1 = p_120098_.getHostAddress() + ":" + s1;
+ if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) {
+ final String ip;
+
+ // compress to short form if enabled in config
+ if (net.minecraftforge.common.ForgeConfig.CLIENT.compressLanIPv6Addresses.get())
+ ip = com.google.common.net.InetAddresses.toAddrString(p_120098_);
+ else
+ ip = p_120098_.getHostAddress();
+
+ s1 = "[" + ip + "]:" + s1;
+ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1;
+ } else {
+ s1 = p_120098_.getHostAddress() + ":" + s1;
+ }
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/server/LanServerPinger.java
+++ b/net/minecraft/client/server/LanServerPinger.java
@@ -16,7 +_,7 @@
@@ -13,7 +_,7 @@
public class LanServerPinger extends Thread {
private static final AtomicInteger f_120101_ = new AtomicInteger(0);
private static final Logger f_120102_ = LogUtils.getLogger();
@@ -9,7 +9,7 @@
public static final int f_174975_ = 4445;
private static final long f_174976_ = 1500L;
private final String f_120103_;
@@ -39,7 +_,7 @@
@@ -36,7 +_,7 @@
while(!this.isInterrupted() && this.f_120105_) {
try {
@@ -0,0 +1,11 @@
--- a/net/minecraft/commands/SharedSuggestionProvider.java
+++ b/net/minecraft/commands/SharedSuggestionProvider.java
@@ -82,7 +_,7 @@
if (m_82949_(p_82946_, s)) {
p_82948_.accept(t);
}
- } else if (m_82949_(p_82946_, resourcelocation.m_135827_()) || resourcelocation.m_135827_().equals("minecraft") && m_82949_(p_82946_, resourcelocation.m_135815_())) {
+ } else if (m_82949_(p_82946_, resourcelocation.m_135827_()) || m_82949_(p_82946_, resourcelocation.m_135815_())) { // Forge: Removed "minecraft" namespace requirement for path searching to allow modded path suggestions to show up
p_82948_.accept(t);
}
}
@@ -24,7 +24,7 @@
public boolean m_207277_(HolderOwner<T> p_256542_) {
return this.f_254711_.m_254921_(p_256542_);
+ }
+ // FORGE: Keep a list of invalidation callbacks so they can be run when tags rebind
+ // FORGE: Keep a list of invalidation callbacks so they can be run when tags rebind
+ private List<Runnable> invalidationCallbacks = new java.util.ArrayList<>();
+ public void addInvalidationListener(Runnable runnable) {
+ invalidationCallbacks.add(runnable);
@@ -66,9 +66,12 @@
Predicate<ResourceLocation> predicate = (p_255496_) -> {
return registrylookup.m_254902_(ResourceKey.m_135785_(this.f_254716_, p_255496_)).isPresent();
};
@@ -77,12 +_,13 @@
@@ -75,14 +_,16 @@
ResourceLocation resourcelocation = p_255499_.getKey();
TagBuilder tagbuilder = p_255499_.getValue();
List<TagEntry> list = tagbuilder.m_215904_();
List<TagEntry> list1 = list.stream().filter((p_274771_) -> {
- List<TagEntry> list1 = list.stream().filter((p_274771_) -> {
+ List<TagEntry> list1 = java.util.stream.Stream.concat(list.stream(), tagbuilder.getRemoveEntries()).filter((p_274771_) -> {
return !p_274771_.m_215940_(predicate, predicate1);
- }).toList();
+ }).filter(this::missing).toList(); // Forge: Add validation via existing resources
@@ -77,13 +80,14 @@
} else {
- JsonElement jsonelement = TagFile.f_215958_.encodeStart(JsonOps.INSTANCE, new TagFile(list, false)).getOrThrow(false, f_126541_::error);
- Path path = this.f_236439_.m_245731_(resourcelocation);
+ JsonElement jsonelement = TagFile.f_215958_.encodeStart(JsonOps.INSTANCE, new TagFile(list, tagbuilder.isReplace())).getOrThrow(false, f_126541_::error);
+ var removed = tagbuilder.getRemoveEntries().toList();
+ JsonElement jsonelement = TagFile.f_215958_.encodeStart(JsonOps.INSTANCE, new TagFile(list, tagbuilder.isReplace(), removed)).getOrThrow(false, f_126541_::error);
+ Path path = this.getPath(resourcelocation);
+ if (path == null) return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags.
return DataProvider.m_253162_(p_253684_, jsonelement, path);
}
}).toArray((p_253442_) -> {
@@ -91,13 +_,23 @@
@@ -91,13 +_,25 @@
});
}
@@ -104,7 +108,9 @@
protected TagBuilder m_236451_(TagKey<T> p_236452_) {
return this.f_126543_.computeIfAbsent(p_236452_.f_203868_(), (p_236442_) -> {
+ existingFileHelper.trackGenerated(p_236442_, resourceType);
+ if (existingFileHelper != null) {
+ existingFileHelper.trackGenerated(p_236442_, resourceType);
+ }
return TagBuilder.m_215899_();
});
}
@@ -44,12 +44,20 @@
}
public ResourceLocation m_132042_() {
@@ -61,4 +_,8 @@
@@ -60,5 +_,16 @@
public FriendlyByteBuf m_132045_() {
return new FriendlyByteBuf(this.f_132030_.copy());
}
+ }
+
+ @Override public int getIndex() { return Integer.MAX_VALUE; }
+ @Override public ResourceLocation getName() { return m_132042_(); }
+ @Override public FriendlyByteBuf getInternalData() { return m_132045_(); }
+ @Override public FriendlyByteBuf getInternalData() {
+ // Create a heap copy to pass off to other consumers because we could be reading from a pooled buffer that never gets released.
+ // Using a heap buffer means that it will be released when the GC determines its free.
+ // See: https://github.com/MinecraftForge/MinecraftForge/issues/10861
+ var heapCopy = io.netty.buffer.Unpooled.buffer(this.f_132030_.readableBytes());
+ heapCopy.writeBytes(this.f_132030_.slice()); // We use a slice to not mess with the reader index, just in case someone else wants to touch the buffer later
+ return new FriendlyByteBuf(heapCopy);
}
}
@@ -9,11 +9,11 @@
}
static <E> void m_255048_(RegistryOps.RegistryInfoLookup p_256369_, ResourceManager p_256349_, ResourceKey<? extends Registry<E>> p_255792_, WritableRegistry<E> p_256211_, Decoder<E> p_256232_, Map<ResourceKey<?>, Exception> p_255884_) {
@@ -139,6 +_,7 @@
@@ -138,6 +_,7 @@
try (Reader reader = resource.m_215508_()) {
JsonElement jsonelement = JsonParser.parseReader(reader);
+ if (!net.minecraftforge.common.crafting.conditions.ICondition.shouldRegisterEntry(jsonelement)) continue;
DataResult<E> dataresult = p_256232_.parse(registryops, jsonelement);
+ if (!net.minecraftforge.common.crafting.conditions.ICondition.shouldRegisterEntry(jsonelement)) continue;
E e = dataresult.getOrThrow(false, (p_248715_) -> {
});
p_256211_.m_255290_(resourcekey, e, resource.m_247137_() ? Lifecycle.stable() : dataresult.lifecycle());
@@ -1,5 +1,29 @@
--- a/net/minecraft/resources/ResourceLocation.java
+++ b/net/minecraft/resources/ResourceLocation.java
@@ -34,6 +_,8 @@
this.f_135805_ = p_249394_;
}
+ /** @deprecated Forge: Consider using {@link #fromNamespaceAndPath(String, String)} instead, as Mojang made this constructor private in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public ResourceLocation(String p_135811_, String p_135812_) {
this(m_245413_(p_135811_, p_135812_), m_245185_(p_135811_, p_135812_), (ResourceLocation.Dummy)null);
}
@@ -42,10 +_,14 @@
this(p_135814_[0], p_135814_[1]);
}
+ /** @deprecated Forge: Consider using {@link #parse(String)} instead, as Mojang made this constructor private in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public ResourceLocation(String p_135809_) {
this(m_135832_(p_135809_, ':'));
}
+ /** @deprecated Forge: Consider using {@link #bySeparator(String, char)} instead, as Mojang removed this method in 1.21 */
+ @Deprecated(forRemoval = true, since = "1.20.6")
public static ResourceLocation m_135822_(String p_135823_, char p_135824_) {
return new ResourceLocation(m_135832_(p_135823_, p_135824_));
}
@@ -143,6 +_,12 @@
return i;
}
@@ -13,3 +37,55 @@
public String m_179910_() {
return this.toString().replace('/', '_').replace(':', '_');
}
@@ -243,6 +_,51 @@
public JsonElement serialize(ResourceLocation p_135855_, Type p_135856_, JsonSerializationContext p_135857_) {
return new JsonPrimitive(p_135855_.toString());
+ }
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #ResourceLocation(String, String)}. */
+ public static ResourceLocation fromNamespaceAndPath(String namespace, String path) {
+ return new ResourceLocation(namespace, path);
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #ResourceLocation(String)}. */
+ public static ResourceLocation parse(String location) {
+ return new ResourceLocation(location);
+ }
+
+ /**
+ * Forge: This is a backported method from 1.21, and acts as an alternative to using {@link #parse(String)}. If you
+ * know for sure you are going to be using the {@linkplain #DEFAULT_NAMESPACE default namespace}
+ * ({@code "minecraft"}), use this.
+ */
+ public static ResourceLocation withDefaultNamespace(String path) {
+ return new ResourceLocation(f_179908_, m_245185_(f_179908_, path), null);
+ }
+
+ /** Forge: This is a backported method from 1.21, and is the replacement for {@link #of(String, char)}. */
+ public static ResourceLocation bySeparator(String location, char separator) {
+ return m_135822_(location, separator);
+ }
+
+ /**
+ * Forge: This is a backported method from 1.21, and is the same as {@link #bySeparator(String, char)} but returns
+ * {@code null} if a resource location cannot be created.
+ */
+ public static @Nullable ResourceLocation tryBySeparator(String location, char separator) {
+ int i = location.indexOf(separator);
+ if (i >= 0) {
+ String s = location.substring(i + 1);
+ if (!m_135841_(s)) {
+ return null;
+ } else if (i != 0) {
+ String s1 = location.substring(0, i);
+ return m_135843_(s1) ? new ResourceLocation(s1, s, null) : null;
+ } else {
+ return new ResourceLocation(f_179908_, s, null);
+ }
+ } else {
+ return m_135841_(location) ? new ResourceLocation(f_179908_, location, null) : null;
}
}
}
@@ -1,10 +1,15 @@
--- a/net/minecraft/server/Bootstrap.java
+++ b/net/minecraft/server/Bootstrap.java
@@ -54,6 +_,8 @@
@@ -54,6 +_,13 @@
CauldronInteraction.m_175649_();
BuiltInRegistries.m_257498_();
CreativeModeTabs.m_280019_();
+ net.minecraftforge.registries.GameData.vanillaSnapshot();
+ // Forge: Hacky fix to ensure that NetworkConstants is loaded before mods are constructed.
+ // Many older mods use network internals that shouldn't be used, yet are exposed so they get used anyways.
+ // This can cause class-loading issues with ForgeMod loading NetworkConstants and HandshakeResolver.
+ // To ensure that doesn't happen, we load it here and now. This is not an issue in 1.20.2 and newer.
+ net.minecraftforge.network.NetworkHooks.init();
+ if (false) // skip redirectOutputToLog, Forge already redirects stdout and stderr output to log so that they print with more context
m_135890_();
f_285608_.set(Duration.between(instant, Instant.now()).toMillis());
@@ -1,5 +1,14 @@
--- a/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/net/minecraft/server/dedicated/DedicatedServer.java
@@ -68,6 +_,8 @@
private MinecraftServerGui f_139605_;
@Nullable
private final TextFilterClient f_139606_;
+ @Nullable
+ private net.minecraft.client.server.LanServerPinger dediLanPinger;
public DedicatedServer(Thread p_214789_, LevelStorageSource.LevelStorageAccess p_214790_, PackRepository p_214791_, WorldStem p_214792_, DedicatedServerSettings p_214793_, DataFixer p_214794_, Services p_214795_, ChunkProgressListenerFactory p_214796_) {
super(p_214789_, p_214790_, p_214791_, p_214792_, Proxy.NO_PROXY, p_214794_, p_214795_, p_214796_);
@@ -79,6 +_,7 @@
public boolean m_7038_() throws IOException {
Thread thread = new Thread("Server console handler") {
@@ -22,26 +31,41 @@
if (dedicatedserverproperties.f_139744_ != null) {
this.m_129900_().m_46170_(GameRules.f_46153_).m_46246_(dedicatedserverproperties.f_139744_, this);
}
@@ -183,12 +_,13 @@
thread1.start();
}
+ // <3 you Grum for this, saves us ~30 patch files! --^
if (dedicatedserverproperties.f_139721_) {
MinecraftServerStatistics.m_18328_(this);
@@ -188,7 +_,12 @@
f_139598_.info("JMX monitoring enabled");
}
- return true;
+ if (net.minecraftforge.common.ForgeConfig.SERVER.advertiseDedicatedServerToLan.get()) {
+ this.dediLanPinger = new net.minecraft.client.server.LanServerPinger(this.m_129916_(), String.valueOf(this.m_7448_()));
+ this.dediLanPinger.start();
+ }
+
+ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this);
}
}
@@ -492,6 +_,7 @@
@@ -263,6 +_,10 @@
this.f_139601_.m_7530_();
}
+ if (this.dediLanPinger != null) {
+ this.dediLanPinger.interrupt();
+ this.dediLanPinger = null;
+ }
}
public void m_5703_(BooleanSupplier p_139661_) {
@@ -492,7 +_,12 @@
}
public void m_7041_() {
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.GameShuttingDownEvent());
super.m_7041_();
+ if (this.dediLanPinger != null) {
+ this.dediLanPinger.interrupt();
+ this.dediLanPinger = null;
+ }
Util.m_137580_();
SkullBlockEntity.m_196704_();
}
@@ -85,6 +85,14 @@
}
}
@@ -681,6 +_,7 @@
return BuiltInRegistries.f_256780_.m_7981_(p_8648_.m_6095_()).toString();
});
profilerfiller.m_6174_("tickNonPassenger");
+ if (p_8648_.canUpdate())
p_8648_.m_8119_();
this.m_46473_().m_7238_();
@@ -700,6 +_,7 @@
return BuiltInRegistries.f_256780_.m_7981_(p_8664_.m_6095_()).toString();
});
@@ -1,15 +1,18 @@
--- a/net/minecraft/server/level/ServerPlayerGameMode.java
+++ b/net/minecraft/server/level/ServerPlayerGameMode.java
@@ -124,7 +_,11 @@
@@ -124,7 +_,14 @@
}
public void m_214168_(BlockPos p_215120_, ServerboundPlayerActionPacket.Action p_215121_, Direction p_215122_, int p_215123_, int p_215124_) {
- if (this.f_9245_.m_146892_().m_82557_(Vec3.m_82512_(p_215120_)) > ServerGamePacketListenerImpl.f_215198_) {
+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(f_9245_, p_215120_, p_215122_);
+ net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock event = net.minecraftforge.common.ForgeHooks.onLeftClickBlock(f_9245_, p_215120_, p_215122_, p_215121_);
+ if (event.isCanceled() || (!this.m_9295_() && event.getResult() == net.minecraftforge.eventbus.api.Event.Result.DENY)) {
+ return;
+ }
+ if (!this.f_9245_.canReach(p_215120_, 1.5)) { // Vanilla check is eye-to-center distance < 6, so padding is 6 - 4.5 = 1.5
+
+ boolean canReachUnmodded = this.testPlayerCanReach(p_215120_);
+ boolean canReachModded = this.f_9245_.canReach(p_215120_, 1.5); // Vanilla uses ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE which is 6*6, default Block reach is 4.5, so add 1.5 padding
+ if (canReachUnmodded == canReachModded ? !this.f_9245_.canReachRaw(p_215120_, 1.5) : !canReachModded) {
this.m_215125_(p_215120_, false, p_215124_, "too far");
} else if (p_215120_.m_123342_() >= p_215123_) {
this.f_9245_.f_8906_.m_9829_(new ClientboundBlockUpdatePacket(p_215120_, this.f_9244_.m_8055_(p_215120_)));
@@ -21,6 +24,18 @@
blockstate.m_60686_(this.f_9244_, p_215120_, this.f_9245_);
f = blockstate.m_60625_(this.f_9245_, this.f_9245_.m_9236_(), p_215120_);
}
@@ -209,6 +_,11 @@
}
}
+ private boolean testPlayerCanReach(BlockPos pos) {
+ // don't mixin into this
+ return this.f_9245_.canReach(pos, 1.5);
+ }
+
public void m_215116_(BlockPos p_215117_, int p_215118_, String p_215119_) {
if (this.m_9280_(p_215117_)) {
this.m_215125_(p_215117_, true, p_215118_, p_215119_);
@@ -221,7 +_,8 @@
public boolean m_9280_(BlockPos p_9281_) {
@@ -13,24 +13,27 @@
public static final double f_215198_ = Mth.m_144952_(6.0D);
private static final int f_215199_ = -1;
private static final int f_244471_ = 4096;
@@ -436,9 +_,11 @@
@@ -983,8 +_,10 @@
case SWAP_ITEM_WITH_OFFHAND:
if (!this.f_9743_.m_5833_()) {
ItemStack itemstack = this.f_9743_.m_21120_(InteractionHand.OFF_HAND);
- this.f_9743_.m_21008_(InteractionHand.OFF_HAND, this.f_9743_.m_21120_(InteractionHand.MAIN_HAND));
- this.f_9743_.m_21008_(InteractionHand.MAIN_HAND, itemstack);
+ var event = net.minecraftforge.common.ForgeHooks.onLivingSwapHandItems(this.f_9743_);
+ if (event.isCanceled()) return;
+ this.f_9743_.m_21008_(InteractionHand.OFF_HAND, event.getItemSwappedToOffHand());
+ this.f_9743_.m_21008_(InteractionHand.MAIN_HAND, event.getItemSwappedToMainHand());
this.f_9743_.m_5810_();
}
entity.m_19890_(d3, d4, d5, f, f1);
+ this.f_9743_.m_19890_(d3, d4, d5, this.f_9743_.m_146908_(), this.f_9743_.m_146909_()); // Forge - Resync player position on vehicle moving
boolean flag3 = serverlevel.m_45756_(entity, entity.m_20191_().m_82406_(0.0625D));
if (flag && (flag2 || !flag3)) {
entity.m_19890_(d0, d1, d2, f, f1);
+ this.f_9743_.m_19890_(d3, d4, d5, this.f_9743_.m_146908_(), this.f_9743_.m_146909_()); // Forge - Resync player position on vehicle moving
this.f_9742_.m_129512_(new ClientboundMoveVehiclePacket(entity));
return;
}
@@ -1035,7 +_,7 @@
@@ -1035,7 +_,9 @@
Vec3 vec3 = blockhitresult.m_82450_();
BlockPos blockpos = blockhitresult.m_82425_();
Vec3 vec31 = Vec3.m_82512_(blockpos);
- if (!(this.f_9743_.m_146892_().m_82557_(vec31) > f_215198_)) {
+ if (this.f_9743_.canReach(blockpos, 1.5)) { // Vanilla uses eye-to-center distance < 6, which implies a padding of 1.5
+ boolean canReachUnmodded = this.testPlayerCanReach(blockpos);
+ boolean canReachModded = this.f_9743_.canReach(blockpos, 1.5); // Vanilla uses eye-to-center distance < ServerGamePacketListenerImpl which is 6*6, default block reach is 4.5, so add 1.5 padding
+ if (canReachUnmodded == canReachModded ? this.f_9743_.canReachRaw(blockpos, 1.5) : canReachModded) {
Vec3 vec32 = vec3.m_82546_(vec31);
double d0 = 1.0000001D;
if (Math.abs(vec32.m_7096_()) < 1.0000001D && Math.abs(vec32.m_7098_()) < 1.0000001D && Math.abs(vec32.m_7094_()) < 1.0000001D) {
@@ -43,6 +46,17 @@
InteractionResult interactionresult = this.f_9743_.f_8941_.m_7179_(this.f_9743_, serverlevel, itemstack, interactionhand, blockhitresult);
if (direction == Direction.UP && !interactionresult.m_19077_() && blockpos.m_123342_() >= i - 1 && m_9790_(this.f_9743_, itemstack)) {
Component component = Component.m_237110_("build.tooHigh", i - 1).m_130940_(ChatFormatting.RED);
@@ -1066,6 +_,10 @@
}
}
+ private boolean testPlayerCanReach(BlockPos pos) {
+ return this.f_9743_.canReach(pos, 1.5);
+ }
+
public void m_5760_(ServerboundUseItemPacket p_9932_) {
PacketUtils.m_131359_(p_9932_, this, this.f_9743_.m_284548_());
this.m_215201_(p_9932_.m_238013_());
@@ -1187,10 +_,13 @@
}
@@ -64,7 +78,7 @@
AABB aabb = entity.m_20191_();
- if (aabb.m_272282_(this.f_9743_.m_146892_()) < f_215198_) {
+ if (this.f_9743_.canReach(entity, 3)) { // Vanilla padding is 3.0 (distSq < 6.0 * 6.0)
+ if (this.f_9743_.canReachRaw(entity, 3.0)) { // Vanilla uses MAX_INTERACTION_DISTANCE which is 6*6 default entity reach is 3.0 so add 3.0 padding
p_9866_.m_179617_(new ServerboundInteractPacket.Handler() {
private void m_143678_(InteractionHand p_143679_, ServerGamePacketListenerImpl.EntityInteraction p_143680_) {
ItemStack itemstack = ServerGamePacketListenerImpl.this.f_9743_.m_21120_(p_143679_);
@@ -15,6 +15,16 @@
this.m_10055_();
} else if (this.f_10019_ == ServerLoginPacketListenerImpl.State.DELAY_ACCEPT) {
ServerPlayer serverplayer = this.f_10018_.m_6846_().m_11259_(this.f_10021_.getId());
@@ -138,7 +_,8 @@
}
public String m_10056_() {
- return this.f_10021_ != null ? this.f_10021_ + " (" + this.f_10013_.m_129523_() + ")" : String.valueOf((Object)this.f_10013_.m_129523_());
+ final String addressString = net.minecraftforge.network.DualStackUtils.getAddressString(this.f_10013_.m_129523_());
+ return this.f_10021_ != null ? this.f_10021_ + " (" + addressString + ")" : addressString;
}
public void m_5990_(ServerboundHelloPacket p_10047_) {
@@ -147,14 +_,14 @@
GameProfile gameprofile = this.f_10018_.m_236731_();
if (gameprofile != null && p_10047_.f_238040_().equalsIgnoreCase(gameprofile.getName())) {
@@ -5,7 +5,7 @@
public PackRepository(RepositorySource... p_251886_) {
- this.f_10497_ = ImmutableSet.copyOf(p_251886_);
+ this.f_10497_ = new java.util.HashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on.
+ this.f_10497_ = new java.util.LinkedHashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on.
}
public void m_10506_() {
@@ -8,7 +8,15 @@
public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess<RegistryLayer> p_251844_, PlayerDataStorage p_203844_, int p_203845_) {
this.f_11195_ = p_203842_;
@@ -174,6 +_,7 @@
@@ -167,13 +_,14 @@
p_11263_.m_284127_(serverlevel1);
String s1 = "local";
if (p_11262_.m_129523_() != null) {
- s1 = p_11262_.m_129523_().toString();
+ s1 = net.minecraftforge.network.DualStackUtils.getAddressString(p_11262_.m_129523_());
}
f_11188_.info("{}[{}] logged in with entity id {} at ({}, {}, {})", p_11263_.m_7755_().getString(), s1, p_11263_.m_19879_(), p_11263_.m_20185_(), p_11263_.m_20186_(), p_11263_.m_20189_());
LevelData leveldata = serverlevel1.m_6106_();
p_11263_.m_143427_(compoundtag);
ServerGamePacketListenerImpl servergamepacketlistenerimpl = new ServerGamePacketListenerImpl(this.f_11195_, p_11262_, p_11263_);
@@ -0,0 +1,17 @@
--- a/net/minecraft/tags/TagFile.java
+++ b/net/minecraft/tags/TagFile.java
@@ -4,8 +_,12 @@
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.List;
-public record TagFile(List<TagEntry> f_215959_, boolean f_215960_) {
+public record TagFile(List<TagEntry> f_215959_, boolean f_215960_, List<TagEntry> remove) {
public static final Codec<TagFile> f_215958_ = RecordCodecBuilder.create((p_215967_) -> {
- return p_215967_.group(TagEntry.f_215911_.listOf().fieldOf("values").forGetter(TagFile::f_215959_), Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::f_215960_)).apply(p_215967_, TagFile::new);
+ return p_215967_.group(TagEntry.f_215911_.listOf().fieldOf("values").forGetter(TagFile::f_215959_), Codec.BOOL.optionalFieldOf("replace", Boolean.valueOf(false)).forGetter(TagFile::f_215960_), TagEntry.f_215911_.listOf().optionalFieldOf("remove", List.of()).forGetter(TagFile::remove)).apply(p_215967_, TagFile::new);
});
+
+ public TagFile(List<TagEntry> f_215959_, boolean f_215960_) {
+ this(f_215959_, f_215960_, List.of());
+ }
}
@@ -1,11 +1,50 @@
--- a/net/minecraft/tags/TagLoader.java
+++ b/net/minecraft/tags/TagLoader.java
@@ -59,6 +_,7 @@
tagfile.f_215959_().forEach((p_215997_) -> {
list.add(new TagLoader.EntryWithSource(p_215997_, s));
});
+ tagfile.remove().forEach(e -> list.add(new TagLoader.EntryWithSource(e, s, true)));
} catch (Exception exception) {
f_13445_.error("Couldn't read tag list {} from {} in data pack {}", resourcelocation1, resourcelocation, resource.m_215506_(), exception);
}
@@ -69,16 +_,17 @@
}
private Either<Collection<TagLoader.EntryWithSource>, Collection<T>> m_215978_(TagEntry.Lookup<T> p_215979_, List<TagLoader.EntryWithSource> p_215980_) {
- ImmutableSet.Builder<T> builder = ImmutableSet.builder();
+ var builder = new java.util.LinkedHashSet<T>(); // Order is important, as ImmutableSet is ordered and some people rely on that. https://github.com/MinecraftForge/MinecraftForge/issues/9774
List<TagLoader.EntryWithSource> list = new ArrayList<>();
for(TagLoader.EntryWithSource tagloader$entrywithsource : p_215980_) {
- if (!tagloader$entrywithsource.f_216042_().m_215927_(p_215979_, builder::add)) {
+ if (!tagloader$entrywithsource.f_216042_().m_215927_(p_215979_, tagloader$entrywithsource.remove() ? builder::remove : builder::add)) {
+ if (!tagloader$entrywithsource.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added.
list.add(tagloader$entrywithsource);
}
}
- return list.isEmpty() ? Either.right(builder.build()) : Either.left(list);
+ return list.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(list);
}
public Map<ResourceLocation, Collection<T>> m_203898_(Map<ResourceLocation, List<TagLoader.EntryWithSource>> p_203899_) {
@@ -100,7 +_,7 @@
});
dependencysorter.m_284430_((p_284682_, p_284683_) -> {
this.m_215978_(lookup, p_284683_.f_283922_).ifLeft((p_215977_) -> {
- f_13445_.error("Couldn't load tag {} as it is missing following references: {}", p_284682_, p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", ")));
+ f_13445_.error("Couldn't load tag {} as it is missing following references: {}", p_215977_, p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", \n\t")));
+ f_13445_.error("Couldn't load tag {} as it is missing following references: {}", p_284682_, p_215977_.stream().map(Objects::toString).collect(Collectors.joining(", \n\t")));
}).ifRight((p_216001_) -> {
map.put(p_284682_, p_216001_);
});
@@ -112,7 +_,8 @@
return this.m_203898_(this.m_144495_(p_203901_));
}
- public static record EntryWithSource(TagEntry f_216042_, String f_216043_) {
+ public static record EntryWithSource(TagEntry f_216042_, String f_216043_, boolean remove) {
+ public EntryWithSource(TagEntry f_216042_, String f_216043_) { this(f_216042_, f_216043_, false); }
public String toString() {
return this.f_216042_ + " (from " + this.f_216043_ + ")";
}
@@ -0,0 +1,18 @@
--- a/net/minecraft/world/Container.java
+++ b/net/minecraft/world/Container.java
@@ -78,10 +_,14 @@
}
static boolean m_272074_(BlockEntity p_273154_, Player p_273222_) {
- return m_271806_(p_273154_, p_273222_, 8);
+ return stillValidBlockEntity(p_273154_, p_273222_, p_273222_.m_21133_(net.minecraftforge.common.ForgeMod.BLOCK_REACH.get()) + 3.5); // Vanilla uses 8, default reach is 4.5 so add 3.5 padding
}
static boolean m_271806_(BlockEntity p_272877_, Player p_272670_, int p_273411_) {
+ return stillValidBlockEntity(p_272877_, p_272670_, (double)p_273411_);
+ }
+
+ static boolean stillValidBlockEntity(BlockEntity p_272877_, Player p_272670_, double p_273411_) {
Level level = p_272877_.m_58904_();
BlockPos blockpos = p_272877_.m_58899_();
if (level == null) {
@@ -41,7 +41,7 @@
this.m_8097_();
this.m_6034_(0.0D, 0.0D, 0.0D);
- this.f_19816_ = this.m_6380_(Pose.STANDING, this.f_19815_);
+ net.minecraftforge.event.entity.EntityEvent.Size sizeEvent = net.minecraftforge.event.ForgeEventFactory.getEntitySizeForge(this, Pose.STANDING, this.f_19815_, this.m_6380_(Pose.STANDING, this.f_19815_));
+ var sizeEvent = net.minecraftforge.event.ForgeEventFactory.getEntitySizeForge(this, Pose.STANDING, this.f_19815_, this.m_6380_(Pose.STANDING, this.f_19815_));
+ this.f_19815_ = sizeEvent.getNewSize();
+ this.f_19816_ = sizeEvent.getNewEyeHeight();
+ net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityEvent.EntityConstructing(this));
@@ -147,7 +147,7 @@
this.m_5496_(soundtype.m_56776_(), soundtype.m_56773_() * 0.15F, soundtype.m_56774_());
}
@@ -1176,19 +_,22 @@
@@ -1176,31 +_,38 @@
public void m_5844_() {
if (this.m_6069_()) {
@@ -175,6 +175,24 @@
}
void m_20074_() {
Entity entity = this.m_20202_();
+ java.util.function.BooleanSupplier updateFluidHeight = () -> this.m_204031_(FluidTags.f_13131_, 0.014D);
if (entity instanceof Boat boat) {
if (!boat.m_5842_()) {
this.f_19798_ = false;
- return;
+ updateFluidHeight = () -> {
+ this.updateFluidHeightAndDoFluidPushing(state -> this.shouldUpdateFluidWhileBoating(state, boat));
+ return false;
+ };
}
}
- if (this.m_204031_(FluidTags.f_13131_, 0.014D)) {
+ if (updateFluidHeight.getAsBoolean()) {
if (!this.f_19798_ && !this.f_19803_) {
this.m_5841_();
}
@@ -1217,6 +_,7 @@
private void m_20323_() {
this.f_19800_ = this.m_204029_(FluidTags.f_13131_);
@@ -385,7 +403,7 @@
EntityDimensions entitydimensions = this.f_19815_;
Pose pose = this.m_20089_();
EntityDimensions entitydimensions1 = this.m_6972_(pose);
+ net.minecraftforge.event.entity.EntityEvent.Size sizeEvent = net.minecraftforge.event.ForgeEventFactory.getEntitySizeForge(this, pose, entitydimensions, entitydimensions1, this.m_6380_(pose, entitydimensions1));
+ var sizeEvent = net.minecraftforge.event.ForgeEventFactory.getEntitySizeForge(this, pose, entitydimensions, entitydimensions1, this.m_6380_(pose, entitydimensions1));
+ entitydimensions1 = sizeEvent.getNewSize();
this.f_19815_ = entitydimensions1;
- this.f_19816_ = this.m_6380_(pose, entitydimensions1);
@@ -404,11 +422,11 @@
});
}
@@ -2980,9 +_,17 @@
@@ -2980,9 +_,31 @@
this.f_19859_ = this.m_146908_();
}
+ @Deprecated // Forge: Use no parameter version instead, only for vanilla Tags
+ @Deprecated // Forge: Use predicate version instead, only for vanilla Tags
public boolean m_204031_(TagKey<Fluid> p_204032_, double p_204033_) {
+ this.updateFluidHeightAndDoFluidPushing();
+ if(p_204032_ == FluidTags.f_13131_) return this.isInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get());
@@ -416,18 +434,35 @@
+ else return false;
+ }
+
+ @Deprecated(forRemoval = true, since = "1.20.1")
+ public void updateFluidHeightAndDoFluidPushing() {
+ this.updateFluidHeightAndDoFluidPushing(com.google.common.base.Predicates.alwaysTrue());
+ }
+
+ private static final class FluidCalcs {
+ double height = 0.0D;
+ Vec3 direction = Vec3.f_82478_;
+ int count = 0;
+ double height(double height) {
+ return (this.height = this.height >= height ? this.height : height);
+ }
+ }
+
+ public void updateFluidHeightAndDoFluidPushing(Predicate<FluidState> shouldUpdate) {
if (this.m_146899_()) {
- return false;
+ return;
} else {
AABB aabb = this.m_20191_().m_82406_(0.001D);
int i = Mth.m_14107_(aabb.f_82288_);
@@ -2997,25 +_,28 @@
Vec3 vec3 = Vec3.f_82478_;
int k1 = 0;
@@ -2994,28 +_,32 @@
double d0 = 0.0D;
boolean flag = this.m_6063_();
boolean flag1 = false;
- Vec3 vec3 = Vec3.f_82478_;
- int k1 = 0;
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
+ it.unimi.dsi.fastutil.objects.Object2ObjectMap<net.minecraftforge.fluids.FluidType, org.apache.commons.lang3.tuple.MutableTriple<Double, Vec3, Integer>> interimCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<>(net.minecraftforge.fluids.FluidType.SIZE.get() - 1);
+ it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<net.minecraftforge.fluids.FluidType, FluidCalcs> fluidPushCalcs = null;
for(int l1 = i; l1 < j; ++l1) {
for(int i2 = k; i2 < l; ++i2) {
@@ -436,64 +471,55 @@
FluidState fluidstate = this.m_9236_().m_6425_(blockpos$mutableblockpos);
- if (fluidstate.m_205070_(p_204032_)) {
+ net.minecraftforge.fluids.FluidType fluidType = fluidstate.getFluidType();
+ if (!fluidType.isAir()) {
+ if (!fluidType.isAir() && shouldUpdate.test(fluidstate)) {
double d1 = (double)((float)i2 + fluidstate.m_76155_(this.m_9236_(), blockpos$mutableblockpos));
if (d1 >= aabb.f_82289_) {
flag1 = true;
- d0 = Math.max(d1 - aabb.f_82289_, d0);
- if (flag) {
+ org.apache.commons.lang3.tuple.MutableTriple<Double, Vec3, Integer> interim = interimCalcs.computeIfAbsent(fluidType, t -> org.apache.commons.lang3.tuple.MutableTriple.of(0.0D, Vec3.f_82478_, 0));
+ interim.setLeft(Math.max(d1 - aabb.f_82289_, interim.getLeft()));
+ if (this.isPushedByFluid(fluidType)) {
+ if (fluidPushCalcs == null)
+ fluidPushCalcs = new it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap<net.minecraftforge.fluids.FluidType, FluidCalcs>(2);
+ var interim = fluidPushCalcs.computeIfAbsent(fluidType, type -> new FluidCalcs());
+ d0 = interim.height(d1 - aabb.f_82289_);
+ flag = this.isPushedByFluid(fluidType);
if (flag) {
Vec3 vec31 = fluidstate.m_76179_(this.m_9236_(), blockpos$mutableblockpos);
- if (d0 < 0.4D) {
- vec31 = vec31.m_82490_(d0);
+ if (interim.getLeft() < 0.4D) {
+ vec31 = vec31.m_82490_(interim.getLeft());
if (d0 < 0.4D) {
vec31 = vec31.m_82490_(d0);
}
- vec3 = vec3.m_82549_(vec31);
- ++k1;
+ interim.setMiddle(interim.getMiddle().m_82549_(vec31));
+ interim.setRight(interim.getRight() + 1);
+ interim.direction = interim.direction.m_82549_(vec31);
+ interim.count++;
}
}
}
@@ -3023,27 +_,28 @@
@@ -3023,6 +_,10 @@
}
}
- if (vec3.m_82553_() > 0.0D) {
- if (k1 > 0) {
- vec3 = vec3.m_82490_(1.0D / (double)k1);
+ interimCalcs.forEach((fluidType, interim) -> {
+ if (interim.getMiddle().m_82553_() > 0.0D) {
+ if (interim.getRight() > 0) {
+ interim.setMiddle(interim.getMiddle().m_82490_(1.0D / (double)interim.getRight()));
}
if (!(this instanceof Player)) {
- vec3 = vec3.m_82541_();
+ interim.setMiddle(interim.getMiddle().m_82541_());
+ if (fluidPushCalcs == null) return;
+ fluidPushCalcs.forEach((fluidType, interim) -> {
+ var vec3 = interim.direction;
+ var k1 = interim.count;
if (vec3.m_82553_() > 0.0D) {
if (k1 > 0) {
vec3 = vec3.m_82490_(1.0D / (double)k1);
@@ -3033,6 +_,7 @@
}
Vec3 vec32 = this.m_20184_();
- vec3 = vec3.m_82490_(p_204033_ * 1.0D);
+ interim.setMiddle(interim.getMiddle().m_82490_(this.getFluidMotionScale(fluidType)));
+ var p_204033_ = this.getFluidMotionScale(fluidType);
vec3 = vec3.m_82490_(p_204033_ * 1.0D);
double d2 = 0.003D;
- if (Math.abs(vec32.f_82479_) < 0.003D && Math.abs(vec32.f_82481_) < 0.003D && vec3.m_82553_() < 0.0045000000000000005D) {
- vec3 = vec3.m_82541_().m_82490_(0.0045000000000000005D);
+ if (Math.abs(vec32.f_82479_) < 0.003D && Math.abs(vec32.f_82481_) < 0.003D && interim.getMiddle().m_82553_() < 0.0045000000000000005D) {
+ interim.setMiddle(interim.getMiddle().m_82541_().m_82490_(0.0045000000000000005D));
}
- this.m_20256_(this.m_20184_().m_82549_(vec3));
+ this.m_20256_(this.m_20184_().m_82549_(interim.getMiddle()));
if (Math.abs(vec32.f_82479_) < 0.003D && Math.abs(vec32.f_82481_) < 0.003D && vec3.m_82553_() < 0.0045000000000000005D) {
@@ -3042,8 +_,8 @@
this.m_20256_(this.m_20184_().m_82549_(vec3));
}
- this.f_19799_.put(p_204032_, d0);
- return flag1;
+ this.setFluidTypeHeight(fluidType, interim.getLeft());
+ this.setFluidTypeHeight(fluidType, interim.height);
+ });
}
}
@@ -525,7 +551,7 @@
public float m_274421_() {
return this.f_19793_;
}
@@ -3319,6 +_,103 @@
@@ -3319,6 +_,109 @@
public boolean m_142265_(Level p_146843_, BlockPos p_146844_) {
return true;
}
@@ -593,6 +619,7 @@
+ /**
+ * Accessor method for {@link #getEyeHeight(Pose, EntityDimensions)}
+ */
+ @Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned
+ public float getEyeHeightAccess(Pose pose, EntityDimensions size) {
+ return this.m_6380_(pose, size);
+ }
@@ -624,6 +651,11 @@
+ return this.forgeFluidTypeHeight.object2DoubleEntrySet().stream().max(java.util.Comparator.comparingDouble(Object2DoubleMap.Entry::getDoubleValue)).map(Object2DoubleMap.Entry::getKey).orElseGet(net.minecraftforge.common.ForgeMod.EMPTY_TYPE);
+ }
+
+ @Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned
+ public EntityDimensions getDimensionsForge(Pose pose) {
+ return m_6972_(pose);
+ }
+
+ /* ================================== Forge End =====================================*/
+
@@ -16,6 +16,16 @@
public static final int f_147166_ = 2;
public static final int f_147167_ = 4;
public static final int f_147168_ = 98;
@@ -239,7 +_,8 @@
this.f_20885_ = this.m_146908_();
this.m_274367_(0.6F);
NbtOps nbtops = NbtOps.f_128958_;
- this.f_20939_ = this.m_8075_(new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap()))));
+ var dyn = new Dynamic<>(nbtops, nbtops.createMap(ImmutableMap.of(nbtops.createString("memories"), nbtops.emptyMap())));
+ this.f_20939_ = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.m_8075_(dyn), dyn);
}
public Brain<?> m_6274_() {
@@ -273,7 +_,7 @@
}
@@ -43,31 +53,16 @@
public boolean m_6040_() {
return this.m_6336_() == MobType.f_21641_;
}
@@ -352,8 +_,8 @@
@@ -352,6 +_,9 @@
}
}
- if (this.m_204029_(FluidTags.f_13131_) && !this.m_9236_().m_8055_(BlockPos.m_274561_(this.m_20185_(), this.m_20188_(), this.m_20189_())).m_60713_(Blocks.f_50628_)) {
- boolean flag1 = !this.m_6040_() && !MobEffectUtil.m_19588_(this) && (!flag || !((Player)this).m_150110_().f_35934_);
+ if (!this.getEyeInFluidType().isAir() && !this.m_9236_().m_8055_(BlockPos.m_274561_(this.m_20185_(), this.m_20188_(), this.m_20189_())).m_60713_(Blocks.f_50628_)) {
+ boolean flag1 = this.canDrownInFluidType(this.getEyeInFluidType()) && !MobEffectUtil.m_19588_(this) && (!flag || !((Player)this).m_150110_().f_35934_);
+ int airSupply = this.m_20146_();
+ net.minecraftforge.common.ForgeHooks.onLivingBreathe(this, airSupply - m_7302_(airSupply), m_7305_(airSupply) - airSupply);
+ if (false) // Forge: Handled in ForgeHooks#onLivingBreathe(LivingEntity, int, int)
if (this.m_204029_(FluidTags.f_13131_) && !this.m_9236_().m_8055_(BlockPos.m_274561_(this.m_20185_(), this.m_20188_(), this.m_20189_())).m_60713_(Blocks.f_50628_)) {
boolean flag1 = !this.m_6040_() && !MobEffectUtil.m_19588_(this) && (!flag || !((Player)this).m_150110_().f_35934_);
if (flag1) {
this.m_20301_(this.m_7302_(this.m_20146_()));
if (this.m_20146_() == -20) {
@@ -371,10 +_,11 @@
}
}
- if (!this.m_9236_().f_46443_ && this.m_20159_() && this.m_20202_() != null && this.m_20202_().m_275843_()) {
+ if (!this.m_9236_().f_46443_ && this.m_20159_() && this.m_20202_() != null && !this.m_20202_().canBeRiddenUnderFluidType(this.getEyeInFluidType(), this)) {
this.m_8127_();
}
- } else if (this.m_20146_() < this.m_6062_()) {
+ } // Forge: Move to if statement since we need to increase the air supply if in bubble column or can't drown
+ if (this.m_20146_() < this.m_6062_() && (!this.canDrownInFluidType(this.getEyeInFluidType()) || this.m_9236_().m_8055_(BlockPos.m_274561_(this.m_20185_(), this.m_20188_(), this.m_20189_())).m_60713_(Blocks.f_50628_))) {
this.m_20301_(this.m_7305_(this.m_20146_()));
}
@@ -387,7 +_,7 @@
}
}
@@ -77,6 +72,16 @@
this.m_252836_();
}
@@ -734,7 +_,8 @@
}
if (p_21096_.m_128425_("Brain", 10)) {
- this.f_20939_ = this.m_8075_(new Dynamic<>(NbtOps.f_128958_, p_21096_.m_128423_("Brain")));
+ var dyn = new Dynamic<>(NbtOps.f_128958_, p_21096_.m_128423_("Brain"));
+ this.f_20939_ = net.minecraftforge.common.ForgeHooks.onLivingMakeBrain(this, this.m_8075_(dyn), dyn);
}
}
@@ -749,7 +_,7 @@
if (!mobeffectinstance.m_19552_(this, () -> {
this.m_141973_(mobeffectinstance, true, (Entity)null);
@@ -177,21 +182,16 @@
if (!p_21016_.m_269533_(DamageTypeTags.f_268524_)) {
Entity entity = p_21016_.m_7640_();
if (entity instanceof LivingEntity) {
@@ -1065,12 +_,13 @@
@@ -1065,7 +_,8 @@
}
}
- flag = true;
+ flag = p_21017_ <= 0;
+ }
}
if (p_21016_.m_269533_(DamageTypeTags.f_268419_) && this.m_6095_().m_204039_(EntityTypeTags.f_144295_)) {
p_21017_ *= 5.0F;
}
+ }
this.f_267362_.m_267771_(1.5F);
boolean flag1 = true;
@@ -1108,11 +_,10 @@
Player player1 = (Player)entity1;
this.f_20889_ = 100;
@@ -386,6 +386,19 @@
if (!this.f_20911_ || this.f_20913_ >= this.m_21304_() / 2 || this.f_20913_ < 0) {
this.f_20913_ = -1;
this.f_20911_ = true;
@@ -1761,8 +_,10 @@
private void m_21312_() {
ItemStack itemstack = this.m_6844_(EquipmentSlot.OFFHAND);
- this.m_8061_(EquipmentSlot.OFFHAND, this.m_6844_(EquipmentSlot.MAINHAND));
- this.m_8061_(EquipmentSlot.MAINHAND, itemstack);
+ var event = net.minecraftforge.common.ForgeHooks.onLivingSwapHandItems(this);
+ if (event.isCanceled()) return;
+ this.m_8061_(EquipmentSlot.OFFHAND, event.getItemSwappedToOffHand());
+ this.m_8061_(EquipmentSlot.MAINHAND, event.getItemSwappedToMainHand());
}
protected void m_6088_() {
@@ -1955,14 +_,17 @@
}
@@ -561,7 +574,7 @@
ItemStack itemstack = this.m_21120_(p_21159_);
if (!itemstack.m_41619_() && !this.m_6117_()) {
+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.m_41779_());
+ if (duration <= 0) return;
+ if (duration < net.minecraftforge.common.ForgeConfig.SERVER.getUseItemDuration()) return;
this.f_20935_ = itemstack;
- this.f_20936_ = itemstack.m_41779_();
+ this.f_20936_ = duration;
@@ -718,7 +731,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_()) {
+ if (facing == null) return handlers[2].cast();
+ else if (facing.m_122434_().m_122478_()) return handlers[0].cast();
+ else if (facing.m_122434_().m_122479_()) return handlers[1].cast();
@@ -0,0 +1,33 @@
--- a/net/minecraft/world/entity/ai/Brain.java
+++ b/net/minecraft/world/entity/ai/Brain.java
@@ -478,6 +_,30 @@
return builder.build();
}
+ public net.minecraftforge.common.util.BrainBuilder<E> createBuilder(){
+ var builder = new net.minecraftforge.common.util.BrainBuilder<>(this);
+ builder.getMemoryTypes().addAll(this.f_21843_.keySet());
+ builder.getSensorTypes().addAll(this.f_21844_.keySet());
+ builder.addAvailableBehaviorsByPriorityFrom(this.f_21845_);
+ builder.setSchedule(this.m_21932_());
+ builder.addActivityRequirementsFrom(this.f_21847_);
+ builder.addActivityMemoriesToEraseWhenStoppedFrom(this.f_21848_);
+ builder.getCoreActivities().addAll(this.f_21849_);
+ builder.setDefaultActivity(this.f_21851_);
+ builder.setActiveActivites(this.f_21850_);
+ return builder;
+ }
+
+ public void copyFromBuilder(net.minecraftforge.common.util.BrainBuilder<E> builder){
+ builder.addAvailableBehaviorsByPriorityTo(this.f_21845_);
+ this.m_21912_(builder.getSchedule());
+ builder.addActivityRequirementsTo(this.f_21847_);
+ builder.addActivityMemoriesToEraseWhenStoppedTo(this.f_21848_);
+ this.m_21930_(builder.getCoreActivities());
+ this.m_21944_(builder.getDefaultActivity());
+ this.f_21850_.addAll(builder.getActiveActivites());
+ }
+
static final class MemoryValue<U> {
private final MemoryModuleType<U> f_22030_;
private final Optional<? extends ExpirableValue<U>> f_22031_;
@@ -38,7 +38,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.core.Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null)
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null && this.m_6084_())
+ return itemHandler.cast();
+ return super.getCapability(capability, facing);
+ }
@@ -0,0 +1,21 @@
--- a/net/minecraft/world/entity/npc/VillagerTrades.java
+++ b/net/minecraft/world/entity/npc/VillagerTrades.java
@@ -151,6 +_,7 @@
private final int f_35667_;
public EmeraldsForVillagerTypeItem(int p_35669_, int p_35670_, int p_35671_, Map<VillagerType, Item> p_35672_) {
+ if (Boolean.valueOf(false)) // FORGE: Modders can add custom villager types, so remove this validation, weird condition is to make the compiler not strip this dead code, breaking some mixins
BuiltInRegistries.f_256934_.m_123024_().filter((p_35680_) -> {
return !p_35672_.containsKey(p_35680_);
}).findAny().ifPresent((p_258962_) -> {
@@ -165,7 +_,9 @@
@Nullable
public MerchantOffer m_213663_(Entity p_219685_, RandomSource p_219686_) {
if (p_219685_ instanceof VillagerDataHolder) {
- ItemStack itemstack = new ItemStack(this.f_35664_.get(((VillagerDataHolder)p_219685_).m_7141_().m_35560_()), this.f_35665_);
+ Item item = this.f_35664_.get(((VillagerDataHolder)p_219685_).m_7141_().m_35560_());
+ if (item == null) return null; // FORGE: Account for modded villager types by returning null if there is no trade
+ ItemStack itemstack = new ItemStack(item, this.f_35665_);
return new MerchantOffer(itemstack, new ItemStack(Items.f_42616_), this.f_35666_, this.f_35667_, 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
@@ -67,4 +_,9 @@
public static VillagerType m_204073_(Holder<Biome> p_204074_) {
return p_204074_.m_203543_().map(f_35827_::get).orElse(f_35821_);
}
+
+ /** 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) {
+ f_35827_.put(biomeKey, villagerType);
+ }
}
@@ -19,15 +19,21 @@
if (p_36049_.m_41782_()) {
itemstack.m_41751_(p_36049_.m_41783_().m_6426_());
}
@@ -229,7 +_,7 @@
}
}
}
-
+ f_35975_.forEach(e -> e.onArmorTick(f_35978_.m_9236_(), f_35978_));
@@ -222,11 +_,13 @@
}
public boolean m_36054_(ItemStack p_36055_) {
public void m_36068_() {
+ int idx = 0;
for(NonNullList<ItemStack> nonnulllist : this.f_35979_) {
for(int i = 0; i < nonnulllist.size(); ++i) {
if (!nonnulllist.get(i).m_41619_()) {
- nonnulllist.get(i).m_41666_(this.f_35978_.m_9236_(), this.f_35978_, i, this.f_35977_ == i);
+ nonnulllist.get(i).onInventoryTick(this.f_35978_.m_9236_(), this.f_35978_, idx, this.f_35977_);
}
+ idx++;
}
}
@@ -277,6 +_,8 @@
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.m_127521_(throwable, "Adding item to inventory");
@@ -37,3 +43,16 @@
crashreportcategory.m_128159_("Item ID", Item.m_41393_(p_36042_.m_41720_()));
crashreportcategory.m_128159_("Item data", p_36042_.m_41773_());
crashreportcategory.m_128165_("Item name", () -> {
@@ -530,7 +_,11 @@
if (this.f_35978_.m_213877_()) {
return false;
} else {
- return !(p_36009_.m_20280_(this.f_35978_) > 64.0D);
+ // Vanilla uses 64 which is 8*8. Default reach is 3.0 so add 5.0 padding
+ // magic number so required Mixins can still target here
+ double reachOld = 64.0;
+ double reach = p_36009_.m_21133_(net.minecraftforge.common.ForgeMod.ENTITY_REACH.get()) + 5.0;
+ return !(p_36009_.m_20280_(this.f_35978_) > reach * reach);
}
}
@@ -135,15 +135,23 @@
if (!this.m_9236_().f_46443_) {
this.m_36246_(Stats.f_12982_.m_12902_(this.f_20935_.m_41720_()));
}
@@ -865,6 +_,8 @@
@@ -863,10 +_,15 @@
if (p_36383_ >= 3.0F) {
int i = 1 + Mth.m_14143_(p_36383_);
InteractionHand interactionhand = this.m_7655_();
+ // FORGE: cache this.useItem -- if this.stopUsingItem() is called, it will be set to ItemStack.EMPTY
+ ItemStack currentItem = this.f_20935_;
this.f_20935_.m_41622_(i, this, (p_219739_) -> {
p_219739_.m_21190_(interactionhand);
+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, this.f_20935_, interactionhand);
+ m_5810_(); // Forge: fix MC-168573
+ if (this.f_20935_ == currentItem) m_5810_(); // Forge: fix MC-168573
});
if (this.f_20935_.m_41619_()) {
- if (this.f_20935_.m_41619_()) {
+ // FORGE: use cached item since this.useItem could be ItemStack.EMPTY
+ if (currentItem.m_41619_()) {
if (interactionhand == InteractionHand.MAIN_HAND) {
this.m_8061_(EquipmentSlot.MAINHAND, ItemStack.f_41583_);
} else {
@@ -883,10 +_,13 @@
protected void m_6475_(DamageSource p_36312_, float p_36313_) {
@@ -243,15 +251,18 @@
}
float f4 = 0.0F;
@@ -1121,8 +_,9 @@
@@ -1121,8 +_,12 @@
if (flag3) {
float f3 = 1.0F + EnchantmentHelper.m_44821_(this) * f;
- for(LivingEntity livingentity : this.m_9236_().m_45976_(LivingEntity.class, p_36347_.m_20191_().m_82377_(1.0D, 0.25D, 1.0D))) {
- if (livingentity != this && livingentity != p_36347_ && !this.m_7307_(livingentity) && (!(livingentity instanceof ArmorStand) || !((ArmorStand)livingentity).m_31677_()) && this.m_20280_(livingentity) < 9.0D) {
+ for(LivingEntity livingentity : this.m_9236_().m_45976_(LivingEntity.class, this.m_21120_(InteractionHand.MAIN_HAND).getSweepHitBox(this, p_36347_))) {
+ double entityReachSq = Mth.m_144952_(this.getEntityReach()); // Use entity reach instead of constant 9.0. Vanilla uses bottom center-to-center checks here, so don't update this to use canReach, since it uses closest-corner checks.
+ if (livingentity != this && livingentity != p_36347_ && !this.m_7307_(livingentity) && (!(livingentity instanceof ArmorStand) || !((ArmorStand)livingentity).m_31677_()) && this.m_20280_(livingentity) < entityReachSq) {
+ // Use entity reach instead of constant 9.0. Vanilla uses bottom center-to-center checks here, so don't update this to use canReach, since it uses closest-corner checks.
+ // magic number so required Mixins can still target here
+ var reachOld = 9.0;
+ var reach = this.m_21133_(net.minecraftforge.common.ForgeMod.ENTITY_REACH.get());
+ if (livingentity != this && livingentity != p_36347_ && !this.m_7307_(livingentity) && (!(livingentity instanceof ArmorStand) || !((ArmorStand)livingentity).m_31677_()) && this.m_20280_(livingentity) < reach * reach) {
livingentity.m_147240_((double)0.4F, (double)Mth.m_14031_(this.m_146908_() * ((float)Math.PI / 180F)), (double)(-Mth.m_14089_(this.m_146908_() * ((float)Math.PI / 180F))));
livingentity.m_6469_(this.m_269291_().m_269075_(this), f3);
}
@@ -452,7 +463,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_()) {
+ if (facing == null) return playerJoinedHandler.cast();
+ else if (facing.m_122434_().m_122478_()) return playerMainHandler.cast();
+ else if (facing.m_122434_().m_122479_()) return playerEquipmentHandler.cast();
@@ -1,5 +1,14 @@
--- a/net/minecraft/world/entity/projectile/AbstractArrow.java
+++ b/net/minecraft/world/entity/projectile/AbstractArrow.java
@@ -66,6 +_,8 @@
@Nullable
private List<Entity> f_36702_;
+ private final IntOpenHashSet ignoredEntities = new IntOpenHashSet();
+
protected AbstractArrow(EntityType<? extends AbstractArrow> p_36721_, Level p_36722_) {
super(p_36721_, p_36722_);
}
@@ -150,7 +_,7 @@
--this.f_36706_;
}
@@ -9,14 +18,61 @@
this.m_20095_();
}
@@ -186,7 +_,9 @@
@@ -186,9 +_,35 @@
}
}
- if (hitresult != null && !flag) {
- this.m_6532_(hitresult);
- this.f_19812_ = true;
+ if (hitresult != null && hitresult.m_6662_() != HitResult.Type.MISS && !flag) {
+ if (net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult))
+ break;
this.m_6532_(hitresult);
this.f_19812_ = true;
+ var result = net.minecraftforge.event.ForgeEventFactory.onProjectileImpactResultNullable(this, hitresult);
+ if (result == null) {
+ if (hitresult.m_6662_() != HitResult.Type.ENTITY)
+ break;
+
+ result = net.minecraftforge.event.entity.ProjectileImpactEvent.ImpactResult.SKIP_ENTITY;
+ }
+ switch (result) {
+ case SKIP_ENTITY:
+ if (hitresult.m_6662_() != HitResult.Type.ENTITY) { // If there is no entity, we just return default behaviour
+ this.m_6532_(hitresult);
+ this.f_19812_ = true;
+ break;
+ }
+ ignoredEntities.add(entityhitresult.m_82443_().m_19879_());
+ entityhitresult = null; // Don't process any further
+ break;
+ case STOP_AT_CURRENT_NO_DAMAGE:
+ this.m_146870_();
+ entityhitresult = null; // Don't process any further
+ break;
+ case STOP_AT_CURRENT:
+ this.m_36767_((byte) 0);
+ case DEFAULT:
+ this.m_6532_(hitresult);
+ this.f_19812_ = true;
+ break;
+ }
}
if (entityhitresult == null || this.m_36796_() <= 0) {
@@ -198,6 +_,9 @@
hitresult = null;
}
+ if (this.m_213877_())
+ return;
+
vec3 = this.m_20184_();
double d5 = vec3.f_82479_;
double d6 = vec3.f_82480_;
@@ -422,7 +_,7 @@
}
protected boolean m_5603_(Entity p_36743_) {
- return super.m_5603_(p_36743_) && (this.f_36701_ == null || !this.f_36701_.contains(p_36743_.m_19879_()));
+ return super.m_5603_(p_36743_) && (this.f_36701_ == null || !this.f_36701_.contains(p_36743_.m_19879_())) && !this.ignoredEntities.contains(p_36743_.m_19879_());
}
public void m_7380_(CompoundTag p_36772_) {
@@ -19,7 +19,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.core.Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER)
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_())
+ return itemHandler.cast();
+ return super.getCapability(capability, facing);
+ }
Loaded 100 of 273 files, more files were not shown because too many files have changed in this diff. Show more