Compare commits

..
6 Commits
Author SHA1 Message Date
LexManos 8e09d47cd6 1.21.10 2025-10-07 10:20:47 -07:00
Paint_Ninja 0404d2d776 Bump EventBus for more javadocs 2025-10-06 20:14:28 +01:00
Paint_Ninja aea804cb6e Make BuildCreativeModeTabContentsEvent a record 2025-10-06 20:12:13 +01:00
LexManos 0bffcb83c5 Fix CustomizeGuiOverlayEvent mistakenly being a RecordEvent 2025-10-05 09:51:12 -07:00
Paint_Ninja 9a022d1451 Move more events away from the mod BusGroup (#10676)
Also adds more validation to strict mode. See the GitHub PR for further details.
2025-10-05 14:02:45 +01:00
LexManos 58aa3b276c Add the new vanilla info object to Keyboard and Mouse related events. 2025-10-02 12:09:01 -07:00
62 changed files with 518 additions and 451 deletions

No files matched your search

+3 -3
View File
@@ -5,11 +5,11 @@ org.gradle.daemon=false
org.gradle.parallel=true org.gradle.parallel=true
JAVA_VERSION=21 JAVA_VERSION=21
MC_VERSION=1.21.9 MC_VERSION=1.21.10
MC_NEXT_VERSION=1.22 MC_NEXT_VERSION=1.22
MCP_VERSION=20250930.103108 MCP_VERSION=20251007.101210
MAPPING_CHANNEL=official MAPPING_CHANNEL=official
MAPPING_VERSION=1.21.9 MAPPING_VERSION=1.21.10
# Set to true before the first build of a new MC version, so we don't do compatibility checks # Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false CHECK_COMPATIBILITY=false
@@ -48,11 +48,13 @@ import java.util.stream.Collectors;
* annotations and passes the class instances to the {@link Bus} * annotations and passes the class instances to the {@link Bus}
* defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS} * defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/ */
public class AutomaticEventSubscriber { public final class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class); private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.class); private static final Type MOD_TYPE = Type.getType(Mod.class);
private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class); private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class);
private static final List<EnumData> DEFAULT_SIDES = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER"));
private static final EnumData DEFAULT_BUS = new EnumData(null, "BOTH");
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) { public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
if (scanData == null) return; if (scanData == null) return;
@@ -71,9 +73,6 @@ public class AutomaticEventSubscriber {
.filter(data -> MOD_TYPE.equals(data.annotationType())) .filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value"))); .collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
var defaultSides = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER"));
var defaultBus = new EnumData(null, "FORGE");
for (var data : targets) { for (var data : targets) {
if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) { if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) {
throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead"); throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead");
@@ -82,13 +81,13 @@ public class AutomaticEventSubscriber {
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId()); var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId); modId = value(data, "modid", modId);
var sidesValue = value(data, "value", defaultSides); var sidesValue = value(data, "value", DEFAULT_SIDES);
var sides = sidesValue.stream() var sides = sidesValue.stream()
.map(EnumData::value) .map(EnumData::value)
.map(Dist::valueOf) .map(Dist::valueOf)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
var busName = value(data, "bus", defaultBus).value(); var busName = value(data, "bus", DEFAULT_BUS).value();
var busTarget = Bus.valueOf(busName); var busTarget = Bus.valueOf(busName);
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) { if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) {
try { try {
@@ -173,7 +172,7 @@ public class AutomaticEventSubscriber {
Class<? extends Event> eventType = (Class<? extends Event>) parameterTypes[0]; Class<? extends Event> eventType = (Class<? extends Event>) parameterTypes[0];
var subscribeEventAnnotation = method.getAnnotation(SubscribeEvent.class); var subscribeEventAnnotation = method.getAnnotation(SubscribeEvent.class);
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method); registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method, false);
listenersCount++; listenersCount++;
if (firstValidListenerEventType == null) if (firstValidListenerEventType == null)
@@ -259,7 +258,7 @@ public class AutomaticEventSubscriber {
throw fail(method, "Return type boolean is only valid for cancellable events"); throw fail(method, "Return type boolean is only valid for cancellable events");
} }
registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method); registerListener(busGroup, paramCount, returnType, eventType, subscribeEventAnnotation, method, true);
listenersCount++; listenersCount++;
if (firstValidListenerEventType == null) if (firstValidListenerEventType == null)
@@ -276,11 +275,24 @@ public class AutomaticEventSubscriber {
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
private static EventListener registerListener(@Nullable BusGroup busGroup, private static EventListener registerListener(@Nullable BusGroup busGroup,
int paramCount, Class<?> returnType, Class<? extends Event> eventType, int paramCount, Class<?> returnType, Class<? extends Event> eventType,
SubscribeEvent subscribeEventAnnotation, Method method) { SubscribeEvent subscribeEventAnnotation, Method method, boolean strict) {
if (busGroup == null) { if (busGroup == null) {
busGroup = IModBusEvent.class.isAssignableFrom(eventType) busGroup = IModBusEvent.class.isAssignableFrom(eventType)
? FMLJavaModLoadingContext.get().getModBusGroup() ? FMLJavaModLoadingContext.get().getModBusGroup()
: BusGroup.DEFAULT; : BusGroup.DEFAULT;
} else if (strict) {
String solution = "To fix this, remove the bus param from your @EventBusSubscriber annotation or move this event listener to another class.";
var isDefaultBusGroup = busGroup == BusGroup.DEFAULT;
var isModBusEvent = IModBusEvent.class.isAssignableFrom(eventType);
if (isDefaultBusGroup && isModBusEvent) { // requested forge bus and has IModBusEvent
throw fail(method, "Event type " + eventType.getName()
+ " is on the mod BusGroup but you are asking to register it on the default BusGroup (BusGroup.DEFAULT/EventBusSubscriber.Bus.FORGE). "
+ solution);
} else if (!isDefaultBusGroup && !isModBusEvent) { // requested mod bus and does not have IModBusEvent
throw fail(method, "Event type " + eventType.getName()
+ " is on the default BusGroup but you are asking to register it on the mod BusGroup (context.getModBusGroup()/EventBusSubscriber.Bus.MOD). "
+ solution);
}
} }
// determine the listener type from its parameters and return type // determine the listener type from its parameters and return type
@@ -43,7 +43,7 @@ public class FMLModContainer extends ModContainer {
LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className); LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className);
this.scanResults = modFileScanResults; this.scanResults = modFileScanResults;
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod); activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId()); this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId(), IModBusEvent.class);
this.contextExtension = () -> context; this.contextExtension = () -> context;
try { try {
var moduleName = info.getOwningFile().moduleName(); var moduleName = info.getOwningFile().moduleName();
@@ -193,6 +193,6 @@ public class FMLModContainer extends ModContainer {
@Override @Override
public String toString() { public String toString() {
return "FMLModContainer[" + this.getModInfo().getModId() + ", " + this.getClass().getName() + "]"; return "FMLModContainer[" + this.getModInfo().getModId() + ", " + this.getClass().getName() + ']';
} }
} }
+1 -1
View File
@@ -145,7 +145,7 @@ dependencies {
// Forge 1.21.6+ uses EventBus 7, which shifts most of its runtime validation to compile-time via an annotation processor // Forge 1.21.6+ uses EventBus 7, which shifts most of its runtime validation to compile-time via an annotation processor
// to improve performance in production environments. This line is required to enable said compile-time validation // to improve performance in production environments. This line is required to enable said compile-time validation
// in your development environment, helping you catch issues early. // in your development environment, helping you catch issues early.
annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.10' annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.12'
// Example mod dependency with JEI // Example mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
@@ -4,7 +4,7 @@
this.activeButton = null; this.activeButton = null;
} }
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo.button(), p_423948_, mousebuttoninfo.modifiers())) return; + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo, p_423948_)) return;
if (this.minecraft.getOverlay() == null) { if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) { if (this.minecraft.screen == null) {
if (!this.mouseGrabbed && flag) { if (!this.mouseGrabbed && flag) {
@@ -30,7 +30,7 @@
KeyMapping.click(inputconstants$key); KeyMapping.click(inputconstants$key);
} }
} }
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo.button(), p_423948_, mousebuttoninfo.modifiers()); + net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo, p_423948_);
} }
} }
@@ -4,7 +4,7 @@
this.soundManager = p_120236_; this.soundManager = p_120236_;
this.options = p_120237_; this.options = p_120237_;
this.soundBuffers = new SoundBufferLibrary(p_249332_); this.soundBuffers = new SoundBufferLibrary(p_249332_);
+ net.minecraftforge.fml.ModLoader.postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); + net.minecraftforge.client.event.sound.SoundEngineLoadEvent.BUS.post(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this));
} }
public void reload() { public void reload() {
@@ -12,7 +12,7 @@
this.destroy(); this.destroy();
this.loadLibrary(); this.loadLibrary();
+ net.minecraftforge.fml.ModLoader.postEvent(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this)); + net.minecraftforge.client.event.sound.SoundEngineLoadEvent.BUS.post(new net.minecraftforge.client.event.sound.SoundEngineLoadEvent(this));
} }
private synchronized void loadLibrary() { private synchronized void loadLibrary() {
@@ -53,7 +53,7 @@
while (this.running) { while (this.running) {
long i; long i;
@@ -775,6 +_,8 @@ @@ -778,6 +_,8 @@
this.isReady = true; this.isReady = true;
JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis); JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis);
} }
@@ -62,7 +62,7 @@
} catch (Throwable throwable2) { } catch (Throwable throwable2) {
LOGGER.error("Encountered an unexpected exception", throwable2); LOGGER.error("Encountered an unexpected exception", throwable2);
CrashReport crashreport = constructOrExtractCrashReport(throwable2); CrashReport crashreport = constructOrExtractCrashReport(throwable2);
@@ -786,6 +_,7 @@ @@ -789,6 +_,7 @@
LOGGER.error("We were unable to save this crash report to disk."); LOGGER.error("We were unable to save this crash report to disk.");
} }
@@ -70,7 +70,7 @@
this.onServerCrash(crashreport); this.onServerCrash(crashreport);
} finally { } finally {
try { try {
@@ -794,6 +_,7 @@ @@ -797,6 +_,7 @@
} catch (Throwable throwable) { } catch (Throwable throwable) {
LOGGER.error("Exception stopping the server", throwable); LOGGER.error("Exception stopping the server", throwable);
} finally { } finally {
@@ -78,7 +78,7 @@
this.onServerExit(); this.onServerExit();
} }
} }
@@ -991,12 +_,14 @@ @@ -994,12 +_,14 @@
} }
} }
@@ -93,7 +93,7 @@
} }
this.ticksUntilAutosave--; this.ticksUntilAutosave--;
@@ -1014,6 +_,7 @@ @@ -1017,6 +_,7 @@
this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)k / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)k / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F;
this.logTickMethodTime(i); this.logTickMethodTime(i);
profilerfiller.pop(); profilerfiller.pop();
@@ -101,7 +101,7 @@
} }
private void autoSave() { private void autoSave() {
@@ -1063,7 +_,8 @@ @@ -1066,7 +_,8 @@
Optional.of(serverstatus$players), Optional.of(serverstatus$players),
Optional.of(ServerStatus.Version.current()), Optional.of(ServerStatus.Version.current()),
Optional.ofNullable(this.statusIcon), Optional.ofNullable(this.statusIcon),
@@ -111,7 +111,7 @@
); );
} }
@@ -1095,7 +_,8 @@ @@ -1098,7 +_,8 @@
profilerfiller.popPush("levels"); profilerfiller.popPush("levels");
this.updateEffectiveRespawnData(); this.updateEffectiveRespawnData();
@@ -121,7 +121,7 @@
profilerfiller.push(() -> serverlevel + " " + serverlevel.dimension().location()); profilerfiller.push(() -> serverlevel + " " + serverlevel.dimension().location());
if (this.tickCount % 20 == 0) { if (this.tickCount % 20 == 0) {
profilerfiller.push("timeSync"); profilerfiller.push("timeSync");
@@ -1104,6 +_,7 @@ @@ -1107,6 +_,7 @@
} }
profilerfiller.push("tick"); profilerfiller.push("tick");
@@ -129,7 +129,7 @@
try { try {
serverlevel.tick(p_129954_); serverlevel.tick(p_129954_);
@@ -1112,9 +_,11 @@ @@ -1115,9 +_,11 @@
serverlevel.fillReportDetails(crashreport); serverlevel.fillReportDetails(crashreport);
throw new ReportedException(crashreport); throw new ReportedException(crashreport);
} }
@@ -141,7 +141,7 @@
} }
profilerfiller.popPush("connection"); profilerfiller.popPush("connection");
@@ -1123,7 +_,7 @@ @@ -1126,7 +_,7 @@
this.playerList.tick(); this.playerList.tick();
profilerfiller.popPush("debugSubscribers"); profilerfiller.popPush("debugSubscribers");
this.debugSubscribers.tick(); this.debugSubscribers.tick();
@@ -150,7 +150,7 @@
profilerfiller.popPush("gameTests"); profilerfiller.popPush("gameTests");
GameTestTicker.SINGLETON.tick(); GameTestTicker.SINGLETON.tick();
} }
@@ -1226,7 +_,7 @@ @@ -1229,7 +_,7 @@
@DontObfuscate @DontObfuscate
public String getServerModName() { public String getServerModName() {
@@ -159,7 +159,7 @@
} }
public SystemReport fillSystemReport(SystemReport p_177936_) { public SystemReport fillSystemReport(SystemReport p_177936_) {
@@ -1576,6 +_,7 @@ @@ -1579,6 +_,7 @@
this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary());
this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager);
this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures()); this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures());
@@ -167,7 +167,7 @@
}, this); }, this);
if (this.isSameThread()) { if (this.isSameThread()) {
this.managedBlock(completablefuture::isDone); this.managedBlock(completablefuture::isDone);
@@ -1585,12 +_,15 @@ @@ -1588,12 +_,15 @@
} }
public static WorldDataConfiguration configurePackRepository(PackRepository p_248681_, WorldDataConfiguration p_331931_, boolean p_249869_, boolean p_330480_) { public static WorldDataConfiguration configurePackRepository(PackRepository p_248681_, WorldDataConfiguration p_331931_, boolean p_249869_, boolean p_330480_) {
@@ -184,7 +184,7 @@
} else { } else {
Set<String> set = Sets.newLinkedHashSet(); Set<String> set = Sets.newLinkedHashSet();
@@ -2155,6 +_,48 @@ @@ -2158,6 +_,48 @@
public ServerLinks serverLinks() { public ServerLinks serverLinks() {
return ServerLinks.EMPTY; return ServerLinks.EMPTY;
@@ -6,7 +6,7 @@
public static PackRepository createPackRepository(Path p_251569_, DirectoryValidator p_300268_) { public static PackRepository createPackRepository(Path p_251569_, DirectoryValidator p_300268_) {
- return new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); - return new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_));
+ var ret = new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_)); + var ret = new PackRepository(new ServerPacksSource(p_300268_), new FolderRepositorySource(p_251569_, PackType.SERVER_DATA, PackSource.WORLD, p_300268_));
+ net.minecraftforge.fml.ModLoader.postEvent(new net.minecraftforge.event.AddPackFindersEvent(PackType.SERVER_DATA, ret::addPackFinder)); + net.minecraftforge.event.AddPackFindersEvent.BUS.post(new net.minecraftforge.event.AddPackFindersEvent(PackType.SERVER_DATA, ret::addPackFinder));
+ return ret; + return ret;
} }
@@ -62,7 +62,7 @@
} }
this.checkBelowWorld(); this.checkBelowWorld();
@@ -955,9 +_,7 @@ @@ -958,9 +_,7 @@
return blockpos; return blockpos;
} else { } else {
BlockState blockstate = this.level().getBlockState(blockpos); BlockState blockstate = this.level().getBlockState(blockpos);
@@ -73,7 +73,7 @@
? blockpos.atY(Mth.floor(this.position.y - p_216987_)) ? blockpos.atY(Mth.floor(this.position.y - p_216987_))
: blockpos; : blockpos;
} }
@@ -1299,19 +_,19 @@ @@ -1304,19 +_,19 @@
return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? p_278049_ : blockpos; return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? p_278049_ : blockpos;
} }
@@ -99,7 +99,7 @@
this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch());
} }
@@ -1444,6 +_,10 @@ @@ -1449,6 +_,10 @@
return this.wasTouchingWater; return this.wasTouchingWater;
} }
@@ -110,7 +110,7 @@
boolean isInRain() { boolean isInRain() {
BlockPos blockpos = this.blockPosition(); BlockPos blockpos = this.blockPosition();
return this.level().isRainingAt(blockpos) return this.level().isRainingAt(blockpos)
@@ -1483,24 +_,32 @@ @@ -1488,24 +_,32 @@
public void updateSwimming() { public void updateSwimming() {
if (this.isSwimming()) { if (this.isSwimming()) {
@@ -150,7 +150,7 @@
if (!this.wasTouchingWater && !this.firstTick) { if (!this.wasTouchingWater && !this.firstTick) {
this.doWaterSplashEffect(); this.doWaterSplashEffect();
} }
@@ -1515,6 +_,7 @@ @@ -1520,6 +_,7 @@
private void updateFluidOnEyes() { private void updateFluidOnEyes() {
this.wasEyeInWater = this.isEyeInFluid(FluidTags.WATER); this.wasEyeInWater = this.isEyeInFluid(FluidTags.WATER);
this.fluidOnEyes.clear(); this.fluidOnEyes.clear();
@@ -158,7 +158,7 @@
double d0 = this.getEyeY(); double d0 = this.getEyeY();
if (!( if (!(
this.getVehicle() instanceof AbstractBoat abstractboat this.getVehicle() instanceof AbstractBoat abstractboat
@@ -1526,7 +_,7 @@ @@ -1531,7 +_,7 @@
FluidState fluidstate = this.level().getFluidState(blockpos); FluidState fluidstate = this.level().getFluidState(blockpos);
double d1 = blockpos.getY() + fluidstate.getHeight(this.level(), blockpos); double d1 = blockpos.getY() + fluidstate.getHeight(this.level(), blockpos);
if (d1 > d0) { if (d1 > d0) {
@@ -167,7 +167,7 @@
} }
} }
} }
@@ -1580,12 +_,13 @@ @@ -1585,12 +_,13 @@
} }
public boolean canSpawnSprintParticle() { public boolean canSpawnSprintParticle() {
@@ -182,7 +182,7 @@
if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { if (blockstate.getRenderShape() != RenderShape.INVISIBLE) {
Vec3 vec3 = this.getDeltaMovement(); Vec3 vec3 = this.getDeltaMovement();
BlockPos blockpos1 = this.blockPosition(); BlockPos blockpos1 = this.blockPosition();
@@ -1601,7 +_,7 @@ @@ -1606,7 +_,7 @@
this.level() this.level()
.addParticle( .addParticle(
@@ -191,7 +191,7 @@
d0, d0,
this.getY() + 0.1, this.getY() + 0.1,
d1, d1,
@@ -1612,12 +_,15 @@ @@ -1617,12 +_,15 @@
} }
} }
@@ -208,7 +208,7 @@
} }
public void moveRelative(float p_19921_, Vec3 p_19922_) { public void moveRelative(float p_19921_, Vec3 p_19922_) {
@@ -1982,6 +_,10 @@ @@ -1987,6 +_,10 @@
p_409187_.putBoolean("HasVisualFire", this.hasVisualFire); p_409187_.putBoolean("HasVisualFire", this.hasVisualFire);
} }
@@ -219,7 +219,7 @@
if (!this.tags.isEmpty()) { if (!this.tags.isEmpty()) {
p_409187_.store("Tags", TAG_LIST_CODEC, List.copyOf(this.tags)); p_409187_.store("Tags", TAG_LIST_CODEC, List.copyOf(this.tags));
} }
@@ -2057,6 +_,9 @@ @@ -2062,6 +_,9 @@
this.setGlowingTag(p_408698_.getBooleanOr("Glowing", false)); this.setGlowingTag(p_408698_.getBooleanOr("Glowing", false));
this.setTicksFrozen(p_408698_.getIntOr("TicksFrozen", 0)); this.setTicksFrozen(p_408698_.getIntOr("TicksFrozen", 0));
this.hasVisualFire = p_408698_.getBooleanOr("HasVisualFire", false); this.hasVisualFire = p_408698_.getBooleanOr("HasVisualFire", false);
@@ -229,7 +229,7 @@
this.customData = p_408698_.read("data", CustomData.CODEC).orElse(CustomData.EMPTY); this.customData = p_408698_.read("data", CustomData.CODEC).orElse(CustomData.EMPTY);
this.tags.clear(); this.tags.clear();
p_408698_.read("Tags", TAG_LIST_CODEC).ifPresent(this.tags::addAll); p_408698_.read("Tags", TAG_LIST_CODEC).ifPresent(this.tags::addAll);
@@ -2109,6 +_,8 @@ @@ -2114,6 +_,8 @@
p_409579_, this.getX() + p_408228_.x, this.getY() + p_408228_.y, this.getZ() + p_408228_.z, p_407826_ p_409579_, this.getX() + p_408228_.x, this.getY() + p_408228_.y, this.getZ() + p_408228_.z, p_407826_
); );
itementity.setDefaultPickUpDelay(); itementity.setDefaultPickUpDelay();
@@ -238,7 +238,7 @@
p_409579_.addFreshEntity(itementity); p_409579_.addFreshEntity(itementity);
return itementity; return itementity;
} }
@@ -2172,7 +_,7 @@ @@ -2177,7 +_,7 @@
itemstack.hurtAndBreak(1, p_19978_, p_19979_); itemstack.hurtAndBreak(1, p_19978_, p_19979_);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} else if (this instanceof Mob mob } else if (this instanceof Mob mob
@@ -247,7 +247,7 @@
&& mob.canShearEquipment(p_19978_) && mob.canShearEquipment(p_19978_)
&& !p_19978_.isSecondaryUseActive() && !p_19978_.isSecondaryUseActive()
&& this.attemptToShearEquipment(p_19978_, p_19979_, itemstack, mob)) { && this.attemptToShearEquipment(p_19978_, p_19979_, itemstack, mob)) {
@@ -2277,6 +_,7 @@ @@ -2282,6 +_,7 @@
public void rideTick() { public void rideTick() {
this.setDeltaMovement(Vec3.ZERO); this.setDeltaMovement(Vec3.ZERO);
@@ -255,7 +255,7 @@
this.tick(); this.tick();
if (this.isPassenger()) { if (this.isPassenger()) {
this.getVehicle().positionRider(this); this.getVehicle().positionRider(this);
@@ -2337,6 +_,7 @@ @@ -2342,6 +_,7 @@
} }
} }
@@ -263,7 +263,7 @@
if (p_19967_ || this.canRide(p_19966_) && p_19966_.canAddPassenger(this)) { if (p_19967_ || this.canRide(p_19966_) && p_19966_.canAddPassenger(this)) {
if (this.isPassenger()) { if (this.isPassenger()) {
this.stopRiding(); this.stopRiding();
@@ -2372,6 +_,7 @@ @@ -2377,6 +_,7 @@
public void removeVehicle() { public void removeVehicle() {
if (this.vehicle != null) { if (this.vehicle != null) {
Entity entity = this.vehicle; Entity entity = this.vehicle;
@@ -271,7 +271,7 @@
this.vehicle = null; this.vehicle = null;
entity.removePassenger(this); entity.removePassenger(this);
Entity.RemovalReason entity$removalreason = this.getRemovalReason(); Entity.RemovalReason entity$removalreason = this.getRemovalReason();
@@ -2422,6 +_,8 @@ @@ -2427,6 +_,8 @@
return this.passengers.isEmpty(); return this.passengers.isEmpty();
} }
@@ -280,7 +280,7 @@
protected boolean couldAcceptPassenger() { protected boolean couldAcceptPassenger() {
return true; return true;
} }
@@ -2618,7 +_,7 @@ @@ -2623,7 +_,7 @@
} }
public boolean isVisuallyCrawling() { public boolean isVisuallyCrawling() {
@@ -289,7 +289,7 @@
} }
public void setSwimming(boolean p_20283_) { public void setSwimming(boolean p_20283_) {
@@ -2735,7 +_,7 @@ @@ -2740,7 +_,7 @@
this.igniteForSeconds(8.0F); this.igniteForSeconds(8.0F);
} }
@@ -298,7 +298,7 @@
} }
public void onAboveBubbleColumn(boolean p_392709_, BlockPos p_391902_) { public void onAboveBubbleColumn(boolean p_392709_, BlockPos p_391902_) {
@@ -2868,7 +_,7 @@ @@ -2873,7 +_,7 @@
} }
protected Component getTypeName() { protected Component getTypeName() {
@@ -307,7 +307,7 @@
} }
public boolean is(Entity p_20356_) { public boolean is(Entity p_20356_) {
@@ -3181,6 +_,7 @@ @@ -3186,6 +_,7 @@
return this.stringUUID; return this.stringUUID;
} }
@@ -315,7 +315,7 @@
public boolean isPushedByFluid() { public boolean isPushedByFluid() {
return true; return true;
} }
@@ -3565,9 +_,17 @@ @@ -3570,9 +_,17 @@
return Mth.lerp(p_344421_, this.yRotO, this.yRot); return Mth.lerp(p_344421_, this.yRotO, this.yRot);
} }
@@ -334,7 +334,7 @@
} else { } else {
AABB aabb = this.getBoundingBox().deflate(0.001); AABB aabb = this.getBoundingBox().deflate(0.001);
int i = Mth.floor(aabb.minX); int i = Mth.floor(aabb.minX);
@@ -3582,25 +_,28 @@ @@ -3587,25 +_,28 @@
Vec3 vec3 = Vec3.ZERO; Vec3 vec3 = Vec3.ZERO;
int k1 = 0; int k1 = 0;
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
@@ -370,7 +370,7 @@
} }
} }
} }
@@ -3608,27 +_,28 @@ @@ -3613,27 +_,28 @@
} }
} }
@@ -409,7 +409,7 @@
} }
} }
@@ -3641,7 +_,10 @@ @@ -3646,7 +_,10 @@
return !this.level().hasChunksAt(i, k, j, l); return !this.level().hasChunksAt(i, k, j, l);
} }
@@ -420,7 +420,7 @@
return this.fluidHeight.getDouble(p_204037_); return this.fluidHeight.getDouble(p_204037_);
} }
@@ -3657,7 +_,9 @@ @@ -3662,7 +_,9 @@
return this.dimensions.height(); return this.dimensions.height();
} }
@@ -430,7 +430,7 @@
return new ClientboundAddEntityPacket(this, p_344981_); return new ClientboundAddEntityPacket(this, p_344981_);
} }
@@ -3788,6 +_,11 @@ @@ -3793,6 +_,11 @@
} }
} }
} }
@@ -442,7 +442,7 @@
} }
public void checkDespawn() { public void checkDespawn() {
@@ -3962,6 +_,100 @@ @@ -3967,6 +_,100 @@
float f1 = (float)Mth.lerp(d0, this.getXRot(), p_298926_); float f1 = (float)Mth.lerp(d0, this.getXRot(), p_298926_);
this.setPos(d1, d2, d3); this.setPos(d1, d2, d3);
this.setRot(f, f1); this.setRot(f, f1);
@@ -28,7 +28,7 @@
+ public static void fireSpawnPlacementEvent() { + public static void fireSpawnPlacementEvent() {
+ Map<EntityType<?>, net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<?>> map = Maps.newHashMap(); + Map<EntityType<?>, net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<?>> map = Maps.newHashMap();
+ DATA_BY_TYPE.forEach((type, data) -> map.put(type, new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<>(data.predicate, data.placement, data.heightMap))); + DATA_BY_TYPE.forEach((type, data) -> map.put(type, new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.MergedSpawnPredicate<>(data.predicate, data.placement, data.heightMap)));
+ net.minecraftforge.fml.ModLoader.postEvent(new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent(map)); + net.minecraftforge.event.entity.SpawnPlacementRegisterEvent.BUS.post(new net.minecraftforge.event.entity.SpawnPlacementRegisterEvent(map));
+ map.forEach(((entityType, merged) -> DATA_BY_TYPE.put(entityType, new SpawnPlacements.Data(merged.getHeightmapType(), merged.getSpawnType(), merged.build())))); + map.forEach(((entityType, merged) -> DATA_BY_TYPE.put(entityType, new SpawnPlacements.Data(merged.getHeightmapType(), merged.getSpawnType(), merged.build()))));
} }
} }
@@ -35,7 +35,7 @@
@@ -151,7 +_,7 @@ @@ -151,7 +_,7 @@
@Override @Override
protected void entityInside(BlockState p_52277_, Level p_52278_, BlockPos p_52279_, Entity p_52280_, InsideBlockEffectApplier p_391246_) { protected void entityInside(BlockState p_52277_, Level p_52278_, BlockPos p_52279_, Entity p_52280_, InsideBlockEffectApplier p_391246_, boolean p_432051_) {
- if (p_52278_ instanceof ServerLevel serverlevel && p_52280_ instanceof Ravager && serverlevel.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { - if (p_52278_ instanceof ServerLevel serverlevel && p_52280_ instanceof Ravager && serverlevel.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) {
+ if (p_52278_ instanceof ServerLevel serverlevel && p_52280_ instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, p_52280_)) { + if (p_52278_ instanceof ServerLevel serverlevel && p_52280_ instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, p_52280_)) {
serverlevel.destroyBlock(p_52279_, true, p_52280_); serverlevel.destroyBlock(p_52279_, true, p_52280_);
+2 -2
View File
@@ -32,8 +32,8 @@ dependencyResolutionManagement {
library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.2') library('accesstransformers', 'net.minecraftforge:accesstransformers:8.2.2')
library('coremods', 'net.minecraftforge:coremods:5.2.6') library('coremods', 'net.minecraftforge:coremods:5.2.6')
library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.4') // Needed by coremods, because the JRE no longer ships JS library('nashorn', 'org.openjdk.nashorn:nashorn-core:15.4') // Needed by coremods, because the JRE no longer ships JS
library('eventbus', 'net.minecraftforge:eventbus:7.0-beta.11') library('eventbus', 'net.minecraftforge:eventbus:7.0-beta.12')
library('eventbus-validator', 'net.minecraftforge:eventbus-validator:7.0-beta.11') library('eventbus-validator', 'net.minecraftforge:eventbus-validator:7.0-beta.12')
library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0') library('mergetool-api', 'net.minecraftforge:mergetool-api:1.0')
library('mixin', 'org.spongepowered:mixin:0.8.7') library('mixin', 'org.spongepowered:mixin:0.8.7')
@@ -7,6 +7,7 @@ package net.minecraftforge.client;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.resources.model.UnbakedGeometry; import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
@@ -17,14 +18,14 @@ import net.minecraftforge.client.model.obj.ObjLoader;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent; import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD, modid = "forge") @Mod.EventBusSubscriber(value = Dist.CLIENT, modid = "forge")
public class ClientForgeMod { public class ClientForgeMod {
@SubscribeEvent @SubscribeEvent
public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { public static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) {
event.register("empty", (json, ctx) -> UnbakedGeometry.EMPTY); event.register(forgeRL("empty"), (json, ctx) -> UnbakedGeometry.EMPTY);
event.register("obj", ObjLoader.INSTANCE); event.register(forgeRL("obj"), ObjLoader.INSTANCE);
event.register("fluid_container", DynamicFluidContainerModel.Loader.INSTANCE); event.register(forgeRL("fluid_container"), DynamicFluidContainerModel.Loader.INSTANCE);
event.register("item_layers", ItemLayerGeometry.Loader.INSTANCE); event.register(forgeRL("item_layers"), ItemLayerGeometry.Loader.INSTANCE);
} }
@SubscribeEvent @SubscribeEvent
@@ -34,6 +35,10 @@ public class ClientForgeMod {
@SubscribeEvent @SubscribeEvent
public static void onRegisterNamedRenderTypes(RegisterNamedRenderTypesEvent event) { public static void onRegisterNamedRenderTypes(RegisterNamedRenderTypesEvent event) {
event.register("item_unlit", ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get()); event.register(forgeRL("item_unlit"), ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get());
}
private static ResourceLocation forgeRL(String path) {
return ResourceLocation.fromNamespaceAndPath("forge", path);
} }
} }
@@ -9,7 +9,6 @@ import net.minecraft.client.color.block.BlockTintCache;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.world.level.ColorResolver; import net.minecraft.world.level.ColorResolver;
import net.minecraftforge.client.event.RegisterColorHandlersEvent; import net.minecraftforge.client.event.RegisterColorHandlersEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import java.util.ArrayList; import java.util.ArrayList;
@@ -27,7 +26,7 @@ public final class ColorResolverManager {
@ApiStatus.Internal @ApiStatus.Internal
public static void init() { public static void init() {
var builder = new ArrayList<ColorResolver>(); var builder = new ArrayList<ColorResolver>();
ModLoader.postEvent(new RegisterColorHandlersEvent.ColorResolvers(builder)); RegisterColorHandlersEvent.ColorResolvers.BUS.post(new RegisterColorHandlersEvent.ColorResolvers(builder));
colorResolvers = List.copyOf(builder); colorResolvers = List.copyOf(builder);
} }
@@ -9,7 +9,6 @@ import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraftforge.client.event.RegisterDimensionSpecialEffectsEvent; import net.minecraftforge.client.event.RegisterDimensionSpecialEffectsEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import java.util.HashMap; import java.util.HashMap;
@@ -38,7 +37,7 @@ public final class DimensionSpecialEffectsManager {
var effects = new HashMap<ResourceLocation, DimensionSpecialEffects>(); var effects = new HashMap<ResourceLocation, DimensionSpecialEffects>();
DEFAULT_EFFECTS = preRegisterVanillaEffects(effects); DEFAULT_EFFECTS = preRegisterVanillaEffects(effects);
var event = new RegisterDimensionSpecialEffectsEvent(effects); var event = new RegisterDimensionSpecialEffectsEvent(effects);
ModLoader.postEventWrapContainerInModOrder(event); RegisterDimensionSpecialEffectsEvent.BUS.post(event);
EFFECTS = Map.copyOf(effects); EFFECTS = Map.copyOf(effects);
} }
@@ -8,9 +8,9 @@ package net.minecraftforge.client;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EntityType;
import net.minecraftforge.client.event.RegisterEntitySpectatorShadersEvent; import net.minecraftforge.client.event.RegisterEntitySpectatorShadersEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -20,24 +20,24 @@ import java.util.Map;
* <p> * <p>
* Provides a lookup. * Provides a lookup.
*/ */
@NullMarked
public final class EntitySpectatorShaderManager { public final class EntitySpectatorShaderManager {
private EntitySpectatorShaderManager() {} private EntitySpectatorShaderManager() {}
private static Map<EntityType<?>, ResourceLocation> SHADERS; private static @Nullable Map<EntityType<?>, ResourceLocation> SHADERS;
/** /**
* Finds the path to the spectator mode shader used for the specified entity type, or null if none is registered. * Finds the path to the spectator mode shader used for the specified entity type, or null if none is registered.
*/ */
@Nullable public static @Nullable ResourceLocation get(EntityType<?> entityType) {
public static ResourceLocation get(EntityType<?> entityType) { assert SHADERS != null;
return SHADERS.get(entityType); return SHADERS.get(entityType);
} }
@ApiStatus.Internal @ApiStatus.Internal
public static void init() { public static void init() {
var shaders = new HashMap<EntityType<?>, ResourceLocation>(); var shaders = new HashMap<EntityType<?>, ResourceLocation>();
var event = new RegisterEntitySpectatorShadersEvent(shaders); RegisterEntitySpectatorShadersEvent.BUS.post(new RegisterEntitySpectatorShadersEvent(shaders));
ModLoader.postEventWrapContainerInModOrder(event);
SHADERS = Map.copyOf(shaders); SHADERS = Map.copyOf(shaders);
} }
} }
@@ -269,11 +269,11 @@ public class ForgeHooksClient {
} }
public static void onTextureStitchedPost(TextureAtlas map) { public static void onTextureStitchedPost(TextureAtlas map) {
ModLoader.postEvent(new TextureStitchEvent.Post(map)); TextureStitchEvent.Post.BUS.post(new TextureStitchEvent.Post(map));
} }
public static void onBlockColorsInit(BlockColors blockColors) { public static void onBlockColorsInit(BlockColors blockColors) {
ModLoader.postEvent(new RegisterColorHandlersEvent.Block(blockColors)); RegisterColorHandlersEvent.Block.BUS.post(new RegisterColorHandlersEvent.Block(blockColors));
} }
public static Model getArmorModel(HumanoidRenderState state, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default) { public static Model getArmorModel(HumanoidRenderState state, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default) {
@@ -359,11 +359,11 @@ public class ForgeHooksClient {
} }
public static void onModifyBakingResult(ModelBakery modelBakery, ModelBakery.BakingResult results) { public static void onModifyBakingResult(ModelBakery modelBakery, ModelBakery.BakingResult results) {
ModLoader.postEvent(new ModelEvent.ModifyBakingResult(modelBakery, results)); ModelEvent.ModifyBakingResult.BUS.post(new ModelEvent.ModifyBakingResult(modelBakery, results));
} }
public static void onModelBake(ModelManager modelManager, ModelBakery modelBakery) { public static void onModelBake(ModelManager modelManager, ModelBakery modelBakery) {
ModLoader.postEvent(new ModelEvent.BakingCompleted(modelManager, modelBakery)); ModelEvent.BakingCompleted.BUS.post(new ModelEvent.BakingCompleted(modelManager, modelBakery));
} }
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) { public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
@@ -428,25 +428,25 @@ public class ForgeHooksClient {
} }
public static boolean onScreenKeyPressed(Screen screen, KeyEvent info) { public static boolean onScreenKeyPressed(Screen screen, KeyEvent info) {
return ForgeEventFactoryClient.onScreenKeyPressedPre(screen, info.key(), info.scancode(), info.modifiers()) return ForgeEventFactoryClient.onScreenKeyPressedPre(screen, info)
|| screen.keyPressed(info) || screen.keyPressed(info)
|| ForgeEventFactoryClient.onScreenKeyPressedPost(screen, info.key(), info.scancode(), info.modifiers()); || ForgeEventFactoryClient.onScreenKeyPressedPost(screen, info);
} }
public static boolean onScreenKeyReleased(Screen screen, KeyEvent info) { public static boolean onScreenKeyReleased(Screen screen, KeyEvent info) {
return ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, info.key(), info.scancode(), info.modifiers()) return ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, info)
|| screen.keyReleased(info) || screen.keyReleased(info)
|| ForgeEventFactoryClient.onScreenKeyReleasedPost(screen, info.key(), info.scancode(), info.modifiers()); || ForgeEventFactoryClient.onScreenKeyReleasedPost(screen, info);
} }
public static boolean onScreenCharTyped(Screen screen, CharacterEvent info) { public static boolean onScreenCharTyped(Screen screen, CharacterEvent info) {
return ForgeEventFactoryClient.onScreenCharTypedPre(screen, (char)info.codepoint(), info.modifiers()) return ForgeEventFactoryClient.onScreenCharTypedPre(screen, info)
|| screen.charTyped(info) || screen.charTyped(info)
|| ForgeEventFactoryClient.onScreenCharTypedPost(screen, (char)info.codepoint(), info.modifiers()); || ForgeEventFactoryClient.onScreenCharTypedPost(screen, info);
} }
public static void onKeyInput(KeyEvent info, int action) { public static void onKeyInput(KeyEvent info, int action) {
InputEvent.Key.BUS.post(new InputEvent.Key(info.key(), info.scancode(), action, info.modifiers())); InputEvent.Key.BUS.post(new InputEvent.Key(info, action));
} }
public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) { public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) {
@@ -615,11 +615,11 @@ public class ForgeHooksClient {
} }
public static void onRegisterParticleProviders(ParticleResources particles) { public static void onRegisterParticleProviders(ParticleResources particles) {
ModLoader.postEvent(new RegisterParticleProvidersEvent(particles)); RegisterParticleProvidersEvent.BUS.post(new RegisterParticleProvidersEvent(particles));
} }
public static void onRegisterKeyMappings(Options options) { public static void onRegisterKeyMappings(Options options) {
ModLoader.postEvent(new RegisterKeyMappingsEvent(options)); RegisterKeyMappingsEvent.BUS.post(new RegisterKeyMappingsEvent(options));
} }
public static void onRegisterPictureInPictureRenderers(List<PictureInPictureRenderer<?>> renderers, public static void onRegisterPictureInPictureRenderers(List<PictureInPictureRenderer<?>> renderers,
@@ -799,9 +799,9 @@ public class ForgeHooksClient {
throw new IllegalStateException("Client hooks initialized more than once"); throw new IllegalStateException("Client hooks initialized more than once");
initializedClientHooks = true; initializedClientHooks = true;
ModLoader.postEvent(new RegisterClientReloadListenersEvent(resourceManager)); RegisterClientReloadListenersEvent.BUS.post(new RegisterClientReloadListenersEvent(resourceManager));
ModLoader.postEvent(new EntityRenderersEvent.RegisterLayerDefinitions()); EntityRenderersEvent.RegisterLayerDefinitions.BUS.post(new EntityRenderersEvent.RegisterLayerDefinitions());
ModLoader.postEvent(new EntityRenderersEvent.RegisterRenderers()); EntityRenderersEvent.RegisterRenderers.BUS.post(new EntityRenderersEvent.RegisterRenderers());
TextureAtlasSpriteLoaderManager.init(); TextureAtlasSpriteLoaderManager.init();
ClientTooltipComponentManager.init(); ClientTooltipComponentManager.init();
EntitySpectatorShaderManager.init(); EntitySpectatorShaderManager.init();
@@ -18,7 +18,6 @@ import net.minecraft.client.gui.Font;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraftforge.client.event.RegisterItemDecorationsEvent; import net.minecraftforge.client.event.RegisterItemDecorationsEvent;
import net.minecraftforge.fml.ModLoader;
@ApiStatus.Internal @ApiStatus.Internal
public final class ItemDecoratorHandler { public final class ItemDecoratorHandler {
@@ -37,8 +36,7 @@ public final class ItemDecoratorHandler {
public static void init() { public static void init() {
var decorators = new HashMap<Item, List<IItemDecorator>>(); var decorators = new HashMap<Item, List<IItemDecorator>>();
var event = new RegisterItemDecorationsEvent(decorators); RegisterItemDecorationsEvent.BUS.post(new RegisterItemDecorationsEvent(decorators));
ModLoader.postEventWrapContainerInModOrder(event);
var builder = new ImmutableMap.Builder<Item, ItemDecoratorHandler>(); var builder = new ImmutableMap.Builder<Item, ItemDecoratorHandler>();
for (var entry : decorators.entrySet()) { for (var entry : decorators.entrySet()) {
Item item = entry.getKey(); Item item = entry.getKey();
@@ -5,12 +5,10 @@
package net.minecraftforge.client; package net.minecraftforge.client;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.event.RegisterNamedRenderTypesEvent; import net.minecraftforge.client.event.RegisterNamedRenderTypesEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import java.util.HashMap; import java.util.HashMap;
@@ -22,7 +20,7 @@ import java.util.Map;
* Provides a lookup. * Provides a lookup.
*/ */
public final class NamedRenderTypeManager { public final class NamedRenderTypeManager {
private static ImmutableMap<ResourceLocation, RenderTypeGroup> RENDER_TYPES; private static Map<ResourceLocation, RenderTypeGroup> RENDER_TYPES;
/** /**
* Finds the {@link RenderTypeGroup} for a given name, or the {@link RenderTypeGroup#EMPTY empty group} if not found. * Finds the {@link RenderTypeGroup} for a given name, or the {@link RenderTypeGroup#EMPTY empty group} if not found.
@@ -35,9 +33,8 @@ public final class NamedRenderTypeManager {
public static void init() { public static void init() {
var renderTypes = new HashMap<ResourceLocation, RenderTypeGroup>(); var renderTypes = new HashMap<ResourceLocation, RenderTypeGroup>();
preRegisterVanillaRenderTypes(renderTypes); preRegisterVanillaRenderTypes(renderTypes);
var event = new RegisterNamedRenderTypesEvent(renderTypes); RegisterNamedRenderTypesEvent.BUS.post(new RegisterNamedRenderTypesEvent(renderTypes));
ModLoader.postEventWrapContainerInModOrder(event); RENDER_TYPES = Map.copyOf(renderTypes);
RENDER_TYPES = ImmutableMap.copyOf(renderTypes);
} }
/** /**
@@ -53,9 +50,9 @@ public final class NamedRenderTypeManager {
blockRenderTypes.put(rl("tripwire"), new RenderTypeGroup(ChunkSectionLayer.TRIPWIRE, ForgeRenderTypes.ITEM_LAYERED_TRANSLUCENT.get())); blockRenderTypes.put(rl("tripwire"), new RenderTypeGroup(ChunkSectionLayer.TRIPWIRE, ForgeRenderTypes.ITEM_LAYERED_TRANSLUCENT.get()));
} }
private static ResourceLocation rl(String paht) { private static ResourceLocation rl(String path) {
return ResourceLocation.withDefaultNamespace(paht); return ResourceLocation.withDefaultNamespace(path);
} }
private NamedRenderTypeManager() { } private NamedRenderTypeManager() {}
} }
@@ -42,7 +42,7 @@ public sealed interface CustomizeGuiOverlayEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
final class BossEventProgress implements Cancellable, CustomizeGuiOverlayEvent, RecordEvent { final class BossEventProgress extends MutableEvent implements Cancellable, CustomizeGuiOverlayEvent {
public static final CancellableEventBus<BossEventProgress> BUS = CancellableEventBus.create(BossEventProgress.class); public static final CancellableEventBus<BossEventProgress> BUS = CancellableEventBus.create(BossEventProgress.class);
private final Window window; private final Window window;
@@ -35,12 +35,13 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jspecify.annotations.NullMarked;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -51,30 +52,30 @@ import java.util.function.Supplier;
* Fired for on different events/actions relating to {@linkplain EntityRenderer entity renderers}. * Fired for on different events/actions relating to {@linkplain EntityRenderer entity renderers}.
* See the various subclasses for listening to different events. * See the various subclasses for listening to different events.
* *
* <p>These events are fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>These events are fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* *
* @see EntityRenderersEvent.RegisterLayerDefinitions * @see EntityRenderersEvent.RegisterLayerDefinitions
* @see EntityRenderersEvent.RegisterRenderers * @see EntityRenderersEvent.RegisterRenderers
* @see EntityRenderersEvent.AddLayers * @see EntityRenderersEvent.AddLayers
* @see EntityRenderersEvent.CreateSkullModels
*/ */
public abstract sealed class EntityRenderersEvent implements IModBusEvent { public sealed interface EntityRenderersEvent {
@ApiStatus.Internal
protected EntityRenderersEvent() {}
/** /**
* Fired for registering layer definitions at the appropriate time. * Fired for registering layer definitions at the appropriate time.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired on only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public static final class RegisterLayerDefinitions extends EntityRenderersEvent implements SelfDestructing { @NullMarked
record RegisterLayerDefinitions() implements SelfDestructing, RecordEvent, EntityRenderersEvent {
public static final EventBus<RegisterLayerDefinitions> BUS = EventBus.create(RegisterLayerDefinitions.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterLayerDefinitions> getBus(BusGroup modBusGroup) { public static EventBus<RegisterLayerDefinitions> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterLayerDefinitions.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
public RegisterLayerDefinitions() {} public RegisterLayerDefinitions {}
/** /**
* Registers a layer definition supplier with the given {@link ModelLayerLocation}. * Registers a layer definition supplier with the given {@link ModelLayerLocation}.
@@ -95,16 +96,19 @@ public abstract sealed class EntityRenderersEvent implements IModBusEvent {
* For registering entity renderer layers to existing entity renderers (whether vanilla or registered through this * For registering entity renderer layers to existing entity renderers (whether vanilla or registered through this
* event), listen for the {@link AddLayers} event instead. * event), listen for the {@link AddLayers} event instead.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public static final class RegisterRenderers extends EntityRenderersEvent implements SelfDestructing { @NullMarked
record RegisterRenderers() implements SelfDestructing, RecordEvent, EntityRenderersEvent {
public static final EventBus<RegisterRenderers> BUS = EventBus.create(RegisterRenderers.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterRenderers> getBus(BusGroup modBusGroup) { public static EventBus<RegisterRenderers> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterRenderers.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
public RegisterRenderers() {} public RegisterRenderers {}
/** /**
* Registers an entity renderer for the given entity type. * Registers an entity renderer for the given entity type.
@@ -131,14 +135,14 @@ public abstract sealed class EntityRenderersEvent implements IModBusEvent {
* Fired for registering entity renderer layers at the appropriate time, after the entity and player renderers maps * Fired for registering entity renderer layers at the appropriate time, after the entity and player renderers maps
* have been created. * have been created.
* *
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public static final class AddLayers extends EntityRenderersEvent { final class AddLayers extends MutableEvent implements EntityRenderersEvent {
public static final EventBus<AddLayers> BUS = EventBus.create(AddLayers.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<AddLayers> getBus(BusGroup modBusGroup) { public static EventBus<AddLayers> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, AddLayers.class); return BUS;
} }
private final Map<EntityType<?>, EntityRenderer<?, ?>> renderers; private final Map<EntityType<?>, EntityRenderer<?, ?>> renderers;
@@ -222,14 +226,14 @@ public abstract sealed class EntityRenderersEvent implements IModBusEvent {
/** /**
* Fired for registering additional {@linkplain net.minecraft.client.model.SkullModelBase skull models} at the appropriate time. * Fired for registering additional {@linkplain net.minecraft.client.model.SkullModelBase skull models} at the appropriate time.
* *
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public static final class CreateSkullModels extends EntityRenderersEvent { final class CreateSkullModels extends MutableEvent implements EntityRenderersEvent {
public static final EventBus<CreateSkullModels> BUS = EventBus.create(CreateSkullModels.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<CreateSkullModels> getBus(BusGroup modBusGroup) { public static EventBus<CreateSkullModels> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, CreateSkullModels.class); return BUS;
} }
private final ImmutableMap.Builder<Type, Function<EntityModelSet, SkullModelBase>> builder; private final ImmutableMap.Builder<Type, Function<EntityModelSet, SkullModelBase>> builder;
@@ -33,7 +33,10 @@ import net.minecraft.client.gui.components.toasts.Toast;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.client.model.EntityModel; import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.SkullModelBase; import net.minecraft.client.model.SkullModelBase;
import net.minecraft.client.model.geom.EntityModelSet; import net.minecraft.client.model.geom.EntityModelSet;
@@ -76,8 +79,7 @@ public final class ForgeEventFactoryClient {
private ForgeEventFactoryClient() {} private ForgeEventFactoryClient() {}
public static void onGatherLayers(Map<EntityType<?>, EntityRenderer<?, ?>> renderers, Map<PlayerModelType, AvatarRenderer<AbstractClientPlayer>> playerRenderers, Map<PlayerModelType, AvatarRenderer<ClientMannequin>> mannequinRenderers, Context context) { public static void onGatherLayers(Map<EntityType<?>, EntityRenderer<?, ?>> renderers, Map<PlayerModelType, AvatarRenderer<AbstractClientPlayer>> playerRenderers, Map<PlayerModelType, AvatarRenderer<ClientMannequin>> mannequinRenderers, Context context) {
// TODO: Why is this a ModLoader event... EntityRenderersEvent.AddLayers.BUS.post(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, mannequinRenderers, context));
ModLoader.postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, mannequinRenderers, context));
} }
public static boolean onScreenMouseReleased(Screen screen, double mouseX, double mouseY, MouseButtonEvent event) { public static boolean onScreenMouseReleased(Screen screen, double mouseX, double mouseY, MouseButtonEvent event) {
@@ -90,20 +92,20 @@ public final class ForgeEventFactoryClient {
} }
public static boolean onScreenMouseClicked(Screen screen, double mouseX, double mouseY, MouseButtonEvent info, boolean repeate) { public static boolean onScreenMouseClicked(Screen screen, double mouseX, double mouseY, MouseButtonEvent info, boolean repeate) {
var ret = ScreenEvent.MouseButtonPressed.Pre.BUS.post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, info.button())); var ret = ScreenEvent.MouseButtonPressed.Pre.BUS.post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, info));
if (!ret) if (!ret)
ret = screen.mouseClicked(info, repeate); ret = screen.mouseClicked(info, repeate);
var result = ScreenEvent.MouseButtonPressed.Post.BUS.fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, info.button(), ret)).getResult(); var result = ScreenEvent.MouseButtonPressed.Post.BUS.fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, info, ret, new Result.Holder())).getResult();
return result == Result.DEFAULT ? ret : result == Result.ALLOW; return result == Result.DEFAULT ? ret : result == Result.ALLOW;
} }
public static boolean onMouseButtonPre(int button, int action, int mods) { public static boolean onMouseButtonPre(MouseButtonInfo info, int action) {
return InputEvent.MouseButton.Pre.BUS.post(new InputEvent.MouseButton.Pre(button, action, mods)); return InputEvent.MouseButton.Pre.BUS.post(new InputEvent.MouseButton.Pre(info, action));
} }
public static void onMouseButtonPost(int button, int action, int mods) { public static void onMouseButtonPost(MouseButtonInfo info, int action) {
InputEvent.MouseButton.Post.BUS.post(new InputEvent.MouseButton.Post(button, action, mods)); InputEvent.MouseButton.Post.BUS.post(new InputEvent.MouseButton.Post(info, action));
} }
public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) { public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
@@ -145,28 +147,28 @@ public final class ForgeEventFactoryClient {
PlayStreamingSourceEvent.BUS.post(new PlayStreamingSourceEvent(engine, sound, channel)); PlayStreamingSourceEvent.BUS.post(new PlayStreamingSourceEvent(engine, sound, channel));
} }
public static boolean onScreenKeyPressedPre(Screen screen, int keyCode, int scanCode, int modifiers) { public static boolean onScreenKeyPressedPre(Screen screen, KeyEvent info) {
return ScreenEvent.KeyPressed.Pre.BUS.post(new ScreenEvent.KeyPressed.Pre(screen, keyCode, scanCode, modifiers)); return ScreenEvent.KeyPressed.Pre.BUS.post(new ScreenEvent.KeyPressed.Pre(screen, info));
} }
public static boolean onScreenKeyPressedPost(Screen screen, int keyCode, int scanCode, int modifiers) { public static boolean onScreenKeyPressedPost(Screen screen, KeyEvent info) {
return ScreenEvent.KeyPressed.Post.BUS.post(new ScreenEvent.KeyPressed.Post(screen, keyCode, scanCode, modifiers)); return ScreenEvent.KeyPressed.Post.BUS.post(new ScreenEvent.KeyPressed.Post(screen, info));
} }
public static boolean onScreenKeyReleasedPre(Screen screen, int keyCode, int scanCode, int modifiers) { public static boolean onScreenKeyReleasedPre(Screen screen, KeyEvent info) {
return ScreenEvent.KeyReleased.Pre.BUS.post(new ScreenEvent.KeyReleased.Pre(screen, keyCode, scanCode, modifiers)); return ScreenEvent.KeyReleased.Pre.BUS.post(new ScreenEvent.KeyReleased.Pre(screen, info));
} }
public static boolean onScreenKeyReleasedPost(Screen screen, int keyCode, int scanCode, int modifiers) { public static boolean onScreenKeyReleasedPost(Screen screen, KeyEvent info) {
return ScreenEvent.KeyReleased.Post.BUS.post(new ScreenEvent.KeyReleased.Post(screen, keyCode, scanCode, modifiers)); return ScreenEvent.KeyReleased.Post.BUS.post(new ScreenEvent.KeyReleased.Post(screen, info));
} }
public static boolean onScreenCharTypedPre(Screen screen, char codePoint, int modifiers) { public static boolean onScreenCharTypedPre(Screen screen, CharacterEvent info) {
return ScreenEvent.CharacterTyped.Pre.BUS.post(new ScreenEvent.CharacterTyped.Pre(screen, codePoint, modifiers)); return ScreenEvent.CharacterTyped.Pre.BUS.post(new ScreenEvent.CharacterTyped.Pre(screen, info));
} }
public static boolean onScreenCharTypedPost(Screen screen, char codePoint, int modifiers) { public static boolean onScreenCharTypedPost(Screen screen, CharacterEvent info) {
return ScreenEvent.CharacterTyped.Post.BUS.post(new ScreenEvent.CharacterTyped.Post(screen, codePoint, modifiers)); return ScreenEvent.CharacterTyped.Post.BUS.post(new ScreenEvent.CharacterTyped.Post(screen, info));
} }
public static boolean onClickInputPickBlock(KeyMapping keyBinding) { public static boolean onClickInputPickBlock(KeyMapping keyBinding) {
@@ -269,13 +271,12 @@ public final class ForgeEventFactoryClient {
public static Map<Type, Function<EntityModelSet, SkullModelBase>> onCreateSkullModels() { public static Map<Type, Function<EntityModelSet, SkullModelBase>> onCreateSkullModels() {
var builder = ImmutableMap.<Type, Function<EntityModelSet, SkullModelBase>>builder(); var builder = ImmutableMap.<Type, Function<EntityModelSet, SkullModelBase>>builder();
ModLoader.postEvent(new EntityRenderersEvent.CreateSkullModels(builder)); EntityRenderersEvent.CreateSkullModels.BUS.post(new EntityRenderersEvent.CreateSkullModels(builder));
return builder.build(); return builder.build();
} }
public static ModelEvent.RegisterModelStateDefinitions onRegisterModeStateDefinitions() { public static ModelEvent.RegisterModelStateDefinitions onRegisterModeStateDefinitions() {
// This is on the mod bus because it happens during the initial texture reload, which is while the Forge bus is shut down. return ModelEvent.RegisterModelStateDefinitions.BUS.fire(new ModelEvent.RegisterModelStateDefinitions());
return ModLoader.postEventWithReturn(new ModelEvent.RegisterModelStateDefinitions());
} }
public static void onInitLevelRenderer() { public static void onInitLevelRenderer() {
@@ -7,6 +7,8 @@ package net.minecraftforge.client.event;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping; import net.minecraft.client.KeyMapping;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus; import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
@@ -37,13 +39,21 @@ public sealed interface InputEvent {
* @see Post * @see Post
*/ */
sealed interface MouseButton extends InputEvent { sealed interface MouseButton extends InputEvent {
/**
* {@return the MouseButtonInfo object containing information about the mouse button state}
* @see MouseButtonInfo
*/
MouseButtonInfo getInfo();
/** /**
* {@return the mouse button's input code} * {@return the mouse button's input code}
* *
* @see GLFW mouse constants starting with 'GLFW_MOUSE_BUTTON_' * @see GLFW mouse constants starting with 'GLFW_MOUSE_BUTTON_'
* @see <a href="https://www.glfw.org/docs/latest/group__buttons.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__buttons.html" target="_top">the online GLFW documentation</a>
*/ */
int getButton(); default int getButton() {
return getInfo().button();
}
/** /**
* {@return the mouse button's action} * {@return the mouse button's action}
@@ -64,7 +74,9 @@ public sealed interface InputEvent {
* @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit * @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit
* @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a>
*/ */
int getModifiers(); default int getModifiers() {
return getInfo().modifiers();
}
/** /**
* Fired when a mouse button is pressed/released, <b>before</b> being processed by vanilla. * Fired when a mouse button is pressed/released, <b>before</b> being processed by vanilla.
@@ -75,7 +87,7 @@ public sealed interface InputEvent {
* *
* @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_mouse_button" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_mouse_button" target="_top">the online GLFW documentation</a>
*/ */
record Pre(int getButton, int getAction, int getModifiers) implements Cancellable, MouseButton, RecordEvent { record Pre(MouseButtonInfo getInfo, int getAction) implements Cancellable, MouseButton, RecordEvent {
public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class); public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -89,7 +101,7 @@ public sealed interface InputEvent {
* *
* @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_mouse_button" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_mouse_button" target="_top">the online GLFW documentation</a>
*/ */
record Post(int getButton, int getAction, int getModifiers) implements MouseButton, RecordEvent { record Post(MouseButtonInfo getInfo, int getAction) implements MouseButton, RecordEvent {
public static final EventBus<Post> BUS = EventBus.create(Post.class); public static final EventBus<Post> BUS = EventBus.create(Post.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -135,12 +147,20 @@ public sealed interface InputEvent {
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Key(int getKey, int getScanCode, int getAction, int getModifiers) implements RecordEvent, InputEvent { record Key(KeyEvent getInfo, int getAction) implements RecordEvent, InputEvent {
public static final EventBus<Key> BUS = EventBus.create(Key.class); public static final EventBus<Key> BUS = EventBus.create(Key.class);
@ApiStatus.Internal @ApiStatus.Internal
public Key {} public Key {}
/**
* {@return the KeyEvent object containing information about the key being pressed/released}
* @see KeyEvent
*/
public KeyEvent getInfo() {
return getInfo;
}
/** /**
* {@return the {@code GLFW} (platform-agnostic) key code} * {@return the {@code GLFW} (platform-agnostic) key code}
* *
@@ -149,7 +169,7 @@ public sealed interface InputEvent {
* @see <a href="https://www.glfw.org/docs/latest/group__keys.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__keys.html" target="_top">the online GLFW documentation</a>
*/ */
public int getKey() { public int getKey() {
return getKey; return getInfo().key();
} }
/** /**
@@ -162,7 +182,7 @@ public sealed interface InputEvent {
* @see InputConstants#getKey(int, int) * @see InputConstants#getKey(int, int)
*/ */
public int getScanCode() { public int getScanCode() {
return getScanCode; return getInfo().scancode();
} }
/** /**
@@ -188,7 +208,7 @@ public sealed interface InputEvent {
* @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a>
*/ */
public int getModifiers() { public int getModifiers() {
return getModifiers; return getInfo().modifiers();
} }
} }
@@ -15,10 +15,13 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraftforge.client.model.geometry.IGeometryLoader; import net.minecraftforge.client.model.geometry.IGeometryLoader;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@@ -45,9 +48,12 @@ public sealed interface ModelEvent {
* @param getResults the modifiable registry map of models and their model names * @param getResults the modifiable registry map of models and their model names
*/ */
record ModifyBakingResult(ModelBakery getModelBakery, ModelBakery.BakingResult getResults) record ModifyBakingResult(ModelBakery getModelBakery, ModelBakery.BakingResult getResults)
implements IModBusEvent, ModelEvent { implements RecordEvent, ModelEvent {
public static final EventBus<ModifyBakingResult> BUS = EventBus.create(ModifyBakingResult.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<ModifyBakingResult> getBus(BusGroup modBusGroup) { public static EventBus<ModifyBakingResult> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, ModifyBakingResult.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
@@ -66,9 +72,12 @@ public sealed interface ModelEvent {
* @param getModelBakery the model loader * @param getModelBakery the model loader
*/ */
record BakingCompleted(ModelManager getModelManager, ModelBakery getModelBakery) record BakingCompleted(ModelManager getModelManager, ModelBakery getModelBakery)
implements IModBusEvent, ModelEvent { implements RecordEvent, ModelEvent {
public static final EventBus<BakingCompleted> BUS = EventBus.create(BakingCompleted.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<BakingCompleted> getBus(BusGroup modBusGroup) { public static EventBus<BakingCompleted> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, BakingCompleted.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
@@ -83,16 +92,19 @@ public sealed interface ModelEvent {
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
final class RegisterModelStateDefinitions implements IModBusEvent, ModelEvent { final class RegisterModelStateDefinitions extends MutableEvent implements ModelEvent {
public static final EventBus<RegisterModelStateDefinitions> BUS = EventBus.create(RegisterModelStateDefinitions.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterModelStateDefinitions> getBus(BusGroup modBusGroup) { public static EventBus<RegisterModelStateDefinitions> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterModelStateDefinitions.class); return BUS;
} }
private final Map<ResourceLocation, StateDefinition<Block, BlockState>> states = new HashMap<>(); private final Map<ResourceLocation, StateDefinition<Block, BlockState>> states = new HashMap<>();
private final Map<ResourceLocation, StateDefinition<Block, BlockState>> view = Collections.unmodifiableMap(states); private final Map<ResourceLocation, StateDefinition<Block, BlockState>> view = Collections.unmodifiableMap(states);
@ApiStatus.Internal @ApiStatus.Internal
public RegisterModelStateDefinitions() { } public RegisterModelStateDefinitions() {}
/** /**
* Returns a read only view of the extra registered models * Returns a read only view of the extra registered models
@@ -114,9 +126,13 @@ public sealed interface ModelEvent {
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
final class RegisterGeometryLoaders implements IModBusEvent, ModelEvent { @NullMarked
final class RegisterGeometryLoaders extends MutableEvent implements ModelEvent {
public static final EventBus<RegisterGeometryLoaders> BUS = EventBus.create(RegisterGeometryLoaders.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterGeometryLoaders> getBus(BusGroup modBusGroup) { public static EventBus<RegisterGeometryLoaders> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterGeometryLoaders.class); return BUS;
} }
private final Map<ResourceLocation, IGeometryLoader> loaders; private final Map<ResourceLocation, IGeometryLoader> loaders;
@@ -128,13 +144,11 @@ public sealed interface ModelEvent {
/** /**
* Registers a new geometry loader. * Registers a new geometry loader.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
*/ */
public void register(String name, IGeometryLoader loader) { public void register(ResourceLocation resourceLocation, IGeometryLoader loader) {
@SuppressWarnings("removal") Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Geometry loader already registered: " + resourceLocation);
var namespace = ModLoadingContext.get().getActiveNamespace(); loaders.put(resourceLocation, loader);
var key = ResourceLocation.fromNamespaceAndPath(namespace, name);
Preconditions.checkArgument(!loaders.containsKey(key), "Geometry loader already registered: " + key);
loaders.put(key, loader);
} }
} }
} }
@@ -11,11 +11,11 @@ import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.AddReloadListenerEvent;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
/** /**
* Fired to allow mods to register their reload listeners on the client-side resource manager. * Fired to allow mods to register their reload listeners on the client-side resource manager.
@@ -23,12 +23,15 @@ import org.jetbrains.annotations.ApiStatus;
* *
* <p>For registering reload listeners on the server-side resource manager, see {@link AddReloadListenerEvent}.</p> * <p>For registering reload listeners on the server-side resource manager, see {@link AddReloadListenerEvent}.</p>
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterClientReloadListenersEvent implements SelfDestructing, IModBusEvent { @NullMarked
public final class RegisterClientReloadListenersEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterClientReloadListenersEvent> BUS = EventBus.create(RegisterClientReloadListenersEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterClientReloadListenersEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterClientReloadListenersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterClientReloadListenersEvent.class); return BUS;
} }
private final ReloadableResourceManager resourceManager; private final ReloadableResourceManager resourceManager;
@@ -9,11 +9,11 @@ import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent
import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
@@ -22,12 +22,15 @@ import java.util.function.Function;
* Allows users to register custom {@link net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent} * Allows users to register custom {@link net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent}
* factories for their {@link net.minecraft.world.inventory.tooltip.TooltipComponent} types. * factories for their {@link net.minecraft.world.inventory.tooltip.TooltipComponent} types.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterClientTooltipComponentFactoriesEvent implements SelfDestructing, IModBusEvent { @NullMarked
public final class RegisterClientTooltipComponentFactoriesEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterClientTooltipComponentFactoriesEvent> BUS = EventBus.create(RegisterClientTooltipComponentFactoriesEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterClientTooltipComponentFactoriesEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterClientTooltipComponentFactoriesEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterClientTooltipComponentFactoriesEvent.class); return BUS;
} }
private final Map<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>> factories; private final Map<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>> factories;
@@ -11,10 +11,10 @@ import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ColorResolver; import net.minecraft.world.level.ColorResolver;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullMarked;
@@ -24,24 +24,23 @@ import java.util.ArrayList;
* Fired for registering block and item color handlers at the appropriate time. * Fired for registering block and item color handlers at the appropriate time.
* See the two subclasses for registering block or item color handlers. * See the two subclasses for registering block or item color handlers.
* *
* <p>These events are fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>These events are fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* *
* @see RegisterColorHandlersEvent.Block * @see RegisterColorHandlersEvent.Block
* @see RegisterColorHandlersEvent.ColorResolvers * @see RegisterColorHandlersEvent.ColorResolvers
*/ */
public sealed interface RegisterColorHandlersEvent extends IModBusEvent { public sealed interface RegisterColorHandlersEvent {
/** /**
* Fired for registering block color handlers. * Fired for registering block color handlers.
* *
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Block(BlockColors getBlockColors) implements RegisterColorHandlersEvent { record Block(BlockColors getBlockColors) implements RecordEvent, RegisterColorHandlersEvent {
public static final EventBus<Block> BUS = EventBus.create(Block.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<Block> getBus(BusGroup modBusGroup) { public static EventBus<Block> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, Block.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
@@ -73,9 +72,12 @@ public sealed interface RegisterColorHandlersEvent extends IModBusEvent {
* {@link net.minecraft.world.level.BlockAndTintGetter#getBlockTint(BlockPos, ColorResolver)}. * {@link net.minecraft.world.level.BlockAndTintGetter#getBlockTint(BlockPos, ColorResolver)}.
*/ */
@NullMarked @NullMarked
final class ColorResolvers implements RegisterColorHandlersEvent, SelfDestructing { final class ColorResolvers extends MutableEvent implements SelfDestructing, RegisterColorHandlersEvent {
public static final EventBus<ColorResolvers> BUS = EventBus.create(ColorResolvers.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<ColorResolvers> getBus(BusGroup modBusGroup) { public static EventBus<ColorResolvers> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, ColorResolvers.class); return BUS;
} }
private final ArrayList<ColorResolver> builder; private final ArrayList<ColorResolver> builder;
@@ -9,10 +9,9 @@ import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullMarked;
@@ -21,13 +20,15 @@ import java.util.Map;
/** /**
* Allows users to register custom {@link DimensionSpecialEffects} for their dimensions. * Allows users to register custom {@link DimensionSpecialEffects} for their dimensions.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
@NullMarked @NullMarked
public final class RegisterDimensionSpecialEffectsEvent implements SelfDestructing, IModBusEvent { public final class RegisterDimensionSpecialEffectsEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterDimensionSpecialEffectsEvent> BUS = EventBus.create(RegisterDimensionSpecialEffectsEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterDimensionSpecialEffectsEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterDimensionSpecialEffectsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterDimensionSpecialEffectsEvent.class); return BUS;
} }
private final Map<ResourceLocation, DimensionSpecialEffects> effects; private final Map<ResourceLocation, DimensionSpecialEffects> effects;
@@ -9,10 +9,9 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EntityType;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullMarked;
@@ -22,13 +21,15 @@ import java.util.Map;
* Allows users to register custom shaders to be used when the player spectates a certain kind of entity. * Allows users to register custom shaders to be used when the player spectates a certain kind of entity.
* Vanilla examples of this are the green effect for creepers and the invert effect for endermen. * Vanilla examples of this are the green effect for creepers and the invert effect for endermen.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired on only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
@NullMarked @NullMarked
public final class RegisterEntitySpectatorShadersEvent implements SelfDestructing, IModBusEvent { public final class RegisterEntitySpectatorShadersEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterEntitySpectatorShadersEvent> BUS = EventBus.create(RegisterEntitySpectatorShadersEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterEntitySpectatorShadersEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterEntitySpectatorShadersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterEntitySpectatorShadersEvent.class); return BUS;
} }
private final Map<EntityType<?>, ResourceLocation> shaders; private final Map<EntityType<?>, ResourceLocation> shaders;
@@ -11,11 +11,11 @@ import net.minecraftforge.client.IItemDecorator;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -24,12 +24,15 @@ import java.util.Map;
/** /**
* Allows users to register custom {@linkplain IItemDecorator IItemDecorator} to Items. * Allows users to register custom {@linkplain IItemDecorator IItemDecorator} to Items.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterItemDecorationsEvent implements SelfDestructing, IModBusEvent { @NullMarked
public final class RegisterItemDecorationsEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterItemDecorationsEvent> BUS = EventBus.create(RegisterItemDecorationsEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterItemDecorationsEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterItemDecorationsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterItemDecorationsEvent.class); return BUS;
} }
private final Map<Item, List<IItemDecorator>> decorators; private final Map<Item, List<IItemDecorator>> decorators;
@@ -9,22 +9,25 @@ import net.minecraft.client.KeyMapping;
import net.minecraft.client.Options; import net.minecraft.client.Options;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
/** /**
* Allows users to register custom {@link net.minecraft.client.KeyMapping key mappings}. * Allows users to register custom {@link net.minecraft.client.KeyMapping key mappings}.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterKeyMappingsEvent implements SelfDestructing, IModBusEvent { @NullMarked
public final class RegisterKeyMappingsEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterKeyMappingsEvent> BUS = EventBus.create(RegisterKeyMappingsEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterKeyMappingsEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterKeyMappingsEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterKeyMappingsEvent.class); return BUS;
} }
private final Options options; private final Options options;
@@ -13,9 +13,9 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.RenderTypeGroup; import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import java.util.Map; import java.util.Map;
@@ -25,9 +25,12 @@ import java.util.Map;
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterNamedRenderTypesEvent implements IModBusEvent { public final class RegisterNamedRenderTypesEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterNamedRenderTypesEvent> BUS = EventBus.create(RegisterNamedRenderTypesEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterNamedRenderTypesEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterNamedRenderTypesEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterNamedRenderTypesEvent.class); return BUS;
} }
private final Map<ResourceLocation, RenderTypeGroup> renderTypes; private final Map<ResourceLocation, RenderTypeGroup> renderTypes;
@@ -40,26 +43,24 @@ public final class RegisterNamedRenderTypesEvent implements IModBusEvent {
/** /**
* Registers a named {@link RenderTypeGroup}. * Registers a named {@link RenderTypeGroup}.
* *
* @param name The name * @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
* @param blockRenderType What ChunkSectionLayer to render in * @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} * @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
*/ */
public void register(String name, ChunkSectionLayer blockRenderType, RenderType entityRenderType) { public void register(ResourceLocation resourceLocation, ChunkSectionLayer blockRenderType, RenderType entityRenderType) {
register(name, blockRenderType, entityRenderType, entityRenderType); register(resourceLocation, blockRenderType, entityRenderType, entityRenderType);
} }
/** /**
* Registers a named {@link RenderTypeGroup}. * Registers a named {@link RenderTypeGroup}.
* *
* @param name The name * @param key The namespace should match your mod's namespace, such as your mod ID
* @param blockRenderType What ChunkSectionLayer to render in * @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} * @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
* @param fabulousEntityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for use when * @param fabulousEntityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for use when
* "fabulous" rendering is enabled * "fabulous" rendering is enabled
*/ */
public void register(String name, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) { public void register(ResourceLocation key, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) {
@SuppressWarnings("removal")
var key = ResourceLocation.fromNamespaceAndPath(ModLoadingContext.get().getActiveNamespace(), name);
Preconditions.checkArgument(!renderTypes.containsKey(key), "Render type already registered: " + key); Preconditions.checkArgument(!renderTypes.containsKey(key), "Render type already registered: " + key);
Preconditions.checkArgument(entityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The entity render type must use the NEW_ENTITY vertex format."); Preconditions.checkArgument(entityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The entity render type must use the NEW_ENTITY vertex format.");
Preconditions.checkArgument(fabulousEntityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The fabulous entity render type must use the NEW_ENTITY vertex format."); Preconditions.checkArgument(fabulousEntityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The fabulous entity render type must use the NEW_ENTITY vertex format.");
@@ -11,11 +11,11 @@ import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleType; import net.minecraft.core.particles.ParticleType;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.RegisterEvent; import net.minecraftforge.registries.RegisterEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
/** /**
* Fired for registering particle providers at the appropriate time. * Fired for registering particle providers at the appropriate time.
@@ -23,14 +23,15 @@ import org.jetbrains.annotations.ApiStatus;
* <p>{@link ParticleType}s must be registered during {@link RegisterEvent} as usual; * <p>{@link ParticleType}s must be registered during {@link RegisterEvent} as usual;
* this event is only for the {@link ParticleProvider}s.</p> * this event is only for the {@link ParticleProvider}s.</p>
* *
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterParticleProvidersEvent implements IModBusEvent { @NullMarked
public final class RegisterParticleProvidersEvent extends MutableEvent {
public static EventBus<RegisterParticleProvidersEvent> BUS = EventBus.create(RegisterParticleProvidersEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterParticleProvidersEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterParticleProvidersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterParticleProvidersEvent.class); return BUS;
} }
private final ParticleResources particles; private final ParticleResources particles;
@@ -12,22 +12,22 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader; import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing; import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
/** /**
* Allows users to register custom {@link ITextureAtlasSpriteLoader texture atlas sprite loaders}. * Allows users to register custom {@link ITextureAtlasSpriteLoader texture atlas sprite loaders}.
* *
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus}, * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public final class RegisterTextureAtlasSpriteLoadersEvent implements SelfDestructing, IModBusEvent { public final class RegisterTextureAtlasSpriteLoadersEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterTextureAtlasSpriteLoadersEvent> BUS = EventBus.create(RegisterTextureAtlasSpriteLoadersEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterTextureAtlasSpriteLoadersEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterTextureAtlasSpriteLoadersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterTextureAtlasSpriteLoadersEvent.class); return BUS;
} }
private final BiMap<ResourceLocation, ITextureAtlasSpriteLoader> loaders; private final BiMap<ResourceLocation, ITextureAtlasSpriteLoader> loaders;
@@ -39,12 +39,11 @@ public final class RegisterTextureAtlasSpriteLoadersEvent implements SelfDestruc
/** /**
* Registers a custom {@link ITextureAtlasSpriteLoader sprite loader}. * Registers a custom {@link ITextureAtlasSpriteLoader sprite loader}.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
*/ */
public void register(String name, ITextureAtlasSpriteLoader loader) { public void register(ResourceLocation resourceLocation, ITextureAtlasSpriteLoader loader) {
@SuppressWarnings("removal") Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Sprite loader already registered: " + resourceLocation);
var key = ResourceLocation.fromNamespaceAndPath(ModLoadingContext.get().getActiveNamespace(), name);
Preconditions.checkArgument(!loaders.containsKey(key), "Sprite loader already registered: " + key);
Preconditions.checkArgument(!loaders.containsValue(loader), "Sprite loader already registered as " + loaders.inverse().get(loader)); Preconditions.checkArgument(!loaders.containsValue(loader), "Sprite loader already registered as " + loaders.inverse().get(loader));
loaders.put(key, loader); loaders.put(resourceLocation, loader);
} }
} }
@@ -9,6 +9,9 @@ import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.HasResult; import net.minecraftforge.common.util.HasResult;
import net.minecraftforge.common.util.Result; import net.minecraftforge.common.util.Result;
@@ -322,13 +325,20 @@ public sealed interface ScreenEvent {
* @see MouseButtonPressed.Post * @see MouseButtonPressed.Post
*/ */
sealed interface MouseButtonPressed extends MouseInput { sealed interface MouseButtonPressed extends MouseInput {
/**
* {@return the MouseButtonEvent object containing information about the mouse button being pressed}
*/
MouseButtonEvent getInfo();
/** /**
* {@return the mouse button's input code} * {@return the mouse button's input code}
* *
* @see GLFW mouse constants starting with 'GLFW_MOUSE_BUTTON_' * @see GLFW mouse constants starting with 'GLFW_MOUSE_BUTTON_'
* @see <a href="https://www.glfw.org/docs/latest/group__buttons.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__buttons.html" target="_top">the online GLFW documentation</a>
*/ */
int getButton(); default int getButton() {
return getInfo().button();
}
/** /**
* Fired <b>before</b> the mouse click is handled by the screen. * Fired <b>before</b> the mouse click is handled by the screen.
@@ -340,7 +350,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Pre(Screen getScreen, double getMouseX, double getMouseY, int getButton) record Pre(Screen getScreen, double getMouseX, double getMouseY, MouseButtonEvent getInfo)
implements Cancellable, MouseButtonPressed, RecordEvent { implements Cancellable, MouseButtonPressed, RecordEvent {
public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class); public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class);
@@ -367,15 +377,14 @@ public sealed interface ScreenEvent {
Screen getScreen, Screen getScreen,
double getMouseX, double getMouseX,
double getMouseY, double getMouseY,
int getButton, MouseButtonEvent getInfo,
boolean wasHandled, boolean wasHandled,
Result.Holder resultHolder Result.Holder resultHolder
) implements HasResult.Record, MouseButtonPressed, RecordEvent { ) implements HasResult.Record, MouseButtonPressed, RecordEvent {
public static final EventBus<Post> BUS = EventBus.create(Post.class); public static final EventBus<Post> BUS = EventBus.create(Post.class);
@ApiStatus.Internal @ApiStatus.Internal
public Post(Screen screen, double mouseX, double mouseY, int button, boolean handled) { public Post {
this(screen, mouseX, mouseY, button, handled, new Result.Holder());
} }
/** /**
@@ -600,6 +609,12 @@ public sealed interface ScreenEvent {
* @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_key" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_key" target="_top">the online GLFW documentation</a>
*/ */
sealed interface KeyInput extends ScreenEvent { sealed interface KeyInput extends ScreenEvent {
/**
* {@return the KeyEvent object containing information about the key being pressed/released}
* @see KeyEvent
*/
KeyEvent getInfo();
/** /**
* {@return the {@code GLFW} (platform-agnostic) key code} * {@return the {@code GLFW} (platform-agnostic) key code}
* *
@@ -607,7 +622,9 @@ public sealed interface ScreenEvent {
* @see GLFW key constants starting with {@code GLFW_KEY_} * @see GLFW key constants starting with {@code GLFW_KEY_}
* @see <a href="https://www.glfw.org/docs/latest/group__keys.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__keys.html" target="_top">the online GLFW documentation</a>
*/ */
int getKeyCode(); default int getKeyCode() {
return getInfo().key();
}
/** /**
* {@return the platform-specific scan code} * {@return the platform-specific scan code}
@@ -618,7 +635,9 @@ public sealed interface ScreenEvent {
* *
* @see InputConstants#getKey(int, int) * @see InputConstants#getKey(int, int)
*/ */
int getScanCode(); default int getScanCode() {
return getInfo().scancode();
}
/** /**
* {@return a bit field representing the active modifier keys} * {@return a bit field representing the active modifier keys}
@@ -631,7 +650,9 @@ public sealed interface ScreenEvent {
* @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit * @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit
* @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a>
*/ */
int getModifiers(); default int getModifiers() {
return getInfo().modifiers();
}
} }
/** /**
@@ -652,8 +673,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Pre(Screen getScreen, int getKeyCode, int getScanCode, int getModifiers) record Pre(Screen getScreen, KeyEvent getInfo) implements Cancellable, KeyPressed, RecordEvent {
implements Cancellable, KeyPressed, RecordEvent {
public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class); public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -670,8 +690,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Post(Screen getScreen, int getKeyCode, int getScanCode, int getModifiers) record Post(Screen getScreen, KeyEvent getInfo) implements Cancellable, KeyPressed, RecordEvent {
implements Cancellable, KeyPressed, RecordEvent {
public static final CancellableEventBus<Post> BUS = CancellableEventBus.create(Post.class); public static final CancellableEventBus<Post> BUS = CancellableEventBus.create(Post.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -697,8 +716,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Pre(Screen getScreen, int getKeyCode, int getScanCode, int getModifiers) record Pre(Screen getScreen, KeyEvent getInfo) implements Cancellable, KeyReleased, RecordEvent {
implements Cancellable, KeyReleased, RecordEvent {
public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class); public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -715,8 +733,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Post(Screen getScreen, int getKeyCode, int getScanCode, int getModifiers) record Post(Screen getScreen, KeyEvent getInfo) implements Cancellable, KeyReleased, RecordEvent {
implements Cancellable, KeyReleased, RecordEvent {
public static final CancellableEventBus<Post> BUS = CancellableEventBus.create(Post.class); public static final CancellableEventBus<Post> BUS = CancellableEventBus.create(Post.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -733,10 +750,18 @@ public sealed interface ScreenEvent {
* @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_char" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/input_guide.html#input_char" target="_top">the online GLFW documentation</a>
*/ */
sealed interface CharacterTyped extends ScreenEvent { sealed interface CharacterTyped extends ScreenEvent {
/**
* {@return The CharacterEvent object containing information about the character being typed}
*/
CharacterEvent getInfo();
/** /**
* {@return the character code point} * {@return the character code point}
*/ */
char getCodePoint(); default char getCodePoint() {
return (char)getInfo().codepoint();
}
/** /**
* {@return a bit field representing the active modifier keys} * {@return a bit field representing the active modifier keys}
@@ -749,7 +774,9 @@ public sealed interface ScreenEvent {
* @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit * @see GLFW#GLFW_KEY_NUM_LOCK NUM LOCK modifier key bit
* @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a> * @see <a href="https://www.glfw.org/docs/latest/group__mods.html" target="_top">the online GLFW documentation</a>
*/ */
int getModifiers(); default int getModifiers() {
return getInfo().modifiers();
}
/** /**
* Fired <b>before</b> the character input is handled by the screen. * Fired <b>before</b> the character input is handled by the screen.
@@ -761,8 +788,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Pre(Screen getScreen, char getCodePoint, int getModifiers) record Pre(Screen getScreen, CharacterEvent getInfo) implements Cancellable, CharacterTyped, RecordEvent {
implements Cancellable, CharacterTyped, RecordEvent {
public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class); public static final CancellableEventBus<Pre> BUS = CancellableEventBus.create(Pre.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -779,7 +805,7 @@ public sealed interface ScreenEvent {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}, * <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Post(Screen getScreen, char getCodePoint, int getModifiers) implements CharacterTyped, RecordEvent { record Post(Screen getScreen, CharacterEvent getInfo) implements CharacterTyped, RecordEvent {
public static final EventBus<Post> BUS = EventBus.create(Post.class); public static final EventBus<Post> BUS = EventBus.create(Post.class);
@ApiStatus.Internal @ApiStatus.Internal
@@ -8,8 +8,8 @@ package net.minecraftforge.client.event;
import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullMarked;
@@ -31,8 +31,7 @@ public sealed interface TextureStitchEvent {
// * <p>Fired <b>before</b> a texture atlas is stitched together. // * <p>Fired <b>before</b> a texture atlas is stitched together.
// * This can be used to add custom sprites to be stitched into the atlas.</p> // * This can be used to add custom sprites to be stitched into the atlas.</p>
// * // *
// * <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus()} mod-specific event bus}, // * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
// * only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
// */ // */
// public static class Pre extends TextureStitchEvent { // public static class Pre extends TextureStitchEvent {
// private final Set<ResourceLocation> sprites; // private final Set<ResourceLocation> sprites;
@@ -61,9 +60,12 @@ public sealed interface TextureStitchEvent {
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
record Post(TextureAtlas getAtlas) implements TextureStitchEvent, IModBusEvent { record Post(TextureAtlas getAtlas) implements RecordEvent, TextureStitchEvent {
public static final EventBus<Post> BUS = EventBus.create(Post.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<Post> getBus(BusGroup modBusGroup) { public static EventBus<Post> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, Post.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
@@ -8,9 +8,10 @@ package net.minecraftforge.client.event.sound;
import net.minecraft.client.sounds.SoundEngine; import net.minecraft.client.sounds.SoundEngine;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
/** /**
* Fired when the {@link SoundEngine} is constructed or (re)loaded, such as during game initialization or when the sound * Fired when the {@link SoundEngine} is constructed or (re)loaded, such as during game initialization or when the sound
@@ -18,9 +19,13 @@ import org.jetbrains.annotations.ApiStatus;
* *
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p> * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/ */
public record SoundEngineLoadEvent(SoundEngine getEngine) implements IModBusEvent, SoundEvent { @NullMarked
public record SoundEngineLoadEvent(SoundEngine getEngine) implements RecordEvent, SoundEvent {
public static final EventBus<SoundEngineLoadEvent> BUS = EventBus.create(SoundEngineLoadEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<SoundEngineLoadEvent> getBus(BusGroup modBusGroup) { public static EventBus<SoundEngineLoadEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, SoundEngineLoadEvent.class); return BUS;
} }
@ApiStatus.Internal @ApiStatus.Internal
@@ -5,15 +5,14 @@
package net.minecraftforge.client.gui; package net.minecraftforge.client.gui;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent; import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.NonNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
/** /**
@@ -22,13 +21,12 @@ import java.util.function.Function;
* Provides a lookup. * Provides a lookup.
*/ */
public final class ClientTooltipComponentManager { public final class ClientTooltipComponentManager {
private static ImmutableMap<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>> FACTORIES; private static Map<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>> FACTORIES;
/** /**
* Creates a client component for the given argument, or null if unsupported. * Creates a client component for the given argument
*/ */
@Nullable public static @NonNull ClientTooltipComponent createClientTooltipComponent(@NonNull TooltipComponent component) {
public static ClientTooltipComponent createClientTooltipComponent(TooltipComponent component) {
var factory = FACTORIES.get(component.getClass()); var factory = FACTORIES.get(component.getClass());
var ret = factory != null ? factory.apply(component) : null; var ret = factory != null ? factory.apply(component) : null;
if (ret == null) if (ret == null)
@@ -40,9 +38,9 @@ public final class ClientTooltipComponentManager {
public static void init() { public static void init() {
var factories = new HashMap<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>>(); var factories = new HashMap<Class<? extends TooltipComponent>, Function<TooltipComponent, ClientTooltipComponent>>();
var event = new RegisterClientTooltipComponentFactoriesEvent(factories); var event = new RegisterClientTooltipComponentFactoriesEvent(factories);
ModLoader.postEventWrapContainerInModOrder(event); RegisterClientTooltipComponentFactoriesEvent.BUS.post(event);
FACTORIES = ImmutableMap.copyOf(factories); FACTORIES = Map.copyOf(factories);
} }
private ClientTooltipComponentManager() { } private ClientTooltipComponentManager() {}
} }
@@ -48,7 +48,7 @@ public class ClientModLoader {
createRunnableWithCatch(()->ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), ImmediateWindowHandler::renderTick)).run(); createRunnableWithCatch(()->ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), ImmediateWindowHandler::renderTick)).run();
if (error == null) { if (error == null) {
ResourcePackLoader.loadResourcePacks(defaultResourcePacks, true); ResourcePackLoader.loadResourcePacks(defaultResourcePacks, true);
ModLoader.postEvent(new AddPackFindersEvent(PackType.CLIENT_RESOURCES, defaultResourcePacks::addPackFinder)); net.minecraftforge.event.AddPackFindersEvent.BUS.post(new AddPackFindersEvent(PackType.CLIENT_RESOURCES, defaultResourcePacks::addPackFinder));
DataPackConfig.DEFAULT.addModPacks(ResourcePackLoader.getPackNames()); DataPackConfig.DEFAULT.addModPacks(ResourcePackLoader.getPackNames());
mcResourceManager.registerReloadListener(ClientModLoader::onResourceReload); mcResourceManager.registerReloadListener(ClientModLoader::onResourceReload);
mcResourceManager.registerReloadListener(BrandingControl.resourceManagerReloadListener()); mcResourceManager.registerReloadListener(BrandingControl.resourceManagerReloadListener());
@@ -5,14 +5,13 @@
package net.minecraftforge.client.model.geometry; package net.minecraftforge.client.model.geometry;
import com.google.common.collect.ImmutableMap;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -21,7 +20,7 @@ import java.util.stream.Collectors;
* Provides a lookup. * Provides a lookup.
*/ */
public final class GeometryLoaderManager { public final class GeometryLoaderManager {
private static ImmutableMap<ResourceLocation, IGeometryLoader> LOADERS; private static Map<ResourceLocation, IGeometryLoader> LOADERS;
private static String LOADER_LIST; private static String LOADER_LIST;
/** /**
@@ -42,11 +41,10 @@ public final class GeometryLoaderManager {
@ApiStatus.Internal @ApiStatus.Internal
public static void init() { public static void init() {
var loaders = new HashMap<ResourceLocation, IGeometryLoader>(); var loaders = new HashMap<ResourceLocation, IGeometryLoader>();
var event = new ModelEvent.RegisterGeometryLoaders(loaders); ModelEvent.RegisterGeometryLoaders.BUS.post(new ModelEvent.RegisterGeometryLoaders(loaders));
ModLoader.postEventWrapContainerInModOrder(event); LOADERS = Map.copyOf(loaders);
LOADERS = ImmutableMap.copyOf(loaders);
LOADER_LIST = loaders.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(", ")); LOADER_LIST = loaders.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
} }
private GeometryLoaderManager() { } private GeometryLoaderManager() {}
} }
@@ -10,7 +10,6 @@ import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableBiMap;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent; import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -39,8 +38,7 @@ public final class TextureAtlasSpriteLoaderManager {
@ApiStatus.Internal @ApiStatus.Internal
public static void init() { public static void init() {
var loaders = HashBiMap.<ResourceLocation, ITextureAtlasSpriteLoader>create(); var loaders = HashBiMap.<ResourceLocation, ITextureAtlasSpriteLoader>create();
var event = new RegisterTextureAtlasSpriteLoadersEvent(loaders); RegisterTextureAtlasSpriteLoadersEvent.BUS.post(new RegisterTextureAtlasSpriteLoadersEvent(loaders));
ModLoader.postEventWrapContainerInModOrder(event);
LOADERS = ImmutableBiMap.copyOf(loaders); LOADERS = ImmutableBiMap.copyOf(loaders);
} }
@@ -790,9 +790,9 @@ public final class ForgeHooks {
@Deprecated @Deprecated
public static void modifyAttributes() { public static void modifyAttributes() {
ModLoader.postEvent(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES)); EntityAttributeCreationEvent.BUS.post(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES));
Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> finalMap = new HashMap<>(); Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> finalMap = new HashMap<>();
ModLoader.postEvent(new EntityAttributeModificationEvent(finalMap)); EntityAttributeModificationEvent.BUS.post(new EntityAttributeModificationEvent(finalMap));
finalMap.forEach((k, v) -> { finalMap.forEach((k, v) -> {
AttributeSupplier supplier = DefaultAttributes.getSupplier(k); AttributeSupplier supplier = DefaultAttributes.getSupplier(k);
@@ -1066,7 +1066,7 @@ public final class ForgeHooks {
entries.put(stack, vis); entries.put(stack, vis);
}); });
ModLoader.postEvent(new BuildCreativeModeTabContentsEvent(tab, tabKey, params, entries)); BuildCreativeModeTabContentsEvent.BUS.post(new BuildCreativeModeTabContentsEvent(tab, tabKey, params, entries));
for (var entry : entries) for (var entry : entries)
output.accept(entry.getKey(), entry.getValue()); output.accept(entry.getKey(), entry.getValue());
@@ -386,7 +386,7 @@ public class ForgeMod {
BusGroup modBusGroup = context.getModBusGroup(); BusGroup modBusGroup = context.getModBusGroup();
// Forge-provided datapack registries // Forge-provided datapack registries
DataPackRegistryEvent.NewRegistry.getBus(modBusGroup).addListener(event -> { DataPackRegistryEvent.NewRegistry.BUS.addListener(event -> {
event.dataPackRegistry(ForgeRegistries.Keys.BIOME_MODIFIERS, BiomeModifier.DIRECT_CODEC); event.dataPackRegistry(ForgeRegistries.Keys.BIOME_MODIFIERS, BiomeModifier.DIRECT_CODEC);
event.dataPackRegistry(ForgeRegistries.Keys.STRUCTURE_MODIFIERS, StructureModifier.DIRECT_CODEC); event.dataPackRegistry(ForgeRegistries.Keys.STRUCTURE_MODIFIERS, StructureModifier.DIRECT_CODEC);
}); });
@@ -395,7 +395,7 @@ public class ForgeMod {
var registerEventBus = RegisterEvent.getBus(modBusGroup); var registerEventBus = RegisterEvent.getBus(modBusGroup);
registerEventBus.addListener(ForgeMod::registerFluids); registerEventBus.addListener(ForgeMod::registerFluids);
registerEventBus.addListener(ForgeMod::registerVanillaDisplayContexts); registerEventBus.addListener(ForgeMod::registerVanillaDisplayContexts);
EntityAttributeModificationEvent.getBus(modBusGroup).addListener(ForgeMod::onRegisterAttributes); EntityAttributeModificationEvent.BUS.addListener(ForgeMod::onRegisterAttributes);
ForgeDeferredRegistriesSetup.setup(modBusGroup); ForgeDeferredRegistriesSetup.setup(modBusGroup);
for (var reg : registries) for (var reg : registries)
reg.register(modBusGroup); reg.register(modBusGroup);
@@ -9,6 +9,7 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.Logging; import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader; import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.forgespi.language.ModFileScanData;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@@ -91,7 +92,7 @@ public final class CapabilityManager {
var autos = modlist.getAllScanData().stream() var autos = modlist.getAllScanData().stream()
.flatMap(e -> e.getAnnotations().stream()) .flatMap(e -> e.getAnnotations().stream())
.filter(a -> AUTO_REGISTER.equals(a.annotationType())) .filter(a -> AUTO_REGISTER.equals(a.annotationType()))
.map(a -> a.clazz()) .map(ModFileScanData.AnnotationData::clazz)
.distinct() .distinct()
.sorted(Comparator.comparing(Type::toString)) .sorted(Comparator.comparing(Type::toString))
.toList(); .toList();
@@ -102,8 +103,7 @@ public final class CapabilityManager {
} }
@SuppressWarnings("removal") @SuppressWarnings("removal")
var event = new RegisterCapabilitiesEvent(); var event = RegisterCapabilitiesEvent.BUS.fire(new RegisterCapabilitiesEvent());
ModLoader.postEvent(event);
} }
private static void error(String message) { private static void error(String message) {
@@ -9,10 +9,10 @@ import java.util.Objects;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import org.jspecify.annotations.NullMarked;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
import net.minecraftforge.fml.event.IModBusEvent;
/** /**
* This event fires when it is time to register your capabilities. * This event fires when it is time to register your capabilities.
* @see Capability * @see Capability
@@ -20,9 +20,13 @@ import net.minecraftforge.fml.event.IModBusEvent;
* @deprecated Use {@link AutoRegisterCapability} annotation on your class. * @deprecated Use {@link AutoRegisterCapability} annotation on your class.
*/ */
@Deprecated(forRemoval = true, since = "1.21") @Deprecated(forRemoval = true, since = "1.21")
public final class RegisterCapabilitiesEvent implements IModBusEvent { @NullMarked
public record RegisterCapabilitiesEvent() implements RecordEvent {
public static final EventBus<RegisterCapabilitiesEvent> BUS = EventBus.create(RegisterCapabilitiesEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterCapabilitiesEvent> getBus(BusGroup modBusGroup) { public static EventBus<RegisterCapabilitiesEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, RegisterCapabilitiesEvent.class); return BUS;
} }
/** /**
@@ -10,7 +10,7 @@ import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.RepositorySource; import net.minecraft.server.packs.repository.RepositorySource;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.eventbus.api.event.RecordEvent;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -19,9 +19,12 @@ import java.util.function.Consumer;
* *
* @param getPackType the {@link PackType} of the pack repository being constructed. * @param getPackType the {@link PackType} of the pack repository being constructed.
*/ */
public record AddPackFindersEvent(PackType getPackType, Consumer<RepositorySource> sourceAdder) implements IModBusEvent { public record AddPackFindersEvent(PackType getPackType, Consumer<RepositorySource> sourceAdder) implements RecordEvent {
public static final EventBus<AddPackFindersEvent> BUS = EventBus.create(AddPackFindersEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<AddPackFindersEvent> getBus(BusGroup modBusGroup) { public static EventBus<AddPackFindersEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, AddPackFindersEvent.class); return BUS;
} }
/** /**
@@ -13,10 +13,10 @@ import net.minecraft.world.level.ItemLike;
import net.minecraftforge.common.util.MutableHashedLinkedMap; import net.minecraftforge.common.util.MutableHashedLinkedMap;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.function.Supplier; import java.util.function.Supplier;
@@ -25,53 +25,33 @@ import java.util.function.Supplier;
* This event may be fired multiple times if the operator status of the local player or enabled feature flags changes. * This event may be fired multiple times if the operator status of the local player or enabled feature flags changes.
* <p> * <p>
* This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}. * This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.
*
* @param getTab the creative mode tab currently populating its contents
* @param getTabKey the key of the creative mode tab currently populating its contents
*/ */
public final class BuildCreativeModeTabContentsEvent implements IModBusEvent, CreativeModeTab.Output { @NullMarked
public static EventBus<BuildCreativeModeTabContentsEvent> getBus(BusGroup modBusGroup) { public record BuildCreativeModeTabContentsEvent(
return IModBusEvent.getBus(modBusGroup, BuildCreativeModeTabContentsEvent.class); CreativeModeTab getTab,
} ResourceKey<CreativeModeTab> getTabKey,
CreativeModeTab.ItemDisplayParameters getParameters,
MutableHashedLinkedMap<ItemStack, CreativeModeTab.TabVisibility> getEntries
) implements RecordEvent, CreativeModeTab.Output {
public static final EventBus<BuildCreativeModeTabContentsEvent> BUS = EventBus.create(BuildCreativeModeTabContentsEvent.class);
private final CreativeModeTab tab; @Deprecated(forRemoval = true, since = "1.21.9")
private final CreativeModeTab.ItemDisplayParameters parameters; public static EventBus<BuildCreativeModeTabContentsEvent> getBus(BusGroup modBusGroup) {
private final MutableHashedLinkedMap<ItemStack, CreativeModeTab.TabVisibility> entries; return BUS;
private final ResourceKey<CreativeModeTab> tabKey; }
@ApiStatus.Internal @ApiStatus.Internal
public BuildCreativeModeTabContentsEvent(CreativeModeTab tab, ResourceKey<CreativeModeTab> tabKey, CreativeModeTab.ItemDisplayParameters parameters, MutableHashedLinkedMap<ItemStack, CreativeModeTab.TabVisibility> entries) { public BuildCreativeModeTabContentsEvent {}
this.tab = tab;
this.tabKey = tabKey;
this.parameters = parameters;
this.entries = entries;
}
/**
* {@return the creative mode tab currently populating its contents}
*/
public CreativeModeTab getTab() {
return this.tab;
}
/**
* {@return the key of the creative mode tab currently populating its contents}
*/
public ResourceKey<CreativeModeTab> getTabKey() {
return this.tabKey;
}
public FeatureFlagSet getFlags() { public FeatureFlagSet getFlags() {
return this.parameters.enabledFeatures(); return getParameters.enabledFeatures();
}
public CreativeModeTab.ItemDisplayParameters getParameters() {
return parameters;
} }
public boolean hasPermissions() { public boolean hasPermissions() {
return this.parameters.hasPermissions(); return getParameters.hasPermissions();
}
public MutableHashedLinkedMap<ItemStack, CreativeModeTab.TabVisibility> getEntries() {
return this.entries;
} }
@Override @Override
@@ -942,9 +942,8 @@ public final class ForgeEventFactory {
PlayerInteractEvent.RightClickEmpty.BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand)); PlayerInteractEvent.RightClickEmpty.BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand));
} }
// TODO: Remove from mod bus - Lex 04222024
public static void addPackFindersServer(Consumer<RepositorySource> consumer) { public static void addPackFindersServer(Consumer<RepositorySource> consumer) {
ModLoader.postEvent(new AddPackFindersEvent(PackType.SERVER_DATA, consumer)); net.minecraftforge.event.AddPackFindersEvent.BUS.post(new AddPackFindersEvent(PackType.SERVER_DATA, consumer));
} }
public static boolean onEntityJoinLevel(Entity entity, Level level) { public static boolean onEntityJoinLevel(Entity entity, Level level) {
@@ -13,18 +13,19 @@ import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes; import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.eventbus.api.event.MutableEvent;
/** /**
* EntityAttributeCreationEvent.<br> * EntityAttributeCreationEvent.<br>
* Use this event to register attributes for your own EntityTypes. * Use this event to register attributes for your own EntityTypes.
* This event is fired after registration and before common setup. * This event is fired after registration and before common setup.
* <br>
* Fired on the Mod bus {@link IModBusEvent}.<br>
**/ **/
public final class EntityAttributeCreationEvent implements IModBusEvent { public final class EntityAttributeCreationEvent extends MutableEvent {
public static final EventBus<EntityAttributeCreationEvent> BUS = EventBus.create(EntityAttributeCreationEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<EntityAttributeCreationEvent> getBus(BusGroup modBusGroup) { public static EventBus<EntityAttributeCreationEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, EntityAttributeCreationEvent.class); return BUS;
} }
private final Map<EntityType<? extends LivingEntity>, AttributeSupplier> map; private final Map<EntityType<? extends LivingEntity>, AttributeSupplier> map;
@@ -5,8 +5,6 @@
package net.minecraftforge.event.entity; package net.minecraftforge.event.entity;
import com.google.common.collect.ImmutableList;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
@@ -15,23 +13,23 @@ import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes; import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistries;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
/** /**
* EntityAttributeModificationEvent.<br> * EntityAttributeModificationEvent.<br>
* Use this event to add attributes to existing entity types. * Use this event to add attributes to existing entity types.
* This event is fired after registration and before common setup, and after {@link EntityAttributeCreationEvent} * This event is fired after registration and before common setup, and after {@link EntityAttributeCreationEvent}
* <br>
* Fired on the Mod bus {@link IModBusEvent}.<br>
**/ **/
public final class EntityAttributeModificationEvent implements IModBusEvent { public final class EntityAttributeModificationEvent extends MutableEvent {
public static final EventBus<EntityAttributeModificationEvent> BUS = EventBus.create(EntityAttributeModificationEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<EntityAttributeModificationEvent> getBus(BusGroup modBusGroup) { public static EventBus<EntityAttributeModificationEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, EntityAttributeModificationEvent.class); return BUS;
} }
private final Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> entityAttributes; private final Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> entityAttributes;
@@ -40,11 +38,11 @@ public final class EntityAttributeModificationEvent implements IModBusEvent {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public EntityAttributeModificationEvent(Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> mapIn) { public EntityAttributeModificationEvent(Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> mapIn) {
this.entityAttributes = mapIn; this.entityAttributes = mapIn;
this.entityTypes = ImmutableList.copyOf( this.entityTypes = List.copyOf(
ForgeRegistries.ENTITY_TYPES.getValues().stream() ForgeRegistries.ENTITY_TYPES.getValues().stream()
.filter(DefaultAttributes::hasSupplier) .filter(DefaultAttributes::hasSupplier)
.map(entityType -> (EntityType<? extends LivingEntity>) entityType) .map(entityType -> (EntityType<? extends LivingEntity>) entityType)
.collect(Collectors.toList()) .toList()
); );
} }
@@ -18,7 +18,8 @@ import net.minecraft.world.entity.SpawnPlacements;
import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.listener.Priority;
import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@@ -26,24 +27,23 @@ import org.jetbrains.annotations.ApiStatus;
/** /**
* This event allows each {@link EntityType} to have a {@link SpawnPlacements.SpawnPredicate} registered or modified. * This event allows each {@link EntityType} to have a {@link SpawnPlacements.SpawnPredicate} registered or modified.
* Spawn Predicates are checked whenever an {@link Entity} of the given {@link EntityType} spawns in the world naturally. * Spawn Predicates are checked whenever an {@link Entity} of the given {@link EntityType} spawns in the world naturally.
* * <br>
* If registering your own entity's spawn placements, you should use {@link SpawnPlacementRegisterEvent#register(EntityType, SpawnPlacements.Type, Heightmap.Types, SpawnPlacements.SpawnPredicate, Operation)} * If registering your own entity's spawn placements, you should use {@link SpawnPlacementRegisterEvent#register(EntityType, SpawnPlacementType, Heightmap.Types, SpawnPlacements.SpawnPredicate, Operation)}
* So that you ensure that your entity has a heightmap type and placement type registered. * So that you ensure that your entity has a heightmap type and placement type registered.
* * <br>
* If modifying vanilla or another mod's spawn placements, you can use three operations: * If modifying vanilla or another mod's spawn placements, you can use three operations:
* REPLACE: checked first, the last mod to replace the predicate wipes out all other predicates. Listen with a low {@link EventPriority} if you need to do this. * <ul>
* OR: checked second, only one of these predicates must pass along with the original predicate * <li>REPLACE: checked first, the last mod to replace the predicate wipes out all other predicates. Listen with a low {@link Priority} if you need to do this.</li>
* AND: checked third, these predicates must all pass along with the original predicate * <li>OR: checked second, only one of these predicates must pass along with the original predicate</li>
* * <li>AND: checked third, these predicates must all pass along with the original predicate</li>
* <p> * </ul>
* This event is not {@linkplain Cancelable cancellable} and does not {@linkplain Event.HasResult have a result}.
* <p>
*
* Fired on the Mod bus {@link IModBusEvent}.<br>
*/ */
public final class SpawnPlacementRegisterEvent implements IModBusEvent { public final class SpawnPlacementRegisterEvent extends MutableEvent {
public static final EventBus<SpawnPlacementRegisterEvent> BUS = EventBus.create(SpawnPlacementRegisterEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<SpawnPlacementRegisterEvent> getBus(BusGroup modBusGroup) { public static EventBus<SpawnPlacementRegisterEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, SpawnPlacementRegisterEvent.class); return BUS;
} }
private final Map<EntityType<?>, MergedSpawnPredicate<?>> map; private final Map<EntityType<?>, MergedSpawnPredicate<?>> map;
@@ -151,7 +151,7 @@ public final class SpawnPlacementRegisterEvent implements IModBusEvent {
} }
@ApiStatus.Internal @ApiStatus.Internal
public SpawnPlacements.SpawnPredicate<T> build() { public final SpawnPlacements.SpawnPredicate<T> build() {
if (replacementPredicate != null) { if (replacementPredicate != null) {
return replacementPredicate; return replacementPredicate;
} }
@@ -17,14 +17,14 @@ import java.util.function.Consumer;
/** /**
* This is the first of four commonly called events during mod initialization. * This is the first of four commonly called events during mod initialization.
* * <br><br>
* Called after {@link net.minecraftforge.registries.RegisterEvent} events have been fired and before * Called after {@link net.minecraftforge.registries.RegisterEvent} events have been fired and before
* {@link FMLClientSetupEvent} or {@link FMLDedicatedServerSetupEvent} during mod startup. * {@link FMLClientSetupEvent} or {@link FMLDedicatedServerSetupEvent} during mod startup.
* * <br><br>
* Either register your listener using {@link net.minecraftforge.fml.javafmlmod.AutomaticEventSubscriber} and * Either register your listener using {@link net.minecraftforge.fml.javafmlmod.AutomaticEventSubscriber} and
* {@link net.minecraftforge.eventbus.api.SubscribeEvent} or * {@link net.minecraftforge.eventbus.api.listener.SubscribeEvent} or
* {@link net.minecraftforge.eventbus.api.IEventBus#addListener(Consumer)} in your constructor. * {@link net.minecraftforge.eventbus.api.bus.EventBus#addListener(Consumer)} in your constructor.
* * <br><br>
* Most non-specific mod setup will be performed here. Note that this is a parallel dispatched event - you cannot * Most non-specific mod setup will be performed here. Note that this is a parallel dispatched event - you cannot
* interact with game state in this event. * interact with game state in this event.
* *
@@ -14,30 +14,28 @@ import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public sealed abstract class DataPackRegistryEvent implements IModBusEvent { public sealed interface DataPackRegistryEvent {
@ApiStatus.Internal
protected DataPackRegistryEvent() {}
/** /**
* Fired when datapack registries can be registered. * Fired when datapack registries can be registered.
* Datapack registries are registries which can only load entries through JSON files from datapacks. * Datapack registries are registries which can only load entries through JSON files from datapacks.
* <p> * <p>
* Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where {@code modid} is the namespace of the registry key. * Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where {@code modid} is the namespace of the registry key.
* <p> * <p>
* This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}. * This event is fired on both {@linkplain LogicalSide logical sides}.
* <p>
* This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* on both {@linkplain LogicalSide logical sides}.
*/ */
public static final class NewRegistry extends DataPackRegistryEvent { final class NewRegistry extends MutableEvent implements DataPackRegistryEvent {
public static final EventBus<NewRegistry> BUS = EventBus.create(NewRegistry.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<NewRegistry> getBus(BusGroup modBusGroup) { public static EventBus<NewRegistry> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, NewRegistry.class); return BUS;
} }
private final List<DataPackRegistryData<?>> registryDataList = new ArrayList<>(); private final List<DataPackRegistryData<?>> registryDataList = new ArrayList<>();
@@ -12,7 +12,6 @@ import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey; import net.minecraft.tags.TagKey;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.fml.javafmlmod.FMLModContainer; import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.registries.tags.ITagManager; import net.minecraftforge.registries.tags.ITagManager;
@@ -20,7 +19,6 @@ import net.minecraftforge.registries.tags.ITagManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandles;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
@@ -322,7 +320,9 @@ public class DeferredRegister<T> {
* your language provider's equivalent. * your language provider's equivalent.
*/ */
public void register(BusGroup modBusGroup) { public void register(BusGroup modBusGroup) {
modBusGroup.register(EventDispatcher.LOOKUP, new EventDispatcher()); var dispatcher = new EventDispatcher();
RegisterEvent.getBus(modBusGroup).addListener(dispatcher::handleEvent);
NewRegistryEvent.BUS.addListener(dispatcher::createRegistry);
} }
/** /**
@@ -376,9 +376,6 @@ public class DeferredRegister<T> {
} }
private final class EventDispatcher { private final class EventDispatcher {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
@SubscribeEvent
public void handleEvent(RegisterEvent event) { public void handleEvent(RegisterEvent event) {
if (event.getRegistryKey().equals(registryKey)) { if (event.getRegistryKey().equals(registryKey)) {
seenRegisterEvent = true; seenRegisterEvent = true;
@@ -392,7 +389,6 @@ public class DeferredRegister<T> {
} }
} }
@SubscribeEvent
public void createRegistry(NewRegistryEvent event) { public void createRegistry(NewRegistryEvent event) {
if (registryFactory != null) if (registryFactory != null)
event.create(registryFactory.get(), DeferredRegister.this::onFill); event.create(registryFactory.get(), DeferredRegister.this::onFill);
@@ -16,16 +16,19 @@ import net.minecraft.core.MappedRegistry;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.eventbus.api.event.MutableEvent;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
/** /**
* Register new registries when you receive this event through {@link RegistryBuilder} and {@link #create(RegistryBuilder)}. * Register new registries when you receive this event through {@link RegistryBuilder} and {@link #create(RegistryBuilder)}.
*/ */
public final class NewRegistryEvent implements IModBusEvent { public final class NewRegistryEvent extends MutableEvent {
public static final EventBus<NewRegistryEvent> BUS = EventBus.create(NewRegistryEvent.class);
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<NewRegistryEvent> getBus(BusGroup modBusGroup) { public static EventBus<NewRegistryEvent> getBus(BusGroup modBusGroup) {
return IModBusEvent.getBus(modBusGroup, NewRegistryEvent.class); return BUS;
} }
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
@@ -131,12 +131,10 @@ public class RegistryManager {
} }
public static void postNewRegistryEvent() { public static void postNewRegistryEvent() {
NewRegistryEvent event = new NewRegistryEvent();
DataPackRegistryEvent.NewRegistry dataPackEvent = new DataPackRegistryEvent.NewRegistry();
vanillaRegistryKeys = Set.copyOf(BuiltInRegistries.REGISTRY.keySet()); vanillaRegistryKeys = Set.copyOf(BuiltInRegistries.REGISTRY.keySet());
ModLoader.postEventWrapContainerInModOrder(event); var event = NewRegistryEvent.BUS.fire(new NewRegistryEvent());
ModLoader.postEventWrapContainerInModOrder(dataPackEvent); var dataPackEvent = DataPackRegistryEvent.NewRegistry.BUS.fire(new DataPackRegistryEvent.NewRegistry());
event.fill(); event.fill();
dataPackEvent.process(); dataPackEvent.process();
@@ -86,7 +86,7 @@ public final class ExampleMod {
CREATIVE_MODE_TABS.register(modBusGroup); CREATIVE_MODE_TABS.register(modBusGroup);
// Register the item to a creative tab // Register the item to a creative tab
BuildCreativeModeTabContentsEvent.getBus(modBusGroup).addListener(ExampleMod::addCreative); BuildCreativeModeTabContentsEvent.BUS.addListener(ExampleMod::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us // Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
context.registerConfig(ModConfig.Type.COMMON, Config.SPEC); context.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
@@ -42,7 +42,6 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.FMLLoader;
@@ -52,7 +51,6 @@ import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.RegistryObject; import net.minecraftforge.registries.RegistryObject;
import net.minecraftforge.test.BaseTestMod; import net.minecraftforge.test.BaseTestMod;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -78,16 +76,16 @@ public class AdditionalModelTest extends BaseTestMod {
public AdditionalModelTest(FMLJavaModLoadingContext context) { public AdditionalModelTest(FMLJavaModLoadingContext context) {
super(context, false, FMLLoader.getLaunchHandler().isData()); super(context, false, FMLLoader.getLaunchHandler().isData());
modBus.register(MethodHandles.lookup(), this); GatherDataEvent.getBus(modBus).addListener(this::runData);
ModelEvent.RegisterModelStateDefinitions.BUS.addListener(this::onRegisterAdditional);
EntityRenderersEvent.AddLayers.BUS.addListener(this::onAddLayers);
} }
@SubscribeEvent
public void runData(GatherDataEvent event) { public void runData(GatherDataEvent event) {
var out = event.getGenerator().getPackOutput(); var out = event.getGenerator().getPackOutput();
event.getGenerator().addProvider(event.includeClient(), new ModelProvider(out)); event.getGenerator().addProvider(event.includeClient(), new ModelProvider(out));
} }
@SubscribeEvent
public void onRegisterAdditional(ModelEvent.RegisterModelStateDefinitions event) { public void onRegisterAdditional(ModelEvent.RegisterModelStateDefinitions event) {
// Our fake blocks are only created during data gen, so we have to add a fake mapper // Our fake blocks are only created during data gen, so we have to add a fake mapper
event.register(rl("cow_head"), COW_HEAD_STATE); event.register(rl("cow_head"), COW_HEAD_STATE);
@@ -119,7 +117,6 @@ public class AdditionalModelTest extends BaseTestMod {
} }
// An example on how to render both the item and block model variants // An example on how to render both the item and block model variants
@SubscribeEvent
public void onAddLayers(EntityRenderersEvent.AddLayers event) { public void onAddLayers(EntityRenderersEvent.AddLayers event) {
// Pigs get a block on their head, this is a test of going through the ItemModel loader // Pigs get a block on their head, this is a test of going through the ItemModel loader
LivingEntityRenderer<Pig, PigRenderState, PigModel> pig = event.getEntityRenderer(EntityType.PIG); LivingEntityRenderer<Pig, PigRenderState, PigModel> pig = event.getEntityRenderer(EntityType.PIG);
@@ -11,7 +11,6 @@ import net.minecraftforge.client.event.AddGuiOverlayLayersEvent;
import net.minecraftforge.client.gui.overlay.ForgeLayer; import net.minecraftforge.client.gui.overlay.ForgeLayer;
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw; import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
import net.minecraftforge.common.extensions.IForgeGameTestHelper; import net.minecraftforge.common.extensions.IForgeGameTestHelper;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.gametest.GameTest; import net.minecraftforge.gametest.GameTest;
@@ -120,7 +119,6 @@ public class ModifyOverlayTest extends BaseTestMod {
}); });
} }
@SubscribeEvent
private void overlayTestListener(AddGuiOverlayLayersEvent event) { private void overlayTestListener(AddGuiOverlayLayersEvent event) {
drawStack = event.getLayeredDraw(); drawStack = event.getLayeredDraw();
var layeredDraw = event.getLayeredDraw(); var layeredDraw = event.getLayeredDraw();
@@ -41,7 +41,7 @@ public class CreativeModeTabTest {
var modBus = context.getModBusGroup(); var modBus = context.getModBusGroup();
RegisterEvent.getBus(modBus).addListener(CreativeModeTabTest::onCreativeModeTabRegister); RegisterEvent.getBus(modBus).addListener(CreativeModeTabTest::onCreativeModeTabRegister);
BuildCreativeModeTabContentsEvent.getBus(modBus).addListener(CreativeModeTabTest::onCreativeModeTabBuildContents); BuildCreativeModeTabContentsEvent.BUS.addListener(CreativeModeTabTest::onCreativeModeTabBuildContents);
} }
private static void onCreativeModeTabRegister(RegisterEvent event) { private static void onCreativeModeTabRegister(RegisterEvent event) {
@@ -41,7 +41,7 @@ public class NetworkDatapackRegistryTest extends BaseTestMod {
public NetworkDatapackRegistryTest(FMLJavaModLoadingContext context) { public NetworkDatapackRegistryTest(FMLJavaModLoadingContext context) {
super(context, false, true); super(context, false, true);
DataPackRegistryEvent.NewRegistry.getBus(modBus).addListener(this::onNewDatapackRegistry); DataPackRegistryEvent.NewRegistry.BUS.addListener(this::onNewDatapackRegistry);
} }
public void onNewDatapackRegistry(DataPackRegistryEvent.NewRegistry event) { public void onNewDatapackRegistry(DataPackRegistryEvent.NewRegistry event) {
@@ -9,7 +9,6 @@ import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@@ -37,7 +36,6 @@ import net.minecraftforge.common.data.DatapackBuiltinEntriesProvider;
import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.gametest.ForgeGameTestHooks; import net.minecraftforge.gametest.ForgeGameTestHooks;
@@ -62,8 +60,10 @@ public abstract class BaseTestMod {
public BaseTestMod(FMLJavaModLoadingContext context, boolean registerSelf, boolean registerDeferred) { public BaseTestMod(FMLJavaModLoadingContext context, boolean registerSelf, boolean registerDeferred) {
this.modBus = context.getModBusGroup(); this.modBus = context.getModBusGroup();
if (registerSelf) if (registerSelf) {
modBus.register(LookupHelper.INSTANCE.in(this.getClass()), this); modBus.register(LookupHelper.INSTANCE.in(this.getClass()), this);
BuildCreativeModeTabContentsEvent.BUS.addListener(this::onCreativeModeTabBuildContents);
}
tests = ForgeGameTestHooks.gatherTests(getClass(), this); tests = ForgeGameTestHooks.gatherTests(getClass(), this);
@@ -103,7 +103,7 @@ public abstract class BaseTestMod {
} }
private final class LookupHelper { private static final class LookupHelper {
private static final Lookup INSTANCE; private static final Lookup INSTANCE;
static { static {
try { try {
@@ -153,7 +153,6 @@ public abstract class BaseTestMod {
this.testItems.add(supplier); this.testItems.add(supplier);
} }
@SubscribeEvent
protected void onCreativeModeTabBuildContents(BuildCreativeModeTabContentsEvent event) { protected void onCreativeModeTabBuildContents(BuildCreativeModeTabContentsEvent event) {
var entries = event.getEntries(); var entries = event.getEntries();
var lookup = event.getParameters().holders(); var lookup = event.getParameters().holders();