Class CommonHooks
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static ThreadLocal<Player> private static final Stringprivate static final Map<EntityType<? extends LivingEntity>, AttributeSupplier> private static final Lazy<Map<String, StructuresBecomeConfiguredFix.Conversion>> private static final org.apache.logging.log4j.Loggerprivate static final String(package private) static final Patternstatic final intprivate static final org.apache.logging.log4j.Marker -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic booleancanContinueUsing(ItemStack from, ItemStack to) static booleancanCropGrow(Level level, BlockPos pos, BlockState state, boolean def) Checks if a crop can grow by firingCropGrowEvent.Pre.static booleancanEntityDestroy(Level level, BlockPos pos, LivingEntity entity) static booleancanMobEffectBeApplied(LivingEntity entity, MobEffectInstance effect) Checks if a mob effect can be applied to an entity by firingMobEffectEvent.Applicable.static booleanstatic ItemAttributeModifierscomputeModifiedAttributes(ItemStack stack, ItemAttributeModifiers defaultModifiers) Hook to fireItemAttributeModifierEvent.static StringencodeLifecycle(com.mojang.serialization.Lifecycle lifecycle) static BlockEvent.BreakEventfireBlockBreak(Level level, GameType gameType, ServerPlayer player, BlockPos pos, BlockState state) FiresBlockEvent.BreakEvent, pre-emptively canceling the event based on the conditions that will cause the block to not be broken anyway.static CriticalHitEventfireCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) Fires theCriticalHitEventand returns the resulting event.static voidfireCropGrowPost(Level level, BlockPos pos, BlockState state) static Map<EntityType<? extends LivingEntity>, AttributeSupplier> Deprecated.static Playerstatic ItemStackstatic @Nullable StringgetDefaultCreatorModId(ItemStack itemStack) Used as the default implementation ofIItemExtension.getCreatorModId(net.minecraft.world.item.ItemStack).static doublegetEntityVisibilityMultiplier(LivingEntity entity, Entity lookingEntity, double originalMultiplier) static ItemStackgetProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) Hook to fireLivingGetProjectileEvent.private static StringgetRawText(Component message) static @Nullable EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) static intgetSerializerId(EntityDataSerializer<?> serializer, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) static ChatDecoratorgetTagFromVanillaTier(Tiers tier) static FluidTypegetVanillaFluidType(Fluid fluid) Returns a vanilla fluid type for the given fluid.static voidhandleBlockDrops(ServerLevel level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, List<ItemEntity> drops, @Nullable Entity breaker, ItemStack tool) Fires theBlockDropsEventwhen block drops (items and experience) are determined.isLivingOnLadder(BlockState state, Level level, BlockPos pos, LivingEntity entity) private static booleanisPotentialRegistryObject(Object value) static @Nullable MobEffectloadMobEffect(CompoundTag nbt, String key, @Nullable MobEffect fallback) lootPoolsCodec(BiConsumer<LootPool, String> nameSetter) static voidmarkComponentClassAsValid(Class<?> clazz) Marks a class as being safe to use as adata component.static voidDeprecated.modifyLoot(List<ItemStack> list, LootContext context) Deprecated.static it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> generatedLoot, LootContext context) Handles the modification of loot table drops via the registered Global Loot Modifiers, so that custom effects can be processed.static ComponentnewChatWithLinks(String string) static ComponentnewChatWithLinks(String string, boolean allowMissingHeader) static booleanonAnvilChange(AnvilMenu container, ItemStack left, ItemStack right, Container outputSlot, String name, long baseCost, Player player) static floatonAnvilRepair(Player player, ItemStack output, ItemStack left, ItemStack right) static @Nullable GameTypeonChangeGameType(Player player, GameType currentGameType, GameType newGameType) static Collection<CreativeModeTab> onCheckCreativeTabs(CreativeModeTab... vanillaTabs) static voidonChunkUnload(PoiManager poiManager, ChunkAccess chunkAccess) The goal here is to fix the POI memory leak that happens due toSectionStorage.storagefield never actually removing POIs long after they become irrelevant.onClientMineHold(Player player, BlockPos pos, Direction face) static voidonDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) static voidonEmptyClick(Player player, InteractionHand hand) static voidonEmptyLeftClick(Player player) static voidonEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) static booleanonFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) static intonGrindstoneChange(ItemStack top, ItemStack bottom, Container outputSlot, int xp) static booleanonGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function<Level, Integer> xpFunction) static @Nullable InteractionResultonInteractEntity(Player player, Entity entity, InteractionHand hand) static @Nullable InteractionResultonInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) static @Nullable InteractionResultonInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) static @Nullable InteractionResultonItemRightClick(Player player, InteractionHand hand) static booleanonItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) static booleanonLivingAttack(LivingEntity entity, DamageSource src, float amount) static voidonLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) Handles living entities being underwater.static LivingChangeTargetEventonLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, LivingChangeTargetEvent.ILivingTargetType targetType) static floatonLivingDamage(LivingEntity entity, DamageSource src, float amount) static booleanonLivingDeath(LivingEntity entity, DamageSource src) static booleanonLivingDrops(LivingEntity entity, DamageSource source, Collection<ItemEntity> drops, boolean recentlyHit) static @org.jetbrains.annotations.Nullable float[]onLivingFall(LivingEntity entity, float distance, float damageMultiplier) static floatonLivingHurt(LivingEntity entity, DamageSource src, float amount) static voidonLivingJump(LivingEntity entity) static LivingKnockBackEventonLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) static LivingSwapItemsEvent.HandsonLivingSwapHandItems(LivingEntity livingEntity) static booleanonLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) static intonNoteChange(Level level, BlockPos pos, BlockState state, int old, int _new) static InteractionResultonPlaceItemIntoWorld(UseOnContext context) static booleanonPlayerAttack(LivingEntity entity, DamageSource src, float amount) static booleanonPlayerAttackTarget(Player player, Entity target) static @Nullable ItemEntityonPlayerTossEvent(Player player, ItemStack item, boolean includeName) onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) static @Nullable ComponentonServerChatSubmittedEvent(ServerPlayer player, String plain, Component decorated) static ShieldBlockEventonShieldBlock(LivingEntity blocker, DamageSource source, float blocked) static booleanonTravelToDimension(Entity entity, ResourceKey<Level> dimension) static booleanonVanillaGameEvent(Level level, Holder<GameEvent> vanillaEvent, Vec3 pos, GameEvent.Context context) private static booleanoverridesEqualsAndHashCode(Class<?> clazz) static com.mojang.serialization.LifecycleparseLifecycle(String lifecycle) static StringprefixNamespace(ResourceLocation registryKey) This method is used to prefix the path, where elements of the associated registry are stored, with their namespace, if it is not minecraftstatic voidreadAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) static <T> @Nullable HolderLookup.RegistryLookup<T> resolveLookup(ResourceKey<? extends Registry<T>> key) Attempts to resolve aHolderLookup.RegistryLookupusing the current global state.static voidsaveMobEffect(CompoundTag nbt, String key, MobEffect effect) static voidsetCraftingPlayer(Player player) static booleanshouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) static voidvalidateComponent(@Nullable Object dataComponent) Checks that all data components override equals and hashCode.static <T> HolderLookup.RegistryLookup<T> wrapRegistryLookup(HolderLookup.RegistryLookup<T> lookup) static voidwriteAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag)
-
Field Details
-
LOGGER
private static final org.apache.logging.log4j.Logger LOGGER -
WORLDPERSISTENCE
private static final org.apache.logging.log4j.Marker WORLDPERSISTENCE -
URL_PATTERN
-
craftingPlayer
-
VANILLA_SERIALIZER_LIMIT
public static final int VANILLA_SERIALIZER_LIMIT- See Also:
-
VANILLA_DIMS
-
DIMENSIONS_KEY
- See Also:
-
SEED_KEY
- See Also:
-
FORGE_ATTRIBUTES
-
FORGE_CONVERSION_MAP
private static final Lazy<Map<String,StructuresBecomeConfiguredFix.Conversion>> FORGE_CONVERSION_MAP -
checkedComponentClasses
-
-
Constructor Details
-
CommonHooks
public CommonHooks()
-
-
Method Details
-
canContinueUsing
-
onItemStackedOn
public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) -
onDifficultyChange
-
onLivingChangeTarget
public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, LivingChangeTargetEvent.ILivingTargetType targetType) -
onLivingAttack
-
onPlayerAttack
-
onLivingKnockBack
public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) -
onLivingUseTotem
public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) -
onLivingHurt
-
onLivingDamage
-
onLivingDeath
-
onLivingDrops
public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection<ItemEntity> drops, boolean recentlyHit) -
onLivingFall
@Nullable public static @org.jetbrains.annotations.Nullable float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier) -
getEntityVisibilityMultiplier
public static double getEntityVisibilityMultiplier(LivingEntity entity, Entity lookingEntity, double originalMultiplier) -
isLivingOnLadder
public static Optional<BlockPos> isLivingOnLadder(BlockState state, Level level, BlockPos pos, LivingEntity entity) -
onLivingJump
-
onPlayerTossEvent
@Nullable public static @Nullable ItemEntity onPlayerTossEvent(Player player, ItemStack item, boolean includeName) -
onVanillaGameEvent
public static boolean onVanillaGameEvent(Level level, Holder<GameEvent> vanillaEvent, Vec3 pos, GameEvent.Context context) -
getRawText
-
onServerChatSubmittedEvent
@Nullable public static @Nullable Component onServerChatSubmittedEvent(ServerPlayer player, String plain, Component decorated) -
getServerChatSubmittedDecorator
-
newChatWithLinks
-
newChatWithLinks
-
handleBlockDrops
public static void handleBlockDrops(ServerLevel level, BlockPos pos, BlockState state, @Nullable @Nullable BlockEntity blockEntity, List<ItemEntity> drops, @Nullable @Nullable Entity breaker, ItemStack tool) Fires theBlockDropsEventwhen block drops (items and experience) are determined. If the event is not cancelled, all drops will be added to the world, and thenBlockBehaviour.spawnAfterBreak(net.minecraft.world.level.block.state.BlockState, net.minecraft.server.level.ServerLevel, net.minecraft.core.BlockPos, net.minecraft.world.item.ItemStack, boolean)will be called.- Parameters:
level- The levelpos- The broken block's positionstate- The broken block's stateblockEntity- The block entity from the given positiondrops- The list of all items dropped by the block, captured fromBlock.getDrops(net.minecraft.world.level.block.state.BlockState, net.minecraft.server.level.ServerLevel, net.minecraft.core.BlockPos, net.minecraft.world.level.block.entity.BlockEntity)breaker- The entity who broke the block, or null if unknowntool- The tool used when breaking the block; may be empty
-
fireBlockBreak
public static BlockEvent.BreakEvent fireBlockBreak(Level level, GameType gameType, ServerPlayer player, BlockPos pos, BlockState state) FiresBlockEvent.BreakEvent, pre-emptively canceling the event based on the conditions that will cause the block to not be broken anyway.Note that undoing the pre-cancel will not permit breaking the block, since the vanilla conditions will always be checked.
- Parameters:
level- The levelgameType- The game type of the breaking playerplayer- The breaking playerpos- The position of the block being brokenstate- The state of the block being broken- Returns:
- The event
-
onPlaceItemIntoWorld
-
onAnvilChange
-
onAnvilRepair
-
onGrindstoneChange
-
onGrindstoneTake
public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function<Level, Integer> xpFunction) -
setCraftingPlayer
-
getCraftingPlayer
-
getCraftingRemainingItem
-
onPlayerAttackTarget
-
onTravelToDimension
-
onInteractEntityAt
@Nullable public static @Nullable InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) -
onInteractEntityAt
@Nullable public static @Nullable InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) -
onInteractEntity
@Nullable public static @Nullable InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) -
onItemRightClick
@Nullable public static @Nullable InteractionResult onItemRightClick(Player player, InteractionHand hand) -
onLeftClickBlock
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) -
onClientMineHold
public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) -
onRightClickBlock
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) -
onEmptyClick
-
onEmptyLeftClick
-
onChangeGameType
@Nullable public static @Nullable GameType onChangeGameType(Player player, GameType currentGameType, GameType newGameType) - Returns:
- null if game type should not be changed, desired new GameType otherwise
-
lootPoolsCodec
@Internal public static com.mojang.serialization.Codec<List<LootPool>> lootPoolsCodec(BiConsumer<LootPool, String> nameSetter) -
getVanillaFluidType
Returns a vanilla fluid type for the given fluid.- Parameters:
fluid- the fluid looking for its type- Returns:
- the type of the fluid if vanilla
- Throws:
RuntimeException- if the fluid is not a vanilla one
-
getTagFromVanillaTier
-
onCheckCreativeTabs
-
canCropGrow
Checks if a crop can grow by firingCropGrowEvent.Pre.- Parameters:
level- The level the crop is inpos- The position of the cropstate- The state of the cropdef- The result of the default checks performed by the crop.- Returns:
- true if the crop can grow
-
fireCropGrowPost
-
fireCriticalHit
public static CriticalHitEvent fireCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) Fires theCriticalHitEventand returns the resulting event.- Parameters:
player- The attacking playertarget- The attack targetvanillaCritical- If the attack would have been a critical hit by vanilla's rules inPlayer.attack(Entity).damageModifier- The base damage modifier. Vanilla critical hits have a damage modifier of 1.5.
-
computeModifiedAttributes
public static ItemAttributeModifiers computeModifiedAttributes(ItemStack stack, ItemAttributeModifiers defaultModifiers) Hook to fireItemAttributeModifierEvent. Modders should useItemStack.forEachModifier(EquipmentSlot, BiConsumer)instead. -
getProjectile
public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) Hook to fireLivingGetProjectileEvent. Returns the ammo to be used. -
getDefaultCreatorModId
Used as the default implementation ofIItemExtension.getCreatorModId(net.minecraft.world.item.ItemStack). Call that method instead. -
onFarmlandTrample
public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) -
onNoteChange
-
getSerializer
@Nullable public static @Nullable EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) -
getSerializerId
public static int getSerializerId(EntityDataSerializer<?> serializer, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) -
canEntityDestroy
-
modifyLoot
Deprecated.All loot table drops should be passed to this function so that mod added effects (e.g. smelting enchantments) can be processed.- Parameters:
list- The loot generatedcontext- The loot context that generated that loot- Returns:
- The modified list
-
modifyLoot
public static it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> generatedLoot, LootContext context) Handles the modification of loot table drops via the registered Global Loot Modifiers, so that custom effects can be processed.All loot-table generated loot should be passed to this function.
- Parameters:
lootTableId- The ID of the loot table currently being queriedgeneratedLoot- The loot generated by the loot tablecontext- The loot context that generated the loot, unmodified- Returns:
- The modified list of drops
-
getModDataPacks
-
getModDataPacksWithVanilla
-
getAttributesView
@Deprecated public static Map<EntityType<? extends LivingEntity>,AttributeSupplier> getAttributesView()Deprecated.FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY -
modifyAttributes
Deprecated.FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY -
onEntityEnterSection
-
onShieldBlock
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) -
onLivingSwapHandItems
-
writeAdditionalLevelSaveData
@Internal public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) -
readAdditionalLevelSaveData
@Internal public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) - Parameters:
rootTag- Level data file contents.levelDirectory- Level currently being loaded.
-
encodeLifecycle
-
parseLifecycle
-
saveMobEffect
-
loadMobEffect
@Nullable public static @Nullable MobEffect loadMobEffect(CompoundTag nbt, String key, @Nullable @Nullable MobEffect fallback) -
shouldSuppressEnderManAnger
-
prefixNamespace
This method is used to prefix the path, where elements of the associated registry are stored, with their namespace, if it is not minecraft
This rules conflicts with equal paths out. If for example the mod
fancy_cheeseadds a registry namedcheeses, but the modawesome_cheesealso adds a registry calledcheeses, they are going to have the same pathcheeses, just with different namespaces. Ifadditional_cheesewants to add additional cheese toawesome_cheese, but notfancy_cheese, it can not differentiate both. Both paths will look likedata/additional_cheese/cheeses.The fix, which is applied here prefixes the path of the registry with the namespace, so
fancy_cheese's registry stores its elements indata/<namespace>/fancy_cheese/cheesesandawesome_cheese's registry stores its elements indata/namespace/awesome_cheese/cheeses- Parameters:
registryKey- key of the registry- Returns:
- path of the registry key. Prefixed with the namespace if it is not "minecraft"
-
wrapRegistryLookup
@Internal public static <T> HolderLookup.RegistryLookup<T> wrapRegistryLookup(HolderLookup.RegistryLookup<T> lookup) -
onLivingBreathe
Handles living entities being underwater. This fires theLivingBreatheEventand if the entity's air supply is less than or equal to zero also theLivingDrownEvent. Additionally, when the entity is underwater it will dismount ifIEntityExtension.canBeRiddenUnderFluidType(FluidType, Entity)returns false.- Parameters:
entity- The living entity which is currently updatedconsumeAirAmount- The amount of air to consume when the entity is unable to breatherefillAirAmount- The amount of air to refill when the entity is able to breathe
-
markComponentClassAsValid
Marks a class as being safe to use as adata component. Keep in mind that data components are compared withObject.equals(Object)and hashed withObject.hashCode(). They must also be immutable.Only call this method if the default implementations of
Object.equals(Object)andObject.hashCode()are suitable for this class, and if instances of this class are immutable. Typically, this is only the case for singletons such asBlockinstances. -
validateComponent
Checks that all data components override equals and hashCode. -
isPotentialRegistryObject
-
overridesEqualsAndHashCode
-
onChunkUnload
The goal here is to fix the POI memory leak that happens due toSectionStorage.storagefield never actually removing POIs long after they become irrelevant. We do it here in chunk unload event so that chunk that are fully unloaded now gets the POI removed from the POI cached storage map. -
canMobEffectBeApplied
Checks if a mob effect can be applied to an entity by firingMobEffectEvent.Applicable.- Parameters:
entity- The target entity the mob effect is being applied to.effect- The mob effect being applied.- Returns:
- True if the mob effect can be applied, otherwise false.
-
resolveLookup
@Nullable public static <T> @Nullable HolderLookup.RegistryLookup<T> resolveLookup(ResourceKey<? extends Registry<T>> key) Attempts to resolve aHolderLookup.RegistryLookupusing the current global state.Prioritizes the server's lookup, only attempting to retrieve it from the client if the server is unavailable.
- Type Parameters:
T- The type of registry being looked up- Parameters:
key- The resource key for the target registry- Returns:
- A registry access, if one was available.
-
modifyLoot(ResourceLocation, ObjectArrayList, LootContext)instead.