From 32c628a99e77dcb5d5cda981159a4b94128aecce Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 17:30:19 +0100 Subject: [PATCH 001/230] 24w09a --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ff5089e052d..5626f33d0f3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=1.20.4 +minecraftVersion=24w09a recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From e0ed11bcf041f6e04ced51d5f219aac9c52393f0 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 19:19:08 +0100 Subject: [PATCH 002/230] fix data: item hide flags --- .../item/AdventureModePredicateAccessor.java | 39 ++++++++++ .../enchantment/ItemEnchantmentsAccessor.java | 47 ++++++++++++ .../resources/mixins.sponge.accessors.json | 34 ++++----- .../item/stack/HideFlagsItemStackData.java | 72 ++++++++++--------- 4 files changed, 144 insertions(+), 48 deletions(-) create mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/item/AdventureModePredicateAccessor.java create mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/AdventureModePredicateAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/AdventureModePredicateAccessor.java new file mode 100644 index 00000000000..4c0425100ce --- /dev/null +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/AdventureModePredicateAccessor.java @@ -0,0 +1,39 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.accessor.world.item; + +import net.minecraft.advancements.critereon.BlockPredicate; +import net.minecraft.world.item.AdventureModePredicate; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.List; + +@Mixin(AdventureModePredicate.class) +public interface AdventureModePredicateAccessor { + + @Accessor("predicates") List accessor$predicates(); + +} diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java new file mode 100644 index 00000000000..ed4bae5eb8d --- /dev/null +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java @@ -0,0 +1,47 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.accessor.world.item.enchantment; + +import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; +import net.minecraft.core.Holder; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.ItemEnchantments; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; +import org.spongepowered.common.UntransformedInvokerError; + +@Mixin(ItemEnchantments.class) +public interface ItemEnchantmentsAccessor { + + @Accessor("showInTooltip") boolean accessor$showInTooltip(); + + @Accessor("enchantments") Object2IntLinkedOpenHashMap> accessor$enchantments(); + + @Invoker("") static ItemEnchantments invoker$new(Object2IntLinkedOpenHashMap> $$0, boolean $$1) { + throw new UntransformedInvokerError(); + } + +} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 045a5c1e26e..8fe6a647e5d 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -23,6 +23,7 @@ "network.chat.HoverEvent_ItemStackInfoAccessor", "network.chat.StyleAccessor", "network.protocol.game.ClientboundAddEntityPacketAccessor", + "network.protocol.game.ClientboundPlayerInfoUpdatePacketAccessor", "network.protocol.game.ServerboundInteractPacket_InteractionActionAccessor", "network.protocol.game.ServerboundInteractPacket_InteractionAtLocationActionAccessor", "network.protocol.game.ServerboundInteractPacketAccessor", @@ -40,6 +41,8 @@ "server.level.ServerPlayerGameModeAccessor", "server.level.TicketAccessor", "server.level.TicketTypeAccessor", + "server.network.ServerCommonPacketListenerImplAccessor", + "server.network.ServerGamePacketListenerImplAccessor", "server.network.ServerLoginPacketListenerImplAccessor", "server.players.GameProfileCache_GameProfileInfoAccessor", "server.players.IpBanListAccessor", @@ -47,6 +50,7 @@ "server.players.StoredUserEntryAccessor", "server.players.StoredUserListAccessor", "server.rcon.thread.RconClientAccessor", + "sounds.SoundEventAccessor", "stats.StatsCounterAccessor", "util.datafix.schemas.V100Accessor", "world.CompoundContainerAccessor", @@ -54,6 +58,10 @@ "world.damagesource.CombatTrackerAccessor", "world.entity.AgableMobAccessor", "world.entity.AreaEffectCloudAccessor", + "world.entity.Display_BlockDisplayAccessor", + "world.entity.Display_ItemDisplayAccessor", + "world.entity.Display_TextDisplayAccessor", + "world.entity.DisplayAccessor", "world.entity.EntityAccessor", "world.entity.EntityTypeAccessor", "world.entity.ExperienceOrbAccessor", @@ -80,6 +88,7 @@ "world.entity.decoration.ArmorStandAccessor", "world.entity.decoration.HangingEntityAccessor", "world.entity.decoration.ItemFrameAccessor", + "world.entity.decoration.PaintingAccessor", "world.entity.item.FallingBlockEntityAccessor", "world.entity.item.PrimedTntAccessor", "world.entity.monster.BlazeAccessor", @@ -127,10 +136,12 @@ "world.inventory.MerchantMenuAccessor", "world.inventory.ResultSlotAccessor", "world.inventory.SlotAccessor", + "world.item.AdventureModePredicateAccessor", "world.item.ArmorMaterialsAccessor", "world.item.DiggerItemAccessor", "world.item.ItemCooldowns_CooldownInstanceAccessor", "world.item.RecordItemAccessor", + "world.item.enchantment.ItemEnchantmentsAccessor", "world.item.trading.MerchantOfferAccessor", "world.level.BaseCommandBlockAccessor", "world.level.BaseSpawnerAccessor", @@ -141,7 +152,11 @@ "world.level.LevelSettingsAccessor", "world.level.NaturalSpawner_SpawnStateAccessor", "world.level.NaturalSpawnerAccessor", + "world.level.biome.Biome_ClimateSettingsAccessor", + "world.level.biome.BiomeAccessor", + "world.level.biome.MobSpawnSettingsAccessor", "world.level.biome.MultiNoiseBiomeSourceAccessor", + "world.level.biome.OverworldBiomeBuilderAccessor", "world.level.biome.TheEndBiomeSourceAccessor", "world.level.block.AbstractSkullBlockAccessor", "world.level.block.BaseFireBlockAccessor", @@ -177,28 +192,15 @@ "world.level.dimension.DimensionTypeAccessor", "world.level.entity.EntityTickListAccessor", "world.level.entity.PersistentEntitySectionManagerAccessor", + "world.level.levelgen.NoiseSettingsAccessor", "world.level.levelgen.flat.FlatLevelGeneratorSettingsAccessor", + "world.level.levelgen.structure.pools.StructureTemplatePoolAccessor", "world.level.saveddata.maps.MapItemSavedDataAccessor", "world.level.storage.LevelStorageSource_LevelStorageAccessAccessor", "world.level.storage.PlayerDataStorageAccessor", "world.phys.AABBAccessor", "world.scores.PlayerTeamAccessor", - "world.entity.decoration.PaintingAccessor", - "world.scores.ScoreboardAccessor", - "world.level.biome.MobSpawnSettingsAccessor", - "world.level.biome.BiomeAccessor", - "world.level.biome.Biome_ClimateSettingsAccessor", - "world.level.biome.OverworldBiomeBuilderAccessor", - "world.level.levelgen.NoiseSettingsAccessor", - "world.level.levelgen.structure.pools.StructureTemplatePoolAccessor", - "network.protocol.game.ClientboundPlayerInfoUpdatePacketAccessor", - "sounds.SoundEventAccessor", - "server.network.ServerCommonPacketListenerImplAccessor", - "server.network.ServerGamePacketListenerImplAccessor", - "world.entity.Display_TextDisplayAccessor", - "world.entity.Display_ItemDisplayAccessor", - "world.entity.DisplayAccessor", - "world.entity.Display_BlockDisplayAccessor" + "world.scores.ScoreboardAccessor" ], "server": [ "server.dedicated.DedicatedServerAccessor" diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java index af3f7bbf46f..6c044ec74e3 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java @@ -24,11 +24,22 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.advancements.critereon.BlockPredicate; +import net.minecraft.core.component.DataComponents; +import net.minecraft.util.Unit; +import net.minecraft.world.item.AdventureModePredicate; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemAttributeModifiers; +import net.minecraft.world.item.component.Unbreakable; +import net.minecraft.world.item.enchantment.ItemEnchantments; +import org.jetbrains.annotations.NotNull; import org.spongepowered.api.data.Keys; +import org.spongepowered.common.accessor.world.item.AdventureModePredicateAccessor; +import org.spongepowered.common.accessor.world.item.enchantment.ItemEnchantmentsAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; + +import java.util.Collections; +import java.util.List; public final class HideFlagsItemStackData { @@ -40,46 +51,43 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) .create(Keys.HIDE_ATTRIBUTES) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.MODIFIERS)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.MODIFIERS, v)) + .get(h -> h.getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY).showInTooltip()) + .set((h, v) -> h.update(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY, p -> new ItemAttributeModifiers(p.modifiers(), !v))) .create(Keys.HIDE_CAN_DESTROY) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.CAN_DESTROY)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.CAN_DESTROY, v)) + .get(h -> h.has(DataComponents.CAN_BREAK) && !h.get(DataComponents.CAN_BREAK).showInTooltip()) + .set((h, v) -> h.set(DataComponents.CAN_BREAK, HideFlagsItemStackData.newAdventureModePredicate(h, !v))) .create(Keys.HIDE_CAN_PLACE) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.CAN_PLACE)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.CAN_PLACE, v)) + .get(h -> h.has(DataComponents.CAN_PLACE_ON) && !h.get(DataComponents.CAN_BREAK).showInTooltip()) + .set((h, v) -> h.set(DataComponents.CAN_PLACE_ON, HideFlagsItemStackData.newAdventureModePredicate(h, !v))) .create(Keys.HIDE_ENCHANTMENTS) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.ENCHANTMENTS)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.ENCHANTMENTS, v)) + .get(h -> ((ItemEnchantmentsAccessor)h.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY)).accessor$showInTooltip()) + .set((h, v) -> h.set(DataComponents.ENCHANTMENTS, HideFlagsItemStackData.newItemEnchantments(h, v))) .create(Keys.HIDE_MISCELLANEOUS) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.ADDITIONAL)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.ADDITIONAL, v)) + .get(h -> h.get(DataComponents.HIDE_ADDITIONAL_TOOLTIP) != Unit.INSTANCE) + .set((h, v) -> h.set(DataComponents.HIDE_ADDITIONAL_TOOLTIP, v ? Unit.INSTANCE : null)) .create(Keys.HIDE_UNBREAKABLE) - .get(h -> HideFlagsItemStackData.get(h, ItemStack.TooltipPart.UNBREAKABLE)) - .set((h, v) -> HideFlagsItemStackData.set(h, ItemStack.TooltipPart.UNBREAKABLE, v)); + .get(h -> h.has(DataComponents.UNBREAKABLE) && !h.get(DataComponents.UNBREAKABLE).showInTooltip()) + .set((h, v) -> { + if (h.has(DataComponents.UNBREAKABLE)) { + h.set(DataComponents.UNBREAKABLE, new Unbreakable(v)); + } // else TODO not supported? + }); } // @formatter:on - private static boolean get(final ItemStack stack, final ItemStack.TooltipPart flag) { - final CompoundTag tag = stack.getTag(); - if (tag == null || !tag.contains(Constants.Item.ITEM_HIDE_FLAGS, Constants.NBT.TAG_ANY_NUMERIC)) { - return false; + @NotNull + private static AdventureModePredicate newAdventureModePredicate(final ItemStack h, final boolean showInTooltip) { + if (h.has(DataComponents.CAN_BREAK)) { + final List $$0 = ((AdventureModePredicateAccessor) h.get(DataComponents.CAN_BREAK)).accessor$predicates(); + return new AdventureModePredicate($$0, showInTooltip); } - return (tag.getInt(Constants.Item.ITEM_HIDE_FLAGS) & flag.getMask()) == 0; + return new AdventureModePredicate(Collections.emptyList(), showInTooltip); } - public static void set(final ItemStack stack, final ItemStack.TooltipPart flag, final boolean value) { - final CompoundTag tag = stack.getOrCreateTag(); - int flags = tag.getInt(Constants.Item.ITEM_HIDE_FLAGS); - if (value) { - tag.putInt(Constants.Item.ITEM_HIDE_FLAGS, flags | flag.getMask()); - } else { - flags = flags & ~flag.getMask(); - if (flags == 0) { - tag.remove(Constants.Item.ITEM_HIDE_FLAGS); - } else { - tag.putInt(Constants.Item.ITEM_HIDE_FLAGS, flags); - } - } + @NotNull + private static ItemEnchantments newItemEnchantments(final ItemStack h, final boolean showInTooltip) { + final ItemEnchantmentsAccessor enchantments = (ItemEnchantmentsAccessor) h.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);; + return ItemEnchantmentsAccessor.invoker$new(enchantments.accessor$enchantments(), showInTooltip); } + } From d6e214c5a6e22ee188b986f6ea28123a866bad24 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 19:42:01 +0100 Subject: [PATCH 003/230] fix data: potions --- .../data/provider/entity/PotionData.java | 15 +++--- .../item/stack/PotionItemStackData.java | 48 ++++++++----------- .../effect/potion/SpongePotionBuilder.java | 3 +- .../spongepowered/common/util/Constants.java | 1 - 4 files changed, 27 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java b/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java index 7cf9e989792..124becfdac8 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/PotionData.java @@ -24,15 +24,14 @@ */ package org.spongepowered.common.data.provider.entity; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.projectile.ThrownPotion; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionContents; +import org.apache.commons.lang3.stream.Streams; import org.spongepowered.api.data.Keys; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; - -import java.util.stream.Collectors; public final class PotionData { @@ -44,12 +43,10 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ThrownPotion.class) .create(Keys.POTION_EFFECTS) - .get(h -> PotionUtils.getMobEffects(h.getItem()).stream().map(PotionEffect.class::cast).collect(Collectors.toList())) + .get(h -> Streams.of(h.getItem().getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getAllEffects()).map(PotionEffect.class::cast).toList()) .set((h, v) -> { - h.getItem().removeTagKey(Constants.Item.CUSTOM_POTION_EFFECTS); - PotionUtils.setCustomEffects(h.getItem(), v.stream() - .map(MobEffectInstance.class::cast) - .collect(Collectors.toList())); + final var mcEffects = v.stream().map(MobEffectInstance.class::cast).toList(); + h.getItem().update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcEffects)); }); } // @formatter:on diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java index 7caa42e8257..98bc716e779 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/PotionItemStackData.java @@ -25,22 +25,22 @@ package org.spongepowered.common.data.provider.item.stack; import com.google.common.collect.ImmutableList; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.Potion; -import net.minecraft.world.item.alchemy.PotionUtils; -import net.minecraft.world.item.alchemy.Potions; +import net.minecraft.world.item.alchemy.PotionContents; import org.spongepowered.api.data.Keys; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.item.potion.PotionType; import org.spongepowered.api.util.Color; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; +import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; +import java.util.Optional; @SuppressWarnings("unchecked") public final class PotionItemStackData { @@ -49,43 +49,33 @@ private PotionItemStackData() { } // @formatter:off + // TODO check support public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) .create(Keys.COLOR) - .get(h -> Color.ofRgb(PotionUtils.getColor(h))) - .set((h, v) -> { - final CompoundTag tag = h.getOrCreateTag(); - tag.putInt(Constants.Item.CUSTOM_POTION_COLOR, v.rgb()); - }) - .delete(h -> h.removeTagKey(Constants.Item.CUSTOM_POTION_COLOR)) - .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION - || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) + .get(h -> Color.ofRgb(h.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getColor())) + .set((h, v) -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects()))) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), Optional.empty(), contents.customEffects()))) + .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) .create(Keys.POTION_EFFECTS) .get(h -> { - final List effects = PotionUtils.getMobEffects(h); + final List effects = h.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).customEffects(); return effects.isEmpty() ? null : ImmutableList.copyOf((List) (Object) effects); }) .set((h, v) -> { - h.removeTagKey(Constants.Item.CUSTOM_POTION_EFFECTS); - PotionUtils.setCustomEffects(h, v.stream() - .map(MobEffectInstance.class::cast) - .collect(Collectors.toList())); + final var mcList = v.stream().map(MobEffectInstance.class::cast).toList(); + h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), mcList)); }) - .delete(h -> h.removeTagKey(Constants.Item.CUSTOM_POTION_EFFECTS)) - .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || - h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(contents.potion(), contents.customColor(), Collections.emptyList()))) + .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW) .create(Keys.POTION_TYPE) - .get(h -> (PotionType) PotionUtils.getPotion(h)) + .get(h -> (PotionType) h.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion().map(Holder::value).orElse(null)) // TODO empty POTION gone? .set((h, v) -> { - h.getOrCreateTag(); - PotionUtils.setPotion(h, (Potion) v); - }) - .delete(h -> { - if (h.hasTag()) { - PotionUtils.setPotion(h, Potions.EMPTY); - } + final var potion = Optional.ofNullable(v).map(Potion.class::cast).map(Holder::direct); // TODO set empty POTION? same as delete? + h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(potion, contents.customColor(), contents.customEffects())); }) + .delete(h -> h.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, contents -> new PotionContents(Optional.empty(), contents.customColor(), contents.customEffects()))) .supports(h -> h.getItem() == Items.POTION || h.getItem() == Items.SPLASH_POTION || h.getItem() == Items.LINGERING_POTION || h.getItem() == Items.TIPPED_ARROW); } diff --git a/src/main/java/org/spongepowered/common/effect/potion/SpongePotionBuilder.java b/src/main/java/org/spongepowered/common/effect/potion/SpongePotionBuilder.java index e1dd7000fd0..773f8fb69a4 100644 --- a/src/main/java/org/spongepowered/common/effect/potion/SpongePotionBuilder.java +++ b/src/main/java/org/spongepowered/common/effect/potion/SpongePotionBuilder.java @@ -25,6 +25,7 @@ package org.spongepowered.common.effect.potion; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import org.checkerframework.checker.nullness.qual.NonNull; @@ -147,7 +148,7 @@ public PotionEffect build() throws IllegalStateException { if (!this.duration.isInfinite() && this.duration.ticks() <= 0) { throw new IllegalStateException("Duration has not been set"); } - return (PotionEffect) new MobEffectInstance((MobEffect) this.potionType, + return (PotionEffect) new MobEffectInstance(Holder.direct((MobEffect) this.potionType), SpongeTicks.toSaturatedIntOrInfinite(this.duration), this.amplifier, this.isAmbient, diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index bf90dd522e3..702e69211fe 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -535,7 +535,6 @@ public static final class Item { public static final String ITEM_HIDE_FLAGS = "HideFlags"; public static final String ITEM_UNBREAKABLE = "Unbreakable"; public static final String CUSTOM_MODEL_DATA = "CustomModelData"; - public static final String CUSTOM_POTION_COLOR = "CustomPotionColor"; public static final String CUSTOM_POTION_EFFECTS = "custom_potion_effects"; public static final String LOCK = "Lock"; From 9439513812a58dc0935ce3831c2e58906a19336d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 20:17:57 +0100 Subject: [PATCH 004/230] fix data: dyables --- ...ackData.java => DyeableItemStackData.java} | 26 +++++++------------ .../item/stack/HideFlagsItemStackData.java | 1 + .../item/stack/ItemStackDataProviders.java | 2 +- 3 files changed, 11 insertions(+), 18 deletions(-) rename src/main/java/org/spongepowered/common/data/provider/item/stack/{IDyeableArmorItemStackData.java => DyeableItemStackData.java} (64%) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/IDyeableArmorItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/DyeableItemStackData.java similarity index 64% rename from src/main/java/org/spongepowered/common/data/provider/item/stack/IDyeableArmorItemStackData.java rename to src/main/java/org/spongepowered/common/data/provider/item/stack/DyeableItemStackData.java index 4e0a6eb6e9a..0308c122358 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/IDyeableArmorItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/DyeableItemStackData.java @@ -24,15 +24,17 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.world.item.DyeableLeatherItem; +import net.minecraft.core.component.DataComponents; +import net.minecraft.tags.ItemTags; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.DyedItemColor; import org.spongepowered.api.data.Keys; import org.spongepowered.api.util.Color; import org.spongepowered.common.data.provider.DataProviderRegistrator; -public final class IDyeableArmorItemStackData { +public final class DyeableItemStackData { - private IDyeableArmorItemStackData() { + private DyeableItemStackData() { } // @formatter:off @@ -40,20 +42,10 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) .create(Keys.COLOR) - .get(h -> { - final int color = ((DyeableLeatherItem) h.getItem()).getColor(h); - return color == -1 ? null : Color.ofRgb(color); - }) - .set((h, v) -> { - final DyeableLeatherItem item = (DyeableLeatherItem) h.getItem(); - if (v == null) { - item.clearColor(h); - } else { - item.setColor(h, (((v.red() << 8) + v.green()) << 8) + v.blue()); - } - }) - .delete(h -> ((DyeableLeatherItem) h.getItem()).clearColor(h)) - .supports(h -> h.getItem() instanceof DyeableLeatherItem); + .get(h -> h.has(DataComponents.DYED_COLOR) ? Color.ofRgb(h.get(DataComponents.DYED_COLOR).rgb()) : null) + .set((h, v) -> h.update(DataComponents.DYED_COLOR, new DyedItemColor(0, true), prev -> new DyedItemColor(v.rgb(), prev.showInTooltip()))) + .delete(h -> h.set(DataComponents.DYED_COLOR, null)) + .supports(h -> h.is(ItemTags.DYEABLE)); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java index 6c044ec74e3..2cdaed6b614 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/HideFlagsItemStackData.java @@ -72,6 +72,7 @@ public static void register(final DataProviderRegistrator registrator) { h.set(DataComponents.UNBREAKABLE, new Unbreakable(v)); } // else TODO not supported? }); + // TODO missing show_in_tooltip (DYED_COLOR, more?) } // @formatter:on diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackDataProviders.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackDataProviders.java index 54942eaa35f..112d12bafbf 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackDataProviders.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackDataProviders.java @@ -39,7 +39,7 @@ public void registerProviders() { CompassItemData.register(this.registrator); FireworkItemStackData.register(this.registrator); HideFlagsItemStackData.register(this.registrator); - IDyeableArmorItemStackData.register(this.registrator); + DyeableItemStackData.register(this.registrator); InaccuracyItemStackData.register(this.registrator); ItemStackData.register(this.registrator); MusicDiscItemStackData.register(this.registrator); From 1331762e8567c6d65572fafc2a5425b46e7d5be8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 09:14:11 +0100 Subject: [PATCH 005/230] fix data: signs --- .../data/provider/item/stack/SignItemStackData.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/SignItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/SignItemStackData.java index ff829bcc32c..610c75fac81 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/SignItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/SignItemStackData.java @@ -27,8 +27,10 @@ import com.google.common.collect.Lists; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Keys; import org.spongepowered.common.data.provider.DataProviderRegistrator; @@ -47,8 +49,8 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.SIGN_LINES) .get(h -> { - final @Nullable CompoundTag tag = h.getTagElement(Constants.Item.BLOCK_ENTITY_TAG); - if (tag == null) { + final CompoundTag tag = h.getOrDefault(DataComponents.BLOCK_ENTITY_DATA, CustomData.EMPTY).copyTag(); + if (tag.isEmpty()) { return null; } final String id = tag.getString(Constants.Item.BLOCK_ENTITY_ID); @@ -64,7 +66,7 @@ public static void register(final DataProviderRegistrator registrator) { }) .set((h, v) -> { final GsonComponentSerializer gcs = GsonComponentSerializer.gson(); - final CompoundTag tag = h.getOrCreateTagElement(Constants.Item.BLOCK_ENTITY_TAG); + final CompoundTag tag = new CompoundTag(); tag.putString(Constants.Item.BLOCK_ENTITY_ID, Constants.TileEntity.SIGN); for (int i = 0; i < 4; i++) { final @Nullable Component line = v.size() > i ? v.get(i) : Component.empty(); @@ -73,8 +75,9 @@ public static void register(final DataProviderRegistrator registrator) { } tag.putString("Text" + (i + 1), gcs.serialize(line)); } + h.set(DataComponents.BLOCK_ENTITY_DATA, CustomData.of(tag)); }) - .delete(h -> h.removeTagKey(Constants.Item.BLOCK_ENTITY_TAG)); + .delete(h -> h.remove(DataComponents.BLOCK_ENTITY_DATA)); } // @formatter:on } From ff1948e32f865e7f8c591209aab627a3c8ddddc5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 09:35:57 +0100 Subject: [PATCH 006/230] fix data: book pages --- .../item/stack/BookPagesItemStackData.java | 83 +++++-------------- 1 file changed, 22 insertions(+), 61 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BookPagesItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BookPagesItemStackData.java index be795054d41..441af7e7f9e 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BookPagesItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BookPagesItemStackData.java @@ -24,37 +24,24 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.ItemEnchantments; import org.spongepowered.api.data.Keys; import org.spongepowered.api.item.enchantment.Enchantment; import org.spongepowered.api.item.enchantment.EnchantmentType; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.item.enchantment.SpongeEnchantment; -import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.NBTCollectors; -import org.spongepowered.common.util.NBTStreams; import org.spongepowered.common.util.Predicates; -import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Objects; import java.util.function.Function; -import java.util.stream.Collectors; import java.util.stream.Stream; public final class BookPagesItemStackData { - private static final String NBTKeyAppliedEnchantments = Constants.Item.ITEM_ENCHANTMENT_LIST; - private static final String NBTKeyStoredEnchantments = Constants.Item.ITEM_STORED_ENCHANTMENTS_LIST; - private BookPagesItemStackData() { } @@ -63,64 +50,38 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) .create(Keys.APPLIED_ENCHANTMENTS) - .get(h -> BookPagesItemStackData.get(h, BookPagesItemStackData.NBTKeyAppliedEnchantments)) - .set((h, v) -> BookPagesItemStackData.set(h, v, iv -> iv.stream().filter(Predicates.distinctBy(Enchantment::type)), BookPagesItemStackData.NBTKeyAppliedEnchantments)) - .delete(h -> BookPagesItemStackData.delete(h, BookPagesItemStackData.NBTKeyAppliedEnchantments)) + .get(h -> BookPagesItemStackData.get(h, DataComponents.ENCHANTMENTS)) + .set((h, v) -> BookPagesItemStackData.set(h, v, iv -> iv.stream().filter(Predicates.distinctBy(Enchantment::type)), DataComponents.ENCHANTMENTS)) + .delete(h -> BookPagesItemStackData.delete(h, DataComponents.ENCHANTMENTS)) .create(Keys.STORED_ENCHANTMENTS) - .get(h -> BookPagesItemStackData.get(h, BookPagesItemStackData.NBTKeyStoredEnchantments)) - .set((h, v) -> BookPagesItemStackData.set(h, v, Collection::stream, BookPagesItemStackData.NBTKeyStoredEnchantments)) - .delete(h -> BookPagesItemStackData.delete(h, BookPagesItemStackData.NBTKeyStoredEnchantments)) + .get(h -> BookPagesItemStackData.get(h, DataComponents.STORED_ENCHANTMENTS)) + .set((h, v) -> BookPagesItemStackData.set(h, v, Collection::stream, DataComponents.STORED_ENCHANTMENTS)) + .delete(h -> BookPagesItemStackData.delete(h, DataComponents.STORED_ENCHANTMENTS)) .supports(h -> h.getItem() == Items.ENCHANTED_BOOK); } // @formatter:on - private static List get(final ItemStack holder, final String nbtKey) { - final CompoundTag tag = holder.getTag(); - if (tag == null || !tag.contains(nbtKey, Constants.NBT.TAG_LIST)) { - return new ArrayList<>(); - } - final ListTag list = tag.getList(nbtKey, Constants.NBT.TAG_COMPOUND); - return NBTStreams.toCompounds(list) - .map(BookPagesItemStackData::enchantmentFromNbt) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + private static List get(final ItemStack holder, final DataComponentType component) { + return holder.getOrDefault(component, ItemEnchantments.EMPTY).entrySet().stream() + .map(e -> Enchantment.of((EnchantmentType) e.getKey().value(), e.getIntValue())).toList(); } private static boolean set(final ItemStack holder, final List value, final Function, Stream> filter, - final String nbtKey) { + final DataComponentType component) { if (value.isEmpty()) { - return BookPagesItemStackData.delete(holder, nbtKey); + return BookPagesItemStackData.delete(holder, component); } - final CompoundTag tag = holder.getOrCreateTag(); - final ListTag list = filter.apply(value) - .map(BookPagesItemStackData::enchantmentToNbt) - .collect(NBTCollectors.toTagList()); - tag.put(nbtKey, list); + holder.update(component, ItemEnchantments.EMPTY, ench -> { + final ItemEnchantments.Mutable mutable = new ItemEnchantments.Mutable(ench); + mutable.keySet().clear(); + value.forEach(e -> mutable.set((net.minecraft.world.item.enchantment.Enchantment) e.type(), e.level())); + return mutable.toImmutable(); + }); return true; } - private static boolean delete(final ItemStack holder, final String nbtKey) { - final CompoundTag tag = holder.getTag(); - if (tag != null) { - tag.remove(nbtKey); - } + private static boolean delete(final ItemStack holder, final DataComponentType component) { + holder.remove(component); return true; } - - private static Enchantment enchantmentFromNbt(final CompoundTag compound) { - final String enchantmentId = compound.getString(Constants.Item.ITEM_ENCHANTMENT_ID); - final int level = compound.getInt(Constants.Item.ITEM_ENCHANTMENT_LEVEL); - final Registry enchantmentRegistry = SpongeCommon.vanillaRegistry(Registries.ENCHANTMENT); - final EnchantmentType enchantment = (EnchantmentType) enchantmentRegistry.getOptional(ResourceLocation.tryParse(enchantmentId)).orElse(null); - return enchantment == null ? null : new SpongeEnchantment(enchantment, level); - } - - private static CompoundTag enchantmentToNbt(final Enchantment enchantment) { - final CompoundTag compound = new CompoundTag(); - final Registry enchantmentRegistry = SpongeCommon.vanillaRegistry(Registries.ENCHANTMENT); - final String enchantmentId = String.valueOf(enchantmentRegistry.getKey((net.minecraft.world.item.enchantment.Enchantment) enchantment.type())); - compound.putString(Constants.Item.ITEM_ENCHANTMENT_ID, enchantmentId); - compound.putShort(Constants.Item.ITEM_ENCHANTMENT_LEVEL, (short) ((byte) enchantment.level())); - return compound; - } } From 2ee2ad0efae330c318a8be19c35b5fb99909ff3f Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 09:40:04 +0100 Subject: [PATCH 007/230] fix data: armor --- .../provider/item/stack/ArmorItemStackData.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java index 5be976b8ea4..58f68dec195 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ArmorItemStackData.java @@ -25,7 +25,6 @@ package org.spongepowered.common.data.provider.item.stack; import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.ArmorMaterial; @@ -43,28 +42,24 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.ARMOR_MATERIAL) .get(h -> { - final Item item = h.getItem(); - if (item instanceof ArmorItem) { - final net.minecraft.world.item.ArmorMaterial armor = ((ArmorItem) item).getMaterial(); - if (armor instanceof org.spongepowered.api.data.type.ArmorMaterial) { - return (ArmorMaterial) armor; - } + if (h.getItem() instanceof ArmorItem armorItem) { + return (ArmorMaterial) (Object) armorItem.getMaterial().value(); } return null; }) .supports(h -> h.getItem() instanceof ArmorItem) .create(Keys.DAMAGE_ABSORPTION) .get(h -> { - if (h.getItem() instanceof ArmorItem) { - return (double) ((ArmorItem) h.getItem()).getDefense(); + if (h.getItem() instanceof ArmorItem armorItem) { + return (double) armorItem.getDefense(); } return null; }) .supports(h -> h.getItem() instanceof ArmorItem) .create(Keys.EQUIPMENT_TYPE) .get(h -> { - if (h.getItem() instanceof ArmorItem) { - switch (((ArmorItem) h.getItem()).getEquipmentSlot()) { + if (h.getItem() instanceof ArmorItem armorItem) { + switch (armorItem.getEquipmentSlot()) { case FEET: return EquipmentTypes.FEET.get(); case LEGS: From 278c72c06df54f3ac3ba70a47cf7049f625bf591 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 16:27:05 +0100 Subject: [PATCH 008/230] fix data: stacks --- .../provider/item/stack/ItemStackData.java | 80 +++++++------------ .../spongepowered/common/util/Constants.java | 1 - 2 files changed, 28 insertions(+), 53 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index e2758d00a86..3c4653e70f4 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -29,15 +29,22 @@ import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; +import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import net.minecraft.network.chat.Component; +import net.minecraft.util.StringUtil; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.PickaxeItem; +import net.minecraft.world.item.component.CustomModelData; +import net.minecraft.world.item.component.ItemLore; +import net.minecraft.world.item.component.Unbreakable; +import net.minecraft.world.item.component.WrittenBookContent; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; @@ -111,67 +118,49 @@ public static void register(final DataProviderRegistrator registrator) { .create(Keys.DISPLAY_NAME) .get(h -> SpongeAdventure.asAdventure(h.getDisplayName())) .create(Keys.CUSTOM_MODEL_DATA) - .get(h -> { - final CompoundTag tag = h.getTag(); - if (tag == null || !tag.contains(Constants.Item.CUSTOM_MODEL_DATA, Constants.NBT.TAG_INT)) { - return null; - } - return tag.getInt(Constants.Item.CUSTOM_MODEL_DATA); - }) - .set((h, v) -> { - final CompoundTag tag = h.getOrCreateTag(); - tag.putInt(Constants.Item.CUSTOM_MODEL_DATA, v); - }) - .delete(h -> { - h.removeTagKey(Constants.Item.CUSTOM_MODEL_DATA); - }) + .get(h -> h.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.DEFAULT).value()) + .set((h, v) -> h.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(v))) + .delete(h -> h.remove(DataComponents.CUSTOM_MODEL_DATA)) .create(Keys.CUSTOM_NAME) .get(h -> { - if (h.hasCustomHoverName()) { + if (h.has(DataComponents.CUSTOM_NAME)) { return SpongeAdventure.asAdventure(h.getHoverName()); } if (h.getItem() == Items.WRITTEN_BOOK) { // When no custom name is set on a written book fallback to its title // The custom name has a higher priority than the title so no setter is needed. - final CompoundTag tag = h.getTag(); - if (tag != null) { - final String title = tag.getString(Constants.Item.Book.ITEM_BOOK_TITLE); - return LegacyComponentSerializer.legacySection().deserialize(title); + var bookContent = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + if (bookContent != null) { + final String rawTitle = bookContent.title().raw(); + if (!StringUtil.isBlank(rawTitle)) { + return LegacyComponentSerializer.legacySection().deserialize(rawTitle); + } } } return null; }) - .set((h, v) -> h.setHoverName(SpongeAdventure.asVanilla(v))) - .delete(ItemStack::resetHoverName) + .set((h, v) -> h.set(DataComponents.CUSTOM_NAME, SpongeAdventure.asVanilla(v))) + .delete(h -> h.remove(DataComponents.CUSTOM_NAME)) .create(Keys.IS_UNBREAKABLE) - .get(h -> { - final CompoundTag tag = h.getTag(); - if (tag == null || !tag.contains(Constants.Item.ITEM_UNBREAKABLE, Constants.NBT.TAG_BYTE)) { - return false; - } - return tag.getBoolean(Constants.Item.ITEM_UNBREAKABLE); - }) + .get(h -> h.has(DataComponents.UNBREAKABLE)) .set(ItemStackData::setIsUnbrekable) .delete(h -> ItemStackData.setIsUnbrekable(h, false)) .create(Keys.LORE) .get(h -> { - final CompoundTag tag = h.getTag(); - if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY)) { + final List lines = h.getOrDefault(DataComponents.LORE, ItemLore.EMPTY).lines(); + if (lines.isEmpty()) { return null; } - final CompoundTag displayCompound = tag.getCompound(Constants.Item.ITEM_DISPLAY); - final ListTag list = displayCompound.getList(Constants.Item.ITEM_LORE, Constants.NBT.TAG_STRING); - return list.isEmpty() ? null : SpongeAdventure.json(list.stream().collect(NBTCollectors.toStringList())); + return lines.stream().map(SpongeAdventure::asAdventure).toList(); }) .set((h, v) -> { if (v.isEmpty()) { - ItemStackData.deleteLore(h); + h.remove(DataComponents.LORE); return; } - final ListTag list = SpongeAdventure.listTagJson(v); - h.getOrCreateTagElement(Constants.Item.ITEM_DISPLAY).put(Constants.Item.ITEM_LORE, list); + h.set(DataComponents.LORE, new ItemLore(v.stream().map(SpongeAdventure::asVanilla).toList())); }) - .delete(ItemStackData::deleteLore) + .delete(h -> h.remove(DataComponents.LORE)) .create(Keys.MAX_DURABILITY) .get(h -> h.getItem().canBeDepleted() ? h.getItem().getMaxDamage() : null) .supports(h -> h.getItem().canBeDepleted()) @@ -206,24 +195,11 @@ public static void register(final DataProviderRegistrator registrator) { // @formatter:on private static void setIsUnbrekable(final ItemStack stack, final Boolean value) { - if (value == null || (!value && !stack.hasTag())) { - return; - } if (value) { - final CompoundTag tag = stack.getOrCreateTag(); - tag.putBoolean(Constants.Item.ITEM_UNBREAKABLE, true); + stack.set(DataComponents.UNBREAKABLE, new Unbreakable(true)); } else { - stack.removeTagKey(Constants.Item.ITEM_UNBREAKABLE); + stack.remove(DataComponents.UNBREAKABLE); } } - private static void deleteLore(final ItemStack stack) { - final @Nullable CompoundTag tag = stack.getTagElement(Constants.Item.ITEM_DISPLAY); - if (tag != null) { - tag.remove(Constants.Item.ITEM_LORE); - if (tag.isEmpty()) { - stack.removeTagKey(Constants.Item.ITEM_DISPLAY); - } - } - } } diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index 702e69211fe..51290b1e12e 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -534,7 +534,6 @@ public static final class Item { public static final String ITEM_PLACEABLE_BLOCKS = "CanPlaceOn"; public static final String ITEM_HIDE_FLAGS = "HideFlags"; public static final String ITEM_UNBREAKABLE = "Unbreakable"; - public static final String CUSTOM_MODEL_DATA = "CustomModelData"; public static final String CUSTOM_POTION_EFFECTS = "custom_potion_effects"; public static final String LOCK = "Lock"; From 69c2cd915396403701a0293ad9160aae92e2ebf7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 16:55:13 +0100 Subject: [PATCH 009/230] fix data: compass --- .../provider/item/stack/CompassItemData.java | 40 ++++++------------- 1 file changed, 13 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java index a2a227009b2..8c96837c120 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java @@ -25,11 +25,11 @@ package org.spongepowered.common.data.provider.item.stack; import net.minecraft.core.GlobalPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.world.item.CompassItem; +import net.minecraft.core.component.DataComponents; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.LodestoneTarget; import net.minecraft.world.level.Level; import org.spongepowered.api.data.Keys; import org.spongepowered.api.world.server.ServerLocation; @@ -39,6 +39,7 @@ import org.spongepowered.common.util.VecHelper; final class CompassItemData { + private CompassItemData() { } @@ -47,32 +48,17 @@ static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.LODESTONE) .get(stack -> { - if (CompassItem.isLodestoneCompass(stack)) { - final CompoundTag tag = stack.getOrCreateTag(); - final GlobalPos pos = CompassItem.getLodestonePosition(tag); - if (pos != null) { - return ServerLocation.of( - (ServerWorld) SpongeCommon.server().getLevel(pos.dimension()), - VecHelper.toVector3d(pos.pos()) - ); - } + final LodestoneTarget component = stack.get(DataComponents.LODESTONE_TARGET); + if (component != null) { + return null; } - return null; + return ServerLocation.of((ServerWorld) SpongeCommon.server().getLevel(component.pos().dimension()), + VecHelper.toVector3d(component.pos().pos())); }) .set((stack, location) -> { - final CompoundTag tag = stack.getOrCreateTag(); - tag.put("LodestonePos", NbtUtils.writeBlockPos(VecHelper.toBlockPos(location))); - Level.RESOURCE_KEY_CODEC.encodeStart(NbtOps.INSTANCE, ((net.minecraft.server.level.ServerLevel) location.world()).dimension()) - .resultOrPartial(SpongeCommon.logger()::error).ifPresent(dimension -> tag.put("LodestoneDimension", dimension)); - tag.putBoolean("LodestoneTracked", true); + final ResourceKey dim = ((ServerLevel) location.world()).dimension(); + stack.set(DataComponents.LODESTONE_TARGET, new LodestoneTarget(new GlobalPos(dim, VecHelper.toBlockPos(location)), true)); }) - .delete(stack -> { - final CompoundTag tag = stack.getTag(); - if (tag != null) { - tag.remove("LodestoneDimension"); - tag.remove("LodestonePos"); - tag.remove("LodestoneTracked"); - } - }); + .delete(stack -> stack.remove(DataComponents.LODESTONE_TARGET)); } } From 904894604798c830dd93461fc2d3df1146f5be15 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 18:28:04 +0100 Subject: [PATCH 010/230] fix data: books --- .../item/stack/BookItemStackData.java | 114 ++++++++---------- 1 file changed, 52 insertions(+), 62 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BookItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BookItemStackData.java index 2734d5bef12..94794386740 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BookItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BookItemStackData.java @@ -24,23 +24,18 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.core.component.DataComponents; +import net.minecraft.server.network.Filterable; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.WritableBookContent; +import net.minecraft.world.item.component.WrittenBookContent; import org.spongepowered.api.data.Keys; +import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.NBTCollectors; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; +import java.util.Collections; public final class BookItemStackData { @@ -53,78 +48,73 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.AUTHOR) .get(h -> { - final CompoundTag tag = h.getTag(); - if (tag == null) { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + if (content == null) { return null; } - return LegacyComponentSerializer.legacySection().deserialize(tag.getString(Constants.Item.Book.ITEM_BOOK_AUTHOR)); + return LegacyComponentSerializer.legacySection().deserialize(content.author()); + }) + .set((h, v) -> { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + // TODO handle missing data? + final String author = LegacyComponentSerializer.legacySection().serialize(v); + h.set(DataComponents.WRITTEN_BOOK_CONTENT, + new WrittenBookContent(content.title(), author, content.generation(), content.pages(), content.resolved())); }) - .set((h, v) -> h.addTagElement(Constants.Item.Book.ITEM_BOOK_AUTHOR, StringTag.valueOf(LegacyComponentSerializer.legacySection().serialize(v)))) .supports(h -> h.getItem() == Items.WRITTEN_BOOK) .create(Keys.GENERATION) .get(h -> { - final CompoundTag tag = h.getTag(); - if (tag == null) { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + if (content == null) { return null; } - return tag.getInt(Constants.Item.Book.ITEM_BOOK_GENERATION); + return content.generation(); }) .setAnd((h, v) -> { if (v < 0) { return false; } - h.addTagElement(Constants.Item.Book.ITEM_BOOK_GENERATION, IntTag.valueOf(v)); + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + // TODO handle missing data? + h.set(DataComponents.WRITTEN_BOOK_CONTENT, + new WrittenBookContent(content.title(), content.author(), v, content.pages(), content.resolved())); return true; }) .supports(h -> h.getItem() == Items.WRITTEN_BOOK) .create(Keys.PAGES) - .get(h -> BookItemStackData.get(h, iv -> GsonComponentSerializer.gson().deserialize(iv))) - .setAnd((h, v) -> BookItemStackData.set(h, v, ih -> GsonComponentSerializer.gson().serialize(ih))) - .deleteAnd(BookItemStackData::delete) + .get(h -> { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + if (content == null) { + return null; + } + return content.pages().stream().map(Filterable::raw).map(SpongeAdventure::asAdventure).toList(); + }) + .set((h, v) -> { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + // TODO handle missing data? + var pages = v.stream().map(SpongeAdventure::asVanilla).map(Filterable::passThrough).toList(); + h.set(DataComponents.WRITTEN_BOOK_CONTENT, + new WrittenBookContent(content.title(), content.author(), content.generation(), pages, content.resolved())); + }) + .delete(h -> { + final WrittenBookContent content = h.get(DataComponents.WRITTEN_BOOK_CONTENT); + // TODO handle missing data? + h.set(DataComponents.WRITTEN_BOOK_CONTENT, + new WrittenBookContent(content.title(), content.author(), content.generation(), Collections.emptyList(), content.resolved())); + }) .supports(h -> h.getItem() == Items.WRITTEN_BOOK) .create(Keys.PLAIN_PAGES) - .get(h -> BookItemStackData.get(h, iv -> iv)) - .setAnd((h, v) -> BookItemStackData.set(h, v, iv -> iv)) - .deleteAnd(BookItemStackData::delete) + .get(h -> { + final WritableBookContent content = h.get(DataComponents.WRITABLE_BOOK_CONTENT); + if (content == null) { + return null; + } + return content.pages().stream().map(Filterable::raw).toList(); + }) + .set((h, v) -> h.set(DataComponents.WRITABLE_BOOK_CONTENT, new WritableBookContent(v.stream().map(Filterable::passThrough).toList()))) + .delete(h -> h.set(DataComponents.WRITABLE_BOOK_CONTENT, new WritableBookContent(Collections.emptyList()))) .supports(h -> h.getItem() == Items.WRITABLE_BOOK); } // @formatter:on - private static List get(final ItemStack holder, final Function predicate) { - final CompoundTag tag = holder.getTag(); - if (tag == null || !tag.contains(Constants.Item.Book.ITEM_BOOK_PAGES)) { - return null; - } - final ListTag list = tag.getList(Constants.Item.Book.ITEM_BOOK_PAGES, Constants.NBT.TAG_STRING); - return list.stream() - .map(Tag::getAsString) - .map(predicate) - .collect(Collectors.toList()); - } - - private static boolean set(final ItemStack holder, final List value, final Function predicate) { - final ListTag list = value.stream() - .map(predicate) - .collect(NBTCollectors.toStringTagList()); - - holder.addTagElement(Constants.Item.Book.ITEM_BOOK_PAGES, list); - final CompoundTag compound = holder.getOrCreateTag(); - if (!compound.contains(Constants.Item.Book.ITEM_BOOK_TITLE)) { - compound.putString(Constants.Item.Book.ITEM_BOOK_TITLE, Constants.Item.Book.INVALID_TITLE); - } - if (!compound.contains(Constants.Item.Book.ITEM_BOOK_AUTHOR)) { - compound.putString(Constants.Item.Book.ITEM_BOOK_AUTHOR, Constants.Item.Book.INVALID_TITLE); - } - compound.putBoolean(Constants.Item.Book.ITEM_BOOK_RESOLVED, true); - return false; - } - - private static boolean delete(final ItemStack holder) { - final CompoundTag tag = holder.getTag(); - if (tag != null && tag.contains(Constants.Item.Book.ITEM_BOOK_PAGES, Constants.NBT.TAG_LIST)) { - tag.remove(Constants.Item.Book.ITEM_BOOK_PAGES); - return true; - } - return false; - } } From 03753a57acb35f1e21f5749e3638fe0b6d2113d2 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 19:05:10 +0100 Subject: [PATCH 011/230] fix data: spawn eggs --- .../item/stack/SpawnEggItemStackData.java | 25 ++++++++----------- .../entity/SpongeEntityArchetypeBuilder.java | 11 ++++++-- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/SpawnEggItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/SpawnEggItemStackData.java index 4af2aacc613..622f02e98f2 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/SpawnEggItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/SpawnEggItemStackData.java @@ -24,17 +24,16 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.SpawnEggItem; -import org.checkerframework.checker.nullness.qual.Nullable; +import net.minecraft.world.item.component.CustomData; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.EntityArchetype; -import org.spongepowered.common.data.persistence.NBTTranslator; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; +import org.spongepowered.common.entity.SpongeEntityArchetypeBuilder; public final class SpawnEggItemStackData { @@ -47,14 +46,12 @@ public static void register(final DataProviderRegistrator registrator) { .get(stack -> { final Item item = stack.getItem(); final SpawnEggItem eggItem = (SpawnEggItem) item; - final @Nullable CompoundTag tag = stack.getTag(); - final EntityType type = eggItem.getType(tag); - final EntityArchetype.Builder builder = EntityArchetype.builder() - .type((org.spongepowered.api.entity.EntityType) type); - if (tag != null && tag.contains(Constants.Item.ENTITY_TAG, Constants.NBT.TAG_COMPOUND)) { - final CompoundTag entityData = tag.getCompound(Constants.Item.ENTITY_TAG); - builder.entityData(NBTTranslator.INSTANCE.translate(entityData)); - } + final EntityType type = eggItem.getType(stack); + final var tag = stack.getOrDefault(DataComponents.ENTITY_DATA, CustomData.EMPTY).getUnsafe(); + + final EntityArchetype.Builder builder = EntityArchetype.builder().type((org.spongepowered.api.entity.EntityType) type); + ((SpongeEntityArchetypeBuilder)builder).entityData(tag); + return builder.build(); }) .asImmutable(ItemStack.class) @@ -63,9 +60,7 @@ public static void register(final DataProviderRegistrator registrator) { .get(stack -> { final Item item = stack.getItem(); final SpawnEggItem eggItem = (SpawnEggItem) item; - final @Nullable CompoundTag tag = stack.getTag(); - final EntityType type = eggItem.getType(tag); - return (org.spongepowered.api.entity.EntityType) type; + return (org.spongepowered.api.entity.EntityType) eggItem.getType(stack); }) ; } diff --git a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java index 354fc982aa4..5296ec8977e 100644 --- a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java +++ b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java @@ -150,12 +150,17 @@ public EntityArchetype.Builder from(final Entity entity) { return this; } + public void entityData(final CompoundTag tag) { + Objects.requireNonNull(tag, "Provided CompoundTag cannot be null!"); + this.compound = tag.copy(); + SpongeEntityArchetypeBuilder.stripCompound(this.compound); + } + @Override public EntityArchetype.Builder entityData(final DataView view) { final DataContainer container = Objects.requireNonNull(view, "Provided DataView cannot be null!").copy(); new DelegateDataValidator(SpongeEntityArchetype.VALIDATORS, ValidationTypes.ENTITY.get()).validate(container); - this.compound = NBTTranslator.INSTANCE.translate(container); - SpongeEntityArchetypeBuilder.stripCompound(this.compound); + this.entityData(NBTTranslator.INSTANCE.translate(container)); return this; } @@ -188,4 +193,6 @@ protected static void stripCompound(final CompoundTag compound) { compound.remove(Constants.UUID_LEAST); compound.remove(Constants.Entity.ENTITY_POSITION); } + + } From 11504431fb5703bfdd29e50134b07928f1c27925 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 19:10:07 +0100 Subject: [PATCH 012/230] fix BlockItemStackData lock --- .../item/stack/BlockItemStackData.java | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java index c5d612b8af5..bf4a788432b 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockItemStackData.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.LockCode; import net.minecraft.world.item.BannerItem; import net.minecraft.world.item.BlockItem; @@ -36,7 +36,6 @@ import org.spongepowered.api.data.Keys; import org.spongepowered.common.bridge.block.DyeColorBlockBridge; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; public final class BlockItemStackData { @@ -55,23 +54,17 @@ public static void register(final DataProviderRegistrator registrator) { .supports(h -> h.getItem() instanceof BlockItem && !(h.getItem() instanceof BannerItem)) .create(Keys.LOCK_TOKEN) .get(h -> { - final CompoundTag tag = h.getTagElement(Constants.Item.BLOCK_ENTITY_TAG); - if (tag != null) { - final String lock = tag.getString(Constants.Item.LOCK); - if (!lock.isEmpty()) { - return lock; - } - } - return null; + var component = h.getOrDefault(DataComponents.LOCK, LockCode.NO_LOCK); + return component.key().isEmpty() ? null : component.key(); }) .set((h, v) -> { if (v.isEmpty()) { - BlockItemStackData.deleteLockToken(h); + h.remove(DataComponents.LOCK); return; } - new LockCode(v).addToTag(h.getOrCreateTagElement(Constants.Item.BLOCK_ENTITY_TAG)); + h.set(DataComponents.LOCK, new LockCode(v)); }) - .delete(BlockItemStackData::deleteLockToken) + .delete(h -> h.remove(DataComponents.LOCK)) .supports(h -> { if (!(h.getItem() instanceof BlockItem)) { return false; @@ -90,10 +83,4 @@ public static void register(final DataProviderRegistrator registrator) { } // @formatter:on - private static void deleteLockToken(final ItemStack stack) { - final CompoundTag tag = stack.getTagElement(Constants.Item.BLOCK_ENTITY_TAG); - if (tag != null) { - tag.remove(Constants.Item.LOCK); - } - } } From 3dbdc2c49004d83f4328c13ca641dde167787ab5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:37:13 +0100 Subject: [PATCH 013/230] fix lockcode --- .../level/block/entity/BaseContainerBlockEntityMixin_API.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java index 77b33cdf5db..8f72b5ac800 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java @@ -38,7 +38,6 @@ import org.spongepowered.api.data.value.Value; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.accessor.world.LockCodeAccessor; import org.spongepowered.common.util.Constants; import java.util.List; From 8558b68b7eb8c5334bbcc713f6befba7527871fa Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:11:53 +0100 Subject: [PATCH 014/230] fix LockableData --- .../accessor/world/LockCodeAccessor.java | 36 ------------------- .../resources/mixins.sponge.accessors.json | 1 - .../provider/block/entity/LockableData.java | 3 +- .../BaseContainerBlockEntityMixin_API.java | 2 +- 4 files changed, 2 insertions(+), 40 deletions(-) delete mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/LockCodeAccessor.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/LockCodeAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/LockCodeAccessor.java deleted file mode 100644 index d386c220c89..00000000000 --- a/src/accessors/java/org/spongepowered/common/accessor/world/LockCodeAccessor.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.accessor.world; - -import net.minecraft.world.LockCode; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(LockCode.class) -public interface LockCodeAccessor { - - @Accessor("key") String accessor$key(); - -} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 8fe6a647e5d..b00c599b9cc 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -54,7 +54,6 @@ "stats.StatsCounterAccessor", "util.datafix.schemas.V100Accessor", "world.CompoundContainerAccessor", - "world.LockCodeAccessor", "world.damagesource.CombatTrackerAccessor", "world.entity.AgableMobAccessor", "world.entity.AreaEffectCloudAccessor", diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java index 43a4a8ce6de..cbd0fae9ef6 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/LockableData.java @@ -26,7 +26,6 @@ import net.minecraft.world.LockCode; import org.spongepowered.api.data.Keys; -import org.spongepowered.common.accessor.world.LockCodeAccessor; import org.spongepowered.common.accessor.world.level.block.entity.BaseContainerBlockEntityAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; @@ -40,7 +39,7 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(BaseContainerBlockEntityAccessor.class) .create(Keys.LOCK_TOKEN) - .get(h -> ((LockCodeAccessor) h.accessor$lockKey()).accessor$key()) + .get(h -> h.accessor$lockKey().key()) .set((h, v) -> h.accessor$lockKey(v.isEmpty() ? LockCode.NO_LOCK : new LockCode(v))); } // @formatter:on diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java index 8f72b5ac800..02911fdedda 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BaseContainerBlockEntityMixin_API.java @@ -55,7 +55,7 @@ public abstract class BaseContainerBlockEntityMixin_API extends BlockEntityMixin public DataContainer toContainer() { final DataContainer container = super.toContainer(); if (this.lockKey != null) { - container.set(Constants.TileEntity.LOCK_CODE, ((LockCodeAccessor) this.lockKey).accessor$key()); + container.set(Constants.TileEntity.LOCK_CODE, this.lockKey.key()); } final List items = Lists.newArrayList(); for (int i = 0; i < ((Container) this).getContainerSize(); i++) { From 145e2f87c5f585d119fcd54478b02ee2c88184d9 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 19:14:14 +0100 Subject: [PATCH 015/230] fix data: skull --- .../provider/item/stack/SkullItemStackData.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/SkullItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/SkullItemStackData.java index 4d49c6527de..00ea8bbed3c 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/SkullItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/SkullItemStackData.java @@ -24,15 +24,13 @@ */ package org.spongepowered.common.data.provider.item.stack; -import com.mojang.authlib.GameProfile; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PlayerHeadItem; +import net.minecraft.world.item.component.ResolvableProfile; import org.spongepowered.api.data.Keys; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.profile.SpongeGameProfile; -import org.spongepowered.common.util.Constants; public final class SkullItemStackData { @@ -45,16 +43,14 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.GAME_PROFILE) .get(h -> { - final CompoundTag tag = h.getTagElement(Constants.Item.Skull.ITEM_SKULL_OWNER); - final GameProfile mcProfile = tag == null ? null : NbtUtils.readGameProfile(tag); - return mcProfile == null ? null : SpongeGameProfile.of(mcProfile); + final ResolvableProfile resolvableProfile = h.get(DataComponents.PROFILE); + return resolvableProfile == null ? null : SpongeGameProfile.of(resolvableProfile.gameProfile()); }) .set((h, v) -> { final com.mojang.authlib.GameProfile mcProfile = SpongeGameProfile.toMcProfile(v); - final CompoundTag tag = NbtUtils.writeGameProfile(new CompoundTag(), mcProfile); - h.addTagElement(Constants.Item.Skull.ITEM_SKULL_OWNER, tag); + h.set(DataComponents.PROFILE, new ResolvableProfile(mcProfile)); }) - .delete(h -> h.removeTagKey(Constants.Item.Skull.ITEM_SKULL_OWNER)) + .delete(h -> h.remove(DataComponents.PROFILE)) .supports(h -> h.getItem() instanceof PlayerHeadItem); } // @formatter:on From 4e7a1a4260df4af93b710b7d0beb8be7bf4ee599 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 19:21:12 +0100 Subject: [PATCH 016/230] fix data: world properties --- .../common/data/provider/world/WorldPropertiesData.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java b/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java index eaa40c73cf2..04d6f524f06 100644 --- a/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java +++ b/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java @@ -54,21 +54,21 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(LevelData.class) .create(Keys.SPAWN_POSITION) - .get(h -> new Vector3i(h.getXSpawn(), h.getYSpawn(), h.getZSpawn())) + .get(h -> VecHelper.toVector3i(h.getSpawnPos())) .create(Keys.HARDCORE) .get(LevelData::isHardcore) .create(Keys.WORLD_DIFFICULTY) .get(h -> (Difficulty) (Object) h.getDifficulty()) .asMutable(WritableLevelData.class) .create(Keys.SPAWN_POSITION) - .get(h -> new Vector3i(h.getXSpawn(), h.getYSpawn(), h.getZSpawn())) + .get(h -> VecHelper.toVector3i(h.getSpawnPos())) .set((h, v) -> h.setSpawn(VecHelper.toBlockPos(v), h.getSpawnAngle())) .asMutable(ServerLevelData.class) .create(Keys.GAME_MODE) .get(h -> (GameMode) (Object) h.getGameType()) .set((h, v) -> h.setGameType((GameType) (Object) v)) .create(Keys.COMMANDS) - .get(ServerLevelData::getAllowCommands) + .get(ServerLevelData::isAllowCommands) .create(Keys.INITIALIZED) .get(ServerLevelData::isInitialized) .create(Keys.WORLD_BORDER) From 82234dcc4f9a57ae33eae58f0ef96504ee411094 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:08:05 +0100 Subject: [PATCH 017/230] fix data: fluids --- .../data/provider/block/state/FlowingFluidData.java | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/block/state/FlowingFluidData.java b/src/main/java/org/spongepowered/common/data/provider/block/state/FlowingFluidData.java index 0ee7929abbb..774c369ace2 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/state/FlowingFluidData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/state/FlowingFluidData.java @@ -26,8 +26,6 @@ import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FlowingFluid; -import net.minecraft.world.level.material.FluidState; import org.spongepowered.api.data.Keys; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.BoundedUtil; @@ -42,14 +40,8 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asImmutable(BlockState.class) .create(Keys.FLUID_LEVEL) - .get(h -> ((LiquidBlock) h.getBlock()).getFluidState(h).getAmount()) - .set((h, v) -> { - final FluidState fluidState = ((LiquidBlock) h.getBlock()).getFluidState(h); - if (fluidState.hasProperty(FlowingFluid.LEVEL)) { - return BoundedUtil.setInteger(fluidState, v, FlowingFluid.LEVEL).createLegacyBlock(); - } - return null; - }) + .get(h -> h.getValue(LiquidBlock.LEVEL)) + .set((h, v) -> BoundedUtil.setInteger(h, v, LiquidBlock.LEVEL)) .supports(h -> h.getBlock() instanceof LiquidBlock); } // @formatter:on From 67b7701b6d7fca79622a11c031840126d1297927 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:17:41 +0100 Subject: [PATCH 018/230] fix data: tameable --- .../common/data/provider/entity/TameableData.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/TameableData.java b/src/main/java/org/spongepowered/common/data/provider/entity/TameableData.java index 0267464bbfa..fd3489e3e2f 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/TameableData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/TameableData.java @@ -42,12 +42,12 @@ public static void register(final DataProviderRegistrator registrator) { .set(TamableAnimal::setInSittingPose) .create(Keys.IS_TAMED) .get(TamableAnimal::isTame) - .set(TamableAnimal::setTame) + .set((h, v) -> h.setTame(v, true)) .create(Keys.TAMER) .get(TamableAnimal::getOwnerUUID) .set((h, v) -> { h.setOwnerUUID(v); - h.setTame(v != null); + h.setTame(v != null, true); }); } // @formatter:on From b05259cd09a99508a47b3dccde3a704a090df034 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:25:28 +0100 Subject: [PATCH 019/230] fix data: fireworks --- .../data/provider/entity/FireworkRocketData.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/FireworkRocketData.java b/src/main/java/org/spongepowered/common/data/provider/entity/FireworkRocketData.java index 0df3e6d75dc..840d8545845 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/FireworkRocketData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/FireworkRocketData.java @@ -25,14 +25,14 @@ package org.spongepowered.common.data.provider.entity; import com.google.common.collect.ImmutableList; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.projectile.FireworkRocketEntity; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.Fireworks; import org.spongepowered.api.data.Keys; import org.spongepowered.common.accessor.world.entity.EntityAccessor; import org.spongepowered.common.accessor.world.entity.projectile.FireworkRocketEntityAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.FireworkUtil; import org.spongepowered.common.util.SpongeTicks; @@ -52,11 +52,11 @@ public static void register(final DataProviderRegistrator registrator) { .create(Keys.FIREWORK_FLIGHT_MODIFIER) .get(h -> { final ItemStack item = FireworkUtil.getItem(h); - final CompoundTag fireworks = item.getOrCreateTagElement(Constants.Item.Fireworks.FIREWORKS); - if (fireworks.contains(Constants.Item.Fireworks.FLIGHT)) { - return new SpongeTicks(fireworks.getByte(Constants.Item.Fireworks.FLIGHT)); + final Fireworks fireworks = item.get(DataComponents.FIREWORKS); + if (fireworks == null) { + return null; } - return null; + return new SpongeTicks(fireworks.flightDuration()); }) .setAnd((h, v) -> { final int ticks = SpongeTicks.toSaturatedIntOrInfinite(v); @@ -64,8 +64,8 @@ public static void register(final DataProviderRegistrator registrator) { return false; } final ItemStack item = FireworkUtil.getItem(h); - final CompoundTag fireworks = item.getOrCreateTagElement(Constants.Item.Fireworks.FIREWORKS); - fireworks.putByte(Constants.Item.Fireworks.FLIGHT, (byte) ticks); + final Fireworks fireworks = item.get(DataComponents.FIREWORKS); + item.set(DataComponents.FIREWORKS, new Fireworks((int) v.ticks(), fireworks.explosions())); ((FireworkRocketEntityAccessor) h).accessor$lifetime(10 * ticks + ((EntityAccessor) h).accessor$random().nextInt(6) + ((EntityAccessor) h).accessor$random().nextInt(7)); return true; }); From 4e9089edcb06e19159cae8ef7ee1f6b528644812 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 23:05:47 +0100 Subject: [PATCH 020/230] fix fireworks --- .../org/spongepowered/common/item/SpongeFireworkEffect.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java b/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java index d9425a12557..75b2cd10031 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java +++ b/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java @@ -109,7 +109,7 @@ public int contentVersion() { @Override public DataContainer toContainer() { - final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.FIREWORK_SHAPE).valueKey(this.shape); + final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.FIREWORK_SHAPE).valueKey((FireworkShape) (Object) this.shape); return DataContainer.createNew() .set(Queries.CONTENT_VERSION, this.contentVersion()) From e8e86a4c63c97dc8a0345369d546d8b555765e56 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:16:08 +0100 Subject: [PATCH 021/230] fix registry FireworkExplosion Shape & API Mixin --- .../registry/loader/VanillaRegistryLoader.java | 13 ++++++------- ...I.java => FireworkExplosion_ShapeMixin_API.java} | 6 +++--- src/mixins/resources/mixins.sponge.api.json | 2 +- 3 files changed, 10 insertions(+), 11 deletions(-) rename src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/{FireworkRocketItem_ShapeMixin_API.java => FireworkExplosion_ShapeMixin_API.java} (88%) diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index bc6d465891d..0b37bc35f2c 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -55,12 +55,11 @@ import net.minecraft.world.entity.projectile.AbstractArrow; import net.minecraft.world.entity.raid.Raid; import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.DyeColor; -import net.minecraft.world.item.FireworkRocketItem; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.Rarity; import net.minecraft.world.item.Tiers; +import net.minecraft.world.item.component.FireworkExplosion; import net.minecraft.world.level.GameType; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.biome.Biome; @@ -258,11 +257,11 @@ private static RegistryLoader criterion() { private static RegistryLoader fireworkShape() { return RegistryLoader.of(l -> { - l.add(FireworkRocketItem.Shape.BURST.getId(), FireworkShapes.BURST, () -> (FireworkShape) (Object) FireworkRocketItem.Shape.BURST); - l.add(FireworkRocketItem.Shape.CREEPER.getId(), FireworkShapes.CREEPER, () -> (FireworkShape) (Object) FireworkRocketItem.Shape.CREEPER); - l.add(FireworkRocketItem.Shape.LARGE_BALL.getId(), FireworkShapes.LARGE_BALL, () -> (FireworkShape) (Object) FireworkRocketItem.Shape.LARGE_BALL); - l.add(FireworkRocketItem.Shape.SMALL_BALL.getId(), FireworkShapes.SMALL_BALL, () -> (FireworkShape) (Object) FireworkRocketItem.Shape.SMALL_BALL); - l.add(FireworkRocketItem.Shape.STAR.getId(), FireworkShapes.STAR, () -> (FireworkShape) (Object) FireworkRocketItem.Shape.STAR); + l.add(FireworkExplosion.Shape.BURST.getId(), FireworkShapes.BURST, () -> (FireworkShape) (Object) FireworkExplosion.Shape.BURST); + l.add(FireworkExplosion.Shape.CREEPER.getId(), FireworkShapes.CREEPER, () -> (FireworkShape) (Object) FireworkExplosion.Shape.CREEPER); + l.add(FireworkExplosion.Shape.LARGE_BALL.getId(), FireworkShapes.LARGE_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.LARGE_BALL); + l.add(FireworkExplosion.Shape.SMALL_BALL.getId(), FireworkShapes.SMALL_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.SMALL_BALL); + l.add(FireworkExplosion.Shape.STAR.getId(), FireworkShapes.STAR, () -> (FireworkShape) (Object) FireworkExplosion.Shape.STAR); }); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkRocketItem_ShapeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkExplosion_ShapeMixin_API.java similarity index 88% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkRocketItem_ShapeMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkExplosion_ShapeMixin_API.java index 7c2818266cf..6cc0e7d064c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkRocketItem_ShapeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/FireworkExplosion_ShapeMixin_API.java @@ -24,10 +24,10 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item; -import net.minecraft.world.item.FireworkRocketItem; +import net.minecraft.world.item.component.FireworkExplosion; import org.spongepowered.api.item.FireworkShape; import org.spongepowered.asm.mixin.Mixin; -@Mixin(FireworkRocketItem.Shape.class) -public abstract class FireworkRocketItem_ShapeMixin_API implements FireworkShape { +@Mixin(FireworkExplosion.Shape.class) +public abstract class FireworkExplosion_ShapeMixin_API implements FireworkShape { } diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 7833fcca3e9..92640908188 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -287,7 +287,7 @@ "minecraft.world.entity.vehicle.MinecartTNTMixin_API", "minecraft.world.item.ArmorMaterialsMixin_API", "minecraft.world.item.DyeColorMixin_API", - "minecraft.world.item.FireworkRocketItem_ShapeMixin_API", + "minecraft.world.item.FireworkExplosion_ShapeMixin_API", "minecraft.world.item.ItemCooldownsMixin_API", "minecraft.world.item.ItemDisplayContextMixin_API", "minecraft.world.item.ItemMixin_API", From 13d6cc63b410f0b1ef6de0657333cedbe32a7c91 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:42:53 +0100 Subject: [PATCH 022/230] fix data: effec clouds --- .../world/entity/AreaEffectCloudAccessor.java | 9 ++------- .../provider/entity/AreaEffectCloudData.java | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/AreaEffectCloudAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/AreaEffectCloudAccessor.java index c52ae28fbf5..a3e104dcae1 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/AreaEffectCloudAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/AreaEffectCloudAccessor.java @@ -24,20 +24,15 @@ */ package org.spongepowered.common.accessor.world.entity; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.item.alchemy.PotionContents; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.gen.Accessor; -import java.util.List; - @Mixin(AreaEffectCloud.class) public interface AreaEffectCloudAccessor { - @Accessor("effects") List accessor$effects(); - - @Accessor("effects") @Mutable void accessor$effects(final List effects); + @Accessor("potionContents") PotionContents accessor$potionContents(); @Accessor("waitTime") int accessor$waitTime(); diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java index 2544eabcb7e..ce95c05fdde 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java @@ -24,7 +24,9 @@ */ package org.spongepowered.common.data.provider.entity; +import com.google.common.collect.Streams; import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.item.alchemy.PotionContents; import org.spongepowered.api.data.Keys; import org.spongepowered.api.util.Color; import org.spongepowered.common.accessor.world.entity.AreaEffectCloudAccessor; @@ -33,6 +35,8 @@ import org.spongepowered.common.util.PotionEffectUtil; import org.spongepowered.common.util.SpongeTicks; +import java.util.Optional; + public final class AreaEffectCloudData { private AreaEffectCloudData() { @@ -44,7 +48,10 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(AreaEffectCloud.class) .create(Keys.COLOR) .get(h -> Color.ofRgb(h.getColor())) - .set((h, v) -> h.setFixedColor(v.rgb())) + .set((h, v) -> { + var contents = ((AreaEffectCloudAccessor)h).accessor$potionContents(); + h.setPotionContents(new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects())); + }) .create(Keys.DURATION) .get(x -> new SpongeTicks(x.getDuration())) .setAnd((h, v) -> { @@ -87,8 +94,11 @@ public static void register(final DataProviderRegistrator registrator) { return true; }) .create(Keys.POTION_EFFECTS) - .get(h -> PotionEffectUtil.copyAsPotionEffects(h.accessor$effects())) - .set((h, v) -> h.accessor$effects(PotionEffectUtil.copyAsEffectInstances(v))) + .get(h -> PotionEffectUtil.copyAsPotionEffects(Streams.stream(h.accessor$potionContents().getAllEffects()).toList())) + .set((h, v) -> { + final PotionContents contents = h.accessor$potionContents(); + ((AreaEffectCloud) h).setPotionContents(new PotionContents(contents.potion(), contents.customColor(), PotionEffectUtil.copyAsEffectInstances(v))); + }) .create(Keys.REAPPLICATION_DELAY) .get(h -> new SpongeTicks(h.accessor$reapplicationDelay())) .setAnd((h, v) -> { From da969a1a4a0274d8595dc2c1e11731f74de828d7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 18:27:34 +0100 Subject: [PATCH 023/230] fix BlockEntity nbt access --- .../common/world/volume/VolumeStreamUtils.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java index 1824446a47a..691418fb826 100644 --- a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java +++ b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java @@ -40,7 +40,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunkSection; @@ -255,14 +255,14 @@ public static BiConsumer { - final CompoundTag nbt = tile.saveWithFullMetadata(); + final CompoundTag nbt = tile.saveWithFullMetadata(tile.getLevel().registryAccess()); // TODO NPE possible? final BlockState state = tile.getBlockState(); final net.minecraft.world.level.block.entity.@Nullable BlockEntity cloned = tile.getType().create(pos, state); Objects.requireNonNull( cloned, () -> String.format( "TileEntityType[%s] creates a null TileEntity!", BlockEntityType.getKey(tile.getType())) - ).load(nbt); + ).load(nbt, tile.getLevel().registryAccess()); // TODO NPE possible? if (level != null) { ((BlockEntityAccessor) cloned).accessor$level(level); From b850675377da372e5ebfac375d5c3dc8f994f744 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 20:43:44 +0100 Subject: [PATCH 024/230] fix BlockEntity nbt --- .../org/spongepowered/common/block/SpongeBlockSnapshot.java | 6 +++--- .../spongepowered/common/event/tracking/TrackingUtil.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java index 00f16fc5998..e845b662df3 100644 --- a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java +++ b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java @@ -195,13 +195,13 @@ public boolean restore(final boolean force, final BlockChangeFlag flag) { @Nullable BlockEntity te = world.getBlockEntity(pos); if (te != null) { te.setBlockState((net.minecraft.world.level.block.state.BlockState) this.blockState); - te.load(this.compound); + te.load(this.compound, world.registryAccess()); } else { // Because, some mods will "unintentionally" only obey some of the rules but not all. // In cases like this, we need to directly just say "fuck it" and deserialize from the compound directly. try { - te = BlockEntity.loadStatic(pos, (net.minecraft.world.level.block.state.BlockState) this.blockState, this.compound); + te = BlockEntity.loadStatic(pos, (net.minecraft.world.level.block.state.BlockState) this.blockState, this.compound, world.registryAccess()); if (te != null) { world.getChunk(pos).setBlockEntity(te); } @@ -646,7 +646,7 @@ public BuilderImpl flag(final BlockChangeFlag flag) { } public BuilderImpl tileEntity(final BlockEntity added) { - this.compound = added.saveWithFullMetadata(); + this.compound = added.saveWithFullMetadata(added.getLevel().registryAccess()); return this; } } diff --git a/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java b/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java index 26376a27e9b..e4bebc95404 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java +++ b/src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java @@ -457,7 +457,7 @@ public static void addTileEntityToBuilder(final net.minecraft.world.level.block. final SpongeBlockSnapshot.BuilderImpl builder) { // TODO - gather custom data. try { - final CompoundTag compound = existing.saveWithFullMetadata(); + final CompoundTag compound = existing.saveWithFullMetadata(existing.getLevel().registryAccess()); builder.addUnsafeCompound(compound); } catch (final Throwable t) { From 790114e62274a40037b3652a7d93bdbcdd4904d8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 20:45:24 +0100 Subject: [PATCH 025/230] delete unused --- .../spongepowered/common/util/Constants.java | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index 51290b1e12e..18d8078cdea 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -1061,26 +1061,6 @@ private static void cleanseInnerCompound(final CompoundTag compound) { } } - public static List getItemEnchantments(final net.minecraft.world.item.ItemStack itemStack) { - if (!itemStack.isEnchanted()) { - return Collections.emptyList(); - } - final List enchantments = Lists.newArrayList(); - final ListTag list = itemStack.getEnchantmentTags(); - for (int i = 0; i < list.size(); i++) { - final CompoundTag compound = list.getCompound(i); - final short enchantmentId = compound.getShort(Item.ITEM_ENCHANTMENT_ID); - final short level = compound.getShort(Item.ITEM_ENCHANTMENT_LEVEL); - final Registry enchantmentRegistry = SpongeCommon.vanillaRegistry(Registries.ENCHANTMENT); - final EnchantmentType enchantmentType = (EnchantmentType) enchantmentRegistry.byId(enchantmentId); - if (enchantmentType == null) { - continue; - } - enchantments.add(new SpongeEnchantment(enchantmentType, level)); - } - return enchantments; - } - public static ListTag newDoubleNBTList(final double... numbers) { final ListTag nbttaglist = new ListTag(); From d73f17de9e7f570691f0a9d3797bf19d6c1343b5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 21:51:31 +0100 Subject: [PATCH 026/230] fix mapid --- .../common/event/SpongeCommonEventFactory.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java index 160cebef84b..d101974221a 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java +++ b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java @@ -43,6 +43,7 @@ import net.minecraft.world.level.block.DirectionalBlock; import net.minecraft.world.level.block.entity.JukeboxBlockEntity; import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.saveddata.maps.MapId; import net.minecraft.world.level.saveddata.maps.MapIndex; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import net.minecraft.world.phys.BlockHitResult; @@ -783,8 +784,8 @@ public static Optional fireCreateMapEvent(final Cause cause, final Set< final int id = mapIdTrackerBridge.bridge$getHighestMapId().orElse(-1) + 1; // Advance map id. - final int mcId = defaultWorld.getFreeMapId(); - if (id != mcId) { + final MapId mcId = defaultWorld.getFreeMapId(); + if (id != mcId.id()) { // TODO: REMOVE OR replace for Integer.MAX_VALUE SpongeCommon.logger().warn("Map size corruption, vanilla only allows " + Integer.MAX_VALUE + "! " + "Expected next number was not equal to the true next number."); @@ -794,8 +795,7 @@ public static Optional fireCreateMapEvent(final Cause cause, final Set< return Optional.empty(); } - final String mapId = MapItem.makeKey(id); - defaultWorld.setMapData(mapId, mapData); + defaultWorld.setMapData(new MapId(id), mapData); ((MapItemSavedDataBridge) mapData).bridge$initMapId(id); ((SpongeMapStorage) Sponge.server().mapStorage()).addMapInfo(mapInfo); From dd8696226a41523e312c200cee865a79af11cd39 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:19:25 +0100 Subject: [PATCH 027/230] fix map items --- .../item/stack/MapInfoItemStackData.java | 23 +++++++------------ .../common/map/SpongeMapStorage.java | 5 ++-- .../spongepowered/common/util/Constants.java | 1 - 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/MapInfoItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/MapInfoItemStackData.java index 0703aa57d52..e31b03eb5c1 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/MapInfoItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/MapInfoItemStackData.java @@ -24,18 +24,17 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.MapItem; import net.minecraft.world.level.Level; -import org.checkerframework.checker.nullness.qual.Nullable; +import net.minecraft.world.level.saveddata.maps.MapId; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.Keys; import org.spongepowered.api.map.MapInfo; import org.spongepowered.api.world.DefaultWorldKeys; import org.spongepowered.common.bridge.world.storage.MapItemSavedDataBridge; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; public final class MapInfoItemStackData { @@ -50,21 +49,15 @@ public static void register(final DataProviderRegistrator registrator) { .create(Keys.MAP_INFO) .supports(item -> item.getItem() instanceof MapItem) .get(itemStack -> { - if (itemStack.getTag() == null) { + final MapId mapId = itemStack.get(DataComponents.MAP_ID); + if (mapId == null) { return null; } - - return (MapInfo) ((Level)Sponge.server().worldManager().world(DefaultWorldKeys.DEFAULT).get()) - .getMapData(Constants.Map.MAP_PREFIX + itemStack.getTag().getInt(Constants.Map.MAP_ID)); + final Level level = (Level)Sponge.server().worldManager().world(DefaultWorldKeys.DEFAULT).get(); + return (MapInfo) level.getMapData(mapId); }) // Nullable - .set((itemStack, mapInfo) -> { - @Nullable CompoundTag nbt = itemStack.getTag(); - if (nbt == null) { - nbt = new CompoundTag(); - } - nbt.putInt(Constants.Map.MAP_ID, ((MapItemSavedDataBridge)mapInfo).bridge$getMapId()); - itemStack.setTag(nbt); - }); + .set((itemStack, mapInfo) -> itemStack.set(DataComponents.MAP_ID, + new MapId(((MapItemSavedDataBridge)mapInfo).bridge$getMapId()))); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/map/SpongeMapStorage.java b/src/main/java/org/spongepowered/common/map/SpongeMapStorage.java index dc49e2e474c..1c5e2cf1106 100644 --- a/src/main/java/org/spongepowered/common/map/SpongeMapStorage.java +++ b/src/main/java/org/spongepowered/common/map/SpongeMapStorage.java @@ -26,6 +26,7 @@ import com.google.common.collect.BiMap; import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.saveddata.maps.MapId; import net.minecraft.world.level.saveddata.maps.MapIndex; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; @@ -66,7 +67,7 @@ public Collection allMapInfos() { final int highestId = ((MapIdTrackerBridge) defaultWorld.getDataStorage() .computeIfAbsent(MapIndex.factory(), Constants.Map.MAP_INDEX_DATA_NAME)).bridge$getHighestMapId().orElse(-1); for (int i = 0; i <= highestId; i++) { - final @Nullable MapInfo mapInfo = (MapInfo) defaultWorld.getMapData(Constants.Map.MAP_PREFIX + i); + final @Nullable MapInfo mapInfo = (MapInfo) defaultWorld.getMapData(new MapId(i)); if (mapInfo == null) { SpongeCommon.logger().warn("Missing map with id: " + i); continue; @@ -89,7 +90,7 @@ public Optional mapInfo(final UUID uuid) { return Optional.empty(); } final ServerLevel defaultWorld = (ServerLevel) Sponge.server().worldManager().world(DefaultWorldKeys.DEFAULT).get(); - final MapInfo loadedMapInfo = (MapInfo) defaultWorld.getMapData(Constants.Map.MAP_PREFIX + mapId); + final MapInfo loadedMapInfo = (MapInfo) defaultWorld.getMapData(new MapId(mapId)); return Optional.ofNullable(loadedMapInfo); } diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index 18d8078cdea..8891ad9ca02 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -1251,7 +1251,6 @@ public static final class Map { public static final boolean DEFAULT_TRACKS_PLAYERS = true; public static final boolean DEFAULT_UNLIMITED_TRACKING = false; public static final boolean DEFAULT_MAP_LOCKED = false; - public static final String MAP_PREFIX = "map_"; public static final int MAP_SIZE = 16384; public static final int MAP_MAX_INDEX = 127; public static final int MAP_PIXELS = 128; From d699821477e0f930824d66eb109d4f14f531e387 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 23:00:31 +0100 Subject: [PATCH 028/230] fix map itemstack data --- .../common/mixin/core/item/EmptyMapItemMixin.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java index 10bab34869d..6bb0aeb5a62 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/item/EmptyMapItemMixin.java @@ -25,7 +25,7 @@ package org.spongepowered.common.mixin.core.item; import com.google.common.collect.Sets; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.item.EmptyMapItem; @@ -33,6 +33,7 @@ import net.minecraft.world.item.Items; import net.minecraft.world.item.MapItem; import net.minecraft.world.level.Level; +import net.minecraft.world.level.saveddata.maps.MapId; import org.objectweb.asm.Opcodes; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.HandType; @@ -51,7 +52,6 @@ import org.spongepowered.common.bridge.world.storage.MapItemSavedDataBridge; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; -import org.spongepowered.common.util.Constants; import org.spongepowered.math.vector.Vector2i; import java.util.Optional; @@ -99,9 +99,7 @@ public abstract class EmptyMapItemMixin { final int id = ((MapItemSavedDataBridge) optMapInfo.get()).bridge$getMapId(); final ItemStack newMap = new ItemStack(Items.FILLED_MAP, 1); - final CompoundTag nbt = newMap.getOrCreateTag(); - nbt.putInt(Constants.Map.MAP_ID, id); - + newMap.set(DataComponents.MAP_ID, new MapId(id)); return newMap; } } From c3b836df3dcff127ee5beeafaa37beec6f7a04cd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:20:57 +0100 Subject: [PATCH 029/230] fix map decoration name --- .../common/map/decoration/SpongeMapDecorationBuilder.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index f4d5912136c..844c2c6b9c0 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -42,6 +42,7 @@ import org.spongepowered.math.vector.Vector2i; import java.util.Objects; +import java.util.Optional; public final class SpongeMapDecorationBuilder implements MapDecoration.Builder { private @Nullable MapDecorationType type = null; @@ -161,7 +162,7 @@ public MapDecoration build() throws IllegalStateException { final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( ((SpongeMapDecorationType) this.type).getType(), (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), - this.customName == null ? null : SpongeAdventure.asVanilla(this.customName)); + Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent return decoration; } From 3eb257f98001da418aad96a0b2548040b31d5527 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 21:54:33 +0100 Subject: [PATCH 030/230] fix ItemStack custom name component --- .../common/event/tracking/phase/packet/PacketPhaseUtil.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/PacketPhaseUtil.java b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/PacketPhaseUtil.java index da3aa2080b8..1e351b0f957 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/phase/packet/PacketPhaseUtil.java +++ b/src/main/java/org/spongepowered/common/event/tracking/phase/packet/PacketPhaseUtil.java @@ -25,6 +25,7 @@ package org.spongepowered.common.event.tracking.phase.packet; import net.minecraft.core.BlockPos; +import net.minecraft.core.component.DataComponents; import net.minecraft.network.PacketListener; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ServerboundClientInformationPacket; @@ -302,7 +303,7 @@ public static void onProcessPacket(final Packet packetIn, final PacketListener n if (item == Items.NAME_TAG) { // ItemNameTag.itemInteractionForEntity - return entity instanceof LivingEntity && !(entity instanceof Player) && stack.hasCustomHoverName() ? EntityAccessor.accessor$DATA_CUSTOM_NAME() : null; + return entity instanceof LivingEntity && !(entity instanceof Player) && stack.has(DataComponents.CUSTOM_NAME) ? EntityAccessor.accessor$DATA_CUSTOM_NAME() : null; } if (item == Items.SADDLE) { From 756ec78b7d0a9bb452ada628086f2c4af80335a7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:40:39 +0100 Subject: [PATCH 031/230] fix easy mixin: ExplosionMixin_Tracker --- .../mixin/tracker/world/level/ExplosionMixin_Tracker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java index 71c57a15516..747a96b39a1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/world/level/ExplosionMixin_Tracker.java @@ -82,7 +82,7 @@ public void finalizeExplosion(final boolean spawnParticles) { // Sponge End // Sponge Start - Send the sound packet down. We must do this as we do not call doExplosionB client-side - this.level.playSound(null, this.x, this.y, this.z, SoundEvents.GENERIC_EXPLODE, SoundSource.BLOCKS, 4.0F, + this.level.playSound(null, this.x, this.y, this.z, SoundEvents.GENERIC_EXPLODE.value(), SoundSource.BLOCKS, 4.0F, (1.0F + (this.level.random.nextFloat() - this.level.random.nextFloat()) * 0.2F) * 0.7F); // Sponge End From ce6e4c5cdcf26cd9b951c1a23119f89af6c15895 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:50:21 +0100 Subject: [PATCH 032/230] fix easy mixin: ServerPlayerGameModeMixin_Tracker --- .../server/level/ServerPlayerGameModeMixin_Tracker.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java index 1a4121bf4a0..5cd18f5aafc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java @@ -30,6 +30,7 @@ import net.minecraft.server.level.ServerPlayerGameMode; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.MenuProvider; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; @@ -137,7 +138,7 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl final ItemStack copiedStack = stackIn.copy(); if (useBlock != Tristate.FALSE && !flag1) { // Sponge check useBlock final AbstractContainerMenu lastOpenContainer = playerIn.containerMenu; - final InteractionResult result = blockstate.use(worldIn, playerIn, handIn, blockRaytraceResultIn); + final ItemInteractionResult result = blockstate.useItemOn(playerIn.getItemInHand(handIn), worldIn, playerIn, handIn, blockRaytraceResultIn); if (result.consumesAction() && lastOpenContainer != playerIn.containerMenu) { final Vector3i pos = VecHelper.toVector3i(blockRaytraceResultIn.getBlockPos()); final ServerLocation location = ServerLocation.of((ServerWorld) worldIn, pos); @@ -152,7 +153,7 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl } if (result.consumesAction()) { CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(playerIn, blockpos, copiedStack); - return result; + return result.result(); } } From 375475985cebfdc7e7efce64103bd166e2596dd5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:03:31 +0100 Subject: [PATCH 033/230] fix easy mixin SynchedEntityDataMixin --- .../mixin/core/network/syncher/SynchedEntityDataMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java index bb6aca6c5ac..e3c026624a4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java @@ -75,7 +75,7 @@ public void set(final EntityDataAccessor key, T value) { // Really silly reasons...... // I don't know, ask Grum.... if (this.entity != null && this.entity.level() != null && !this.entity.level().isClientSide && !((EntityBridge) this.entity).bridge$isConstructing()) { // We only want to spam the server world ;) - final Optional> converter = ((EntityDataAccessorBridge) key).bridge$getDataConverter(); + final Optional> converter = ((EntityDataAccessorBridge) (Object) key).bridge$getDataConverter(); // At this point it is changing if (converter.isPresent()) { // Ok, we have a key ready to use the converter From 2e2d3afc721856d5741df56e7faed3c2a0563adf Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:32:21 +0100 Subject: [PATCH 034/230] fix easy mixin: EntityMixin --- .../common/mixin/core/world/entity/EntityMixin.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java index de09ff02afb..278d11469d6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/EntityMixin.java @@ -29,6 +29,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Holder; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; @@ -1205,13 +1206,13 @@ public void stopRiding() { } @Redirect( - method = "gameEvent(Lnet/minecraft/world/level/gameevent/GameEvent;Lnet/minecraft/world/entity/Entity;)V", + method = "gameEvent(Lnet/minecraft/core/Holder;Lnet/minecraft/world/entity/Entity;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;gameEvent(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/level/gameevent/GameEvent;Lnet/minecraft/world/phys/Vec3;)V" + target = "Lnet/minecraft/world/level/Level;gameEvent(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/Holder;Lnet/minecraft/world/phys/Vec3;)V" ) ) - private void impl$ignoreGameEventIfVanished(final Level instance, final Entity entity, final GameEvent gameEvent, final Vec3 vec) { + private void impl$ignoreGameEventIfVanished(final Level instance, final Entity entity, final Holder gameEvent, final Vec3 vec) { if (entity instanceof VanishableBridge && ((VanishableBridge) entity).bridge$vanishState().triggerVibrations()) { instance.gameEvent(entity, gameEvent, vec); } From cec7c0e0ae304e51eab8f28f2e062e6bd9c521f9 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 23:04:06 +0100 Subject: [PATCH 035/230] fix easy mixin EnderEyeItemMixin --- .../common/mixin/core/world/item/EnderEyeItemMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java index a5e13d456cc..572050becb8 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/EnderEyeItemMixin.java @@ -95,7 +95,7 @@ public abstract class EnderEyeItemMixin extends ItemMixin { final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(PhaseTracker.getCauseStackManager().currentCause(), ServerLocation.of((ServerWorld) worldIn, playerIn.getX(), playerIn.getY() + (double) (playerIn.getDimensions(playerIn - .getPose()).height / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); + .getPose()).height() / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); if (SpongeCommon.post(event)) { cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, used)); } @@ -113,7 +113,7 @@ public abstract class EnderEyeItemMixin extends ItemMixin { final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(PhaseTracker.getCauseStackManager().currentCause(), ServerLocation.of((ServerWorld) worldIn, playerIn.getX(), playerIn.getY() + (double) (playerIn.getDimensions(playerIn - .getPose()).height / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); + .getPose()).height() / 2.0F), playerIn.getZ()), new Vector3d(0, 0, 0), EntityTypes.EYE_OF_ENDER.get()); if (SpongeCommon.post(event)) { cir.setReturnValue(new InteractionResultHolder<>(InteractionResult.SUCCESS, used)); } From 0e68852f0f5c1795d97a8adfac80ebe4cbbc097c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 14:20:09 +0100 Subject: [PATCH 036/230] fix easy mixin CreeperMixin --- .../mixin/core/world/entity/monster/CreeperMixin.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java index 23f4b870988..76bdff39e87 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/monster/CreeperMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.entity.monster; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -46,7 +47,6 @@ import org.spongepowered.common.util.Constants; import java.util.Optional; -import java.util.function.Consumer; @Mixin(net.minecraft.world.entity.monster.Creeper.class) public abstract class CreeperMixin extends MonsterMixin implements FusedExplosiveBridge, ExplosiveBridge { @@ -168,12 +168,12 @@ public abstract class CreeperMixin extends MonsterMixin implements FusedExplosiv @Redirect(method = "mobInteract", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/item/ItemStack;hurtAndBreak(ILnet/minecraft/world/entity/LivingEntity;Ljava/util/function/Consumer;)V" + target = "Lnet/minecraft/world/item/ItemStack;hurtAndBreak(ILnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/entity/EquipmentSlot;)V" ) ) - private void impl$onDamageFlintAndSteel(ItemStack fas, int amount, LivingEntity player, Consumer onBroken) { + private void impl$onDamageFlintAndSteel(final ItemStack fas, final int amount, final LivingEntity player, final EquipmentSlot slot) { if (!this.impl$interactPrimeCancelled) { - fas.hurtAndBreak(amount, player, onBroken); + fas.hurtAndBreak(amount, player, slot); } this.impl$interactPrimeCancelled = false; } From d1ac5867f46b6dc59b526107fa2c8b927fecf682 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 14:22:29 +0100 Subject: [PATCH 037/230] fix easy mixin BlockStateMixin --- .../core/world/level/block/state/BlockStateMixin.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/state/BlockStateMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/state/BlockStateMixin.java index e5ba8e1075a..bf80871b97d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/state/BlockStateMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/state/BlockStateMixin.java @@ -24,8 +24,8 @@ */ package org.spongepowered.common.mixin.core.world.level.block.state; -import com.google.common.collect.ImmutableMap; import com.mojang.serialization.MapCodec; +import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; @@ -42,14 +42,10 @@ @Mixin(BlockState.class) public abstract class BlockStateMixin extends BlockBehaviour.BlockStateBase implements BlockStateBridge { - protected BlockStateMixin(Block p_i231870_1_, - ImmutableMap, Comparable> p_i231870_2_, - MapCodec p_i231870_3_ - ) { - super(p_i231870_1_, p_i231870_2_, p_i231870_3_); + protected BlockStateMixin(Block $$0, Reference2ObjectArrayMap, Comparable> $$1, MapCodec $$2) { + super($$0, $$1, $$2); } - @Override public boolean bridge$hasTileEntity() { return this.getBlock() instanceof EntityBlock; From fdcec1fac3b9187e6454f14d2190357a0f0fb1b8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 18:07:55 +0100 Subject: [PATCH 038/230] fix easy mixin: BlocksMixin_Tracker --- .../world/level/block/state/BlockBehaviourAccessor.java | 4 ++++ .../mixin/tracker/world/level/block/BlocksMixin_Tracker.java | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/BlockBehaviourAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/BlockBehaviourAccessor.java index b7a3faf154e..7cd6a28571c 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/BlockBehaviourAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/state/BlockBehaviourAccessor.java @@ -25,8 +25,10 @@ package org.spongepowered.common.accessor.world.level.block.state; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(BlockBehaviour.class) public interface BlockBehaviourAccessor { @@ -34,4 +36,6 @@ public interface BlockBehaviourAccessor { @Accessor("properties") BlockBehaviour.Properties accessor$properties(); @Accessor("hasCollision") boolean accessor$hasCollision(); + + @Invoker("isRandomlyTicking") boolean invoker$isRandomlyTicking(BlockState $$0); } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java index 95f8729bb5d..f6a2a37ed1a 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java @@ -30,6 +30,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.accessor.world.level.block.state.BlockBehaviourAccessor; import org.spongepowered.common.bridge.RegistryBackedTrackableBridge; @Mixin(Blocks.class) @@ -42,7 +43,7 @@ public abstract class BlocksMixin_Tracker { ) ) private static ResourceLocation impl$initializeTrackerState(final Block block) { - final boolean randomlyTicking = block.isRandomlyTicking(block.defaultBlockState()); + final boolean randomlyTicking = ((BlockBehaviourAccessor) block).invoker$isRandomlyTicking(block.defaultBlockState()); // TODO Not the best check but the tracker options only matter during block ticks... if (randomlyTicking) { From 540cdde38ca07f66638ad8ae554185b14aae745f Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 14:35:43 +0100 Subject: [PATCH 039/230] fix easy mixin: ServerGamePacketListenerImplMixin --- .../core/server/network/ServerGamePacketListenerImplMixin.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java index ea609e17d15..cba6e09a9ea 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java @@ -50,6 +50,7 @@ import net.minecraft.server.network.FilteredText; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.players.PlayerList; +import net.minecraft.util.StringUtil; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.RelativeMovement; @@ -458,7 +459,7 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack // TODO is this still needed? // Sponge Start - While Vanilla does some strip formatting, it doesn't catch everything. This patches an exploit that allows color // signs to be created. - newLines.add(Component.text(SharedConstants.filterText(line.filtered()))); + newLines.add(Component.text(StringUtil.filterText(line.filtered()))); } try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { From 6a5a8ea30c957aabb39645e90591ade58b8633cf Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:46:50 +0100 Subject: [PATCH 040/230] fix easy mixin: PlayerMixin canPlaceOnBlockInAdventureMode --- .../common/mixin/core/world/entity/player/PlayerMixin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java index 03628bf8854..d80b21e7186 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java @@ -259,11 +259,11 @@ public abstract class PlayerMixin extends LivingEntityMixin implements PlayerBri */ @Redirect(method = "mayUseItemAt", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/item/ItemStack;hasAdventureModePlaceTagForBlock(Lnet/minecraft/core/Registry;Lnet/minecraft/world/level/block/state/pattern/BlockInWorld;)Z")) - private boolean impl$callChangeBlockPre(final ItemStack stack, final Registry registry, final BlockInWorld cachedBlockInfo) { + target = "Lnet/minecraft/world/item/ItemStack;canPlaceOnBlockInAdventureMode(Lnet/minecraft/world/level/block/state/pattern/BlockInWorld;)Z")) + private boolean impl$callChangeBlockPre(final ItemStack stack, final BlockInWorld cachedBlockInfo) { // Lazy evaluation, if the stack isn't placeable anyways, might as well not // call the logic. - if (!stack.hasAdventureModePlaceTagForBlock(registry, cachedBlockInfo)) { + if (!stack.canPlaceOnBlockInAdventureMode(cachedBlockInfo)) { return false; } // If we're going to throw an event, then do it. From 3466628d03c4d1abb49563f742cd588e3a9ba338 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:42:25 +0100 Subject: [PATCH 041/230] fix nbt saving --- .../mixin/tracker/server/level/ServerLevelMixin_Tracker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java index 223e6986d28..a5d8274d3e5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java @@ -577,7 +577,7 @@ public boolean destroyBlock(final BlockPos pos, final boolean doDrops, @Nullable final CompoundTag nbt = new CompoundTag(); // Some mods like OpenComputers assert if attempting to save robot while moving try { - tileEntity.saveWithFullMetadata(); + tileEntity.saveWithFullMetadata(tileEntity.getLevel().registryAccess()); builder.addUnsafeCompound(nbt); } catch (final Throwable t) { // ignore From f7ad3cea5ddcbe2e9fdf59d85a0268ce5244226e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 23:21:20 +0100 Subject: [PATCH 042/230] fix nbt access BlockStateMixin_API --- .../minecraft/world/level/block/state/BlockStateMixin_API.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/BlockStateMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/BlockStateMixin_API.java index 128459013fd..eae8c163d1b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/BlockStateMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/BlockStateMixin_API.java @@ -75,7 +75,8 @@ public BlockSnapshot snapshotFor(final ServerLocation location) { final BlockEntity blockEntity = location.blockEntity() .orElseThrow(() -> new IllegalStateException("Unable to retrieve a TileEntity for location: " + location)); builder.add(((SpongeDataHolderBridge) blockEntity).bridge$getManipulator()); - final CompoundTag compound = ((net.minecraft.world.level.block.entity.BlockEntity) blockEntity).saveWithFullMetadata(); + final var mcBlockEntity = (net.minecraft.world.level.block.entity.BlockEntity) blockEntity; + final CompoundTag compound = mcBlockEntity.saveWithFullMetadata(mcBlockEntity.getLevel().registryAccess()); builder.addUnsafeCompound(compound); } return builder.build(); From ea065232db0cbf76e818f3641e26e3287de6a9b9 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 15:53:31 +0100 Subject: [PATCH 043/230] fix nbt ServerLevelMixin --- .../common/mixin/core/server/level/ServerLevelMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java index 98a7c52daac..46a6b89598e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerLevelMixin.java @@ -356,7 +356,7 @@ public void save(@Nullable final ProgressListener progress, final boolean flush, levelData.setWorldBorder(this.getWorldBorder().createSettings()); - levelData.setCustomBossEvents(((ServerLevelBridge) this).bridge$getBossBarManager().save()); + levelData.setCustomBossEvents(((ServerLevelBridge) this).bridge$getBossBarManager().save(SpongeCommon.server().registryAccess())); ((ServerLevelBridge) this).bridge$getLevelSave().saveDataTag(SpongeCommon.server().registryAccess() , (PrimaryLevelData) this.shadow$getLevelData(), this.shadow$dimension() == Level.OVERWORLD ? SpongeCommon.server().getPlayerList() @@ -486,7 +486,7 @@ public void save(@Nullable final ProgressListener progress, final boolean flush, } @Inject(method = "gameEvent", at = @At("HEAD"), cancellable = true) - private void impl$ignoreGameEventsForVanishedEntities(final GameEvent $$0, final Vec3 $$1, final GameEvent.Context $$2, final CallbackInfo ci) { + private void impl$ignoreGameEventsForVanishedEntities(final Holder $$0, final Vec3 $$1, final GameEvent.Context $$2, final CallbackInfo ci) { if ($$2.sourceEntity() instanceof VanishableBridge bridge && !bridge.bridge$vanishState().triggerVibrations()) { ci.cancel(); } From cec11987378598e309c18a98dae9c013db0c89bf Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 22:08:17 +0100 Subject: [PATCH 044/230] fix nbt MapDecorationMixin_API --- .../common/mixin/api/minecraft/map/MapDecorationMixin_API.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index f94dbbbfd1c..17af7bbabc8 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -34,6 +34,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.world.storage.MapDecorationBridge; import org.spongepowered.common.map.decoration.SpongeMapDecorationType; import org.spongepowered.common.map.decoration.orientation.SpongeMapDecorationOrientation; @@ -104,7 +105,7 @@ public DataContainer toContainer() { .set(Constants.Map.DECORATION_Y, this.y) .set(Constants.Map.DECORATION_ROTATION, (byte) MapUtil.normalizeDecorationOrientation(this.rot)); if (this.shadow$name() != null) { - data.set(Constants.Map.NAME, Component.Serializer.toJson(this.shadow$name())); + data.set(Constants.Map.NAME, Component.Serializer.toJson(this.shadow$name(), SpongeCommon.server().registryAccess())); } return data; } From 78410ddf7af877786721280c5b0ea85d9522cc48 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:03:12 +0100 Subject: [PATCH 045/230] fix entity restore TODO check if this is working --- .../world/EntityPerformingDropsTransaction.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/world/EntityPerformingDropsTransaction.java b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/world/EntityPerformingDropsTransaction.java index 7870ccb4cbe..af22d75f300 100644 --- a/src/main/java/org/spongepowered/common/event/tracking/context/transaction/world/EntityPerformingDropsTransaction.java +++ b/src/main/java/org/spongepowered/common/event/tracking/context/transaction/world/EntityPerformingDropsTransaction.java @@ -143,10 +143,11 @@ public Optional generateEvent( @Override public void restore(PhaseContext context, HarvestEntityEvent event) { - this.destroyingEntity.getType() - .spawn(this.worldSupplier.get(), - this.entityTag, null, this.destroyingEntity.blockPosition(), - MobSpawnType.COMMAND, false, false); + @Nullable final Entity spawn = this.destroyingEntity.getType() + .spawn(this.worldSupplier.get(), null, this.destroyingEntity.blockPosition(), MobSpawnType.COMMAND, false, false); + if (spawn != null) { + spawn.load(this.entityTag); + } } @Override From 2454bd266febaaef9f9104562da39fba639b220a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 20:42:28 +0100 Subject: [PATCH 046/230] fixing RegistryHolderLogic TODO is id required? --- .../common/registry/RegistryHolderLogic.java | 12 +- .../common/registry/RegistryLoader.java | 18 +- .../registry/loader/SpongeRegistryLoader.java | 208 +++++++++--------- .../loader/VanillaRegistryLoader.java | 10 +- 4 files changed, 122 insertions(+), 126 deletions(-) diff --git a/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java b/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java index 351825a07ec..c477bedd461 100644 --- a/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java +++ b/src/main/java/org/spongepowered/common/registry/RegistryHolderLogic.java @@ -27,6 +27,7 @@ import com.mojang.serialization.Lifecycle; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.RegistryAccess; import net.minecraft.core.WritableRegistry; import net.minecraft.core.registries.Registries; @@ -82,7 +83,7 @@ public RegistryHolderLogic(final RegistryAccess dynamicAccess) { // Add the dynamic registries. These are server-scoped in Vanilla dynamicAccess.registries().forEach(entry -> { - root.register(entry.key(), entry.value(), Lifecycle.stable()); + root.register(entry.key(), entry.value(), RegistrationInfo.BUILT_IN); }); root.freeze(); } @@ -187,22 +188,21 @@ public Registry createRegistry(final RegistryType type, final @Nullabl final MappedRegistry mr = (MappedRegistry) registry; defaultValues.forEach((vk, vi, vv) -> { if (vi.isPresent()) { - mr.registerMapping( - vi.getAsInt(), + mr.register( net.minecraft.resources.ResourceKey.create(key, (ResourceLocation) (Object) vk), vv, - Lifecycle.stable() + RegistrationInfo.BUILT_IN ); } else { mr.register( net.minecraft.resources.ResourceKey.create(key, (ResourceLocation) (Object) vk), vv, - Lifecycle.stable() + RegistrationInfo.BUILT_IN ); } }); } - ((WritableRegistry) root).register(key, registry, Lifecycle.stable()); + ((WritableRegistry) root).register(key, registry, RegistrationInfo.BUILT_IN); if (registry instanceof CallbackRegistry) { ((CallbackRegistry) registry).setCallbackEnabled(true); } diff --git a/src/main/java/org/spongepowered/common/registry/RegistryLoader.java b/src/main/java/org/spongepowered/common/registry/RegistryLoader.java index a9a599a58df..b16aaa5d37b 100644 --- a/src/main/java/org/spongepowered/common/registry/RegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/RegistryLoader.java @@ -66,19 +66,19 @@ public RegistryLoader add(final ResourceKey key, final T value) { } - public RegistryLoader add(final int id, final RegistryKey key, final Supplier supplier) { - return this.add0(id, key, supplier.get()); + public RegistryLoader addWithId(final int id, final RegistryKey key, final Supplier supplier) { + return this.addWithId0(id, key, supplier.get()); } - public RegistryLoader add(final int id, final RegistryKey key, final Function function) { - return this.add0(id, key, function.apply(key.location())); + public RegistryLoader addWithId(final int id, final RegistryKey key, final Function function) { + return this.addWithId0(id, key, function.apply(key.location())); } - public RegistryLoader add(final MC mcType, final RegistryKey key, final Function function, final Function idFunction) { - return this.add0(idFunction.apply(mcType), key, function.apply(mcType)); + public RegistryLoader addWithId(final MC mcType, final RegistryKey key, final Function function, final Function idFunction) { + return this.addWithId0(idFunction.apply(mcType), key, function.apply(mcType)); } - private RegistryLoader add0(final int id, final RegistryKey key, final T value) { + private RegistryLoader addWithId0(final int id, final RegistryKey key, final T value) { this.values.put(key.location(), value); if (this.ids == null) { this.ids = new HashMap<>(); @@ -119,10 +119,6 @@ public Map values() { return this.values; } - public @Nullable Map ids() { - return this.ids; - } - @Override Map keyToValue() { return this.values; diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index 75697966318..69ded2d71fd 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -335,31 +335,31 @@ public static RegistryLoader musicDisc() { public static RegistryLoader notePitch() { return RegistryLoader.of(l -> { - l.add(0, NotePitches.F_SHARP0, SpongeNotePitch::new); - l.add(1, NotePitches.G0, SpongeNotePitch::new); - l.add(2, NotePitches.G_SHARP0, SpongeNotePitch::new); - l.add(3, NotePitches.A1, SpongeNotePitch::new); - l.add(4, NotePitches.A_SHARP1, SpongeNotePitch::new); - l.add(5, NotePitches.B1, SpongeNotePitch::new); - l.add(6, NotePitches.C1, SpongeNotePitch::new); - l.add(7, NotePitches.C_SHARP1, SpongeNotePitch::new); - l.add(8, NotePitches.D1, SpongeNotePitch::new); - l.add(9, NotePitches.D_SHARP1, SpongeNotePitch::new); - l.add(10, NotePitches.E1, SpongeNotePitch::new); - l.add(11, NotePitches.F1, SpongeNotePitch::new); - l.add(12, NotePitches.F_SHARP1, SpongeNotePitch::new); - l.add(13, NotePitches.G1, SpongeNotePitch::new); - l.add(14, NotePitches.G_SHARP1, SpongeNotePitch::new); - l.add(15, NotePitches.A2, SpongeNotePitch::new); - l.add(16, NotePitches.A_SHARP2, SpongeNotePitch::new); - l.add(17, NotePitches.B2, SpongeNotePitch::new); - l.add(18, NotePitches.C2, SpongeNotePitch::new); - l.add(19, NotePitches.C_SHARP2, SpongeNotePitch::new); - l.add(20, NotePitches.D2, SpongeNotePitch::new); - l.add(21, NotePitches.D_SHARP2, SpongeNotePitch::new); - l.add(22, NotePitches.E2, SpongeNotePitch::new); - l.add(23, NotePitches.F2, SpongeNotePitch::new); - l.add(24, NotePitches.F_SHARP2, SpongeNotePitch::new); + l.addWithId(0, NotePitches.F_SHARP0, SpongeNotePitch::new); + l.addWithId(1, NotePitches.G0, SpongeNotePitch::new); + l.addWithId(2, NotePitches.G_SHARP0, SpongeNotePitch::new); + l.addWithId(3, NotePitches.A1, SpongeNotePitch::new); + l.addWithId(4, NotePitches.A_SHARP1, SpongeNotePitch::new); + l.addWithId(5, NotePitches.B1, SpongeNotePitch::new); + l.addWithId(6, NotePitches.C1, SpongeNotePitch::new); + l.addWithId(7, NotePitches.C_SHARP1, SpongeNotePitch::new); + l.addWithId(8, NotePitches.D1, SpongeNotePitch::new); + l.addWithId(9, NotePitches.D_SHARP1, SpongeNotePitch::new); + l.addWithId(10, NotePitches.E1, SpongeNotePitch::new); + l.addWithId(11, NotePitches.F1, SpongeNotePitch::new); + l.addWithId(12, NotePitches.F_SHARP1, SpongeNotePitch::new); + l.addWithId(13, NotePitches.G1, SpongeNotePitch::new); + l.addWithId(14, NotePitches.G_SHARP1, SpongeNotePitch::new); + l.addWithId(15, NotePitches.A2, SpongeNotePitch::new); + l.addWithId(16, NotePitches.A_SHARP2, SpongeNotePitch::new); + l.addWithId(17, NotePitches.B2, SpongeNotePitch::new); + l.addWithId(18, NotePitches.C2, SpongeNotePitch::new); + l.addWithId(19, NotePitches.C_SHARP2, SpongeNotePitch::new); + l.addWithId(20, NotePitches.D2, SpongeNotePitch::new); + l.addWithId(21, NotePitches.D_SHARP2, SpongeNotePitch::new); + l.addWithId(22, NotePitches.E2, SpongeNotePitch::new); + l.addWithId(23, NotePitches.F2, SpongeNotePitch::new); + l.addWithId(24, NotePitches.F_SHARP2, SpongeNotePitch::new); }); } @@ -531,86 +531,86 @@ public static RegistryLoader dataFormat() { public static RegistryLoader mapColorType() { final Function colorId = mc -> mc.id; return RegistryLoader.of(l -> { - l.add(MapColor.NONE, MapColorTypes.NONE, SpongeMapColorType::new, colorId); - l.add(MapColor.GRASS, MapColorTypes.GRASS, SpongeMapColorType::new, colorId); - l.add(MapColor.SAND, MapColorTypes.SAND, SpongeMapColorType::new, colorId); - l.add(MapColor.WOOL, MapColorTypes.WOOL, SpongeMapColorType::new, colorId); - l.add(MapColor.FIRE, MapColorTypes.FIRE, SpongeMapColorType::new, colorId); - l.add(MapColor.ICE, MapColorTypes.ICE, SpongeMapColorType::new, colorId); - l.add(MapColor.METAL, MapColorTypes.METAL, SpongeMapColorType::new, colorId); - l.add(MapColor.PLANT, MapColorTypes.PLANT, SpongeMapColorType::new, colorId); - l.add(MapColor.SNOW, MapColorTypes.SNOW, SpongeMapColorType::new, colorId); - l.add(MapColor.CLAY, MapColorTypes.CLAY, SpongeMapColorType::new, colorId); - l.add(MapColor.DIRT, MapColorTypes.DIRT, SpongeMapColorType::new, colorId); - l.add(MapColor.STONE, MapColorTypes.STONE, SpongeMapColorType::new, colorId); - l.add(MapColor.WATER, MapColorTypes.WATER, SpongeMapColorType::new, colorId); - l.add(MapColor.WOOD, MapColorTypes.WOOD, SpongeMapColorType::new, colorId); - l.add(MapColor.QUARTZ, MapColorTypes.QUARTZ, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_ORANGE, MapColorTypes.COLOR_ORANGE, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_MAGENTA, MapColorTypes.COLOR_MAGENTA, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_LIGHT_BLUE, MapColorTypes.COLOR_LIGHT_BLUE, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_YELLOW, MapColorTypes.COLOR_YELLOW, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_LIGHT_GREEN, MapColorTypes.COLOR_LIGHT_GREEN, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_PINK, MapColorTypes.COLOR_PINK, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_GRAY, MapColorTypes.COLOR_GRAY, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_LIGHT_GRAY, MapColorTypes.COLOR_LIGHT_GRAY, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_CYAN, MapColorTypes.COLOR_CYAN, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_PURPLE, MapColorTypes.COLOR_PURPLE, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_BLUE, MapColorTypes.COLOR_BLUE, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_BROWN, MapColorTypes.COLOR_BROWN, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_GREEN, MapColorTypes.COLOR_GREEN, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_RED, MapColorTypes.COLOR_RED, SpongeMapColorType::new, colorId); - l.add(MapColor.COLOR_BLACK, MapColorTypes.COLOR_BLACK, SpongeMapColorType::new, colorId); - l.add(MapColor.GOLD, MapColorTypes.GOLD, SpongeMapColorType::new, colorId); - l.add(MapColor.DIAMOND, MapColorTypes.DIAMOND, SpongeMapColorType::new, colorId); - l.add(MapColor.LAPIS, MapColorTypes.LAPIS_LAZULI, SpongeMapColorType::new, colorId); - l.add(MapColor.EMERALD, MapColorTypes.EMERALD, SpongeMapColorType::new, colorId); - l.add(MapColor.PODZOL, MapColorTypes.PODZOL, SpongeMapColorType::new, colorId); - l.add(MapColor.NETHER, MapColorTypes.NETHER, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_WHITE, MapColorTypes.TERRACOTTA_WHITE, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_ORANGE, MapColorTypes.TERRACOTTA_ORANGE, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_MAGENTA, MapColorTypes.TERRACOTTA_MAGENTA, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_LIGHT_BLUE, MapColorTypes.TERRACOTTA_LIGHT_BLUE, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_YELLOW, MapColorTypes.TERRACOTTA_YELLOW, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_LIGHT_GREEN, MapColorTypes.TERRACOTTA_LIGHT_GREEN, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_PINK, MapColorTypes.TERRACOTTA_PINK, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_GRAY, MapColorTypes.TERRACOTTA_GRAY, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_LIGHT_GRAY, MapColorTypes.TERRACOTTA_LIGHT_GRAY, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_CYAN, MapColorTypes.TERRACOTTA_CYAN, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_PURPLE, MapColorTypes.TERRACOTTA_PURPLE, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_BLUE, MapColorTypes.TERRACOTTA_BLUE, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_BROWN, MapColorTypes.TERRACOTTA_BROWN, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_GREEN, MapColorTypes.TERRACOTTA_GREEN, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_RED, MapColorTypes.TERRACOTTA_RED, SpongeMapColorType::new, colorId); - l.add(MapColor.TERRACOTTA_BLACK, MapColorTypes.TERRACOTTA_BLACK, SpongeMapColorType::new, colorId); - l.add(MapColor.CRIMSON_NYLIUM, MapColorTypes.CRIMSON_NYLIUM, SpongeMapColorType::new, colorId); - l.add(MapColor.CRIMSON_STEM, MapColorTypes.CRIMSON_STEM, SpongeMapColorType::new, colorId); - l.add(MapColor.CRIMSON_HYPHAE, MapColorTypes.CRIMSON_HYPHAE, SpongeMapColorType::new, colorId); - l.add(MapColor.WARPED_NYLIUM, MapColorTypes.WARPED_NYLIUM, SpongeMapColorType::new, colorId); - l.add(MapColor.WARPED_STEM, MapColorTypes.WARPED_STEM, SpongeMapColorType::new, colorId); - l.add(MapColor.WARPED_HYPHAE, MapColorTypes.WARPED_HYPHAE, SpongeMapColorType::new, colorId); - l.add(MapColor.WARPED_WART_BLOCK, MapColorTypes.WARPED_WART_BLOCK, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.NONE, MapColorTypes.NONE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.GRASS, MapColorTypes.GRASS, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.SAND, MapColorTypes.SAND, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WOOL, MapColorTypes.WOOL, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.FIRE, MapColorTypes.FIRE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.ICE, MapColorTypes.ICE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.METAL, MapColorTypes.METAL, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.PLANT, MapColorTypes.PLANT, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.SNOW, MapColorTypes.SNOW, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.CLAY, MapColorTypes.CLAY, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.DIRT, MapColorTypes.DIRT, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.STONE, MapColorTypes.STONE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WATER, MapColorTypes.WATER, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WOOD, MapColorTypes.WOOD, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.QUARTZ, MapColorTypes.QUARTZ, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_ORANGE, MapColorTypes.COLOR_ORANGE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_MAGENTA, MapColorTypes.COLOR_MAGENTA, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_LIGHT_BLUE, MapColorTypes.COLOR_LIGHT_BLUE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_YELLOW, MapColorTypes.COLOR_YELLOW, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_LIGHT_GREEN, MapColorTypes.COLOR_LIGHT_GREEN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_PINK, MapColorTypes.COLOR_PINK, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_GRAY, MapColorTypes.COLOR_GRAY, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_LIGHT_GRAY, MapColorTypes.COLOR_LIGHT_GRAY, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_CYAN, MapColorTypes.COLOR_CYAN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_PURPLE, MapColorTypes.COLOR_PURPLE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_BLUE, MapColorTypes.COLOR_BLUE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_BROWN, MapColorTypes.COLOR_BROWN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_GREEN, MapColorTypes.COLOR_GREEN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_RED, MapColorTypes.COLOR_RED, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.COLOR_BLACK, MapColorTypes.COLOR_BLACK, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.GOLD, MapColorTypes.GOLD, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.DIAMOND, MapColorTypes.DIAMOND, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.LAPIS, MapColorTypes.LAPIS_LAZULI, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.EMERALD, MapColorTypes.EMERALD, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.PODZOL, MapColorTypes.PODZOL, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.NETHER, MapColorTypes.NETHER, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_WHITE, MapColorTypes.TERRACOTTA_WHITE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_ORANGE, MapColorTypes.TERRACOTTA_ORANGE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_MAGENTA, MapColorTypes.TERRACOTTA_MAGENTA, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_LIGHT_BLUE, MapColorTypes.TERRACOTTA_LIGHT_BLUE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_YELLOW, MapColorTypes.TERRACOTTA_YELLOW, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_LIGHT_GREEN, MapColorTypes.TERRACOTTA_LIGHT_GREEN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_PINK, MapColorTypes.TERRACOTTA_PINK, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_GRAY, MapColorTypes.TERRACOTTA_GRAY, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_LIGHT_GRAY, MapColorTypes.TERRACOTTA_LIGHT_GRAY, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_CYAN, MapColorTypes.TERRACOTTA_CYAN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_PURPLE, MapColorTypes.TERRACOTTA_PURPLE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_BLUE, MapColorTypes.TERRACOTTA_BLUE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_BROWN, MapColorTypes.TERRACOTTA_BROWN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_GREEN, MapColorTypes.TERRACOTTA_GREEN, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_RED, MapColorTypes.TERRACOTTA_RED, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.TERRACOTTA_BLACK, MapColorTypes.TERRACOTTA_BLACK, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.CRIMSON_NYLIUM, MapColorTypes.CRIMSON_NYLIUM, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.CRIMSON_STEM, MapColorTypes.CRIMSON_STEM, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.CRIMSON_HYPHAE, MapColorTypes.CRIMSON_HYPHAE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WARPED_NYLIUM, MapColorTypes.WARPED_NYLIUM, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WARPED_STEM, MapColorTypes.WARPED_STEM, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WARPED_HYPHAE, MapColorTypes.WARPED_HYPHAE, SpongeMapColorType::new, colorId); + l.addWithId(MapColor.WARPED_WART_BLOCK, MapColorTypes.WARPED_WART_BLOCK, SpongeMapColorType::new, colorId); }); } public static RegistryLoader mapDecorationOrientation() { return RegistryLoader.of(l -> { - l.add(0, MapDecorationOrientations.SOUTH, k -> new SpongeMapDecorationOrientation(0)); - l.add(1, MapDecorationOrientations.SOUTH_SOUTHWEST, k -> new SpongeMapDecorationOrientation(1)); - l.add(2, MapDecorationOrientations.SOUTHWEST, k -> new SpongeMapDecorationOrientation(2)); - l.add(3, MapDecorationOrientations.WEST_SOUTHWEST, k -> new SpongeMapDecorationOrientation(3)); - l.add(4, MapDecorationOrientations.WEST, k -> new SpongeMapDecorationOrientation(4)); - l.add(5, MapDecorationOrientations.WEST_NORTHWEST, k -> new SpongeMapDecorationOrientation(5)); - l.add(6, MapDecorationOrientations.NORTHWEST, k -> new SpongeMapDecorationOrientation(6)); - l.add(7, MapDecorationOrientations.NORTH_NORTHWEST, k -> new SpongeMapDecorationOrientation(7)); - l.add(8, MapDecorationOrientations.NORTH, k -> new SpongeMapDecorationOrientation(8)); - l.add(9, MapDecorationOrientations.NORTH_NORTHEAST, k -> new SpongeMapDecorationOrientation(9)); - l.add(10, MapDecorationOrientations.NORTHEAST, k -> new SpongeMapDecorationOrientation(10)); - l.add(11, MapDecorationOrientations.EAST_NORTHEAST, k -> new SpongeMapDecorationOrientation(11)); - l.add(12, MapDecorationOrientations.EAST, k -> new SpongeMapDecorationOrientation(12)); - l.add(13, MapDecorationOrientations.EAST_SOUTHEAST, k -> new SpongeMapDecorationOrientation(13)); - l.add(14, MapDecorationOrientations.SOUTHEAST, k -> new SpongeMapDecorationOrientation(14)); - l.add(15, MapDecorationOrientations.SOUTH_SOUTHEAST, k -> new SpongeMapDecorationOrientation(15)); + l.addWithId(0, MapDecorationOrientations.SOUTH, k -> new SpongeMapDecorationOrientation(0)); + l.addWithId(1, MapDecorationOrientations.SOUTH_SOUTHWEST, k -> new SpongeMapDecorationOrientation(1)); + l.addWithId(2, MapDecorationOrientations.SOUTHWEST, k -> new SpongeMapDecorationOrientation(2)); + l.addWithId(3, MapDecorationOrientations.WEST_SOUTHWEST, k -> new SpongeMapDecorationOrientation(3)); + l.addWithId(4, MapDecorationOrientations.WEST, k -> new SpongeMapDecorationOrientation(4)); + l.addWithId(5, MapDecorationOrientations.WEST_NORTHWEST, k -> new SpongeMapDecorationOrientation(5)); + l.addWithId(6, MapDecorationOrientations.NORTHWEST, k -> new SpongeMapDecorationOrientation(6)); + l.addWithId(7, MapDecorationOrientations.NORTH_NORTHWEST, k -> new SpongeMapDecorationOrientation(7)); + l.addWithId(8, MapDecorationOrientations.NORTH, k -> new SpongeMapDecorationOrientation(8)); + l.addWithId(9, MapDecorationOrientations.NORTH_NORTHEAST, k -> new SpongeMapDecorationOrientation(9)); + l.addWithId(10, MapDecorationOrientations.NORTHEAST, k -> new SpongeMapDecorationOrientation(10)); + l.addWithId(11, MapDecorationOrientations.EAST_NORTHEAST, k -> new SpongeMapDecorationOrientation(11)); + l.addWithId(12, MapDecorationOrientations.EAST, k -> new SpongeMapDecorationOrientation(12)); + l.addWithId(13, MapDecorationOrientations.EAST_SOUTHEAST, k -> new SpongeMapDecorationOrientation(13)); + l.addWithId(14, MapDecorationOrientations.SOUTHEAST, k -> new SpongeMapDecorationOrientation(14)); + l.addWithId(15, MapDecorationOrientations.SOUTH_SOUTHEAST, k -> new SpongeMapDecorationOrientation(15)); }); } @@ -649,10 +649,10 @@ public static RegistryLoader mapDecorationType() { public static RegistryLoader mapShade() { return RegistryLoader.of(l -> { - l.add(0, MapShades.BASE, k -> new SpongeMapShade(0, 180)); - l.add(1, MapShades.DARK, k -> new SpongeMapShade(1, 220)); - l.add(2, MapShades.DARKER, k -> new SpongeMapShade(2, 255)); - l.add(3, MapShades.DARKEST, k -> new SpongeMapShade(3, 135)); + l.addWithId(0, MapShades.BASE, k -> new SpongeMapShade(0, 180)); + l.addWithId(1, MapShades.DARK, k -> new SpongeMapShade(1, 220)); + l.addWithId(2, MapShades.DARKER, k -> new SpongeMapShade(2, 255)); + l.addWithId(3, MapShades.DARKEST, k -> new SpongeMapShade(3, 135)); }); } diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index 0b37bc35f2c..b7b49c3ad4e 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -257,11 +257,11 @@ private static RegistryLoader criterion() { private static RegistryLoader fireworkShape() { return RegistryLoader.of(l -> { - l.add(FireworkExplosion.Shape.BURST.getId(), FireworkShapes.BURST, () -> (FireworkShape) (Object) FireworkExplosion.Shape.BURST); - l.add(FireworkExplosion.Shape.CREEPER.getId(), FireworkShapes.CREEPER, () -> (FireworkShape) (Object) FireworkExplosion.Shape.CREEPER); - l.add(FireworkExplosion.Shape.LARGE_BALL.getId(), FireworkShapes.LARGE_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.LARGE_BALL); - l.add(FireworkExplosion.Shape.SMALL_BALL.getId(), FireworkShapes.SMALL_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.SMALL_BALL); - l.add(FireworkExplosion.Shape.STAR.getId(), FireworkShapes.STAR, () -> (FireworkShape) (Object) FireworkExplosion.Shape.STAR); + l.addWithId(FireworkExplosion.Shape.BURST.getId(), FireworkShapes.BURST, () -> (FireworkShape) (Object) FireworkExplosion.Shape.BURST); + l.addWithId(FireworkExplosion.Shape.CREEPER.getId(), FireworkShapes.CREEPER, () -> (FireworkShape) (Object) FireworkExplosion.Shape.CREEPER); + l.addWithId(FireworkExplosion.Shape.LARGE_BALL.getId(), FireworkShapes.LARGE_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.LARGE_BALL); + l.addWithId(FireworkExplosion.Shape.SMALL_BALL.getId(), FireworkShapes.SMALL_BALL, () -> (FireworkShape) (Object) FireworkExplosion.Shape.SMALL_BALL); + l.addWithId(FireworkExplosion.Shape.STAR.getId(), FireworkShapes.STAR, () -> (FireworkShape) (Object) FireworkExplosion.Shape.STAR); }); } From a0aa65553db8ba91454b78fe2ecd7f8e1ab1d1ea Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:05:26 +0100 Subject: [PATCH 047/230] fix registry --- .../org/spongepowered/common/registry/CallbackRegistry.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/registry/CallbackRegistry.java b/src/main/java/org/spongepowered/common/registry/CallbackRegistry.java index 60251f08056..97444359ff1 100644 --- a/src/main/java/org/spongepowered/common/registry/CallbackRegistry.java +++ b/src/main/java/org/spongepowered/common/registry/CallbackRegistry.java @@ -27,6 +27,7 @@ import com.mojang.serialization.Lifecycle; import net.minecraft.core.Holder; import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; @@ -43,7 +44,7 @@ public CallbackRegistry(final ResourceKey> key, final Life } @Override - public Holder.Reference register(final ResourceKey key, final T instance, final Lifecycle lifecycle) { + public Holder.Reference register(final ResourceKey key, final T instance, final RegistrationInfo lifecycle) { final Holder.Reference value = super.register(key, instance, lifecycle); if (this.callbackEnabled) { this.callback.accept(key, instance); From 6c8588b4655074a05ad5090942f272ca10c9f7c3 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:02:20 +0100 Subject: [PATCH 048/230] fix registry RegistryDataLoaderMixin --- .../resources/RegistryDataLoaderMixin.java | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/resources/RegistryDataLoaderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/resources/RegistryDataLoaderMixin.java index 8d7e607660e..dec6168190e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/resources/RegistryDataLoaderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/resources/RegistryDataLoaderMixin.java @@ -25,8 +25,7 @@ package org.spongepowered.common.mixin.core.resources; import com.mojang.serialization.Decoder; -import com.mojang.serialization.Lifecycle; -import net.minecraft.core.Registry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.WritableRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.ChatType; @@ -48,16 +47,19 @@ public class RegistryDataLoaderMixin { @SuppressWarnings("unchecked") - @Inject(method = "loadRegistryContents", at = @At("RETURN")) - private static void impl$afterLoadRegistryContents(final RegistryOps.RegistryInfoLookup $$0, final ResourceManager $$1, final ResourceKey> $$2, - final WritableRegistry $$3, final Decoder $$4, final Map, Exception> $$5, final CallbackInfo ci) + @Inject(method = "loadContentsFromManager", at = @At("RETURN")) + private static void impl$afterLoadRegistryContents( + final ResourceManager $$0, + final RegistryOps.RegistryInfoLookup $$1, + final WritableRegistry $$2, + final Decoder $$3, + final Map, Exception> $$4, + final CallbackInfo ci) { - final ChatTypeDecoration narration = ChatTypeDecoration.withSender("chat.type.text.narrate"); - - if (Registries.CHAT_TYPE.equals($$2)) { - - $$3.register(ResourceKey.create($$2, (ResourceLocation) (Object) ChatTypes.CUSTOM_CHAT.location()), (E) new ChatType(ChatTypeDecoration.withSender("%s%s"), narration), Lifecycle.stable()); - $$3.register(ResourceKey.create($$2, (ResourceLocation) (Object) ChatTypes.CUSTOM_MESSAGE.location()), (E) new ChatType(ChatTypeDecoration.teamMessage("%s%s%s"), narration), Lifecycle.stable()); + if (Registries.CHAT_TYPE.equals($$2.key())) { + final ChatTypeDecoration narration = ChatTypeDecoration.withSender("chat.type.text.narrate"); + $$2.register(ResourceKey.create($$2.key(), (ResourceLocation) (Object) ChatTypes.CUSTOM_CHAT.location()), (E) new ChatType(ChatTypeDecoration.withSender("%s%s"), narration), RegistrationInfo.BUILT_IN); + $$2.register(ResourceKey.create($$2.key(), (ResourceLocation) (Object) ChatTypes.CUSTOM_MESSAGE.location()), (E) new ChatType(ChatTypeDecoration.teamMessage("%s%s%s"), narration), RegistrationInfo.BUILT_IN); } } } From 27330519b4ae8f0e42efc5a9cf29f182ffc862ce Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:13:01 +0100 Subject: [PATCH 049/230] fix AttributeModifier Operation --- .../common/registry/loader/VanillaRegistryLoader.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index b7b49c3ad4e..bb28182dad8 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -151,9 +151,9 @@ private void loadEnumRegistries() { this.automaticSerializedName(RegistryTypes.BELL_ATTACHMENT_TYPE, BellAttachType.values()); this.manualName(RegistryTypes.ATTRIBUTE_OPERATION, AttributeModifier.Operation.values(), map -> { // names come from net.minecraft.world.level.storage.loot.functions.SetAttributesFunction.Modifier#operationFromString - map.put(AttributeModifier.Operation.ADDITION, "addition"); - map.put(AttributeModifier.Operation.MULTIPLY_BASE, "multiply_base"); - map.put(AttributeModifier.Operation.MULTIPLY_TOTAL, "multiply_total"); + map.put(AttributeModifier.Operation.ADD_VALUE, "addition"); + map.put(AttributeModifier.Operation.ADD_MULTIPLIED_BASE, "multiply_base"); + map.put(AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL, "multiply_total"); }); this.knownName(RegistryTypes.BOAT_TYPE, Boat.Type.values(), Boat.Type::getName); this.automaticSerializedName(RegistryTypes.CHEST_ATTACHMENT_TYPE, ChestType.values()); From 719d9b2f7221aaecc5cf396516c6745d18257de3 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:06:42 +0100 Subject: [PATCH 050/230] fix cmd related registry --- .../org/spongepowered/common/registry/SpongeRegistries.java | 2 +- .../common/registry/loader/CommandRegistryLoader.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java b/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java index d27f733201c..e67967dba8f 100644 --- a/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java +++ b/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java @@ -107,7 +107,7 @@ public static void registerGlobalRegistriesDimensionLayer(final SpongeRegistryHo return; // Already done } final RegistryAccess.ImmutableRegistryAccess builtInRegistryAccess = new RegistryAccess.ImmutableRegistryAccess(BuiltInRegistries.REGISTRY.stream().toList()); - final CommandBuildContext cbCtx = CommandBuildContext.configurable(builtInRegistryAccess, featureFlags); + final CommandBuildContext cbCtx = CommandBuildContext.simple(builtInRegistryAccess, featureFlags); holder.createFrozenRegistry(RegistryTypes.COMMAND_TREE_NODE_TYPE, CommandRegistryLoader.clientCompletionKey(cbCtx)); holder.createFrozenRegistry(RegistryTypes.REGISTRY_KEYED_VALUE_PARAMETER, CommandRegistryLoader.valueParameter(cbCtx)); diff --git a/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java index 2b74c906277..4b6f07a7b43 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/CommandRegistryLoader.java @@ -172,7 +172,7 @@ public static RegistryLoader> valueParameter(final CommandBuil l.add(ResourceKeyedValueParameters.TARGET_PLAYER, k -> new SpongeTargetEntityValueParameter(k, true)); l.add(ResourceKeyedValueParameters.TEXT_FORMATTING_CODE, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.string(), (reader, cause, result) -> LegacyComponentSerializer.legacyAmpersand().deserialize(result))); l.add(ResourceKeyedValueParameters.TEXT_FORMATTING_CODE_ALL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.greedyString(), (reader, cause, result) -> LegacyComponentSerializer.legacyAmpersand().deserialize(result))); - l.add(ResourceKeyedValueParameters.TEXT_JSON, k -> ClientNativeArgumentParser.createConverter(k, ComponentArgument.textComponent(), (reader, cause, result) -> SpongeAdventure.asAdventure(result))); + l.add(ResourceKeyedValueParameters.TEXT_JSON, k -> ClientNativeArgumentParser.createConverter(k, ComponentArgument.textComponent(cbCtx), (reader, cause, result) -> SpongeAdventure.asAdventure(result))); l.add(ResourceKeyedValueParameters.TEXT_JSON_ALL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.greedyString(), (reader, cause, result) -> GsonComponentSerializer.gson().deserialize(result))); l.add(ResourceKeyedValueParameters.URL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.string(), (reader, cause, input) -> { From 05e4159e1c970599458f129016a13a94888b1ddd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:12:25 +0100 Subject: [PATCH 051/230] fix ArmorMaterials are now in a registry --- SpongeAPI | 2 +- .../world/item/ArmorMaterialsAccessor.java | 36 ------------------- .../resources/mixins.sponge.accessors.json | 1 - .../loader/VanillaRegistryLoader.java | 2 -- ...n_API.java => ArmorMaterialMixin_API.java} | 11 +++--- src/mixins/resources/mixins.sponge.api.json | 2 +- 6 files changed, 9 insertions(+), 45 deletions(-) delete mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/item/ArmorMaterialsAccessor.java rename src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/{ArmorMaterialsMixin_API.java => ArmorMaterialMixin_API.java} (85%) diff --git a/SpongeAPI b/SpongeAPI index 5b125a1d7a9..5565cde1d2d 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit 5b125a1d7a9c7e5935c8598237f2348a4c1ae3ca +Subproject commit 5565cde1d2d40fc5cb6ae2ddee63431255bcf51e diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/ArmorMaterialsAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/ArmorMaterialsAccessor.java deleted file mode 100644 index facdcf7ab63..00000000000 --- a/src/accessors/java/org/spongepowered/common/accessor/world/item/ArmorMaterialsAccessor.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.accessor.world.item; - -import net.minecraft.world.item.ArmorMaterials; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(ArmorMaterials.class) -public interface ArmorMaterialsAccessor { - - @Accessor("name") String accessor$name(); - -} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index b00c599b9cc..648c1eff914 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -136,7 +136,6 @@ "world.inventory.ResultSlotAccessor", "world.inventory.SlotAccessor", "world.item.AdventureModePredicateAccessor", - "world.item.ArmorMaterialsAccessor", "world.item.DiggerItemAccessor", "world.item.ItemCooldowns_CooldownInstanceAccessor", "world.item.RecordItemAccessor", diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index bb28182dad8..8c8fa13996a 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -100,7 +100,6 @@ import org.spongepowered.api.scoreboard.criteria.Criterion; import org.spongepowered.common.accessor.world.entity.animal.MushroomCow_MushroomTypeAccessor; import org.spongepowered.common.accessor.world.entity.boss.enderdragon.phases.EnderDragonPhaseAccessor; -import org.spongepowered.common.accessor.world.item.ArmorMaterialsAccessor; import org.spongepowered.common.accessor.world.level.GameRulesAccessor; import org.spongepowered.common.registry.RegistryLoader; import org.spongepowered.common.registry.SpongeRegistryHolder; @@ -145,7 +144,6 @@ private void loadInstanceRegistries() { } private void loadEnumRegistries() { - this.knownName(RegistryTypes.ARMOR_MATERIAL, ArmorMaterials.values(), am -> ((ArmorMaterialsAccessor) (Object) am).accessor$name()); this.automaticSerializedName(RegistryTypes.ATTACHMENT_SURFACE, AttachFace.values()); this.automaticSerializedName(RegistryTypes.BAMBOO_LEAVES_TYPE, BambooLeaves.values()); this.automaticSerializedName(RegistryTypes.BELL_ATTACHMENT_TYPE, BellAttachType.values()); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialsMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java similarity index 85% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialsMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java index fc821b8c6b1..4a003b8b2b3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialsMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ArmorMaterialMixin_API.java @@ -26,24 +26,27 @@ import org.spongepowered.api.data.type.ArmorMaterial; import org.spongepowered.api.item.recipe.crafting.Ingredient; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.Optional; +import java.util.function.Supplier; -@Mixin(net.minecraft.world.item.ArmorMaterials.class) +@Mixin(net.minecraft.world.item.ArmorMaterial.class) @Implements(@Interface(iface = ArmorMaterial.class, prefix = "armorMaterial$")) -public abstract class ArmorMaterialsMixin_API implements ArmorMaterial { +public abstract class ArmorMaterialMixin_API implements ArmorMaterial { // @formatter:off - @Shadow public abstract net.minecraft.world.item.crafting.Ingredient shadow$getRepairIngredient(); + @Shadow @Final private Supplier repairIngredient; + // @formatter:on @Override public Optional repairIngredient() { - final net.minecraft.world.item.crafting.Ingredient repairMaterial = this.shadow$getRepairIngredient(); + final net.minecraft.world.item.crafting.Ingredient repairMaterial = this.repairIngredient.get(); return Optional.ofNullable(((Ingredient) (Object) repairMaterial)); } diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 92640908188..cceb906867c 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -285,7 +285,7 @@ "minecraft.world.entity.vehicle.MinecartMixin_API", "minecraft.world.entity.vehicle.MinecartSpawnerMixin_API", "minecraft.world.entity.vehicle.MinecartTNTMixin_API", - "minecraft.world.item.ArmorMaterialsMixin_API", + "minecraft.world.item.ArmorMaterialMixin_API", "minecraft.world.item.DyeColorMixin_API", "minecraft.world.item.FireworkExplosion_ShapeMixin_API", "minecraft.world.item.ItemCooldownsMixin_API", From 513edd5cd0f8ef094befe7515e76772fba9302df Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 22:53:15 +0100 Subject: [PATCH 052/230] fix Fireworks can now be mixed in --- .../item/SpongeFireworkEffectBuilder.java | 8 +- .../common/util/FireworkUtil.java | 126 ++++-------------- .../FireworkExplosionMixin_API.java} | 81 ++++------- src/mixins/resources/mixins.sponge.api.json | 1 + 4 files changed, 54 insertions(+), 162 deletions(-) rename src/{main/java/org/spongepowered/common/item/SpongeFireworkEffect.java => mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/component/FireworkExplosionMixin_API.java} (57%) diff --git a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffectBuilder.java b/src/main/java/org/spongepowered/common/item/SpongeFireworkEffectBuilder.java index b69c5ce7770..3169fb09cb2 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffectBuilder.java +++ b/src/main/java/org/spongepowered/common/item/SpongeFireworkEffectBuilder.java @@ -26,6 +26,8 @@ import com.google.common.collect.Lists; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import net.minecraft.world.item.component.FireworkExplosion; import org.spongepowered.api.item.FireworkEffect; import org.spongepowered.api.item.FireworkShape; import org.spongepowered.api.item.FireworkShapes; @@ -111,7 +113,11 @@ public SpongeFireworkEffectBuilder shape(final FireworkShape shape) { @Override public FireworkEffect build() { - return new SpongeFireworkEffect(this.flicker, this.trail, this.colors, this.fades, this.shape.get()); + return (FireworkEffect) (Object) new FireworkExplosion( + (FireworkExplosion.Shape) (Object) this.shape.get(), + new IntArrayList(this.colors.stream().map(Color::rgb).toList()), + new IntArrayList(this.fades.stream().map(Color::rgb).toList()), + this.trail, this.flicker); } @Override diff --git a/src/main/java/org/spongepowered/common/util/FireworkUtil.java b/src/main/java/org/spongepowered/common/util/FireworkUtil.java index 129b31d4951..173abfa996c 100644 --- a/src/main/java/org/spongepowered/common/util/FireworkUtil.java +++ b/src/main/java/org/spongepowered/common/util/FireworkUtil.java @@ -24,94 +24,23 @@ */ package org.spongepowered.common.util; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import net.minecraft.core.MappedRegistry; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.projectile.FireworkRocketEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.Sponge; +import net.minecraft.world.item.component.FireworkExplosion; +import net.minecraft.world.item.component.Fireworks; import org.spongepowered.api.item.FireworkEffect; -import org.spongepowered.api.item.FireworkShape; import org.spongepowered.api.item.ItemTypes; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.util.Color; import org.spongepowered.common.accessor.world.entity.projectile.FireworkRocketEntityAccessor; -import org.spongepowered.common.item.SpongeFireworkEffectBuilder; import org.spongepowered.common.item.SpongeItemStack; +import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; public final class FireworkUtil { - public static @Nullable FireworkEffect getStarEffect(final ItemStack item) { - Preconditions.checkArgument(item.getItem() == Items.FIREWORK_STAR, "Item is not a firework star!"); - final @Nullable CompoundTag tag = item.getTagElement(Constants.Entity.Firework.EXPLOSION); - if (tag == null) { - return null; - } - return FireworkUtil.fromCompound(tag); - } - - public static FireworkEffect fromCompound(final CompoundTag compound) { - final FireworkEffect.Builder builder = new SpongeFireworkEffectBuilder(); - if (compound.contains(Constants.Item.Fireworks.FLICKER)) { - builder.flicker(compound.getBoolean(Constants.Item.Fireworks.FLICKER)); - } - if (compound.contains(Constants.Item.Fireworks.TRAIL)) { - builder.trail(compound.getBoolean(Constants.Item.Fireworks.TRAIL)); - } - if (compound.contains(Constants.Item.Fireworks.SHAPE_TYPE)) { - final byte type = compound.getByte(Constants.Item.Fireworks.SHAPE_TYPE); - final MappedRegistry registry = (MappedRegistry) (Object) Sponge.game().registry(RegistryTypes.FIREWORK_SHAPE); - final @Nullable FireworkShape shape = registry.byId(type); - if (shape != null) { - builder.shape(shape); - } - } - if (compound.contains(Constants.Item.Fireworks.COLORS)) { - final List colors = Lists.newArrayList(); - final int[] colorsRaw = compound.getIntArray(Constants.Item.Fireworks.COLORS); - for (final int color : colorsRaw) { - colors.add(Color.ofRgb(color)); - } - builder.colors(colors); - } - if (compound.contains(Constants.Item.Fireworks.FADE_COLORS)) { - final List fades = Lists.newArrayList(); - final int[] fadesRaw = compound.getIntArray(Constants.Item.Fireworks.FADE_COLORS); - for (final int fade : fadesRaw) { - fades.add(Color.ofRgb(fade)); - } - builder.fades(fades); - } - - return builder.build(); - } - - public static CompoundTag toCompound(final FireworkEffect effect) { - final MappedRegistry registry = (MappedRegistry) (Object) Sponge.game().registry(RegistryTypes.FIREWORK_SHAPE); - - final CompoundTag tag = new CompoundTag(); - tag.putBoolean(Constants.Item.Fireworks.FLICKER, effect.flickers()); - tag.putBoolean(Constants.Item.Fireworks.TRAIL, effect.hasTrail()); - tag.putByte(Constants.Item.Fireworks.SHAPE_TYPE, (byte) registry.getId(effect.shape())); - final int[] colorsArray = effect.colors().stream() - .mapToInt(Color::rgb) - .toArray(); - tag.putIntArray(Constants.Item.Fireworks.COLORS, colorsArray); - final int[] fadeArray = effect.fadeColors().stream() - .mapToInt(Color::rgb) - .toArray(); - tag.putIntArray(Constants.Item.Fireworks.FADE_COLORS, fadeArray); - return tag; - } - public static boolean setFireworkEffects(final Object object, final List effects) { if (effects.isEmpty()) { return FireworkUtil.removeFireworkEffects(object); @@ -122,13 +51,11 @@ public static boolean setFireworkEffects(final Object object, final List mcEffects = effects.stream().map(FireworkExplosion.class::cast).toList(); + item.update(DataComponents.FIREWORKS, new Fireworks(1, Collections.emptyList()), p -> new Fireworks(p.flightDuration(), mcEffects)); return true; } return false; @@ -140,26 +67,20 @@ public static Optional> getFireworkEffects(final Object obj return Optional.empty(); } - final List effects; if (item.getItem() == Items.FIREWORK_ROCKET) { - final @Nullable CompoundTag fireworks = item.getTagElement(Constants.Item.Fireworks.FIREWORKS); - if (fireworks == null || !fireworks.contains(Constants.Item.Fireworks.EXPLOSIONS)) { + final Fireworks fireworks = item.get(DataComponents.FIREWORKS); + if (fireworks == null || fireworks.explosions().isEmpty()) { return Optional.empty(); } - - final ListTag effectCompounds = fireworks.getList(Constants.Item.Fireworks.EXPLOSIONS, Constants.NBT.TAG_COMPOUND); - effects = NBTStreams.toCompounds(effectCompounds) - .map(FireworkUtil::fromCompound) - .collect(Collectors.toList()); - } else { - final @Nullable FireworkEffect effect = FireworkUtil.getStarEffect(item); - if (effect == null) { - return Optional.empty(); - } - effects = ImmutableList.of(effect); + return Optional.of(fireworks.explosions().stream().map(FireworkEffect.class::cast).toList()); } - return Optional.of(effects); + Preconditions.checkArgument(item.getItem() == Items.FIREWORK_STAR, "Item is not a firework star!"); + final FireworkExplosion fireworkExplosion = item.get(DataComponents.FIREWORK_EXPLOSION); + if (fireworkExplosion == null) { + return Optional.empty(); + } + return Optional.of(List.of((FireworkEffect) (Object) fireworkExplosion)); } public static boolean removeFireworkEffects(final Object object) { @@ -169,15 +90,14 @@ public static boolean removeFireworkEffects(final Object object) { } if (item.getItem() == Items.FIREWORK_STAR) { - final @Nullable CompoundTag tag = item.getTag(); - if (tag == null) { - return true; - } - tag.remove(Constants.Entity.Firework.EXPLOSION); + item.remove(DataComponents.FIREWORK_EXPLOSION); return true; - } else if (item.getItem() == Items.FIREWORK_ROCKET) { - final CompoundTag fireworks = item.getOrCreateTagElement(Constants.Item.Fireworks.FIREWORKS); - fireworks.remove(Constants.Item.Fireworks.EXPLOSIONS); + } + if (item.getItem() == Items.FIREWORK_ROCKET) { + if (item.has(DataComponents.FIREWORKS)) { + // keep flight duration + item.update(DataComponents.FIREWORKS, null, p -> new Fireworks(p.flightDuration(), Collections.emptyList())); + } return true; } return false; diff --git a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/component/FireworkExplosionMixin_API.java similarity index 57% rename from src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/component/FireworkExplosionMixin_API.java index 75b2cd10031..b95d100eb7f 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeFireworkEffect.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/component/FireworkExplosionMixin_API.java @@ -22,9 +22,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.item; +package org.spongepowered.common.mixin.api.minecraft.world.item.component; -import com.google.common.collect.ImmutableList; +import it.unimi.dsi.fastutil.ints.IntList; +import net.minecraft.world.item.component.FireworkExplosion; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.persistence.DataContainer; @@ -33,73 +34,47 @@ import org.spongepowered.api.item.FireworkShape; import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.api.util.Color; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.util.Constants; import java.util.List; -import java.util.Objects; -import java.util.StringJoiner; -public class SpongeFireworkEffect implements FireworkEffect { +@Mixin(FireworkExplosion.class) +public abstract class FireworkExplosionMixin_API implements FireworkEffect { - private final boolean flicker; - private final boolean trails; - private final ImmutableList colors; - private final ImmutableList fades; - private final FireworkShape shape; - - SpongeFireworkEffect(final boolean flicker, final boolean trails, final Iterable colors, final Iterable fades, final FireworkShape shape) { - this.flicker = flicker; - this.trails = trails; - this.colors = ImmutableList.copyOf(colors); - this.fades = ImmutableList.copyOf(fades); - this.shape = shape; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || this.getClass() != o.getClass()) { - return false; - } - final SpongeFireworkEffect that = (SpongeFireworkEffect) o; - return this.flicker == that.flicker && - this.trails == that.trails && - Objects.equals(this.colors, that.colors) && - Objects.equals(this.fades, that.fades) && - Objects.equals(this.shape, that.shape); - } - - @Override - public int hashCode() { - - return Objects.hash(this.flicker, this.trails, this.colors, this.fades, this.shape); - } + // @formatter:off + @Shadow @Final private boolean hasTwinkle; + @Shadow @Final private boolean hasTrail; + @Shadow @Final private IntList colors; + @Shadow @Final private IntList fadeColors; + @Shadow @Final private FireworkExplosion.Shape shape; + // @formatter:on @Override public boolean flickers() { - return this.flicker; + return this.hasTwinkle; } @Override public boolean hasTrail() { - return this.trails; + return this.hasTrail; } @Override public List colors() { - return this.colors; + return this.colors.intStream().mapToObj(Color::ofRgb).toList(); } @Override public List fadeColors() { - return this.fades; + return this.fadeColors.intStream().mapToObj(Color::ofRgb).toList(); } @Override public FireworkShape shape() { - return this.shape; + return (FireworkShape) (Object) this.shape; } @Override @@ -115,19 +90,9 @@ public DataContainer toContainer() { .set(Queries.CONTENT_VERSION, this.contentVersion()) .set(Constants.Item.Fireworks.FIREWORK_SHAPE, resourceKey) .set(Constants.Item.Fireworks.FIREWORK_COLORS, this.colors) - .set(Constants.Item.Fireworks.FIREWORK_FADE_COLORS, this.fades) - .set(Constants.Item.Fireworks.FIREWORK_TRAILS, this.trails) - .set(Constants.Item.Fireworks.FIREWORK_FLICKERS, this.flicker); + .set(Constants.Item.Fireworks.FIREWORK_FADE_COLORS, this.fadeColors()) + .set(Constants.Item.Fireworks.FIREWORK_TRAILS, this.hasTrail) + .set(Constants.Item.Fireworks.FIREWORK_FLICKERS, this.hasTwinkle); } - @Override - public String toString() { - return new StringJoiner(", ", SpongeFireworkEffect.class.getSimpleName() + "[", "]") - .add("shape=" + this.shape) - .add("trails=" + this.trails) - .add("flickers=" + this.flicker) - .add("colors=" + this.colors) - .add("fades=" + this.fades) - .toString(); - } } diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index cceb906867c..4d3051391bc 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -295,6 +295,7 @@ "minecraft.world.item.RarityMixin_API", "minecraft.world.item.TiersMixin_API", "minecraft.world.item.alchemy.PotionMixin_API", + "minecraft.world.item.component.FireworkExplosionMixin_API", "minecraft.world.item.crafting.AbstractCookingRecipeMixin_API", "minecraft.world.item.crafting.CraftingRecipeMixin_API", "minecraft.world.item.crafting.CustomRecipeMixin_API", From ea51b4c065c92144ce8af1d1c4daf93564f35b8d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 20:45:55 +0100 Subject: [PATCH 053/230] fix DamageType codec --- .../event/cause/entity/damage/SpongeDamageTypeTemplate.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java index 6d79c823bb7..c976b1a6382 100644 --- a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java @@ -72,13 +72,13 @@ public DataContainer toContainer() { public static JsonElement encode(final DamageTypeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return DamageType.CODEC.encodeStart(ops, (DamageType) (Object) template.type()).getOrThrow(false, e -> { + return DamageType.DIRECT_CODEC.encodeStart(ops, (DamageType) (Object) template.type()).getOrThrow(false, e -> { }); } public static DamageType decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return DamageType.CODEC.parse(ops, json).getOrThrow(false, e -> { + return DamageType.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> { }); } From ed8e68f50666169e4a5aff4a1f80f9ee63336b02 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:22:16 +0100 Subject: [PATCH 054/230] fix itemstack recipe nbt --- .../common/item/recipe/SpongeRecipeRegistration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java index 978f9f6a78e..eefb08c0743 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java @@ -82,7 +82,7 @@ public static , C extends Container> RecipeSerializer> remainingItemsFunction, final Collection ingredients, final RecipeSerializer vanilla, final RecipeSerializer sponge) { - if (resultStack.hasTag() || resultFunction != null || remainingItemsFunction != null) { + if (!resultStack.getComponents().isEmpty() || resultFunction != null || remainingItemsFunction != null) { return sponge; } for (final Ingredient value : ingredients) { @@ -97,7 +97,7 @@ public static boolean isVanillaSerializer(final ItemStack final Function resultFunction, final Function> remainingItemsFunction, final Collection ingredients) { - if (resultStack.hasTag() || resultFunction != null || remainingItemsFunction != null) { + if (!resultStack.getComponents().isEmpty() || resultFunction != null || remainingItemsFunction != null) { return false; } for (final Ingredient value : ingredients) { From 71fbd4f0a707a95059b90c1efe27b13125b2aa4e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 22:51:05 +0100 Subject: [PATCH 055/230] fix custom recipe --- .../common/bridge/world/item/crafting/RecipeResultBridge.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/bridge/world/item/crafting/RecipeResultBridge.java b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/RecipeResultBridge.java index 2547b8363fd..612a09e6e60 100644 --- a/src/main/java/org/spongepowered/common/bridge/world/item/crafting/RecipeResultBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/world/item/crafting/RecipeResultBridge.java @@ -31,7 +31,7 @@ public interface RecipeResultBridge { ItemStack bridge$result(); default ItemStack bridge$spongeResult() { final ItemStack result = this.bridge$result(); - return result.hasTag() ? result : ItemStack.EMPTY; + return !result.getComponents().isEmpty() ? result : ItemStack.EMPTY; } } From 6cf4d254815e1ba280f0c1f6d70f0697d6ecc417 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:24:35 +0100 Subject: [PATCH 056/230] TODO fix special recipes --- .../custom/SpongeSpecialCraftingRecipeSerializer.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java index 3dca78a59ff..4cc47c9f7be 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java @@ -27,6 +27,8 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.crafting.CraftingBookCategory; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.RecipeSerializer; @@ -50,6 +52,11 @@ public Codec codec() { return this.codec; } + @Override + public StreamCodec streamCodec() { + throw new UnsupportedOperationException("custom serializer needs client side support"); + } + public T fromNetwork(FriendlyByteBuf $$0) { throw new UnsupportedOperationException("custom serializer needs client side support"); } From 2fb9b8debcd86b83d12e734006a3a36ab9d7ea23 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:53:43 +0100 Subject: [PATCH 057/230] fix smithing recipe --- .../item/recipe/smithing/SpongeSmithingRecipe.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java index 0889e82d668..5435a3e5c23 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java @@ -83,12 +83,12 @@ public ItemStack assemble(Container $$0, RegistryAccess $$1) { return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply($$0); } - if (this.getResultItem($$1).hasTag()) { - final ItemStack itemStack = this.getResultItem($$1).copy(); - CompoundTag compoundnbt = $$0.getItem(0).getTag(); - if (compoundnbt != null) { - final CompoundTag merged = itemStack.getTag().merge(compoundnbt.copy()); - itemStack.setTag(merged); + final ItemStack resultItem = this.getResultItem($$1); + if (!resultItem.getComponents().isEmpty()) { + final ItemStack itemStack = resultItem.copy(); + var patch = $$0.getItem(0).getComponentsPatch(); + if (!patch.isEmpty()) { + itemStack.applyComponents(patch); return itemStack; } } From 10a590b9c882b8a79bd70c4169de5fd2a52589a1 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:53:33 +0100 Subject: [PATCH 058/230] TODO start fixing ItemStack builder --- .../common/item/SpongeItemStack.java | 50 +++++++++---------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java index 494437feceb..7bbbfc46b6e 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java @@ -25,6 +25,9 @@ package org.spongepowered.common.item; +import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -69,7 +72,7 @@ public static final class BuilderImpl extends AbstractDataBuilder imp private ItemType type; private int quantity; private @Nullable LinkedHashMap, Object> keyValues; - private @Nullable CompoundTag compound; + private DataComponentMap components = DataComponentMap.EMPTY; public BuilderImpl() { super(ItemStack.class, 1); @@ -110,13 +113,8 @@ public ItemStack.Builder fromItemStack(final ItemStack itemStack) { // Assumes the item stack's values don't need to be validated this.type = itemStack.type(); this.quantity = itemStack.quantity(); - if ((Object) itemStack instanceof net.minecraft.world.item.ItemStack) { - final CompoundTag itemCompound = ((net.minecraft.world.item.ItemStack) (Object) itemStack).getTag(); - if (itemCompound != null && !itemCompound.isEmpty()) { - this.compound = itemCompound.copy(); - } else { - this.compound = null; - } + if ((Object) itemStack instanceof net.minecraft.world.item.ItemStack mcStack) { + components = DataComponentMap.builder().addAll(mcStack.getComponents()).build(); // this.itemDataSet.addAll(((CustomDataHolderBridge) itemStack).bridge$getCustomManipulators()); } else { @@ -131,18 +129,16 @@ public ItemStack.Builder attributeModifier(final AttributeType attributeType, fi Objects.requireNonNull(modifier, "AttributeModifier cannot be null"); Objects.requireNonNull(equipmentType, "EquipmentType cannot be null"); - // Create the compound if needed - if (this.compound == null) { - this.compound = new CompoundTag(); - } - - final CompoundTag compound = this.compound; + if (!this.components.has(DataComponents.ATTRIBUTE_MODIFIERS)) { - if (!compound.contains(Constants.ItemStack.ATTRIBUTE_MODIFIERS, Constants.NBT.TAG_LIST)) { - compound.put(Constants.ItemStack.ATTRIBUTE_MODIFIERS, new ListTag()); } - final ListTag attributeModifiers = compound.getList(Constants.ItemStack.ATTRIBUTE_MODIFIERS, Constants.NBT.TAG_COMPOUND); + // TODO this is not doing anything +// if (!compound.contains(Constants.ItemStack.ATTRIBUTE_MODIFIERS, Constants.NBT.TAG_LIST)) { +// compound.put(Constants.ItemStack.ATTRIBUTE_MODIFIERS, new ListTag()); +// } +// +// final ListTag attributeModifiers = compound.getList(Constants.ItemStack.ATTRIBUTE_MODIFIERS, Constants.NBT.TAG_COMPOUND); // The modifier will apply in any slot, equipable or not. Pass null for the slot // if (equipmentType.equals(EquipmentTypes.ANY.get()) || equipmentType.equals(EquipmentTypes.EQUIPPED.get())) { @@ -188,9 +184,9 @@ public ItemStack.Builder fromContainer(final DataView container) { compound.remove(Constants.Sponge.Data.V2.SPONGE_DATA); } if (!compound.isEmpty()) { - this.compound = compound; + this.components = compound; } else { - this.compound = null; + this.components = null; } } if (container.contains(Constants.Sponge.DATA_MANIPULATORS)) { @@ -215,7 +211,7 @@ public ItemStack.Builder fromSnapshot(final ItemStackSnapshot snapshot) { } if (snapshot instanceof SpongeItemStackSnapshot) { - this.compound = ((SpongeItemStackSnapshot) snapshot).getCompound().orElse(null); + this.components = ((SpongeItemStackSnapshot) snapshot).getCompound().orElse(null); } return this; @@ -233,8 +229,8 @@ public ItemStack.Builder fromBlockSnapshot(final BlockSnapshot blockSnapshot) { if (blockSnapshot instanceof SpongeBlockSnapshot) { final Optional compound = ((SpongeBlockSnapshot) blockSnapshot).getCompound(); if (compound.isPresent()) { - this.compound = new CompoundTag(); - this.compound.put(Constants.Item.BLOCK_ENTITY_TAG, compound.get()); + this.components = new CompoundTag(); + this.components.put(Constants.Item.BLOCK_ENTITY_TAG, compound.get()); } // todo probably needs more testing, but this'll do donkey... } else { // TODO handle through the API specifically handling the rest of the data stuff @@ -301,7 +297,7 @@ protected Optional buildContent(final DataView container) throws Inva public ItemStack.Builder reset() { this.type = null; this.quantity = 1; - this.compound = null; + this.components = null; return this; } @@ -316,8 +312,8 @@ public ItemStack build() throws IllegalStateException { } final ItemStack stack = (ItemStack) (Object) new net.minecraft.world.item.ItemStack((Item) this.type, this.quantity); - if (this.compound != null && !this.compound.isEmpty()) { - ((net.minecraft.world.item.ItemStack) (Object) stack).setTag(this.compound.copy()); + if (this.components != null && !this.components.isEmpty()) { + ((net.minecraft.world.item.ItemStack) (Object) stack).setTag(this.components.copy()); } // if (this.itemDataSet != null) { // this.itemDataSet.forEach(stack::offer); @@ -326,8 +322,8 @@ public ItemStack build() throws IllegalStateException { if (this.keyValues != null) { this.keyValues.forEach((key, value) -> stack.offer((Key) key, value)); } - if (this.compound != null && this.compound.contains(Constants.Forge.FORGE_CAPS, Constants.NBT.TAG_COMPOUND)) { - final CompoundTag compoundTag = this.compound.getCompound(Constants.Forge.FORGE_CAPS); + if (this.components != null && this.components.contains(Constants.Forge.FORGE_CAPS, Constants.NBT.TAG_COMPOUND)) { + final CompoundTag compoundTag = this.components.getCompound(Constants.Forge.FORGE_CAPS); if (compoundTag != null) { PlatformHooks.INSTANCE.getItemHooks().setCapabilitiesFromSpongeBuilder((net.minecraft.world.item.ItemStack) (Object) stack, compoundTag); } From f7d67c96b456c824b6f426819eddedd978f64768 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 22:49:39 +0100 Subject: [PATCH 059/230] fix trade offer builder --- .../merchant/SpongeTradeOfferBuilder.java | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/merchant/SpongeTradeOfferBuilder.java b/src/main/java/org/spongepowered/common/item/merchant/SpongeTradeOfferBuilder.java index fd8d25ef83a..d75913d6b22 100644 --- a/src/main/java/org/spongepowered/common/item/merchant/SpongeTradeOfferBuilder.java +++ b/src/main/java/org/spongepowered/common/item/merchant/SpongeTradeOfferBuilder.java @@ -25,9 +25,12 @@ package org.spongepowered.common.item.merchant; +import net.minecraft.core.component.DataComponentPredicate; +import net.minecraft.world.item.trading.ItemCost; import net.minecraft.world.item.trading.MerchantOffer; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +import org.jetbrains.annotations.NotNull; import org.spongepowered.api.data.persistence.AbstractDataBuilder; import org.spongepowered.api.data.persistence.DataBuilder; import org.spongepowered.api.data.persistence.DataView; @@ -124,16 +127,27 @@ public TradeOffer build() throws IllegalStateException { Preconditions.checkState(this.firstItem != null, "Trading item has not been set"); Preconditions.checkState(this.sellingItem != null, "Selling item has not been set"); Preconditions.checkState(this.useCount <= this.maxUses, String.format("Usage count cannot be greater than the max usage count (%d)", this.maxUses)); - final ItemStack first = this.firstItem.createStack(); - final ItemStack second = this.secondItem == null ? null : this.secondItem.createStack(); - final ItemStack selling = this.sellingItem.createStack(); - final MerchantOffer merchantOffer = new MerchantOffer(ItemStackUtil.toNative(first), ItemStackUtil.toNative(second), ItemStackUtil.toNative(selling), - this.useCount, this.maxUses, this.merchantExperienceGranted, (float) this.priceGrowthMultiplier); + final var first = ItemStackUtil.fromSnapshotToNative(this.firstItem); + final var second = ItemStackUtil.fromSnapshotToNative(this.secondItem); + final var selling = ItemStackUtil.fromSnapshotToNative(this.sellingItem); + + final MerchantOffer merchantOffer = new MerchantOffer(SpongeTradeOfferBuilder.itemCostOf(first), + Optional.ofNullable(second).map(SpongeTradeOfferBuilder::itemCostOf), + selling, + this.useCount, + this.maxUses, + this.merchantExperienceGranted, + (float) this.priceGrowthMultiplier); ((MerchantOfferAccessor) merchantOffer).accessor$rewardExp(this.allowsExperience); ((MerchantOfferAccessor) merchantOffer).accessor$demand(this.demandBonus); return (TradeOffer) merchantOffer; } + @NotNull + private static ItemCost itemCostOf(final net.minecraft.world.item.ItemStack stack) { + return new ItemCost(stack.getItemHolder(), stack.getCount(), DataComponentPredicate.allOf(stack.getComponents()), stack); + } + @Override public TradeOffer.Builder from(final TradeOffer offer) { Objects.requireNonNull(offer, "Trade offer cannot be null"); From 3ee4240106c0129d90bb344f44364887b5e5509b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 22:35:20 +0100 Subject: [PATCH 060/230] start fixing ItemStack Data --- .../SpongeItemStackSnapshotDataBuilder.java | 42 +---- .../spongepowered/common/hooks/ItemHooks.java | 5 - .../item/ItemStackDataComponentsUpdater.java | 47 ++++++ ...ckSnapshotDuplicateManipulatorUpdater.java | 5 +- .../common/item/SpongeItemStack.java | 152 +++++++++++------- .../common/item/SpongeItemStackSnapshot.java | 90 ++--------- .../spongepowered/common/util/Constants.java | 47 +++--- .../world/item/ItemStackMixin_API.java | 40 +---- .../mixin/core/world/item/ItemStackMixin.java | 42 +++-- 9 files changed, 218 insertions(+), 252 deletions(-) create mode 100644 src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java diff --git a/src/main/java/org/spongepowered/common/data/builder/item/SpongeItemStackSnapshotDataBuilder.java b/src/main/java/org/spongepowered/common/data/builder/item/SpongeItemStackSnapshotDataBuilder.java index 59468e04f24..d9bae61a122 100644 --- a/src/main/java/org/spongepowered/common/data/builder/item/SpongeItemStackSnapshotDataBuilder.java +++ b/src/main/java/org/spongepowered/common/data/builder/item/SpongeItemStackSnapshotDataBuilder.java @@ -24,61 +24,25 @@ */ package org.spongepowered.common.data.builder.item; -import com.google.common.collect.ImmutableList; -import net.minecraft.nbt.CompoundTag; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.data.DataManipulator; import org.spongepowered.api.data.persistence.AbstractDataBuilder; import org.spongepowered.api.data.persistence.DataBuilder; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.item.ItemTypes; +import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.common.data.persistence.NBTTranslator; import org.spongepowered.common.item.SpongeItemStack; -import org.spongepowered.common.item.SpongeItemStackSnapshot; import org.spongepowered.common.util.Constants; -import java.util.List; import java.util.Optional; public final class SpongeItemStackSnapshotDataBuilder extends AbstractDataBuilder implements DataBuilder { public SpongeItemStackSnapshotDataBuilder() { - super(ItemStackSnapshot.class, Constants.Sponge.ItemStackSnapshot.CURRENT_VERSION); + super(ItemStackSnapshot.class, Constants.ItemStack.Data.CURRENT_VERSION); } @Override protected Optional buildContent(DataView container) throws InvalidDataException { - if (container.contains(Constants.ItemStack.TYPE, Constants.ItemStack.COUNT)) { - final ItemType itemType = container.getRegistryValue(Constants.ItemStack.TYPE, RegistryTypes.ITEM_TYPE, Sponge.game()).get(); - if (itemType == ItemTypes.AIR.get()) { - return Optional.of(ItemStackSnapshot.empty()); - } - final int count = container.getInt(Constants.ItemStack.COUNT).get(); - - final @Nullable CompoundTag compound; - if (container.contains(Constants.Sponge.UNSAFE_NBT)) { - compound = NBTTranslator.INSTANCE.translate(container.getView(Constants.Sponge.UNSAFE_NBT).get()); - SpongeItemStack.BuilderImpl.fixEnchantmentData(itemType, compound); - } else { - compound = null; - } - - final ImmutableList manipulators; - if (container.contains(Constants.Sponge.DATA_MANIPULATORS)) { - final List views = container.getViewList(Constants.Sponge.DATA_MANIPULATORS).get(); - // TODO manipulators = DataUtil.deserializeImmutableManipulatorList(container.getViewList(Constants.Sponge.DATA_MANIPULATORS).get()); - manipulators = ImmutableList.of(); - } else { - manipulators = ImmutableList.of(); - } - - return Optional.of(new SpongeItemStackSnapshot(itemType, count, manipulators, compound)); - } - return Optional.empty(); + return SpongeItemStack.createItemStack(container).map(ItemStack::createSnapshot); } } diff --git a/src/main/java/org/spongepowered/common/hooks/ItemHooks.java b/src/main/java/org/spongepowered/common/hooks/ItemHooks.java index f008cf0e6b4..0c2c4c94d67 100644 --- a/src/main/java/org/spongepowered/common/hooks/ItemHooks.java +++ b/src/main/java/org/spongepowered/common/hooks/ItemHooks.java @@ -24,18 +24,13 @@ */ package org.spongepowered.common.hooks; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; -import org.spongepowered.api.data.persistence.DataContainer; public interface ItemHooks { - default void setCapabilitiesFromSpongeBuilder(final ItemStack stack, final CompoundTag compound) { } - default boolean canEnchantmentBeAppliedToItem(final Enchantment enchantment, final ItemStack stack) { return enchantment.canEnchant(stack); } - default void writeItemStackCapabilitiesToDataView(final DataContainer container, final ItemStack stack) { } } diff --git a/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java b/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java new file mode 100644 index 00000000000..6b9534eb88f --- /dev/null +++ b/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java @@ -0,0 +1,47 @@ +package org.spongepowered.common.item; + +import org.spongepowered.api.data.persistence.DataContainer; +import org.spongepowered.api.data.persistence.DataContentUpdater; +import org.spongepowered.api.data.persistence.DataView; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.registry.RegistryTypes; +import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.util.Constants; + +class ItemStackDataComponentsUpdater implements DataContentUpdater { + + public static final DataContentUpdater INSTANCE = new ItemStackDataComponentsUpdater(); + + @Override + public int inputVersion() { + return Constants.ItemStack.Data.DUPLICATE_MANIPULATOR_DATA_VERSION; + } + + @Override + public int outputVersion() { + return Constants.ItemStack.Data.DATA_COMPONENTS; + } + + @Override + public DataView update(final DataView content) { + final int count = content.getInt(Constants.ItemStack.V2.COUNT).get(); + final String type = content.getString(Constants.ItemStack.V2.TYPE).get(); + + final DataContainer updated = DataContainer.createNew(); + updated.set(Constants.ItemStack.TYPE, type); + updated.set(Constants.ItemStack.COUNT, count); + + final DataContainer components = DataContainer.createNew(); + content.getInt(Constants.ItemStack.V2.DAMAGE_VALUE).ifPresent(dmg -> components.set(Constants.ItemStack.DAMAGE, dmg)); + content.getView(Constants.Sponge.UNSAFE_NBT).ifPresent(unsafe -> { + // TODO unsafe contains the entire old nbt tag + // TODO update plugin/sponge data + // TODO apply ItemStackComponentizationFix for vanilla data + components.set(Constants.ItemStack.CUSTOM_DATA, unsafe); + }); + + updated.set(Constants.ItemStack.COMPONENTS, components); + + return updated; + } +} diff --git a/src/main/java/org/spongepowered/common/item/ItemStackSnapshotDuplicateManipulatorUpdater.java b/src/main/java/org/spongepowered/common/item/ItemStackSnapshotDuplicateManipulatorUpdater.java index e30116eb15f..b9e54ff7435 100644 --- a/src/main/java/org/spongepowered/common/item/ItemStackSnapshotDuplicateManipulatorUpdater.java +++ b/src/main/java/org/spongepowered/common/item/ItemStackSnapshotDuplicateManipulatorUpdater.java @@ -33,14 +33,15 @@ public final class ItemStackSnapshotDuplicateManipulatorUpdater implements DataContentUpdater { + public static final DataContentUpdater INSTANCE = new ItemStackSnapshotDuplicateManipulatorUpdater(); @Override public int inputVersion() { - return Constants.Sponge.ItemStackSnapshot.DUPLICATE_MANIPULATOR_DATA_VERSION; + return Constants.ItemStack.Data.DUPLICATE_MANIPULATOR_DATA_VERSION; } @Override public int outputVersion() { - return Constants.Sponge.ItemStackSnapshot.REMOVED_DUPLICATE_DATA; + return Constants.ItemStack.Data.REMOVED_DUPLICATE_DATA; } @Override diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java index 7bbbfc46b6e..786ad2e458b 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java @@ -25,27 +25,41 @@ package org.spongepowered.common.item; +import com.google.common.collect.ImmutableList; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.component.TypedDataComponent; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.JavaOps; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.block.Block; import org.checkerframework.checker.nullness.qual.Nullable; +import org.jetbrains.annotations.NotNull; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.persistence.AbstractDataBuilder; +import org.spongepowered.api.data.persistence.DataContainer; +import org.spongepowered.api.data.persistence.DataContentUpdater; +import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; +import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.entity.attribute.AttributeModifier; import org.spongepowered.api.entity.attribute.type.AttributeType; @@ -56,8 +70,8 @@ import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.block.SpongeBlockSnapshot; +import org.spongepowered.common.data.DataUpdaterDelegate; import org.spongepowered.common.data.persistence.NBTTranslator; -import org.spongepowered.common.hooks.PlatformHooks; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.Preconditions; @@ -167,15 +181,15 @@ private void writeAttributeModifier(final ListTag attributeModifiers, final net. @Override public ItemStack.Builder fromContainer(final DataView container) { Objects.requireNonNull(container); - if (!container.contains(Constants.ItemStack.TYPE, Constants.ItemStack.COUNT)) { + if (!container.contains(Constants.ItemStack.V2.TYPE, Constants.ItemStack.V2.COUNT)) { return this; } this.reset(); - final int count = container.getInt(Constants.ItemStack.COUNT).get(); + final int count = container.getInt(Constants.ItemStack.V2.COUNT).get(); this.quantity(count); - final ItemType itemType = container.getRegistryValue(Constants.ItemStack.TYPE, RegistryTypes.ITEM_TYPE, SpongeCommon.game()).get(); + final ItemType itemType = container.getRegistryValue(Constants.ItemStack.V2.TYPE, RegistryTypes.ITEM_TYPE, SpongeCommon.game()).get(); this.itemType(itemType); if (container.contains(Constants.Sponge.UNSAFE_NBT)) { @@ -184,9 +198,10 @@ public ItemStack.Builder fromContainer(final DataView container) { compound.remove(Constants.Sponge.Data.V2.SPONGE_DATA); } if (!compound.isEmpty()) { - this.components = compound; + this.components = net.minecraft.world.item.ItemStack.parse(SpongeCommon.server().registryAccess(), compound).map( + net.minecraft.world.item.ItemStack::getComponents).orElse(DataComponentMap.EMPTY); } else { - this.components = null; + this.components = DataComponentMap.EMPTY; } } if (container.contains(Constants.Sponge.DATA_MANIPULATORS)) { @@ -211,7 +226,8 @@ public ItemStack.Builder fromSnapshot(final ItemStackSnapshot snapshot) { } if (snapshot instanceof SpongeItemStackSnapshot) { - this.components = ((SpongeItemStackSnapshot) snapshot).getCompound().orElse(null); + + this.components = ((SpongeItemStackSnapshot) snapshot).getComponents(); } return this; @@ -227,11 +243,8 @@ public ItemStack.Builder fromBlockSnapshot(final BlockSnapshot blockSnapshot) { this.itemType(itemType.orElseThrow(() -> new IllegalArgumentException("ItemType not found for block type: " + blockTypeKey))); this.quantity(1); if (blockSnapshot instanceof SpongeBlockSnapshot) { - final Optional compound = ((SpongeBlockSnapshot) blockSnapshot).getCompound(); - if (compound.isPresent()) { - this.components = new CompoundTag(); - this.components.put(Constants.Item.BLOCK_ENTITY_TAG, compound.get()); - } + ((SpongeBlockSnapshot) blockSnapshot).getCompound().ifPresent(compoundTag -> + this.components = DataComponentMap.builder().set(DataComponents.BLOCK_ENTITY_DATA, CustomData.of(compoundTag)).build()); // todo probably needs more testing, but this'll do donkey... } else { // TODO handle through the API specifically handling the rest of the data stuff // blockSnapshot.getContainers().forEach(this::itemData); @@ -263,34 +276,7 @@ public ItemStack.Builder from(final ItemStack value) { @Override protected Optional buildContent(final DataView container) throws InvalidDataException { - Objects.requireNonNull(container); - if (!container.contains(Constants.ItemStack.TYPE, Constants.ItemStack.COUNT)) { - return Optional.empty(); - } - final int count = container.getInt(Constants.ItemStack.COUNT).get(); - final ItemType itemType = - container.getRegistryValue(Constants.ItemStack.TYPE, RegistryTypes.ITEM_TYPE, SpongeCommon.game()).orElseThrow(() -> new IllegalStateException( - "Unable to find item with id: ")); - final net.minecraft.world.item.ItemStack itemStack = new net.minecraft.world.item.ItemStack((Item) itemType, count); - if (container.contains(Constants.Sponge.UNSAFE_NBT)) { - final CompoundTag compound = NBTTranslator.INSTANCE.translate(container.getView(Constants.Sponge.UNSAFE_NBT).get()); - if (!compound.isEmpty()) { - BuilderImpl.fixEnchantmentData(itemType, compound); - itemStack.setTag(compound); - } - } - if (container.contains(Constants.Sponge.DATA_MANIPULATORS)) { - final List views = container.getViewList(Constants.Sponge.DATA_MANIPULATORS).get(); - // final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(views); - // final List> manipulators = transaction.deserializedManipulators; - // for (final Mutable manipulator : manipulators) { - // ((CustomDataHolderBridge) itemStack).bridge$offerCustom(manipulator, MergeFunction.IGNORE_ALL); - // } - // if (!transaction.failedData.isEmpty()) { - // ((CustomDataHolderBridge) itemStack).bridge$addFailedData(transaction.failedData); - // } - } - return Optional.of((ItemStack) (Object) itemStack); + return SpongeItemStack.createItemStack(container); } @Override @@ -311,24 +297,13 @@ public ItemStack build() throws IllegalStateException { return ((ItemStack) (Object) net.minecraft.world.item.ItemStack.EMPTY); } - final ItemStack stack = (ItemStack) (Object) new net.minecraft.world.item.ItemStack((Item) this.type, this.quantity); - if (this.components != null && !this.components.isEmpty()) { - ((net.minecraft.world.item.ItemStack) (Object) stack).setTag(this.components.copy()); - } - // if (this.itemDataSet != null) { - // this.itemDataSet.forEach(stack::offer); - // } + final net.minecraft.world.item.ItemStack mcStack = new net.minecraft.world.item.ItemStack((Item) this.type, this.quantity); + mcStack.applyComponents(this.components); + final ItemStack stack = (ItemStack) (Object) mcStack; if (this.keyValues != null) { this.keyValues.forEach((key, value) -> stack.offer((Key) key, value)); } - if (this.components != null && this.components.contains(Constants.Forge.FORGE_CAPS, Constants.NBT.TAG_COMPOUND)) { - final CompoundTag compoundTag = this.components.getCompound(Constants.Forge.FORGE_CAPS); - if (compoundTag != null) { - PlatformHooks.INSTANCE.getItemHooks().setCapabilitiesFromSpongeBuilder((net.minecraft.world.item.ItemStack) (Object) stack, compoundTag); - } - } - return stack; } @@ -363,4 +338,73 @@ public ItemStack empty() { return (ItemStack) (Object) net.minecraft.world.item.ItemStack.EMPTY; } } + + private static void fillComponents(DataContainer container, TypedDataComponent component) { + final ResourceLocation componentTypeKey = BuiltInRegistries.DATA_COMPONENT_TYPE.getKey(component.type()); + final DataResult value = component.type().codec().encodeStart(JavaOps.INSTANCE, component.value()); + container.set(DataQuery.of(':', componentTypeKey.toString()), value.result().orElse(null)); + + } + @NotNull + public static DataContainer getDataContainer(final net.minecraft.world.item.ItemStack mcStack) { + final ResourceLocation key = BuiltInRegistries.ITEM.getKey(mcStack.getItem()); + final DataContainer container = DataContainer.createNew() + .set(Queries.CONTENT_VERSION, ((ItemStack) (Object) mcStack).contentVersion()) + .set(Constants.ItemStack.TYPE, key) + .set(Constants.ItemStack.COUNT, mcStack.getCount()); + // Cleanup Old Custom Data + SpongeItemStack.cleanupOldCustomData(mcStack); + // Serialize all DataComponents... + DataContainer components = DataContainer.createNew(); + mcStack.getComponents().forEach(tdc -> SpongeItemStack.fillComponents(components, tdc)); + container.set(Constants.ItemStack.COMPONENTS, components); + // TODO handle Sponge/Plugin Data, register our own DataComponentTypes? + return container; + } + + private static void cleanupOldCustomData(final net.minecraft.world.item.ItemStack stack) { + final CompoundTag unsafe = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).getUnsafe(); + unsafe.remove(Constants.Sponge.Data.V2.SPONGE_DATA); // and its V2.CUSTOM_MANIPULATOR_TAG_LIST + Constants.NBT.filterSpongeCustomData(unsafe); // FORGE_DATA > V2.SPONGE_DATA also removes it if empty + } + + // TODO updater for old (maybe V2?) Constants.Sponge.DATA_MANIPULATORS + public static final ImmutableList STACK_UPDATERS = ImmutableList.of( + ItemStackSnapshotDuplicateManipulatorUpdater.INSTANCE, + ItemStackDataComponentsUpdater.INSTANCE); + + @NotNull + public static Optional createItemStack(final DataView container) { + Objects.requireNonNull(container); + + final Integer version = container.getInt(Queries.CONTENT_VERSION).orElse(1); + final DataUpdaterDelegate delegate = new DataUpdaterDelegate(STACK_UPDATERS, version, Constants.ItemStack.Data.CURRENT_VERSION); + final DataView updatedContainer = delegate.update(container); + + if (!updatedContainer.contains(Constants.ItemStack.TYPE, Constants.ItemStack.COUNT)) { + return Optional.empty(); + } + + final int count = updatedContainer.getInt(Constants.ItemStack.COUNT).get(); + + final ItemType itemType = updatedContainer.getRegistryValue(Constants.ItemStack.TYPE, RegistryTypes.ITEM_TYPE) + .orElseThrow(() -> new IllegalStateException("Unable to find item with id: ")); + final var mcStack = new net.minecraft.world.item.ItemStack((Item) itemType, count); + if (!mcStack.isEmpty()) { // ignore components when the stack is empty anyways + // TODO v3 Data + container.getView(Constants.ItemStack.COMPONENTS).ifPresent(components -> { + final CompoundTag compound = NBTTranslator.INSTANCE.translate(components); + // TODO check if enchantment-data is still broken + // BuilderImpl.fixEnchantmentData(itemType, compound); + + final DataResult> decoded = DataComponentPatch.CODEC.decode(NbtOps.INSTANCE, compound); + // TODO handle errors? e.g. missing custom DataComponentType + decoded.result().map(Pair::getFirst).ifPresent(mcStack::applyComponents); + }); + } + return Optional.of((ItemStack) (Object) mcStack); + } + + + } diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java b/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java index 580bf2f9309..c3fc52a7006 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java @@ -28,8 +28,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import net.kyori.adventure.text.event.HoverEvent; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.item.Item; +import net.minecraft.core.component.DataComponentMap; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; @@ -39,16 +38,13 @@ import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; -import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.data.value.MergeFunction; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.data.SpongeDataHolderBridge; -import org.spongepowered.common.data.persistence.NBTTranslator; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.util.Constants; @@ -73,7 +69,7 @@ public class SpongeItemStackSnapshot implements ItemStackSnapshot { private final transient ItemStack privateStack; // only for internal use since the processors have a huge say private final ImmutableSet> keys; private final ImmutableSet> values; - private final @Nullable CompoundTag compound; + private final DataComponentMap components; private @Nullable UUID creatorUniqueId; @SuppressWarnings({"EqualsBetweenInconvertibleTypes", "ConstantConditions"}) @@ -87,7 +83,7 @@ public SpongeItemStackSnapshot(final ItemStack itemStack) { this.privateStack = itemStack; this.keys = ImmutableSet.of(); this.values = ImmutableSet.of(); - this.compound = null; + this.components = DataComponentMap.EMPTY; return; } this.itemType = itemStack.type(); @@ -105,47 +101,7 @@ public SpongeItemStackSnapshot(final ItemStack itemStack) { this.keys = keyBuilder.build(); this.values = valueBuilder.build(); - @Nullable CompoundTag compound = ItemStackUtil.toNative(this.privateStack).getTag(); - if (compound != null) { - compound = compound.copy(); - } - if (compound != null) { - if (compound.contains(Constants.Sponge.Data.V2.SPONGE_DATA)) { - final CompoundTag spongeCompound = compound.getCompound(Constants.Sponge.Data.V2.SPONGE_DATA); - if (spongeCompound.contains(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_TAG_LIST)) { - spongeCompound.remove(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_TAG_LIST); - } - } - Constants.NBT.filterSpongeCustomData(compound); - if (!compound.isEmpty()) { - this.compound = compound; - } else { - this.compound = null; - } - } else { - this.compound = null; - } - } - - public SpongeItemStackSnapshot(final ItemType itemType, - final int quantity, - final ImmutableList manipulators, - final @Nullable CompoundTag compound) { - this.itemType = java.util.Objects.requireNonNull(itemType); - this.quantity = quantity; - this.manipulators = java.util.Objects.requireNonNull(manipulators); - this.privateStack = ItemStackUtil.fromNative(new net.minecraft.world.item.ItemStack((Item) this.itemType, this.quantity)); - final ImmutableSet.Builder> keyBuilder = ImmutableSet.builder(); - final ImmutableSet.Builder> valueBuilder = ImmutableSet.builder(); - for (final DataManipulator.Immutable manipulator : this.manipulators) { - this.privateStack.copyFrom(manipulator); - keyBuilder.addAll(manipulator.getKeys()); - valueBuilder.addAll(manipulator.getValues()); - } - this.keys = keyBuilder.build(); - this.values = valueBuilder.build(); - this.compound = compound == null ? null : compound.copy(); - this.damageValue = 0; + this.components = DataComponentMap.builder().addAll(ItemStackUtil.toNative(this.privateStack).getComponents()).build(); // copy } @Override @@ -170,8 +126,8 @@ public boolean isNone() { @Override public ItemStack createStack() { final net.minecraft.world.item.ItemStack nativeStack = ItemStackUtil.cloneDefensiveNative(ItemStackUtil.toNative(this.privateStack.copy())); - if(this.compound != null) { - nativeStack.setTag(this.compound.copy()); + if(this.components != null) { + nativeStack.applyComponents(this.components); } for (final DataManipulator.Immutable manipulator : this.manipulators) { ((ItemStack) (Object) nativeStack).copyFrom(manipulator); @@ -181,24 +137,12 @@ public ItemStack createStack() { @Override public int contentVersion() { - return Constants.Sponge.ItemStackSnapshot.CURRENT_VERSION; + return Constants.ItemStack.Data.CURRENT_VERSION; } @Override public DataContainer toContainer() { - final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.ITEM_TYPE).valueKey(this.itemType); - final DataContainer container = DataContainer.createNew() - .set(Queries.CONTENT_VERSION, this.contentVersion()) - .set(Constants.ItemStack.TYPE, resourceKey) - .set(Constants.ItemStack.COUNT, this.quantity) - .set(Constants.ItemStack.DAMAGE_VALUE, this.damageValue); - if (!this.manipulators.isEmpty()) { -// TODO container.set(Constants.Sponge.DATA_MANIPULATORS, DataUtil.getSerializedImmutableManipulatorList(this.manipulators)); - } - if (this.compound != null) { - container.set(Constants.Sponge.UNSAFE_NBT, NBTTranslator.INSTANCE.translateFrom(this.compound)); - } - return container; + return SpongeItemStack.getDataContainer((net.minecraft.world.item.ItemStack) (Object) this.createStack()); } @Override @@ -271,14 +215,10 @@ public int getDamageValue() { return this.damageValue; } - public Optional getCompound() { - if (this.compound != null) { - return Optional.of(this.compound.copy()); - } - return Optional.empty(); + public DataComponentMap getComponents() { + return this.components; } - public Optional getCreator() { return Optional.ofNullable(this.creatorUniqueId); } @@ -331,19 +271,21 @@ public boolean equals(final Object o) { return this.quantity == that.quantity && this.damageValue == that.damageValue && Objects.equals(this.itemType, that.itemType) && - Objects.equals(this.compound, that.compound) && + Objects.equals(this.components, that.components) && Objects.equals(this.creatorUniqueId, that.creatorUniqueId); } @Override public int hashCode() { - return Objects.hash(this.itemType, this.quantity, this.damageValue, this.compound, this.creatorUniqueId); + return Objects.hash(this.itemType, this.quantity, this.damageValue, this.components, this.creatorUniqueId); } @Override public HoverEvent asHoverEvent(final UnaryOperator op) { final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.ITEM_TYPE).valueKey(this.itemType); - final CompoundTag tag = this.getCompound().orElse(null); - return HoverEvent.showItem(op.apply(HoverEvent.ShowItem.of(resourceKey, this.quantity(), SpongeAdventure.asBinaryTagHolder(tag)))); + // TODO requires adventure change +// final CompoundTag tag = this.getComponents().orElse(null); +// return HoverEvent.showItem(op.apply(HoverEvent.ShowItem.of(resourceKey, this.quantity(), SpongeAdventure.asBinaryTagHolder(tag)))); + return null; } } diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index 8891ad9ca02..dcd858aa409 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -29,14 +29,12 @@ import com.google.common.collect.BiMap; import com.google.common.collect.ComparisonChain; import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; +import jdk.jfr.Percentage; import net.minecraft.commands.arguments.CompoundTagArgument; import net.minecraft.commands.arguments.ResourceLocationArgument; import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.FloatTag; @@ -73,20 +71,14 @@ import org.spongepowered.api.data.type.StructureModes; import org.spongepowered.api.entity.living.player.gamemode.GameMode; import org.spongepowered.api.entity.living.player.gamemode.GameModes; -import org.spongepowered.api.item.enchantment.Enchantment; -import org.spongepowered.api.item.enchantment.EnchantmentType; import org.spongepowered.api.util.Axis; import org.spongepowered.api.util.Direction; -import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.item.enchantment.SpongeEnchantment; import org.spongepowered.math.vector.Vector3i; import java.net.InetSocketAddress; import java.time.Duration; -import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; -import java.util.List; import java.util.Objects; import java.util.function.Supplier; @@ -389,13 +381,6 @@ public static final class Potion { public static final int CURRENT_VERSION = Potion.POTION_V2; } - public static final class ItemStackSnapshot { - - public static final int DUPLICATE_MANIPULATOR_DATA_VERSION = 1; - public static final int REMOVED_DUPLICATE_DATA = 2; - public static final int CURRENT_VERSION = ItemStackSnapshot.REMOVED_DUPLICATE_DATA; - } - public static final class BlockState { public static final int BLOCK_TYPE_WITH_DAMAGE_VALUE = 1; @@ -1193,13 +1178,29 @@ public static final class Fluids { public static final class ItemStack { - // ItemStacks - public static final DataQuery COUNT = of("Count"); - public static final DataQuery TYPE = of("ItemType"); - public static final DataQuery DAMAGE_VALUE = of("UnsafeDamage"); - public static final String ATTRIBUTE_MODIFIERS = "AttributeModifiers"; - public static final String ATTRIBUTE_NAME = "AttributeName"; - public static final String ATTRIBUTE_SLOT = "Slot"; + public static final DataQuery COUNT = of("count"); + public static final DataQuery TYPE = of("id"); + public static final DataQuery COMPONENTS = of("components"); + public static final DataQuery CUSTOM_DATA = of("minecraft:custom_data"); + public static final DataQuery DAMAGE = of("minecraft:damage"); + + @Deprecated + public static final class V2 { + + public static final DataQuery DAMAGE_VALUE = of("UnsafeDamage"); + // ItemStacks + public static final DataQuery COUNT = of("Count"); + public static final DataQuery TYPE = of("ItemType"); + } + + // Previously only ItemStackSnapshot + public static final class Data { + + public static final int DUPLICATE_MANIPULATOR_DATA_VERSION = 1; + public static final int REMOVED_DUPLICATE_DATA = 2; + public static final int DATA_COMPONENTS = 3; + public static final int CURRENT_VERSION = Data.DATA_COMPONENTS; + } } public static final class Map { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java index 0a012786253..d4cd0b6dc2a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java @@ -26,24 +26,25 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; +import com.mojang.serialization.DataResult; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEventSource; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtOps; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.item.Item; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; -import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.SerializableDataHolder; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; -import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.entity.attribute.AttributeModifier; import org.spongepowered.api.entity.attribute.type.AttributeType; import org.spongepowered.api.item.ItemType; @@ -60,7 +61,7 @@ import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.data.persistence.NBTTranslator; -import org.spongepowered.common.hooks.PlatformHooks; +import org.spongepowered.common.item.SpongeItemStack; import org.spongepowered.common.item.SpongeItemStackSnapshot; import org.spongepowered.common.util.Constants; @@ -78,12 +79,9 @@ public abstract class ItemStackMixin_API implements SerializableDataHolder.Mutab @Shadow public abstract int shadow$getCount(); @Shadow public abstract void shadow$setCount(int size); // Do not use field directly as Minecraft tracks the empty state @Shadow public abstract void shadow$setDamageValue(int meta); - @Shadow public abstract void shadow$setTag(@Nullable CompoundTag compound); @Shadow public abstract int shadow$getDamageValue(); @Shadow public abstract int shadow$getMaxStackSize(); - @Shadow public abstract boolean shadow$hasTag(); @Shadow public abstract boolean shadow$isEmpty(); - @Shadow public abstract CompoundTag shadow$getTag(); @Shadow public abstract net.minecraft.world.item.ItemStack shadow$copy(); @Shadow public abstract Item shadow$getItem(); @Shadow public abstract Multimap shadow$getAttributeModifiers(EquipmentSlot equipmentSlot); @@ -126,9 +124,10 @@ public void setRawData(final DataView container) throws InvalidDataException { } final DataView nbtData = container.getView(Constants.Sponge.UNSAFE_NBT).get(); try { - final int integer = container.getInt(Constants.ItemStack.DAMAGE_VALUE).orElse(this.shadow$getDamageValue()); + final int integer = container.getInt(Constants.ItemStack.V2.DAMAGE_VALUE).orElse(this.shadow$getDamageValue()); this.shadow$setDamageValue(integer); final CompoundTag stackCompound = NBTTranslator.INSTANCE.translate(nbtData); + final DataResult parse = DataComponentPatch.CODEC.parse(NbtOps.INSTANCE, stackCompound); this.shadow$setTag(stackCompound); } catch (final Exception e) { throw new InvalidDataException("Unable to set raw data or translate raw data for ItemStack setting", e); @@ -171,32 +170,7 @@ public int contentVersion() { @Override public DataContainer toContainer() { - final ResourceKey key = (ResourceKey) (Object) SpongeCommon.vanillaRegistry(Registries.ITEM).getKey((Item) this.itemStack$type()); - final DataContainer container = DataContainer.createNew() - .set(Queries.CONTENT_VERSION, this.contentVersion()) - .set(Constants.ItemStack.TYPE, key) - .set(Constants.ItemStack.COUNT, this.itemStack$quantity()) - .set(Constants.ItemStack.DAMAGE_VALUE, this.shadow$getDamageValue()); - if (this.shadow$hasTag()) { // no tag? no data, simple as that. - final CompoundTag compound = this.shadow$getTag().copy(); - if (compound.contains(Constants.Sponge.Data.V2.SPONGE_DATA)) { - final CompoundTag spongeCompound = compound.getCompound(Constants.Sponge.Data.V2.SPONGE_DATA); - if (spongeCompound.contains(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_TAG_LIST)) { - spongeCompound.remove(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_TAG_LIST); - } - } - Constants.NBT.filterSpongeCustomData(compound); // We must filter the custom data so it isn't stored twice - if (!compound.isEmpty()) { - final DataContainer unsafeNbt = NBTTranslator.INSTANCE.translateFrom(compound); - container.set(Constants.Sponge.UNSAFE_NBT, unsafeNbt); - } - } - try { - PlatformHooks.INSTANCE.getItemHooks().writeItemStackCapabilitiesToDataView(container, (net.minecraft.world.item.ItemStack) (Object) this); - } catch (final Exception e) { - ItemStackMixin_API.LOGGER.error("Failed to write capabilities to data view", e); - } - return container; + return SpongeItemStack.getDataContainer((net.minecraft.world.item.ItemStack) (Object) this); } public ItemStackSnapshot itemStack$createSnapshot() { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java index 731c4ae14d5..d6099107145 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java @@ -24,13 +24,18 @@ */ package org.spongepowered.common.mixin.core.world.item; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.component.PatchedDataComponentMap; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; +import net.minecraft.world.level.ItemLike; import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -50,17 +55,16 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataCompoundHolder { // @formatter:off - @Shadow private CompoundTag tag; + @Shadow public abstract boolean shadow$isEmpty(); + @Shadow @Final private PatchedDataComponentMap components; - @Shadow public abstract void shadow$setTag(@Nullable CompoundTag nbt); - @Shadow @Nullable public abstract CompoundTag shadow$getTag(); // @formatter:on - @Shadow public abstract boolean isEmpty(); + @Override public Optional bridge$get(final Key<@NonNull ? extends Value> key) { - if (this.isEmpty()) { + if (this.shadow$isEmpty()) { return Optional.empty(); } return DataHolderProcessor.bridge$get(this, key); @@ -68,7 +72,7 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp @Override public DataTransactionResult bridge$offer(final Key<@NonNull ? extends Value> key, final E value) { - if (this.isEmpty()) { + if (this.shadow$isEmpty()) { return DataTransactionResult.failNoData(); } return DataHolderProcessor.bridge$offer(this, key, value); @@ -76,7 +80,7 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp @Override public DataTransactionResult bridge$remove(final Key<@NonNull ? extends Value> key) { - if (this.isEmpty()) { + if (this.shadow$isEmpty()) { return DataTransactionResult.failNoData(); } return DataHolderProcessor.bridge$remove(this, key); @@ -84,12 +88,12 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp @Override public CompoundTag data$getCompound() { - return this.shadow$getTag(); + return this.components.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).getUnsafe(); } @Override public void data$setCompound(final CompoundTag nbt) { - this.shadow$setTag(nbt); + this.components.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt)); } // Add our manipulators when creating copies from this ItemStack: @@ -106,24 +110,18 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp } // Read custom data from nbt - @Inject(method = "(Lnet/minecraft/nbt/CompoundTag;)V", at = @At("RETURN")) - private void impl$onRead(final CompoundTag compound, final CallbackInfo info) { - if (!this.isEmpty()) { + @Inject(method = "(Lnet/minecraft/world/level/ItemLike;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", at = @At("RETURN")) + private void impl$onRead(final ItemLike $$0, final int $$1, final PatchedDataComponentMap $$2, final CallbackInfo ci) { + if (!this.shadow$isEmpty()) { DataUtil.syncTagToData(this); // Deserialize DataUtil.syncDataToTag(this); // Sync back after reading } - // Prune empty stack tag compound if its empty to enable stacking. - if (this.tag != null && this.tag.isEmpty()) { - this.tag = null; - } } - @Inject(method = "setTag", at = @At("RETURN")) - private void impl$onSet(final CompoundTag compound, final CallbackInfo callbackInfo) { - if (this.shadow$getTag() != compound) { + @Inject(method = "set", at = @At("RETURN")) + private void impl$onSetCustomData(final DataComponentType $$0, final T $$1, final CallbackInfoReturnable cir) { + if ($$0.equals(DataComponents.CUSTOM_DATA)) { this.bridge$clear(); - } - if (compound != null && !compound.isEmpty()) { DataUtil.syncTagToData(this); // Deserialize DataUtil.syncDataToTag(this); // Sync back after reading } From 439c0b1ad21812671573b2990ec2f610c407a7e5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 22:50:31 +0100 Subject: [PATCH 061/230] fix easy DataParameterConverter --- .../common/data/datasync/DataParameterConverter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/data/datasync/DataParameterConverter.java b/src/main/java/org/spongepowered/common/data/datasync/DataParameterConverter.java index d2566b8746a..97dc8ac9392 100644 --- a/src/main/java/org/spongepowered/common/data/datasync/DataParameterConverter.java +++ b/src/main/java/org/spongepowered/common/data/datasync/DataParameterConverter.java @@ -41,7 +41,7 @@ public abstract class DataParameterConverter { @SuppressWarnings("unchecked") public DataParameterConverter(final EntityDataAccessor parameter) { this.parameter = parameter; - ((EntityDataAccessorBridge) parameter).bridge$setDataConverter(this); + ((EntityDataAccessorBridge) (Object) parameter).bridge$setDataConverter(this); } public EntityDataAccessor getParameter() { From 00f608760da6eae2884fa18f536661260376f5ec Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:12:16 +0100 Subject: [PATCH 062/230] fix user data --- .../common/entity/player/SpongeUserData.java | 4 +- .../entity/player/SpongeUserInventory.java | 9 ++-- .../common/user/SpongeUserManager.java | 42 +++++++++++-------- 3 files changed, 31 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/spongepowered/common/entity/player/SpongeUserData.java b/src/main/java/org/spongepowered/common/entity/player/SpongeUserData.java index 55a3815c87a..c006fdd3369 100644 --- a/src/main/java/org/spongepowered/common/entity/player/SpongeUserData.java +++ b/src/main/java/org/spongepowered/common/entity/player/SpongeUserData.java @@ -209,7 +209,7 @@ private SpongeUserData loadEnderInventory() { this.enderChest = new SpongeUserInventoryEnderchest(this); if (this.compound.contains(Constants.Entity.Player.ENDERCHEST_INVENTORY, 9)) { final ListTag nbttaglist1 = this.compound.getList(Constants.Entity.Player.ENDERCHEST_INVENTORY, 10); - this.enderChest.fromTag(nbttaglist1); + this.enderChest.fromTag(nbttaglist1, SpongeCommon.server().registryAccess()); } } return this; @@ -243,7 +243,7 @@ public void writeCompound(final CompoundTag compound) { this.loadEnderInventory(); compound.put(Constants.Entity.Player.INVENTORY, this.inventory.writeList(new ListTag())); - compound.put(Constants.Entity.Player.ENDERCHEST_INVENTORY, this.enderChest.createTag()); + compound.put(Constants.Entity.Player.ENDERCHEST_INVENTORY, this.enderChest.createTag(SpongeCommon.server().registryAccess())); compound.putInt(Constants.Entity.Player.SELECTED_ITEM_SLOT, this.inventory.currentItem); compound.put(Constants.Entity.ENTITY_POSITION, Constants.NBT.newDoubleNBTList(this.x, this.y, this.z)); diff --git a/src/main/java/org/spongepowered/common/entity/player/SpongeUserInventory.java b/src/main/java/org/spongepowered/common/entity/player/SpongeUserInventory.java index 1425675e84f..9a08c90c14b 100644 --- a/src/main/java/org/spongepowered/common/entity/player/SpongeUserInventory.java +++ b/src/main/java/org/spongepowered/common/entity/player/SpongeUserInventory.java @@ -32,6 +32,7 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import org.spongepowered.common.SpongeCommon; import java.util.Arrays; import java.util.List; @@ -138,7 +139,7 @@ public ListTag writeList(final ListTag nbtTagListIn) { if (!this.mainInventory.get(i).isEmpty()) { final CompoundTag nbttagcompound = new CompoundTag(); nbttagcompound.putByte("Slot", (byte) i); - this.mainInventory.get(i).save(nbttagcompound); + this.mainInventory.get(i).save(SpongeCommon.server().registryAccess(), nbttagcompound); nbtTagListIn.add(nbttagcompound); } } @@ -147,7 +148,7 @@ public ListTag writeList(final ListTag nbtTagListIn) { if (!this.armorInventory.get(j).isEmpty()) { final CompoundTag nbttagcompound1 = new CompoundTag(); nbttagcompound1.putByte("Slot", (byte) (j + 100)); - this.armorInventory.get(j).save(nbttagcompound1); + this.armorInventory.get(j).save(SpongeCommon.server().registryAccess(), nbttagcompound1); nbtTagListIn.add(nbttagcompound1); } } @@ -156,7 +157,7 @@ public ListTag writeList(final ListTag nbtTagListIn) { if (!this.offHandInventory.get(k).isEmpty()) { final CompoundTag nbttagcompound2 = new CompoundTag(); nbttagcompound2.putByte("Slot", (byte) (k + 150)); - this.offHandInventory.get(k).save(nbttagcompound2); + this.offHandInventory.get(k).save(SpongeCommon.server().registryAccess(), nbttagcompound2); nbtTagListIn.add(nbttagcompound2); } } @@ -177,7 +178,7 @@ public void readList(final ListTag nbtTagListIn) { for (int i = 0; i < nbtTagListIn.size(); ++i) { final CompoundTag nbttagcompound = nbtTagListIn.getCompound(i); final int j = nbttagcompound.getByte("Slot") & 255; - final ItemStack itemstack = ItemStack.of(nbttagcompound); + final ItemStack itemstack = ItemStack.parse(SpongeCommon.server().registryAccess(), nbttagcompound).get(); if (!itemstack.isEmpty()) { if (j >= 0 && j < this.mainInventory.size()) { diff --git a/src/main/java/org/spongepowered/common/user/SpongeUserManager.java b/src/main/java/org/spongepowered/common/user/SpongeUserManager.java index 8a4101958b9..f67603f1cfb 100644 --- a/src/main/java/org/spongepowered/common/user/SpongeUserManager.java +++ b/src/main/java/org/spongepowered/common/user/SpongeUserManager.java @@ -28,6 +28,7 @@ import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.util.concurrent.ThreadFactoryBuilder; import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.PlayerDataStorage; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -39,13 +40,16 @@ import org.spongepowered.api.profile.GameProfileCache; import org.spongepowered.api.user.UserManager; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.accessor.server.MinecraftServerAccessor; import org.spongepowered.common.accessor.server.players.PlayerListAccessor; import org.spongepowered.common.accessor.world.level.storage.PlayerDataStorageAccessor; import org.spongepowered.common.entity.player.SpongeUserData; import org.spongepowered.common.entity.player.SpongeUserView; import org.spongepowered.common.profile.SpongeGameProfile; +import java.io.File; import java.io.IOException; +import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -53,8 +57,10 @@ import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; @@ -335,25 +341,25 @@ void refreshFilesystemProfiles() { this.userCache.invalidateAll(); // Add all known profiles from the data files - final String[] uuids = this.getSaveHandler().getSeenPlayers(); - for (final String playerUuid : uuids) { - - // If the filename contains a period, we can fail fast. Vanilla code fixes the Strings that have ".dat" to strip that out - // before passing that back in getAvailablePlayerDat. It doesn't remove non ".dat" filenames from the list. - if (playerUuid.contains(".")) { - continue; - } - - // At this point, we have a filename who has no extension. This doesn't mean it is actually a UUID. We trap the exception and ignore - // any filenames that fail the UUID check. - final UUID uuid; - try { - uuid = UUID.fromString(playerUuid); - } catch (final Exception ex) { - continue; + final Path playerDataDir = ((MinecraftServerAccessor) this.server).accessor$storageSource().getLevelPath(LevelResource.PLAYER_DATA_DIR); + if (Files.isDirectory(playerDataDir)) { + try (Stream list = Files.list(playerDataDir)) { + list.map(Path::toString) + .filter(file -> file.endsWith(".dat")) // only .dat files + .map(file -> file.substring(0, file.length() - 4)) + .filter(uuid -> !uuid.contains(".")) // fail fast for invalid uuid + .map(playerUuid -> { + try { + return UUID.fromString(playerUuid); + } catch (final Exception ex) { + return null; + } + }) + .filter(Objects::nonNull) + .forEach(this.knownUUIDs::add); + } catch (IOException e) { + SpongeCommon.logger().error("Failed to get player files"); } - - this.knownUUIDs.add(uuid); } } From afa9b38a52fa070b6253b2336a2af03537d45af5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:18:04 +0100 Subject: [PATCH 063/230] fix easy sendChangeDimension --- .../common/bridge/server/level/ServerPlayerBridge.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java b/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java index 0da29abad54..4344c6b3ee8 100644 --- a/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/server/level/ServerPlayerBridge.java @@ -96,7 +96,7 @@ public interface ServerPlayerBridge extends ServerPlayerEntityHealthScaleBridge default void bridge$sendChangeDimension(final Holder dimensionType, final ResourceKey key, final long hashedSeed, final GameType gameType, final GameType previousGameType, final boolean isDebug, final boolean isFlat, final byte dataToKeepMask) { - ((ServerPlayer) this).connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo(dimensionType.unwrapKey().get(), key, hashedSeed, gameType, previousGameType, isDebug, + ((ServerPlayer) this).connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo(dimensionType, key, hashedSeed, gameType, previousGameType, isDebug, isFlat, ((ServerPlayer) this).getLastDeathLocation(), ((ServerPlayer) this).getPortalCooldown()), dataToKeepMask)); } From 706c5cbe790fb0d1d5789489058d0814b841a57e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:19:13 +0100 Subject: [PATCH 064/230] fix easy worldmanager --- .../common/world/server/SpongeWorldManager.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java index f6e56e90d73..4fb8ba31908 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java @@ -334,7 +334,7 @@ private LevelSettings createLevelSettings(final PrimaryLevelData defaultLevelDat gameType == null ? defaultLevelData.getGameType() : gameType, hardcore == null ? defaultLevelData.isHardcore() : hardcore, difficulty == null ? defaultLevelData.getDifficulty() : difficulty, - commands == null ? defaultLevelData.getAllowCommands() : commands, + commands == null ? defaultLevelData.isAllowCommands() : commands, new GameRules(), defaultLevelData.getDataConfiguration()); } @@ -859,7 +859,7 @@ private ServerLevel prepareWorld(final ServerLevel world) { levelData.setSpawn(ServerLevel.END_SPAWN_POINT, 0); } } else if (levelData.worldGenOptions().generateBonusChest()) { - final BlockPos pos = new BlockPos(levelData.getXSpawn(), levelData.getYSpawn(), levelData.getZSpawn()); + final BlockPos pos = levelData.getSpawnPos(); final ConfiguredFeature bonusChestFeature = SpongeCommon.vanillaRegistry(Registries.CONFIGURED_FEATURE).get(MiscOverworldFeatures.BONUS_CHEST); bonusChestFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos); } @@ -884,7 +884,7 @@ private ServerLevel prepareWorld(final ServerLevel world) { this.server.getPlayerList().addWorldborderListener(world); if (levelData.getCustomBossEvents() != null) { - ((ServerLevelBridge) world).bridge$getBossBarManager().load(levelData.getCustomBossEvents()); + ((ServerLevelBridge) world).bridge$getBossBarManager().load(levelData.getCustomBossEvents(), world.registryAccess()); } return world; From c14060a5e11dd0552424d2a8019bb42aa231cddd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:19:59 +0100 Subject: [PATCH 065/230] fix nbt blockentity archetype --- .../common/block/entity/SpongeBlockEntityArchetype.java | 2 +- .../block/entity/SpongeBlockEntityArchetypeBuilder.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java index 0c93ec38a36..7b1892a763e 100644 --- a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java +++ b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java @@ -106,7 +106,7 @@ public Optional apply(final ServerLocation location) { compound.putInt(Constants.TileEntity.Y_POS, blockpos.getY()); compound.putInt(Constants.TileEntity.Z_POS, blockpos.getZ()); tileEntity.setBlockState((net.minecraft.world.level.block.state.BlockState) currentState); - tileEntity.load(compound); + tileEntity.load(compound, minecraftWorld.registryAccess()); return Optional.of((org.spongepowered.api.block.entity.BlockEntity) tileEntity); } diff --git a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetypeBuilder.java b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetypeBuilder.java index a7fa56540ff..2e5facb5f05 100644 --- a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetypeBuilder.java +++ b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetypeBuilder.java @@ -127,10 +127,10 @@ public BlockEntityArchetype.Builder from(final ServerLocation location) { @Override public BlockEntityArchetype.Builder blockEntity(final BlockEntity blockEntity) { - if (!(Objects.requireNonNull(blockEntity, "BlockEntity cannot be null!") instanceof net.minecraft.world.level.block.entity.BlockEntity)) { + if (!(Objects.requireNonNull(blockEntity, "BlockEntity cannot be null!") instanceof net.minecraft.world.level.block.entity.BlockEntity mcBlockEntity)) { throw new IllegalArgumentException("BlockEntity is not compatible with this implementation!"); } - final CompoundTag compound = ((net.minecraft.world.level.block.entity.BlockEntity) blockEntity).saveWithFullMetadata(); + final CompoundTag compound = mcBlockEntity.saveWithFullMetadata(mcBlockEntity.getLevel().registryAccess()); compound.remove(Constants.Sponge.BlockSnapshot.TILE_ENTITY_POSITION_X); compound.remove(Constants.Sponge.BlockSnapshot.TILE_ENTITY_POSITION_Y); compound.remove(Constants.Sponge.BlockSnapshot.TILE_ENTITY_POSITION_Z); From 051ac2e300bde6b4dc25de5b3bb168fdff249af8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:28:43 +0100 Subject: [PATCH 066/230] fix HumanEntity data / damage / ranged attack --- .../entity/living/human/HumanEntity.java | 64 ++++++++----------- 1 file changed, 26 insertions(+), 38 deletions(-) diff --git a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java index d37133cbfd5..f4a0f0c6238 100644 --- a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java +++ b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java @@ -38,6 +38,7 @@ import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; @@ -59,12 +60,15 @@ import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.Arrow; +import net.minecraft.world.entity.projectile.ProjectileUtil; +import net.minecraft.world.item.ArrowItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.PlayerTeam; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; @@ -120,23 +124,23 @@ public HumanEntity(final EntityType type, final Level wor } @Override - protected void defineSynchedData() { + protected void defineSynchedData(SynchedEntityData.Builder $$0) { // LivingEntity - this.entityData.define(LivingEntityAccessor.accessor$DATA_LIVING_ENTITY_FLAGS(), (byte) 0); - this.entityData.define(LivingEntityAccessor.accessor$DATA_HEALTH_ID(), 1.0F); - this.entityData.define(LivingEntityAccessor.accessor$DATA_EFFECT_COLOR_ID(), 0); - this.entityData.define(LivingEntityAccessor.accessor$DATA_EFFECT_AMBIENCE_ID(), Boolean.FALSE); - this.entityData.define(LivingEntityAccessor.accessor$DATA_ARROW_COUNT_ID(), 0); - this.entityData.define(LivingEntityAccessor.accessor$DATA_STINGER_COUNT_ID(), 0); - this.entityData.define(LivingEntityAccessor.accessor$SLEEPING_POS_ID(), Optional.empty()); + $$0.define(LivingEntityAccessor.accessor$DATA_LIVING_ENTITY_FLAGS(), (byte) 0); + $$0.define(LivingEntityAccessor.accessor$DATA_HEALTH_ID(), 1.0F); + $$0.define(LivingEntityAccessor.accessor$DATA_EFFECT_COLOR_ID(), 0); + $$0.define(LivingEntityAccessor.accessor$DATA_EFFECT_AMBIENCE_ID(), Boolean.FALSE); + $$0.define(LivingEntityAccessor.accessor$DATA_ARROW_COUNT_ID(), 0); + $$0.define(LivingEntityAccessor.accessor$DATA_STINGER_COUNT_ID(), 0); + $$0.define(LivingEntityAccessor.accessor$SLEEPING_POS_ID(), Optional.empty()); // Player - this.entityData.define(PlayerAccessor.accessor$DATA_PLAYER_ABSORPTION_ID(), 0.0F); - this.entityData.define(PlayerAccessor.accessor$DATA_SCORE_ID(), 0); - this.entityData.define(PlayerAccessor.accessor$DATA_PLAYER_MODE_CUSTOMISATION(), (byte) 0); - this.entityData.define(PlayerAccessor.accessor$DATA_PLAYER_MAIN_HAND(), (byte) 1); - this.entityData.define(PlayerAccessor.accessor$DATA_SHOULDER_LEFT(), new CompoundTag()); - this.entityData.define(PlayerAccessor.accessor$DATA_SHOULDER_RIGHT(), new CompoundTag()); + $$0.define(PlayerAccessor.accessor$DATA_PLAYER_ABSORPTION_ID(), 0.0F); + $$0.define(PlayerAccessor.accessor$DATA_SCORE_ID(), 0); + $$0.define(PlayerAccessor.accessor$DATA_PLAYER_MODE_CUSTOMISATION(), (byte) 0); + $$0.define(PlayerAccessor.accessor$DATA_PLAYER_MAIN_HAND(), (byte) 1); + $$0.define(PlayerAccessor.accessor$DATA_SHOULDER_LEFT(), new CompoundTag()); + $$0.define(PlayerAccessor.accessor$DATA_SHOULDER_RIGHT(), new CompoundTag()); } @Override @@ -307,7 +311,7 @@ public boolean doHurtTarget(final Entity entityIn) { float f = (float) this.getAttribute(Attributes.ATTACK_DAMAGE).getValue(); int i = 0; - f += EnchantmentHelper.getDamageBonus(this.getItemInHand(InteractionHand.MAIN_HAND), this.getMobType()); + f += EnchantmentHelper.getDamageBonus(this.getItemInHand(InteractionHand.MAIN_HAND), this.getType()); i += EnchantmentHelper.getKnockbackBonus(this); final boolean flag = entityIn.hurt(this.damageSources().mobAttack(this), f); @@ -322,7 +326,7 @@ public boolean doHurtTarget(final Entity entityIn) { final int j = EnchantmentHelper.getFireAspect(this); if (j > 0) { - entityIn.setSecondsOnFire(j * 4); + entityIn.igniteForSeconds(j * 4); } this.doEnchantDamageEffects(this, entityIn); @@ -502,34 +506,18 @@ public Stream> popQueuedPackets(final @Nullable ServerPlayer player) { @Override public void performRangedAttack(final LivingEntity target, final float distanceFactor) { - // Borrowed from Skeleton - final Arrow entitytippedarrow = new Arrow(this.level(), this, new ItemStack(Items.ARROW)); + final ItemStack itemstack = this.getItemInHand(InteractionHand.OFF_HAND); + final Arrow arrow = new Arrow(this.level(), this, itemstack.getItem() instanceof ArrowItem ? itemstack : new ItemStack(Items.ARROW)); final double d0 = target.getX() - this.getX(); - final double d1 = target.getBoundingBox().minY + target.getBbHeight() / 3.0F - entitytippedarrow.getY(); + final double d1 = target.getBoundingBox().minY + target.getBbHeight() / 3.0F - arrow.getY(); final double d2 = target.getZ() - this.getZ(); final double d3 = Math.sqrt(d0 * d0 + d2 * d2); - entitytippedarrow.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, 14 - this.level().getDifficulty().getId() * 4); - // These names are wrong - final int i = EnchantmentHelper.getEnchantmentLevel(Enchantments.PUNCH_ARROWS, this); - final int j = EnchantmentHelper.getEnchantmentLevel(Enchantments.FLAMING_ARROWS, this); - entitytippedarrow.setBaseDamage(distanceFactor * 2.0F + this.random.nextGaussian() * 0.25D + this.level().getDifficulty().getId() * 0.11F); - - if (i > 0) { - entitytippedarrow.setBaseDamage(entitytippedarrow.getBaseDamage() + i * 0.5D + 0.5D); - } - - if (j > 0) { - entitytippedarrow.setKnockback(j); - } + arrow.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, 14 - this.level().getDifficulty().getId() * 4); - final ItemStack itemstack = this.getItemInHand(InteractionHand.OFF_HAND); - - if (itemstack.getItem() == Items.TIPPED_ARROW) { - entitytippedarrow.setEffectsFromItem(itemstack); - } + arrow.setEnchantmentEffectsFromEntity(this, distanceFactor); this.playSound(SoundEvents.ARROW_SHOOT, 1.0F, 1.0F / (this.random.nextFloat() * 0.4F + 0.8F)); - this.level().addFreshEntity(entitytippedarrow); + this.level().addFreshEntity(arrow); } @Override From 627acbdd2d80504738fff62d56411dae579e18ce Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 1 Mar 2024 23:29:12 +0100 Subject: [PATCH 067/230] TODO HumanEntity fix ridingOffset now vehicleAttachmentPoint --- .../common/entity/living/human/HumanEntity.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java index f4a0f0c6238..f07519d9827 100644 --- a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java +++ b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java @@ -272,8 +272,9 @@ protected SoundEvent getDeathSound() { } @Override - protected float ridingOffset(Entity $$0) { - return Constants.Entity.Player.PLAYER_Y_OFFSET; + public Vec3 getVehicleAttachmentPoint(final Entity $$0) { + // TODO Constants.Entity.Player.PLAYER_Y_OFFSET; + return super.getVehicleAttachmentPoint($$0); } @Override From 67f359959b01c5f878cfd8ce2511871439e4a80e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 08:55:50 +0100 Subject: [PATCH 068/230] fix nbt EntityArchetype --- .../common/entity/SpongeEntityArchetype.java | 12 ------------ .../common/entity/SpongeEntityArchetypeBuilder.java | 1 - .../org/spongepowered/common/util/Constants.java | 1 - 3 files changed, 14 deletions(-) diff --git a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetype.java b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetype.java index c3688450b54..8b6e6d98173 100644 --- a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetype.java +++ b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetype.java @@ -32,7 +32,6 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.persistence.DataContainer; @@ -147,22 +146,11 @@ public Optional apply(final ServerLocation compound.put(Constants.Entity.ENTITY_POSITION, pos); compound.remove(Constants.Entity.ENTITY_UUID); - final boolean requiresInitialSpawn; - if (compound.contains(Constants.Sponge.EntityArchetype.REQUIRES_EXTRA_INITIAL_SPAWN)) { - requiresInitialSpawn = compound.getBoolean(Constants.Sponge.EntityArchetype.REQUIRES_EXTRA_INITIAL_SPAWN); - compound.remove(Constants.Sponge.EntityArchetype.REQUIRES_EXTRA_INITIAL_SPAWN); - } else { - requiresInitialSpawn = true; - } - final @Nullable Entity entity = net.minecraft.world.entity.EntityType.loadEntityRecursive(compound, level, e -> { e.moveTo(location.x(), location.y(), location.z()); if (e instanceof Mob mobentity) { mobentity.yHeadRot = mobentity.getYRot(); mobentity.yBodyRot = mobentity.getXRot(); - if (requiresInitialSpawn) { - mobentity.finalizeSpawn(level, level.getCurrentDifficultyAt(e.blockPosition()), MobSpawnType.COMMAND, null, compound); - } } return e; }); diff --git a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java index 5296ec8977e..2f7d81e7e69 100644 --- a/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java +++ b/src/main/java/org/spongepowered/common/entity/SpongeEntityArchetypeBuilder.java @@ -144,7 +144,6 @@ public EntityArchetype.Builder from(final Entity entity) { } this.position = new Vector3d(mcEntity.getX(), mcEntity.getY(), mcEntity.getZ()); SpongeEntityArchetypeBuilder.stripCompound(compound); - compound.putBoolean(Constants.Sponge.EntityArchetype.REQUIRES_EXTRA_INITIAL_SPAWN, true); this.position = entity.position(); this.compound = compound; return this; diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index dcd858aa409..bbadb09f761 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -209,7 +209,6 @@ public static final class PlayerData { public static final class EntityArchetype { public static final int BASE_VERSION = 1; - public static final String REQUIRES_EXTRA_INITIAL_SPAWN = "RequireInitialSpawn"; public static final String ENTITY_ID = "Id"; public static final DataQuery ENTITY_TYPE = of("EntityType"); public static final DataQuery ENTITY_DATA = of("EntityData"); From 9ad4185ba1ea77c16ae38ec1d57d4b19cc9e0d0d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 09:10:10 +0100 Subject: [PATCH 069/230] fix ClientboundUpdateMobEffectPacket --- .../common/data/provider/entity/ServerPlayerData.java | 2 +- src/main/java/org/spongepowered/common/entity/EntityUtil.java | 2 +- .../common/mixin/core/server/level/ServerPlayerMixin.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java index 78243c3d27e..076c2fd07ab 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java @@ -162,7 +162,7 @@ private static void resendProfile(final ServerPlayer h) { playerList.sendAllPlayerInfo(h); playerList.sendPlayerPermissionLevel(h); for(MobEffectInstance $$6 : h.getActiveEffects()) { - h.connection.send(new ClientboundUpdateMobEffectPacket(h.getId(), $$6)); + h.connection.send(new ClientboundUpdateMobEffectPacket(h.getId(), $$6, false)); } h.connection.send(new ClientboundSetExperiencePacket(h.experienceProgress, h.totalExperience, h.experienceLevel)); diff --git a/src/main/java/org/spongepowered/common/entity/EntityUtil.java b/src/main/java/org/spongepowered/common/entity/EntityUtil.java index 5d5663b1de0..f88747561c6 100644 --- a/src/main/java/org/spongepowered/common/entity/EntityUtil.java +++ b/src/main/java/org/spongepowered/common/entity/EntityUtil.java @@ -124,7 +124,7 @@ public static void performPostChangePlayerWorldLogic(final ServerPlayer player, playerlist.sendAllPlayerInfo(player); for (final MobEffectInstance effectinstance : player.getActiveEffects()) { - player.connection.send(new ClientboundUpdateMobEffectPacket(player.getId(), effectinstance)); + player.connection.send(new ClientboundUpdateMobEffectPacket(player.getId(), effectinstance, false)); } if (isPortal) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java index 1146b12131d..bedf2722781 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java @@ -578,7 +578,7 @@ public void teleportTo( // Sponge End for (final MobEffectInstance effectinstance : this.shadow$getActiveEffects()) { - this.connection.send(new ClientboundUpdateMobEffectPacket(this.shadow$getId(), effectinstance)); + this.connection.send(new ClientboundUpdateMobEffectPacket(this.shadow$getId(), effectinstance, false)); } if (isNetherPortal) { // Sponge: only play the sound if we've got a vanilla teleporter that reports a nether portal From 8060e6f756601e05a949824c184f47164b8f6bbb Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 09:11:05 +0100 Subject: [PATCH 070/230] fix easy dimensiontype usage --- .../common/data/provider/entity/ServerPlayerData.java | 2 +- .../common/mixin/core/server/level/ServerPlayerMixin.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java index 076c2fd07ab..61c63ce3516 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ServerPlayerData.java @@ -144,7 +144,7 @@ private static void resendProfile(final ServerPlayer h) { h.serverLevel().getChunkSource().addEntity(h); // Reconnect local player h.connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo( - h.level().dimensionTypeId(), + h.level().dimensionTypeRegistration(), h.level().dimension(), BiomeManager.obfuscateSeed(h.serverLevel().getSeed()), h.gameMode.getGameModeForPlayer(), diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java index bedf2722781..8e017e2d954 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin.java @@ -510,7 +510,7 @@ public void teleportTo( @Override protected final void impl$prepareForPortalTeleport(final ServerLevel currentWorld, final ServerLevel targetWorld) { final LevelData levelData = targetWorld.getLevelData(); - this.connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo(targetWorld.dimensionTypeId(), targetWorld.dimension(), + this.connection.send(new ClientboundRespawnPacket(new CommonPlayerSpawnInfo(targetWorld.dimensionTypeRegistration(), targetWorld.dimension(), BiomeManager.obfuscateSeed(targetWorld.getSeed()), this.gameMode.getGameModeForPlayer(), this.gameMode.getPreviousGameModeForPlayer(), targetWorld.isDebug(), targetWorld.isFlat(), this.shadow$getLastDeathLocation(), this.shadow$getPortalCooldown()), ClientboundRespawnPacket.KEEP_ALL_DATA)); From 40599da2f5d332854b796cf4e9cd1adc38af0fec Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 10:21:51 +0100 Subject: [PATCH 071/230] fix BannerPatternLayers TODO base color? --- .../meta/SpongePatternLayerBuilder.java | 14 ++-- .../common/data/meta/package-info.java | 26 ------- .../provider/block/entity/BannerData.java | 17 +++- .../item/stack/ShieldItemStackData.java | 78 ++----------------- .../BannerPatternLayers_LayerMixin_API.java} | 34 ++++---- .../block/entity/BannerBlockEntityMixin.java | 55 ++----------- src/mixins/resources/mixins.sponge.api.json | 1 + 7 files changed, 60 insertions(+), 165 deletions(-) delete mode 100644 src/main/java/org/spongepowered/common/data/meta/package-info.java rename src/{main/java/org/spongepowered/common/data/meta/SpongePatternLayer.java => mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java} (64%) diff --git a/src/main/java/org/spongepowered/common/data/builder/meta/SpongePatternLayerBuilder.java b/src/main/java/org/spongepowered/common/data/builder/meta/SpongePatternLayerBuilder.java index b62cc8947f9..edce6eec5b3 100644 --- a/src/main/java/org/spongepowered/common/data/builder/meta/SpongePatternLayerBuilder.java +++ b/src/main/java/org/spongepowered/common/data/builder/meta/SpongePatternLayerBuilder.java @@ -25,6 +25,9 @@ package org.spongepowered.common.data.builder.meta; +import net.minecraft.core.Holder; +import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.meta.BannerPatternLayer; import org.spongepowered.api.data.persistence.AbstractDataBuilder; @@ -34,7 +37,6 @@ import org.spongepowered.api.data.type.BannerPatternShape; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.common.data.meta.SpongePatternLayer; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.Preconditions; @@ -61,15 +63,16 @@ protected Optional buildContent(final DataView container) th return Optional.empty(); } final BannerPatternShape shape = container.getRegistryValue(Constants.TileEntity.Banner.SHAPE, RegistryTypes.BANNER_PATTERN_SHAPE, - Sponge.game()) - .orElseThrow(() -> new InvalidDataException("The provided container has an invalid banner pattern shape entry!")); + Sponge.game()).orElseThrow(() -> new InvalidDataException("The provided container has an invalid banner pattern shape entry!")); // Now we need to validate the dye color of course... final DyeColor color = container.getRegistryValue(Constants.TileEntity.Banner.COLOR, RegistryTypes.DYE_COLOR, Sponge.game()) .orElseThrow(() -> new InvalidDataException("The provided container has an invalid dye color entry!")); - return Optional.of(new SpongePatternLayer(shape, color)); + + final Holder mcPattern = Holder.direct((BannerPattern) (Object) shape); + return Optional.of((BannerPatternLayer) (Object) new BannerPatternLayers.Layer(mcPattern, (net.minecraft.world.item.DyeColor) (Object) color)); } @Override @@ -102,6 +105,7 @@ public BannerPatternLayer.Builder from(final BannerPatternLayer value) { public BannerPatternLayer build() { Preconditions.checkState(this.shape != null); Preconditions.checkState(this.color != null); - return new SpongePatternLayer(this.shape, this.color); + final Holder mcPattern = Holder.direct((BannerPattern) (Object) shape); + return (BannerPatternLayer) (Object) new BannerPatternLayers.Layer(mcPattern, (net.minecraft.world.item.DyeColor) (Object) color); } } diff --git a/src/main/java/org/spongepowered/common/data/meta/package-info.java b/src/main/java/org/spongepowered/common/data/meta/package-info.java deleted file mode 100644 index 40f61b212e0..00000000000 --- a/src/main/java/org/spongepowered/common/data/meta/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -@org.checkerframework.framework.qual.DefaultQualifier(org.checkerframework.checker.nullness.qual.NonNull.class) -package org.spongepowered.common.data.meta; diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java index 7a19455635e..f1a61032b82 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java @@ -24,12 +24,18 @@ */ package org.spongepowered.common.data.provider.block.entity; +import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BannerBlockEntity; +import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.data.Keys; +import org.spongepowered.api.data.meta.BannerPatternLayer; import org.spongepowered.common.bridge.world.level.block.entity.BannerBlockEntityBridge; import org.spongepowered.common.data.provider.DataProviderRegistrator; +import java.util.List; + public final class BannerData { private BannerData() { @@ -40,11 +46,11 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(BannerBlockEntity.class) .create(Keys.BANNER_PATTERN_LAYERS) - .get(h -> ((BannerBlockEntityBridge) h).bridge$getLayers()) + .get(h -> h.getPatternsWithBase().layers().stream().map(BannerPatternLayer.class::cast).toList()) .setAnd((h, v) -> { final Level world = h.getLevel(); if (world != null && !world.isClientSide) { // This avoids a client crash because clientside. - ((BannerBlockEntityBridge) h).bridge$setLayers(v); + applyBannerPatternLayers(h, v); return true; } return false; @@ -61,4 +67,11 @@ public static void register(final DataProviderRegistrator registrator) { }); } // @formatter:on + private static void applyBannerPatternLayers(final BannerBlockEntity h, final List v) { + final DataComponentMap.Builder builder = DataComponentMap.builder(); + h.collectComponents(builder); + // TODO base color? + builder.set(DataComponents.BANNER_PATTERNS, new BannerPatternLayers(v.stream().map(BannerPatternLayers.Layer.class::cast).toList())); + final DataComponentMap components = builder.build(); + h.applyComponents(components);} } diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ShieldItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ShieldItemStackData.java index adad2a1f680..9b499f8084f 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ShieldItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ShieldItemStackData.java @@ -24,100 +24,38 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.BannerItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShieldItem; -import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.meta.BannerPatternLayer; -import org.spongepowered.api.data.type.BannerPatternShape; -import org.spongepowered.api.data.type.BannerPatternShapes; import org.spongepowered.api.data.type.DyeColor; -import org.spongepowered.api.data.type.DyeColors; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.NBTCollectors; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; public final class ShieldItemStackData { - private static final Map SHAPE_BY_HASHNAME = new HashMap<>(); - - static { - - } - private ShieldItemStackData() { } // @formatter:off public static void register(final DataProviderRegistrator registrator) { - final Registry bannerRegistry = BuiltInRegistries.BANNER_PATTERN; - bannerRegistry.stream().forEach(pattern -> ShieldItemStackData.SHAPE_BY_HASHNAME.put(pattern.getHashname(), (BannerPatternShape) pattern)); - registrator .asMutable(ItemStack.class) .create(Keys.DYE_COLOR) - .get(h -> { - final CompoundTag tag = h.getTagElement(Constants.Item.BLOCK_ENTITY_TAG); - if (tag == null || tag.contains(Constants.TileEntity.Banner.BANNER_PATTERNS, Constants.NBT.TAG_LIST)) { - return DyeColors.WHITE.get(); - } - final int id = tag.getInt(Constants.TileEntity.Banner.BANNER_BASE); - return (DyeColor) (Object) net.minecraft.world.item.DyeColor.byId(id); - }) - .set((h, v) -> { - final CompoundTag tag = h.getOrCreateTagElement(Constants.Item.BLOCK_ENTITY_TAG); - tag.putInt(Constants.TileEntity.Banner.BANNER_BASE, ((net.minecraft.world.item.DyeColor) (Object) v).getId()); - }) + .get(h -> (DyeColor) (Object) h.getOrDefault(DataComponents.BASE_COLOR, net.minecraft.world.item.DyeColor.WHITE)) + .set((h, v) -> h.set(DataComponents.BASE_COLOR, (net.minecraft.world.item.DyeColor) (Object) v)) .supports(h -> h.getItem() instanceof ShieldItem) .create(Keys.BANNER_PATTERN_LAYERS) - .get(h -> { - final CompoundTag tag = h.getTagElement(Constants.Item.BLOCK_ENTITY_TAG); - if (tag == null || !tag.contains(Constants.TileEntity.Banner.BANNER_PATTERNS, Constants.NBT.TAG_LIST)) { - return new ArrayList<>(); - } - final ListTag layersList = tag.getList(Constants.TileEntity.Banner.BANNER_PATTERNS, Constants.NBT.TAG_COMPOUND); - return layersList.stream() - .map(layer -> ShieldItemStackData.layerFromNbt((CompoundTag) layer)) - .collect(Collectors.toList()); - }) + .get(h -> h.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers() + .stream().map(BannerPatternLayer.class::cast).toList()) .set((h, v) -> { - final ListTag layersTag = v.stream() - .filter(layer -> layer.shape() != BannerPatternShapes.BASE.get()) - .map(ShieldItemStackData::layerToNbt) - .collect(NBTCollectors.toTagList()); - final CompoundTag blockEntity = h.getOrCreateTagElement(Constants.Item.BLOCK_ENTITY_TAG); - blockEntity.put(Constants.TileEntity.Banner.BANNER_PATTERNS, layersTag); - if (h.getItem() instanceof ShieldItem) { - // TODO reject BannerPatternShapes.BASE for BannerItem? - v.stream().filter(layer -> layer.shape() == BannerPatternShapes.BASE.get()).forEach(layer -> { - blockEntity.putInt(Constants.TileEntity.Banner.BANNER_BASE, ((net.minecraft.world.item.DyeColor) (Object) layer.color()).getId()); - }); - } + h.set(DataComponents.BANNER_PATTERNS, new BannerPatternLayers(v.stream().map(BannerPatternLayers.Layer.class::cast).toList())); + // TODO check setting banner base? Constants.TileEntity.Banner.BANNER_BASE / BannerPatternShapes.BASE }) .supports(h -> h.getItem() instanceof ShieldItem || h.getItem() instanceof BannerItem); } // @formatter:on - public static BannerPatternLayer layerFromNbt(final CompoundTag nbt) { - final BannerPatternShape shape = ShieldItemStackData.SHAPE_BY_HASHNAME.get(nbt.getString(Constants.TileEntity.Banner.BANNER_PATTERN_ID)); - final net.minecraft.world.item.DyeColor dyeColor = net.minecraft.world.item.DyeColor.byId(nbt.getInt(Constants.TileEntity.Banner.BANNER_PATTERN_COLOR)); - return BannerPatternLayer.of(shape, (org.spongepowered.api.data.type.DyeColor) (Object) dyeColor); - } - - public static CompoundTag layerToNbt(final BannerPatternLayer layer) { - final CompoundTag nbt = new CompoundTag(); - nbt.putString(Constants.TileEntity.Banner.BANNER_PATTERN_ID, ((BannerPattern) (Object) layer.shape()).getHashname()); - nbt.putInt(Constants.TileEntity.Banner.BANNER_PATTERN_COLOR, ((net.minecraft.world.item.DyeColor) (Object) layer.color()).getId()); - return nbt; - } } diff --git a/src/main/java/org/spongepowered/common/data/meta/SpongePatternLayer.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java similarity index 64% rename from src/main/java/org/spongepowered/common/data/meta/SpongePatternLayer.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java index 0b90ee109a4..de3818a5bf1 100644 --- a/src/main/java/org/spongepowered/common/data/meta/SpongePatternLayer.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java @@ -22,8 +22,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.data.meta; +package org.spongepowered.common.mixin.api.minecraft.world.level.block.entity; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.meta.BannerPatternLayer; @@ -32,26 +36,26 @@ import org.spongepowered.api.data.type.BannerPatternShape; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.registry.RegistryTypes; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.util.Constants; -public final class SpongePatternLayer implements BannerPatternLayer { +@Mixin(BannerPatternLayers.Layer.class) +public abstract class BannerPatternLayers_LayerMixin_API implements BannerPatternLayer { - private final BannerPatternShape id; - private final DyeColor color; + @Shadow @Final private Holder pattern; - public SpongePatternLayer(final BannerPatternShape id, final DyeColor color) { - this.id = id; - this.color = color; - } + @Shadow @Final private net.minecraft.world.item.DyeColor color; @Override public BannerPatternShape shape() { - return this.id; + return (BannerPatternShape) (Object) this.pattern.value(); } @Override public DyeColor color() { - return this.color; + return (DyeColor) (Object) this.color; } @Override @@ -61,12 +65,12 @@ public int contentVersion() { @Override public DataContainer toContainer() { - final ResourceKey idKey = Sponge.game().registry(RegistryTypes.BANNER_PATTERN_SHAPE).valueKey(this.id); - final ResourceKey colorKey = Sponge.game().registry(RegistryTypes.DYE_COLOR).valueKey(this.color); + final ResourceKey idKey = (ResourceKey) (Object) BuiltInRegistries.BANNER_PATTERN.getKey(this.pattern.value()); + final ResourceKey colorKey = Sponge.game().registry(RegistryTypes.DYE_COLOR).valueKey(this.color()); return DataContainer.createNew() - .set(Queries.CONTENT_VERSION, this.contentVersion()) - .set(Constants.TileEntity.Banner.SHAPE, idKey) - .set(Constants.TileEntity.Banner.COLOR, colorKey); + .set(Queries.CONTENT_VERSION, this.contentVersion()) + .set(Constants.TileEntity.Banner.SHAPE, idKey) + .set(Constants.TileEntity.Banner.COLOR, colorKey); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java index d50c6dde53e..0f50b1511b6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java @@ -25,41 +25,27 @@ package org.spongepowered.common.mixin.core.world.level.block.entity; -import com.google.common.collect.Lists; -import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.block.entity.BannerBlockEntity; -import org.spongepowered.api.data.meta.BannerPatternLayer; +import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.CustomNameableBridge; import org.spongepowered.common.bridge.world.level.block.entity.BannerBlockEntityBridge; -import org.spongepowered.common.data.provider.item.stack.ShieldItemStackData; -import java.util.ArrayList; -import java.util.List; import java.util.Objects; +import javax.annotation.Nullable; + @Mixin(BannerBlockEntity.class) public abstract class BannerBlockEntityMixin extends BlockEntityMixin implements BannerBlockEntityBridge, CustomNameableBridge { @Shadow private net.minecraft.world.item.DyeColor baseColor; - @Shadow private ListTag itemPatterns; - - private List impl$patternLayers = Lists.newArrayList(); - - @Inject(method = "load", at = @At("RETURN")) - private void onSetItemValues(final CallbackInfo ci) { - this.impl$updatePatterns(); - } + @Shadow private BannerPatternLayers patternsWithBase; + @Shadow private BannerPatternLayers itemPatterns; + @Shadow @Nullable private Component name; private void impl$markDirtyAndUpdate() { this.shadow$setChanged(); @@ -68,32 +54,6 @@ private void onSetItemValues(final CallbackInfo ci) { } } - private void impl$updatePatterns() { - this.impl$patternLayers.clear(); - if (this.itemPatterns != null) { - for (final Tag pattern : this.itemPatterns) { - this.impl$patternLayers.add(ShieldItemStackData.layerFromNbt((CompoundTag) pattern)); - } - } - this.impl$markDirtyAndUpdate(); - } - - @Override - public List bridge$getLayers() { - return new ArrayList<>(this.impl$patternLayers); - } - - @Override - public void bridge$setLayers(final List layers) { - this.impl$patternLayers = NonNullList.create(); - this.impl$patternLayers.addAll(layers); - this.itemPatterns = new ListTag(); - for (final BannerPatternLayer layer : this.impl$patternLayers) { - this.itemPatterns.add(ShieldItemStackData.layerToNbt(layer)); - } - this.impl$markDirtyAndUpdate(); - } - @SuppressWarnings("ConstantConditions") @Override public DyeColor bridge$getBaseColor() { @@ -109,11 +69,12 @@ private void onSetItemValues(final CallbackInfo ci) { } catch (final Exception e) { this.baseColor = net.minecraft.world.item.DyeColor.BLACK; } + this.patternsWithBase = this.itemPatterns.withBase(this.baseColor); this.impl$markDirtyAndUpdate(); } @Override public void bridge$setCustomDisplayName(final Component customName) { - ((BannerBlockEntity) (Object) this).setCustomName(customName); + this.name = customName; } } diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 4d3051391bc..8b246d18910 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -339,6 +339,7 @@ "minecraft.world.level.block.RotationMixin_API", "minecraft.world.level.block.entity.AbstractFurnaceBlockEntityMixin_API", "minecraft.world.level.block.entity.BannerBlockEntityMixin_API", + "minecraft.world.level.block.entity.BannerPatternLayers_LayerMixin_API", "minecraft.world.level.block.entity.BannerPatternMixin_API", "minecraft.world.level.block.entity.BarrelBlockEntityMixin_API", "minecraft.world.level.block.entity.BaseContainerBlockEntityMixin_API", From 7e4f3be1dce3f60b9b5e077d96373f701e85c3d2 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 17:31:56 +0100 Subject: [PATCH 072/230] fix BlockTypeItemStackData TODO change API Type to predicate --- .../item/stack/BlockTypeItemStackData.java | 64 ++++++++----------- .../spongepowered/common/util/Constants.java | 3 - 2 files changed, 27 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java index 4ae41f991ca..f05aa2200fb 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/BlockTypeItemStackData.java @@ -24,22 +24,20 @@ */ package org.spongepowered.common.data.provider.item.stack; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.advancements.critereon.BlockPredicate; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.AdventureModePredicate; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.data.Keys; -import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.accessor.world.item.AdventureModePredicateAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.NBTCollectors; -import org.spongepowered.common.util.NBTStreams; -import java.util.Objects; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -53,44 +51,36 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(ItemStack.class) .create(Keys.BREAKABLE_BLOCK_TYPES) - .get(h -> BlockTypeItemStackData.get(h, Constants.Item.ITEM_BREAKABLE_BLOCKS)) - .set((h, v) -> BlockTypeItemStackData.set(h, Constants.Item.ITEM_BREAKABLE_BLOCKS, v)) + .get(h -> BlockTypeItemStackData.get(h, DataComponents.CAN_BREAK)) + .set((h, v) -> BlockTypeItemStackData.set(h, DataComponents.CAN_BREAK, v)) .create(Keys.PLACEABLE_BLOCK_TYPES) - .get(h -> BlockTypeItemStackData.get(h, Constants.Item.ITEM_PLACEABLE_BLOCKS)) - .set((h, v) -> BlockTypeItemStackData.set(h, Constants.Item.ITEM_PLACEABLE_BLOCKS, v)); + .get(h -> BlockTypeItemStackData.get(h, DataComponents.CAN_PLACE_ON)) + .set((h, v) -> BlockTypeItemStackData.set(h, DataComponents.CAN_PLACE_ON, v)); } // @formatter:on - private static Set get(final ItemStack stack, final String nbtKey) { - final CompoundTag tag = stack.getTag(); - if (tag == null) { - return null; + private static Set get(final ItemStack stack, final DataComponentType component) { + // TODO change API type to predicates + final AdventureModePredicate predicate = stack.get(component); + if (predicate != null) { + return ((AdventureModePredicateAccessor) predicate).accessor$predicates().stream() + .flatMap(p -> p.blocks().orElse(HolderSet.direct()).stream()) + .map(Holder::value).map(BlockType.class::cast) + .collect(Collectors.toSet()); } - final ListTag list = tag.getList(nbtKey, Constants.NBT.TAG_STRING); - if (list.isEmpty()) { - return null; - } - final Registry blockRegistry = SpongeCommon.vanillaRegistry(Registries.BLOCK); - return NBTStreams.toStrings(list) - .map(ResourceLocation::tryParse) - .filter(Objects::nonNull) - .map(key -> (BlockType) blockRegistry.getOptional(key).orElse(null)) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + return null; } - private static boolean set(final ItemStack stack, final String nbtKey, final Set value) { + private static boolean set(final ItemStack stack, final DataComponentType component, final Set value) { if (value.isEmpty()) { - stack.removeTagKey(nbtKey); + stack.remove(component); return true; } - final Registry blockRegistry = SpongeCommon.vanillaRegistry(Registries.BLOCK); - final CompoundTag tag = stack.getOrCreateTag(); - final ListTag list = value.stream() - .map(type -> blockRegistry.getKey((Block) type).toString()) - .collect(NBTCollectors.toStringTagList()); - tag.put(nbtKey, list); + final AdventureModePredicate prev = stack.get(component); + final BlockPredicate blockPredicate = BlockPredicate.Builder.block().of(value.stream().map(Block.class::cast).toList()).build(); + final AdventureModePredicate predicate = new AdventureModePredicate(List.of(blockPredicate), prev == null || prev.showInTooltip()); + stack.set(component, predicate); return true; } } diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index bbadb09f761..9520cee5075 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -513,9 +513,6 @@ public static final class Item { public static final String ITEM_ORIGINAL_NAME = "SpongeOriginalName"; public static final String ITEM_ENCHANTMENT_ID = "id"; public static final String ITEM_ENCHANTMENT_LEVEL = "lvl"; - public static final String ITEM_BREAKABLE_BLOCKS = "CanDestroy"; - - public static final String ITEM_PLACEABLE_BLOCKS = "CanPlaceOn"; public static final String ITEM_HIDE_FLAGS = "HideFlags"; public static final String ITEM_UNBREAKABLE = "Unbreakable"; public static final String CUSTOM_POTION_EFFECTS = "custom_potion_effects"; From a5e68e126e9432ac16e09d3bc924ef1482fb3872 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:48:37 +0100 Subject: [PATCH 073/230] fix client --- .../spongepowered/vanilla/client/gui/widget/ScrollPanel.java | 2 +- .../vanilla/client/gui/widget/list/FilterableList.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java index fcf73615af4..a3f17120dda 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/ScrollPanel.java @@ -190,7 +190,7 @@ public void render(final GuiGraphics stack, final int mouseX, final int mouseY, (int) (this.height * scale)); RenderSystem.setShader(GameRenderer::getPositionTexColorShader); - RenderSystem.setShaderTexture(0, Screen.BACKGROUND_LOCATION); + RenderSystem.setShaderTexture(0, Screen.MENU_BACKGROUND); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); final float texScale = 32.0F; worldr.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/list/FilterableList.java b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/list/FilterableList.java index f387156d035..3522d2607aa 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/list/FilterableList.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/client/gui/widget/list/FilterableList.java @@ -160,7 +160,7 @@ public boolean mouseClicked(final double p_mouseClicked_1_, final double p_mouse } @Override - protected void renderList(final GuiGraphics $$0, final int $$1, final int $$2, final float $$3) { + protected void renderListItems(final GuiGraphics $$0, final int $$1, final int $$2, final float $$3) { // Most of this is based on AbstractList::renderList logic final List filteredList = this.filterSupplier == null ? this.children() : this.filterSupplier.get(); From 040bf9936956ed2019a94920114f3095bf1ae6db Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 20:57:48 +0100 Subject: [PATCH 074/230] fix PluginRepositorySource --- .../vanilla/server/packs/PluginRepositorySource.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java index c1f52b73db3..511ea171f6e 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java @@ -25,7 +25,9 @@ package org.spongepowered.vanilla.server.packs; import net.minecraft.network.chat.Component; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackResources; +import net.minecraft.server.packs.PackSelectionConfig; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.repository.Pack; import net.minecraft.server.packs.repository.PackRepository; @@ -41,11 +43,13 @@ import org.spongepowered.vanilla.launch.plugin.VanillaPluginManager; import java.nio.file.FileSystem; +import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; public final class PluginRepositorySource implements RepositorySource { + public static final PackSelectionConfig PLUGIN_SELECTION_CONFIG = new PackSelectionConfig(false, Pack.Position.BOTTOM, false); private final PackRepository repository; public PluginRepositorySource(final PackRepository repository) { @@ -74,17 +78,19 @@ public void loadPacks(final Consumer callback) { final PluginPackResources packResources = new PluginPackResources(id, pluginContainer, fileSystemSupplier); final Pack.ResourcesSupplier packSupplier = new Pack.ResourcesSupplier() { + @Override - public PackResources openPrimary(String var1) { + public PackResources openPrimary(final PackLocationInfo var1) { return packResources; } @Override - public PackResources openFull(String var1, Pack.Info var2) { + public PackResources openFull(final PackLocationInfo var1, final Pack.Metadata var2) { return packResources; } }; - final Pack pack = Pack.readMetaAndCreate(id, Component.literal(id), true, packSupplier, PackType.SERVER_DATA, Pack.Position.BOTTOM, PackSource.DEFAULT); + final PackLocationInfo info = new PackLocationInfo(id, Component.literal(id), PackSource.DEFAULT, Optional.empty()); + final Pack pack = Pack.readMetaAndCreate(info, packSupplier, PackType.SERVER_DATA, PLUGIN_SELECTION_CONFIG); ((PackRepositoryBridge_Vanilla) this.repository).bridge$registerResourcePack(pluginContainer, pack); callback.accept(pack); } From bffe2bef20ff5c8703d11cbc5a3de0fb63d91620 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:13:56 +0100 Subject: [PATCH 075/230] fix chat codec --- .../common/adventure/SpongeChatTypeTemplate.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java b/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java index 43f0a9de860..a1c525aec4b 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java @@ -72,12 +72,12 @@ public DataContainer toContainer() { public static JsonElement encode(final ChatTypeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ChatType.CODEC.encodeStart(ops, (ChatType) (Object) template.type()).getOrThrow(false, e -> {}); + return ChatType.DIRECT_CODEC.encodeStart(ops, (ChatType) (Object) template.type()).getOrThrow(false, e -> {}); } public static ChatType decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ChatType.CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return ChatType.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); } public static ChatTypeTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { From a906e304800c2963223cc160f748e8203492195c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:10:07 +0100 Subject: [PATCH 076/230] TODO Component codec --- .../core/network/FriendlyByteBufMixin.java | 177 +++++++++--------- .../core/network/PacketEncoderMixin.java | 17 +- .../network/FriendlyByteBufMixin_Vanilla.java | 14 +- 3 files changed, 101 insertions(+), 107 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java index 6a18162068b..4a11799ae72 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java @@ -46,94 +46,95 @@ public abstract class FriendlyByteBufMixin implements FriendlyByteBufBridge { private @Nullable Locale impl$locale; - @ModifyVariable(method = "writeComponent", at = @At("HEAD"), argsOnly = true) - private Component localizeComponent(final Component input) { - return NativeComponentRenderer.apply(input, this.impl$locale == null ? Locales.DEFAULT : this.impl$locale); - } - - @Override - public CompoundTag bridge$renderItemComponents(CompoundTag tag) { - if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY, 10)) { - return tag; - } - - final Locale locale = this.impl$locale == null ? Locales.DEFAULT : this.impl$locale; - CompoundTag display = tag.getCompound(Constants.Item.ITEM_DISPLAY); - boolean copy = true; - - if (display.contains(Constants.Item.ITEM_NAME, 8)) { - final String nameStr = display.getString(Constants.Item.ITEM_NAME); - final Component name = Component.Serializer.fromJson(nameStr); - final Component renderedName = NativeComponentRenderer.apply(name, locale); - - if (!renderedName.equals(name)) { - if (copy) { - tag = tag.copy(); - display = tag.getCompound(Constants.Item.ITEM_DISPLAY); - copy = false; - } - - display.putString(Constants.Item.ITEM_ORIGINAL_NAME, nameStr); - display.putString(Constants.Item.ITEM_NAME, Component.Serializer.toJson(renderedName)); - } - } - - if (display.contains(Constants.Item.ITEM_LORE, 9)) { - final ListTag lore = display.getList(Constants.Item.ITEM_LORE, 8); - - final Component[] renderedLines = new Component[lore.size()]; - boolean equal = true; - - for (int i = 0; i < renderedLines.length; i++) { - final String lineStr = lore.getString(i); - final Component line = Component.Serializer.fromJson(lineStr); - final Component renderedLine = NativeComponentRenderer.apply(line, locale); - - renderedLines[i] = renderedLine; - equal = equal && renderedLine.equals(line); - } - - if (!equal) { - if (copy) { - tag = tag.copy(); - display = tag.getCompound(Constants.Item.ITEM_DISPLAY); - copy = false; - } - - final ListTag newLore = new ListTag(); - for (Component renderedLine : renderedLines) { - newLore.add(StringTag.valueOf(Component.Serializer.toJson(renderedLine))); - } - - display.put(Constants.Item.ITEM_ORIGINAL_LORE, lore); - display.put(Constants.Item.ITEM_LORE, newLore); - } - } - return tag; - } - - @Redirect(method = "readItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;readNbt()Lnet/minecraft/nbt/CompoundTag;")) - public CompoundTag restoreItemComponents(final FriendlyByteBuf buf) { - CompoundTag tag = buf.readNbt(); - if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY, 10)) { - return tag; - } - - final CompoundTag display = tag.getCompound(Constants.Item.ITEM_DISPLAY); - - if (display.contains(Constants.Item.ITEM_ORIGINAL_NAME, 8)) { - final String name = display.getString(Constants.Item.ITEM_ORIGINAL_NAME); - display.remove(Constants.Item.ITEM_ORIGINAL_NAME); - display.putString(Constants.Item.ITEM_NAME, name); - } - - if (display.contains(Constants.Item.ITEM_ORIGINAL_LORE, 9)) { - final ListTag lore = display.getList(Constants.Item.ITEM_ORIGINAL_LORE, 8); - display.remove(Constants.Item.ITEM_ORIGINAL_LORE); - display.put(Constants.Item.ITEM_LORE, lore); - } - return tag; - } + // TODO mc is using codec now to write to the Buffer, it might even not be a FriendlyByteBuf anymore +// @ModifyVariable(method = "writeComponent", at = @At("HEAD"), argsOnly = true) +// private Component localizeComponent(final Component input) { +// return NativeComponentRenderer.apply(input, this.impl$locale == null ? Locales.DEFAULT : this.impl$locale); +// } + +// @Override +// public CompoundTag bridge$renderItemComponents(CompoundTag tag) { +// if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY, 10)) { +// return tag; +// } +// +// final Locale locale = this.impl$locale == null ? Locales.DEFAULT : this.impl$locale; +// CompoundTag display = tag.getCompound(Constants.Item.ITEM_DISPLAY); +// boolean copy = true; +// +// if (display.contains(Constants.Item.ITEM_NAME, 8)) { +// final String nameStr = display.getString(Constants.Item.ITEM_NAME); +// final Component name = Component.Serializer.fromJson(nameStr); +// final Component renderedName = NativeComponentRenderer.apply(name, locale); +// +// if (!renderedName.equals(name)) { +// if (copy) { +// tag = tag.copy(); +// display = tag.getCompound(Constants.Item.ITEM_DISPLAY); +// copy = false; +// } +// +// display.putString(Constants.Item.ITEM_ORIGINAL_NAME, nameStr); +// display.putString(Constants.Item.ITEM_NAME, Component.Serializer.toJson(renderedName)); +// } +// } +// +// if (display.contains(Constants.Item.ITEM_LORE, 9)) { +// final ListTag lore = display.getList(Constants.Item.ITEM_LORE, 8); +// +// final Component[] renderedLines = new Component[lore.size()]; +// boolean equal = true; +// +// for (int i = 0; i < renderedLines.length; i++) { +// final String lineStr = lore.getString(i); +// final Component line = Component.Serializer.fromJson(lineStr); +// final Component renderedLine = NativeComponentRenderer.apply(line, locale); +// +// renderedLines[i] = renderedLine; +// equal = equal && renderedLine.equals(line); +// } +// +// if (!equal) { +// if (copy) { +// tag = tag.copy(); +// display = tag.getCompound(Constants.Item.ITEM_DISPLAY); +// copy = false; +// } +// +// final ListTag newLore = new ListTag(); +// for (Component renderedLine : renderedLines) { +// newLore.add(StringTag.valueOf(Component.Serializer.toJson(renderedLine))); +// } +// +// display.put(Constants.Item.ITEM_ORIGINAL_LORE, lore); +// display.put(Constants.Item.ITEM_LORE, newLore); +// } +// } +// return tag; +// } +// +// @Redirect(method = "readItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;readNbt()Lnet/minecraft/nbt/CompoundTag;")) +// public CompoundTag restoreItemComponents(final FriendlyByteBuf buf) { +// CompoundTag tag = buf.readNbt(); +// if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY, 10)) { +// return tag; +// } +// +// final CompoundTag display = tag.getCompound(Constants.Item.ITEM_DISPLAY); +// +// if (display.contains(Constants.Item.ITEM_ORIGINAL_NAME, 8)) { +// final String name = display.getString(Constants.Item.ITEM_ORIGINAL_NAME); +// display.remove(Constants.Item.ITEM_ORIGINAL_NAME); +// display.putString(Constants.Item.ITEM_NAME, name); +// } +// +// if (display.contains(Constants.Item.ITEM_ORIGINAL_LORE, 9)) { +// final ListTag lore = display.getList(Constants.Item.ITEM_ORIGINAL_LORE, 8); +// display.remove(Constants.Item.ITEM_ORIGINAL_LORE); +// display.put(Constants.Item.ITEM_LORE, lore); +// } +// return tag; +// } @Override public void bridge$setLocale(final Locale locale) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java index f149ef0de8a..0a0d63f0020 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java @@ -26,29 +26,22 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; -import io.netty.util.Attribute; -import net.minecraft.network.ConnectionProtocol; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.PacketEncoder; +import net.minecraft.network.PacketListener; import net.minecraft.network.protocol.Packet; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.FriendlyByteBufBridge; @Mixin(PacketEncoder.class) -public class PacketEncoderMixin { +public class PacketEncoderMixin { @Inject(method = "encode(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/protocol/Packet;Lio/netty/buffer/ByteBuf;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;writeVarInt(I)Lnet/minecraft/network/FriendlyByteBuf;"), locals = LocalCapture.CAPTURE_FAILHARD) - private void applyLocaleToBuffer(final ChannelHandlerContext ctx, final Packet pkt, final ByteBuf orig, final CallbackInfo ci, - final Attribute> $$3, - final ConnectionProtocol.CodecData $$4, - final int unused$id, - final FriendlyByteBuf buffer) { - ((FriendlyByteBufBridge) buffer).bridge$setLocale(ctx.channel().attr(SpongeAdventure.CHANNEL_LOCALE).get()); + at = @At(value = "INVOKE", target = "Lnet/minecraft/network/codec/StreamCodec;encode(Ljava/lang/Object;Ljava/lang/Object;)V")) + private void applyLocaleToBuffer(final ChannelHandlerContext ctx, final Packet $$1, final ByteBuf $$2, final CallbackInfo ci) { + ((FriendlyByteBufBridge) $$2).bridge$setLocale(ctx.channel().attr(SpongeAdventure.CHANNEL_LOCALE).get()); // TODO check if this correct } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java index 9fcce81f48b..d5161e11aa5 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java @@ -35,11 +35,11 @@ @Mixin(FriendlyByteBuf.class) public abstract class FriendlyByteBufMixin_Vanilla implements FriendlyByteBufBridge { - @Redirect(method = "writeItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;writeNbt(Lnet/minecraft/nbt/Tag;)Lnet/minecraft/network/FriendlyByteBuf;")) - public FriendlyByteBuf renderItemComponents(final FriendlyByteBuf buf, final Tag tag) { - if (tag instanceof CompoundTag compoundTag) { - return buf.writeNbt(bridge$renderItemComponents(compoundTag)); - } - return buf.writeNbt(tag); - } +// @Redirect(method = "writeItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;writeNbt(Lnet/minecraft/nbt/Tag;)Lnet/minecraft/network/FriendlyByteBuf;")) +// public FriendlyByteBuf renderItemComponents(final FriendlyByteBuf buf, final Tag tag) { +// if (tag instanceof CompoundTag compoundTag) { +// return buf.writeNbt(bridge$renderItemComponents(compoundTag)); +// } +// return buf.writeNbt(tag); +// } } From cd3c001f9f1fa972f9324859e924f805f8f84e1d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:11:51 +0100 Subject: [PATCH 077/230] fix PluginPackResources --- .../vanilla/server/packs/PluginPackResources.java | 5 +++-- .../vanilla/server/packs/PluginRepositorySource.java | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginPackResources.java b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginPackResources.java index 97d32ddd9dd..0f3f38e8a01 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginPackResources.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginPackResources.java @@ -28,6 +28,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.AbstractPackResources; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.metadata.MetadataSectionSerializer; import net.minecraft.server.packs.metadata.pack.PackMetadataSection; @@ -59,8 +60,8 @@ public final class PluginPackResources extends AbstractPackResources { private final @Nullable Supplier fileSystem; private final File file; - public PluginPackResources(final String name, final PluginContainer container, final @Nullable Supplier fileSystem) { - super(name, false); + public PluginPackResources(final PackLocationInfo info, final PluginContainer container, final @Nullable Supplier fileSystem) { + super(info); this.file = new File("sponge_plugin_pack"); this.container = container; this.metadata = new PackMetadataSection(Component.literal("Plugin Resources"), 6, Optional.empty()); diff --git a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java index 511ea171f6e..84011e55e49 100644 --- a/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java +++ b/vanilla/src/main/java/org/spongepowered/vanilla/server/packs/PluginRepositorySource.java @@ -76,7 +76,8 @@ public void loadPacks(final Consumer callback) { } } - final PluginPackResources packResources = new PluginPackResources(id, pluginContainer, fileSystemSupplier); + final PackLocationInfo info = new PackLocationInfo(id, Component.literal(id), PackSource.DEFAULT, Optional.empty()); + final PluginPackResources packResources = new PluginPackResources(info, pluginContainer, fileSystemSupplier); final Pack.ResourcesSupplier packSupplier = new Pack.ResourcesSupplier() { @Override @@ -89,7 +90,6 @@ public PackResources openFull(final PackLocationInfo var1, final Pack.Metadata v return packResources; } }; - final PackLocationInfo info = new PackLocationInfo(id, Component.literal(id), PackSource.DEFAULT, Optional.empty()); final Pack pack = Pack.readMetaAndCreate(info, packSupplier, PackType.SERVER_DATA, PLUGIN_SELECTION_CONFIG); ((PackRepositoryBridge_Vanilla) this.repository).bridge$registerResourcePack(pluginContainer, pack); callback.accept(pack); From 4b9313ad66e1d3b05271f81f9f9bda8954a1fa47 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 29 Feb 2024 23:05:21 +0100 Subject: [PATCH 078/230] TODO channels need fixing --- .../common/network/PacketUtil.java | 53 ++++++++++--------- .../network/channel/SpongeChannelManager.java | 31 ++++------- 2 files changed, 37 insertions(+), 47 deletions(-) diff --git a/src/main/java/org/spongepowered/common/network/PacketUtil.java b/src/main/java/org/spongepowered/common/network/PacketUtil.java index 262d94ad598..91fc3b6f0b5 100644 --- a/src/main/java/org/spongepowered/common/network/PacketUtil.java +++ b/src/main/java/org/spongepowered/common/network/PacketUtil.java @@ -75,33 +75,34 @@ public static net.minecraft.network.protocol.Packet createLoginPayloadRequest } public static net.minecraft.network.protocol.Packet createPlayPayload(final ResourceKey channel, final ChannelBuf payload, final EngineConnectionSide side) { - if (side == EngineConnectionSide.CLIENT) { - return new ServerboundCustomPayloadPacket(new CustomPacketPayload() { - @Override - public void write(FriendlyByteBuf var1) { - var1.writeBytes((FriendlyByteBuf)payload); - } - - @Override - public ResourceLocation id() { - return (ResourceLocation) (Object) channel; - } - }); - } else if (side == EngineConnectionSide.SERVER) { - return new ClientboundCustomPayloadPacket(new CustomPacketPayload() { - @Override - public void write(FriendlyByteBuf var1) { - var1.writeBytes((FriendlyByteBuf)payload); - } - - @Override - public ResourceLocation id() { - return (ResourceLocation) (Object) channel; - } - }); - } else { + // TODO fix me +// if (side == EngineConnectionSide.CLIENT) { +// return new ServerboundCustomPayloadPacket(new CustomPacketPayload() { +// @Override +// public void write(FriendlyByteBuf var1) { +// var1.writeBytes((FriendlyByteBuf)payload); +// } +// +// @Override +// public ResourceLocation id() { +// return (ResourceLocation) (Object) channel; +// } +// }); +// } else if (side == EngineConnectionSide.SERVER) { +// return new ClientboundCustomPayloadPacket(new CustomPacketPayload() { +// @Override +// public void write(FriendlyByteBuf var1) { +// var1.writeBytes((FriendlyByteBuf)payload); +// } +// +// @Override +// public ResourceLocation id() { +// return (ResourceLocation) (Object) channel; +// } +// }); +// } else { throw new UnsupportedOperationException(); - } +// } } // TODO: Use Lmbda instead? diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java index 1aeefa65774..d1a34e97ca7 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java @@ -37,6 +37,10 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; +import org.spongepowered.api.item.ItemTypes; +import org.spongepowered.api.item.inventory.Inventory; +import org.spongepowered.api.item.inventory.query.Query; +import org.spongepowered.api.item.inventory.query.QueryTypes; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.channel.Channel; import org.spongepowered.api.network.channel.ChannelBuf; @@ -281,27 +285,12 @@ private void handleChannelRegistry(final EngineConnection connection, final Chan } public boolean handlePlayPayload(final EngineConnection connection, final CustomPacketPayload payload) { - final ResourceKey channel = (ResourceKey) (Object) payload.id(); - final ChannelBuf buf = this.bufferAllocator.buffer(); - payload.write((FriendlyByteBuf) buf); - - return this.handlePlayPayload(connection, channel, buf); - } - - public boolean handlePlayPayload(final EngineConnection connection, final ServerboundCustomPayloadPacket packet) { - final ResourceKey channel = (ResourceKey) (Object) packet.payload().id(); - final ChannelBuf payload = this.bufferAllocator.buffer(); - packet.payload().write((FriendlyByteBuf) payload); - - return this.handlePlayPayload(connection, channel, payload); - } - - public boolean handlePlayPayload(final EngineConnection connection, final ClientboundCustomPayloadPacket packet) { - final ResourceKey channel = (ResourceKey) (Object) packet.payload().id(); - final ChannelBuf payload = this.bufferAllocator.buffer(); - packet.payload().write((FriendlyByteBuf) payload); - - return this.handlePlayPayload(connection, channel, payload); +// final ResourceKey channel = (ResourceKey) (Object) payload.id(); +// final ChannelBuf buf = this.bufferAllocator.buffer(); +// payload.write((FriendlyByteBuf) buf); +// +// return this.handlePlayPayload(connection, channel, buf); + return false; // TODO fix me } private void handleRegisterChannel(final EngineConnection connection, final ChannelBuf payload, From c5c6dbb679ed80c97a44ac22b9992c737fe514a7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:25:51 +0100 Subject: [PATCH 079/230] TODO @aromaa please check this --- ...sMixin.java => ChunkStatusTasksMixin.java} | 30 ++++++++----------- src/mixins/resources/mixins.sponge.core.json | 2 +- 2 files changed, 14 insertions(+), 18 deletions(-) rename src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/{ChunkStatusMixin.java => ChunkStatusTasksMixin.java} (69%) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java similarity index 69% rename from src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java index 75843efa566..3258b233b42 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java @@ -24,16 +24,14 @@ */ package org.spongepowered.common.mixin.core.world.level.chunk; -import com.mojang.datafixers.util.Either; -import net.minecraft.server.level.ChunkHolder; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ThreadedLevelLightEngine; import net.minecraft.server.level.WorldGenRegion; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatusTasks; +import net.minecraft.world.level.chunk.status.ToFullChunk; +import net.minecraft.world.level.chunk.status.WorldGenContext; import net.minecraft.world.level.levelgen.blending.Blender; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.common.world.level.chunk.SpongeUnloadedChunkException; @@ -41,10 +39,9 @@ import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; -import java.util.function.Function; -@Mixin(ChunkStatus.class) -public abstract class ChunkStatusMixin { +@Mixin(ChunkStatusTasks.class) +public abstract class ChunkStatusTasksMixin { /** * @author aromaa - December 17th, 2023 - 1.19.4 @@ -61,20 +58,19 @@ public abstract class ChunkStatusMixin { * See IOWorkerMixin#createOldDataForRegion */ @Overwrite - private static CompletableFuture> lambda$static$6( - final ChunkStatus $$0, final Executor $$1, final ServerLevel $$2, final ChunkGenerator $$3, final StructureTemplateManager $$4, - final ThreadedLevelLightEngine $$5, final Function>> $$6, - final List $$7, final ChunkAccess $$8) { - final WorldGenRegion $$9 = new WorldGenRegion($$2, $$7, $$0, -1); + static CompletableFuture generateBiomes(final WorldGenContext $$0, final ChunkStatus $$1, final Executor $$2, + final ToFullChunk $$3, final List $$4, final ChunkAccess $$5) { + ServerLevel $$6 = $$0.level(); + WorldGenRegion $$7 = new WorldGenRegion($$6, $$4, $$1, -1); try { //Sponge: Add try - return $$3.createBiomes($$1, $$2.getChunkSource().randomState(), Blender.of($$9), $$2.structureManager().forWorldGenRegion($$9), $$8) - .thenApply($$0x -> Either.left($$0x)); + return $$0.generator().createBiomes($$2, $$6.getChunkSource().randomState(), Blender.of($$7), $$6.structureManager().forWorldGenRegion($$7), $$5); } catch (final Exception e) { //Sponge start: Add catch if (e.getCause() != SpongeUnloadedChunkException.INSTANCE) { throw e; } - return ChunkHolder.UNLOADED_CHUNK_FUTURE; + // TODO what to return here? return ChunkHolder.UNLOADED_CHUNK_FUTURE; + return null; } //Sponge end } } diff --git a/src/mixins/resources/mixins.sponge.core.json b/src/mixins/resources/mixins.sponge.core.json index fd5d338eb4c..2b6502512a4 100644 --- a/src/mixins/resources/mixins.sponge.core.json +++ b/src/mixins/resources/mixins.sponge.core.json @@ -237,7 +237,7 @@ "world.level.border.WorldBorderMixin", "world.level.chunk.ChunkGeneratorMixin", "world.level.chunk.ChunkSerializerMixin", - "world.level.chunk.ChunkStatusMixin", + "world.level.chunk.ChunkStatusTasksMixin", "world.level.chunk.LevelChunkMixin", "world.level.chunk.storage.EntityStorageMixin", "world.level.chunk.storage.IOWorkerMixin", From 8453b69228ddadea37a6b899b8273ee663febe24 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:32:24 +0100 Subject: [PATCH 080/230] fix ChunkMapMixin --- .../mixin/core/server/level/ChunkMapMixin.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java index 5dc931f3f25..8d2824ded78 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java @@ -24,17 +24,17 @@ */ package org.spongepowered.common.mixin.core.server.level; -import com.mojang.datafixers.util.Either; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ChunkHolder; import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ChunkResult; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.ai.village.poi.PoiManager; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.storage.ChunkSerializer; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.SpongeEventFactory; @@ -114,16 +114,16 @@ public abstract class ChunkMapMixin implements ChunkMapBridge { } @Redirect(method = "save", at = @At(value = "INVOKE", - target = "Lnet/minecraft/server/level/ChunkMap;write(Lnet/minecraft/world/level/ChunkPos;Lnet/minecraft/nbt/CompoundTag;)V")) - private void impl$doNotWriteIfWeHaveNoData(final ChunkMap chunkManager, final ChunkPos pos, final CompoundTag compound) { + target = "Lnet/minecraft/server/level/ChunkMap;write(Lnet/minecraft/world/level/ChunkPos;Lnet/minecraft/nbt/CompoundTag;)Ljava/util/concurrent/CompletableFuture;")) + private CompletableFuture impl$doNotWriteIfWeHaveNoData(final ChunkMap chunkManager, final ChunkPos pos, final CompoundTag compound) { if (compound == null) { - return; + return CompletableFuture.completedFuture(null); } - chunkManager.write(pos, compound); + return chunkManager.write(pos, compound); } - @Redirect(method = "lambda$scheduleUnload$14", + @Redirect(method = "lambda$scheduleUnload$16", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;unload(Lnet/minecraft/world/level/chunk/LevelChunk;)V"), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ChunkMap;save(Lnet/minecraft/world/level/chunk/ChunkAccess;)Z") @@ -172,7 +172,7 @@ public abstract class ChunkMapMixin implements ChunkMapBridge { } } - @Redirect(method = "lambda$protoChunkToFullChunk$34", + @Redirect(method = "lambda$protoChunkToFullChunk$35", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/LevelChunk;setLoaded(Z)V"), slice = @Slice( from = @At(value = "INVOKE", remap = false, target = "Lit/unimi/dsi/fastutil/longs/LongSet;add(J)Z"), @@ -204,7 +204,7 @@ public abstract class ChunkMapMixin implements ChunkMapBridge { } @Inject(method = "schedule", at = @At("HEAD"), cancellable = true) - private void impl$onSchedule(final CallbackInfoReturnable>> cir) { + private void impl$onSchedule(final CallbackInfoReturnable>> cir) { if (!((ServerLevelBridge) this.level).bridge$isLoaded()) { cir.setReturnValue(ChunkHolder.UNLOADED_CHUNK_FUTURE); } From 049345872951e5e788556b66f848675c66ff506a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:34:00 +0100 Subject: [PATCH 081/230] fix chunk status/result --- .../mixin/api/minecraft/world/level/LevelMixin_API.java | 6 +++--- .../api/minecraft/world/level/LevelReaderMixin_API.java | 2 +- .../minecraft/world/level/chunk/ChunkAccessMixin_API.java | 2 +- .../minecraft/world/level/chunk/ChunkStatusMixin_API.java | 2 +- .../minecraft/world/level/chunk/ProtoChunkMixin_API.java | 2 +- .../common/mixin/core/server/level/ChunkHolderMixin.java | 6 +++--- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index cbcce8cceb6..081721e129b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -48,7 +48,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkSource; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.entity.EntityTypeTest; @@ -337,7 +337,7 @@ public void addBlockEntity(final int x, final int y, final int z, final BlockEnt // would cause unexpected bugs. final net.minecraft.world.level.block.entity.BlockEntity mcOriginalBlockEntity = (net.minecraft.world.level.block.entity.BlockEntity) Objects.requireNonNull(blockEntity, "blockEntity"); // Save the nbt so we can copy it, specifically wout the metadata of x,y,z coordinates - final CompoundTag tag = mcOriginalBlockEntity.saveWithId(); + final CompoundTag tag = mcOriginalBlockEntity.saveWithId(mcOriginalBlockEntity.getLevel().registryAccess()); // Ensure that where we are placing this blockentity is the right blockstate, so that minecraft will actually accept it. this.world().setBlock(x, y, z, (org.spongepowered.api.block.BlockState) mcOriginalBlockEntity.getBlockState()); @@ -346,7 +346,7 @@ public void addBlockEntity(final int x, final int y, final int z, final BlockEnt .orElseThrow(() -> new IllegalStateException("Failed to create Block Entity at " + this.location(Vector3i.from(x, y, z)))); // Load the data into it. - mcNewBlockEntity.load(tag); + mcNewBlockEntity.load(tag, mcOriginalBlockEntity.getLevel().registryAccess()); // Finally, inform minecraft about our actions. this.shadow$setBlockEntity(mcNewBlockEntity); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java index 959e7e88f64..38f527bd840 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelReaderMixin_API.java @@ -30,7 +30,7 @@ import net.minecraft.world.level.CollisionGetter; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.levelgen.Heightmap; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java index d28895b2192..91f130a4880 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java @@ -27,7 +27,7 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.levelgen.Heightmap; import org.spongepowered.api.block.BlockType; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkStatusMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkStatusMixin_API.java index 9e5bb7f56e3..6a71e3aec95 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkStatusMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkStatusMixin_API.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.chunk; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import org.spongepowered.api.world.chunk.ChunkState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java index b59bdbba22d..76a298ddcca 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java @@ -30,7 +30,7 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.chunk.UpgradeData; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java index 31ef0eac30e..78130f5629f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java @@ -24,14 +24,14 @@ */ package org.spongepowered.common.mixin.core.server.level; -import com.mojang.datafixers.util.Either; import net.minecraft.server.level.ChunkHolder; import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ChunkResult; import net.minecraft.server.level.FullChunkStatus; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.status.ChunkStatus; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.world.chunk.ChunkEvent; @@ -77,7 +77,7 @@ abstract class ChunkHolderMixin { } @Inject(method = "getOrScheduleFuture", at = @At("HEAD"), cancellable = true) - private void impl$onGetOrScheduleFuture(final ChunkStatus $$0, final ChunkMap chunkMap, final CallbackInfoReturnable>> cir) { + private void impl$onGetOrScheduleFuture(final ChunkStatus $$0, final ChunkMap chunkMap, final CallbackInfoReturnable>> cir) { if (!((ServerLevelBridge) ((ChunkMapAccessor) chunkMap).accessor$level()).bridge$isLoaded()) { cir.setReturnValue(ChunkHolder.UNLOADED_CHUNK_FUTURE); } From 850fd2737342a95240cabe54d203272402ae556e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:39:51 +0100 Subject: [PATCH 082/230] fix chunk status --- .../api/minecraft/server/level/WorldGenRegionMixin_API.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java index f7bd31db695..3e875e294f0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java @@ -28,7 +28,7 @@ import net.minecraft.server.level.WorldGenRegion; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; From b110c8ec11cc1b2fd86fb6fd35275efea9adff04 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:39:18 +0100 Subject: [PATCH 083/230] fix PackMixin_API --- .../server/packs/repository/PackMixin_API.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/packs/repository/PackMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/packs/repository/PackMixin_API.java index aa2863fad2d..7e4c3406b49 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/packs/repository/PackMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/packs/repository/PackMixin_API.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.api.minecraft.server.packs.repository; import net.kyori.adventure.text.Component; +import net.minecraft.server.packs.PackLocationInfo; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.repository.Pack; import net.minecraft.server.packs.repository.PackCompatibility; @@ -39,17 +40,15 @@ public abstract class PackMixin_API implements org.spongepowered.api.resource.pack.Pack { // @formatter:off - @Shadow @Final private net.minecraft.network.chat.Component title; - + @Shadow @Final private PackLocationInfo location; + @Shadow @Final private Pack.Metadata metadata; @Shadow public abstract String shadow$getId(); @Shadow public abstract PackCompatibility shadow$getCompatibility(); @Shadow public abstract boolean shadow$isRequired(); @Shadow public abstract boolean shadow$isFixedPosition(); - // @formatter:on - @Shadow public abstract PackResources shadow$open(); + // @formatter:on - @Shadow @Final private Pack.Info info; @Override public String id() { @@ -63,12 +62,12 @@ public PackContents contents() { @Override public Component title() { - return SpongeAdventure.asAdventure(this.title); + return SpongeAdventure.asAdventure(this.location.title()); } @Override public Component description() { - return SpongeAdventure.asAdventure(this.info.description()); + return SpongeAdventure.asAdventure(this.metadata.description()); } @Override From d5dff3ebb14b19a1c754fe8364d6c4d616f1940a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:44:54 +0100 Subject: [PATCH 084/230] TODO check neighborChanged --- .../mixin/tracker/server/level/ServerLevelMixin_Tracker.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java index a5d8274d3e5..e61f91fde93 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerLevelMixin_Tracker.java @@ -33,6 +33,7 @@ import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.DebugPackets; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.RandomSource; @@ -721,7 +722,8 @@ public boolean destroyBlock(final BlockPos pos, final boolean doDrops, @Nullable peek.associateNeighborStateNotifier(immutableFrom, targetBlockState.getBlock(), immutableTarget, ((ServerLevel) (Object) this), PlayerTracker.Type.NOTIFIER); // Sponge End - targetBlockState.neighborChanged(((ServerLevel) (Object) this), immutableTarget, blockIn, immutableFrom, false); + DebugPackets.sendNeighborsUpdatePacket(((ServerLevel) (Object) this), immutableTarget); + // TODO targetBlockState.neighborChanged(((ServerLevel) (Object) this), immutableTarget, blockIn, immutableFrom, false); } catch (final Throwable throwable) { final CrashReport crashreport = CrashReport.forThrowable(throwable, "Exception while updating neighbours"); From c0d6827438064148f3bb7121afaedb94f3ad50ed Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:56:04 +0100 Subject: [PATCH 085/230] fix packet PlayerListMixin per world viewdistance --- .../core/server/players/PlayerListMixin.java | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java index 867c27669d8..78721e50039 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java @@ -377,24 +377,9 @@ public abstract class PlayerListMixin implements PlayerListBridge { ((ServerPlayerBridge) playerIn).bridge$setConnectionMessageToSend(message); } - @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "(IZLjava/util/Set;IIIZZZLnet/minecraft/network/protocol/game/CommonPlayerSpawnInfo;)Lnet/minecraft/network/protocol/game/ClientboundLoginPacket;")) - private ClientboundLoginPacket impl$usePerWorldViewDistance( - final int playerId, - final boolean hardcore, - final Set levels, - final int maxPlayers, - final int chunkRadius, - final int simulationDistance, - final boolean reducedDebugInfo, - final boolean showDeathScreen, - final boolean limitedCrafting, - final CommonPlayerSpawnInfo info, - final Connection conn, - final net.minecraft.server.level.ServerPlayer player, - final CommonListenerCookie clc) { - final Integer viewDistance = ((PrimaryLevelDataBridge) player.serverLevel().getLevelData()).bridge$viewDistance().orElse(chunkRadius); - return new ClientboundLoginPacket(playerId, hardcore, levels, maxPlayers, viewDistance, simulationDistance, reducedDebugInfo, - showDeathScreen, limitedCrafting, info); + @Redirect(method = "placeNewPlayer", at = @At(value = "FIELD", target = "Lnet/minecraft/server/players/PlayerList;viewDistance:I")) + private int impl$usePerWorldViewDistance(final PlayerList instance, final Connection $$0, final net.minecraft.server.level.ServerPlayer $$1, final CommonListenerCookie $$2) { + return ((PrimaryLevelDataBridge) $$1.serverLevel().getLevelData()).bridge$viewDistance().orElse( instance.getViewDistance()); } @Redirect(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getCustomBossEvents()Lnet/minecraft/server/bossevents/CustomBossEvents;")) From 7299d4dddd6aa0f47893ccb9183d0ac2f6a7033b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:59:38 +0100 Subject: [PATCH 086/230] fix PlayerListMixin new player spawn nbt + easy fix --- .../core/server/players/PlayerListMixin.java | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java index 78721e50039..cc421888834 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java @@ -38,9 +38,7 @@ import net.minecraft.network.chat.PlayerChatMessage; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; -import net.minecraft.network.protocol.game.ClientboundLoginPacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.protocol.game.CommonPlayerSpawnInfo; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; @@ -129,7 +127,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -151,13 +148,14 @@ public abstract class PlayerListMixin implements PlayerListBridge { @Shadow @Final private PlayerDataStorage playerIo; @Shadow public abstract MinecraftServer shadow$getServer(); - @Shadow @Nullable public abstract CompoundTag shadow$load(net.minecraft.server.level.ServerPlayer playerIn); + @Shadow public abstract Optional shadow$load(final net.minecraft.server.level.ServerPlayer $$0); @Shadow public abstract boolean shadow$canBypassPlayerLimit(com.mojang.authlib.GameProfile param0); @Shadow protected abstract boolean shadow$verifyChatTrusted(final PlayerChatMessage $$0); @Shadow protected abstract void shadow$broadcastChatMessage(final PlayerChatMessage $$0, final Predicate $$1, final net.minecraft.server.level.@Nullable ServerPlayer $$2, final ChatType.Bound $$4); // @formatter:on + private boolean impl$isGameMechanicRespawn = false; private boolean impl$isDuringSystemMessageEvent = false; @@ -248,12 +246,12 @@ public abstract class PlayerListMixin implements PlayerListBridge { @Redirect(method = "placeNewPlayer", at = @At(value = "INVOKE", - target = "Lnet/minecraft/server/players/PlayerList;load(Lnet/minecraft/server/level/ServerPlayer;)Lnet/minecraft/nbt/CompoundTag;" + target = "Lnet/minecraft/server/players/PlayerList;load(Lnet/minecraft/server/level/ServerPlayer;)Ljava/util/Optional;" ) ) - private CompoundTag impl$setPlayerDataForNewPlayers(final PlayerList playerList, final net.minecraft.server.level.ServerPlayer playerIn) { - final CompoundTag compound = this.shadow$load(playerIn); - if (compound == null) { + private Optional impl$setPlayerDataForNewPlayers(final PlayerList playerList, final net.minecraft.server.level.ServerPlayer playerIn) { + final Optional compound = this.shadow$load(playerIn); + if (compound.isEmpty()) { ((SpongeServer) SpongeCommon.server()).getPlayerDataManager().setPlayerInfo(playerIn.getUUID(), Instant.now(), Instant.now()); } return compound; @@ -628,7 +626,7 @@ public abstract class PlayerListMixin implements PlayerListBridge { final Component sender = SpongeAdventure.asAdventure($$4.name()); final Component target = $$4.targetName() == null ? null : SpongeAdventure.asAdventure($$4.targetName()); final Registry chatTypeRegistry = SpongeCommon.vanillaRegistry(Registries.CHAT_TYPE); - final var chatType = RegistryTypes.CHAT_TYPE.defaultReferenced((org.spongepowered.api.ResourceKey) (Object) chatTypeRegistry.getKey($$4.chatType())); + final var chatType = RegistryTypes.CHAT_TYPE.defaultReferenced((org.spongepowered.api.ResourceKey) (Object) chatTypeRegistry.getKey($$4.chatType().value())); final Predicate filter; final ChatType.Bound boundChatType; From 6435e52c6a0aa16b9993e07548b956d961ecac60 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 28 Feb 2024 18:20:25 +0100 Subject: [PATCH 087/230] fix damage --- .../common/util/DamageEventUtil.java | 43 +++++-------------- .../core/world/entity/LivingEntityMixin.java | 3 +- .../mixin/core/world/entity/MobMixin.java | 2 +- .../player/PlayerMixin_Attack_Impl.java | 5 +-- 4 files changed, 14 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/spongepowered/common/util/DamageEventUtil.java b/src/main/java/org/spongepowered/common/util/DamageEventUtil.java index 8d6d2ae625f..84e46ef8536 100644 --- a/src/main/java/org/spongepowered/common/util/DamageEventUtil.java +++ b/src/main/java/org/spongepowered/common/util/DamageEventUtil.java @@ -25,23 +25,20 @@ package org.spongepowered.common.util; import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.ListTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.component.DataComponents; import net.minecraft.tags.DamageTypeTags; import net.minecraft.util.Mth; import net.minecraft.world.damagesource.CombatRules; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.ItemEnchantments; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.LevelChunk; @@ -60,7 +57,6 @@ import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.accessor.world.entity.LivingEntityAccessor; import org.spongepowered.common.bridge.CreatorTrackedBridge; import org.spongepowered.common.bridge.world.damagesource.DamageSourceBridge; @@ -68,11 +64,8 @@ import org.spongepowered.common.item.util.ItemStackUtil; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.function.DoubleUnaryOperator; import java.util.function.Predicate; @@ -223,46 +216,30 @@ public static void generateCauseFor(final DamageSource damageSource, final Cause } public static List createAttackEnchantmentFunction(final net.minecraft.world.item.ItemStack heldItem, - final MobType creatureAttribute, final float attackStrength) { + final EntityType entityType, final float attackStrength) { if (heldItem.isEmpty()) { return Collections.emptyList(); } - final ListTag enchantmentCompounds = heldItem.getEnchantmentTags(); + final ItemEnchantments enchantmentCompounds = heldItem.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY); if (enchantmentCompounds.isEmpty()) { return Collections.emptyList(); } - final Map> enchantments = new HashMap<>(); - - for (int i = 0; i < enchantmentCompounds.size(); ++i) { - final String id = enchantmentCompounds.getCompound(i).getString("id"); - final int enchantmentLevel = enchantmentCompounds.getCompound(i).getInt("lvl"); - - final Registry enchantmentRegistry = SpongeCommon.vanillaRegistry(Registries.ENCHANTMENT); - final Enchantment enchantment = enchantmentRegistry.get(new ResourceLocation(id)); - if (enchantment != null) { - enchantments.computeIfAbsent(enchantment, k -> new ArrayList<>()).add(enchantmentLevel); - } - } - - if (enchantments.isEmpty()) { - return Collections.emptyList(); - } - final List damageModifierFunctions = new ArrayList<>(); final ItemStackSnapshot snapshot = ItemStackUtil.snapshotOf(heldItem); - for (final Map.Entry> enchantment : enchantments.entrySet()) { + for (final var entry : enchantmentCompounds.entrySet()) { + final var enchantment = entry.getKey().value(); + final int level = entry.getIntValue(); + final DamageModifier enchantmentModifier = DamageModifier.builder() .type(DamageModifierTypes.WEAPON_ENCHANTMENT) .cause(Cause.of(EventContext.empty(), snapshot, enchantment)) .build(); final DoubleUnaryOperator enchantmentFunction = (damage) -> { double totalDamage = 0; - for (final int level : enchantment.getValue()) { - totalDamage += (double) enchantment.getKey().getDamageBonus(level, creatureAttribute) * attackStrength; - } + totalDamage += enchantment.getDamageBonus(level, entityType) * attackStrength; return totalDamage; }; damageModifierFunctions.add(new DamageFunction(enchantmentModifier, enchantmentFunction)); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java index b69950328da..f72bbad0f23 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.entity; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; @@ -112,7 +113,7 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt @Shadow @Nullable private DamageSource lastDamageSource; @Shadow private long lastDamageStamp; - @Shadow public abstract AttributeInstance shadow$getAttribute(Attribute attribute); + @Shadow public abstract AttributeInstance shadow$getAttribute(Holder attribute); @Shadow public abstract void shadow$setHealth(float health); @Shadow public abstract void shadow$setAbsorptionAmount(float amount); @Shadow public abstract void shadow$setItemInHand(InteractionHand hand, @Nullable ItemStack stack); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java index 95c0c0c3623..057494399a9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java @@ -216,7 +216,7 @@ public boolean doHurtTarget(final net.minecraft.world.entity.Entity targetEntity if (targetEntity instanceof LivingEntity) { // Sponge Start - Gather modifiers originalFunctions.addAll(DamageEventUtil - .createAttackEnchantmentFunction(this.shadow$getMainHandItem(), ((LivingEntity) targetEntity).getMobType(), 1.0F)); // 1.0F is for full attack strength since mobs don't have the concept + .createAttackEnchantmentFunction(this.shadow$getMainHandItem(), targetEntity.getType(), 1.0F)); // 1.0F is for full attack strength since mobs don't have the concept // baseDamage += EnchantmentHelper.getModifierForCreature(this.getHeldItem(), ((EntityLivingBase) targetEntity).getCreatureAttribute()); knockbackModifier += EnchantmentHelper.getKnockbackBonus((Mob) (Object) this); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java index 7ea13205d78..0de24b8baa4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java @@ -150,11 +150,8 @@ public void attack(final Entity targetEntity) { final List originalFunctions = new ArrayList<>(); - final MobType creatureAttribute = targetEntity instanceof LivingEntity - ? ((LivingEntity) targetEntity).getMobType() - : MobType.UNDEFINED; final List enchantmentModifierFunctions = DamageEventUtil - .createAttackEnchantmentFunction(this.shadow$getMainHandItem(), creatureAttribute, attackStrength); + .createAttackEnchantmentFunction(this.shadow$getMainHandItem(), targetEntity.getType(), attackStrength); // This is kept for the post-damage event handling final List enchantmentModifiers = enchantmentModifierFunctions.stream() .map(ModifierFunction::modifier) From 3f91049ed8aaf3118c7d60c15e0e812136bff427 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 21:12:34 +0100 Subject: [PATCH 088/230] fix player attack --- .../core/world/entity/player/PlayerMixin_Attack_Impl.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java index 0de24b8baa4..5eef830afb3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java @@ -36,7 +36,6 @@ import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.decoration.ArmorStand; import net.minecraft.world.entity.player.Player; @@ -186,7 +185,7 @@ public void attack(final Entity targetEntity) { } isCriticalAttack = isStrongAttack && this.fallDistance > 0.0F && !this.shadow$onGround() && !this.shadow$onClimbable() && !this.shadow$isInWater() && !this.shadow$hasEffect( - MobEffects.BLINDNESS) && !this.shadow$isPassenger() && targetEntity instanceof LivingEntity; + MobEffects.BLINDNESS.value()) && !this.shadow$isPassenger() && targetEntity instanceof LivingEntity; isCriticalAttack = isCriticalAttack && !this.shadow$isSprinting(); final EventHooks.CriticalHitResult criticalResult = PlatformHooks.INSTANCE.getEventHooks().callCriticalHitEvent((net.minecraft.world.entity.player.Player) (Object) this, targetEntity, isCriticalAttack, isCriticalAttack ? 0.5F : 0.0F); isCriticalAttack = criticalResult.criticalHit; @@ -245,7 +244,7 @@ public void attack(final Entity targetEntity) { if (fireAspectModifier > 0 && !targetEntity.isOnFire()) { litEntityOnFire = true; - targetEntity.setSecondsOnFire(1); + targetEntity.igniteForSeconds(1); } } @@ -378,7 +377,7 @@ public void attack(final Entity targetEntity) { this.shadow$awardStat(Stats.DAMAGE_DEALT, Math.round(f5 * 10.0F)); if (fireAspectModifier > 0) { - targetEntity.setSecondsOnFire(fireAspectModifier * 4); + targetEntity.igniteForSeconds(fireAspectModifier * 4); } if (this.shadow$level() instanceof ServerWorld && f5 > 2.0F) { From 54bcec9e118243321a645966474d61115b8d6d53 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 22:44:31 +0100 Subject: [PATCH 089/230] fix LivingEntity/attack mixins --- .../common/mixin/core/world/entity/LivingEntityMixin.java | 4 ++-- .../core/world/entity/LivingEntityMixin_Attack_impl.java | 3 ++- .../core/world/entity/player/PlayerMixin_Attack_Impl.java | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java index f72bbad0f23..7768e4e6173 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin.java @@ -121,7 +121,7 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt @Shadow public abstract int shadow$getUseItemRemainingTicks(); @Shadow public abstract float shadow$getAbsorptionAmount(); @Shadow public abstract float shadow$getHealth(); - @Shadow public abstract boolean shadow$hasEffect(MobEffect potion); + @Shadow public abstract boolean shadow$hasEffect(Holder potion); @Shadow public abstract ItemStack shadow$getItemBySlot(EquipmentSlot slotIn); @Shadow public abstract ItemStack shadow$getMainHandItem(); @Shadow public abstract CombatTracker shadow$getCombatTracker(); @@ -219,7 +219,7 @@ public abstract class LivingEntityMixin extends EntityMixin implements LivingEnt // without using our mixin redirects in EntityFallingBlockMixin. if ((damageSource.getDirectEntity() instanceof FallingBlock || damageSource.is(DamageTypeTags.DAMAGES_HELMET)) && !helmet.isEmpty()) { helmet.hurtAndBreak((int) (event.baseDamage() * 4.0F + this.random.nextFloat() * event.baseDamage() * 2.0F), - (LivingEntity) (Object) this, (entity) -> entity.broadcastBreakEvent(EquipmentSlot.HEAD) + (LivingEntity) (Object) this, EquipmentSlot.HEAD ); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_impl.java index 760baef8879..50b31eff002 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/LivingEntityMixin_Attack_impl.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.entity; import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.core.Holder; import net.minecraft.sounds.SoundEvent; import net.minecraft.stats.Stats; import net.minecraft.tags.DamageTypeTags; @@ -66,7 +67,7 @@ public abstract class LivingEntityMixin_Attack_impl extends EntityMixin @Shadow @Nullable protected Player lastHurtByPlayer; @Shadow private long lastDamageStamp; - @Shadow public abstract boolean shadow$hasEffect(MobEffect param0); + @Shadow public abstract boolean shadow$hasEffect(Holder param0); @Shadow public abstract boolean shadow$isSleeping(); @Shadow public abstract void shadow$stopSleeping(); @Shadow public abstract boolean shadow$isDamageSourceBlocked(DamageSource param0); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java index 5eef830afb3..d9b18706866 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin_Attack_Impl.java @@ -185,7 +185,7 @@ public void attack(final Entity targetEntity) { } isCriticalAttack = isStrongAttack && this.fallDistance > 0.0F && !this.shadow$onGround() && !this.shadow$onClimbable() && !this.shadow$isInWater() && !this.shadow$hasEffect( - MobEffects.BLINDNESS.value()) && !this.shadow$isPassenger() && targetEntity instanceof LivingEntity; + MobEffects.BLINDNESS) && !this.shadow$isPassenger() && targetEntity instanceof LivingEntity; isCriticalAttack = isCriticalAttack && !this.shadow$isSprinting(); final EventHooks.CriticalHitResult criticalResult = PlatformHooks.INSTANCE.getEventHooks().callCriticalHitEvent((net.minecraft.world.entity.player.Player) (Object) this, targetEntity, isCriticalAttack, isCriticalAttack ? 0.5F : 0.0F); isCriticalAttack = criticalResult.criticalHit; From e2096c187ff225789be323e2e4e05be449f897d6 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 2 Mar 2024 23:13:09 +0100 Subject: [PATCH 090/230] fix attack MobMixin TODO unsure about shield code --- .../common/mixin/core/world/entity/MobMixin.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java index 057494399a9..dde130c923a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java @@ -78,7 +78,6 @@ public abstract class MobMixin extends LivingEntityMixin { @Shadow @Nullable private LivingEntity target; @Shadow public abstract net.minecraft.world.entity.@Nullable Entity shadow$getLeashHolder(); @Shadow protected abstract void shadow$registerGoals(); - @Shadow protected abstract void shadow$maybeDisableShield(Player p_233655_1_, ItemStack p_233655_2_, ItemStack p_233655_3_); // @formatter:on @@ -245,14 +244,7 @@ public boolean doHurtTarget(final net.minecraft.world.entity.Entity targetEntity final int j = EnchantmentHelper.getFireAspect((Mob) (Object) this); if (j > 0) { - targetEntity.setSecondsOnFire(j * 4); - } - - if (targetEntity instanceof Player) { - final Player playerentity = (Player) targetEntity; - final ItemStack mainHandItem = this.shadow$getMainHandItem(); - final ItemStack useItem = playerentity.isUsingItem() ? playerentity.getUseItem() : ItemStack.EMPTY; - this.shadow$maybeDisableShield(playerentity, mainHandItem, useItem); + targetEntity.igniteForSeconds(j * 4); } this.shadow$doEnchantDamageEffects((Mob) (Object) this, targetEntity); From 6e23584f479a749aa221802400ebbffb0e7ff6c9 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 14:24:35 +0100 Subject: [PATCH 091/230] fix network packet ServerScoreboardMixin --- .../common/mixin/core/server/ServerScoreboardMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/ServerScoreboardMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/ServerScoreboardMixin.java index b9dc29ee5d9..00a9ab4125e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/ServerScoreboardMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/ServerScoreboardMixin.java @@ -203,8 +203,8 @@ public abstract class ServerScoreboardMixin extends Scoreboard implements Server score.owner(), objective.getName(), score.value(), - score.display(), - score.numberFormatOverride()); + Optional.ofNullable(score.display()), + Optional.ofNullable(score.numberFormatOverride())); player.connection.send(packetIn); } } From 7a7eb6a078e50e41ee9366d1df8bf07a8149c3fb Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 18:03:24 +0100 Subject: [PATCH 092/230] fix raw level access ServerLevelMixin --- .../mixin/api/minecraft/server/level/ServerLevelMixin_API.java | 3 ++- .../common/mixin/api/minecraft/world/level/LevelMixin_API.java | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java index cde40bb5ee6..c1d9d0ef8d9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerLevelMixin_API.java @@ -40,6 +40,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.storage.RegionFile; +import net.minecraft.world.level.chunk.storage.RegionStorageInfo; import net.minecraft.world.level.entity.PersistentEntitySectionManager; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.storage.LevelResource; @@ -348,7 +349,7 @@ public ChunkManager chunkManager() { .flatMap(stream -> StreamSupport.stream(stream.spliterator(), false) .flatMap(path -> { try { // For every region file - RegionFile regionFile = new RegionFile(path, regionPath, true); + RegionFile regionFile = new RegionFile(new RegionStorageInfo("sponge:chunkPosStream:" + this.shadow$dimension(), this.shadow$dimension(), "chunk"), path, regionPath, true); final Vector4i regionBound = this.api$pathToRegionPos(path); // Find all chunks in bounds final Stream chunkPosStream = IntStream.rangeClosed(regionBound.x(), regionBound.z()) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index 081721e129b..154c9c189c0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -135,7 +135,6 @@ public abstract class LevelMixin_API, L extends Location entityTypeTest, net.minecraft.world.phys.AABB param1, @Nullable Predicate param2); - @Shadow public abstract ResourceKey dimension(); // @formatter:on From f640f57b572a46c14d86779b5bf58b9fce8b2121 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 15:53:44 +0100 Subject: [PATCH 093/230] fix ServerPlayerMixin_HealthScale --- .../mixin/core/server/level/ServerPlayerMixin_HealthScale.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin_HealthScale.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin_HealthScale.java index df8999315f1..717bf7212b2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin_HealthScale.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ServerPlayerMixin_HealthScale.java @@ -123,7 +123,7 @@ private void updateHealthPriorToArmor(final CallbackInfo ci) { boolean foundMax = false; // Sometimes the max health isn't modified and no longer dirty for (final Iterator iter = set.iterator(); iter.hasNext(); ) { final AttributeInstance dirtyInstance = iter.next(); - if ("attribute.name.generic.maxHealth".equals(dirtyInstance.getAttribute().getDescriptionId())) { + if ("attribute.name.generic.maxHealth".equals(dirtyInstance.getAttribute().value().getDescriptionId())) { foundMax = true; attribute = dirtyInstance; iter.remove(); From 2216b60f0ccce92b44792706256ae4dedc33a823 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 18:04:33 +0100 Subject: [PATCH 094/230] fix network Player resourcepack sending --- .../mixin/api/minecraft/server/level/ServerPlayerMixin_API.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java index 690b8445e5a..7215790fc65 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java @@ -274,7 +274,7 @@ public void stopMusicDisc(final Vector3i position) { public void sendResourcePack(final ResourcePack pack) { Objects.requireNonNull(pack, "pack"); final UUID uuid = UUID.nameUUIDFromBytes(pack.name().getBytes(StandardCharsets.UTF_8)); - this.connection.send(new ClientboundResourcePackPushPacket(uuid, ((SpongeResourcePack) pack).getUrlString(), pack.hash().orElse(""), false, SpongeAdventure.asVanilla(pack.prompt()))); + this.connection.send(new ClientboundResourcePackPushPacket(uuid, ((SpongeResourcePack) pack).getUrlString(), pack.hash().orElse(""), false, Optional.ofNullable(SpongeAdventure.asVanilla(pack.prompt())))); } @Override From 933e159110219f6e43e3678599bec08f1563e81d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 22:06:09 +0100 Subject: [PATCH 095/230] fix network ServerHandshakePacketListenerImplMixin_IpForward --- .../ServerHandshakePacketListenerImplMixin_IpForward.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/ipforward/server/network/ServerHandshakePacketListenerImplMixin_IpForward.java b/src/mixins/java/org/spongepowered/common/mixin/ipforward/server/network/ServerHandshakePacketListenerImplMixin_IpForward.java index 915f203aeeb..00a560bf989 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/ipforward/server/network/ServerHandshakePacketListenerImplMixin_IpForward.java +++ b/src/mixins/java/org/spongepowered/common/mixin/ipforward/server/network/ServerHandshakePacketListenerImplMixin_IpForward.java @@ -33,6 +33,7 @@ import net.minecraft.network.protocol.handshake.ClientIntent; import net.minecraft.network.protocol.handshake.ClientIntentionPacket; import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; +import net.minecraft.network.protocol.login.LoginProtocols; import net.minecraft.server.network.ServerHandshakePacketListenerImpl; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -73,7 +74,7 @@ public abstract class ServerHandshakePacketListenerImplMixin_IpForward { ServerHandshakePacketListenerImplMixin_IpForward.ipForward$GSON.fromJson(split[3], Property[].class)); } } else { - this.connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN); + this.connection.setupOutboundProtocol(LoginProtocols.CLIENTBOUND); final Component error = Component.literal("If you wish to use IP forwarding, please enable it in your BungeeCord config as well!") .withStyle(ChatFormatting.RED); this.connection.send(new ClientboundLoginDisconnectPacket(error)); From 27ade905b0ee6201eacd58432adfe00bcdb5ba48 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 22:27:17 +0100 Subject: [PATCH 096/230] TODO fix adventure binary tag holder --- .../mixin/api/minecraft/world/item/ItemStackMixin_API.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java index d4cd0b6dc2a..999d5a5cbb1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java @@ -199,7 +199,7 @@ public Component asComponent() { final HoverEvent.ShowItem event = HoverEvent.ShowItem.of( SpongeAdventure.asAdventure(SpongeCommon.vanillaRegistry(Registries.ITEM).getKey(this.shadow$getItem())), this.shadow$getCount(), - SpongeAdventure.asBinaryTagHolder(this.shadow$getTag()) + null // TODO requires adventure change SpongeAdventure.asBinaryTagHolder(this.shadow$getTag()) ); return HoverEvent.showItem(Objects.requireNonNull(op, "op").apply(event)); } From d07682e31ef1214325474444c679bbde7da96e08 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 22:53:37 +0100 Subject: [PATCH 097/230] fix itemstack TODO equipmentslotgroup handling? --- .../common/adventure/SpongeAdventure.java | 8 ++- .../common/item/SpongeItemStack.java | 21 +++--- .../common/item/SpongeItemStackSnapshot.java | 6 +- .../world/item/ItemStackMixin_API.java | 67 ++++++++++++------- 4 files changed, 59 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java index 0142749b46d..87403aab4b4 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java @@ -64,6 +64,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; +import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -734,12 +735,13 @@ public static Set asAdventureFlags(final boolean darkenScreen, fin } } - public static @Nullable BinaryTagHolder asBinaryTagHolder(final @Nullable CompoundTag tag) { - if (tag == null) { + public static @Nullable BinaryTagHolder asBinaryTagHolder(final DataComponentMap components) { + if (components == null) { return null; } try { - return BinaryTagHolder.encode(tag, SpongeAdventure.NBT_CODEC); + // TODO requires Adventure Change + return BinaryTagHolder.encode(null, SpongeAdventure.NBT_CODEC); } catch (final IOException e) { return null; } diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java index 786ad2e458b..49d7d0e3a35 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java @@ -37,7 +37,6 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.JavaOps; import net.minecraft.world.entity.EquipmentSlot; @@ -391,20 +390,20 @@ public static Optional createItemStack(final DataView container) { .orElseThrow(() -> new IllegalStateException("Unable to find item with id: ")); final var mcStack = new net.minecraft.world.item.ItemStack((Item) itemType, count); if (!mcStack.isEmpty()) { // ignore components when the stack is empty anyways - // TODO v3 Data - container.getView(Constants.ItemStack.COMPONENTS).ifPresent(components -> { - final CompoundTag compound = NBTTranslator.INSTANCE.translate(components); - // TODO check if enchantment-data is still broken - // BuilderImpl.fixEnchantmentData(itemType, compound); - - final DataResult> decoded = DataComponentPatch.CODEC.decode(NbtOps.INSTANCE, compound); - // TODO handle errors? e.g. missing custom DataComponentType - decoded.result().map(Pair::getFirst).ifPresent(mcStack::applyComponents); - }); + mcStack.applyComponents(SpongeItemStack.patchFromData(container)); } return Optional.of((ItemStack) (Object) mcStack); } + public static DataComponentPatch patchFromData(final DataView container) { + // TODO update data? + return container.getView(Constants.ItemStack.COMPONENTS).flatMap(components -> { + final CompoundTag compound = NBTTranslator.INSTANCE.translate(components); + // TODO check if enchantment-data is still broken + // BuilderImpl.fixEnchantmentData(itemType, compound); + return DataComponentPatch.CODEC.decode(NbtOps.INSTANCE, compound).result().map(Pair::getFirst); + }).orElse(DataComponentPatch.EMPTY); + } } diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java b/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java index c3fc52a7006..808012842b7 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStackSnapshot.java @@ -44,6 +44,7 @@ import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.registry.RegistryTypes; +import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.data.SpongeDataHolderBridge; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.util.Constants; @@ -283,9 +284,6 @@ public int hashCode() { @Override public HoverEvent asHoverEvent(final UnaryOperator op) { final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.ITEM_TYPE).valueKey(this.itemType); - // TODO requires adventure change -// final CompoundTag tag = this.getComponents().orElse(null); -// return HoverEvent.showItem(op.apply(HoverEvent.ShowItem.of(resourceKey, this.quantity(), SpongeAdventure.asBinaryTagHolder(tag)))); - return null; + return HoverEvent.showItem(op.apply(HoverEvent.ShowItem.of(resourceKey, this.quantity(), SpongeAdventure.asBinaryTagHolder(this.getComponents())))); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java index 999d5a5cbb1..c8ffb7bce77 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java @@ -25,21 +25,24 @@ package org.spongepowered.common.mixin.api.minecraft.world.item; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Multimap; -import com.mojang.serialization.DataResult; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEventSource; +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.EquipmentSlotGroup; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.item.Item; +import net.minecraft.world.item.Rarity; +import net.minecraft.world.item.component.ItemAttributeModifiers; +import net.minecraft.world.item.enchantment.Enchantment; import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; import org.spongepowered.api.data.SerializableDataHolder; import org.spongepowered.api.data.persistence.DataContainer; @@ -60,15 +63,15 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; -import org.spongepowered.common.data.persistence.NBTTranslator; import org.spongepowered.common.item.SpongeItemStack; import org.spongepowered.common.item.SpongeItemStackSnapshot; -import org.spongepowered.common.util.Constants; import java.util.Collection; import java.util.Objects; import java.util.function.UnaryOperator; +import javax.annotation.Nullable; + @Mixin(net.minecraft.world.item.ItemStack.class) @Implements(@Interface(iface = ItemStack.class, prefix = "itemStack$", remap = Remap.NONE)) // We need to soft implement this interface due to a synthetic bridge method public abstract class ItemStackMixin_API implements SerializableDataHolder.Mutable, ComponentLike, HoverEventSource { // conflict from overriding ValueContainer#copy() from DataHolder @@ -78,18 +81,21 @@ public abstract class ItemStackMixin_API implements SerializableDataHolder.Mutab @Shadow public abstract int shadow$getCount(); @Shadow public abstract void shadow$setCount(int size); // Do not use field directly as Minecraft tracks the empty state - @Shadow public abstract void shadow$setDamageValue(int meta); - @Shadow public abstract int shadow$getDamageValue(); @Shadow public abstract int shadow$getMaxStackSize(); @Shadow public abstract boolean shadow$isEmpty(); @Shadow public abstract net.minecraft.world.item.ItemStack shadow$copy(); @Shadow public abstract Item shadow$getItem(); - @Shadow public abstract Multimap shadow$getAttributeModifiers(EquipmentSlot equipmentSlot); - @Shadow public abstract void shadow$addAttributeModifier(Attribute attribute, net.minecraft.world.entity.ai.attributes.AttributeModifier modifier, @Nullable EquipmentSlot equipmentSlot); - @Shadow public abstract String shadow$getDescriptionId(); @Shadow public abstract net.minecraft.network.chat.Component shadow$getDisplayName(); + @Shadow public abstract void shadow$applyComponents(final DataComponentPatch $$0); + @Shadow public abstract DataComponentMap shadow$getComponents(); + @Shadow @Nullable public abstract T shadow$update(final DataComponentType $$0, final T $$1, final UnaryOperator $$2); + // @formatter:on + @Shadow public abstract void enchant(final Enchantment $$0, final int $$1); + + @Shadow public abstract Rarity getRarity(); + public int itemStack$quantity() { return this.shadow$getCount(); } @@ -119,16 +125,9 @@ public void setRawData(final DataView container) throws InvalidDataException { if (this.shadow$isEmpty()) { throw new IllegalArgumentException("Cannot set data on empty item stacks!"); } - if (!container.contains(Constants.Sponge.UNSAFE_NBT)) { - throw new InvalidDataException("There's no NBT Data set in the provided container"); - } - final DataView nbtData = container.getView(Constants.Sponge.UNSAFE_NBT).get(); + try { - final int integer = container.getInt(Constants.ItemStack.V2.DAMAGE_VALUE).orElse(this.shadow$getDamageValue()); - this.shadow$setDamageValue(integer); - final CompoundTag stackCompound = NBTTranslator.INSTANCE.translate(nbtData); - final DataResult parse = DataComponentPatch.CODEC.parse(NbtOps.INSTANCE, stackCompound); - this.shadow$setTag(stackCompound); + this.shadow$applyComponents(SpongeItemStack.patchFromData(container)); } catch (final Exception e) { throw new InvalidDataException("Unable to set raw data or translate raw data for ItemStack setting", e); } @@ -149,8 +148,12 @@ public SerializableDataHolder.Mutable copy() { final ImmutableList.Builder builder = ImmutableList.builder(); - final Multimap modifierMultimap = this.shadow$getAttributeModifiers(((EquipmentSlot) (Object) equipmentType)); - builder.addAll((Iterable) modifierMultimap.get(((Attribute) attributeType))); + final var modifiers = ((net.minecraft.world.item.ItemStack) (Object) this).getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY); + for (final ItemAttributeModifiers.Entry entry : modifiers.modifiers()) { + if (entry.attribute().value().equals(attributeType) && entry.slot().test(((EquipmentSlot) (Object) equipmentType))) { + builder.add((AttributeModifier) entry.modifier()); + } + } return builder.build(); } @@ -160,7 +163,21 @@ public SerializableDataHolder.Mutable copy() { Objects.requireNonNull(modifier, "Attribute modifier cannot be null"); Objects.requireNonNull(equipmentType, "Equipment type cannot be null"); - this.shadow$addAttributeModifier((Attribute) attributeType, (net.minecraft.world.entity.ai.attributes.AttributeModifier) modifier, ((EquipmentSlot) (Object) equipmentType)); + // TODO expose EquipmentSlotGroup? + var group = switch (((EquipmentSlot) (Object) equipmentType)) { + case MAINHAND -> EquipmentSlotGroup.MAINHAND; + case OFFHAND -> EquipmentSlotGroup.OFFHAND; + case FEET -> EquipmentSlotGroup.FEET; + case LEGS -> EquipmentSlotGroup.LEGS; + case CHEST -> EquipmentSlotGroup.CHEST; + case HEAD -> EquipmentSlotGroup.HEAD; + case BODY -> EquipmentSlotGroup.ANY; // TODO no mapping + }; + + this.shadow$update(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY, component -> + component.withModifierAdded(Holder.direct((Attribute) attributeType), + (net.minecraft.world.entity.ai.attributes.AttributeModifier) modifier, + group)); } @Override @@ -199,7 +216,7 @@ public Component asComponent() { final HoverEvent.ShowItem event = HoverEvent.ShowItem.of( SpongeAdventure.asAdventure(SpongeCommon.vanillaRegistry(Registries.ITEM).getKey(this.shadow$getItem())), this.shadow$getCount(), - null // TODO requires adventure change SpongeAdventure.asBinaryTagHolder(this.shadow$getTag()) + SpongeAdventure.asBinaryTagHolder(this.shadow$getComponents()) ); return HoverEvent.showItem(Objects.requireNonNull(op, "op").apply(event)); } From afd3041c102e870071a246dcbf9f811ec9113aa5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sun, 3 Mar 2024 23:04:22 +0100 Subject: [PATCH 098/230] fix hoverevent TODO needs adventure change --- .../HoverEvent_ItemStackInfoAccessor.java | 16 +----- .../common/adventure/SpongeAdventure.java | 56 ++++++++++--------- 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/network/chat/HoverEvent_ItemStackInfoAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/network/chat/HoverEvent_ItemStackInfoAccessor.java index 459dd397dff..14c89652187 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/network/chat/HoverEvent_ItemStackInfoAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/network/chat/HoverEvent_ItemStackInfoAccessor.java @@ -24,29 +24,19 @@ */ package org.spongepowered.common.accessor.network.chat; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.network.chat.HoverEvent; import net.minecraft.world.item.Item; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedInvokerError; -import java.util.Optional; - @Mixin(HoverEvent.ItemStackInfo.class) public interface HoverEvent_ItemStackInfoAccessor { @Invoker("") - static HoverEvent.ItemStackInfo invoker$new(final Item item, final int count, final @Nullable CompoundTag tag) { + static HoverEvent.ItemStackInfo invoker$new(final Holder item, final int count, final DataComponentPatch patch) { throw new UntransformedInvokerError(); } - - @Accessor("item") Item accessor$item(); - - @Accessor("count") int accessor$count(); - - @Accessor("tag") Optional accessor$tag(); - } diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java index 87403aab4b4..8694bc5ea71 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java @@ -62,9 +62,11 @@ import net.kyori.adventure.util.Codec; import net.kyori.adventure.util.TriState; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -72,6 +74,8 @@ import net.minecraft.nbt.TagParser; import net.minecraft.network.chat.ChatType; import net.minecraft.network.chat.ComponentContents; +import net.minecraft.network.chat.HoverEvent.Action; +import net.minecraft.network.chat.HoverEvent.ItemStackInfo; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.contents.BlockDataSource; import net.minecraft.network.chat.contents.EntityDataSource; @@ -89,6 +93,7 @@ import net.minecraft.world.BossEvent; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.adventure.ResolveOperation; @@ -497,26 +502,26 @@ public static ChatType.Bound asVanilla(final MessageType type, final RegistryAcc @SuppressWarnings("ConstantConditions") public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEvent event) { - final net.minecraft.network.chat.HoverEvent.Action action = event.getAction(); - if (action == net.minecraft.network.chat.HoverEvent.Action.SHOW_TEXT) { - return HoverEvent.showText(SpongeAdventure.asAdventure(event.getValue(net.minecraft.network.chat.HoverEvent.Action.SHOW_TEXT))); - } else if (action == net.minecraft.network.chat.HoverEvent.Action.SHOW_ENTITY) { + final Action action = event.getAction(); + if (action == Action.SHOW_TEXT) { + return HoverEvent.showText(SpongeAdventure.asAdventure(event.getValue(Action.SHOW_TEXT))); + } else if (action == Action.SHOW_ENTITY) { final net.minecraft.network.chat.HoverEvent.EntityTooltipInfo value = event.getValue( - net.minecraft.network.chat.HoverEvent.Action.SHOW_ENTITY); + Action.SHOW_ENTITY); final Registry> entityTypeRegistry = SpongeCommon.vanillaRegistry(Registries.ENTITY_TYPE); return HoverEvent.showEntity( SpongeAdventure.asAdventure(entityTypeRegistry.getKey(value.type)), value.id, SpongeAdventure.asAdventure(value.name) ); - } else if (action == net.minecraft.network.chat.HoverEvent.Action.SHOW_ITEM) { - final net.minecraft.network.chat.HoverEvent.ItemStackInfo value = event.getValue( - net.minecraft.network.chat.HoverEvent.Action.SHOW_ITEM); + } else if (action == Action.SHOW_ITEM) { + final ItemStackInfo value = event.getValue(Action.SHOW_ITEM); final Registry itemRegistry = SpongeCommon.vanillaRegistry(Registries.ITEM); + final ItemStack itemStack = value.getItemStack(); return HoverEvent.showItem( - SpongeAdventure.asAdventure(itemRegistry.getKey(((HoverEvent_ItemStackInfoAccessor) value).accessor$item())), - ((HoverEvent_ItemStackInfoAccessor) value).accessor$count(), - SpongeAdventure.asBinaryTagHolder(((HoverEvent_ItemStackInfoAccessor) value).accessor$tag().orElse(null)) + SpongeAdventure.asAdventure(itemRegistry.getKey(itemStack.getItem())), + itemStack.getCount(), + SpongeAdventure.asBinaryTagHolder(itemStack.getComponents()) ); } throw new IllegalArgumentException(event.toString()); @@ -536,14 +541,14 @@ public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEv final HoverEvent.Action action = event.action(); if (action == HoverEvent.Action.SHOW_TEXT) { return new net.minecraft.network.chat.HoverEvent( - net.minecraft.network.chat.HoverEvent.Action.SHOW_TEXT, + Action.SHOW_TEXT, SpongeAdventure.asVanilla((Component) event.value()) ); } else if (action == HoverEvent.Action.SHOW_ENTITY) { final HoverEvent.ShowEntity value = (HoverEvent.ShowEntity) event.value(); final Registry> entityTypeRegistry = SpongeCommon.vanillaRegistry(Registries.ENTITY_TYPE); return new net.minecraft.network.chat.HoverEvent( - net.minecraft.network.chat.HoverEvent.Action.SHOW_ENTITY, + Action.SHOW_ENTITY, new net.minecraft.network.chat.HoverEvent.EntityTooltipInfo( entityTypeRegistry.get(SpongeAdventure.asVanilla(value.type())), value.id(), @@ -554,9 +559,9 @@ public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEv final HoverEvent.ShowItem value = (HoverEvent.ShowItem) event.value(); final Registry itemRegistry = SpongeCommon.vanillaRegistry(Registries.ITEM); return new net.minecraft.network.chat.HoverEvent( - net.minecraft.network.chat.HoverEvent.Action.SHOW_ITEM, + Action.SHOW_ITEM, HoverEvent_ItemStackInfoAccessor.invoker$new( - itemRegistry.get(SpongeAdventure.asVanilla(value.item())), + Holder.direct(itemRegistry.get(SpongeAdventure.asVanilla(value.item()))), value.count(), SpongeAdventure.asVanillaCompound(value.nbt()) ) @@ -565,13 +570,13 @@ public static HoverEvent asAdventure(final net.minecraft.network.chat.HoverEv throw new IllegalArgumentException(event.toString()); } - public static net.minecraft.network.chat.HoverEvent.Action asVanilla(final HoverEvent.Action action) { + public static Action asVanilla(final HoverEvent.Action action) { if (action == HoverEvent.Action.SHOW_TEXT) { - return net.minecraft.network.chat.HoverEvent.Action.SHOW_TEXT; + return Action.SHOW_TEXT; } else if (action == HoverEvent.Action.SHOW_ITEM) { - return net.minecraft.network.chat.HoverEvent.Action.SHOW_ITEM; + return Action.SHOW_ITEM; } else if (action == HoverEvent.Action.SHOW_ENTITY) { - return net.minecraft.network.chat.HoverEvent.Action.SHOW_ENTITY; + return Action.SHOW_ENTITY; } throw new IllegalArgumentException(action.toString()); } @@ -724,15 +729,16 @@ public static Set asAdventureFlags(final boolean darkenScreen, fin // NBT - public static @Nullable CompoundTag asVanillaCompound(final @Nullable BinaryTagHolder tag) { + public static @Nullable DataComponentPatch asVanillaCompound(final @Nullable BinaryTagHolder tag) { if (tag == null) { return null; } - try { - return tag.get(SpongeAdventure.NBT_CODEC); - } catch (final IOException e) { - return null; - } +// try { + // TODO requires Adventure Change tag.get(SpongeAdventure.NBT_CODEC); + return DataComponentPatch.EMPTY; +// } catch (final IOException e) { +// return null; +// } } public static @Nullable BinaryTagHolder asBinaryTagHolder(final DataComponentMap components) { From e444091d18fd6a9e43012bea3e8f2f21d54031cc Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 18:10:19 +0100 Subject: [PATCH 099/230] TODO custom packets --- ...boundCustomPayloadPacketMixin_Vanilla.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java index da171154d4b..91b20ec2029 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java @@ -42,25 +42,25 @@ public abstract class ServerboundCustomPayloadPacketMixin_Vanilla { @Shadow @Final private static int MAX_PAYLOAD_SIZE; // @formatter: on - @Inject(method = "readPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;"), cancellable = true) - private static void impl$onReadUnknownPayload(ResourceLocation id, FriendlyByteBuf buf, final CallbackInfoReturnable cir) { - int readableBytes = buf.readableBytes(); - if (readableBytes >= 0 && readableBytes <= ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE) { - final var payload = new FriendlyByteBuf(buf.readBytes(readableBytes)); - - cir.setReturnValue(new CustomPacketPayload() { - @Override - public void write(FriendlyByteBuf buf) { - buf.writeBytes(payload.copy()); - } - - @Override - public ResourceLocation id() { - return id; - } - }); - } else { - throw new IllegalArgumentException("Payload may not be larger than " + ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE + " bytes"); - } - } +// @Inject(method = "readPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;"), cancellable = true) +// private static void impl$onReadUnknownPayload(ResourceLocation id, FriendlyByteBuf buf, final CallbackInfoReturnable cir) { +// int readableBytes = buf.readableBytes(); +// if (readableBytes >= 0 && readableBytes <= ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE) { +// final var payload = new FriendlyByteBuf(buf.readBytes(readableBytes)); +// +// cir.setReturnValue(new CustomPacketPayload() { +// @Override +// public void write(FriendlyByteBuf buf) { +// buf.writeBytes(payload.copy()); +// } +// +// @Override +// public ResourceLocation id() { +// return id; +// } +// }); +// } else { +// throw new IllegalArgumentException("Payload may not be larger than " + ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE + " bytes"); +// } +// } } From cfdc4b8ed9050449a59f8360dc9b1c50a4e0654c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:01:50 +0100 Subject: [PATCH 100/230] fix easy mixin LivingEntityMixin_API --- .../minecraft/world/entity/LivingEntityMixin_API.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java index 75eccd8fcd1..c60a16077ea 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java @@ -24,9 +24,10 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.AttributeMap; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.entity.Entity; @@ -49,14 +50,16 @@ public abstract class LivingEntityMixin_API extends EntityMixin_API implements L // @formatter:off @Shadow public abstract float shadow$getHealth(); - @Shadow public abstract AttributeInstance shadow$getAttribute(net.minecraft.world.entity.ai.attributes.Attribute attribute); @Shadow public abstract boolean addEffect(MobEffectInstance p_195064_1_); + @Shadow public abstract AttributeMap shadow$getAttributes(); + // @formatter:on @Override public Optional attribute(final AttributeType type) { Objects.requireNonNull(type, "AttributeType cannot be null"); - return Optional.ofNullable((Attribute) this.shadow$getAttribute((net.minecraft.world.entity.ai.attributes.Attribute) type)); + + return Optional.ofNullable((Attribute) this.shadow$getAttributes().getInstance(Holder.direct((net.minecraft.world.entity.ai.attributes.Attribute) type))); } @Override From 96c359cabc2bae5bd6d715805317882912a97b7f Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:02:27 +0100 Subject: [PATCH 101/230] cleanup LivingEntityMixin_API --- .../mixin/api/minecraft/world/entity/LivingEntityMixin_API.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java index c60a16077ea..62e3d7baea8 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java @@ -50,7 +50,6 @@ public abstract class LivingEntityMixin_API extends EntityMixin_API implements L // @formatter:off @Shadow public abstract float shadow$getHealth(); - @Shadow public abstract boolean addEffect(MobEffectInstance p_195064_1_); @Shadow public abstract AttributeMap shadow$getAttributes(); // @formatter:on From efd23f0ba1d0904205c7425ead7df121cdb01403 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:03:49 +0100 Subject: [PATCH 102/230] fix LivingEntityMixin_Vanilla hurtAndBreak replaced lambda with slot --- .../mixin/core/world/entity/LivingEntityMixin_Vanilla.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Vanilla.java index 9416172edc8..2e1fe7088ab 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/world/entity/LivingEntityMixin_Vanilla.java @@ -37,7 +37,7 @@ public abstract class LivingEntityMixin_Vanilla extends EntityMixin_Vanilla { method = "updateFallFlying", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/item/ItemStack;hurtAndBreak(ILnet/minecraft/world/entity/LivingEntity;Ljava/util/function/Consumer;)V", + target = "Lnet/minecraft/world/item/ItemStack;hurtAndBreak(ILnet/minecraft/world/entity/LivingEntity;Lnet/minecraft/world/entity/EquipmentSlot;)V", shift = At.Shift.AFTER ) ) From 35511b10a663cd861aa1c23a12affd3c50eaa577 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:08:39 +0100 Subject: [PATCH 103/230] fix easy mixin BuiltInRegistriesMixin --- .../common/mixin/core/registries/BuiltInRegistriesMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java index 4629fc8e8ea..2cca8f0d1a0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java @@ -50,7 +50,7 @@ public abstract class BuiltInRegistriesMixin { @Shadow @Final private static Map> LOADERS; - @Inject(method = "lambda$static$18", at = @At(value = "FIELD", target = "Lnet/minecraft/world/item/crafting/RecipeSerializer;SHAPELESS_RECIPE:Lnet/minecraft/world/item/crafting/RecipeSerializer;")) + @Inject(method = "lambda$static$15", at = @At(value = "FIELD", target = "Lnet/minecraft/world/item/crafting/RecipeSerializer;SHAPELESS_RECIPE:Lnet/minecraft/world/item/crafting/RecipeSerializer;")) private static void impl$staticInitSpongeRecipeSerializers(final Registry $$0, final CallbackInfoReturnable cir) { final var serializer = SpongeRecipeSerializers.SPONGE_SPECIAL; From c78b01d75fe02c9b1c62ce97fa64f065659f64d4 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:09:44 +0100 Subject: [PATCH 104/230] fix registry MappedRegistryMixin_API --- .../mixin/api/minecraft/core/MappedRegistryMixin_API.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java index 9dc16501b4d..86db0c69b2f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java @@ -28,6 +28,7 @@ import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import org.checkerframework.checker.nullness.qual.Nullable; @@ -55,7 +56,7 @@ @Implements(@Interface(iface = Registry.class, prefix = "registry$", remap = Interface.Remap.NONE)) public abstract class MappedRegistryMixin_API implements Registry { - @Shadow public abstract Holder.Reference shadow$register(final net.minecraft.resources.ResourceKey $$0, final T $$1, final Lifecycle $$2); + @Shadow public abstract Holder.Reference shadow$register(final net.minecraft.resources.ResourceKey $$0, final T $$1, final RegistrationInfo $$2); @Shadow public abstract net.minecraft.resources.ResourceKey> shadow$key(); @Shadow @Nullable public abstract T shadow$get(@Nullable ResourceLocation var1); @@ -162,7 +163,7 @@ public Optional> register(final ResourceKey key, if (this.isDynamic()) { final net.minecraft.resources.ResourceKey mcKey = net.minecraft.resources.ResourceKey.create(this.shadow$key(), (ResourceLocation) (Object) key); - this.shadow$register(mcKey, value, Lifecycle.stable()); + this.shadow$register(mcKey, value, RegistrationInfo.BUILT_IN); return ((RegistryBridge) this).bridge$get(key); } return Optional.empty(); From f335d3afbb54fb21b4508a54cf3d139b65280a06 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:13:19 +0100 Subject: [PATCH 105/230] fix registry --- .../common/mixin/core/core/MappedRegistryMixin.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/core/MappedRegistryMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/core/MappedRegistryMixin.java index b8fbb1a0d9c..b4b0975ac12 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/core/MappedRegistryMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/core/MappedRegistryMixin.java @@ -27,6 +27,7 @@ import com.mojang.serialization.Lifecycle; import net.minecraft.core.Holder; import net.minecraft.core.MappedRegistry; +import net.minecraft.core.RegistrationInfo; import net.minecraft.core.Registry; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.registry.RegistryEntry; @@ -74,15 +75,15 @@ public abstract class MappedRegistryMixin implements RegistryBridge, Writa } - @Inject(method = "registerMapping", at = @At("TAIL")) - private void impl$cacheRegistryEntry(final int p_243537_1_, final net.minecraft.resources.ResourceKey p_243537_2_, final T p_243537_3_, - final Lifecycle p_243537_4_, final CallbackInfoReturnable> cir) { + @Inject(method = "register", at = @At("TAIL")) + private void impl$cacheRegistryEntry(final net.minecraft.resources.ResourceKey $$0, final T $$1, + final RegistrationInfo $$3, final CallbackInfoReturnable> cir) { final net.minecraft.resources.ResourceKey> resourceKey = ((MappedRegistry) (Object) this).key(); final ResourceKey root = (ResourceKey) (Object) ((ResourceKeyAccessor) resourceKey).accessor$registryName(); final ResourceKey location = (ResourceKey) (Object) resourceKey.location(); this.bridge$register(new SpongeRegistryEntry<>(new SpongeRegistryType<>(root, location), - (ResourceKey) (Object) p_243537_2_.location(), p_243537_3_)); + (ResourceKey) (Object) $$0.location(), $$1)); } @Override From 87f91f32e563d522d99632af97ab085cc4e9534f Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:15:40 +0100 Subject: [PATCH 106/230] fix LevelMixin dimensiontypeid --- .../spongepowered/common/mixin/core/world/level/LevelMixin.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java index ac666522470..229cfe2fcfa 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/LevelMixin.java @@ -76,7 +76,6 @@ public abstract class LevelMixin implements LevelBridge, LevelAccessor { // @formatter: off - @Mutable @Shadow @Final private net.minecraft.resources.ResourceKey dimensionTypeId; @Mutable @Shadow @Final private Holder dimensionTypeRegistration; @Shadow protected float oRainLevel; @Shadow protected float rainLevel; @@ -109,7 +108,6 @@ public abstract class LevelMixin implements LevelBridge, LevelAccessor { @Override public void bridge$adjustDimensionLogic(final DimensionType dimensionType) { this.dimensionTypeRegistration = Holder.direct(dimensionType); - this.dimensionTypeId = dimensionTypeRegistration.unwrapKey().orElseThrow(() -> new IllegalArgumentException("Dimension must be registered, got " + dimensionTypeRegistration)); // TODO Minecraft 1.16.4 - Re-create the WorldBorder due to new coordinate scale, send that updated packet to players } From 37fbc41ed58209df5bf03efadc92d4cfa8397145 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:17:21 +0100 Subject: [PATCH 107/230] fix use CommandBlockMixin --- .../mixin/core/world/level/block/CommandBlockMixin.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CommandBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CommandBlockMixin.java index 0c1038ca986..f548ada6bb6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CommandBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CommandBlockMixin.java @@ -27,7 +27,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.protocol.game.ClientboundContainerClosePacket; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.CommandBlock; @@ -43,8 +42,8 @@ @Mixin(CommandBlock.class) public abstract class CommandBlockMixin { - @Inject(method = "use", at = @At(value = "RETURN", ordinal = 1)) - private void impl$checkCommandBlockPermission(final BlockState state, final Level world, final BlockPos pos, final Player player, final InteractionHand hand, + @Inject(method = "useWithoutItem", at = @At(value = "RETURN", ordinal = 1)) + private void impl$checkCommandBlockPermission(final BlockState state, final Level world, final BlockPos pos, final Player player, final BlockHitResult hit, final CallbackInfoReturnable cir) { // In Vanilla, the command block will never even open, since the client will do the permission check. // However, when a plugin provides a permission service, we have to force the op level to 0 on the client, since From 461eb1794f877e1735daa6ae8f6fd28935556bcf Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:18:55 +0100 Subject: [PATCH 108/230] fix use CampfireBlockMixin --- .../mixin/core/world/level/block/CampfireBlockMixin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java index 9a2ed5ef1c5..cf7f36d90a7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/CampfireBlockMixin.java @@ -71,9 +71,9 @@ public abstract class CampfireBlockMixin extends BlockMixin { return (DamageSource) blockSource; } - @Inject(method = "use", locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/CampfireBlockEntity;placeFood(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/item/ItemStack;I)Z")) - public void impl$placeFood(BlockState p_225533_1_, Level p_225533_2_, BlockPos p_225533_3_, Player p_225533_4_, InteractionHand p_225533_5_, - BlockHitResult p_225533_6_, CallbackInfoReturnable cir, + @Inject(method = "useItemOn", locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/CampfireBlockEntity;placeFood(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/item/ItemStack;I)Z")) + public void impl$placeFood(ItemStack $$0, BlockState $$1, Level $$2, BlockPos $$3, Player $$4, InteractionHand $$5, BlockHitResult $$6, + CallbackInfoReturnable cir, BlockEntity tileEntity, CampfireBlockEntity campfire, ItemStack itemStack, Optional> optional) { ((CampfireBlockEntityBridge) campfire).bridge$placeRecipe(optional.get()); } From d386c399b68cb18bc492e24992630289464b4b7b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:19:38 +0100 Subject: [PATCH 109/230] fix use BedBlockMixin --- .../common/mixin/core/block/BedBlockMixin.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java index 9f718e4aa19..b0c27fe4efb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java @@ -23,6 +23,7 @@ * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.block; + import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; @@ -45,8 +46,8 @@ @Mixin(BedBlock.class) public class BedBlockMixin { - @Inject(method = "use", at = @At(value = "HEAD"), cancellable = true) - private void impl$onUseBed(final BlockState param0, final Level param1, final BlockPos param2, final Player param3, final InteractionHand param4, final BlockHitResult param5, + @Inject(method = "useWithoutItem", at = @At(value = "HEAD"), cancellable = true) + private void impl$onUseBed(final BlockState param0, final Level param1, final BlockPos param2, final Player param3, final BlockHitResult param5, final CallbackInfoReturnable cir) { if (!param1.isClientSide) { final Cause currentCause = Sponge.server().causeStackManager().currentCause(); @@ -58,8 +59,8 @@ public class BedBlockMixin { } } - @Inject(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;removeBlock(Lnet/minecraft/core/BlockPos;Z)Z"), cancellable = true) - private void impl$onExplodeBed(final BlockState param0, final Level param1, final BlockPos param2, final Player param3, final InteractionHand param4, final BlockHitResult param5, + @Inject(method = "useWithoutItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;removeBlock(Lnet/minecraft/core/BlockPos;Z)Z"), cancellable = true) + private void impl$onExplodeBed(final BlockState param0, final Level param1, final BlockPos param2, final Player param3, final BlockHitResult param5, final CallbackInfoReturnable cir) { final Cause currentCause = Sponge.server().causeStackManager().currentCause(); final BlockPos bedLocation = param5.getBlockPos(); From 6fc25603264075604b7bdafbe1b329e5b648c5ac Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:22:20 +0100 Subject: [PATCH 110/230] fix easy mixin StateHolderMixin_API --- .../world/level/block/state/StateHolderMixin_API.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/StateHolderMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/StateHolderMixin_API.java index 8bb385276c1..7ec60477d4b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/StateHolderMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/state/StateHolderMixin_API.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.block.state; -import com.google.common.collect.ImmutableMap; import net.minecraft.core.Direction; import net.minecraft.world.level.block.state.StateHolder; import net.minecraft.world.level.block.state.properties.BedPart; @@ -58,7 +57,7 @@ public abstract class StateHolderMixin_API, C> implements Sta @Shadow public abstract > T shadow$getValue(Property property); @Shadow public abstract , V extends T> C shadow$setValue(Property property, V value); @Shadow public abstract > C shadow$cycle(Property property); - @Shadow public abstract ImmutableMap, Comparable> shadow$getValues(); + @Shadow public abstract Map, Comparable> shadow$getValues(); // @formatter:on @SuppressWarnings("unchecked") From 5c5ce4dccbf8d04f8fd89189dcd83a700a67c474 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:23:36 +0100 Subject: [PATCH 111/230] fix nbt blockentity saving --- .../world/level/block/entity/BlockEntityMixin_API.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BlockEntityMixin_API.java index 3e26a137d77..68adc7db790 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BlockEntityMixin_API.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.api.minecraft.world.level.block.entity; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import org.checkerframework.checker.nullness.qual.Nullable; @@ -64,7 +65,7 @@ public abstract class BlockEntityMixin_API implements BlockEntity { @Shadow protected boolean remove; @Shadow public abstract BlockPos shadow$getBlockPos(); - @Shadow public abstract CompoundTag shadow$saveWithFullMetadata(); + @Shadow public abstract CompoundTag shadow$saveWithFullMetadata(HolderLookup.Provider $$0); //@formatter:on @Shadow @Final protected BlockPos worldPosition; @@ -114,7 +115,7 @@ public DataContainer toContainer() { .set(Queries.POSITION_Y, this.shadow$getBlockPos().getY()) .set(Queries.POSITION_Z, this.shadow$getBlockPos().getZ()) .set(Constants.TileEntity.TILE_TYPE, key); - final CompoundTag compound = this.shadow$saveWithFullMetadata(); + final CompoundTag compound = this.shadow$saveWithFullMetadata(this.level.registryAccess()); Constants.NBT.filterSpongeCustomData(compound); // We must filter the custom data so it isn't stored twice container.set(Constants.Sponge.UNSAFE_NBT, NBTTranslator.INSTANCE.translateFrom(compound)); return container; From 5ab3b554cf96dff12fd05c44f0f72c08467c1111 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:24:28 +0100 Subject: [PATCH 112/230] fix nbt blockentity loading --- .../mixin/core/world/level/block/entity/BlockEntityMixin.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java index 25dd051f13f..9298b98dafc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.world.level.block.entity; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -85,7 +86,7 @@ public abstract class BlockEntityMixin implements BlockEntityBridge, DataCompoun } @Inject(method = "load", at = @At("RETURN")) - private void impl$readSpongeData(final CompoundTag compound, final CallbackInfo ci) { + private void impl$readSpongeData(final CompoundTag compound, HolderLookup.Provider $$1, final CallbackInfo ci) { // TODO If we are in Forge data is already present this.data$setCompound(compound); // For vanilla we set the incoming nbt // Deserialize custom data... From f4980519fb65720cc3a747779aa156ca034aba67 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:28:11 +0100 Subject: [PATCH 113/230] fix BaseContainerBlockEntity set custom name --- .../level/block/entity/BaseContainerBlockEntityAccessor.java | 3 +-- .../level/block/entity/BaseContainerBlockEntityMixin.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BaseContainerBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BaseContainerBlockEntityAccessor.java index 9dfd08ef9a6..0b3486d3de3 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BaseContainerBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BaseContainerBlockEntityAccessor.java @@ -30,7 +30,6 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(BaseContainerBlockEntity.class) public interface BaseContainerBlockEntityAccessor { @@ -39,6 +38,6 @@ public interface BaseContainerBlockEntityAccessor { @Accessor("lockKey") void accessor$lockKey(final LockCode lockKey); - @Invoker("setCustomName") void invoker$setCustomName(final @Nullable Component customName); + @Accessor("name") void accessor$setCustomName(final @Nullable Component customName); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java index ee097e1cd52..8f0483a0f52 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java @@ -35,6 +35,6 @@ public abstract class BaseContainerBlockEntityMixin extends BlockEntityMixin imp @Override public void bridge$setCustomDisplayName(final Component customName) { - ((BaseContainerBlockEntityAccessor) this).invoker$setCustomName(customName); + ((BaseContainerBlockEntityAccessor) this).accessor$setCustomName(customName); } } From b7c16fba0a712c633f57e0af4bd1acd829b23c49 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:29:41 +0100 Subject: [PATCH 114/230] fix BeaconBlockEntityMixin_API effects --- .../block/entity/BeaconBlockEntityMixin_API.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BeaconBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BeaconBlockEntityMixin_API.java index 5123d406798..a4eee2d4265 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BeaconBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BeaconBlockEntityMixin_API.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.block.entity; -import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.level.block.entity.BeaconBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; @@ -41,9 +41,9 @@ public abstract class BeaconBlockEntityMixin_API extends BlockEntityMixin_API implements Beacon { // @formatter:off - @Shadow private int levels; - @Shadow @Nullable private MobEffect primaryPower; - @Shadow @Nullable private MobEffect secondaryPower; + @Shadow int levels; + @Shadow @Nullable Holder primaryPower; + @Shadow @Nullable Holder secondaryPower; // @formatter:on @Override @@ -54,8 +54,8 @@ public int completedLevels() { @Override public DataContainer toContainer() { DataContainer container = super.toContainer(); - container.set(Constants.TileEntity.Beacon.PRIMARY, BuiltInRegistries.MOB_EFFECT.getId(this.primaryPower)); - container.set(Constants.TileEntity.Beacon.SECONDARY, BuiltInRegistries.MOB_EFFECT.getId(this.secondaryPower)); + container.set(Constants.TileEntity.Beacon.PRIMARY, this.primaryPower.unwrapKey()); + container.set(Constants.TileEntity.Beacon.SECONDARY, this.secondaryPower.unwrapKey()); return container; } From e1a92de83139947888cafd58329475dd169943a0 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:33:43 +0100 Subject: [PATCH 115/230] fix data: beacon effect --- .../block/entity/BeaconBlockEntityAccessor.java | 9 +++++---- .../data/provider/block/entity/BeaconData.java | 13 +++++++------ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BeaconBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BeaconBlockEntityAccessor.java index 436fa6fc174..22bd458b185 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BeaconBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BeaconBlockEntityAccessor.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.accessor.world.level.block.entity; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.level.block.entity.BeaconBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; @@ -41,12 +42,12 @@ public interface BeaconBlockEntityAccessor { throw new UntransformedAccessorError(); } - @Accessor("primaryPower") @Nullable MobEffect accessor$primaryPower(); + @Accessor("primaryPower") @Nullable Holder accessor$primaryPower(); - @Accessor("primaryPower") void accessor$primaryPower(final @Nullable MobEffect primaryPower); + @Accessor("primaryPower") void accessor$primaryPower(final @Nullable Holder primaryPower); - @Accessor("secondaryPower") @Nullable MobEffect accessor$secondaryPower(); + @Accessor("secondaryPower") @Nullable Holder accessor$secondaryPower(); - @Accessor("secondaryPower") void accessor$secondaryPower(final @Nullable MobEffect secondaryPower); + @Accessor("secondaryPower") void accessor$secondaryPower(final @Nullable Holder secondaryPower); } diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BeaconData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BeaconData.java index 56155afb387..d677eadc889 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BeaconData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BeaconData.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.data.provider.block.entity; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.level.block.entity.BeaconBlockEntity; import org.spongepowered.api.data.Keys; @@ -56,24 +57,24 @@ public static void register(final DataProviderRegistrator registrator) { } // @formatter:on - private static PotionEffectType get(final BeaconBlockEntity holder, final Function getter) { - return (PotionEffectType) getter.apply((BeaconBlockEntityAccessor) holder); + private static PotionEffectType get(final BeaconBlockEntity holder, final Function> getter) { + return (PotionEffectType) getter.apply((BeaconBlockEntityAccessor) holder).value(); } private static boolean set(final BeaconBlockEntity holder, final PotionEffectType value, - final BiConsumer setter) { + final BiConsumer> setter) { final BeaconBlockEntityAccessor accessor = (BeaconBlockEntityAccessor) holder; final MobEffect effect = (MobEffect) value; if (!BeaconBlockEntityAccessor.accessor$VALID_EFFECTS().contains(effect)) { return false; } - setter.accept(accessor, (MobEffect) value); + setter.accept(accessor, Holder.direct((MobEffect) value)); holder.setChanged(); return true; } - private static boolean delete(final BeaconBlockEntity holder, final Function getter, - final BiConsumer setter) { + private static boolean delete(final BeaconBlockEntity holder, final Function> getter, + final BiConsumer> setter) { final BeaconBlockEntityAccessor accessor = (BeaconBlockEntityAccessor) holder; if (accessor.accessor$primaryPower() != null) { setter.accept(accessor, null); From 1218ff7facd2282134c71fa510312382923ba66f Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:43:13 +0100 Subject: [PATCH 116/230] fix Hopper Pre event --- .../entity/HopperBlockEntityAccessor.java | 4 ++-- .../HopperBlockEntityMixin_Inventory.java | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java index 00739d6940d..e4a7961704b 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java @@ -48,8 +48,8 @@ public interface HopperBlockEntityAccessor { throw new UntransformedInvokerError(); } - @Invoker("isEmptyContainer") - static boolean invoker$isEmptyContainer(final Container inventory, final Direction side) { + @Invoker("getSlots") + static int[] invoker$getSlots(final Container inventory, final Direction side) { throw new UntransformedInvokerError(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java index a3655269ecc..d7fafd882b9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java @@ -50,6 +50,8 @@ import org.spongepowered.common.inventory.adapter.InventoryAdapter; import org.spongepowered.common.inventory.util.InventoryUtil; +import java.util.stream.IntStream; + @Mixin(HopperBlockEntity.class) public abstract class HopperBlockEntityMixin_Inventory { @@ -59,13 +61,17 @@ public abstract class HopperBlockEntityMixin_Inventory { @Redirect(method = "suckInItems", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/level/block/entity/HopperBlockEntity;isEmptyContainer(Lnet/minecraft/world/Container;Lnet/minecraft/core/Direction;)Z")) - private static boolean impl$throwTransferPreIfNotEmpty(final Container inventory, final Direction facing, final Level level, final Hopper hopper) { - final boolean result = HopperBlockEntityAccessor.invoker$isEmptyContainer(inventory, facing); - if (result || !ShouldFire.TRANSFER_INVENTORY_EVENT_PRE) { - return result; + target = "Lnet/minecraft/world/level/block/entity/HopperBlockEntity;getSlots(Lnet/minecraft/world/Container;Lnet/minecraft/core/Direction;)[I")) + private static int[] impl$throwTransferPreIfNotEmpty(final Container inventory, final Direction facing, final Level level, final Hopper hopper) { + final var slots = HopperBlockEntityAccessor.invoker$getSlots(inventory, facing); + final boolean isEmpty = IntStream.of(slots).allMatch(slot -> inventory.getItem(slot).isEmpty()); + if (isEmpty || !ShouldFire.TRANSFER_INVENTORY_EVENT_PRE) { + return slots; + } + if (InventoryEventFactory.callTransferPre(InventoryUtil.toInventory(inventory), InventoryUtil.toInventory(hopper)).isCancelled()) { + return new int[]{}; } - return InventoryEventFactory.callTransferPre(InventoryUtil.toInventory(inventory), InventoryUtil.toInventory(hopper)).isCancelled(); + return slots; } // Capture Transactions From 583c736152874cce5493120ce0a9bd49d33b0621 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:48:16 +0100 Subject: [PATCH 117/230] fix Hopper transfer post Event --- .../block/entity/HopperBlockEntityMixin_Inventory.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java index d7fafd882b9..658609e9705 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory.java @@ -105,11 +105,15 @@ public abstract class HopperBlockEntityMixin_Inventory { ordinal = 1)) private static void imlp$throwTransferEventsWhenPullingItems(final Hopper hopper, final Container iInventory, final int index, final Direction direction, - final CallbackInfoReturnable cir, final ItemStack itemStack, final ItemStack itemStack1, final ItemStack itemStack2) { + final CallbackInfoReturnable cir, final ItemStack itemStack, final int oldCount, final ItemStack itemstack2) { // after putStackInInventoryAllSlots if the transfer worked - if (ShouldFire.TRANSFER_INVENTORY_EVENT_POST && itemStack2.isEmpty()) { + if (ShouldFire.TRANSFER_INVENTORY_EVENT_POST && itemstack2.isEmpty()) { // Capture Insert in Origin final TrackedInventoryBridge capture = InventoryUtil.forCapture(hopper); + final int newCount = itemStack.getCount(); + itemstack2.setCount(oldCount); + var itemStack1 = itemstack2.copy(); + itemstack2.setCount(newCount); final SlotTransaction sourceSlotTransaction = InventoryEventFactory.captureTransaction(capture, InventoryUtil.toInventory(iInventory), index, itemStack1); // Call event InventoryEventFactory.callTransferPost(capture, InventoryUtil.toInventory(iInventory), InventoryUtil.toInventory(hopper), itemStack1, sourceSlotTransaction); From b5307c8c5b1587bffaf394b28b36ff7b18188454 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:49:53 +0100 Subject: [PATCH 118/230] fix easy mixin hopper containerAt --- .../world/level/block/entity/HopperBlockEntityAccessor.java | 3 ++- .../event/world/level/block/DropperBlockMixin_Inventory.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java index e4a7961704b..2a6b9c55d25 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/HopperBlockEntityAccessor.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.accessor.world.level.block.entity; +import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -54,7 +55,7 @@ public interface HopperBlockEntityAccessor { } @Invoker("getContainerAt") - static Container invoker$getContainerAt(Level var0, double var1, double var3, double var5) { + static Container invoker$getContainerAt(Level var0, BlockPos blockPos) { throw new UntransformedInvokerError(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/DropperBlockMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/DropperBlockMixin_Inventory.java index 99f5f293972..7157c6d1641 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/DropperBlockMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/world/level/block/DropperBlockMixin_Inventory.java @@ -89,7 +89,7 @@ private void afterDispense(final ServerLevel worldIn, final BlockState state, fi final SlotTransaction sourceSlotTransaction = InventoryEventFactory.captureTransaction(capture, sourceInv, i, itemstack); final Direction enumfacing = worldIn.getBlockState(pos).getValue(DispenserBlock.FACING); final BlockPos blockpos = pos.relative(enumfacing); - final Container iinventory = HopperBlockEntityAccessor.invoker$getContainerAt(worldIn, blockpos.getX(), blockpos.getY(), blockpos.getZ()); + final Container iinventory = HopperBlockEntityAccessor.invoker$getContainerAt(worldIn, blockpos); InventoryEventFactory.callTransferPost(capture, sourceInv, ((Inventory) iinventory), itemstack, sourceSlotTransaction); } } From f5be36f98b82f9cd8f7e86bb377578509e6a2cc8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:51:52 +0100 Subject: [PATCH 119/230] fix MapItem mapid --- .../common/mixin/core/world/item/MapItemMixin.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/MapItemMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/MapItemMixin.java index 29c70e7b4a2..0563739bcbc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/MapItemMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/MapItemMixin.java @@ -27,6 +27,7 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.item.MapItem; import net.minecraft.world.level.Level; +import net.minecraft.world.level.saveddata.maps.MapId; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -38,7 +39,9 @@ @Mixin(MapItem.class) public class MapItemMixin { - @Inject(method = "createNewSavedData", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;setMapData(Ljava/lang/String;Lnet/minecraft/world/level/saveddata/maps/MapItemSavedData;)V"), locals = LocalCapture.CAPTURE_FAILHARD) + @Inject(method = "createNewSavedData", at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/Level;setMapData(Lnet/minecraft/world/level/saveddata/maps/MapId;Lnet/minecraft/world/level/saveddata/maps/MapItemSavedData;)V"), + locals = LocalCapture.CAPTURE_FAILHARD) private static void impl$storeMapId( final Level level, final int x, @@ -49,9 +52,9 @@ public class MapItemMixin { final ResourceKey dimension, final CallbackInfoReturnable cir, final MapItemSavedData data, - final int id + final MapId id ) { - ((MapItemSavedDataBridge) data).bridge$initMapId(id); + ((MapItemSavedDataBridge) data).bridge$initMapId(id.id()); } } From 6b07fe79023bba1ea4fa4c769151442c917639ae Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 19:53:01 +0100 Subject: [PATCH 120/230] fix easy mixin MobEffectInstanceMixin_API --- .../minecraft/world/effect/MobEffectInstanceMixin_API.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/effect/MobEffectInstanceMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/effect/MobEffectInstanceMixin_API.java index 3b6281d7b79..54e218ccdc1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/effect/MobEffectInstanceMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/effect/MobEffectInstanceMixin_API.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.effect; +import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.world.effect.MobEffect; import org.spongepowered.api.ResourceKey; @@ -43,7 +44,7 @@ public abstract class MobEffectInstanceMixin_API implements PotionEffect { // @formatter:off - @Shadow @Final private MobEffect effect; + @Shadow @Final private Holder effect; @Shadow private int duration; @Shadow private int amplifier; @Shadow private boolean ambient; @@ -53,7 +54,7 @@ public abstract class MobEffectInstanceMixin_API implements PotionEffect { @Override public PotionEffectType type() { - return (PotionEffectType) this.effect; + return (PotionEffectType) this.effect.value(); } @Override From 1bf5df47566fdfc77ac7e0f2cb13e84af69fc65c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:04:28 +0100 Subject: [PATCH 121/230] fix data: arrow potion effects --- .../entity/projectile/ArrowAccessor.java | 9 +++--- .../data/provider/entity/ArrowData.java | 32 ++++++++++++------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/projectile/ArrowAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/projectile/ArrowAccessor.java index 03e5039b087..7e197ba4819 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/projectile/ArrowAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/projectile/ArrowAccessor.java @@ -24,16 +24,15 @@ */ package org.spongepowered.common.accessor.world.entity.projectile; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.projectile.Arrow; +import net.minecraft.world.item.alchemy.PotionContents; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Set; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(Arrow.class) public interface ArrowAccessor { - @Accessor("effects") Set accessor$effects(); + @Invoker("getPotionContents") PotionContents invoker$getPotionContents(); + @Invoker("setPotionContents") void invoker$setPotionContents(PotionContents contents); } diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java b/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java index 3bb8dd6dc98..b2f6a9a0769 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/ArrowData.java @@ -26,12 +26,15 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.projectile.Arrow; +import net.minecraft.world.item.alchemy.PotionContents; +import org.apache.commons.lang3.stream.Streams; +import org.jetbrains.annotations.NotNull; import org.spongepowered.api.data.Keys; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.common.accessor.world.entity.projectile.ArrowAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import java.util.Set; +import java.util.List; import java.util.stream.Collectors; public final class ArrowData { @@ -45,20 +48,27 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(Arrow.class) .create(Keys.POTION_EFFECTS) .get(h -> { - final Set effects = ((ArrowAccessor) h).accessor$effects(); - return effects.stream() - .map(effect -> (PotionEffect) new MobEffectInstance(effect.getEffect(), effect.getDuration(), - effect.getAmplifier(), effect.isAmbient(), effect.isVisible())) + final Iterable effects = ((ArrowAccessor) h).invoker$getPotionContents().getAllEffects(); + return Streams.of(effects) + .map(effect -> (PotionEffect) ArrowData.clone(effect)) .collect(Collectors.toList()); }) .set((h, v) -> { - ((ArrowAccessor) h).accessor$effects().clear(); - for (final PotionEffect effect : v) { - final MobEffectInstance mcEffect = new MobEffectInstance(((MobEffectInstance) effect).getEffect(), (int) effect.duration().ticks(), - effect.amplifier(), effect.isAmbient(), effect.showsParticles()); - h.addEffect(mcEffect); - } + final PotionContents previousContents = ((ArrowAccessor) h).invoker$getPotionContents(); + final List list = v.stream().map(effect -> ArrowData.clone((MobEffectInstance) effect)).toList(); + ((ArrowAccessor) h).invoker$setPotionContents(new PotionContents(previousContents.potion(), previousContents.customColor(), list)); }); } // @formatter:on + @NotNull + private static MobEffectInstance clone(final MobEffectInstance effect) { + return new MobEffectInstance(effect.getEffect(), + effect.getDuration(), + effect.getAmplifier(), + effect.isAmbient(), + effect.isVisible(), + effect.showIcon()); + // TODO API showIcon? + // TODO hiddenEffect? + } } From 302eed74c350cf16010c0e399899c4b60276d723 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:07:03 +0100 Subject: [PATCH 122/230] fix SynchedEntityDataMixin --- .../mixin/core/network/syncher/SynchedEntityDataMixin.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java index e3c026624a4..5a339a6f4c5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/syncher/SynchedEntityDataMixin.java @@ -25,6 +25,7 @@ package org.spongepowered.common.mixin.core.network.syncher; import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.syncher.SyncedDataHolder; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.world.entity.Entity; import org.apache.commons.lang3.ObjectUtils; @@ -47,7 +48,7 @@ @Mixin(SynchedEntityData.class) public abstract class SynchedEntityDataMixin { - @Shadow @Final private Entity entity; + @Shadow @Final private SyncedDataHolder entity; @Shadow private boolean isDirty; @Shadow protected abstract SynchedEntityData.DataItem getItem(final EntityDataAccessor key); @@ -74,12 +75,12 @@ public void set(final EntityDataAccessor key, T value) { // Client side can have an entity, because reasons....... // Really silly reasons...... // I don't know, ask Grum.... - if (this.entity != null && this.entity.level() != null && !this.entity.level().isClientSide && !((EntityBridge) this.entity).bridge$isConstructing()) { // We only want to spam the server world ;) + if (this.entity != null && ((Entity) this.entity).level() != null && !((Entity) this.entity).level().isClientSide && !((EntityBridge) this.entity).bridge$isConstructing()) { // We only want to spam the server world ;) final Optional> converter = ((EntityDataAccessorBridge) (Object) key).bridge$getDataConverter(); // At this point it is changing if (converter.isPresent()) { // Ok, we have a key ready to use the converter - final Optional optional = converter.get().createTransaction(this.entity, currentValue, value); + final Optional optional = converter.get().createTransaction(((Entity) this.entity), currentValue, value); if (optional.isPresent()) { // Only need to make a transaction if there are actual changes necessary. final DataTransactionResult transaction = optional.get(); From ee6f488339a79aa7b501009841079a29d8cc1b3d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:08:16 +0100 Subject: [PATCH 123/230] fix ItemStack null customdata --- .../common/mixin/core/world/item/ItemStackMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java index d6099107145..03bce62279c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java @@ -93,7 +93,7 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp @Override public void data$setCompound(final CompoundTag nbt) { - this.components.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt)); + this.components.set(DataComponents.CUSTOM_DATA, nbt == null ? CustomData.EMPTY : CustomData.of(nbt)); } // Add our manipulators when creating copies from this ItemStack: From d54aac16d7ee656e93b1d8ff4f3823859372e5ff Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:08:44 +0100 Subject: [PATCH 124/230] fix easy mixin PotionMixin_API --- .../api/minecraft/world/item/alchemy/PotionMixin_API.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/alchemy/PotionMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/alchemy/PotionMixin_API.java index 0245dac04cf..3b5e9f0cfd7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/alchemy/PotionMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/alchemy/PotionMixin_API.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.alchemy; -import com.google.common.collect.ImmutableList; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.item.potion.PotionType; import org.spongepowered.asm.mixin.Final; @@ -37,7 +36,7 @@ public abstract class PotionMixin_API implements PotionType { // @formatter:off - @Shadow @Final private ImmutableList effects; + @Shadow @Final private List effects; // @formatter:on @Override From 9b606471bac6bcc5be6936843e367063e6e69a37 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:10:18 +0100 Subject: [PATCH 125/230] TODO API fix registry EquipmentGroup --- .../common/registry/loader/VanillaRegistryLoader.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index 8c8fa13996a..bce6a8c8ca0 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -169,6 +169,7 @@ private void loadEnumRegistries() { this.manualName(RegistryTypes.EQUIPMENT_GROUP, EquipmentSlot.Type.values(), map -> { map.put(EquipmentSlot.Type.ARMOR, "worn"); map.put(EquipmentSlot.Type.HAND, "held"); + map.put(EquipmentSlot.Type.BODY, "body"); }); this.manualName(RegistryTypes.EQUIPMENT_TYPE, EquipmentSlot.values(), map -> { map.put(EquipmentSlot.CHEST, "chest"); From 7c0c47b30ec4d7e360416a14b6b1c30aa3e57753 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:11:05 +0100 Subject: [PATCH 126/230] TODO API fix registry EquipmentType --- .../common/registry/loader/VanillaRegistryLoader.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java index bce6a8c8ca0..9c0aca88d5f 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/VanillaRegistryLoader.java @@ -178,6 +178,7 @@ private void loadEnumRegistries() { map.put(EquipmentSlot.LEGS, "legs"); map.put(EquipmentSlot.MAINHAND, "main_hand"); map.put(EquipmentSlot.OFFHAND, "off_hand"); + map.put(EquipmentSlot.BODY, "body"); }); this.knownName(RegistryTypes.FOX_TYPE, Fox.Type.values(), Fox.Type::getSerializedName); this.knownName(RegistryTypes.GAME_MODE, GameType.values(), GameType::getName); From 8c0f171bb3d6c9476e21c494bed43b40f020e72e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:12:15 +0100 Subject: [PATCH 127/230] fix easy mixin AttributeInstanceMixin_API --- .../entity/ai/attributes/AttributeInstanceMixin_API.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java index 619fd70feab..f64f2d4c60a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.ai.attributes; +import net.minecraft.core.Holder; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import org.spongepowered.api.entity.attribute.Attribute; import org.spongepowered.api.entity.attribute.AttributeModifier; @@ -47,7 +48,7 @@ public abstract class AttributeInstanceMixin_API implements Attribute { // @formatter:off - @Shadow public abstract net.minecraft.world.entity.ai.attributes.Attribute shadow$getAttribute(); + @Shadow public abstract Holder shadow$getAttribute(); @Shadow public abstract double shadow$getBaseValue(); @Shadow public abstract void shadow$setBaseValue(double baseValue); @Shadow public abstract double shadow$getValue(); @@ -62,7 +63,7 @@ public abstract class AttributeInstanceMixin_API implements Attribute { @Override public AttributeType type() { - return (AttributeType) this.shadow$getAttribute(); + return (AttributeType) this.shadow$getAttribute().value(); } @Override From 21038e845cd22d91b862fe1db92bf146d0f859d0 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:13:59 +0100 Subject: [PATCH 128/230] fix easy mixin MapDecorationMixin_API --- .../mixin/api/minecraft/map/MapDecorationMixin_API.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index 17af7bbabc8..0b891ab5e3c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -26,7 +26,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.level.saveddata.maps.MapDecoration; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.map.decoration.MapDecorationType; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation; @@ -51,9 +50,10 @@ public abstract class MapDecorationMixin_API implements org.spongepowered.api.ma @Shadow @Final @Mutable private byte x; @Shadow @Final @Mutable private byte y; @Shadow @Final @Mutable private byte rot; - @Shadow @Nullable public abstract Component shadow$name(); + @Shadow @Final private java.util.Optional name; // @formatter:on + @Override public MapDecorationType type() { return SpongeMapDecorationType.toSpongeType(this.type) @@ -104,9 +104,7 @@ public DataContainer toContainer() { .set(Constants.Map.DECORATION_X, this.x) .set(Constants.Map.DECORATION_Y, this.y) .set(Constants.Map.DECORATION_ROTATION, (byte) MapUtil.normalizeDecorationOrientation(this.rot)); - if (this.shadow$name() != null) { - data.set(Constants.Map.NAME, Component.Serializer.toJson(this.shadow$name(), SpongeCommon.server().registryAccess())); - } + this.name.ifPresent(component -> data.set(Constants.Map.NAME, Component.Serializer.toJson(component, SpongeCommon.server().registryAccess()))); return data; } } From 4a191e9d880dd2a8c051746df027e4bc01e4a49d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:15:32 +0100 Subject: [PATCH 129/230] fix nbt saving SavedDataMixin --- .../common/mixin/core/world/level/SavedDataMixin.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java index 2d4313b671e..cada3864214 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/SavedDataMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.level; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.saveddata.SavedData; import org.spongepowered.asm.mixin.Mixin; @@ -39,10 +40,10 @@ @Mixin(SavedData.class) public abstract class SavedDataMixin { - @Inject(method = "save(Ljava/io/File;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/saveddata/SavedData;save(Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/nbt/CompoundTag;"), + @Inject(method = "save(Ljava/io/File;Lnet/minecraft/core/HolderLookup$Provider;)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/saveddata/SavedData;save(Lnet/minecraft/nbt/CompoundTag;Lnet/minecraft/core/HolderLookup$Provider;)Lnet/minecraft/nbt/CompoundTag;"), locals = LocalCapture.CAPTURE_FAILHARD) - public void impl$writeAdditionalMapNBT(File file, final CallbackInfo cir, CompoundTag compound) { + public void impl$writeAdditionalMapNBT(File file, HolderLookup.Provider registry, final CallbackInfo cir, CompoundTag compound) { if (this instanceof DataCompoundHolder) { if (DataUtil.syncDataToTag(this)) { compound.merge(((DataCompoundHolder) this).data$getCompound()); From d582dc66da64a026c88097c27c3c37f01f563592 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:17:14 +0100 Subject: [PATCH 130/230] fix easy mixin PrimaryLevelDataMixin --- .../core/world/level/storage/PrimaryLevelDataMixin.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java index bb381412a9b..de59c3dd179 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PrimaryLevelDataMixin.java @@ -81,9 +81,7 @@ public abstract class PrimaryLevelDataMixin implements WorldData, PrimaryLevelDa // @formatter:off @Shadow private LevelSettings settings; - @Shadow private int xSpawn; - @Shadow private int ySpawn; - @Shadow private int zSpawn; + @Shadow private BlockPos spawnPos; @Shadow private float spawnAngle; @Shadow public abstract boolean shadow$isDifficultyLocked(); @@ -408,10 +406,11 @@ public ServerLevelData overworldData() { @Override public String toString() { return new StringJoiner(", ", PrimaryLevelData.class.getSimpleName() + "[", "]") + .add("key=" + this.impl$key) .add("worldType=" + this.impl$dimensionType) .add("uniqueId=" + this.impl$uniqueId) - .add("spawn=" + new Vector3i(this.xSpawn, this.ySpawn, this.zSpawn)) + .add("spawn=" + VecHelper.toVector3i(this.spawnPos)) .add("gameType=" + ((ServerLevelData) this).getGameType()) .add("hardcore=" + ((LevelData) this).isHardcore()) .add("difficulty=" + ((LevelData) this).getDifficulty()) From 6da0f16cc01f2f4a6af3f75a917896f03bb2622a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:28:48 +0100 Subject: [PATCH 131/230] fix ChatTypeMixin_API --- .../network/chat/ChatTypeMixin_API.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/network/chat/ChatTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/network/chat/ChatTypeMixin_API.java index c411a991455..46d50d5e73f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/network/chat/ChatTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/network/chat/ChatTypeMixin_API.java @@ -26,6 +26,7 @@ import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.format.Style; +import net.minecraft.core.Holder; import net.minecraft.network.chat.ChatType; import net.minecraft.network.chat.ChatTypeDecoration; import net.minecraft.network.chat.Component; @@ -36,6 +37,8 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.adventure.SpongeAdventure; +import java.util.Optional; + @Mixin(ChatType.class) public abstract class ChatTypeMixin_API implements org.spongepowered.api.adventure.ChatType { @@ -46,14 +49,10 @@ public abstract class ChatTypeMixin_API implements org.spongepowered.api.adventu // @formatter:on - @Shadow public abstract ChatType.Bound bind(final Component $$0); - @Override public @NonNull Bound bind(@NonNull final ComponentLike name, @Nullable final ComponentLike target) { - ChatType.Bound ret = this.bind(SpongeAdventure.asVanilla(name.asComponent())); - if (target != null) { - ret = ret.withTargetName(SpongeAdventure.asVanilla(target.asComponent())); - } + var ret = new ChatType.Bound(Holder.direct((ChatType) (Object) this), SpongeAdventure.asVanilla(name.asComponent()), + Optional.ofNullable(target).map(ComponentLike::asComponent).map(SpongeAdventure::asVanilla)); return (net.kyori.adventure.chat.ChatType.Bound) (Object) ret; } @@ -72,13 +71,13 @@ public static abstract class BoundMixin_API implements net.kyori.adventure.chat. // @formatter:off @Shadow public abstract Component shadow$name(); - @Shadow public abstract Component shadow$targetName(); - @Shadow public abstract ChatType shadow$chatType(); + @Shadow public abstract Optional shadow$targetName(); + @Shadow public abstract Holder shadow$chatType(); // @formatter:on @Override public net.kyori.adventure.chat.@NonNull ChatType type() { - return (net.kyori.adventure.chat.ChatType) (Object) this.shadow$chatType(); + return (net.kyori.adventure.chat.ChatType) (Object) this.shadow$chatType().value(); } @Override @@ -88,7 +87,7 @@ public static abstract class BoundMixin_API implements net.kyori.adventure.chat. @Override public net.kyori.adventure.text.@Nullable Component target() { - return this.shadow$targetName() == null ? null: SpongeAdventure.asAdventure(this.shadow$targetName()); + return this.shadow$targetName().map(SpongeAdventure::asAdventure).orElse(null); } } From 7efb076f6af9c1fef481deece4276c1cee9cb1ca Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:31:54 +0100 Subject: [PATCH 132/230] fix WorldDimensionsMixin --- .../core/world/level/levelgen/WorldDimensionsMixin.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/levelgen/WorldDimensionsMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/levelgen/WorldDimensionsMixin.java index 3f434bda6a6..82bf8dc0b92 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/levelgen/WorldDimensionsMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/levelgen/WorldDimensionsMixin.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.core.world.level.levelgen; -import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.dimension.LevelStem; @@ -34,11 +33,13 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.SpongeCommon; +import java.util.Map; + @Mixin(WorldDimensions.class) public abstract class WorldDimensionsMixin { - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/Registry;get(Lnet/minecraft/resources/ResourceKey;)Ljava/lang/Object;")) - private T findOverworldStem(Registry instance, ResourceKey key) { + @Redirect(method = "(Ljava/util/Map;)V", at = @At(value = "INVOKE", target = "Ljava/util/Map;get(Ljava/lang/Object;)Ljava/lang/Object;")) + private Object findOverworldStem(final Map instance, final Object key) { var val = instance.get(key); // Yes this looks strange. The issue is Sponge gives all levels a PrimaryLevelData. Vanilla reads that file and reads the // "worldgensettings" tag section which is really where LevelStems are retained. It then creates a view of the stems, wherein called @@ -51,7 +52,7 @@ private T findOverworldStem(Registry instance, ResourceKey key) { // ends up being a double lookup for all worlds but the overworld but I feel it is a small price to pay vs. a very complicated series // of mixins to remove retrieving the level stem settings solely for all worlds but the overworld if (val == null) { - return (T) SpongeCommon.vanillaRegistry(Registries.LEVEL_STEM).get((ResourceKey) key); + return SpongeCommon.vanillaRegistry(Registries.LEVEL_STEM).get((ResourceKey) key); } return val; From 93906199fb43c9a06bb884dc5acdd55328c8778d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:37:19 +0100 Subject: [PATCH 133/230] fix PlayerDataStorageMixin --- .../core/world/level/storage/PlayerDataStorageMixin.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PlayerDataStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PlayerDataStorageMixin.java index bc85293da30..3fa3082439d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PlayerDataStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/PlayerDataStorageMixin.java @@ -51,6 +51,7 @@ import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; +import java.util.Optional; @Mixin(PlayerDataStorage.class) public abstract class PlayerDataStorageMixin { @@ -61,7 +62,7 @@ public abstract class PlayerDataStorageMixin { @Nullable private Exception impl$capturedException; - @Redirect(method = "load", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;load(Lnet/minecraft/nbt/CompoundTag;)V")) + @Redirect(method = "lambda$load$1", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/player/Player;load(Lnet/minecraft/nbt/CompoundTag;)V")) private void impl$readSpongePlayerData(final Player playerEntity, final CompoundTag compound) throws IOException { playerEntity.load(compound); final Path file = new File(this.playerDir, playerEntity.getStringUUID() + ".dat").toPath(); @@ -69,7 +70,7 @@ public abstract class PlayerDataStorageMixin { ((SpongeServer) SpongeCommon.server()).getPlayerDataManager().readPlayerData(compound, null, creationTime); } - @Redirect(method = "load", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/NbtIo;readCompressed(Ljava/nio/file/Path;Lnet/minecraft/nbt/NbtAccounter;)Lnet/minecraft/nbt/CompoundTag;")) + @Redirect(method = "load(Lnet/minecraft/world/entity/player/Player;Ljava/lang/String;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/NbtIo;readCompressed(Ljava/nio/file/Path;Lnet/minecraft/nbt/NbtAccounter;)Lnet/minecraft/nbt/CompoundTag;")) private CompoundTag impl$wrapFileRead(final Path path, final NbtAccounter accounter) throws IOException { try { return NbtIo.readCompressed(path, accounter); @@ -80,11 +81,11 @@ public abstract class PlayerDataStorageMixin { } } - @Inject(method = "load", + @Inject(method = "load(Lnet/minecraft/world/entity/player/Player;Ljava/lang/String;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD ) - private void impl$onFailedLoad(final Player param0, final CallbackInfoReturnable cir, final CompoundTag tag, final Exception exception) { + private void impl$onFailedLoad(final Player param0, final String param1, final CallbackInfoReturnable> cir, final File file, final Exception exception) { throw new RuntimeException(exception); } From b726e8ec41992e504028bedc2a7159d30a230bc4 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:38:43 +0100 Subject: [PATCH 134/230] fix easy mixin MapDecorationMixin --- .../minecraft/world/level/saveddata/MapDecorationMixin.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java index 1b4553b1da7..52ed67fd52d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java @@ -36,6 +36,7 @@ import org.spongepowered.common.util.Constants; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -48,7 +49,7 @@ public abstract class MapDecorationMixin implements MapDecorationBridge { private String impl$key = Constants.Map.DECORATION_KEY_PREFIX + UUID.randomUUID().toString(); @Inject(method = "", at = @At("RETURN")) - public void impl$setPersistenceOnInit(final MapDecoration.Type typeIn, final byte x, final byte y, final byte rot, final Component name, final CallbackInfo ci) { + public void impl$setPersistenceOnInit(final MapDecoration.Type typeIn, final byte x, final byte y, final byte rot, final Optional name, final CallbackInfo ci) { // All of the below types have no reason to be saved to disk // This is because they can/should be calculated when needed // Furthermore if a sponge plugin adds a MapDecoration, isPersistent From 0354dcb59b570204bd91db3270acbe1333f65079 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:39:38 +0100 Subject: [PATCH 135/230] fix easy mixin ConnectionMixin --- .../common/mixin/core/network/ConnectionMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java index 70940fd6008..3979651ca56 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java @@ -156,7 +156,7 @@ public abstract class ConnectionMixin extends SimpleChannelInboundHandler Date: Mon, 4 Mar 2024 20:40:36 +0100 Subject: [PATCH 136/230] fix DimensionDataStorageMixin --- .../core/world/level/storage/DimensionDataStorageMixin.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java index b43a536838a..bc77c2550aa 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.core.world.level.storage; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.datafix.DataFixTypes; import net.minecraft.world.level.saveddata.SavedData; @@ -37,13 +38,14 @@ import org.spongepowered.common.data.DataUtil; import java.io.File; +import java.util.function.BiFunction; import java.util.function.Function; @Mixin(DimensionDataStorage.class) public abstract class DimensionDataStorageMixin { @Inject(method = "readSavedData", at = @At(value = "RETURN", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD) - public void readSpongeMapData(Function var1, DataFixTypes $$1, String var2, + public void readSpongeMapData(BiFunction var1, DataFixTypes $$1, String var2, CallbackInfoReturnable cir, File var3, CompoundTag rootTag) { final SavedData savedData = cir.getReturnValue(); From d66f80e52b5e2bab362cc3d81c6e1178c467bcb7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:44:05 +0100 Subject: [PATCH 137/230] TODO check if exploit fix still needed --- .../WritableBookItemMixin_LimitBookSize.java | 60 +++++++++---------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java b/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java index 3f2a000d361..5cc62814d1b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java +++ b/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java @@ -42,35 +42,35 @@ @Mixin(WritableBookItem.class) public abstract class WritableBookItemMixin_LimitBookSize { - @Redirect( - method = "makeSureTagIsValid", - at = @At(value = "INVOKE", remap = false, target = "Ljava/lang/String;length()I") - ) - private static int impl$useByteLength(final String s) { - return s.getBytes(StandardCharsets.UTF_8).length; - } - - @ModifyConstant( - method = "makeSureTagIsValid", - constant = @Constant(intValue = 32767) - ) - private static int impl$useMaxBookPageSizeFromConfig(final int maxBookPageSize) { - return SpongeConfigs.getCommon().get().exploits.maxBookPageSize; - } - - @Inject( - method = "makeSureTagIsValid", - cancellable = true, - at = @At(value = "RETURN") - ) - private static void impl$useMaxBookSizeFromConfig(final CompoundTag p_150930_0_, final CallbackInfoReturnable cir) { - if (cir.getReturnValue()) { - final ListTag listnbt = p_150930_0_.getList("pages", 8); - final int size = IntStream.range(0, listnbt.size()).mapToObj(listnbt::getString).mapToInt(s -> s.getBytes(StandardCharsets.UTF_8).length).sum(); - if (size > SpongeConfigs.getCommon().get().exploits.maxBookSize) { - cir.setReturnValue(false); - } - } - } +// @Redirect( +// method = "makeSureTagIsValid", +// at = @At(value = "INVOKE", remap = false, target = "Ljava/lang/String;length()I") +// ) +// private static int impl$useByteLength(final String s) { +// return s.getBytes(StandardCharsets.UTF_8).length; +// } +// +// @ModifyConstant( +// method = "makeSureTagIsValid", +// constant = @Constant(intValue = 32767) +// ) +// private static int impl$useMaxBookPageSizeFromConfig(final int maxBookPageSize) { +// return SpongeConfigs.getCommon().get().exploits.maxBookPageSize; +// } +// +// @Inject( +// method = "makeSureTagIsValid", +// cancellable = true, +// at = @At(value = "RETURN") +// ) +// private static void impl$useMaxBookSizeFromConfig(final CompoundTag p_150930_0_, final CallbackInfoReturnable cir) { +// if (cir.getReturnValue()) { +// final ListTag listnbt = p_150930_0_.getList("pages", 8); +// final int size = IntStream.range(0, listnbt.size()).mapToObj(listnbt::getString).mapToInt(s -> s.getBytes(StandardCharsets.UTF_8).length).sum(); +// if (size > SpongeConfigs.getCommon().get().exploits.maxBookSize) { +// cir.setReturnValue(false); +// } +// } +// } } From c9f0b72fde8f6a1b5d287688c60de21380d4d722 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:47:17 +0100 Subject: [PATCH 138/230] fix ChunkMapMixin_Tracker --- .../mixin/tracker/server/level/ChunkMapMixin_Tracker.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java index 599f189e781..26cbcab7ebf 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ChunkMapMixin_Tracker.java @@ -95,7 +95,7 @@ public abstract class ChunkMapMixin_Tracker { } - @Redirect(method = "lambda$protoChunkToFullChunk$34", + @Redirect(method = "lambda$protoChunkToFullChunk$35", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/LevelChunk;runPostLoad()V"), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/LevelChunk;setFullStatus(Ljava/util/function/Supplier;)V"), @@ -131,7 +131,7 @@ public abstract class ChunkMapMixin_Tracker { .buildAndSwitch(); } - @Inject(method = "lambda$protoChunkToFullChunk$34", + @Inject(method = "lambda$protoChunkToFullChunk$35", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/LevelChunk;registerAllBlockEntitiesAfterLevelLoad()V", shift = At.Shift.BY, by = 2), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/LevelChunk;runPostLoad()V") From 96209e792547f50cfbf587b710ec7ed88a1bea79 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 20:57:10 +0100 Subject: [PATCH 139/230] fix Component_SerializerMixin --- .../chat/Component_SerializerMixin.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/chat/Component_SerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/chat/Component_SerializerMixin.java index a6c387ca789..9947aeaddf9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/chat/Component_SerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/chat/Component_SerializerMixin.java @@ -28,6 +28,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.minecraft.core.HolderLookup; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -41,18 +42,18 @@ @Mixin(net.minecraft.network.chat.Component.Serializer.class) public abstract class Component_SerializerMixin { @Shadow - static JsonElement shadow$serialize(final net.minecraft.network.chat.Component text) { + static JsonElement shadow$serialize(final net.minecraft.network.chat.Component text, HolderLookup.Provider $$1) { throw new UnsupportedOperationException("Shadowed createLegacyDisconnectPacket"); } @Shadow @Final private static Gson GSON; @Inject(method = "serialize", at = @At("HEAD"), cancellable = true) - private static void impl$writeComponentText(final net.minecraft.network.chat.Component text, final CallbackInfoReturnable cir) { + private static void impl$writeComponentText(final net.minecraft.network.chat.Component text, final HolderLookup.Provider $$1, final CallbackInfoReturnable cir) { if(text instanceof AdventureTextComponent atc) { final net.minecraft.network.chat.@Nullable Component converted = ((AdventureTextComponent) text).deepConvertedIfPresent(); if(converted != null) { - cir.setReturnValue(Component_SerializerMixin.shadow$serialize(text)); + cir.setReturnValue(Component_SerializerMixin.shadow$serialize(text, $$1)); } else { // TODO actually fix this // cir.setReturnValue(ctx.serialize(((AdventureTextComponent) text).wrapped(), Component.class)); @@ -68,15 +69,8 @@ public abstract class Component_SerializerMixin { return gson; } - @Inject(method = "toJson", at = @At("HEAD"), cancellable = true) - private static void impl$redirectSerialization(final net.minecraft.network.chat.Component component, final CallbackInfoReturnable cir) { - if (component instanceof AdventureTextComponent atc) { - cir.setReturnValue(GSON.toJson(atc.wrapped())); - } - } - - @Inject(method = "toJsonTree", at = @At("HEAD"), cancellable = true) - private static void impl$redirectTreeSerialization(final net.minecraft.network.chat.Component component, final CallbackInfoReturnable cir) { + @Inject(method = "serialize", at = @At("HEAD"), cancellable = true) + private static void impl$redirectSerialization(final net.minecraft.network.chat.Component component, HolderLookup.Provider $$1, final CallbackInfoReturnable cir) { if (component instanceof AdventureTextComponent atc) { cir.setReturnValue(GSON.toJsonTree(atc.wrapped())); } From 0cd2a0d0f1dae9b18d91c28e4c5741cad0f64d08 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 21:02:26 +0100 Subject: [PATCH 140/230] TODO component serialization is in codec, server side translation is not possible like this anymore --- .../common/mixin/core/network/PacketEncoderMixin.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java index 0a0d63f0020..fc24284f1b1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java @@ -39,9 +39,10 @@ @Mixin(PacketEncoder.class) public class PacketEncoderMixin { - @Inject(method = "encode(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/protocol/Packet;Lio/netty/buffer/ByteBuf;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/network/codec/StreamCodec;encode(Ljava/lang/Object;Ljava/lang/Object;)V")) - private void applyLocaleToBuffer(final ChannelHandlerContext ctx, final Packet $$1, final ByteBuf $$2, final CallbackInfo ci) { - ((FriendlyByteBufBridge) $$2).bridge$setLocale(ctx.channel().attr(SpongeAdventure.CHANNEL_LOCALE).get()); // TODO check if this correct - } + // TODO find out how we can still translate serverside see FriendlyByteBufMixin +// @Inject(method = "encode(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/protocol/Packet;Lio/netty/buffer/ByteBuf;)V", +// at = @At(value = "INVOKE", target = "Lnet/minecraft/network/codec/StreamCodec;encode(Ljava/lang/Object;Ljava/lang/Object;)V")) +// private void applyLocaleToBuffer(final ChannelHandlerContext ctx, final Packet $$1, final ByteBuf $$2, final CallbackInfo ci) { +// ((FriendlyByteBufBridge) $$2).bridge$setLocale(ctx.channel().attr(SpongeAdventure.CHANNEL_LOCALE).get()); // TODO check if this correct, it is not +// } } From d2b12c0a50730b8eb91d9b8e59e750c91748ccdd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 21:04:00 +0100 Subject: [PATCH 141/230] fix easy mixin ClientboundResourcePackPushPacketMixin --- .../game/ClientboundResourcePackPushPacketMixin.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/protocol/game/ClientboundResourcePackPushPacketMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/protocol/game/ClientboundResourcePackPushPacketMixin.java index 261a919d357..c98e203daaa 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/protocol/game/ClientboundResourcePackPushPacketMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/protocol/game/ClientboundResourcePackPushPacketMixin.java @@ -37,6 +37,7 @@ import org.spongepowered.common.resourcepack.SpongeResourcePack; import java.net.URISyntaxException; +import java.util.Optional; import java.util.UUID; @Mixin(ClientboundResourcePackPushPacket.class) @@ -47,10 +48,10 @@ public abstract class ClientboundResourcePackPushPacketMixin implements Clientbo private ResourcePack impl$pack; - @Inject(method = "(Ljava/util/UUID;Ljava/lang/String;Ljava/lang/String;ZLnet/minecraft/network/chat/Component;)V", at = @At("RETURN") , remap = false) - private void impl$setResourcePackOrThrowException(final UUID uuid, final String url, final String hash, final boolean required, final Component prompt, final CallbackInfo ci) { + @Inject(method = "", at = @At("RETURN") , remap = false) + private void impl$setResourcePackOrThrowException(final UUID uuid, final String url, final String hash, final boolean required, final Optional prompt, final CallbackInfo ci) { try { - this.impl$pack = SpongeResourcePack.create(url, hash, prompt == null ? net.kyori.adventure.text.Component.empty() : SpongeAdventure.asAdventure(prompt)); + this.impl$pack = SpongeResourcePack.create(url, hash, prompt.isEmpty() ? net.kyori.adventure.text.Component.empty() : SpongeAdventure.asAdventure(prompt)); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } From 25d2a0dfd3f32ca9c3db23e9e974fa124dbbb1c7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 21:28:23 +0100 Subject: [PATCH 142/230] fix easy mixin ServerGamePacketListenerImplMixin_Vanilla --- .../network/ServerGamePacketListenerImplMixin_Vanilla.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 81b0b4b57c5..247ed0fb8ee 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -58,7 +58,7 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo //@formatter:on @SuppressWarnings({"unchecked", "rawtypes"}) - @Redirect(method = "lambda$handlePlaceRecipe$10", + @Redirect(method = "lambda$handlePlaceRecipe$9", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) private void vanilla$onPlaceRecipe(final RecipeBookMenu recipeBookMenu, final boolean shift, final RecipeHolder recipe, final net.minecraft.server.level.ServerPlayer player) { final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext(); From f0e25a01797bae1799c2ac8355f0f0fa9c516e1c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Mon, 4 Mar 2024 21:28:41 +0100 Subject: [PATCH 143/230] fix get rid of entity interaction range hook as vanilla now supports it --- .../org/spongepowered/common/hooks/GeneralHooks.java | 9 --------- .../ServerGamePacketListenerImplMixin_Vanilla.java | 1 - 2 files changed, 10 deletions(-) diff --git a/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java b/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java index 44453069686..0e898f94035 100644 --- a/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java +++ b/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java @@ -34,15 +34,6 @@ public interface GeneralHooks { - default double getEntityReachDistanceSq(ServerPlayer player, Entity targeted) { - double d0 = 36.0d; // 6 blocks - if (!player.hasLineOfSight(targeted)) { - d0 = 9.0D; // 3 blocks - } - - return d0; - } - default boolean onServerThread() { // Return true when the server isn't yet initialized, this means on a client // that the game is still being loaded. This is needed to support initialization diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 247ed0fb8ee..d24bea5696f 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -47,7 +47,6 @@ import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.context.transaction.EffectTransactor; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; -import org.spongepowered.common.hooks.PlatformHooks; @Mixin(value = ServerGamePacketListenerImpl.class, priority = 999) public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCommonPacketListenerImplMixin_Vanilla implements ServerGamePacketListener { From 490c6c9e0d1a50ec9ac0fe5edc27be870b924e0c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 01:09:12 +0100 Subject: [PATCH 144/230] TODO Connection#configureSerialization is limiting what packets are sent --- .../common/network/PacketUtil.java | 10 ++++ .../network/channel/SpongeChannelManager.java | 27 +++++++++-- ...rConfigurationPacketListenerImplMixin.java | 2 +- .../ClientboundCustomPayloadPacketMixin.java | 47 +++++++++++++++++++ .../resources/mixins.spongevanilla.core.json | 7 +-- 5 files changed, 86 insertions(+), 7 deletions(-) create mode 100644 vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java diff --git a/src/main/java/org/spongepowered/common/network/PacketUtil.java b/src/main/java/org/spongepowered/common/network/PacketUtil.java index 91fc3b6f0b5..440edaa5dca 100644 --- a/src/main/java/org/spongepowered/common/network/PacketUtil.java +++ b/src/main/java/org/spongepowered/common/network/PacketUtil.java @@ -74,6 +74,16 @@ public static net.minecraft.network.protocol.Packet createLoginPayloadRequest return new ClientboundCustomQueryPacket(transactionId, payload); } + public static net.minecraft.network.protocol.Packet createPlayPayload(final CustomPacketPayload payload, final EngineConnectionSide side) { + if (side == EngineConnectionSide.CLIENT) { + return new ServerboundCustomPayloadPacket(payload); + } else if (side == EngineConnectionSide.SERVER) { + return new ClientboundCustomPayloadPacket(payload); + } else { + throw new UnsupportedOperationException(); + } + } + public static net.minecraft.network.protocol.Packet createPlayPayload(final ResourceKey channel, final ChannelBuf payload, final EngineConnectionSide side) { // TODO fix me // if (side == EngineConnectionSide.CLIENT) { diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java index d1a34e97ca7..3756acdbb7d 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java @@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableList; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; @@ -239,10 +240,30 @@ public void write(FriendlyByteBuf var1) { return future; } + public record SpongeRegisterChannelPayload(Collection channels) implements CustomPacketPayload + { + public static final StreamCodec STREAM_CODEC = CustomPacketPayload.codec( + SpongeRegisterChannelPayload::write, SpongeRegisterChannelPayload::new + ); + public static final CustomPacketPayload.Type TYPE = CustomPacketPayload.createType(Constants.Channels.REGISTER_KEY.value()); + + public SpongeRegisterChannelPayload(FriendlyByteBuf $$0) { + this(RegisterChannelUtil.decodePayload((ChannelBuf) $$0)); + } + + private void write(FriendlyByteBuf $$0) { + $$0.writeBytes((FriendlyByteBuf) RegisterChannelUtil.encodePayload(this.channels)); + } + + @Override + public Type type() { + return TYPE; + } + } + public void sendChannelRegistrations(final EngineConnection connection) { - final ChannelBuf payload = RegisterChannelUtil.encodePayload(this.channels.keySet()); - final Packet mcPacket = PacketUtil.createPlayPayload(Constants.Channels.REGISTER_KEY, payload, connection.side()); - PacketSender.sendTo(connection, mcPacket); + final Packet mcPacket = PacketUtil.createPlayPayload(new SpongeRegisterChannelPayload(this.channels.keySet()), connection.side()); + // TODO this is currently broken PacketSender.sendTo(connection, mcPacket);/ } /** diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java index f4406af095f..3cc88ad426a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java @@ -111,7 +111,7 @@ public abstract class ServerConfigurationPacketListenerImplMixin extends ServerC return null; }, SpongeCommon.server()).exceptionally(throwable -> { - SpongeCommon.logger().error("Forcibly disconnecting user {} due to an error during login.", this.gameProfile, throwable); + SpongeCommon.logger().error("Forcibly disconnecting user {}({}) due to an error during login.", this.gameProfile.getName(), this.gameProfile.getId(), throwable); this.shadow$disconnect(Component.literal("Internal Server Error: unable to complete login.")); return null; }); diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java new file mode 100644 index 00000000000..e386a0dd82d --- /dev/null +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java @@ -0,0 +1,47 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.vanilla.mixin.core.network.protocol.common; + +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.network.channel.SpongeChannelManager; + +import java.util.ArrayList; +import java.util.List; + +@Mixin(ClientboundCustomPayloadPacket.class) +public abstract class ClientboundCustomPayloadPacketMixin { + + @Redirect(method = "", at = @At(value = "INVOKE", target = "Ljava/util/List;of(Ljava/lang/Object;)Ljava/util/List;")) + private static List vanilla$registerCustomPacketPayloads(Object registrations) { + final List allRegistrations = new ArrayList<>(List.of(registrations)); + allRegistrations.add(new CustomPacketPayload.TypeAndCodec<>(SpongeChannelManager.SpongeRegisterChannelPayload.TYPE, SpongeChannelManager.SpongeRegisterChannelPayload.STREAM_CODEC)); + return allRegistrations; + } + +} diff --git a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json index 1542523f282..42ee3453677 100644 --- a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json +++ b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json @@ -21,15 +21,16 @@ "brigadier.exceptions.CommandSyntaxExceptionMixin_Vanilla", "commands.CommandsMixin_Vanilla", "network.FriendlyByteBufMixin_Vanilla", + "network.protocol.common.ClientboundCustomPayloadPacketMixin", "server.BootstrapMixin_Vanilla", "server.MinecraftServerMixin_Vanilla", "server.commands.SpreadPlayersCommandMixin_Vanilla", "server.level.ServerPlayerMixin_Vanilla", - "server.network.protocol.common.ServerboundCustomPayloadPacketMixin_Vanilla", - "server.network.protocol.login.ServerboundCustomQueryAnswerPacketMixin_Vanilla", "server.network.ServerCommonPacketListenerImplMixin_Vanilla", "server.network.ServerGamePacketListenerImplMixin_Vanilla", "server.network.ServerLoginPacketListenerImplMixin_Vanilla", + "server.network.protocol.common.ServerboundCustomPayloadPacketMixin_Vanilla", + "server.network.protocol.login.ServerboundCustomQueryAnswerPacketMixin_Vanilla", "server.packs.repository.PackRepositoryMixin_Vanilla", "world.entity.EntityMixin_Vanilla", "world.entity.EntityTypeMixin_Vanilla", @@ -38,8 +39,8 @@ "world.entity.item.ItemEntityMixin_Vanilla", "world.entity.projectile.ThrownEnderpearlMixin_Vanilla", "world.entity.vehicle.BoatMixin_Vanilla", - "world.level.block.entity.AbstractFurnaceBlockEntityMixin_Vanilla", "world.level.block.FireBlockMixin_Vanilla", + "world.level.block.entity.AbstractFurnaceBlockEntityMixin_Vanilla", "world.level.portal.PortalForcerMixin_Vanilla", "world.level.storage.LevelStorageSourceMixin_Vanilla" ], From 39d8488979d3442d53620f8d64cd0292a1cc99c1 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 19:14:49 +0100 Subject: [PATCH 145/230] fix client --- .../spongepowered/common/mixin/core/client/MinecraftMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/client/MinecraftMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/client/MinecraftMixin.java index d3e4607ec40..386a1dd6fe0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/client/MinecraftMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/client/MinecraftMixin.java @@ -109,7 +109,7 @@ public MinecraftMixin(String param0) { Launch.instance().lifecycle().callStoppingEngineEvent(this); } - @Redirect(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;singleplayerServer:Lnet/minecraft/client/server/IntegratedServer;", opcode = + @Redirect(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;singleplayerServer:Lnet/minecraft/client/server/IntegratedServer;", opcode = Opcodes.PUTFIELD)) private void impl$storeTemporaryServerRef(Minecraft minecraft, IntegratedServer server) { ((MinecraftBridge) minecraft).bridge$setTemporaryIntegratedServer(this.singleplayerServer); From 0f6d73c76f5a79e7e589d099d111d6e0fb012175 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 19:22:15 +0100 Subject: [PATCH 146/230] fix HopperBlockEntityMixin_Inventory_Vanilla --- ...pperBlockEntityMixin_Inventory_Vanilla.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java index ce3d262a53e..17b1d205a5e 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java @@ -52,14 +52,12 @@ public abstract class HopperBlockEntityMixin_Inventory_Vanilla { at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/HopperBlockEntity;isFullContainer(Lnet/minecraft/world/Container;Lnet/minecraft/core/Direction;)Z")) private static boolean vanilla$throwTransferPreIfNotFull( - final Container attachedContainer, final Direction direction, final Level level, final BlockPos pos, final BlockState state, - final Container container - ) { + final Container attachedContainer, final Direction direction, final Level level, final BlockPos pos, final HopperBlockEntity hopper) { final boolean result = HopperBlockEntityAccessor.invoker$isFullContainer(attachedContainer, direction); if (result || !ShouldFire.TRANSFER_INVENTORY_EVENT_PRE) { return result; } - return InventoryEventFactory.callTransferPre(InventoryUtil.toInventory(container), InventoryUtil.toInventory(attachedContainer)).isCancelled(); + return InventoryEventFactory.callTransferPre(InventoryUtil.toInventory(hopper), InventoryUtil.toInventory(attachedContainer)).isCancelled(); } @@ -70,17 +68,21 @@ public abstract class HopperBlockEntityMixin_Inventory_Vanilla { target = "Lnet/minecraft/world/item/ItemStack;isEmpty()Z", ordinal = 1)) private static void vanilla$afterPutStackInSlots( - final Level var0, final BlockPos var1, final BlockState var2, final Container var3, + final Level var0, final BlockPos var1, final HopperBlockEntity var3, final CallbackInfoReturnable cir, final Container iInventory, final Direction enumFacing, - final int i, final ItemStack itemStack, final ItemStack itemStack1 + final int i, final ItemStack itemStack, int count, final ItemStack itemStack1 ) { // after putStackInInventoryAllSlots if the transfer worked if (ShouldFire.TRANSFER_INVENTORY_EVENT_POST && itemStack1.isEmpty()) { // Capture Insert in Origin final TrackedInventoryBridge capture = InventoryUtil.forCapture(var3); - final SlotTransaction sourceSlotTransaction = InventoryEventFactory.captureTransaction(capture, (Inventory) var3, i, itemStack); + int newCount = itemStack.getCount(); + itemStack.setCount(count); + var originalStack = itemStack.copy(); + itemStack.setCount(newCount); + final SlotTransaction sourceSlotTransaction = InventoryEventFactory.captureTransaction(capture, (Inventory) var3, i, originalStack); // Call event - InventoryEventFactory.callTransferPost(capture, (Inventory) iInventory, InventoryUtil.toInventory(iInventory), itemStack, sourceSlotTransaction); + InventoryEventFactory.callTransferPost(capture, (Inventory) iInventory, InventoryUtil.toInventory(iInventory), originalStack, sourceSlotTransaction); } } From 62b1fd48130a6313f760b658c8440590a0eb7272 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 20:06:17 +0100 Subject: [PATCH 147/230] logging disconnect errors --- .../common/mixin/core/network/ConnectionMixin.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java index 3979651ca56..cdff6403cc7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java @@ -26,6 +26,7 @@ import com.google.common.collect.Sets; import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.local.LocalAddress; import io.netty.util.concurrent.Future; @@ -47,6 +48,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.entity.player.ClientType; @@ -230,4 +232,9 @@ public void accept(final Connection connection) { cir.setReturnValue(false); } } + + @Inject(method = "exceptionCaught", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/Connection;disconnect(Lnet/minecraft/network/chat/Component;)V")) + private void impl$onExceptionDisconnect(final ChannelHandlerContext $$0, final Throwable $$1, final CallbackInfo ci) { + SpongeCommon.logger().error("Disconnected due to error", $$1); + } } From 91e2bfca7291e02d8367423cded094e104f0d25c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 20:39:11 +0100 Subject: [PATCH 148/230] fix advancement stuff --- .../mixin/core/advancements/AdvancementProgressMixin.java | 8 ++++---- .../common/mixin/core/world/scores/ScoreboardMixin.java | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java index e88c1727d69..2caa05a7274 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java @@ -136,7 +136,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri if (!PlatformHooks.INSTANCE.getGeneralHooks().onServerThread()) { return; } - final Optional advancement = this.getOptionalAdvancement(); + final Optional advancement = this.impl$getOptionalAdvancement(); if (advancement.isPresent()) { this.impl$progressMap = new LinkedHashMap<>(); this.impl$processProgressMap(advancement.get().criterion(), this.impl$progressMap); @@ -160,7 +160,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri for (final List reqs : requirements.requirements()) { for (final String req : reqs) { if (!criteria.containsKey(req)) { // TODO was parameter is now field, correct? - final String advName = this.getOptionalAdvancement() + final String advName = this.impl$getOptionalAdvancement() .map(Objects::toString) .orElse("unknown"); throw new IllegalStateException("Found a requirement which does not exist in the criteria, " @@ -212,7 +212,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri return; } - final Advancement advancement = this.getOptionalAdvancement().orElse(null); + final Advancement advancement = this.impl$getOptionalAdvancement().orElse(null); if (advancement != null) { final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); @@ -340,7 +340,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri * * @return The advancement */ - private Optional getOptionalAdvancement() { + private Optional impl$getOptionalAdvancement() { Preconditions.checkState(PlatformHooks.INSTANCE.getGeneralHooks().onServerThread()); Preconditions.checkState(this.impl$advancementKey != null, "The advancement is not yet initialized"); final AdvancementHolder advancement = SpongeCommon.server().getAdvancements().get(this.impl$advancementKey); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/scores/ScoreboardMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/scores/ScoreboardMixin.java index d600eb76c0e..7e49b4a1241 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/scores/ScoreboardMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/scores/ScoreboardMixin.java @@ -59,8 +59,10 @@ public abstract class ScoreboardMixin implements ScoreboardBridge { @Inject(method = "getOrCreatePlayerScore(Lnet/minecraft/world/scores/ScoreHolder;Lnet/minecraft/world/scores/Objective;Z)Lnet/minecraft/world/scores/ScoreAccess;", at = @At("RETURN"), cancellable = true) private void impl$onGetScoreAccess(final ScoreHolder $$0, final Objective $$1, final boolean $$2, final CallbackInfoReturnable cir) { - // wrap to intercept setting data - cir.setReturnValue(new SpongeScore.SpongeScoreAccess($$0, $$1, cir.getReturnValue())); + if ((Scoreboard) (Object) this instanceof ServerScoreboard) { + // wrap to intercept setting data + cir.setReturnValue(new SpongeScore.SpongeScoreAccess($$0, $$1, cir.getReturnValue())); + } } @Inject(method = "addObjective", at = @At("RETURN")) From aca21332ab04b0272c496e4febddf08993faf137 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 20:39:21 +0100 Subject: [PATCH 149/230] TODO I gave up on advancements --- .../mixin/core/advancements/AdvancementProgressMixin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java index 2caa05a7274..0ff9b2b0f8b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java @@ -169,7 +169,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri } } // Update the progress map - this.bridge$updateProgressMap(); + // TODO this breaks on client this.bridge$updateProgressMap(); } private Map impl$getProgressMap() { @@ -214,8 +214,8 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri final Advancement advancement = this.impl$getOptionalAdvancement().orElse(null); if (advancement != null) { - final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); - ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); +// final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); +// ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); } } From cd82c4521f20165f4c606883d8f39d44f24df595 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 21:05:47 +0100 Subject: [PATCH 150/230] TODO check how special recipes can still work, atm this crashes vanilla clients --- .../common/mixin/core/registries/BuiltInRegistriesMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java index 2cca8f0d1a0..b7e44f4358a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java @@ -53,7 +53,7 @@ public abstract class BuiltInRegistriesMixin { @Inject(method = "lambda$static$15", at = @At(value = "FIELD", target = "Lnet/minecraft/world/item/crafting/RecipeSerializer;SHAPELESS_RECIPE:Lnet/minecraft/world/item/crafting/RecipeSerializer;")) private static void impl$staticInitSpongeRecipeSerializers(final Registry $$0, final CallbackInfoReturnable cir) { - final var serializer = SpongeRecipeSerializers.SPONGE_SPECIAL; +// final var serializer = SpongeRecipeSerializers.SPONGE_SPECIAL; } @Inject(method = "bootStrap", at = @At(value = "HEAD")) From da2d6882b9c04e19b9505b47790b550fe63f4d5b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 21:07:26 +0100 Subject: [PATCH 151/230] And in turn it breaks the server when this is commented out so... Revert "TODO I gave up on advancements" This reverts commit c85b0431d67ee7c40452e22c8641d032779263ae. --- .../mixin/core/advancements/AdvancementProgressMixin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java index 0ff9b2b0f8b..2caa05a7274 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java @@ -169,7 +169,7 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri } } // Update the progress map - // TODO this breaks on client this.bridge$updateProgressMap(); + this.bridge$updateProgressMap(); } private Map impl$getProgressMap() { @@ -214,8 +214,8 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri final Advancement advancement = this.impl$getOptionalAdvancement().orElse(null); if (advancement != null) { -// final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); -// ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); + final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); + ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); } } From b73dcd82fc757d3cd668a8c113ffb944b80081fe Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 21:21:04 +0100 Subject: [PATCH 152/230] fix chat --- .../common/mixin/core/server/players/PlayerListMixin.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java index cc421888834..9357367e17d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java @@ -629,7 +629,7 @@ public abstract class PlayerListMixin implements PlayerListBridge { final var chatType = RegistryTypes.CHAT_TYPE.defaultReferenced((org.spongepowered.api.ResourceKey) (Object) chatTypeRegistry.getKey($$4.chatType().value())); final Predicate filter; - final ChatType.Bound boundChatType; + ChatType.Bound boundChatType; try (final CauseStackManager.StackFrame frame = PhaseTracker.SERVER.pushCauseFrame()) { if ($$2 != null) { @@ -642,7 +642,8 @@ public abstract class PlayerListMixin implements PlayerListBridge { return; // Do nothing when canceled or audience removed } boundChatType = ChatType.bind(ResourceKey.create(Registries.CHAT_TYPE, (ResourceLocation) (Object) event.chatType().location()), - this.server.registryAccess(), SpongeAdventure.asVanilla(event.sender())).withTargetName(event.target().map(SpongeAdventure::asVanilla).orElse(null)); + this.server.registryAccess(), SpongeAdventure.asVanilla(event.sender())); + boundChatType = event.target().map(SpongeAdventure::asVanilla).map(boundChatType::withTargetName).orElse(boundChatType); filter = event.filter().map(f -> $$1.and((Predicate) f)).orElse($$1); if (!isTrusted && event.message() != event.originalMessage()) { From 74c75790a923e55baf1265a07089ee70bfbb516a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 21:46:02 +0100 Subject: [PATCH 153/230] fix block interaction --- .../ServerPlayerGameModeMixin_Tracker.java | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java index 5cd18f5aafc..91e3465fc9a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java @@ -137,24 +137,36 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl final boolean flag1 = playerIn.isSecondaryUseActive() && flag; final ItemStack copiedStack = stackIn.copy(); if (useBlock != Tristate.FALSE && !flag1) { // Sponge check useBlock - final AbstractContainerMenu lastOpenContainer = playerIn.containerMenu; final ItemInteractionResult result = blockstate.useItemOn(playerIn.getItemInHand(handIn), worldIn, playerIn, handIn, blockRaytraceResultIn); - if (result.consumesAction() && lastOpenContainer != playerIn.containerMenu) { - final Vector3i pos = VecHelper.toVector3i(blockRaytraceResultIn.getBlockPos()); - final ServerLocation location = ServerLocation.of((ServerWorld) worldIn, pos); - try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { - frame.pushCause(playerIn); - frame.addContext(EventContextKeys.BLOCK_HIT, ((ServerWorld) (worldIn)).createSnapshot(pos)); - ((ContainerBridge) playerIn.containerMenu).bridge$setOpenLocation(location); - if (!InventoryEventFactory.callInteractContainerOpenEvent(playerIn)) { - return InteractionResult.FAIL; - } - } - } + if (result.consumesAction()) { CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(playerIn, blockpos, copiedStack); return result.result(); } + + if (result == ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION && handIn == InteractionHand.MAIN_HAND) { + final AbstractContainerMenu lastOpenContainer = playerIn.containerMenu; // Sponge + final InteractionResult result2 = blockstate.useWithoutItem(worldIn, playerIn, blockRaytraceResultIn); + if (result2.consumesAction()) { + // Sponge Start + if (lastOpenContainer != playerIn.containerMenu) { + final Vector3i pos = VecHelper.toVector3i(blockRaytraceResultIn.getBlockPos()); + final ServerLocation location = ServerLocation.of((ServerWorld) worldIn, pos); + try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { + frame.pushCause(playerIn); + frame.addContext(EventContextKeys.BLOCK_HIT, ((ServerWorld) (worldIn)).createSnapshot(pos)); + ((ContainerBridge) playerIn.containerMenu).bridge$setOpenLocation(location); + if (!InventoryEventFactory.callInteractContainerOpenEvent(playerIn)) { + return InteractionResult.FAIL; + } + } + } + // Sponge End + + CriteriaTriggers.DEFAULT_BLOCK_USE.trigger(playerIn, blockpos); + return result2; + } + } } if (!stackIn.isEmpty() && !playerIn.getCooldowns().isOnCooldown(stackIn.getItem())) { From 3e12390d14a9c6f84ebe927f17a2b7c2d99d275c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 22:22:54 +0100 Subject: [PATCH 154/230] fix ItemStack building --- .../java/org/spongepowered/common/item/SpongeItemStack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java index 49d7d0e3a35..ded2f79f0f9 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java @@ -282,7 +282,7 @@ protected Optional buildContent(final DataView container) throws Inva public ItemStack.Builder reset() { this.type = null; this.quantity = 1; - this.components = null; + this.components = DataComponentMap.EMPTY; return this; } From 61231da8027d1f3bb7e12beb09b5e9bbea756874 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Tue, 5 Mar 2024 22:30:50 +0100 Subject: [PATCH 155/230] fix missing SmithingRecipe Mixin --- src/mixins/resources/mixins.sponge.api.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 8b246d18910..03261cbd18c 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -306,6 +306,7 @@ "minecraft.world.item.crafting.ShapedRecipeMixin_API", "minecraft.world.item.crafting.ShapelessRecipeMixin_API", "minecraft.world.item.crafting.SingleItemRecipeMixin_API", + "minecraft.world.item.crafting.SmithingTransformRecipeMixin_API", "minecraft.world.item.crafting.StonecutterRecipeMixin_API", "minecraft.world.item.enchantment.EnchantmentMixin_API", "minecraft.world.item.trading.MerchantOfferMixin_API", From bbd0d32d38a3086b28fd6b3caa27ac4e30741af8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 19:58:22 +0100 Subject: [PATCH 156/230] 24w10a --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 5626f33d0f3..475d26d6916 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=24w09a +minecraftVersion=24w10a recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From b61df5d6ef021003981b65a69d73599ead1bf117 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 19:58:47 +0100 Subject: [PATCH 157/230] fix CompassItemData --- .../data/provider/item/stack/CompassItemData.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java index 8c96837c120..c3c4c251928 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/CompassItemData.java @@ -29,7 +29,7 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.component.LodestoneTarget; +import net.minecraft.world.item.component.LodestoneTracker; import net.minecraft.world.level.Level; import org.spongepowered.api.data.Keys; import org.spongepowered.api.world.server.ServerLocation; @@ -38,6 +38,8 @@ import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.VecHelper; +import java.util.Optional; + final class CompassItemData { private CompassItemData() { @@ -48,17 +50,18 @@ static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.LODESTONE) .get(stack -> { - final LodestoneTarget component = stack.get(DataComponents.LODESTONE_TARGET); + final LodestoneTracker component = stack.get(DataComponents.LODESTONE_TRACKER); if (component != null) { return null; } - return ServerLocation.of((ServerWorld) SpongeCommon.server().getLevel(component.pos().dimension()), - VecHelper.toVector3d(component.pos().pos())); + final GlobalPos globalPos = component.target().get(); + return ServerLocation.of((ServerWorld) SpongeCommon.server().getLevel(globalPos.dimension()), + VecHelper.toVector3d(globalPos.pos())); }) .set((stack, location) -> { final ResourceKey dim = ((ServerLevel) location.world()).dimension(); - stack.set(DataComponents.LODESTONE_TARGET, new LodestoneTarget(new GlobalPos(dim, VecHelper.toBlockPos(location)), true)); + stack.set(DataComponents.LODESTONE_TRACKER, new LodestoneTracker(Optional.of(new GlobalPos(dim, VecHelper.toBlockPos(location))), true)); }) - .delete(stack -> stack.remove(DataComponents.LODESTONE_TARGET)); + .delete(stack -> stack.remove(DataComponents.LODESTONE_TRACKER)); } } From 2a9cc66d73ac99b3d26b1b451f09b48a53c04184 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:05:07 +0100 Subject: [PATCH 158/230] fix recipe codecs, vanilla now supports nbt/components for result stacks --- .../recipe/crafting/shaped/SpongeShapedRecipe.java | 10 ++++------ .../crafting/shapeless/SpongeShapelessRecipe.java | 7 ++----- .../item/recipe/smithing/SpongeSmithingRecipe.java | 8 +++----- .../mixin/core/registries/BuiltInRegistriesMixin.java | 10 ---------- 4 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java index 1a03fab7f54..5d13add5666 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java @@ -52,9 +52,8 @@ public class SpongeShapedRecipe extends ShapedRecipe implements ResultFunctionRe ExtraCodecs.strictOptionalField(Codec.STRING, Constants.Recipe.GROUP, "").forGetter(ShapedRecipe::getGroup), CraftingBookCategory.CODEC.fieldOf(Constants.Recipe.CATEGORY).orElse(CraftingBookCategory.MISC).forGetter(ShapedRecipe::category), ShapedRecipePattern.MAP_CODEC.forGetter($$0x -> ((ShapedRecipeBridge) $$0x).bridge$pattern()), - ItemStack.ITEM_WITH_COUNT_CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), + ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), ExtraCodecs.strictOptionalField(Codec.BOOL, "show_notification", true).forGetter(ShapedRecipe::showNotification), - ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$spongeResult()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId), IngredientResultUtil.CACHED_REMAINING_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_REMAINING_ITEMS).forGetter(SpongeShapedRecipe::remainingItemsFunctionId) ) @@ -70,7 +69,6 @@ public static SpongeShapedRecipe of( final ShapedRecipePattern pattern, final ItemStack recipeOutputIn, final boolean showNotification, - final ItemStack spongeResultStack, final Optional resultFunctionId, final Optional remainingItemsFunctionId) { return new SpongeShapedRecipe( @@ -78,7 +76,7 @@ public static SpongeShapedRecipe of( category, pattern, showNotification, - spongeResultStack.isEmpty() ? recipeOutputIn : spongeResultStack, + recipeOutputIn, resultFunctionId.orElse(null), remainingItemsFunctionId.orElse(null)); } @@ -88,10 +86,10 @@ public SpongeShapedRecipe( final CraftingBookCategory category, final ShapedRecipePattern pattern, final boolean showNotification, - final ItemStack spongeResultStack, + final ItemStack resultStack, final String resultFunctionId, final String remainingItemsFunctionId) { - super(groupIn, category, pattern, spongeResultStack, showNotification); + super(groupIn, category, pattern, resultStack, showNotification); this.resultFunctionId = resultFunctionId; this.remainingItemsFunctionId = remainingItemsFunctionId; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java index 94bb86d03c2..3fd70000124 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java @@ -63,7 +63,7 @@ public class SpongeShapelessRecipe extends ShapelessRecipe { Codec.STRING.fieldOf(Constants.Recipe.SPONGE_TYPE).forGetter(t -> "custom"), // important to fail early when decoding vanilla recipes ExtraCodecs.strictOptionalField(Codec.STRING, "group", "").forGetter(ShapelessRecipe::getGroup), CraftingBookCategory.CODEC.fieldOf("category").orElse(CraftingBookCategory.MISC).forGetter(ShapelessRecipe::category), - ItemStack.ITEM_WITH_COUNT_CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), + ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), Ingredient.CODEC_NONEMPTY .listOf() .fieldOf(Constants.Recipe.SHAPELESS_INGREDIENTS) @@ -81,7 +81,6 @@ public class SpongeShapelessRecipe extends ShapelessRecipe { DataResult::success ) .forGetter(ShapelessRecipe::getIngredients), - ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$spongeResult()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(SpongeShapelessRecipe::resultFunctionId), IngredientResultUtil.CACHED_REMAINING_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_REMAINING_ITEMS).forGetter(SpongeShapelessRecipe::remainingItemsFunctionId) ) @@ -99,12 +98,10 @@ public static SpongeShapelessRecipe of( final CraftingBookCategory category, final ItemStack recipeOutputIn, final NonNullList recipeItemsIn, - final ItemStack spongeResultStack, final Optional resultFunctionId, final Optional remainingItemsFunctionId) { - return new SpongeShapelessRecipe(groupIn, category, recipeItemsIn, - spongeResultStack.isEmpty() ? recipeOutputIn : spongeResultStack, + return new SpongeShapelessRecipe(groupIn, category, recipeItemsIn, recipeOutputIn, resultFunctionId.orElse(null), remainingItemsFunctionId.orElse(null)); } diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java index 5435a3e5c23..515fd76f609 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java @@ -30,7 +30,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -51,8 +50,7 @@ public class SpongeSmithingRecipe extends SmithingTransformRecipe implements Res Ingredient.CODEC.fieldOf("template").forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$template()), Ingredient.CODEC.fieldOf(Constants.Recipe.SMITHING_BASE_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$base()), Ingredient.CODEC.fieldOf(Constants.Recipe.SMITHING_ADDITION_INGREDIENT).forGetter($$0x -> ((SmithingRecipeBridge) $$0x).bridge$addition()), - ItemStack.ITEM_WITH_COUNT_CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge) $$0x).bridge$result()), - ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge) $$0x).bridge$spongeResult()), + ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge) $$0x).bridge$result()), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId) ) .apply($$0, SpongeSmithingRecipe::of) @@ -61,9 +59,9 @@ public class SpongeSmithingRecipe extends SmithingTransformRecipe implements Res private final String resultFunctionId; public static SpongeSmithingRecipe of(final String spongeType, final Ingredient template, final Ingredient base, - final Ingredient addition, final ItemStack resultIn, final ItemStack spongeResult, final Optional resultFunctionId) + final Ingredient addition, final ItemStack resultIn, final Optional resultFunctionId) { - return new SpongeSmithingRecipe(template, base, addition, spongeResult.isEmpty() ? resultIn : spongeResult, resultFunctionId.orElse(null)); + return new SpongeSmithingRecipe(template, base, addition, resultIn, resultFunctionId.orElse(null)); } public SpongeSmithingRecipe(final Ingredient template, final Ingredient base, diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java index b7e44f4358a..01b7d782789 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/registries/BuiltInRegistriesMixin.java @@ -25,18 +25,14 @@ package org.spongepowered.common.mixin.core.registries; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.RecipeSerializer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.common.item.recipe.SpongeRecipeSerializers; import org.spongepowered.common.launch.Launch; import java.util.Map; @@ -50,12 +46,6 @@ public abstract class BuiltInRegistriesMixin { @Shadow @Final private static Map> LOADERS; - @Inject(method = "lambda$static$15", at = @At(value = "FIELD", target = "Lnet/minecraft/world/item/crafting/RecipeSerializer;SHAPELESS_RECIPE:Lnet/minecraft/world/item/crafting/RecipeSerializer;")) - private static void impl$staticInitSpongeRecipeSerializers(final Registry $$0, final CallbackInfoReturnable cir) - { -// final var serializer = SpongeRecipeSerializers.SPONGE_SPECIAL; - } - @Inject(method = "bootStrap", at = @At(value = "HEAD")) private static void impl$beforeCreateContents(CallbackInfo ci) { From c4fe1f7d4f61c7f501cb62d897cdb08278194b8c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:05:13 +0100 Subject: [PATCH 159/230] fix ItemStackUtil --- .../java/org/spongepowered/common/item/util/ItemStackUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/item/util/ItemStackUtil.java b/src/main/java/org/spongepowered/common/item/util/ItemStackUtil.java index c96d6c4a85a..5165443c451 100644 --- a/src/main/java/org/spongepowered/common/item/util/ItemStackUtil.java +++ b/src/main/java/org/spongepowered/common/item/util/ItemStackUtil.java @@ -119,7 +119,7 @@ public static Optional cloneDefensiveOptional(net.minecraft.world.ite } public static boolean compareIgnoreQuantity(net.minecraft.world.item.ItemStack stack1, net.minecraft.world.item.ItemStack stack2) { - return net.minecraft.world.item.ItemStack.isSameItemSameTags(stack1, stack2); + return net.minecraft.world.item.ItemStack.isSameItemSameComponents(stack1, stack2); } public static boolean compareIgnoreQuantity(net.minecraft.world.item.ItemStack stack1, ItemStack stack2) { From 8ed7ad9095d484367c2bdd6b5fe4aa8454735004 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:33:35 +0100 Subject: [PATCH 160/230] fix AttributeModifiers --- .../attribute/SpongeAttributeModifierBuilder.java | 2 +- .../ai/attributes/AttributeInstanceMixin_API.java | 13 +++++++------ .../ai/attributes/AttributeModifierMixin_API.java | 15 +++++++++------ .../minecraft/world/item/ItemStackMixin_API.java | 4 ++-- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/spongepowered/common/entity/attribute/SpongeAttributeModifierBuilder.java b/src/main/java/org/spongepowered/common/entity/attribute/SpongeAttributeModifierBuilder.java index d7d639732ec..54a5452e6cf 100644 --- a/src/main/java/org/spongepowered/common/entity/attribute/SpongeAttributeModifierBuilder.java +++ b/src/main/java/org/spongepowered/common/entity/attribute/SpongeAttributeModifierBuilder.java @@ -68,7 +68,7 @@ public AttributeModifier.Builder amount(final double amount) { public AttributeModifier build() { Objects.requireNonNull(this.name, "Name must be set"); Objects.requireNonNull(this.operation, "Operation must be set"); - return (AttributeModifier) new net.minecraft.world.entity.ai.attributes.AttributeModifier(this.id, this.name, this.amount, (net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation) (Object) this.operation); + return (AttributeModifier) (Object) new net.minecraft.world.entity.ai.attributes.AttributeModifier(this.id, this.name, this.amount, (net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation) (Object) this.operation); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java index f64f2d4c60a..79d63af52ac 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeInstanceMixin_API.java @@ -38,6 +38,7 @@ import org.spongepowered.asm.mixin.Shadow; import java.util.Collection; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -57,7 +58,7 @@ public abstract class AttributeInstanceMixin_API implements Attribute { @Shadow protected abstract void shadow$addModifier(net.minecraft.world.entity.ai.attributes.AttributeModifier modifier); @Shadow public abstract void shadow$removeModifier(net.minecraft.world.entity.ai.attributes.AttributeModifier modifier); @Shadow public abstract void shadow$removeModifier(UUID uuid); - @Shadow public abstract Set shadow$getModifiers(net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation p_225504_1_); + @Shadow abstract Map shadow$getModifiers(net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation p_225504_1_); @Shadow public abstract Set shadow$getModifiers(); // @formatter:on @@ -88,27 +89,27 @@ public Collection modifiers() { @Override public Collection modifiers(final AttributeOperation operation) { - return (Collection) this.shadow$getModifiers((net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation) (Object) Objects.requireNonNull(operation, "operation")); + return (Collection) this.shadow$getModifiers((net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation) (Object) Objects.requireNonNull(operation, "operation")).values(); } @Override public boolean hasModifier(final AttributeModifier modifier) { - return this.shadow$hasModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) Objects.requireNonNull(modifier, "modifier")); + return this.shadow$hasModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) (Object) Objects.requireNonNull(modifier, "modifier")); } @Override public Optional modifier(final UUID uniqueId) { - return Optional.ofNullable((AttributeModifier) this.shadow$getModifier(Objects.requireNonNull(uniqueId, "uniqueId"))); + return Optional.ofNullable((AttributeModifier) (Object) this.shadow$getModifier(Objects.requireNonNull(uniqueId, "uniqueId"))); } @Override public void addModifier(final AttributeModifier modifier) { - this.shadow$addModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) Objects.requireNonNull(modifier, "modifier")); + this.shadow$addModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) (Object) Objects.requireNonNull(modifier, "modifier")); } @Override public void removeModifier(final AttributeModifier modifier) { - this.shadow$removeModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) Objects.requireNonNull(modifier, "modifier")); + this.shadow$removeModifier((net.minecraft.world.entity.ai.attributes.AttributeModifier) (Object) Objects.requireNonNull(modifier, "modifier")); } @Intrinsic diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeModifierMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeModifierMixin_API.java index 9c522d061ed..d28ade0751a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeModifierMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/ai/attributes/AttributeModifierMixin_API.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.entity.ai.attributes; +import net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation; import org.spongepowered.api.entity.attribute.AttributeModifier; import org.spongepowered.api.entity.attribute.AttributeOperation; import org.spongepowered.asm.mixin.Final; @@ -37,13 +38,14 @@ public abstract class AttributeModifierMixin_API implements AttributeModifier { // @formatter:off @Shadow @Final private String name; + @Shadow @Final private double amount; + @Shadow @Final private UUID id; - @Shadow public abstract double shadow$getAmount(); - @Shadow public abstract net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation shadow$getOperation(); - @Shadow public abstract UUID shadow$getId(); + @Shadow @Final private Operation operation; // @formatter:on + @Override public String name() { return this.name; @@ -51,17 +53,18 @@ public String name() { @Override public AttributeOperation operation() { - return (AttributeOperation) (Object) this.shadow$getOperation(); + + return (AttributeOperation) (Object) this.operation; } @Override public double amount() { - return this.shadow$getAmount(); + return this.amount; } @Override public UUID uniqueId() { - return this.shadow$getId(); + return this.id; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java index c8ffb7bce77..e4a51424ca1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemStackMixin_API.java @@ -151,7 +151,7 @@ public SerializableDataHolder.Mutable copy() { final var modifiers = ((net.minecraft.world.item.ItemStack) (Object) this).getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY); for (final ItemAttributeModifiers.Entry entry : modifiers.modifiers()) { if (entry.attribute().value().equals(attributeType) && entry.slot().test(((EquipmentSlot) (Object) equipmentType))) { - builder.add((AttributeModifier) entry.modifier()); + builder.add((AttributeModifier) (Object) entry.modifier()); } } @@ -176,7 +176,7 @@ public SerializableDataHolder.Mutable copy() { this.shadow$update(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY, component -> component.withModifierAdded(Holder.direct((Attribute) attributeType), - (net.minecraft.world.entity.ai.attributes.AttributeModifier) modifier, + (net.minecraft.world.entity.ai.attributes.AttributeModifier) (Object) modifier, group)); } From 80e1ed4eb77de65b486f1ae5d758a30c15ff7a7d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:35:19 +0100 Subject: [PATCH 161/230] fix BannerData --- .../common/data/provider/block/entity/BannerData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java index f1a61032b82..a0432e6644c 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java @@ -46,7 +46,7 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(BannerBlockEntity.class) .create(Keys.BANNER_PATTERN_LAYERS) - .get(h -> h.getPatternsWithBase().layers().stream().map(BannerPatternLayer.class::cast).toList()) + .get(h -> h.getPatterns().layers().stream().map(BannerPatternLayer.class::cast).toList()) .setAnd((h, v) -> { final Level world = h.getLevel(); if (world != null && !world.isClientSide) { // This avoids a client crash because clientside. From d8ad291ca6277ae3694fa548183bb3af9264d607 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:39:10 +0100 Subject: [PATCH 162/230] TODO check if changing basecolor works fix BannerBlockEntityMixin --- .../core/world/level/block/entity/BannerBlockEntityMixin.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java index 0f50b1511b6..2c71c51ae6e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BannerBlockEntityMixin.java @@ -28,7 +28,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.block.entity.BannerBlockEntity; -import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -43,8 +42,6 @@ public abstract class BannerBlockEntityMixin extends BlockEntityMixin implements BannerBlockEntityBridge, CustomNameableBridge { @Shadow private net.minecraft.world.item.DyeColor baseColor; - @Shadow private BannerPatternLayers patternsWithBase; - @Shadow private BannerPatternLayers itemPatterns; @Shadow @Nullable private Component name; private void impl$markDirtyAndUpdate() { @@ -69,7 +66,6 @@ public abstract class BannerBlockEntityMixin extends BlockEntityMixin implements } catch (final Exception e) { this.baseColor = net.minecraft.world.item.DyeColor.BLACK; } - this.patternsWithBase = this.itemPatterns.withBase(this.baseColor); this.impl$markDirtyAndUpdate(); } From 5ff57f0679ef91442402060291106c43c1297a2c Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:44:56 +0100 Subject: [PATCH 163/230] TODO check if registry is found this way fix BannerPatternLayers_LayerMixin_API --- .../level/block/entity/BannerPatternLayers_LayerMixin_API.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java index de3818a5bf1..fb9ede182e1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java @@ -26,6 +26,7 @@ import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.world.level.block.entity.BannerPattern; import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.ResourceKey; @@ -65,7 +66,7 @@ public int contentVersion() { @Override public DataContainer toContainer() { - final ResourceKey idKey = (ResourceKey) (Object) BuiltInRegistries.BANNER_PATTERN.getKey(this.pattern.value()); + final ResourceKey idKey = Sponge.game().registry(RegistryTypes.BANNER_PATTERN_SHAPE).valueKey(this.shape()); final ResourceKey colorKey = Sponge.game().registry(RegistryTypes.DYE_COLOR).valueKey(this.color()); return DataContainer.createNew() .set(Queries.CONTENT_VERSION, this.contentVersion()) From 2c994745235d4ff726fc3bb3e4fe1eec14fb0054 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Wed, 6 Mar 2024 20:46:29 +0100 Subject: [PATCH 164/230] fix Gameprofile --- .../entity/SkullBlockEntityAccessor.java | 37 -------------- .../resources/mixins.sponge.accessors.json | 1 - .../block/entity/SkullBlockEntityBridge.java | 33 ------------- .../data/provider/block/entity/SkullData.java | 13 ++--- .../entity/living/human/HumanEntity.java | 48 ++++++++++--------- .../entity/living/HumanEntityMixin_API.java | 6 +-- .../block/entity/SkullBlockEntityMixin.java | 18 +------ 7 files changed, 36 insertions(+), 120 deletions(-) delete mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/SkullBlockEntityAccessor.java delete mode 100644 src/main/java/org/spongepowered/common/bridge/world/level/block/entity/SkullBlockEntityBridge.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/SkullBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/SkullBlockEntityAccessor.java deleted file mode 100644 index 8070c4d1777..00000000000 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/SkullBlockEntityAccessor.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.accessor.world.level.block.entity; - -import com.mojang.authlib.GameProfile; -import net.minecraft.world.level.block.entity.SkullBlockEntity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(SkullBlockEntity.class) -public interface SkullBlockEntityAccessor { - - @Accessor("owner") GameProfile accessor$owner(); - -} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 648c1eff914..d2d4d7dfb5a 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -171,7 +171,6 @@ "world.level.block.entity.EnchantmentTableBlockEntityAccessor", "world.level.block.entity.HopperBlockEntityAccessor", "world.level.block.entity.LecternBlockEntity_Accessor", - "world.level.block.entity.SkullBlockEntityAccessor", "world.level.block.entity.SpawnerBlockEntityAccessor", "world.level.block.entity.StructureBlockEntityAccessor", "world.level.block.entity.TheEndGatewayBlockEntityAccessor", diff --git a/src/main/java/org/spongepowered/common/bridge/world/level/block/entity/SkullBlockEntityBridge.java b/src/main/java/org/spongepowered/common/bridge/world/level/block/entity/SkullBlockEntityBridge.java deleted file mode 100644 index 5fcb1a03079..00000000000 --- a/src/main/java/org/spongepowered/common/bridge/world/level/block/entity/SkullBlockEntityBridge.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.bridge.world.level.block.entity; - -import com.mojang.authlib.GameProfile; -import org.checkerframework.checker.nullness.qual.Nullable; - -public interface SkullBlockEntityBridge { - - void bridge$setUnresolvedPlayerProfile(@Nullable GameProfile mcProfile); -} diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/SkullData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/SkullData.java index c41d485cb53..3236b1e1d77 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/SkullData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/SkullData.java @@ -24,10 +24,9 @@ */ package org.spongepowered.common.data.provider.block.entity; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.block.entity.SkullBlockEntity; import org.spongepowered.api.data.Keys; -import org.spongepowered.common.accessor.world.level.block.entity.SkullBlockEntityAccessor; -import org.spongepowered.common.bridge.world.level.block.entity.SkullBlockEntityBridge; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.profile.SpongeGameProfile; @@ -42,15 +41,13 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(SkullBlockEntity.class) .create(Keys.GAME_PROFILE) .get(h -> { - if (h instanceof SkullBlockEntityAccessor sbea) { - if (sbea.accessor$owner() != null) { - return SpongeGameProfile.of(sbea.accessor$owner()); - } + if (h.getOwnerProfile() != null) { + return SpongeGameProfile.of(h.getOwnerProfile().gameProfile()); } return null; }) - .set((h, v) -> ((SkullBlockEntityBridge) h).bridge$setUnresolvedPlayerProfile(SpongeGameProfile.toMcProfile(v))) - .delete(h -> ((SkullBlockEntityBridge) h).bridge$setUnresolvedPlayerProfile(null)); + .set((h, v) -> h.setOwner(new ResolvableProfile(SpongeGameProfile.toMcProfile(v)))) + .delete(h -> h.setOwner(null)); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java index f07519d9827..9f7bdbd627c 100644 --- a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java +++ b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java @@ -28,10 +28,13 @@ import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.yggdrasil.ProfileResult; +import com.mojang.serialization.DataResult; import net.kyori.adventure.text.Component; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtUtils; +import net.minecraft.nbt.Tag; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; @@ -64,6 +67,7 @@ import net.minecraft.world.item.ArrowItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.GameType; @@ -113,12 +117,12 @@ public static AttributeSupplier createAttributes() { // A queue of packets waiting to send to players tracking this human private final Map>>> playerPacketMap = new HashMap<>(); - private GameProfile fakeProfile; + private ResolvableProfile fakeProfile; private boolean aiDisabled = false, leftHanded = false; public HumanEntity(final EntityType type, final Level world) { super(type, world); - this.fakeProfile = new GameProfile(this.uuid, ""); + this.fakeProfile = new ResolvableProfile(new GameProfile(this.uuid, "")); this.setCanPickUpLoot(true); this.entityData.set(PlayerAccessor.accessor$DATA_PLAYER_MODE_CUSTOMISATION(), Constants.Sponge.Entity.Human.PLAYER_MODEL_FLAG_ALL); } @@ -164,12 +168,12 @@ public boolean isNoAi() { @Override public Component teamRepresentation() { - return Component.text(this.fakeProfile.getName()); + return Component.text(this.fakeProfile.name().orElse("")); } @Override public PlayerTeam getTeam() { - return this.level().getScoreboard().getPlayersTeam(this.fakeProfile.getName()); + return this.level().getScoreboard().getPlayersTeam(this.fakeProfile.name().orElse("")); } @Override @@ -189,20 +193,20 @@ public void setCustomName(final net.minecraft.network.chat.@Nullable Component n public void readAdditionalSaveData(final CompoundTag tag) { super.readAdditionalSaveData(tag); if (tag.contains("profile")) { - this.fakeProfile = NbtUtils.readGameProfile(tag.getCompound("profile")); - this.setUUID(this.fakeProfile.getId()); - // Fix Vanilla not writing profiles with empty names, instead it skips the "name" property. We allow humans to have no names - // but they are players on the client. Easiest fix is just to check for the null name and make it empty - if (this.fakeProfile.getName() == null) { - this.fakeProfile = new GameProfile(this.fakeProfile.getId(), ""); - } + ResolvableProfile.CODEC + .parse(NbtOps.INSTANCE, tag.get("profile")) + .resultOrPartial($$0x -> SpongeCommon.logger().error("Failed to load profile from player head: {}", $$0x)) + .ifPresent(profile -> this.fakeProfile = profile); + + this.setUUID(this.fakeProfile.id().get()); } } @Override public void addAdditionalSaveData(final CompoundTag tag) { super.addAdditionalSaveData(tag); - tag.put("profile", NbtUtils.writeGameProfile(new CompoundTag(), this.fakeProfile)); + final DataResult result = ResolvableProfile.CODEC.encodeStart(NbtOps.INSTANCE, this.fakeProfile); + tag.put("profile", result.result().get()); } @Override @@ -337,9 +341,8 @@ public boolean doHurtTarget(final Entity entityIn) { } private void setProfileName(final net.minecraft.network.chat.@Nullable Component newName) { - final PropertyMap props = this.fakeProfile.getProperties(); - this.fakeProfile = new GameProfile(this.fakeProfile.getId(), newName == null ? "" : newName.getString()); - this.fakeProfile.getProperties().putAll(props); + final Optional optName = Optional.ofNullable(newName).map(net.minecraft.network.chat.Component::getString); + this.fakeProfile = new ResolvableProfile(optName, this.fakeProfile.id(), this.fakeProfile.properties()); } public boolean getOrLoadSkin(final UUID minecraftAccount) { @@ -358,7 +361,7 @@ public boolean getOrLoadSkin(final UUID minecraftAccount) { SpongeCommon.server().getProfileCache().add(gameProfile); } - this.fakeProfile.getProperties().replaceValues(ProfileProperty.TEXTURES, gameProfile.getProperties().get(ProfileProperty.TEXTURES)); + this.fakeProfile.properties().replaceValues(ProfileProperty.TEXTURES, gameProfile.getProperties().get(ProfileProperty.TEXTURES)); if (this.isAliveAndInWorld()) { this.respawnOnClient(); } @@ -382,8 +385,8 @@ public boolean getOrLoadSkin(final String minecraftAccount) { SpongeCommon.server().getProfileCache().add(gameProfile); } - this.fakeProfile.getProperties().clear(); - this.fakeProfile.getProperties().putAll(gameProfile.getProperties()); + this.fakeProfile.properties().clear(); + this.fakeProfile.properties().putAll(gameProfile.getProperties()); if (this.isAliveAndInWorld()) { this.respawnOnClient(); } @@ -406,7 +409,7 @@ public void removeFromTabListDelayed(final @Nullable ServerPlayer player, final } public SpongeProfileProperty getSkinProperty() { - final Collection properties = this.fakeProfile.getProperties().get(ProfileProperty.TEXTURES); + final Collection properties = this.fakeProfile.properties().get(ProfileProperty.TEXTURES); if (properties.isEmpty()) { return null; } @@ -414,7 +417,7 @@ public SpongeProfileProperty getSkinProperty() { } public void setSkinProperty(final ProfileProperty property) { - this.fakeProfile.getProperties() + this.fakeProfile.properties() .replaceValues( ProfileProperty.TEXTURES, Collections.singletonList(((SpongeProfileProperty) property).asProperty())); @@ -440,7 +443,7 @@ private void respawnOnClient() { * @return Whether it can be removed with 0 ticks delay */ public boolean canRemoveFromListImmediately() { - return !this.fakeProfile.getProperties().containsKey(ProfileProperty.TEXTURES); + return !this.fakeProfile.properties().containsKey(ProfileProperty.TEXTURES); } /** @@ -464,7 +467,8 @@ public void untrackFrom(final ServerPlayer player) { */ public ClientboundPlayerInfoUpdatePacket createPlayerListPacket(final EnumSet actions) { final ClientboundPlayerInfoUpdatePacket packet = new ClientboundPlayerInfoUpdatePacket(actions, List.of()); - ((ClientboundPlayerInfoUpdatePacketAccessor) packet).accessor$entries(List.of(new ClientboundPlayerInfoUpdatePacket.Entry(this.uuid, this.fakeProfile, false, 0, GameType.DEFAULT_MODE, this.getDisplayName(), null))); + + ((ClientboundPlayerInfoUpdatePacketAccessor) packet).accessor$entries(List.of(new ClientboundPlayerInfoUpdatePacket.Entry(this.uuid, this.fakeProfile.gameProfile(), false, 0, GameType.DEFAULT_MODE, this.getDisplayName(), null))); return packet; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/common/entity/living/HumanEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/common/entity/living/HumanEntityMixin_API.java index 09a632f9cd7..6059d74bf2a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/common/entity/living/HumanEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/common/entity/living/HumanEntityMixin_API.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.mixin.api.common.entity.living; -import com.mojang.authlib.GameProfile; +import net.minecraft.world.item.component.ResolvableProfile; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.entity.living.Human; @@ -40,11 +40,11 @@ @Mixin(value = HumanEntity.class, remap = false) public abstract class HumanEntityMixin_API extends PathfinderMobMixin_API implements Human { - @Shadow private GameProfile fakeProfile; + @Shadow private ResolvableProfile fakeProfile; @Override public String name() { - return this.fakeProfile.getName(); + return this.fakeProfile.name().orElse(""); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/SkullBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/SkullBlockEntityMixin.java index 4cd0688310d..bfa1bccad02 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/SkullBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/SkullBlockEntityMixin.java @@ -24,33 +24,19 @@ */ package org.spongepowered.common.mixin.core.world.level.block.entity; -import com.mojang.authlib.GameProfile; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.block.state.BlockState; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.bridge.world.level.block.entity.SkullBlockEntityBridge; @Mixin(SkullBlockEntity.class) -public abstract class SkullBlockEntityMixin extends BlockEntity implements SkullBlockEntityBridge { +public abstract class SkullBlockEntityMixin extends BlockEntity { - @Shadow private GameProfile owner; - - private SkullBlockEntityMixin( - final BlockEntityType var1, final BlockPos var2, final BlockState var3 - ) { + private SkullBlockEntityMixin(final BlockEntityType var1, final BlockPos var2, final BlockState var3) { super(var1, var2, var3); } - @Override - public void bridge$setUnresolvedPlayerProfile(final @Nullable GameProfile owner) { - // TODO: cancel existing resolve future from authlib callback - this.owner = owner; - this.setChanged(); - } } From 7112e9be5531ed7988a583a96bf24c4ec760d062 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 15 Mar 2024 17:37:34 +0100 Subject: [PATCH 165/230] 24w11a --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 475d26d6916..a47e6508ab0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=24w10a +minecraftVersion=24w11a recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From e2fd5699734b58c336387667bb9312c7a0578132 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 15 Mar 2024 17:56:03 +0100 Subject: [PATCH 166/230] fix data --- .../world/entity/animal/CatAccessor.java | 40 +++++++++++++++++++ .../world/entity/animal/WolfAccessor.java | 3 ++ .../resources/mixins.sponge.accessors.json | 1 + .../common/data/provider/entity/CatData.java | 8 ++-- .../common/data/provider/entity/WolfData.java | 2 +- 5 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/CatAccessor.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/CatAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/CatAccessor.java new file mode 100644 index 00000000000..0612395f449 --- /dev/null +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/CatAccessor.java @@ -0,0 +1,40 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.accessor.world.entity.animal; + +import net.minecraft.world.entity.animal.Cat; +import net.minecraft.world.item.DyeColor; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(Cat.class) +public interface CatAccessor { + + @Invoker("setCollarColor") void invoker$setCollarColor(final DyeColor $$0); + + @Invoker("setRelaxStateOne") void invoker$setRelaxStateOne(boolean $$0); + + @Invoker("isRelaxStateOne") boolean invoker$isRelaxStateOne(); +} diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/WolfAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/WolfAccessor.java index be237dc2974..3c1ba1ae088 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/WolfAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/WolfAccessor.java @@ -26,8 +26,10 @@ import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.world.entity.animal.Wolf; +import net.minecraft.world.item.DyeColor; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedAccessorError; @Mixin(Wolf.class) @@ -48,5 +50,6 @@ public interface WolfAccessor { @Accessor("shakeAnim") void accessor$shakeAnim(final float shakeAnim); @Accessor("shakeAnimO") void accessor$shakeAnimO(final float shakeAnim0); + @Invoker("setCollarColor") void invoker$setCollarColor(final DyeColor $$0); } diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index d2d4d7dfb5a..1d8df9c9905 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -69,6 +69,7 @@ "world.entity.MobAccessor", "world.entity.ai.targeting.TargetingConditionsAccessor", "world.entity.animal.AnimalAccessor", + "world.entity.animal.CatAccessor", "world.entity.animal.FoxAccessor", "world.entity.animal.MushroomCow_MushroomTypeAccessor", "world.entity.animal.OcelotAccessor", diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java b/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java index 9f5d88fa229..d7cb5bb58cb 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java @@ -29,6 +29,7 @@ import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.CatType; import org.spongepowered.api.data.type.DyeColor; +import org.spongepowered.common.accessor.world.entity.animal.CatAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.MissingImplementationException; @@ -46,7 +47,7 @@ public static void register(final DataProviderRegistrator registrator) { .set((h, v) -> h.setVariant((CatVariant) (Object) v)) .create(Keys.DYE_COLOR) .get(h -> (DyeColor) (Object) h.getCollarColor()) - .set((h, v) -> h.setCollarColor((net.minecraft.world.item.DyeColor) (Object) v)) + .set((h, v) -> ((CatAccessor)h).invoker$setCollarColor((net.minecraft.world.item.DyeColor) (Object) v)) .create(Keys.IS_BEGGING_FOR_FOOD) .get(h -> { throw new MissingImplementationException("CatData", "IS_BEGGING_FOR_FOOD::getter"); @@ -71,9 +72,10 @@ public static void register(final DataProviderRegistrator registrator) { .set((h, v) -> { throw new MissingImplementationException("CatData", "IS_PURRING::setter"); }) + .asMutable(CatAccessor.class) .create(Keys.IS_RELAXED) - .get(Cat::isRelaxStateOne) - .set(Cat::setRelaxStateOne); + .get(CatAccessor::invoker$isRelaxStateOne) + .set(CatAccessor::invoker$setRelaxStateOne); } // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/WolfData.java b/src/main/java/org/spongepowered/common/data/provider/entity/WolfData.java index 5c3becd0b03..3328216b1f4 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/WolfData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/WolfData.java @@ -41,7 +41,7 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(Wolf.class) .create(Keys.DYE_COLOR) .get(h -> (DyeColor) (Object) h.getCollarColor()) - .set((h, v) -> h.setCollarColor((net.minecraft.world.item.DyeColor) (Object) v)) + .set((h, v) -> ((WolfAccessor)h).invoker$setCollarColor((net.minecraft.world.item.DyeColor) (Object) v)) .create(Keys.IS_BEGGING_FOR_FOOD) .get(Wolf::isInterested) .set(Wolf::setIsInterested) From 96eb133bd5b55c0d6f4b67357538ad7626ca1de6 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 15 Mar 2024 17:59:11 +0100 Subject: [PATCH 167/230] fix HumanEntity --- .../common/accessor/world/entity/LivingEntityAccessor.java | 6 ++++-- .../common/entity/living/human/HumanEntity.java | 6 +----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/entity/LivingEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/entity/LivingEntityAccessor.java index ca4e4b7b6e6..34db3745efd 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/entity/LivingEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/entity/LivingEntityAccessor.java @@ -25,6 +25,7 @@ package org.spongepowered.common.accessor.world.entity; import net.minecraft.core.BlockPos; +import net.minecraft.core.particles.ParticleOptions; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.LivingEntity; @@ -35,6 +36,7 @@ import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.common.UntransformedAccessorError; +import java.util.List; import java.util.Optional; @Mixin(LivingEntity.class) @@ -50,8 +52,8 @@ public interface LivingEntityAccessor { throw new UntransformedAccessorError(); } - @Accessor("DATA_EFFECT_COLOR_ID") - static EntityDataAccessor accessor$DATA_EFFECT_COLOR_ID() { + @Accessor("DATA_EFFECT_PARTICLES") + static EntityDataAccessor> accessor$DATA_EFFECT_PARTICLES() { throw new UntransformedAccessorError(); } diff --git a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java index 9f7bdbd627c..da2e5cde901 100644 --- a/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java +++ b/src/main/java/org/spongepowered/common/entity/living/human/HumanEntity.java @@ -26,14 +26,12 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; -import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.yggdrasil.ProfileResult; import com.mojang.serialization.DataResult; import net.kyori.adventure.text.Component; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.Tag; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; @@ -63,13 +61,11 @@ import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.Arrow; -import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.item.ArrowItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; @@ -132,7 +128,7 @@ protected void defineSynchedData(SynchedEntityData.Builder $$0) { // LivingEntity $$0.define(LivingEntityAccessor.accessor$DATA_LIVING_ENTITY_FLAGS(), (byte) 0); $$0.define(LivingEntityAccessor.accessor$DATA_HEALTH_ID(), 1.0F); - $$0.define(LivingEntityAccessor.accessor$DATA_EFFECT_COLOR_ID(), 0); + $$0.define(LivingEntityAccessor.accessor$DATA_EFFECT_PARTICLES(), List.of()); $$0.define(LivingEntityAccessor.accessor$DATA_EFFECT_AMBIENCE_ID(), Boolean.FALSE); $$0.define(LivingEntityAccessor.accessor$DATA_ARROW_COUNT_ID(), 0); $$0.define(LivingEntityAccessor.accessor$DATA_STINGER_COUNT_ID(), 0); From ef21ecf42655f6c4395227dc8db17c50935dd02b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Fri, 15 Mar 2024 18:17:19 +0100 Subject: [PATCH 168/230] fix Wolf Taming --- .../mixin/core/world/entity/MobMixin.java | 2 + .../core/world/entity/animal/WolfMixin.java | 49 ++++++++++++------- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java index dde130c923a..6c982ee7580 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java @@ -81,6 +81,8 @@ public abstract class MobMixin extends LivingEntityMixin { // @formatter:on + @Shadow @Final protected float[] handDropChances; + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Mob;registerGoals()V")) private void impl$registerGoals(final Mob this$0) { this.impl$setupGoalSelectors(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java index 0344fb1f9c6..19a9d08300a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java @@ -24,17 +24,19 @@ */ package org.spongepowered.common.mixin.core.world.entity.animal; -import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.NeutralMob; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import org.spongepowered.api.entity.living.animal.Wolf; import org.spongepowered.api.event.SpongeEventFactory; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.world.entity.AggressiveEntityBridge; import org.spongepowered.common.event.tracking.PhaseTracker; @@ -47,8 +49,10 @@ public abstract class WolfMixin extends AgableMobMixin implements AggressiveEnti // @formatter:off @Shadow public abstract void shadow$startPersistentAngerTimer(); + @Shadow protected abstract void shadow$tryToTame(final Player $$0); // @formatter:on + @Override public boolean bridge$isAngry() { return ((NeutralMob) this).isAngry(); @@ -59,25 +63,36 @@ public abstract class WolfMixin extends AgableMobMixin implements AggressiveEnti this.shadow$startPersistentAngerTimer(); } + @Redirect(method = "mobInteract", - at = @At(value = "INVOKE", target = "Lnet/minecraft/util/RandomSource;nextInt(I)I")) - private int impl$ChangeRandomForTameEvent(final RandomSource rand, final int bound, final Player player, final InteractionHand hand) { - int random = rand.nextInt(bound); - ItemStack stack = player.getItemInHand(hand); - if (random == 0) { - stack.shrink(1); - try { - PhaseTracker.getCauseStackManager().pushCause(ItemStackUtil.fromNative(stack).createSnapshot()); - PhaseTracker.getCauseStackManager().pushCause(player); - if (!SpongeCommon.post(SpongeEventFactory.createTameEntityEvent(PhaseTracker.getCauseStackManager().currentCause(), (Wolf) this))) { - stack.grow(1); - return random; - } - } finally { - PhaseTracker.getCauseStackManager().popCauses(2); + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/Wolf;tryToTame(Lnet/minecraft/world/entity/player/Player;)V")) + private void impl$onTame(final net.minecraft.world.entity.animal.Wolf instance, final Player player, final Player $$0, final InteractionHand $$1) { + try { + final ItemStack handStack = player.getItemInHand($$1); + handStack.grow(1); + final ItemStackSnapshot snapshot = ItemStackUtil.snapshotOf(handStack); + handStack.shrink(1); + PhaseTracker.getCauseStackManager().pushCause(snapshot); + this.shadow$tryToTame(player); + } finally { + PhaseTracker.getCauseStackManager().popCause(); + } + } + + @Inject(method = "tryToTame", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/Wolf;tame(Lnet/minecraft/world/entity/player/Player;)V"), + cancellable = true) + private void impl$onTame(final Player player, final CallbackInfo ci) { + try { + + PhaseTracker.getCauseStackManager().pushCause(player); + if (!SpongeCommon.post(SpongeEventFactory.createTameEntityEvent(PhaseTracker.getCauseStackManager().currentCause(), (Wolf) this))) { + this.shadow$level().broadcastEntityEvent((net.minecraft.world.entity.animal.Wolf) (Object) this, (byte)6); + ci.cancel(); } + } finally { + PhaseTracker.getCauseStackManager().popCause(); } - return 1; } } From 3be481a427fcd496f4e0052f4fb386095aca15bc Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 18:54:45 +0100 Subject: [PATCH 169/230] 24w12a --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index a47e6508ab0..5580b0cc7b9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=24w11a +minecraftVersion=24w12a recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From 27b801e4485427078455babc1c5d4b4a8abf64a8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:01:19 +0100 Subject: [PATCH 170/230] TODO setters on map decoration not supported? fix map decoration type --- .../SpongeMapDecorationBannerType.java | 5 +- .../SpongeMapDecorationBuilder.java | 24 +++++---- .../decoration/SpongeMapDecorationType.java | 18 +++---- .../registry/loader/SpongeRegistryLoader.java | 54 +++++++++---------- .../minecraft/map/MapDecorationMixin_API.java | 16 +++--- 5 files changed, 63 insertions(+), 54 deletions(-) diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java index e36f4280edd..4c27c32dca4 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java @@ -24,7 +24,8 @@ */ package org.spongepowered.common.map.decoration; -import net.minecraft.world.level.saveddata.maps.MapDecoration; +import net.minecraft.core.Holder; +import net.minecraft.world.level.saveddata.maps.MapDecorationType; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.map.decoration.MapDecorationBannerType; @@ -33,7 +34,7 @@ public class SpongeMapDecorationBannerType extends SpongeMapDecorationType implements MapDecorationBannerType { private final Supplier bannerColor; - public SpongeMapDecorationBannerType(final MapDecoration.Type mapDecorationType, final Supplier bannerColor) { + public SpongeMapDecorationBannerType(final Holder mapDecorationType, final Supplier bannerColor) { super(mapDecorationType); this.bannerColor = bannerColor; } diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index 844c2c6b9c0..8820be59856 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -26,7 +26,11 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; @@ -114,18 +118,18 @@ public MapDecoration.Builder fromContainer(final DataView container) { } this.reset(); - final byte type = this.getByteFromContainer(container, Constants.Map.DECORATION_TYPE); + final Optional oldType = container.getByte(Constants.Map.DECORATION_TYPE); + // TODO fix old type + // throw new InvalidDataException(Constants.Map.DECORATION_TYPE + ", is out of bounds. Should be 0-" + (possibleTypes-1)); + final ResourceKey type = container.getResourceKey(Constants.Map.DECORATION_TYPE).get(); final byte rot = this.getByteFromContainer(container, Constants.Map.DECORATION_ROTATION); - final net.minecraft.world.level.saveddata.maps.MapDecoration.Type[] decorations = net.minecraft.world.level.saveddata.maps.MapDecoration.Type.values(); - final int possibleTypes = decorations.length; - if (type < 0 || type > possibleTypes) { - throw new InvalidDataException(Constants.Map.DECORATION_TYPE + ", is out of bounds. Should be 0-" + (possibleTypes-1)); - } - final MapDecorationType mapDecorationType = SpongeMapDecorationType.toSpongeType(decorations[type]) - .orElseThrow(() -> new IllegalStateException("Missing a MapDecorationType, could not find one for Minecraft's MapDecoration.Type: " - + decorations[type].toString())); + final var mcType = BuiltInRegistries.MAP_DECORATION_TYPE.get((ResourceLocation) (Object) type); + if (mcType == null) { + throw new IllegalStateException("Missing a MapDecorationType, could not find one for Minecraft's MapDecoration.Type: " + type); + } + final MapDecorationType mapDecorationType = SpongeMapDecorationType.toSpongeType(BuiltInRegistries.MAP_DECORATION_TYPE.wrapAsHolder(mcType)).get(); this.type(mapDecorationType); final int intRot = MapUtil.normalizeDecorationOrientation(rot); @@ -160,7 +164,7 @@ private byte getByteFromContainer(final DataView container, final DataQuery quer public MapDecoration build() throws IllegalStateException { Objects.requireNonNull(this.type, "Type has not been set"); final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( - ((SpongeMapDecorationType) this.type).getType(), + Holder.direct(((SpongeMapDecorationType) this.type).getType()), (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java index 95b43409bfb..20f839b88c3 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.map.decoration; -import net.minecraft.world.level.saveddata.maps.MapDecoration; +import net.minecraft.core.Holder; import org.spongepowered.api.map.decoration.MapDecorationType; import java.util.HashMap; @@ -33,20 +33,20 @@ public class SpongeMapDecorationType implements MapDecorationType { - private static final Map VANILLA_TYPE_MAP = new HashMap<>(); + private static final Map VANILLA_TYPE_MAP = new HashMap<>(); - public static Optional toSpongeType(final MapDecoration.Type vanillaType) { - return Optional.ofNullable(SpongeMapDecorationType.VANILLA_TYPE_MAP.get(vanillaType)); + public static Optional toSpongeType(final Holder vanillaType) { + return Optional.ofNullable(SpongeMapDecorationType.VANILLA_TYPE_MAP.get(vanillaType.value())); } - private final MapDecoration.Type type; + private final net.minecraft.world.level.saveddata.maps.MapDecorationType type; - public SpongeMapDecorationType(final MapDecoration.Type mapDecorationType) { - this.type = mapDecorationType; - SpongeMapDecorationType.VANILLA_TYPE_MAP.put(mapDecorationType, this); + public SpongeMapDecorationType(final Holder mapDecorationType) { + this.type = mapDecorationType.value(); + SpongeMapDecorationType.VANILLA_TYPE_MAP.put(mapDecorationType.value(), this); } - public MapDecoration.Type getType() { + public net.minecraft.world.level.saveddata.maps.MapDecorationType getType() { return this.type; } } diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index 69ded2d71fd..da1eec317f0 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -616,34 +616,34 @@ public static RegistryLoader mapDecorationOrientation( public static RegistryLoader mapDecorationType() { return RegistryLoader.of(l -> { - l.add(MapDecorationTypes.PLAYER_MARKER, k -> new SpongeMapDecorationType(MapDecoration.Type.PLAYER)); - l.add(MapDecorationTypes.GREEN_MARKER, k -> new SpongeMapDecorationType(MapDecoration.Type.FRAME)); - l.add(MapDecorationTypes.RED_MARKER, k -> new SpongeMapDecorationType(MapDecoration.Type.RED_MARKER)); - l.add(MapDecorationTypes.BLUE_MARKER, k -> new SpongeMapDecorationType(MapDecoration.Type.BLUE_MARKER)); - l.add(MapDecorationTypes.TARGET_X, k -> new SpongeMapDecorationType(MapDecoration.Type.TARGET_X)); - l.add(MapDecorationTypes.TARGET_POINT, k -> new SpongeMapDecorationType(MapDecoration.Type.TARGET_POINT)); - l.add(MapDecorationTypes.PLAYER_OFF_MAP, k -> new SpongeMapDecorationType(MapDecoration.Type.PLAYER_OFF_MAP)); - l.add(MapDecorationTypes.PLAYER_OFF_LIMITS, k -> new SpongeMapDecorationType(MapDecoration.Type.PLAYER_OFF_LIMITS)); - l.add(MapDecorationTypes.MANSION, k -> new SpongeMapDecorationType(MapDecoration.Type.MANSION)); - l.add(MapDecorationTypes.MONUMENT, k -> new SpongeMapDecorationType(MapDecoration.Type.MONUMENT)); + l.add(MapDecorationTypes.PLAYER_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER)); + l.add(MapDecorationTypes.GREEN_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.FRAME)); + l.add(MapDecorationTypes.RED_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_MARKER)); + l.add(MapDecorationTypes.BLUE_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLUE_MARKER)); + l.add(MapDecorationTypes.TARGET_X, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.TARGET_X)); + l.add(MapDecorationTypes.TARGET_POINT, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.TARGET_POINT)); + l.add(MapDecorationTypes.PLAYER_OFF_MAP, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER_OFF_MAP)); + l.add(MapDecorationTypes.PLAYER_OFF_LIMITS, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER_OFF_LIMITS)); + l.add(MapDecorationTypes.MANSION, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.WOODLAND_MANSION)); + l.add(MapDecorationTypes.MONUMENT, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.OCEAN_MONUMENT)); // banners - l.add(MapDecorationTypes.BANNER_WHITE, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_WHITE, DyeColors.WHITE)); - l.add(MapDecorationTypes.BANNER_ORANGE, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_ORANGE, DyeColors.ORANGE)); - l.add(MapDecorationTypes.BANNER_MAGENTA, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_MAGENTA, DyeColors.MAGENTA)); - l.add(MapDecorationTypes.BANNER_LIGHT_BLUE, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_LIGHT_BLUE, DyeColors.LIGHT_BLUE)); - l.add(MapDecorationTypes.BANNER_YELLOW, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_YELLOW, DyeColors.YELLOW)); - l.add(MapDecorationTypes.BANNER_LIME, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_LIME, DyeColors.LIME)); - l.add(MapDecorationTypes.BANNER_PINK, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_PINK, DyeColors.PINK)); - l.add(MapDecorationTypes.BANNER_GRAY, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_GRAY, DyeColors.GRAY)); - l.add(MapDecorationTypes.BANNER_LIGHT_GRAY, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_LIGHT_GRAY, DyeColors.LIGHT_GRAY)); - l.add(MapDecorationTypes.BANNER_CYAN, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_CYAN, DyeColors.CYAN)); - l.add(MapDecorationTypes.BANNER_PURPLE, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_PURPLE, DyeColors.PURPLE)); - l.add(MapDecorationTypes.BANNER_BLUE, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_BLUE, DyeColors.BLUE)); - l.add(MapDecorationTypes.BANNER_BROWN, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_BROWN, DyeColors.BROWN)); - l.add(MapDecorationTypes.BANNER_GREEN, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_GREEN, DyeColors.GREEN)); - l.add(MapDecorationTypes.BANNER_RED, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_RED, DyeColors.RED)); - l.add(MapDecorationTypes.BANNER_BLACK, k -> new SpongeMapDecorationBannerType(MapDecoration.Type.BANNER_BLACK, DyeColors.BLACK)); - l.add(MapDecorationTypes.RED_X, k -> new SpongeMapDecorationType(MapDecoration.Type.RED_X)); + l.add(MapDecorationTypes.BANNER_WHITE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.WHITE_BANNER, DyeColors.WHITE)); + l.add(MapDecorationTypes.BANNER_ORANGE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.ORANGE_BANNER, DyeColors.ORANGE)); + l.add(MapDecorationTypes.BANNER_MAGENTA, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.MAGENTA_BANNER, DyeColors.MAGENTA)); + l.add(MapDecorationTypes.BANNER_LIGHT_BLUE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIGHT_BLUE_BANNER, DyeColors.LIGHT_BLUE)); + l.add(MapDecorationTypes.BANNER_YELLOW, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.YELLOW_BANNER, DyeColors.YELLOW)); + l.add(MapDecorationTypes.BANNER_LIME, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIME_BANNER, DyeColors.LIME)); + l.add(MapDecorationTypes.BANNER_PINK, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PINK_BANNER, DyeColors.PINK)); + l.add(MapDecorationTypes.BANNER_GRAY, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.GRAY_BANNER, DyeColors.GRAY)); + l.add(MapDecorationTypes.BANNER_LIGHT_GRAY, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIGHT_GRAY_BANNER, DyeColors.LIGHT_GRAY)); + l.add(MapDecorationTypes.BANNER_CYAN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.CYAN_BANNER, DyeColors.CYAN)); + l.add(MapDecorationTypes.BANNER_PURPLE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PURPLE_BANNER, DyeColors.PURPLE)); + l.add(MapDecorationTypes.BANNER_BLUE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLUE_BANNER, DyeColors.BLUE)); + l.add(MapDecorationTypes.BANNER_BROWN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BROWN_BANNER, DyeColors.BROWN)); + l.add(MapDecorationTypes.BANNER_GREEN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.GREEN_BANNER, DyeColors.GREEN)); + l.add(MapDecorationTypes.BANNER_RED, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_BANNER, DyeColors.RED)); + l.add(MapDecorationTypes.BANNER_BLACK, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLACK_BANNER, DyeColors.BLACK)); + l.add(MapDecorationTypes.RED_X, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_X)); }); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index 0b891ab5e3c..63236f28e8e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -25,6 +25,8 @@ package org.spongepowered.common.mixin.api.minecraft.map; import net.minecraft.network.chat.Component; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.saveddata.maps.MapDecoration; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.map.decoration.MapDecorationType; @@ -42,15 +44,17 @@ import org.spongepowered.common.util.Preconditions; import org.spongepowered.math.vector.Vector2i; +import java.util.Optional; + @Mixin(MapDecoration.class) public abstract class MapDecorationMixin_API implements org.spongepowered.api.map.decoration.MapDecoration { // @formatter:off - @Shadow @Final private MapDecoration.Type type; - @Shadow @Final @Mutable private byte x; - @Shadow @Final @Mutable private byte y; - @Shadow @Final @Mutable private byte rot; - @Shadow @Final private java.util.Optional name; + @Shadow @Final private Holder type; + @Shadow @Final private byte x; + @Shadow @Final private byte y; + @Shadow @Final private byte rot; + @Shadow @Final private Optional name; // @formatter:on @@ -99,7 +103,7 @@ public int contentVersion() { @Override public DataContainer toContainer() { final DataContainer data = DataContainer.createNew() - .set(Constants.Map.DECORATION_TYPE, this.type.getIcon()) + .set(Constants.Map.DECORATION_TYPE, BuiltInRegistries.MAP_DECORATION_TYPE.getKey(this.type.value())) .set(Constants.Map.DECORATION_ID, ((MapDecorationBridge) this).bridge$getKey()) .set(Constants.Map.DECORATION_X, this.x) .set(Constants.Map.DECORATION_Y, this.y) From 484650318424a01f05cc629e26ef0a79b25d1a6b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:37:06 +0100 Subject: [PATCH 171/230] fix ItemStackData --- .../provider/item/stack/ItemStackData.java | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index 3c4653e70f4..0d99f6340d5 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -79,12 +79,12 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.APPLICABLE_POTION_EFFECTS) .get(h -> { - if (h.isEdible()) { - final List> itemEffects = h.getItem().getFoodProperties().getEffects(); + if (h.has(DataComponents.FOOD)) { + final var itemEffects = h.get(DataComponents.FOOD).effects(); final WeightedTable effects = new WeightedTable<>(); final ChanceTable chance = new ChanceTable<>(); - for (final Pair effect : itemEffects) { - chance.add((PotionEffect) effect.getFirst(), effect.getSecond()); + for (final var effect : itemEffects) { + chance.add((PotionEffect) effect.effect(), effect.probability()); } effects.add(new NestedTableEntry<>(1, chance)); return effects; @@ -108,7 +108,7 @@ public static void register(final DataProviderRegistrator registrator) { } final Set blockTypes = blockRegistry.stream() - .filter(b -> item.isCorrectToolForDrops(b.defaultBlockState())) + .filter(b -> h.isCorrectToolForDrops(b.defaultBlockState())) .map(BlockType.class::cast) .collect(Collectors.toUnmodifiableSet()); return blockTypes.isEmpty() ? null : blockTypes; @@ -162,35 +162,32 @@ public static void register(final DataProviderRegistrator registrator) { }) .delete(h -> h.remove(DataComponents.LORE)) .create(Keys.MAX_DURABILITY) - .get(h -> h.getItem().canBeDepleted() ? h.getItem().getMaxDamage() : null) - .supports(h -> h.getItem().canBeDepleted()) + .get(h -> h.getMaxDamage() != 0 ? h.getMaxDamage() : null) + .supports(h -> h.getMaxDamage() != 0) .create(Keys.ITEM_DURABILITY) .get(stack -> stack.getMaxDamage() - stack.getDamageValue()) .set((stack, durability) -> stack.setDamageValue(stack.getMaxDamage() - durability)) - .supports(h -> h.getItem().canBeDepleted()) + .supports(h -> h.getMaxDamage() != 0) .create(Keys.ITEM_RARITY) .get(stack -> (ItemRarity) (Object) stack.getRarity()) .create(Keys.REPLENISHED_FOOD) .get(h -> { - if (h.getItem().isEdible()) { - final FoodProperties food = h.getItem().getFoodProperties(); - return food == null ? null : food.getNutrition(); + final var food = h.get(DataComponents.FOOD); + if (food != null) { + return food.nutrition(); } return null; }) - .supports(h -> h.getItem().isEdible()) .create(Keys.REPLENISHED_SATURATION) .get(h -> { - if (h.getItem().isEdible()) { - final FoodProperties food = h.getItem().getFoodProperties(); - if (food != null) { - // Translate's Minecraft's weird internal value to the actual saturation value - return food.getSaturationModifier() * food.getNutrition() * 2.0; - } + final var food = h.get(DataComponents.FOOD); + if (food != null) { + // Translate's Minecraft's weird internal value to the actual saturation value + return food.saturationModifier() * food.nutrition() * 2.0; } return null; }) - .supports(h -> h.getItem().isEdible()); + ; } // @formatter:on From 60517fff66bf85bde51d60348b96095c1a58ab93 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:38:34 +0100 Subject: [PATCH 172/230] fix CatData --- .../spongepowered/common/data/provider/entity/CatData.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java b/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java index d7cb5bb58cb..e5b33daf25b 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/CatData.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.data.provider.entity; +import net.minecraft.core.Holder; import net.minecraft.world.entity.animal.Cat; import net.minecraft.world.entity.animal.CatVariant; import org.spongepowered.api.data.Keys; @@ -43,8 +44,8 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(Cat.class) .create(Keys.CAT_TYPE) - .get(h -> (CatType) (Object) h.getVariant()) - .set((h, v) -> h.setVariant((CatVariant) (Object) v)) + .get(h -> (CatType) (Object) h.getVariant().value()) + .set((h, v) -> h.setVariant(Holder.direct((CatVariant) (Object) v))) .create(Keys.DYE_COLOR) .get(h -> (DyeColor) (Object) h.getCollarColor()) .set((h, v) -> ((CatAccessor)h).invoker$setCollarColor((net.minecraft.world.item.DyeColor) (Object) v)) From 0d612e542ee1996a51998b8730b4e0058c4cd7e9 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:40:05 +0100 Subject: [PATCH 173/230] fix EnchantmentMixin_API --- .../world/item/enchantment/EnchantmentMixin_API.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java index b08d510f4bb..68c7763d13f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java @@ -44,7 +44,6 @@ public abstract class EnchantmentMixin_API implements EnchantmentType { // @formatter:off - @Shadow @Final private net.minecraft.world.item.enchantment.Enchantment.Rarity rarity; @Shadow public abstract int shadow$getMinLevel(); @Shadow public abstract int shadow$getMaxLevel(); @Shadow public abstract int shadow$getMinCost(int level); @@ -53,11 +52,14 @@ public abstract class EnchantmentMixin_API implements EnchantmentType { @Shadow protected abstract String shadow$getOrCreateDescriptionId(); @Shadow public abstract boolean shadow$isTreasureOnly(); @Shadow public abstract boolean shadow$isCurse(); + @Shadow public abstract int shadow$getWeight(); + // @formatter:on + @Override public int weight() { - return this.rarity.getWeight(); + return this.shadow$getWeight(); } @Override From eeb9e5bbed57886ee959ba342897777da30ff48a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:43:23 +0100 Subject: [PATCH 174/230] fix FishingHookMixin --- .../mixin/core/world/entity/projectile/FishingHookMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java index b04273fcea3..b8226173836 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java @@ -110,7 +110,7 @@ public int retrieve(final ItemStack stack) { .withParameter(LootContextParams.TOOL, stack) .withParameter(LootContextParams.THIS_ENTITY, (FishingHook) (Object) this) .withLuck((float)this.luck + playerEntity.getLuck()); - final LootTable lootTable = this.shadow$level().getServer().getLootData().getLootTable(BuiltInLootTables.FISHING); + final LootTable lootTable = this.shadow$level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); final List list = lootTable.getRandomItems(lootcontext$builder.create(LootContextParamSets.FISHING)); transactions = list.stream().map(ItemStackUtil::snapshotOf) .map(snapshot -> new Transaction<>(snapshot, snapshot)) From e0b2c3938b0ceb09761ce4e19589728d6b140d7e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:45:06 +0100 Subject: [PATCH 175/230] fix BlocksMixin_Tracker --- .../tracker/world/level/block/BlocksMixin_Tracker.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java index f6a2a37ed1a..042db730cd6 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/tracker/world/level/block/BlocksMixin_Tracker.java @@ -24,9 +24,10 @@ */ package org.spongepowered.vanilla.mixin.tracker.world.level.block; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.storage.loot.LootTable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -39,10 +40,10 @@ public abstract class BlocksMixin_Tracker { @Redirect(method = "", at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/Block;getLootTable()Lnet/minecraft/resources/ResourceLocation;" + target = "Lnet/minecraft/world/level/block/Block;getLootTable()Lnet/minecraft/resources/ResourceKey;" ) ) - private static ResourceLocation impl$initializeTrackerState(final Block block) { + private static ResourceKey impl$initializeTrackerState(final Block block) { final boolean randomlyTicking = ((BlockBehaviourAccessor) block).invoker$isRandomlyTicking(block.defaultBlockState()); // TODO Not the best check but the tracker options only matter during block ticks... From 1b3437a042d2ebc5ccedde10ec5d8996c684e73a Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:50:01 +0100 Subject: [PATCH 176/230] fix ItemMixin_API --- .../api/minecraft/world/item/ItemMixin_API.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java index d06bfa664e2..557d19c5177 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/ItemMixin_API.java @@ -26,9 +26,10 @@ import net.kyori.adventure.text.Component; import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponents; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; -import net.minecraft.world.item.Rarity; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.item.ItemRarity; @@ -51,15 +52,16 @@ public abstract class ItemMixin_API implements ItemType, SpongeImmutableDataHolder { // @formatter:off - @Shadow @Final private Rarity rarity; @Shadow @Final private Holder.Reference builtInRegistryHolder; + @Shadow @Final private DataComponentMap components; - @Shadow public abstract int shadow$getMaxStackSize(); @Shadow public abstract String shadow$getDescriptionId(); @Shadow @Nullable public abstract Item shadow$getCraftingRemainingItem(); + @Shadow public abstract int shadow$getDefaultMaxStackSize(); // @formatter:on + @Nullable protected BlockType api$blockType = null; @Override @@ -69,12 +71,12 @@ public Component asComponent() { @Override public int maxStackQuantity() { - return this.shadow$getMaxStackSize(); + return this.shadow$getDefaultMaxStackSize(); } @Override public ItemRarity rarity() { - return (ItemRarity) (Object) this.rarity; + return (ItemRarity) (Object) this.components.get(DataComponents.RARITY); } @Override From c80d013a8b4dea2e856436531bf0ea9987576a1e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:56:49 +0100 Subject: [PATCH 177/230] fix ItemStackData --- .../data/provider/item/stack/ItemStackData.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index 0d99f6340d5..d1bae83f705 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -43,6 +43,7 @@ import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.component.CustomModelData; import net.minecraft.world.item.component.ItemLore; +import net.minecraft.world.item.component.Tool; import net.minecraft.world.item.component.Unbreakable; import net.minecraft.world.item.component.WrittenBookContent; import net.minecraft.world.level.block.Block; @@ -102,9 +103,13 @@ public static void register(final DataProviderRegistrator registrator) { .create(Keys.CAN_HARVEST) .get(h -> { final Registry blockRegistry = SpongeCommon.vanillaRegistry(Registries.BLOCK); - final Item item = h.getItem(); - if (item instanceof DiggerItemAccessor && !(item instanceof PickaxeItem)) { - return blockRegistry.getTag(((DiggerItemAccessor) item).accessor$blocks()).stream().flatMap(HolderSet.ListBacked::stream).map(Holder::value).map(BlockType.class::cast).collect(Collectors.toSet()); + final Tool tool = h.get(DataComponents.TOOL); + if (tool != null) { + return tool.rules().stream().map(Tool.Rule::blocks) + .flatMap(HolderSet::stream) + .map(Holder::value) + .map(BlockType.class::cast) + .collect(Collectors.toSet()); } final Set blockTypes = blockRegistry.stream() From 6b5396d3f1dbe9993c8f062867f8fb43a1385b14 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:59:00 +0100 Subject: [PATCH 178/230] fix ToolItemStackData --- .../world/item/DiggerItemAccessor.java | 40 ------------------- .../resources/mixins.sponge.accessors.json | 1 - .../provider/item/stack/ItemStackData.java | 12 ------ .../item/stack/ToolItemStackData.java | 11 ++--- 4 files changed, 6 insertions(+), 58 deletions(-) delete mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/item/DiggerItemAccessor.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/DiggerItemAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/DiggerItemAccessor.java deleted file mode 100644 index 80b6d061a98..00000000000 --- a/src/accessors/java/org/spongepowered/common/accessor/world/item/DiggerItemAccessor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.accessor.world.item; - -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.DiggerItem; -import net.minecraft.world.level.block.Block; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(DiggerItem.class) -public interface DiggerItemAccessor { - - @Accessor("blocks") TagKey accessor$blocks(); - - @Accessor("speed") float accessor$speed(); - -} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 1d8df9c9905..6351c2c9a61 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -137,7 +137,6 @@ "world.inventory.ResultSlotAccessor", "world.inventory.SlotAccessor", "world.item.AdventureModePredicateAccessor", - "world.item.DiggerItemAccessor", "world.item.ItemCooldowns_CooldownInstanceAccessor", "world.item.RecordItemAccessor", "world.item.enchantment.ItemEnchantmentsAccessor", diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index d1bae83f705..185de9fa512 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -24,31 +24,22 @@ */ package org.spongepowered.common.data.provider.item.stack; -import com.mojang.datafixers.util.Pair; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; import net.minecraft.network.chat.Component; import net.minecraft.util.StringUtil; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.food.FoodProperties; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.component.CustomModelData; import net.minecraft.world.item.component.ItemLore; import net.minecraft.world.item.component.Tool; import net.minecraft.world.item.component.Unbreakable; -import net.minecraft.world.item.component.WrittenBookContent; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.data.Keys; import org.spongepowered.api.effect.potion.PotionEffect; @@ -58,11 +49,8 @@ import org.spongepowered.api.util.weighted.NestedTableEntry; import org.spongepowered.api.util.weighted.WeightedTable; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.accessor.world.item.DiggerItemAccessor; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.data.provider.DataProviderRegistrator; -import org.spongepowered.common.util.Constants; -import org.spongepowered.common.util.NBTCollectors; import java.util.List; import java.util.Set; diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ToolItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ToolItemStackData.java index f494c458802..21358eafeec 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ToolItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ToolItemStackData.java @@ -24,9 +24,10 @@ */ package org.spongepowered.common.data.provider.item.stack; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.Tool; import org.spongepowered.api.data.Keys; -import org.spongepowered.common.accessor.world.item.DiggerItemAccessor; import org.spongepowered.common.data.provider.DataProviderRegistrator; public final class ToolItemStackData { @@ -40,12 +41,12 @@ public static void register(final DataProviderRegistrator registrator) { .asMutable(ItemStack.class) .create(Keys.EFFICIENCY) .get(h -> { - if (h.getItem() instanceof DiggerItemAccessor) { - return (double) ((DiggerItemAccessor) h.getItem()).accessor$speed(); + final Tool tool = h.get(DataComponents.TOOL); + if (tool!= null) { + return (double) tool.defaultMiningSpeed(); } return null; - }) - .supports(h -> h.getItem() instanceof DiggerItemAccessor); + }); } // @formatter:on } From db2e8d42ac8f6961ed2296ddfb7bdb4f04b6f4d2 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 20:00:26 +0100 Subject: [PATCH 179/230] fix RarityMixin_API --- .../mixin/api/minecraft/world/item/RarityMixin_API.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/RarityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/RarityMixin_API.java index b84c8235981..aa8a58ba58a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/RarityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/RarityMixin_API.java @@ -39,8 +39,8 @@ public abstract class RarityMixin_API implements ItemRarity { private TextColor api$color; @Inject(method = "", at = @At(value = "RETURN")) - private void api$setColor(final String enumName, final int ordinal, final ChatFormatting param0, final CallbackInfo ci) { - this.api$color = SpongeAdventure.asAdventure(param0); + private void api$setColor(final String $$0, final int $$1, final int $$2, final String par4, final ChatFormatting par5, final CallbackInfo ci) { + this.api$color = SpongeAdventure.asAdventure(par5); } @Override From ee41750f61d21d327730c5ac828b06b667d70521 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 19:42:40 +0100 Subject: [PATCH 180/230] fix map decoration fix MapDecorationType fix MapDecorationType fix MapDecorationType --- .../SpongeMapDecorationBannerType.java | 46 ------------- .../SpongeMapDecorationBuilder.java | 3 + .../decoration/SpongeMapDecorationType.java | 52 -------------- .../common/registry/SpongeRegistries.java | 4 -- .../registry/loader/SpongeRegistryLoader.java | 33 --------- .../map/MapDecorationTypeMixin_API.java | 67 +++++++++++++++++++ .../level/saveddata/MapDecorationMixin.java | 26 ++++--- src/mixins/resources/mixins.sponge.api.json | 1 + 8 files changed, 83 insertions(+), 149 deletions(-) delete mode 100644 src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java delete mode 100644 src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationTypeMixin_API.java diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java deleted file mode 100644 index 4c27c32dca4..00000000000 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBannerType.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.map.decoration; - -import net.minecraft.core.Holder; -import net.minecraft.world.level.saveddata.maps.MapDecorationType; -import org.spongepowered.api.data.type.DyeColor; -import org.spongepowered.api.map.decoration.MapDecorationBannerType; - -import java.util.function.Supplier; - -public class SpongeMapDecorationBannerType extends SpongeMapDecorationType implements MapDecorationBannerType { - private final Supplier bannerColor; - - public SpongeMapDecorationBannerType(final Holder mapDecorationType, final Supplier bannerColor) { - super(mapDecorationType); - this.bannerColor = bannerColor; - } - - @Override - public DyeColor bannerColor() { - return this.bannerColor.get(); - } -} diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index 8820be59856..e2a7f6fde0e 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -34,13 +34,16 @@ import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; +import org.spongepowered.api.data.type.DyeColors; import org.spongepowered.api.map.decoration.MapDecoration; import org.spongepowered.api.map.decoration.MapDecorationType; +import org.spongepowered.api.map.decoration.MapDecorationTypes; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientations; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.world.storage.MapDecorationBridge; import org.spongepowered.common.map.decoration.orientation.SpongeMapDecorationOrientation; +import org.spongepowered.common.registry.RegistryLoader; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.MapUtil; import org.spongepowered.math.vector.Vector2i; diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java deleted file mode 100644 index 20f839b88c3..00000000000 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationType.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.map.decoration; - -import net.minecraft.core.Holder; -import org.spongepowered.api.map.decoration.MapDecorationType; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -public class SpongeMapDecorationType implements MapDecorationType { - - private static final Map VANILLA_TYPE_MAP = new HashMap<>(); - - public static Optional toSpongeType(final Holder vanillaType) { - return Optional.ofNullable(SpongeMapDecorationType.VANILLA_TYPE_MAP.get(vanillaType.value())); - } - - private final net.minecraft.world.level.saveddata.maps.MapDecorationType type; - - public SpongeMapDecorationType(final Holder mapDecorationType) { - this.type = mapDecorationType.value(); - SpongeMapDecorationType.VANILLA_TYPE_MAP.put(mapDecorationType.value(), this); - } - - public net.minecraft.world.level.saveddata.maps.MapDecorationType getType() { - return this.type; - } -} diff --git a/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java b/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java index e67967dba8f..199517541d5 100644 --- a/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java +++ b/src/main/java/org/spongepowered/common/registry/SpongeRegistries.java @@ -84,14 +84,10 @@ public static void registerEarlyGlobalRegistries(final SpongeRegistryHolder hold holder.createFrozenRegistry(RegistryTypes.DATA_FORMAT, SpongeRegistryLoader.dataFormat()); holder.createFrozenRegistry(RegistryTypes.MAP_COLOR_TYPE, SpongeRegistryLoader.mapColorType()); holder.createFrozenRegistry(RegistryTypes.MAP_DECORATION_ORIENTATION, SpongeRegistryLoader.mapDecorationOrientation()); - holder.createFrozenRegistry(RegistryTypes.MAP_DECORATION_TYPE, SpongeRegistryLoader.mapDecorationType()); holder.createFrozenRegistry(RegistryTypes.MAP_SHADE, SpongeRegistryLoader.mapShade()); holder.createFrozenRegistry(RegistryTypes.NOISE_CONFIG, SpongeRegistryLoader.noiseConfig()); SpongeRegistries.registerEarlyDynamicRegistries(holder); - - - } private static void registerEarlyDynamicRegistries(final SpongeRegistryHolder holder) { diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index da1eec317f0..7cba6b12e9e 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -614,39 +614,6 @@ public static RegistryLoader mapDecorationOrientation( }); } - public static RegistryLoader mapDecorationType() { - return RegistryLoader.of(l -> { - l.add(MapDecorationTypes.PLAYER_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER)); - l.add(MapDecorationTypes.GREEN_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.FRAME)); - l.add(MapDecorationTypes.RED_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_MARKER)); - l.add(MapDecorationTypes.BLUE_MARKER, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLUE_MARKER)); - l.add(MapDecorationTypes.TARGET_X, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.TARGET_X)); - l.add(MapDecorationTypes.TARGET_POINT, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.TARGET_POINT)); - l.add(MapDecorationTypes.PLAYER_OFF_MAP, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER_OFF_MAP)); - l.add(MapDecorationTypes.PLAYER_OFF_LIMITS, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PLAYER_OFF_LIMITS)); - l.add(MapDecorationTypes.MANSION, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.WOODLAND_MANSION)); - l.add(MapDecorationTypes.MONUMENT, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.OCEAN_MONUMENT)); - // banners - l.add(MapDecorationTypes.BANNER_WHITE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.WHITE_BANNER, DyeColors.WHITE)); - l.add(MapDecorationTypes.BANNER_ORANGE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.ORANGE_BANNER, DyeColors.ORANGE)); - l.add(MapDecorationTypes.BANNER_MAGENTA, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.MAGENTA_BANNER, DyeColors.MAGENTA)); - l.add(MapDecorationTypes.BANNER_LIGHT_BLUE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIGHT_BLUE_BANNER, DyeColors.LIGHT_BLUE)); - l.add(MapDecorationTypes.BANNER_YELLOW, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.YELLOW_BANNER, DyeColors.YELLOW)); - l.add(MapDecorationTypes.BANNER_LIME, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIME_BANNER, DyeColors.LIME)); - l.add(MapDecorationTypes.BANNER_PINK, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PINK_BANNER, DyeColors.PINK)); - l.add(MapDecorationTypes.BANNER_GRAY, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.GRAY_BANNER, DyeColors.GRAY)); - l.add(MapDecorationTypes.BANNER_LIGHT_GRAY, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.LIGHT_GRAY_BANNER, DyeColors.LIGHT_GRAY)); - l.add(MapDecorationTypes.BANNER_CYAN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.CYAN_BANNER, DyeColors.CYAN)); - l.add(MapDecorationTypes.BANNER_PURPLE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.PURPLE_BANNER, DyeColors.PURPLE)); - l.add(MapDecorationTypes.BANNER_BLUE, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLUE_BANNER, DyeColors.BLUE)); - l.add(MapDecorationTypes.BANNER_BROWN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BROWN_BANNER, DyeColors.BROWN)); - l.add(MapDecorationTypes.BANNER_GREEN, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.GREEN_BANNER, DyeColors.GREEN)); - l.add(MapDecorationTypes.BANNER_RED, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_BANNER, DyeColors.RED)); - l.add(MapDecorationTypes.BANNER_BLACK, k -> new SpongeMapDecorationBannerType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.BLACK_BANNER, DyeColors.BLACK)); - l.add(MapDecorationTypes.RED_X, k -> new SpongeMapDecorationType(net.minecraft.world.level.saveddata.maps.MapDecorationTypes.RED_X)); - }); - } - public static RegistryLoader mapShade() { return RegistryLoader.of(l -> { l.addWithId(0, MapShades.BASE, k -> new SpongeMapShade(0, 180)); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationTypeMixin_API.java new file mode 100644 index 00000000000..c2d29178e1f --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationTypeMixin_API.java @@ -0,0 +1,67 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.map; + +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.saveddata.maps.MapDecorationTypes; +import org.spongepowered.api.data.type.DyeColor; +import org.spongepowered.api.data.type.DyeColors; +import org.spongepowered.api.map.decoration.MapDecorationType; +import org.spongepowered.api.registry.DefaultedRegistryReference; +import org.spongepowered.asm.mixin.Mixin; + +import java.util.Map; +import java.util.Optional; + +@Mixin(net.minecraft.world.level.saveddata.maps.MapDecorationType.class) +public abstract class MapDecorationTypeMixin_API implements MapDecorationType { + + private static final Map, DefaultedRegistryReference> BANNER_COLORS = + Map.ofEntries( + Map.entry(MapDecorationTypes.WHITE_BANNER, DyeColors.WHITE), + Map.entry(MapDecorationTypes.ORANGE_BANNER, DyeColors.ORANGE), + Map.entry(MapDecorationTypes.MAGENTA_BANNER, DyeColors.MAGENTA), + Map.entry(MapDecorationTypes.LIGHT_BLUE_BANNER, DyeColors.LIGHT_BLUE), + Map.entry(MapDecorationTypes.YELLOW_BANNER, DyeColors.YELLOW), + Map.entry(MapDecorationTypes.LIME_BANNER, DyeColors.LIME), + Map.entry(MapDecorationTypes.PINK_BANNER, DyeColors.PINK), + Map.entry(MapDecorationTypes.GRAY_BANNER, DyeColors.GRAY), + Map.entry(MapDecorationTypes.LIGHT_GRAY_BANNER, DyeColors.LIGHT_GRAY), + Map.entry(MapDecorationTypes.CYAN_BANNER, DyeColors.CYAN), + Map.entry(MapDecorationTypes.PURPLE_BANNER, DyeColors.PURPLE), + Map.entry(MapDecorationTypes.BLUE_BANNER, DyeColors.BLUE), + Map.entry(MapDecorationTypes.BROWN_BANNER, DyeColors.BROWN), + Map.entry(MapDecorationTypes.GREEN_BANNER, DyeColors.GREEN), + Map.entry(MapDecorationTypes.RED_BANNER, DyeColors.RED), + Map.entry(MapDecorationTypes.BLACK_BANNER, DyeColors.BLACK) + ); + + @Override + public Optional bannerColor() { + final var holder = BuiltInRegistries.MAP_DECORATION_TYPE.wrapAsHolder((net.minecraft.world.level.saveddata.maps.MapDecorationType) (Object) this); + return Optional.ofNullable(BANNER_COLORS.get(holder)).map(DefaultedRegistryReference::get); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java index 52ed67fd52d..408daa5d1b0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/saveddata/MapDecorationMixin.java @@ -24,8 +24,11 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.level.saveddata; +import net.minecraft.core.Holder; import net.minecraft.network.chat.Component; import net.minecraft.world.level.saveddata.maps.MapDecoration; +import net.minecraft.world.level.saveddata.maps.MapDecorationType; +import net.minecraft.world.level.saveddata.maps.MapDecorationTypes; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import org.spongepowered.api.map.MapInfo; import org.spongepowered.asm.mixin.Mixin; @@ -49,24 +52,19 @@ public abstract class MapDecorationMixin implements MapDecorationBridge { private String impl$key = Constants.Map.DECORATION_KEY_PREFIX + UUID.randomUUID().toString(); @Inject(method = "", at = @At("RETURN")) - public void impl$setPersistenceOnInit(final MapDecoration.Type typeIn, final byte x, final byte y, final byte rot, final Optional name, final CallbackInfo ci) { + public void impl$setPersistenceOnInit(final Holder typeIn, final byte x, final byte y, final byte rot, final Optional name, final CallbackInfo ci) { // All of the below types have no reason to be saved to disk // This is because they can/should be calculated when needed // Furthermore if a sponge plugin adds a MapDecoration, isPersistent // should also be changed to true - switch (typeIn) { - case PLAYER: - case PLAYER_OFF_MAP: - case PLAYER_OFF_LIMITS: - case FRAME: { - this.impl$isPersistent = false; - break; - } - default: { - this.impl$isPersistent = true; - break; - } - + if (MapDecorationTypes.PLAYER.equals(typeIn) + || MapDecorationTypes.PLAYER_OFF_MAP.equals(typeIn) + || MapDecorationTypes.PLAYER_OFF_LIMITS.equals(typeIn) + || MapDecorationTypes.FRAME.equals(typeIn) + ) { + this.impl$isPersistent = false; + } else { + this.impl$isPersistent = true; } } diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 03261cbd18c..dc44f90cf39 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -30,6 +30,7 @@ "minecraft.entity.boss.WitherEntityMixin_API", "minecraft.item.BlockItemMixin_API", "minecraft.map.MapDecorationMixin_API", + "minecraft.map.MapDecorationTypeMixin_API", "minecraft.map.MapInfoMixin_API", "minecraft.network.FriendlyByteBufMixin_API", "minecraft.network.chat.ChatTypeMixin_API", From 6ce55fd2e7161dc93f7e33b53d713ca953de5c86 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 23 Mar 2024 20:19:47 +0100 Subject: [PATCH 181/230] fix recipe fix recipes --- .../common/item/recipe/cooking/SpongeBlastingRecipe.java | 5 +++-- .../item/recipe/cooking/SpongeCampfireCookingRecipe.java | 5 +++-- .../common/item/recipe/cooking/SpongeSmeltingRecipe.java | 5 +++-- .../common/item/recipe/cooking/SpongeSmokingRecipe.java | 5 +++-- .../item/recipe/crafting/custom/SpongeSpecialRecipe.java | 3 ++- .../item/recipe/crafting/shaped/SpongeShapedRecipe.java | 6 ++++-- .../recipe/crafting/shapeless/SpongeShapelessRecipe.java | 5 +++-- .../common/item/recipe/smithing/SpongeSmithingRecipe.java | 5 +++-- .../item/recipe/stonecutting/SpongeStonecuttingRecipe.java | 5 +++-- .../api/minecraft/world/item/crafting/RecipeMixin_API.java | 5 +++-- 10 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java index 4705b2ebf6d..0fd5caf6333 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item.recipe.cooking; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -50,7 +51,7 @@ public Optional resultFunctionId() { } @Override - public ItemStack assemble(final Container container, final RegistryAccess $$1) { + public ItemStack assemble(final Container container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { final ItemStack result = IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); result.setCount(1); @@ -60,7 +61,7 @@ public ItemStack assemble(final Container container, final RegistryAccess $$1) { } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { // if (this.resultFunction != null) { // return ItemStack.EMPTY; // } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java index d7647f44be4..8dadbfdfc3a 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item.recipe.cooking; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -50,7 +51,7 @@ public Optional resultFunctionId() { } @Override - public ItemStack assemble(final Container container, final RegistryAccess $$1) { + public ItemStack assemble(final Container container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { final ItemStack result = IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); result.setCount(1); @@ -60,7 +61,7 @@ public ItemStack assemble(final Container container, final RegistryAccess $$1) { } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return ItemStack.EMPTY; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java index 30191e9b6b1..e518fbb560c 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item.recipe.cooking; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -51,7 +52,7 @@ public Optional resultFunctionId() { @Override - public ItemStack assemble(final Container container, final RegistryAccess $$1) { + public ItemStack assemble(final Container container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { final ItemStack result = IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); result.setCount(1); @@ -61,7 +62,7 @@ public ItemStack assemble(final Container container, final RegistryAccess $$1) { } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return ItemStack.EMPTY; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java index 091b0d4b99a..2a7e5517908 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item.recipe.cooking; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -51,7 +52,7 @@ public Optional resultFunctionId() { @Override - public ItemStack assemble(final Container container, final RegistryAccess $$1) { + public ItemStack assemble(final Container container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { final ItemStack result = IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); result.setCount(1); @@ -61,7 +62,7 @@ public ItemStack assemble(final Container container, final RegistryAccess $$1) { } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return ItemStack.EMPTY; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java index 7f71c546b13..56b2366d96b 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.item.recipe.crafting.custom; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; @@ -74,7 +75,7 @@ public boolean matches(CraftingContainer inv, Level worldIn) { } @Override - public ItemStack assemble(final CraftingContainer inv, final RegistryAccess $$1) { + public ItemStack assemble(final CraftingContainer inv, final HolderLookup.Provider $$1) { return ItemStackUtil.toNative(this.resultFunction.apply(InventoryUtil.toSpongeInventory(inv))); } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java index 5d13add5666..95bdb4fbe5b 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java @@ -28,12 +28,14 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; import net.minecraft.util.ExtraCodecs; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; +import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapedRecipePattern; import org.spongepowered.common.bridge.world.item.crafting.RecipeResultBridge; @@ -112,7 +114,7 @@ public NonNullList getRemainingItems(CraftingContainer inv) { } @Override - public ItemStack assemble(final CraftingContainer $$0, final RegistryAccess $$1) { + public ItemStack assemble(final CraftingContainer $$0, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply($$0); } @@ -120,7 +122,7 @@ public ItemStack assemble(final CraftingContainer $$0, final RegistryAccess $$1) } @Override - public ItemStack getResultItem(final RegistryAccess $$0) { + public ItemStack getResultItem(final HolderLookup.Provider $$0) { if (this.resultFunctionId != null) { return ItemStack.EMPTY; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java index 3fd70000124..ac82f50300c 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java @@ -28,6 +28,7 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; import net.minecraft.util.ExtraCodecs; @@ -150,7 +151,7 @@ public NonNullList getRemainingItems(CraftingContainer inv) { } @Override - public ItemStack assemble(CraftingContainer container, final RegistryAccess $$1) { + public ItemStack assemble(CraftingContainer container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); } @@ -158,7 +159,7 @@ public ItemStack assemble(CraftingContainer container, final RegistryAccess $$1) } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { // if (this.resultFunctionId != null) { // return ItemStack.EMPTY; // } diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java index 515fd76f609..d98e6bace98 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java @@ -29,6 +29,7 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -76,7 +77,7 @@ public Optional resultFunctionId() { } @Override - public ItemStack assemble(Container $$0, RegistryAccess $$1) { + public ItemStack assemble(Container $$0, HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply($$0); } @@ -94,7 +95,7 @@ public ItemStack assemble(Container $$0, RegistryAccess $$1) { } @Override - public ItemStack getResultItem(RegistryAccess $$1) { + public ItemStack getResultItem(HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return ItemStack.EMPTY; } diff --git a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java index 126391cd6cc..40511167842 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java @@ -29,6 +29,7 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.util.ExtraCodecs; @@ -89,7 +90,7 @@ public Optional resultFunctionId() { } @Override - public ItemStack assemble(final Container container, final RegistryAccess $$1) { + public ItemStack assemble(final Container container, final HolderLookup.Provider $$1) { if (this.resultFunctionId != null) { return IngredientResultUtil.cachedResultFunction(this.resultFunctionId).apply(container); } @@ -97,7 +98,7 @@ public ItemStack assemble(final Container container, final RegistryAccess $$1) { } @Override - public ItemStack getResultItem(final RegistryAccess $$1) { + public ItemStack getResultItem(final HolderLookup.Provider $$1) { // if (this.resultFunctionId != null) { // return ItemStack.EMPTY; // } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java index 25636748add..0a25ba15e38 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java @@ -26,6 +26,7 @@ import static org.spongepowered.common.inventory.util.InventoryUtil.toNativeInventory; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; @@ -50,8 +51,8 @@ public interface RecipeMixin_API extends Recipe { // @formatter:off - @Shadow ItemStack shadow$assemble(C inv, RegistryAccess registryAccess); - @Shadow net.minecraft.world.item.ItemStack shadow$getResultItem(RegistryAccess registryAccess); + @Shadow ItemStack shadow$assemble(C inv, HolderLookup.Provider registryAccess); + @Shadow net.minecraft.world.item.ItemStack shadow$getResultItem(HolderLookup.Provider registryAccess); @Shadow boolean shadow$isSpecial(); @Shadow boolean shadow$matches(C inv, net.minecraft.world.level.Level worldIn); @Shadow NonNullList shadow$getRemainingItems(C inv); From 533ade082ee0348d11b447643f113971739c80d4 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:09:42 +0100 Subject: [PATCH 182/230] 24w13a --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 5580b0cc7b9..4547c0ca77b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=24w12a +minecraftVersion=24w13a recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From a178d59e5018bec76313e28a14509fb584babde7 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:12:44 +0100 Subject: [PATCH 183/230] fix JavaOps --- .../java/org/spongepowered/common/item/SpongeItemStack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java index ded2f79f0f9..245c5e701f9 100644 --- a/src/main/java/org/spongepowered/common/item/SpongeItemStack.java +++ b/src/main/java/org/spongepowered/common/item/SpongeItemStack.java @@ -28,6 +28,7 @@ import com.google.common.collect.ImmutableList; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.DataResult; +import com.mojang.serialization.JavaOps; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; @@ -38,7 +39,6 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtOps; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.JavaOps; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; From 34deb76ab6f5408f6608aefe28b13b0527d3febd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:28:44 +0100 Subject: [PATCH 184/230] fix recipe --- .../item/recipe/SpongeRecipeSerializers.java | 48 ------------- ...SpongeSpecialCraftingRecipeSerializer.java | 72 ------------------- 2 files changed, 120 deletions(-) delete mode 100644 src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeSerializers.java delete mode 100644 src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java diff --git a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeSerializers.java b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeSerializers.java deleted file mode 100644 index e534898f7fc..00000000000 --- a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeSerializers.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.item.recipe; - -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import org.spongepowered.common.item.recipe.crafting.custom.SpongeSpecialCraftingRecipeRegistration; -import org.spongepowered.common.item.recipe.crafting.custom.SpongeSpecialCraftingRecipeSerializer; -import org.spongepowered.common.item.recipe.crafting.custom.SpongeSpecialRecipe; - -public interface SpongeRecipeSerializers { - - - SpongeSpecialCraftingRecipeSerializer SPONGE_SPECIAL = register("special", new SpongeSpecialCraftingRecipeSerializer<>(SpongeSpecialCraftingRecipeRegistration::get)); - - static , T extends Recipe> S register(final String spongeName, final S recipeSerializer) { - return (S)(Registry.>register(BuiltInRegistries.RECIPE_SERIALIZER, new ResourceLocation("sponge", spongeName).toString(), recipeSerializer)); - } - - static , T extends Recipe> S register(final ResourceLocation resourceLocation, final S recipeSerializer) { - return (S)(Registry.>register(BuiltInRegistries.RECIPE_SERIALIZER, resourceLocation.toString(), recipeSerializer)); - } -} diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java deleted file mode 100644 index 4cc47c9f7be..00000000000 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialCraftingRecipeSerializer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.item.recipe.crafting.custom; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.network.codec.StreamCodec; -import net.minecraft.world.item.crafting.CraftingBookCategory; -import net.minecraft.world.item.crafting.CraftingRecipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import org.spongepowered.common.util.Constants; - -public final class SpongeSpecialCraftingRecipeSerializer implements RecipeSerializer { - - private final Codec codec; - - public SpongeSpecialCraftingRecipeSerializer(Factory factory) { - this.codec = RecordCodecBuilder.create( - $$1 -> $$1.group( - Codec.STRING.fieldOf(Constants.Recipe.SPONGE_ID).forGetter(SpongeSpecialRecipe::id), - CraftingBookCategory.CODEC.fieldOf("category").orElse(CraftingBookCategory.MISC).forGetter(CraftingRecipe::category)) - .apply($$1, factory::create) - ); - } - - @Override - public Codec codec() { - return this.codec; - } - - @Override - public StreamCodec streamCodec() { - throw new UnsupportedOperationException("custom serializer needs client side support"); - } - - public T fromNetwork(FriendlyByteBuf $$0) { - throw new UnsupportedOperationException("custom serializer needs client side support"); - } - - public void toNetwork(FriendlyByteBuf $$0, T $$1) { - throw new UnsupportedOperationException("custom serializer needs client side support"); - } - - @FunctionalInterface - public interface Factory { - T create(String id, CraftingBookCategory category); - } -} From 5bd29ac01cea7ae605d6cbbe107352c4b84ec028 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:17:09 +0100 Subject: [PATCH 185/230] fix DamageEventUtil --- .../java/org/spongepowered/common/util/DamageEventUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/util/DamageEventUtil.java b/src/main/java/org/spongepowered/common/util/DamageEventUtil.java index 84e46ef8536..7759a36ed64 100644 --- a/src/main/java/org/spongepowered/common/util/DamageEventUtil.java +++ b/src/main/java/org/spongepowered/common/util/DamageEventUtil.java @@ -101,7 +101,7 @@ public static Optional createArmorModifiers(final LivingEntity l return Optional.empty(); } - final DoubleUnaryOperator function = incomingDamage -> -(incomingDamage - CombatRules.getDamageAfterAbsorb((float) incomingDamage, living.getArmorValue(), (float) living.getAttributeValue(Attributes.ARMOR_TOUGHNESS))); + final DoubleUnaryOperator function = incomingDamage -> -(incomingDamage - CombatRules.getDamageAfterAbsorb((float) incomingDamage, damageSource, living.getArmorValue(), (float) living.getAttributeValue(Attributes.ARMOR_TOUGHNESS))); final DamageFunction armorModifier; try (final CauseStackManager.StackFrame frame = ((Server) living.getServer()).causeStackManager().pushCauseFrame()){ frame.pushCause(living); From d6f7765d323be4a0d94bfc9da3d240c2d988f66d Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:19:28 +0100 Subject: [PATCH 186/230] fix codecs --- .../criterion/SpongeDummyTrigger.java | 2 +- .../criterion/SpongeScoreTrigger.java | 4 ++-- .../adventure/SpongeChatTypeTemplate.java | 4 ++-- .../entity/damage/SpongeDamageTypeTemplate.java | 6 ++---- .../item/recipe/SpongeRecipeRegistration.java | 2 +- .../crafting/shaped/SpongeShapedRecipe.java | 4 ++-- .../shapeless/SpongeShapelessRecipe.java | 2 +- .../recipe/ingredient/SpongeIngredient.java | 8 ++++---- .../stonecutting/SpongeStonecuttingRecipe.java | 2 +- .../common/tag/SpongeTagTemplate.java | 3 +-- .../common/world/biome/SpongeBiomeTemplate.java | 4 ++-- .../generation/carver/SpongeCarverTemplate.java | 4 ++-- .../noise/SpongeDensityFunctionTemplate.java | 4 ++-- .../SpongeNoiseGeneratorConfigTemplate.java | 4 ++-- .../config/noise/SpongeNoiseTemplate.java | 4 ++-- .../feature/SpongeFeatureTemplate.java | 4 ++-- .../feature/SpongePlacedFeatureTemplate.java | 4 ++-- .../structure/SpongeStructureSetTemplate.java | 4 ++-- .../structure/SpongeStructureTemplate.java | 4 ++-- .../jigsaw/SpongeJigsawPoolTemplate.java | 4 ++-- .../jigsaw/SpongeProcessorListTemplate.java | 4 ++-- .../world/server/SpongeWorldTemplate.java | 5 ++--- .../world/server/SpongeWorldTypeTemplate.java | 6 +++--- .../levelgen/carver/WorldCarverMixin_API.java | 5 +++-- .../feature/ConfiguredFeatureMixin_API.java | 2 +- .../levelgen/feature/FeatureMixin_API.java | 6 +++--- .../PlacementModifierTypeMixin_API.java | 6 +++--- .../levelgen/structure/StructureMixin_API.java | 4 ++-- .../structure/StructureTypeMixin_API.java | 6 +++--- .../StructureProcessorMixin_API.java | 2 +- .../StructureProcessorTypeMixin_API.java | 5 +++-- .../mixin/core/advancements/CriterionMixin.java | 4 ++-- .../world/item/crafting/IngredientMixin.java | 3 +-- .../crafting/ShapedRecipe_SerializerMixin.java | 7 ++++--- .../ShapelessRecipe_SerializerMixin.java | 7 ++++--- .../crafting/SimpleCookingSerializerMixin.java | 17 ++++++++--------- ...SmithingTransformRecipe_SerializerMixin.java | 7 ++++--- .../StonecutterRecipe_SerializerMixin.java | 7 ++++--- 38 files changed, 90 insertions(+), 90 deletions(-) diff --git a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java index e0b3c99b2c0..afc034d4c37 100644 --- a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java +++ b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java @@ -49,7 +49,7 @@ public Codec codec() { public record TriggerInstance(Optional player) implements SimpleCriterionTrigger.SimpleInstance { - public static final Codec CODEC = RecordCodecBuilder.create(($$0) -> $$0.group(ExtraCodecs.strictOptionalField(EntityPredicate.ADVANCEMENT_CODEC, "player").forGetter(TriggerInstance::player)).apply($$0, TriggerInstance::new)); + public static final Codec CODEC = RecordCodecBuilder.create(($$0) -> $$0.group(EntityPredicate.ADVANCEMENT_CODEC.optionalFieldOf("player").forGetter(TriggerInstance::player)).apply($$0, TriggerInstance::new)); public static TriggerInstance dummy() { diff --git a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java index 55be4527c81..2eb09d15eed 100644 --- a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java +++ b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java @@ -51,8 +51,8 @@ public Codec codec() { public record TriggerInstance(Optional player, int triggerTimes) implements SimpleCriterionTrigger.SimpleInstance { public static final Codec CODEC = RecordCodecBuilder.create(($$0) -> $$0.group( - ExtraCodecs.strictOptionalField(EntityPredicate.ADVANCEMENT_CODEC, "player").forGetter(TriggerInstance::player), - ExtraCodecs.strictOptionalField(Codec.INT, "triggerTimes", -1).forGetter(TriggerInstance::triggerTimes) + EntityPredicate.ADVANCEMENT_CODEC.optionalFieldOf("player").forGetter(TriggerInstance::player), + Codec.INT.optionalFieldOf("triggerTimes", -1).forGetter(TriggerInstance::triggerTimes) ).apply($$0, TriggerInstance::new)); diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java b/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java index a1c525aec4b..bdc5636e3a6 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeChatTypeTemplate.java @@ -72,12 +72,12 @@ public DataContainer toContainer() { public static JsonElement encode(final ChatTypeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ChatType.DIRECT_CODEC.encodeStart(ops, (ChatType) (Object) template.type()).getOrThrow(false, e -> {}); + return ChatType.DIRECT_CODEC.encodeStart(ops, (ChatType) (Object) template.type()).getOrThrow(); } public static ChatType decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ChatType.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return ChatType.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static ChatTypeTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java index c976b1a6382..32a6840a18d 100644 --- a/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/event/cause/entity/damage/SpongeDamageTypeTemplate.java @@ -72,14 +72,12 @@ public DataContainer toContainer() { public static JsonElement encode(final DamageTypeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return DamageType.DIRECT_CODEC.encodeStart(ops, (DamageType) (Object) template.type()).getOrThrow(false, e -> { - }); + return DamageType.DIRECT_CODEC.encodeStart(ops, (DamageType) (Object) template.type()).getOrThrow(); } public static DamageType decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return DamageType.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> { - }); + return DamageType.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static DamageTypeTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, diff --git a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java index eefb08c0743..7b1a01885c3 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java +++ b/src/main/java/org/spongepowered/common/item/recipe/SpongeRecipeRegistration.java @@ -156,7 +156,7 @@ public static JsonObject encode(RecipeRegistration template, RegistryAccess acce if (encoded.result().isPresent()) { return encoded.result().get().getAsJsonObject(); } - final DataResult.PartialResult error = encoded.error().get(); + final var error = encoded.error().get(); throw new RuntimeException(error.message()); } catch (Exception e) { throw new RuntimeException("Could not encode recipe " + template.key(), e); diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java index 95bdb4fbe5b..3eb951e1f5a 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java @@ -51,11 +51,11 @@ public class SpongeShapedRecipe extends ShapedRecipe implements ResultFunctionRe public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$0 -> $$0.group( Codec.STRING.fieldOf(Constants.Recipe.SPONGE_TYPE).forGetter(t -> "custom"), // important to fail early when decoding vanilla recipes - ExtraCodecs.strictOptionalField(Codec.STRING, Constants.Recipe.GROUP, "").forGetter(ShapedRecipe::getGroup), + Codec.STRING.optionalFieldOf(Constants.Recipe.GROUP, "").forGetter(ShapedRecipe::getGroup), CraftingBookCategory.CODEC.fieldOf(Constants.Recipe.CATEGORY).orElse(CraftingBookCategory.MISC).forGetter(ShapedRecipe::category), ShapedRecipePattern.MAP_CODEC.forGetter($$0x -> ((ShapedRecipeBridge) $$0x).bridge$pattern()), ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), - ExtraCodecs.strictOptionalField(Codec.BOOL, "show_notification", true).forGetter(ShapedRecipe::showNotification), + Codec.BOOL.optionalFieldOf("show_notification", true).forGetter(ShapedRecipe::showNotification), IngredientResultUtil.CACHED_RESULT_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULTFUNCTION).forGetter(ResultFunctionRecipe::resultFunctionId), IngredientResultUtil.CACHED_REMAINING_FUNC_CODEC.optionalFieldOf(Constants.Recipe.SPONGE_REMAINING_ITEMS).forGetter(SpongeShapedRecipe::remainingItemsFunctionId) ) diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java index ac82f50300c..656ae496ba0 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java @@ -62,7 +62,7 @@ public class SpongeShapelessRecipe extends ShapelessRecipe { public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$0 -> $$0.group( Codec.STRING.fieldOf(Constants.Recipe.SPONGE_TYPE).forGetter(t -> "custom"), // important to fail early when decoding vanilla recipes - ExtraCodecs.strictOptionalField(Codec.STRING, "group", "").forGetter(ShapelessRecipe::getGroup), + Codec.STRING.optionalFieldOf("group", "").forGetter(ShapelessRecipe::getGroup), CraftingBookCategory.CODEC.fieldOf("category").orElse(CraftingBookCategory.MISC).forGetter(ShapelessRecipe::category), ItemStack.CODEC.fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), Ingredient.CODEC_NONEMPTY diff --git a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java index 45732d8a748..17f79ab1e5c 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java +++ b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java @@ -55,13 +55,13 @@ public class SpongeIngredient extends Ingredient { SpongeCommon.logger().info("Found legacy recipe"); return new ItemStack(type, qty); })); - private static final Codec STACK_CODEC = ExtraCodecs.xor(ItemStack.CODEC, LEGACY_STACK_CODEC).xmap(to -> to.map(i -> i, i -> i), Either::left); + private static final Codec STACK_CODEC = Codec.xor(ItemStack.CODEC, LEGACY_STACK_CODEC).xmap(to -> to.map(i -> i, i -> i), Either::left); private static final Codec RAW_CODEC = RecordCodecBuilder.create( builder -> builder.group( - ExtraCodecs.strictOptionalField(Codec.STRING, SpongeItemList.INGREDIENT_TYPE, "vanilla").forGetter(raw -> raw.type), - ExtraCodecs.strictOptionalField(Codec.list(STACK_CODEC), SpongeItemList.INGREDIENT_ITEM, List.of()).forGetter(raw -> raw.stacks), - ExtraCodecs.strictOptionalField(Codec.STRING, SpongePredicateItemList.INGREDIENT_PREDICATE).forGetter(raw -> raw.predicateId) + Codec.STRING.optionalFieldOf(SpongeItemList.INGREDIENT_TYPE, "vanilla").forGetter(raw -> raw.type), + Codec.list(STACK_CODEC).optionalFieldOf(SpongeItemList.INGREDIENT_ITEM, List.of()).forGetter(raw -> raw.stacks), + Codec.STRING.optionalFieldOf(SpongePredicateItemList.INGREDIENT_PREDICATE).forGetter(raw -> raw.predicateId) ).apply(builder, SpongeRawIngredient::new) ); diff --git a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java index 40511167842..3da81e3e330 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java @@ -59,7 +59,7 @@ public class SpongeStonecuttingRecipe extends StonecutterRecipe implements Resul public static final MapCodec SPONGE_CODEC = RecordCodecBuilder.mapCodec( $$1 -> $$1.group( Codec.STRING.fieldOf(SPONGE_TYPE).forGetter(a -> "custom"), - ExtraCodecs.strictOptionalField(Codec.STRING, "group", "").forGetter(SingleItemRecipe::getGroup), + Codec.STRING.optionalFieldOf("group", "").forGetter(SingleItemRecipe::getGroup), Ingredient.CODEC_NONEMPTY.fieldOf(Constants.Recipe.STONECUTTING_INGREDIENT).forGetter($$0x -> $$0x.getIngredients().get(0)), RESULT_CODEC.forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), ItemStack.CODEC.optionalFieldOf(Constants.Recipe.SPONGE_RESULT, ItemStack.EMPTY).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$spongeResult()), diff --git a/src/main/java/org/spongepowered/common/tag/SpongeTagTemplate.java b/src/main/java/org/spongepowered/common/tag/SpongeTagTemplate.java index 766b1d0056b..7f7d0c84d03 100644 --- a/src/main/java/org/spongepowered/common/tag/SpongeTagTemplate.java +++ b/src/main/java/org/spongepowered/common/tag/SpongeTagTemplate.java @@ -85,8 +85,7 @@ public static > JsonObject encode(TagTemplate template, builder.addOptionalTag(location); } }); - return TagFile.CODEC.encodeStart(JsonOps.INSTANCE, new TagFile(builder.build(), spongeTemplate.replace)).getOrThrow(false, e -> { - }).getAsJsonObject(); + return TagFile.CODEC.encodeStart(JsonOps.INSTANCE, new TagFile(builder.build(), spongeTemplate.replace)).getOrThrow().getAsJsonObject(); } } diff --git a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java index 62fcd007d73..cea046cce1d 100644 --- a/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java +++ b/src/main/java/org/spongepowered/common/world/biome/SpongeBiomeTemplate.java @@ -101,12 +101,12 @@ public org.spongepowered.api.world.biome.Biome biome() { public static JsonElement encode(final BiomeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return Biome.DIRECT_CODEC.encodeStart(ops, (Biome) (Object) template.biome()).getOrThrow(false, e -> {}); + return Biome.DIRECT_CODEC.encodeStart(ops, (Biome) (Object) template.biome()).getOrThrow(); } public static Biome decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return Biome.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return Biome.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static BiomeTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/carver/SpongeCarverTemplate.java b/src/main/java/org/spongepowered/common/world/generation/carver/SpongeCarverTemplate.java index 169dd8dfeb7..cefbb919521 100644 --- a/src/main/java/org/spongepowered/common/world/generation/carver/SpongeCarverTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/carver/SpongeCarverTemplate.java @@ -73,7 +73,7 @@ public Carver carver() { public static JsonElement encode(final Codec> codec, final ConfiguredWorldCarver carver, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return codec.encodeStart(ops, carver).getOrThrow(false, e -> {}); + return codec.encodeStart(ops, carver).getOrThrow(); } public static JsonElement encode(final CarverTemplate template, final RegistryAccess registryAccess) { @@ -82,7 +82,7 @@ public static JsonElement encode(final CarverTemplate template, final RegistryAc public static ConfiguredWorldCarver decode(final Codec> codec, final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return codec.parse(ops, json).getOrThrow(false, e -> {}); + return codec.parse(ops, json).getOrThrow(); } public static CarverTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeDensityFunctionTemplate.java b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeDensityFunctionTemplate.java index d20b0c5ca04..7d52ebff2c2 100644 --- a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeDensityFunctionTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeDensityFunctionTemplate.java @@ -68,12 +68,12 @@ public DataContainer toContainer() { } public static JsonElement encode(final DensityFunctionTemplate template, final RegistryAccess registryAccess) { - return DensityFunction.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (DensityFunction) template.densityFunction()).getOrThrow(false, e -> {}); + return DensityFunction.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (DensityFunction) template.densityFunction()).getOrThrow(); } public static DensityFunction decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return DensityFunction.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return DensityFunction.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeDensityFunctionTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseGeneratorConfigTemplate.java b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseGeneratorConfigTemplate.java index d3eadba0cae..cb7707232b1 100644 --- a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseGeneratorConfigTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseGeneratorConfigTemplate.java @@ -78,12 +78,12 @@ public DataContainer toContainer() { } public static JsonElement encode(final NoiseGeneratorConfigTemplate template, final RegistryAccess registryAccess) { - return NoiseGeneratorSettings.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (NoiseGeneratorSettings) (Object) template.config()).getOrThrow(false, e -> {}); + return NoiseGeneratorSettings.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (NoiseGeneratorSettings) (Object) template.config()).getOrThrow(); } public static NoiseGeneratorSettings decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return NoiseGeneratorSettings.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return NoiseGeneratorSettings.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static NoiseGeneratorConfigTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseTemplate.java b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseTemplate.java index e8b94711f5a..57e4ab827cd 100644 --- a/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/config/noise/SpongeNoiseTemplate.java @@ -72,12 +72,12 @@ public DataContainer toContainer() { } public static JsonElement encode(final NoiseTemplate template, final RegistryAccess registryAccess) { - return NormalNoise.NoiseParameters.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (NormalNoise.NoiseParameters) (Object) template.noise()).getOrThrow(false, e -> {}); + return NormalNoise.NoiseParameters.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, (NormalNoise.NoiseParameters) (Object) template.noise()).getOrThrow(); } public static NormalNoise.NoiseParameters decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return NormalNoise.NoiseParameters.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return NormalNoise.NoiseParameters.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeNoiseTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/feature/SpongeFeatureTemplate.java b/src/main/java/org/spongepowered/common/world/generation/feature/SpongeFeatureTemplate.java index b16c6d08aeb..514c33a6f2b 100644 --- a/src/main/java/org/spongepowered/common/world/generation/feature/SpongeFeatureTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/feature/SpongeFeatureTemplate.java @@ -71,12 +71,12 @@ public org.spongepowered.api.world.generation.feature.Feature feature() { public static JsonElement encode(final FeatureTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ConfiguredFeature.DIRECT_CODEC.encodeStart(ops, (ConfiguredFeature) (Object) template.feature()).getOrThrow(false, e -> {}); + return ConfiguredFeature.DIRECT_CODEC.encodeStart(ops, (ConfiguredFeature) (Object) template.feature()).getOrThrow(); } public static ConfiguredFeature decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return ConfiguredFeature.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return ConfiguredFeature.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeFeatureTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java b/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java index 32f01de11b4..637c7386973 100644 --- a/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/feature/SpongePlacedFeatureTemplate.java @@ -80,12 +80,12 @@ public PlacedFeature feature() { public static JsonElement encode(final PlacedFeatureTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return net.minecraft.world.level.levelgen.placement.PlacedFeature.DIRECT_CODEC.encodeStart(ops, (net.minecraft.world.level.levelgen.placement.PlacedFeature) (Object) template.feature()).getOrThrow(false, e -> {}); + return net.minecraft.world.level.levelgen.placement.PlacedFeature.DIRECT_CODEC.encodeStart(ops, (net.minecraft.world.level.levelgen.placement.PlacedFeature) (Object) template.feature()).getOrThrow(); } public static net.minecraft.world.level.levelgen.placement.PlacedFeature decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return net.minecraft.world.level.levelgen.placement.PlacedFeature.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return net.minecraft.world.level.levelgen.placement.PlacedFeature.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static PlacedFeatureTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureSetTemplate.java b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureSetTemplate.java index b2352dfe8c0..e2b13b26b98 100644 --- a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureSetTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureSetTemplate.java @@ -76,12 +76,12 @@ public DataContainer toContainer() { public static JsonElement encode(final StructureSetTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureSet.DIRECT_CODEC.encodeStart(ops, (StructureSet) (Object) template.structureSet()).getOrThrow(false, e -> {}); + return StructureSet.DIRECT_CODEC.encodeStart(ops, (StructureSet) (Object) template.structureSet()).getOrThrow(); } public static StructureSet decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureSet.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return StructureSet.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeStructureSetTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureTemplate.java b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureTemplate.java index b5c8d1114e4..61894fca865 100644 --- a/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/structure/SpongeStructureTemplate.java @@ -69,12 +69,12 @@ public DataContainer toContainer() { public static JsonElement encode(final StructureTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return Structure.DIRECT_CODEC.encodeStart(ops, (Structure) template.structure()).getOrThrow(false, e -> {}); + return Structure.DIRECT_CODEC.encodeStart(ops, (Structure) template.structure()).getOrThrow(); } public static net.minecraft.world.level.levelgen.structure.Structure decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return Structure.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return Structure.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeStructureTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeJigsawPoolTemplate.java b/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeJigsawPoolTemplate.java index 6819ee59196..a6011f2a6cd 100644 --- a/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeJigsawPoolTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeJigsawPoolTemplate.java @@ -75,12 +75,12 @@ public DataContainer toContainer() { public static JsonElement encode(final JigsawPoolTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureTemplatePool.DIRECT_CODEC.encodeStart(ops, (StructureTemplatePool) template.jigsawPool()).getOrThrow(false, e -> {}); + return StructureTemplatePool.DIRECT_CODEC.encodeStart(ops, (StructureTemplatePool) template.jigsawPool()).getOrThrow(); } public static StructureTemplatePool decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureTemplatePool.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return StructureTemplatePool.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeJigsawPoolTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeProcessorListTemplate.java b/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeProcessorListTemplate.java index 5e8d7bb3b95..200dea65d32 100644 --- a/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeProcessorListTemplate.java +++ b/src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeProcessorListTemplate.java @@ -73,12 +73,12 @@ public DataContainer toContainer() { public static JsonElement encode(final ProcessorListTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureProcessorType.LIST_OBJECT_CODEC.encodeStart(ops, ((StructureProcessorList) template.processorList())).getOrThrow(false, e -> {}); + return StructureProcessorType.LIST_OBJECT_CODEC.encodeStart(ops, ((StructureProcessorList) template.processorList())).getOrThrow(); } public static StructureProcessorList decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return StructureProcessorType.LIST_OBJECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return StructureProcessorType.LIST_OBJECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeProcessorListTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement json, final RegistryAccess registryAccess) { diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java index fc0aa426c21..29f57c803eb 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTemplate.java @@ -130,7 +130,7 @@ public record SpongeWorldTemplate(ResourceKey key, LevelStem levelStem, DataPack public static LevelStem decodeStem(final JsonElement pack, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); SpongeWorldTemplate.fixDimensionDatapack(pack); - return LevelStem.CODEC.parse(ops, pack).getOrThrow(false, e -> {}); + return LevelStem.CODEC.parse(ops, pack).getOrThrow(); } public static WorldTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { @@ -171,8 +171,7 @@ public DataContainer toContainer() { public static JsonElement serialize(final WorldTemplate s, final RegistryAccess registryAccess) { if (s instanceof final SpongeWorldTemplate t) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return SpongeWorldTemplate.DIRECT_CODEC.encodeStart(ops, t.levelStem).getOrThrow(false, e -> { - }); + return SpongeWorldTemplate.DIRECT_CODEC.encodeStart(ops, t.levelStem).getOrThrow(); } throw new IllegalArgumentException("WorldTemplate is not a SpongeWorldTemplate"); } diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java index 4992455eb67..1474ef3e1f6 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldTypeTemplate.java @@ -94,12 +94,12 @@ public WorldType worldType() { public static JsonElement encode(final WorldTypeTemplate template, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return SpongeDimensionTypes.DIRECT_CODEC.encodeStart(ops, (DimensionType) (Object) template.worldType()).getOrThrow(false, e -> {}); + return SpongeDimensionTypes.DIRECT_CODEC.encodeStart(ops, (DimensionType) (Object) template.worldType()).getOrThrow(); } public static DimensionType decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - return SpongeDimensionTypes.DIRECT_CODEC.parse(ops, json).getOrThrow(false, e -> {}); + return SpongeDimensionTypes.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static WorldTypeTemplate decode(final DataPack pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { @@ -151,7 +151,7 @@ public Builder fromValue(final WorldType type) { public Builder fromDataPack(final DataView pack) throws IOException { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(pack)); final DataResult> parsed = DimensionType.CODEC.parse(JsonOps.INSTANCE, json); - final DimensionType dimensionType = parsed.getOrThrow(false, e -> {}).value(); + final DimensionType dimensionType = parsed.getOrThrow().value(); this.fromValue((WorldType) (Object) dimensionType); return this; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/carver/WorldCarverMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/carver/WorldCarverMixin_API.java index b6fecdff0fb..e0105288e0e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/carver/WorldCarverMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/carver/WorldCarverMixin_API.java @@ -27,6 +27,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import net.minecraft.world.level.levelgen.carver.CarverConfiguration; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; import net.minecraft.world.level.levelgen.carver.WorldCarver; @@ -46,14 +47,14 @@ public abstract class WorldCarverMixin_API implements CarverType { //@formatter:off - @Shadow @Final private Codec> configuredCodec; + @Shadow @Final private MapCodec> configuredCodec; //@formatter:on @Override public Carver configure(final DataView config) throws IllegalArgumentException { try { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(config)); - return (Carver) (Object) SpongeCarverTemplate.decode((Codec>) (Object) this.configuredCodec, json, SpongeCommon.server().registryAccess()); + return (Carver) (Object) SpongeCarverTemplate.decode((Codec>) (Object) this.configuredCodec.codec(), json, SpongeCommon.server().registryAccess()); } catch (IOException e) { throw new IllegalStateException("Could not read configuration: " + config, e); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/ConfiguredFeatureMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/ConfiguredFeatureMixin_API.java index 0f46a2ed120..3226480c026 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/ConfiguredFeatureMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/ConfiguredFeatureMixin_API.java @@ -69,7 +69,7 @@ public APIF type() { @Override public DataView toContainer() { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - final JsonElement serialized = this.feature.configuredCodec().encodeStart(ops, (ConfiguredFeature>) (Object) this).getOrThrow(false, e -> {}); + final JsonElement serialized = this.feature.configuredCodec().codec().encodeStart(ops, (ConfiguredFeature>) (Object) this).getOrThrow(); try { return DataFormats.JSON.get().read(serialized.toString()); } catch (IOException e) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/FeatureMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/FeatureMixin_API.java index d29b46bcc1c..834e95ef47c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/FeatureMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/feature/FeatureMixin_API.java @@ -26,8 +26,8 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import net.minecraft.resources.RegistryOps; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; @@ -46,7 +46,7 @@ public abstract class FeatureMixin_API implements FeatureType { //@formatter:off - @Shadow @Final private Codec>> configuredCodec; + @Shadow @Final private MapCodec>> configuredCodec; //@formatter:on @Override @@ -54,7 +54,7 @@ public Feature configure(final DataView config) { try { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(config)); final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - return (Feature) (Object) this.configuredCodec.parse(ops, json).getOrThrow(false, e -> {}); + return (Feature) (Object) this.configuredCodec.codec().parse(ops, json).getOrThrow(); } catch (IOException e) { throw new IllegalStateException("Could not read configuration: " + config, e); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/placement/PlacementModifierTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/placement/PlacementModifierTypeMixin_API.java index 38bdb27dcab..0bf6767b445 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/placement/PlacementModifierTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/placement/PlacementModifierTypeMixin_API.java @@ -26,8 +26,8 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import net.minecraft.resources.RegistryOps; import org.spongepowered.api.data.persistence.DataFormats; import org.spongepowered.api.data.persistence.DataView; @@ -41,7 +41,7 @@ public interface PlacementModifierTypeMixin_API

extends PlacementModifierType { //@formatter:off - @Shadow Codec

shadow$codec(); + @Shadow MapCodec

shadow$codec(); //@formatter:on @Override @@ -49,7 +49,7 @@ default PlacementModifier configure(final DataView config) throws IllegalArgumen try { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(config)); final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - return (PlacementModifier) this.shadow$codec().parse(ops, json).getOrThrow(false, e -> {}); + return (PlacementModifier) this.shadow$codec().codec().parse(ops, json).getOrThrow(); } catch (Exception e) { throw new IllegalArgumentException("Could not configure PlacementModifier." , e); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java index 09106752fda..9e057d9f93d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureMixin_API.java @@ -119,7 +119,7 @@ public DecorationStep decorationStep() { @Override public DataView toContainer() { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - final JsonElement serialized = this.api$codec().encodeStart(ops, (Structure) (Object) this).getOrThrow(false, e -> {}); + final JsonElement serialized = this.api$codec().encodeStart(ops, (Structure) (Object) this).getOrThrow(); try { return DataFormats.JSON.get().read(serialized.toString()); } catch (IOException e) { @@ -129,6 +129,6 @@ public DataView toContainer() { private Codec api$codec() { final var type = (net.minecraft.world.level.levelgen.structure.StructureType) this.shadow$type(); - return type.codec(); + return type.codec().codec(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureTypeMixin_API.java index 4e98aaf7ed4..fc85a2e240a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/StructureTypeMixin_API.java @@ -26,8 +26,8 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import net.minecraft.resources.RegistryOps; import org.spongepowered.api.data.persistence.DataFormats; import org.spongepowered.api.data.persistence.DataView; @@ -41,7 +41,7 @@ @Mixin(net.minecraft.world.level.levelgen.structure.StructureType.class) public interface StructureTypeMixin_API extends org.spongepowered.api.world.generation.structure.StructureType { // @formatter:off - @Shadow Codec codec(); + @Shadow MapCodec codec(); // @formatter:on @Override @@ -50,7 +50,7 @@ default Structure configure(DataView config) { try { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(config)); final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - return (Structure) (Object) this.codec().parse(ops, json).getOrThrow(false, e -> {}); + return (Structure) (Object) this.codec().codec().parse(ops, json).getOrThrow(); } catch (IOException e) { throw new IllegalStateException("Could not read configuration: " + config, e); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorMixin_API.java index 7c0ed5772b9..c30a3c57d88 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorMixin_API.java @@ -54,7 +54,7 @@ public ProcessorType type() { @Override public DataContainer toContainer() { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); - final JsonElement serialized = this.shadow$getType().codec().encodeStart(ops, (StructureProcessor) (Object) this).getOrThrow(false, e -> {}); + final JsonElement serialized = this.shadow$getType().codec().codec().encodeStart(ops, (StructureProcessor) (Object) this).getOrThrow(); try { return DataFormats.JSON.get().read(serialized.toString()); } catch (IOException e) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java index 323f8237d8a..5be0f737ce6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java @@ -28,6 +28,7 @@ import com.google.gson.JsonParser; import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; +import com.mojang.serialization.MapCodec; import net.minecraft.resources.RegistryOps; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; @@ -45,14 +46,14 @@ public interface StructureProcessorTypeMixin_API

extends ProcessorType { // @formatter:off - @Shadow Codec

shadow$codec(); + @Shadow MapCodec

shadow$codec(); // @formatter:on @Override default Processor configure(final DataView dataView) throws IOException { final RegistryOps ops = RegistryOps.create(JsonOps.INSTANCE, SpongeCommon.server().registryAccess()); final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(dataView)); - final P processor = this.shadow$codec().parse(ops, json).getOrThrow(false, e -> {}); + final P processor = this.shadow$codec().codec().parse(ops, json).getOrThrow(); return (Processor) processor; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/CriterionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/CriterionMixin.java index 1a153bb87f0..72b97c688f5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/CriterionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/CriterionMixin.java @@ -70,10 +70,10 @@ public abstract class CriterionMixin impleme @SuppressWarnings("deprecation") var mcCodec = ExtraCodecs.dispatchOptionalValue($$0, $$1, $$2, $$3, $$4); - final var triggerTimesCodec = Codec.optionalField("trigger_times", Codec.INT); + final var triggerTimesCodec = Codec.INT.optionalFieldOf("trigger_times"); var tmpCodec = CriterionMixin.impl$dependent(mcCodec, triggerTimesCodec, CriterionBridge::bridge$getScoreGoal, CriterionBridge::bridge$setScoreGoal); - final var criterionCodec = Codec.optionalField("criterion", Codec.STRING); + final var criterionCodec = Codec.STRING.optionalFieldOf("criterion"); tmpCodec = CriterionMixin.impl$dependent(tmpCodec, criterionCodec, bridge -> bridge.bridge$getScoreCriterion() == null ? null : bridge.bridge$getScoreCriterion().name(), CriterionBridge::bridge$setScoreCriterionName); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java index eef822b85a2..ade3ce146d4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/IngredientMixin.java @@ -26,7 +26,6 @@ import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.item.crafting.Ingredient; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -40,7 +39,7 @@ public abstract class IngredientMixin { @Inject(method = "codec", at = @At(value = "RETURN"), cancellable = true) private static void impl$modifyCodec(final boolean $$0, final CallbackInfoReturnable> cir) { final Codec original = cir.getReturnValue(); - var combinedCodec = ExtraCodecs.xor(SpongeIngredient.CODEC, original).xmap(to -> to.map(si -> si, i -> i), + var combinedCodec = Codec.xor(SpongeIngredient.CODEC, original).xmap(to -> to.map(si -> si, i -> i), fr -> { if (fr instanceof SpongeIngredient si) { return Either.left(si); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapedRecipe_SerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapedRecipe_SerializerMixin.java index 5a1b3659029..10af39bc8f3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapedRecipe_SerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapedRecipe_SerializerMixin.java @@ -27,6 +27,7 @@ import com.mojang.datafixers.kinds.App; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.crafting.ShapedRecipe; import org.spongepowered.asm.mixin.Mixin; @@ -39,8 +40,8 @@ @Mixin(ShapedRecipe.Serializer.class) public abstract class ShapedRecipe_SerializerMixin { - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;create(Ljava/util/function/Function;)Lcom/mojang/serialization/Codec;")) - private static Codec impl$onCreateCodec(final Function, ? extends App, ShapedRecipe>> builder) { + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) + private static MapCodec impl$onCreateCodec(final Function, ? extends App, ShapedRecipe>> builder) { final var mcMapCodec = RecordCodecBuilder.mapCodec(builder); return Codec.mapEither(SpongeShapedRecipe.SPONGE_CODEC, mcMapCodec).xmap(to -> to.map(si -> si, i -> i), fr -> { @@ -48,6 +49,6 @@ public abstract class ShapedRecipe_SerializerMixin { return Either.left(si); } return Either.right(fr); - }).codec(); + }); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapelessRecipe_SerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapelessRecipe_SerializerMixin.java index 0c7fb4d0d1a..a8bf6cacf16 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapelessRecipe_SerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/ShapelessRecipe_SerializerMixin.java @@ -27,6 +27,7 @@ import com.mojang.datafixers.kinds.App; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.crafting.ShapelessRecipe; import org.spongepowered.asm.mixin.Mixin; @@ -41,8 +42,8 @@ public abstract class ShapelessRecipe_SerializerMixin { @Redirect(method = "", at = @At(value = "INVOKE", - target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;create(Ljava/util/function/Function;)Lcom/mojang/serialization/Codec;")) - private static Codec impl$onCreateCodec( + target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) + private static MapCodec impl$onCreateCodec( final Function, ? extends App, ShapelessRecipe>> builder) { final var mcMapCodec = RecordCodecBuilder.mapCodec(builder); return Codec.mapEither(SpongeShapelessRecipe.SPONGE_CODEC, mcMapCodec).xmap(to -> to.map(si -> si, i -> i), @@ -51,6 +52,6 @@ public abstract class ShapelessRecipe_SerializerMixin { return Either.left(si); } return Either.right(fr); - }).codec(); + }); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java index 8111e8d1df3..1ff1a6a7ddb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SimpleCookingSerializerMixin.java @@ -32,7 +32,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.AbstractCookingRecipe; import net.minecraft.world.item.crafting.BlastingRecipe; @@ -60,8 +59,8 @@ public abstract class SimpleCookingSerializerMixin { @Redirect(method = "", at = @At(value = "INVOKE", - target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;create(Ljava/util/function/Function;)Lcom/mojang/serialization/Codec;")) - private Codec impl$onCreateCodec( + target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) + private MapCodec impl$onCreateCodec( final Function, ? extends App, T>> builder, final AbstractCookingRecipe.Factory $$0, final int defaultCookingTime) { @@ -76,7 +75,7 @@ public abstract class SimpleCookingSerializerMixin MapCodec impl$buildCodec(CookingRecipeFactory factory, int defaultCookingTime) @@ -124,7 +123,7 @@ public abstract class SimpleCookingSerializerMixin $$2.group( Codec.STRING.fieldOf(SPONGE_TYPE).forGetter(a -> "custom"), - ExtraCodecs.strictOptionalField(Codec.STRING, "group", "").forGetter(AbstractCookingRecipe::getGroup), + Codec.STRING.optionalFieldOf("group", "").forGetter(AbstractCookingRecipe::getGroup), CookingBookCategory.CODEC.fieldOf("category").orElse(CookingBookCategory.MISC).forGetter(AbstractCookingRecipe::category), Ingredient.CODEC_NONEMPTY.fieldOf(Constants.Recipe.COOKING_INGREDIENT).forGetter($$0x -> $$0x.getIngredients().get(0)), BuiltInRegistries.ITEM.byNameCodec().xmap(ItemStack::new, ItemStack::getItem).fieldOf(Constants.Recipe.RESULT).forGetter($$0x -> ((RecipeResultBridge)$$0x).bridge$result()), diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipe_SerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipe_SerializerMixin.java index e8eb4f1e8f3..fd37c712862 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipe_SerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/SmithingTransformRecipe_SerializerMixin.java @@ -27,6 +27,7 @@ import com.mojang.datafixers.kinds.App; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.crafting.SmithingTransformRecipe; import org.spongepowered.asm.mixin.Mixin; @@ -39,8 +40,8 @@ @Mixin(SmithingTransformRecipe.Serializer.class) public abstract class SmithingTransformRecipe_SerializerMixin { - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;create(Ljava/util/function/Function;)Lcom/mojang/serialization/Codec;")) - private static Codec impl$onCreateCodec(final Function, ? extends App, SmithingTransformRecipe>> builder) { + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) + private static MapCodec impl$onCreateCodec(final Function, ? extends App, SmithingTransformRecipe>> builder) { final var mcMapCodec = RecordCodecBuilder.mapCodec(builder); return Codec.mapEither(SpongeSmithingRecipe.SPONGE_CODEC, mcMapCodec).xmap(to -> to.map(si -> si, i -> i), fr -> { @@ -48,6 +49,6 @@ public abstract class SmithingTransformRecipe_SerializerMixin { return Either.left(si); } return Either.right(fr); - }).codec(); + }); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/StonecutterRecipe_SerializerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/StonecutterRecipe_SerializerMixin.java index 1249f6eaa22..2da5defb44b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/StonecutterRecipe_SerializerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/StonecutterRecipe_SerializerMixin.java @@ -27,6 +27,7 @@ import com.mojang.datafixers.kinds.App; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.crafting.StonecutterRecipe; import org.spongepowered.asm.mixin.Mixin; @@ -39,8 +40,8 @@ @Mixin(StonecutterRecipe.Serializer.class) public abstract class StonecutterRecipe_SerializerMixin { - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;create(Ljava/util/function/Function;)Lcom/mojang/serialization/Codec;")) - private Codec impl$onCreateCodec(final Function, ? extends App, StonecutterRecipe>> builder) { + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/codecs/RecordCodecBuilder;mapCodec(Ljava/util/function/Function;)Lcom/mojang/serialization/MapCodec;")) + private MapCodec impl$onCreateCodec(final Function, ? extends App, StonecutterRecipe>> builder) { final var mcMapCodec = RecordCodecBuilder.mapCodec(builder); return Codec.mapEither(SpongeStonecuttingRecipe.SPONGE_CODEC, mcMapCodec).xmap(to -> to.map(si -> si, i -> i), fr -> { @@ -48,6 +49,6 @@ public abstract class StonecutterRecipe_SerializerMixin { return Either.left(si); } return Either.right(fr); - }).codec(); + }); } } From 2d20c489d00cb373e80f8a2f3d68207d33f7c3f8 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 21:07:55 +0100 Subject: [PATCH 187/230] fix enchantment --- .../container/EnchantmentContainerMixin_Inventory.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/inventory/container/EnchantmentContainerMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/inventory/container/EnchantmentContainerMixin_Inventory.java index e58ed2f8ae0..878d5ff4611 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/inventory/container/EnchantmentContainerMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/inventory/container/EnchantmentContainerMixin_Inventory.java @@ -28,6 +28,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.inventory.EnchantmentMenu; @@ -73,7 +74,7 @@ public abstract class EnchantmentContainerMixin_Inventory { } @Inject(method = "getEnchantmentList", cancellable = true, at = @At(value = "RETURN")) - private void impl$onBuildEnchantmentList( + private void impl$onBuildEnchantmentList(final FeatureFlagSet ffs, final ItemStack stack, final int enchantSlot, final int level, final CallbackInfoReturnable> cir) { final List newList = InventoryEventFactory .callEnchantEventEnchantmentList((EnchantmentMenu) (Object) this, this.enchantmentSeed.get(), stack, enchantSlot, level, cir.getReturnValue()); From 5c5a329b99a2700f2ce53dd5186bb3a3c307ec68 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:12:23 +0100 Subject: [PATCH 188/230] fix BlockEntity loading --- .../org/spongepowered/common/block/SpongeBlockSnapshot.java | 2 +- .../common/block/entity/SpongeBlockEntityArchetype.java | 2 +- .../spongepowered/common/world/volume/VolumeStreamUtils.java | 2 +- .../common/mixin/api/minecraft/world/level/LevelMixin_API.java | 2 +- .../mixin/core/world/level/block/entity/BlockEntityMixin.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java index e845b662df3..afea0309fab 100644 --- a/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java +++ b/src/main/java/org/spongepowered/common/block/SpongeBlockSnapshot.java @@ -195,7 +195,7 @@ public boolean restore(final boolean force, final BlockChangeFlag flag) { @Nullable BlockEntity te = world.getBlockEntity(pos); if (te != null) { te.setBlockState((net.minecraft.world.level.block.state.BlockState) this.blockState); - te.load(this.compound, world.registryAccess()); + te.loadWithComponents(this.compound, world.registryAccess()); } else { // Because, some mods will "unintentionally" only obey some of the rules but not all. // In cases like this, we need to directly just say "fuck it" and deserialize from the compound directly. diff --git a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java index 7b1892a763e..22c96953c8e 100644 --- a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java +++ b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java @@ -106,7 +106,7 @@ public Optional apply(final ServerLocation location) { compound.putInt(Constants.TileEntity.Y_POS, blockpos.getY()); compound.putInt(Constants.TileEntity.Z_POS, blockpos.getZ()); tileEntity.setBlockState((net.minecraft.world.level.block.state.BlockState) currentState); - tileEntity.load(compound, minecraftWorld.registryAccess()); + tileEntity.loadWithComponents(compound, minecraftWorld.registryAccess()); return Optional.of((org.spongepowered.api.block.entity.BlockEntity) tileEntity); } diff --git a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java index 691418fb826..6df112f0e46 100644 --- a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java +++ b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java @@ -262,7 +262,7 @@ public static BiConsumer String.format( "TileEntityType[%s] creates a null TileEntity!", BlockEntityType.getKey(tile.getType())) - ).load(nbt, tile.getLevel().registryAccess()); // TODO NPE possible? + ).loadWithComponents(nbt, tile.getLevel().registryAccess()); // TODO NPE possible? if (level != null) { ((BlockEntityAccessor) cloned).accessor$level(level); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index 154c9c189c0..1224489195b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -345,7 +345,7 @@ public void addBlockEntity(final int x, final int y, final int z, final BlockEnt .orElseThrow(() -> new IllegalStateException("Failed to create Block Entity at " + this.location(Vector3i.from(x, y, z)))); // Load the data into it. - mcNewBlockEntity.load(tag, mcOriginalBlockEntity.getLevel().registryAccess()); + mcNewBlockEntity.loadWithComponents(tag, mcOriginalBlockEntity.getLevel().registryAccess()); // Finally, inform minecraft about our actions. this.shadow$setBlockEntity(mcNewBlockEntity); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java index 9298b98dafc..0241fb2ec9c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BlockEntityMixin.java @@ -85,7 +85,7 @@ public abstract class BlockEntityMixin implements BlockEntityBridge, DataCompoun } } - @Inject(method = "load", at = @At("RETURN")) + @Inject(method = "loadWithComponents", at = @At("RETURN")) private void impl$readSpongeData(final CompoundTag compound, HolderLookup.Provider $$1, final CallbackInfo ci) { // TODO If we are in Forge data is already present this.data$setCompound(compound); // For vanilla we set the incoming nbt From 49f228b9639825df6968bc0b8be05e988566a3ea Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:34:48 +0100 Subject: [PATCH 189/230] fix SpongeRandomEnchantmentListBuilder --- .../item/enchantment/SpongeRandomEnchantmentListBuilder.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java b/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java index feed30c7af7..f3be116cd2b 100644 --- a/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java +++ b/src/main/java/org/spongepowered/common/item/enchantment/SpongeRandomEnchantmentListBuilder.java @@ -35,6 +35,7 @@ import org.spongepowered.api.item.enchantment.Enchantment; import org.spongepowered.api.item.enchantment.EnchantmentType; import org.spongepowered.api.item.inventory.ItemStack; +import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.item.util.ItemStackUtil; import java.util.List; @@ -97,8 +98,8 @@ public List build() throws IllegalStateException { if (this.pool == null || this.pool.isEmpty()) { Objects.requireNonNull(this.item, "The item cannot be null"); this.randomSource.setSeed(this.seed + this.option); - enchantments = EnchantmentHelper.selectEnchantment(this.randomSource, - ItemStackUtil.toNative(this.item), this.level, this.treasure); + enchantments = EnchantmentHelper.selectEnchantment(SpongeCommon.server().getWorldData().enabledFeatures(), + this.randomSource, ItemStackUtil.toNative(this.item), this.level, this.treasure); } else { From adf1877e5289620c98f630c765b3a1fed5cdfc01 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:42:45 +0100 Subject: [PATCH 190/230] fix MobSpawnerData --- .../common/data/provider/block/entity/MobSpawnerData.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/MobSpawnerData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/MobSpawnerData.java index e1b6cf49fe6..561119d02e5 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/MobSpawnerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/MobSpawnerData.java @@ -141,14 +141,14 @@ private static void setNextEntity(final SpawnerBlockEntity entity, final Weighte compound.putString(Constants.Entity.ENTITY_TYPE_ID, key.toString()); } - ((BaseSpawnerBridge) entity.getSpawner()).bridge$setNextSpawnData(entity.getLevel(), entity.getBlockPos(), new SpawnData(compound, Optional.empty())); + ((BaseSpawnerBridge) entity.getSpawner()).bridge$setNextSpawnData(entity.getLevel(), entity.getBlockPos(), new SpawnData(compound, Optional.empty(), Optional.empty())); } private static WeightedTable getEntities(final BaseSpawner logic) { final WeightedTable possibleEntities = new WeightedTable<>(); for (final WeightedEntry.Wrapper weightedEntity : ((BaseSpawnerAccessor) logic).accessor$spawnPotentials().unwrap()) { - final CompoundTag nbt = weightedEntity.getData().entityToSpawn(); + final CompoundTag nbt = weightedEntity.data().entityToSpawn(); final String resourceLocation = nbt.getString(Constants.Entity.ENTITY_TYPE_ID); final Registry> entityTypeRegistry = SpongeCommon.vanillaRegistry(Registries.ENTITY_TYPE); @@ -180,7 +180,7 @@ private static void setEntities(final BaseSpawnerAccessor logic, final WeightedT compound.putString(Constants.Entity.ENTITY_TYPE_ID, key.toString()); } - builder.add(new SpawnData(compound, Optional.empty()), (int) entry.weight()); + builder.add(new SpawnData(compound, Optional.empty(), Optional.empty()), (int) entry.weight()); } logic.accessor$spawnPotentials(builder.build()); } From 18a0e1d1ee1e07c1ff09eaf69008bc5a5f63bfd5 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:45:20 +0100 Subject: [PATCH 191/230] fix BannerData --- .../common/data/provider/block/entity/BannerData.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java index a0432e6644c..8efdcc317bb 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BannerData.java @@ -25,6 +25,7 @@ package org.spongepowered.common.data.provider.block.entity; import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BannerBlockEntity; @@ -69,9 +70,10 @@ public static void register(final DataProviderRegistrator registrator) { // @formatter:on private static void applyBannerPatternLayers(final BannerBlockEntity h, final List v) { final DataComponentMap.Builder builder = DataComponentMap.builder(); - h.collectComponents(builder); + builder.addAll(h.collectComponents()); // TODO base color? builder.set(DataComponents.BANNER_PATTERNS, new BannerPatternLayers(v.stream().map(BannerPatternLayers.Layer.class::cast).toList())); final DataComponentMap components = builder.build(); - h.applyComponents(components);} + h.applyComponents(components, DataComponentPatch.EMPTY); + } } From 1b120d98dd42587e69e5e1bcb0425b8115db1502 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:49:22 +0100 Subject: [PATCH 192/230] fix AreaEffectCloudData --- .../common/data/provider/entity/AreaEffectCloudData.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java index ce95c05fdde..a62aab53c6a 100644 --- a/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java +++ b/src/main/java/org/spongepowered/common/data/provider/entity/AreaEffectCloudData.java @@ -47,9 +47,9 @@ public static void register(final DataProviderRegistrator registrator) { registrator .asMutable(AreaEffectCloud.class) .create(Keys.COLOR) - .get(h -> Color.ofRgb(h.getColor())) + .get(h -> Color.ofRgb(((AreaEffectCloudAccessor) h).accessor$potionContents().getColor())) .set((h, v) -> { - var contents = ((AreaEffectCloudAccessor)h).accessor$potionContents(); + var contents = ((AreaEffectCloudAccessor) h).accessor$potionContents(); h.setPotionContents(new PotionContents(contents.potion(), Optional.of(v.rgb()), contents.customEffects())); }) .create(Keys.DURATION) From 780fc86cd3968ffb47ff333e7f3066fd9133a2ec Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 20:53:23 +0100 Subject: [PATCH 193/230] fix ProjectileDispenseBehaviorMixin --- ...aviorMixin.java => ProjectileDispenseBehaviorMixin.java} | 6 +++--- src/mixins/resources/mixins.sponge.core.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) rename src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/{AbstractProjectileDispenseBehaviorMixin.java => ProjectileDispenseBehaviorMixin.java} (91%) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/AbstractProjectileDispenseBehaviorMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java similarity index 91% rename from src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/AbstractProjectileDispenseBehaviorMixin.java rename to src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java index 6165d8bde34..0ef52cdaf02 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/AbstractProjectileDispenseBehaviorMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/core/dispenser/ProjectileDispenseBehaviorMixin.java @@ -24,9 +24,9 @@ */ package org.spongepowered.common.mixin.core.core.dispenser; -import net.minecraft.core.dispenser.AbstractProjectileDispenseBehavior; import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; +import net.minecraft.core.dispenser.ProjectileDispenseBehavior; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -38,8 +38,8 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -@Mixin(AbstractProjectileDispenseBehavior.class) -public abstract class AbstractProjectileDispenseBehaviorMixin extends DefaultDispenseItemBehavior { +@Mixin(ProjectileDispenseBehavior.class) +public abstract class ProjectileDispenseBehaviorMixin extends DefaultDispenseItemBehavior { @Redirect(method = "execute", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z")) diff --git a/src/mixins/resources/mixins.sponge.core.json b/src/mixins/resources/mixins.sponge.core.json index 2b6502512a4..1a8e1043f4a 100644 --- a/src/mixins/resources/mixins.sponge.core.json +++ b/src/mixins/resources/mixins.sponge.core.json @@ -29,7 +29,7 @@ "commands.arguments.selector.EntitySelectorParserMixin", "core.MappedRegistryMixin", "core.Vec3iMixin", - "core.dispenser.AbstractProjectileDispenseBehaviorMixin", + "core.dispenser.ProjectileDispenseBehaviorMixin", "data.SpongeDataHolderMixin", "item.EmptyMapItemMixin", "item.ThrowableInaccurateItemMixin", From 86e4e6b2d9c4582e3ca2e355b1a8e2e699f6c33e Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 21:38:36 +0100 Subject: [PATCH 194/230] better exceptions for errors loading level.dat --- .../common/world/server/SpongeWorldManager.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java index 4fb8ba31908..531af9823c5 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java @@ -734,6 +734,8 @@ public void loadLevel() { this.prepareWorld(world); } catch (final IOException e) { throw new RuntimeException(String.format("Failed to create level data for world '%s'!", worldKey), e); + } catch (final Exception e) { + throw new IllegalStateException(String.format("Failed to create level data for world '%s'!", worldKey), e); } } } @@ -754,9 +756,13 @@ public void loadLevel() { private PrimaryLevelData getOrCreateLevelData(final Dynamic dynamicLevelData, final LevelStem levelStem, final String directoryName) { final PrimaryLevelData defaultLevelData = (PrimaryLevelData) this.server.getWorldData(); - @Nullable PrimaryLevelData levelData = this.loadLevelData(this.server.registryAccess(), defaultLevelData.getDataConfiguration(), dynamicLevelData); - if (levelData != null) { - return levelData; + try { + @Nullable PrimaryLevelData levelData = this.loadLevelData(this.server.registryAccess(), defaultLevelData.getDataConfiguration(), dynamicLevelData); + if (levelData != null) { + return levelData; + } + } catch (Exception e) { + throw new RuntimeException("Failed to load level data from " + directoryName, e); } if (this.server.isDemo()) { From 44ad341338f74b723f68994fa21d079aa97b117b Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 21:44:19 +0100 Subject: [PATCH 195/230] fix ServerGamePacketListenerImplMixin chat command ctx --- .../network/ServerGamePacketListenerImplMixin.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java index cba6e09a9ea..36c81596313 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java @@ -31,7 +31,6 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; -import net.minecraft.SharedConstants; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -128,9 +127,12 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack @Shadow public abstract void shadow$teleport(double x, double y, double z, float yaw, float pitch, Set relativeArguments); @Shadow protected abstract CompletableFuture> shadow$filterTextPacket(final List $$0); + @Shadow protected abstract void shadow$performUnsignedChatCommand(final String $$0); @Shadow protected abstract ParseResults shadow$parseCommand(final String $$0); // @formatter:on + @Shadow protected abstract void performUnsignedChatCommand(final String $$0); + @Nullable private ResourcePack impl$lastAcceptedPack; private int impl$ignorePackets; @@ -499,6 +501,15 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack } } + @Redirect(method = "lambda$handleChatCommand$7", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;performUnsignedChatCommand(Ljava/lang/String;)V")) + public void impl$onPerformChatCommand(final ServerGamePacketListenerImpl instance, final String $$0) { + try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { + frame.pushCause(this.player); + frame.addContext(EventContextKeys.COMMAND, $$0); + this.performUnsignedChatCommand($$0); + } + } + @Override public @Nullable ResourcePack bridge$popReceivedResourcePack(final boolean markAccepted) { final ResourcePack pack = this.impl$lastReceivedPack; From 3752e5b926b3f13be6ac0ae85945907fca862e50 Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Thu, 28 Mar 2024 21:46:18 +0100 Subject: [PATCH 196/230] fix recipe mixin --- .../network/ServerGamePacketListenerImplMixin_Vanilla.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index d24bea5696f..a9ca58b632f 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -57,7 +57,7 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo //@formatter:on @SuppressWarnings({"unchecked", "rawtypes"}) - @Redirect(method = "lambda$handlePlaceRecipe$9", + @Redirect(method = "lambda$handlePlaceRecipe$10", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) private void vanilla$onPlaceRecipe(final RecipeBookMenu recipeBookMenu, final boolean shift, final RecipeHolder recipe, final net.minecraft.server.level.ServerPlayer player) { final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext(); From fe13f0e34eb6af67a217afa6a84584cd606aa0bd Mon Sep 17 00:00:00 2001 From: Anselm Brehme Date: Sat, 4 May 2024 23:07:47 +0200 Subject: [PATCH 197/230] 1.20.6 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 4547c0ca77b..df9090fc215 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,7 +12,7 @@ mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.c mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json superClassChanges=common.superclasschange -minecraftVersion=24w13a +minecraftVersion=1.20.6 recommendedVersion=0-SNAPSHOT org.gradle.dependency.verification.console=verbose From 81efbd4ed4ab2f55dc1a888101d64918568b97d9 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sat, 4 May 2024 23:17:55 +0200 Subject: [PATCH 198/230] Bump java to 21 --- .github/workflows/check-spotless.yaml | 2 +- .github/workflows/common-integration-test.yaml | 2 +- .github/workflows/common-run-build.yaml | 2 +- .github/workflows/deploy.yaml | 2 +- README.md | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/check-spotless.yaml b/.github/workflows/check-spotless.yaml index 65bf49eb272..dd11a3d5cab 100644 --- a/.github/workflows/check-spotless.yaml +++ b/.github/workflows/check-spotless.yaml @@ -10,6 +10,6 @@ jobs: call-check: uses: SpongePowered/.github/.github/workflows/shared-check-spotless.yaml@master with: - runtime_version: 17 + runtime_version: 21 extra_gradle_params: "-PenableTestPlugins=true -PenableSpongeForge=true" secrets: inherit diff --git a/.github/workflows/common-integration-test.yaml b/.github/workflows/common-integration-test.yaml index 4a03a349e34..d337e2b0cc2 100644 --- a/.github/workflows/common-integration-test.yaml +++ b/.github/workflows/common-integration-test.yaml @@ -15,7 +15,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-22.04, windows-latest, macos-latest] - java: [17, 21] + java: [ 21 ] runs-on: "${{ matrix.os }}" steps: - name: Check out repository to use the build.gradle.kts as a hash file diff --git a/.github/workflows/common-run-build.yaml b/.github/workflows/common-run-build.yaml index da1e04568a2..d8a878da59c 100644 --- a/.github/workflows/common-run-build.yaml +++ b/.github/workflows/common-run-build.yaml @@ -16,7 +16,7 @@ jobs: id: setup uses: SpongePowered/.github/.github/actions/setup-java-env@master with: - runtime_version: 17 + runtime_version: 21 publishing_branch_regex: 'api-\d+' - name: setup / cache minecraft dependencies uses: "actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9" # v4.0.2 diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 13e61457a27..c4a65192b77 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -27,7 +27,7 @@ jobs: id: setup uses: SpongePowered/.github/.github/actions/setup-java-env@master with: - runtime_version: 17 + runtime_version: 21 - name: setup / minecraft cache uses: "actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9" # v4.0.2 with: diff --git a/README.md b/README.md index eba5d6be62b..dc2904f98d4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Sponge ![Java CI with Gradle](https://github.com/SpongePowered/Sponge/workflows/Java%20CI%20with%20Gradle/badge.svg?branch=api-8&event=push) +Sponge ![Java CI with Gradle](https://github.com/SpongePowered/Sponge/workflows/Java%20CI%20with%20Gradle/badge.svg?branch=api-11&event=push) ============= The SpongeAPI implementation targeting vanilla Minecraft and 3rd party platforms. It is licensed under the [MIT License]. @@ -25,7 +25,7 @@ The SpongeAPI implementation targeting vanilla Minecraft and 3rd party platforms ## Prerequisites -* [Java] 8 +* [Java] 21 ## Clone The following steps will ensure your project is cloned properly. From 51d7bb19ad3f36abc328bcb2185c2ad4dc5262e6 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sat, 4 May 2024 23:22:56 +0200 Subject: [PATCH 199/230] Update verification metadata --- gradle/verification-metadata.xml | 295 ++++++++++++++++++++++++++++++- 1 file changed, 294 insertions(+), 1 deletion(-) diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 4dbf4b26fcc..f020be7afd5 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -8,9 +8,9 @@ - + @@ -136,6 +136,11 @@ + + + + + @@ -272,6 +277,14 @@ + + + + + + + + @@ -280,6 +293,11 @@ + + + + + @@ -797,6 +815,14 @@ + + + + + + + + @@ -821,6 +847,14 @@ + + + + + + + + @@ -829,6 +863,14 @@ + + + + + + + + @@ -999,6 +1041,14 @@ + + + + + + + + @@ -1149,6 +1199,11 @@ + + + + + @@ -1265,11 +1320,21 @@ + + + + + + + + + + @@ -1365,6 +1430,14 @@ + + + + + + + + @@ -1373,6 +1446,14 @@ + + + + + + + + @@ -1827,6 +1908,14 @@ + + + + + + + + @@ -1835,6 +1924,14 @@ + + + + + + + + @@ -1888,6 +1985,21 @@ + + + + + + + + + + + + + + + @@ -2041,6 +2153,11 @@ + + + + + @@ -2066,6 +2183,11 @@ + + + + + @@ -2090,6 +2212,14 @@ + + + + + + + + @@ -2105,6 +2235,11 @@ + + + + + @@ -2126,6 +2261,14 @@ + + + + + + + + @@ -2152,6 +2295,14 @@ + + + + + + + + @@ -2361,6 +2512,11 @@ + + + + + @@ -2447,6 +2603,11 @@ + + + + + @@ -2468,6 +2629,11 @@ + + + + + @@ -2567,6 +2733,14 @@ + + + + + + + + @@ -2947,6 +3121,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -2967,6 +3163,17 @@ + + + + + + + + + + + @@ -2987,6 +3194,17 @@ + + + + + + + + + + + @@ -3007,6 +3225,17 @@ + + + + + + + + + + + @@ -3027,6 +3256,17 @@ + + + + + + + + + + + @@ -3047,6 +3287,17 @@ + + + + + + + + + + + @@ -3067,6 +3318,25 @@ + + + + + + + + + + + + + + + + + + + @@ -3083,6 +3353,11 @@ + + + + + @@ -3336,11 +3611,24 @@ + + + + + + + + + + + + + @@ -3366,6 +3654,11 @@ + + + + + From 73d86cfc76db0abe1498db73ca21a5bf1f610f2d Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sat, 4 May 2024 23:33:00 +0200 Subject: [PATCH 200/230] Rename EnchantmentTableBlockEntityAccessor to EnchantingTableBlockEntityAccessor --- ...ccessor.java => EnchantingTableBlockEntityAccessor.java} | 6 +++--- src/accessors/resources/mixins.sponge.accessors.json | 2 +- .../block/entity/EnchantmentTableBlockEntityMixin.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) rename src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/{EnchantmentTableBlockEntityAccessor.java => EnchantingTableBlockEntityAccessor.java} (90%) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantmentTableBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantingTableBlockEntityAccessor.java similarity index 90% rename from src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantmentTableBlockEntityAccessor.java rename to src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantingTableBlockEntityAccessor.java index 74a8c27741d..04c3886fd2d 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantmentTableBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/EnchantingTableBlockEntityAccessor.java @@ -25,13 +25,13 @@ package org.spongepowered.common.accessor.world.level.block.entity; import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.entity.EnchantmentTableBlockEntity; +import net.minecraft.world.level.block.entity.EnchantingTableBlockEntity; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; -@Mixin(EnchantmentTableBlockEntity.class) -public interface EnchantmentTableBlockEntityAccessor { +@Mixin(EnchantingTableBlockEntity.class) +public interface EnchantingTableBlockEntityAccessor { @Invoker("setCustomName") void invoker$setCustomName(final @Nullable Component customName); diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index 6351c2c9a61..a7e6436d199 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -168,7 +168,7 @@ "world.level.block.entity.BlockEntityAccessor", "world.level.block.entity.BrewingStandBlockEntityAccessor", "world.level.block.entity.ConduitBlockEntityAccessor", - "world.level.block.entity.EnchantmentTableBlockEntityAccessor", + "world.level.block.entity.EnchantingTableBlockEntityAccessor", "world.level.block.entity.HopperBlockEntityAccessor", "world.level.block.entity.LecternBlockEntity_Accessor", "world.level.block.entity.SpawnerBlockEntityAccessor", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java index e49a348d11c..d1b99741f76 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java @@ -27,7 +27,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.entity.EnchantmentTableBlockEntity; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.common.accessor.world.level.block.entity.EnchantmentTableBlockEntityAccessor; +import org.spongepowered.common.accessor.world.level.block.entity.EnchantingTableBlockEntityAccessor; import org.spongepowered.common.bridge.CustomNameableBridge; @Mixin(EnchantmentTableBlockEntity.class) @@ -35,6 +35,6 @@ public abstract class EnchantmentTableBlockEntityMixin implements CustomNameable @Override public void bridge$setCustomDisplayName(final Component customName) { - ((EnchantmentTableBlockEntityAccessor) this).invoker$setCustomName(customName); + ((EnchantingTableBlockEntityAccessor) this).invoker$setCustomName(customName); } } From 7c805204f6d0956d86fcda279907a1e5ad9e7e94 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 01:08:12 +0200 Subject: [PATCH 201/230] A lot of fixes and TODO later, the server starts --- .../enchantment/ItemEnchantmentsAccessor.java | 5 +- .../BrewingStandBlockEntityAccessor.java | 3 +- .../block/entity/BrewingStandData.java | 25 +-- .../provider/item/stack/ItemStackData.java | 2 +- .../effect/particle/SpongeParticleHelper.java | 182 +++++++++--------- .../SpongeMapDecorationBuilder.java | 19 +- .../registry/loader/SpongeRegistryLoader.java | 2 - .../common/util/ParticleOptionUtil.java | 17 +- .../minecraft/map/MapDecorationMixin_API.java | 6 +- .../projectile/WindChargeMixin_API.java | 2 +- .../item/crafting/RecipeManagerMixin_API.java | 14 +- .../BrewingStandBlockEntityMixin_API.java | 5 +- .../EnchantmentTableBlockEntityMixin_API.java | 4 +- ...zableContainerBlockEntityMixin_BugFix.java | 3 +- .../core/server/level/ChunkHolderMixin.java | 6 +- .../AbstractHurtingProjectileMixin.java | 3 +- .../entity/projectile/FishingHookMixin.java | 5 +- .../projectile/ThrowableProjectileMixin.java | 11 +- .../entity/BrewingStandBlockEntityMixin.java | 5 +- .../EnchantmentTableBlockEntityMixin.java | 4 +- .../chunk/storage/EntityStorageMixin.java | 4 +- ...GamePacketListenerImplMixin_Inventory.java | 4 +- src/mixins/resources/mixins.sponge.core.json | 2 - ...erGamePacketListenerImplMixin_Vanilla.java | 24 ++- 24 files changed, 185 insertions(+), 172 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java index ed4bae5eb8d..bef861f4181 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java @@ -25,6 +25,7 @@ package org.spongepowered.common.accessor.world.item.enchantment; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.minecraft.core.Holder; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.ItemEnchantments; @@ -38,9 +39,9 @@ public interface ItemEnchantmentsAccessor { @Accessor("showInTooltip") boolean accessor$showInTooltip(); - @Accessor("enchantments") Object2IntLinkedOpenHashMap> accessor$enchantments(); + @Accessor("enchantments") Object2IntOpenHashMap> accessor$enchantments(); - @Invoker("") static ItemEnchantments invoker$new(Object2IntLinkedOpenHashMap> $$0, boolean $$1) { + @Invoker("") static ItemEnchantments invoker$new(Object2IntOpenHashMap> $$0, boolean $$1) { throw new UntransformedInvokerError(); } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java index 60b629262e1..bc1aa7e629c 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java @@ -26,6 +26,7 @@ import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @@ -45,7 +46,7 @@ public interface BrewingStandBlockEntityAccessor { @Accessor("items") NonNullList accessor$items(); - @Invoker("isBrewable") static boolean invoker$isBrewable(NonNullList var0) { + @Invoker("isBrewable") static boolean invoker$isBrewable(PotionBrewing $$0, NonNullList $$1) { throw new UntransformedInvokerError(); } diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java index ff9cc0fbbc8..3d01c64ca40 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java @@ -46,18 +46,19 @@ public static void register(final DataProviderRegistrator registrator) { } h.accessor$fuel(v); return true; - }) - .create(Keys.REMAINING_BREW_TIME) - .get(h -> BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items()) ? new SpongeTicks(h.accessor$brewTime()) : null) - .setAnd((h, v) -> { - if (v.isInfinite()) { - return false; - } - if (BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items())) { - h.accessor$brewTime(SpongeTicks.toSaturatedIntOrInfinite(v)); - return true; - } - return false; + // TODO fix me +// }) +// .create(Keys.REMAINING_BREW_TIME) +// .get(h -> BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items()) ? new SpongeTicks(h.accessor$brewTime()) : null) +// .setAnd((h, v) -> { +// if (v.isInfinite()) { +// return false; +// } +// if (BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items())) { +// h.accessor$brewTime(SpongeTicks.toSaturatedIntOrInfinite(v)); +// return true; +// } +// return false; }); } // @formatter:on diff --git a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java index 185de9fa512..9f9611c20ed 100644 --- a/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java +++ b/src/main/java/org/spongepowered/common/data/provider/item/stack/ItemStackData.java @@ -176,7 +176,7 @@ public static void register(final DataProviderRegistrator registrator) { final var food = h.get(DataComponents.FOOD); if (food != null) { // Translate's Minecraft's weird internal value to the actual saturation value - return food.saturationModifier() * food.nutrition() * 2.0; + return (double)food.saturation(); } return null; }) diff --git a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java index 8b70b638167..7b1b493f170 100644 --- a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java +++ b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java @@ -112,61 +112,62 @@ private static CachedParticlePacket getNamedPacket(final ParticleEffect effect, // The only way we can see what options are supported for a particular named particle // is to compare the internal type's deserializer to some static deserializer fields. // If only mojang had some type akin to our ParticleEffect... - if (internalType.getDeserializer() == BlockParticleOption.DESERIALIZER) { - // This particle type supports a block state option. - final BlockState state = effect.optionOrDefault(ParticleOptions.BLOCK_STATE).get(); - final BlockParticleOption particleData = new BlockParticleOption( - (net.minecraft.core.particles.ParticleType) internalType, - (net.minecraft.world.level.block.state.BlockState) state); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { - final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); - final Color toColor = effect.optionOrDefault(ParticleOptions.TO_COLOR).get(); - final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); - final DustColorTransitionOptions particleData = new DustColorTransitionOptions( - new org.joml.Vector3f( - (float) color.red() / 255, - (float) color.green() / 255, - (float) color.blue() / 255 - ), - new org.joml.Vector3f( - (float) toColor.red() / 255, - (float) toColor.green() / 255, - (float) toColor.blue() / 255 - ), - (float) scale); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == DustParticleOptions.DESERIALIZER) { - // This particle type supports a color option. - final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); - final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); - final DustParticleOptions particleData = new DustParticleOptions(new org.joml.Vector3f( - (float) color.red() / 255, - (float) color.green() / 255, - (float) color.blue() / 255), - (float) scale); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == ItemParticleOption.DESERIALIZER) { - // This particle type supports an item option. - final ItemStackSnapshot snapshot = effect.optionOrDefault(ParticleOptions.ITEM_STACK_SNAPSHOT).get(); - final ItemParticleOption particleData = new ItemParticleOption( - (net.minecraft.core.particles.ParticleType) internalType, - (net.minecraft.world.item.ItemStack) (Object) snapshot.createStack()); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { - final double roll = effect.optionOrDefault(ParticleOptions.ROLL).get(); - final SculkChargeParticleOptions particleData = new SculkChargeParticleOptions((float) roll); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == ShriekParticleOption.DESERIALIZER) { - final int delay = effect.optionOrDefault(ParticleOptions.DELAY).get(); - final ShriekParticleOption particleData = new ShriekParticleOption(delay); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } else if (internalType.getDeserializer() == VibrationParticleOption.DESERIALIZER) { - final Ticks delay = effect.optionOrDefault(ParticleOptions.TRAVEL_TIME).get(); - // TODO add position source - final VibrationParticleOption particleData = new VibrationParticleOption(new BlockPositionSource(BlockPos.ZERO), (int) delay.ticks()); - return new NamedCachedPacket(particleData, offset, quantity, velocity); - } + // TODO fix me +// if (internalType.getDeserializer() == BlockParticleOption.DESERIALIZER) { +// // This particle type supports a block state option. +// final BlockState state = effect.optionOrDefault(ParticleOptions.BLOCK_STATE).get(); +// final BlockParticleOption particleData = new BlockParticleOption( +// (net.minecraft.core.particles.ParticleType) internalType, +// (net.minecraft.world.level.block.state.BlockState) state); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { +// final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); +// final Color toColor = effect.optionOrDefault(ParticleOptions.TO_COLOR).get(); +// final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); +// final DustColorTransitionOptions particleData = new DustColorTransitionOptions( +// new org.joml.Vector3f( +// (float) color.red() / 255, +// (float) color.green() / 255, +// (float) color.blue() / 255 +// ), +// new org.joml.Vector3f( +// (float) toColor.red() / 255, +// (float) toColor.green() / 255, +// (float) toColor.blue() / 255 +// ), +// (float) scale); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == DustParticleOptions.DESERIALIZER) { +// // This particle type supports a color option. +// final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); +// final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); +// final DustParticleOptions particleData = new DustParticleOptions(new org.joml.Vector3f( +// (float) color.red() / 255, +// (float) color.green() / 255, +// (float) color.blue() / 255), +// (float) scale); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == ItemParticleOption.DESERIALIZER) { +// // This particle type supports an item option. +// final ItemStackSnapshot snapshot = effect.optionOrDefault(ParticleOptions.ITEM_STACK_SNAPSHOT).get(); +// final ItemParticleOption particleData = new ItemParticleOption( +// (net.minecraft.core.particles.ParticleType) internalType, +// (net.minecraft.world.item.ItemStack) (Object) snapshot.createStack()); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { +// final double roll = effect.optionOrDefault(ParticleOptions.ROLL).get(); +// final SculkChargeParticleOptions particleData = new SculkChargeParticleOptions((float) roll); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == ShriekParticleOption.DESERIALIZER) { +// final int delay = effect.optionOrDefault(ParticleOptions.DELAY).get(); +// final ShriekParticleOption particleData = new ShriekParticleOption(delay); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } else if (internalType.getDeserializer() == VibrationParticleOption.DESERIALIZER) { +// final Ticks delay = effect.optionOrDefault(ParticleOptions.TRAVEL_TIME).get(); +// // TODO add position source +// final VibrationParticleOption particleData = new VibrationParticleOption(new BlockPositionSource(BlockPos.ZERO), (int) delay.ticks()); +// return new NamedCachedPacket(particleData, offset, quantity, velocity); +// } // Otherwise, we don't really know how to get a valid IParticleData. Sorry mods! return EmptyCachedPacket.INSTANCE; @@ -225,41 +226,42 @@ public static ParticleEffect spongeParticleOptions(final net.minecraft.core.part return new SpongeParticleEffect((ParticleType) type, Collections.emptyMap()); } - if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { - final BlockParticleOption particleData = (BlockParticleOption) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getState())); - } else if (type.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { - final DustColorTransitionOptions particleData = (DustColorTransitionOptions) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of( - ParticleOptions.COLOR.get(), Color.of( - Vector3f.from(particleData.getFromColor().x, particleData.getFromColor().y, particleData.getFromColor().z).mul(255)), - ParticleOptions.TO_COLOR.get(), Color.of( - Vector3f.from(particleData.getToColor().x, particleData.getToColor().y, particleData.getToColor().z).mul(255)), - ParticleOptions.SCALE.get(), particleData.getScale() - )); - } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { - // This particle type supports a color option. - final DustParticleOptions particleData = (DustParticleOptions) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of( - ParticleOptions.COLOR.get(), Color.of( - Vector3f.from(particleData.getColor().x, particleData.getColor().y, particleData.getColor().z).mul(255)), - ParticleOptions.SCALE.get(), particleData.getScale() - )); - } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { - // This particle type supports an item option. - final ItemParticleOption particleData = (ItemParticleOption) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getItem().copy())); - } else if (type.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { - final SculkChargeParticleOptions particleData = (SculkChargeParticleOptions) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.ROLL.get(), particleData.roll())); - } else if (type.getDeserializer() == ShriekParticleOption.DESERIALIZER) { - final ShriekParticleOption particleData = (ShriekParticleOption) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.DELAY.get(), particleData.getDelay())); - } else if (type.getDeserializer() == VibrationParticleOption.DESERIALIZER) { - // TODO add position source - final VibrationParticleOption particleData = (VibrationParticleOption) effect; - return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.TRAVEL_TIME.get(), Ticks.of(particleData.getArrivalInTicks()))); - } + // TODO fix me +// if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { +// final BlockParticleOption particleData = (BlockParticleOption) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getState())); +// } else if (type.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { +// final DustColorTransitionOptions particleData = (DustColorTransitionOptions) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of( +// ParticleOptions.COLOR.get(), Color.of( +// Vector3f.from(particleData.getFromColor().x, particleData.getFromColor().y, particleData.getFromColor().z).mul(255)), +// ParticleOptions.TO_COLOR.get(), Color.of( +// Vector3f.from(particleData.getToColor().x, particleData.getToColor().y, particleData.getToColor().z).mul(255)), +// ParticleOptions.SCALE.get(), particleData.getScale() +// )); +// } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { +// // This particle type supports a color option. +// final DustParticleOptions particleData = (DustParticleOptions) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of( +// ParticleOptions.COLOR.get(), Color.of( +// Vector3f.from(particleData.getColor().x, particleData.getColor().y, particleData.getColor().z).mul(255)), +// ParticleOptions.SCALE.get(), particleData.getScale() +// )); +// } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { +// // This particle type supports an item option. +// final ItemParticleOption particleData = (ItemParticleOption) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getItem().copy())); +// } else if (type.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { +// final SculkChargeParticleOptions particleData = (SculkChargeParticleOptions) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.ROLL.get(), particleData.roll())); +// } else if (type.getDeserializer() == ShriekParticleOption.DESERIALIZER) { +// final ShriekParticleOption particleData = (ShriekParticleOption) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.DELAY.get(), particleData.getDelay())); +// } else if (type.getDeserializer() == VibrationParticleOption.DESERIALIZER) { +// // TODO add position source +// final VibrationParticleOption particleData = (VibrationParticleOption) effect; +// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.TRAVEL_TIME.get(), Ticks.of(particleData.getArrivalInTicks()))); +// } return new SpongeParticleEffect((ParticleType) type, Collections.emptyMap()); } diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index e2a7f6fde0e..70ccc4b60d7 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -132,8 +132,9 @@ public MapDecoration.Builder fromContainer(final DataView container) { if (mcType == null) { throw new IllegalStateException("Missing a MapDecorationType, could not find one for Minecraft's MapDecoration.Type: " + type); } - final MapDecorationType mapDecorationType = SpongeMapDecorationType.toSpongeType(BuiltInRegistries.MAP_DECORATION_TYPE.wrapAsHolder(mcType)).get(); - this.type(mapDecorationType); + // TODO fix me + //final MapDecorationType mapDecorationType = SpongeMapDecorationType.toSpongeType(BuiltInRegistries.MAP_DECORATION_TYPE.wrapAsHolder(mcType)).get(); + //this.type(mapDecorationType); final int intRot = MapUtil.normalizeDecorationOrientation(rot); this.rotation(MapUtil.getMapRotById(intRot)); @@ -166,11 +167,13 @@ private byte getByteFromContainer(final DataView container, final DataQuery quer @Override public MapDecoration build() throws IllegalStateException { Objects.requireNonNull(this.type, "Type has not been set"); - final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( - Holder.direct(((SpongeMapDecorationType) this.type).getType()), - (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), - Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); - ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent - return decoration; + // TODO fix me + return null; +// final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( +// Holder.direct(((SpongeMapDecorationType) this.type).getType()), +// (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), +// Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); +// ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent +// return decoration; } } diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index 7cba6b12e9e..fc95fd2c8ab 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -159,8 +159,6 @@ import org.spongepowered.common.inventory.query.type.UnionQuery; import org.spongepowered.common.map.color.SpongeMapColorType; import org.spongepowered.common.map.color.SpongeMapShade; -import org.spongepowered.common.map.decoration.SpongeMapDecorationBannerType; -import org.spongepowered.common.map.decoration.SpongeMapDecorationType; import org.spongepowered.common.map.decoration.orientation.SpongeMapDecorationOrientation; import org.spongepowered.common.registry.RegistryLoader; import org.spongepowered.common.util.SpongeOrientation; diff --git a/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java b/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java index 2ac0467dfc5..b3fdd092987 100644 --- a/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java +++ b/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java @@ -50,14 +50,15 @@ public static ImmutableMap, Object> generateDefaultsForNamed(P options.put(ParticleOptions.OFFSET.get(), Vector3d.ZERO); options.put(ParticleOptions.QUANTITY.get(), 1); - if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { - options.put(ParticleOptions.BLOCK_STATE.get(), BlockTypes.AIR.get().defaultState()); - } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { - options.put(ParticleOptions.ITEM_STACK_SNAPSHOT.get(), ItemStackSnapshot.empty()); - } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { - options.put(ParticleOptions.COLOR.get(), Color.RED); - options.put(ParticleOptions.SCALE.get(), 1.0d); - } + // TODO fix me +// if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { +// options.put(ParticleOptions.BLOCK_STATE.get(), BlockTypes.AIR.get().defaultState()); +// } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { +// options.put(ParticleOptions.ITEM_STACK_SNAPSHOT.get(), ItemStackSnapshot.empty()); +// } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { +// options.put(ParticleOptions.COLOR.get(), Color.RED); +// options.put(ParticleOptions.SCALE.get(), 1.0d); +// } return ImmutableMap.copyOf(options); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index 63236f28e8e..c1bc8f94d91 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -37,7 +37,6 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.world.storage.MapDecorationBridge; -import org.spongepowered.common.map.decoration.SpongeMapDecorationType; import org.spongepowered.common.map.decoration.orientation.SpongeMapDecorationOrientation; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.MapUtil; @@ -60,8 +59,9 @@ public abstract class MapDecorationMixin_API implements org.spongepowered.api.ma @Override public MapDecorationType type() { - return SpongeMapDecorationType.toSpongeType(this.type) - .orElseThrow(() -> new IllegalStateException("Tried to get MapDecoration type but it didn't exist in Sponge's registries! Have MC Decoration types been missed?")); + //TODO fixme + return null; + //return SpongeMapDecorationType.toSpongeType(this.type).orElseThrow(() -> new IllegalStateException("Tried to get MapDecoration type but it didn't exist in Sponge's registries! Have MC Decoration types been missed?")); } @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WindChargeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WindChargeMixin_API.java index e24c95c0aa2..f9ec51725bf 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WindChargeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/WindChargeMixin_API.java @@ -27,6 +27,6 @@ import org.spongepowered.api.entity.projectile.WindCharge; import org.spongepowered.asm.mixin.Mixin; -@Mixin(net.minecraft.world.entity.projectile.WindCharge.class) +@Mixin(net.minecraft.world.entity.projectile.windcharge.WindCharge.class) public abstract class WindChargeMixin_API extends AbstractHurtingProjectileMixin_API implements WindCharge { } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java index 5d2020ddcda..f3d18b7b7b6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java @@ -63,11 +63,10 @@ public abstract class RecipeManagerMixin_API implements RecipeManager { // @formatter:off @Shadow public abstract Optional> shadow$byKey(ResourceLocation recipeId); - @Shadow protected abstract > Map> shadow$byType(net.minecraft.world.item.crafting.RecipeType recipeTypeIn); + @Shadow protected abstract > Collection> shadow$byType(net.minecraft.world.item.crafting.RecipeType recipeTypeIn); @Shadow public abstract Collection> shadow$getRecipes(); @Shadow public abstract > Optional shadow$getRecipeFor(net.minecraft.world.item.crafting.RecipeType recipeTypeIn, C inventoryIn, net.minecraft.world.level.Level worldIn); - @Shadow private Map, Map>> recipes; // @formatter:on @Override @@ -86,7 +85,7 @@ public Collection all() { @SuppressWarnings(value = {"unchecked", "rawtypes"}) public Collection allOfType(final RecipeType type) { Objects.requireNonNull(type); - return this.shadow$byType((net.minecraft.world.item.crafting.RecipeType)type).values(); + return this.shadow$byType((net.minecraft.world.item.crafting.RecipeType)type); } @Override @@ -149,8 +148,9 @@ public Optional findCookingRecipe(final RecipeType< return this.shadow$getRecipeFor((net.minecraft.world.item.crafting.RecipeType) type, fakeFurnace, null); } - @Redirect(method = "apply", at = @At(value = "INVOKE", remap = false, target = "Ljava/util/Map;size()I")) - public int impl$getActualRecipeCount(final Map, ImmutableMap.Builder>> map) { - return this.recipes.values().stream().mapToInt(Map::size).sum(); - } + // TODO fix me +// @Redirect(method = "apply", at = @At(value = "INVOKE", remap = false, target = "Ljava/util/Map;size()I")) +// public int impl$getActualRecipeCount(final Map, ImmutableMap.Builder>> map) { +// return this.recipes.values().stream().mapToInt(Map::size).sum(); +// } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BrewingStandBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BrewingStandBlockEntityMixin_API.java index ccecabb41e1..7b6925b19e3 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BrewingStandBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BrewingStandBlockEntityMixin_API.java @@ -27,6 +27,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; import org.spongepowered.api.block.entity.carrier.BrewingStand; @@ -43,14 +44,14 @@ public abstract class BrewingStandBlockEntityMixin_API extends BaseContainerBloc @Shadow private NonNullList items; @Shadow private static void shadow$doBrew(final Level param0, final BlockPos param1, final NonNullList param2) {}; - @Shadow private static boolean shadow$isBrewable(final NonNullList param0) { + @Shadow private static boolean shadow$isBrewable(PotionBrewing $$0, NonNullList $$1) { return false; } // @formatter:on @Override public boolean brew() { - if (BrewingStandBlockEntityMixin_API.shadow$isBrewable(this.items)) { + if (BrewingStandBlockEntityMixin_API.shadow$isBrewable(this.level.potionBrewing(), this.items)) { BrewingStandBlockEntityMixin_API.shadow$doBrew(this.level, this.shadow$getBlockPos(), this.items); return true; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/EnchantmentTableBlockEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/EnchantmentTableBlockEntityMixin_API.java index 6fdd63c996a..910f5142400 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/EnchantmentTableBlockEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/EnchantmentTableBlockEntityMixin_API.java @@ -25,7 +25,7 @@ package org.spongepowered.common.mixin.api.minecraft.world.level.block.entity; import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.entity.EnchantmentTableBlockEntity; +import net.minecraft.world.level.block.entity.EnchantingTableBlockEntity; import org.spongepowered.api.block.entity.EnchantmentTable; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.value.Value; @@ -35,7 +35,7 @@ import java.util.Set; -@Mixin(EnchantmentTableBlockEntity.class) +@Mixin(EnchantingTableBlockEntity.class) public abstract class EnchantmentTableBlockEntityMixin_API extends BlockEntityMixin_API implements EnchantmentTable { // @formatter:off diff --git a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java b/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java index f408882cbf0..08213a3a2a1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java +++ b/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java @@ -41,7 +41,8 @@ public abstract class RandomizableContainerBlockEntityMixin_BugFix { protected ResourceLocation lootTable; // Minecraft 1.19.4 - Fixes https://bugs.mojang.com/browse/MC-136917 - @Inject(method = "clearContent", at = @At("TAIL")) + // TODO fix me + //@Inject(method = "clearContent", at = @At("TAIL")) private void impl$clearContent(final CallbackInfo ci) { this.lootTable = null; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java index 78130f5629f..27e1e7c81cf 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkHolderMixin.java @@ -56,7 +56,7 @@ abstract class ChunkHolderMixin { // @formatter:off - @Shadow public abstract CompletableFuture> shadow$getEntityTickingChunkFuture(); + @Shadow public abstract CompletableFuture> shadow$getEntityTickingChunkFuture(); // @formatter:on @Inject( @@ -83,10 +83,10 @@ abstract class ChunkHolderMixin { } } - @Inject(method = "lambda$scheduleFullChunkPromotion$7", at = @At("TAIL")) + @Inject(method = "lambda$scheduleFullChunkPromotion$5", at = @At("TAIL")) private void impl$onScheduleFullChunkPromotion(final ChunkMap $$0x, final FullChunkStatus $$1x, final CallbackInfo ci) { if ($$1x == FullChunkStatus.ENTITY_TICKING && ShouldFire.CHUNK_EVENT_LOAD) { - this.shadow$getEntityTickingChunkFuture().getNow(ChunkHolder.UNLOADED_LEVEL_CHUNK).ifLeft(chunk -> { + this.shadow$getEntityTickingChunkFuture().getNow(ChunkHolder.UNLOADED_LEVEL_CHUNK).ifSuccess(chunk -> { final Vector3i chunkPos = VecHelper.toVector3i(chunk.getPos()); final ChunkEvent.Load event = SpongeEventFactory.createChunkEventLoad(PhaseTracker.getInstance().currentCause(), (WorldChunk) chunk, chunkPos, (ResourceKey) (Object) chunk.getLevel().dimension().location()); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java index 098e65a34e8..13c663f0fdc 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java @@ -36,7 +36,8 @@ @Mixin(AbstractHurtingProjectile.class) public abstract class AbstractHurtingProjectileMixin extends ProjectileMixin { - @Redirect(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/AbstractHurtingProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V")) + //TODO fix me + //@Redirect(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/AbstractHurtingProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V")) private void impl$callCollideImpactEvent(AbstractHurtingProjectile projectile, HitResult result) { if (result.getType() == HitResult.Type.MISS || ((LevelBridge) this.shadow$level()).bridge$isFake()) { this.shadow$onHit(result); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java index b8226173836..4cb9cd8344a 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java @@ -179,8 +179,9 @@ public int retrieve(final ItemStack stack) { } } - @Inject(method = "checkCollision", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/FishingHook;onHit(Lnet/minecraft/world/phys/HitResult;)V")) + //TODO fix me +// @Inject(method = "checkCollision", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, +// at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/FishingHook;onHit(Lnet/minecraft/world/phys/HitResult;)V")) private void impl$callCollideImpactEvent(final CallbackInfo ci, final HitResult hitResult) { if (hitResult.getType() == HitResult.Type.MISS || ((LevelBridge) this.shadow$level()).bridge$isFake()) { return; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java index b9a701249e7..93e20ab21a6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java @@ -42,11 +42,12 @@ @Mixin(ThrowableProjectile.class) public abstract class ThrowableProjectileMixin extends ProjectileMixin { - @Redirect(method = "tick()V", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/entity/projectile/ThrowableProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V" - ) - ) + // TODO fixme +// @Redirect(method = "tick()V", +// at = @At(value = "INVOKE", +// target = "Lnet/minecraft/world/entity/projectile/ThrowableProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V" +// ) +// ) private void impl$handleProjectileImpact(final ThrowableProjectile projectile, final HitResult movingObjectPosition) { if (((LevelBridge) this.shadow$level()).bridge$isFake() || movingObjectPosition.getType() == HitResult.Type.MISS) { this.shadow$onHit(movingObjectPosition); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BrewingStandBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BrewingStandBlockEntityMixin.java index bed642f5757..513ad0cc302 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BrewingStandBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BrewingStandBlockEntityMixin.java @@ -64,9 +64,8 @@ public class BrewingStandBlockEntityMixin { @Inject(method = "serverTick", locals = LocalCapture.CAPTURE_FAILEXCEPTION, - slice = @Slice(to = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BrewingStandBlockEntity;isBrewable(Lnet/minecraft/core/NonNullList;)Z")), - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BrewingStandBlockEntity;" + - "setChanged(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) + slice = @Slice(to = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BrewingStandBlockEntity;isBrewable(Lnet/minecraft/world/item/alchemy/PotionBrewing;Lnet/minecraft/core/NonNullList;)Z")), + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BrewingStandBlockEntity;setChanged(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;)V")) private static void impl$onConsumeFuel(final Level param0, final BlockPos param1, final BlockState param2, final BrewingStandBlockEntity param3, final CallbackInfo ci, final ItemStack fuelStack) { final Cause currentCause = Sponge.server().causeStackManager().currentCause(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java index d1b99741f76..7835599af0d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/EnchantmentTableBlockEntityMixin.java @@ -25,12 +25,12 @@ package org.spongepowered.common.mixin.core.world.level.block.entity; import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.entity.EnchantmentTableBlockEntity; +import net.minecraft.world.level.block.entity.EnchantingTableBlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.accessor.world.level.block.entity.EnchantingTableBlockEntityAccessor; import org.spongepowered.common.bridge.CustomNameableBridge; -@Mixin(EnchantmentTableBlockEntity.class) +@Mixin(EnchantingTableBlockEntity.class) public abstract class EnchantmentTableBlockEntityMixin implements CustomNameableBridge { @Override diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java index 7e95447bd35..bf600f72072 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java @@ -59,13 +59,13 @@ public abstract class EntityStorageMixin { // @formatter:off - @Shadow @Final private IOWorker worker; @Shadow @Final private ServerLevel level; // @formatter:on @Inject(method = "", at = @At("RETURN")) private void impl$setIOWorkerDimension(final CallbackInfo ci) { - ((IOWorkerBridge) this.worker).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); + // TODO fix me + //((IOWorkerBridge) this.worker).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); } @Inject(method = "lambda$loadEntities$0", at = @At("RETURN"), cancellable = true) diff --git a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/server/network/ServerGamePacketListenerImplMixin_Inventory.java b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/server/network/ServerGamePacketListenerImplMixin_Inventory.java index a129256c8ec..c95c646d4f6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/inventory/event/server/network/ServerGamePacketListenerImplMixin_Inventory.java +++ b/src/mixins/java/org/spongepowered/common/mixin/inventory/event/server/network/ServerGamePacketListenerImplMixin_Inventory.java @@ -68,10 +68,10 @@ public class ServerGamePacketListenerImplMixin_Inventory { private void impl$onBroadcastCreativeActionResult(final InventoryMenu inventoryMenu, final ServerboundSetCreativeModeSlotPacket packetIn) { final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext(); final TransactionalCaptureSupplier transactor = context.getTransactor(); - final ItemStack itemstack = packetIn.getItem(); + final ItemStack itemstack = packetIn.itemStack(); // TODO handle vanilla sending a bunch of creative events (previously ignoring events within 100ms) - try (final EffectTransactor ignored = transactor.logCreativeClickContainer(packetIn.getSlotNum(), ItemStackUtil.snapshotOf(itemstack), this.player)) { + try (final EffectTransactor ignored = transactor.logCreativeClickContainer(packetIn.slotNum(), ItemStackUtil.snapshotOf(itemstack), this.player)) { } inventoryMenu.broadcastChanges(); } diff --git a/src/mixins/resources/mixins.sponge.core.json b/src/mixins/resources/mixins.sponge.core.json index 1a8e1043f4a..fa4d3f0fa74 100644 --- a/src/mixins/resources/mixins.sponge.core.json +++ b/src/mixins/resources/mixins.sponge.core.json @@ -266,8 +266,6 @@ ], "client": [ "client.MinecraftMixin", - "client.gui.screens.worldselection.CreateWorldScreenMixin", - "client.gui.screens.worldselection.WorldOpenFlowsMixin", "client.multiplayer.ClientHandshakePacketListenerImplMixin", "client.multiplayer.ClientLevelMixin", "client.multiplayer.ClientPacketListenerMixin", diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index a9ca58b632f..30c2a85e019 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -47,6 +47,7 @@ import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.context.transaction.EffectTransactor; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; +import org.spongepowered.common.hooks.PlatformHooks; @Mixin(value = ServerGamePacketListenerImpl.class, priority = 999) public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCommonPacketListenerImplMixin_Vanilla implements ServerGamePacketListener { @@ -56,6 +57,8 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo @Shadow protected abstract void shadow$performChatCommand(final ServerboundChatCommandPacket $$0, final LastSeenMessages $$1); //@formatter:on + @Shadow protected abstract void performUnsignedChatCommand(String $$0); + @SuppressWarnings({"unchecked", "rawtypes"}) @Redirect(method = "lambda$handlePlaceRecipe$10", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) @@ -80,19 +83,20 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo * Specifically hooks the reach distance to use the forge hook. SpongeForge does not need this hook as forge already * replaces this logic with an equivalent. */ - @Redirect( - method = "handleInteract", - at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;MAX_INTERACTION_DISTANCE:D")) - private double vanilla$getPlatformReach(final ServerboundInteractPacket packet) { - return PlatformHooks.INSTANCE.getGeneralHooks().getEntityReachDistanceSq(this.player, packet.getTarget(this.player.serverLevel())); - } + // TODO fix me +// @Redirect( +// method = "handleInteract", +// at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;MAX_INTERACTION_DISTANCE:D")) +// private double vanilla$getPlatformReach(final ServerboundInteractPacket packet) { +// return PlatformHooks.INSTANCE.getGeneralHooks().getEntityReachDistanceSq(this.player, packet.getTarget(this.player.serverLevel())); +// } - @Redirect(method = "lambda$handleChatCommand$8", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;performChatCommand(Lnet/minecraft/network/protocol/game/ServerboundChatCommandPacket;Lnet/minecraft/network/chat/LastSeenMessages;)V")) - private void vanilla$onPerformChatCommand(final ServerGamePacketListenerImpl instance, final ServerboundChatCommandPacket $$0, final LastSeenMessages $$1) { + @Redirect(method = "lambda$handleChatCommand$7", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;performUnsignedChatCommand(Ljava/lang/String;)V")) + private void vanilla$onPerformChatCommand(final ServerGamePacketListenerImpl instance, final String $$0) { try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this.player); - frame.addContext(EventContextKeys.COMMAND, $$0.command()); - this.shadow$performChatCommand($$0, $$1); + frame.addContext(EventContextKeys.COMMAND, $$0); + this.performUnsignedChatCommand($$0); } } } From b44ab812de557abf8cb35d6bbce72675934b50b0 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 17:28:19 +0200 Subject: [PATCH 202/230] Fix Keys.REMAINING_BREW_TIME --- .../block/entity/BlockEntityAccessor.java | 2 ++ .../BrewingStandBlockEntityAccessor.java | 2 +- .../block/entity/BrewingStandData.java | 25 +++++++++---------- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BlockEntityAccessor.java index a5e51c969aa..19091ecab69 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BlockEntityAccessor.java @@ -34,4 +34,6 @@ public interface BlockEntityAccessor { @Accessor("level") void accessor$level(final Level level); + @Accessor("level") Level accessor$level(); + } diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java index bc1aa7e629c..81c6c571d94 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/block/entity/BrewingStandBlockEntityAccessor.java @@ -34,7 +34,7 @@ import org.spongepowered.common.UntransformedInvokerError; @Mixin(BrewingStandBlockEntity.class) -public interface BrewingStandBlockEntityAccessor { +public interface BrewingStandBlockEntityAccessor extends BlockEntityAccessor { @Accessor("brewTime") int accessor$brewTime(); diff --git a/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java b/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java index 3d01c64ca40..1f2fba45f9d 100644 --- a/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java +++ b/src/main/java/org/spongepowered/common/data/provider/block/entity/BrewingStandData.java @@ -46,19 +46,18 @@ public static void register(final DataProviderRegistrator registrator) { } h.accessor$fuel(v); return true; - // TODO fix me -// }) -// .create(Keys.REMAINING_BREW_TIME) -// .get(h -> BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items()) ? new SpongeTicks(h.accessor$brewTime()) : null) -// .setAnd((h, v) -> { -// if (v.isInfinite()) { -// return false; -// } -// if (BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$items())) { -// h.accessor$brewTime(SpongeTicks.toSaturatedIntOrInfinite(v)); -// return true; -// } -// return false; + }) + .create(Keys.REMAINING_BREW_TIME) + .get(h -> BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$level().potionBrewing(), h.accessor$items()) ? new SpongeTicks(h.accessor$brewTime()) : null) + .setAnd((h, v) -> { + if (v.isInfinite()) { + return false; + } + if (BrewingStandBlockEntityAccessor.invoker$isBrewable(h.accessor$level().potionBrewing(), h.accessor$items())) { + h.accessor$brewTime(SpongeTicks.toSaturatedIntOrInfinite(v)); + return true; + } + return false; }); } // @formatter:on From cdff5b87d439db683ac465f9743159aa7be11545 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 19:13:08 +0200 Subject: [PATCH 203/230] Fix MapDecoration --- .../SpongeMapDecorationBuilder.java | 19 ++++++++----------- .../minecraft/map/MapDecorationMixin_API.java | 4 +--- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index 70ccc4b60d7..19bae566f56 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -132,9 +132,8 @@ public MapDecoration.Builder fromContainer(final DataView container) { if (mcType == null) { throw new IllegalStateException("Missing a MapDecorationType, could not find one for Minecraft's MapDecoration.Type: " + type); } - // TODO fix me - //final MapDecorationType mapDecorationType = SpongeMapDecorationType.toSpongeType(BuiltInRegistries.MAP_DECORATION_TYPE.wrapAsHolder(mcType)).get(); - //this.type(mapDecorationType); + + this.type((MapDecorationType) (Object) mcType); final int intRot = MapUtil.normalizeDecorationOrientation(rot); this.rotation(MapUtil.getMapRotById(intRot)); @@ -167,13 +166,11 @@ private byte getByteFromContainer(final DataView container, final DataQuery quer @Override public MapDecoration build() throws IllegalStateException { Objects.requireNonNull(this.type, "Type has not been set"); - // TODO fix me - return null; -// final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( -// Holder.direct(((SpongeMapDecorationType) this.type).getType()), -// (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), -// Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); -// ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent -// return decoration; + final MapDecoration decoration = (MapDecoration) (Object) new net.minecraft.world.level.saveddata.maps.MapDecoration( + Holder.direct((net.minecraft.world.level.saveddata.maps.MapDecorationType) (Object) this.type), + (byte) this.x, (byte) this.y, (byte) ((SpongeMapDecorationOrientation) this.rot).getOrientationNumber(), + Optional.ofNullable(this.customName).map(SpongeAdventure::asVanilla)); + ((MapDecorationBridge) decoration).bridge$setPersistent(true); // Anything that comes out of this builder should be persistent + return decoration; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index c1bc8f94d91..d88cd2404ca 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -59,9 +59,7 @@ public abstract class MapDecorationMixin_API implements org.spongepowered.api.ma @Override public MapDecorationType type() { - //TODO fixme - return null; - //return SpongeMapDecorationType.toSpongeType(this.type).orElseThrow(() -> new IllegalStateException("Tried to get MapDecoration type but it didn't exist in Sponge's registries! Have MC Decoration types been missed?")); + return (MapDecorationType) (Object) this.type.value(); } @Override From 07feae61015fe3ba6b68de2a1a861b8eb2d5fb21 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 20:43:45 +0200 Subject: [PATCH 204/230] Fix onHit mixin injections --- .../AbstractHurtingProjectileMixin.java | 12 +++++------ .../entity/projectile/FishingHookMixin.java | 5 ++--- .../entity/projectile/ProjectileMixin.java | 3 +++ .../projectile/ThrowableProjectileMixin.java | 20 +++++++++---------- 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java index 13c663f0fdc..b909d0e1e36 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/AbstractHurtingProjectileMixin.java @@ -26,6 +26,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; +import net.minecraft.world.entity.projectile.ProjectileDeflection; import net.minecraft.world.phys.HitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -36,18 +37,17 @@ @Mixin(AbstractHurtingProjectile.class) public abstract class AbstractHurtingProjectileMixin extends ProjectileMixin { - //TODO fix me - //@Redirect(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/AbstractHurtingProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V")) - private void impl$callCollideImpactEvent(AbstractHurtingProjectile projectile, HitResult result) { + @Redirect(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/AbstractHurtingProjectile;hitTargetOrDeflectSelf(Lnet/minecraft/world/phys/HitResult;)Lnet/minecraft/world/entity/projectile/ProjectileDeflection;")) + private ProjectileDeflection impl$callCollideImpactEvent(AbstractHurtingProjectile projectile, HitResult result) { if (result.getType() == HitResult.Type.MISS || ((LevelBridge) this.shadow$level()).bridge$isFake()) { - this.shadow$onHit(result); - return; + return this.shadow$hitTargetOrDeflectSelf(result); } if (SpongeCommonEventFactory.handleCollideImpactEvent(projectile, this.impl$getProjectileSource(), result)) { this.shadow$remove(Entity.RemovalReason.DISCARDED); + return ProjectileDeflection.NONE; } else { - this.shadow$onHit(result); + return this.shadow$hitTargetOrDeflectSelf(result); } } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java index 4cb9cd8344a..323795d0834 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/FishingHookMixin.java @@ -179,9 +179,8 @@ public int retrieve(final ItemStack stack) { } } - //TODO fix me -// @Inject(method = "checkCollision", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, -// at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/FishingHook;onHit(Lnet/minecraft/world/phys/HitResult;)V")) + @Inject(method = "checkCollision", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/projectile/FishingHook;hitTargetOrDeflectSelf(Lnet/minecraft/world/phys/HitResult;)Lnet/minecraft/world/entity/projectile/ProjectileDeflection;")) private void impl$callCollideImpactEvent(final CallbackInfo ci, final HitResult hitResult) { if (hitResult.getType() == HitResult.Type.MISS || ((LevelBridge) this.shadow$level()).bridge$isFake()) { return; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java index 0793c0f19d2..5af1962961e 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ProjectileMixin.java @@ -26,6 +26,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.ProjectileDeflection; import net.minecraft.world.phys.HitResult; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; @@ -50,6 +51,8 @@ public abstract class ProjectileMixin extends EntityMixin { @Shadow protected abstract void shadow$onHit(HitResult result); @Shadow public abstract void shadow$setOwner(@Nullable Entity p_212361_1_); @Shadow public abstract @Nullable Entity shadow$getOwner(); + @Shadow protected abstract ProjectileDeflection shadow$hitTargetOrDeflectSelf(HitResult $$0); + // @formatter:on private ProjectileSource impl$projectileSource = UnknownProjectileSource.UNKNOWN; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java index 93e20ab21a6..d8cfebbe9ea 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/ThrowableProjectileMixin.java @@ -26,6 +26,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.projectile.ProjectileDeflection; import net.minecraft.world.entity.projectile.ThrowableProjectile; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity; @@ -42,22 +43,21 @@ @Mixin(ThrowableProjectile.class) public abstract class ThrowableProjectileMixin extends ProjectileMixin { - // TODO fixme -// @Redirect(method = "tick()V", -// at = @At(value = "INVOKE", -// target = "Lnet/minecraft/world/entity/projectile/ThrowableProjectile;onHit(Lnet/minecraft/world/phys/HitResult;)V" -// ) -// ) - private void impl$handleProjectileImpact(final ThrowableProjectile projectile, final HitResult movingObjectPosition) { + @Redirect(method = "tick()V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/world/entity/projectile/ThrowableProjectile;hitTargetOrDeflectSelf(Lnet/minecraft/world/phys/HitResult;)Lnet/minecraft/world/entity/projectile/ProjectileDeflection;" + ) + ) + private ProjectileDeflection impl$handleProjectileImpact(final ThrowableProjectile projectile, final HitResult movingObjectPosition) { if (((LevelBridge) this.shadow$level()).bridge$isFake() || movingObjectPosition.getType() == HitResult.Type.MISS) { - this.shadow$onHit(movingObjectPosition); - return; + return this.shadow$hitTargetOrDeflectSelf(movingObjectPosition); } if (SpongeCommonEventFactory.handleCollideImpactEvent(projectile, this.impl$getProjectileSource(), movingObjectPosition)) { this.shadow$discard(); + return ProjectileDeflection.NONE; } else { - this.shadow$onHit(movingObjectPosition); + return this.shadow$hitTargetOrDeflectSelf(movingObjectPosition); } } From 9f11925716f34756d1f38f17a05f42123944cc37 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 20:49:38 +0200 Subject: [PATCH 205/230] Fix EntityStorageMixin injection --- .../core/world/level/chunk/storage/EntityStorageMixin.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java index bf600f72072..14fcccc3498 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java @@ -30,6 +30,7 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.EntityStorage; import net.minecraft.world.level.chunk.storage.IOWorker; +import net.minecraft.world.level.chunk.storage.SimpleRegionStorage; import net.minecraft.world.level.entity.ChunkEntities; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; @@ -54,6 +55,7 @@ import java.util.List; import java.util.Optional; +import java.util.concurrent.Executor; @Mixin(EntityStorage.class) public abstract class EntityStorageMixin { @@ -63,9 +65,8 @@ public abstract class EntityStorageMixin { // @formatter:on @Inject(method = "", at = @At("RETURN")) - private void impl$setIOWorkerDimension(final CallbackInfo ci) { - // TODO fix me - //((IOWorkerBridge) this.worker).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); + private void impl$setIOWorkerDimension(final SimpleRegionStorage $$0, final ServerLevel $$1, final Executor $$2, final CallbackInfo ci) { + ((IOWorkerBridge) $$0).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); } @Inject(method = "lambda$loadEntities$0", at = @At("RETURN"), cancellable = true) From a18257d547e0c91c53af289553366c56f8cca53c Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Sun, 5 May 2024 21:21:50 +0200 Subject: [PATCH 206/230] Remove unnecessary redirect for recipe size fix in RecipeManagerMixin_API --- .../world/item/crafting/RecipeManagerMixin_API.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java index f3d18b7b7b6..b09dd0d0f8b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java @@ -147,10 +147,4 @@ public Optional findCookingRecipe(final RecipeType< fakeFurnace.setItem(0, ItemStackUtil.fromSnapshotToNative(ingredient)); return this.shadow$getRecipeFor((net.minecraft.world.item.crafting.RecipeType) type, fakeFurnace, null); } - - // TODO fix me -// @Redirect(method = "apply", at = @At(value = "INVOKE", remap = false, target = "Ljava/util/Map;size()I")) -// public int impl$getActualRecipeCount(final Map, ImmutableMap.Builder>> map) { -// return this.recipes.values().stream().mapToInt(Map::size).sum(); -// } } From 82a1144fe951051aea9a226af1ab22b155eb9166 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 00:03:45 +0200 Subject: [PATCH 207/230] Fix RandomizableContainerBlockEntity mixin --- ...RandomizableContainerBlockEntityMixin_BugFix.java | 12 +++++------- .../block/entity/BaseContainerBlockEntityMixin.java | 3 +++ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java b/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java index 08213a3a2a1..bb820dea15d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java +++ b/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java @@ -29,21 +29,19 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.common.mixin.core.world.level.block.entity.BaseContainerBlockEntityMixin; @Mixin(RandomizableContainerBlockEntity.class) -public abstract class RandomizableContainerBlockEntityMixin_BugFix { +public abstract class RandomizableContainerBlockEntityMixin_BugFix extends BaseContainerBlockEntityMixin { @Shadow @Nullable protected ResourceLocation lootTable; // Minecraft 1.19.4 - Fixes https://bugs.mojang.com/browse/MC-136917 - // TODO fix me - //@Inject(method = "clearContent", at = @At("TAIL")) - private void impl$clearContent(final CallbackInfo ci) { + // @Override + public void clearContent() { + super.shadow$clearContent(); this.lootTable = null; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java index 8f0483a0f52..ac442f5b6c2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/BaseContainerBlockEntityMixin.java @@ -27,12 +27,15 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.accessor.world.level.block.entity.BaseContainerBlockEntityAccessor; import org.spongepowered.common.bridge.CustomNameableBridge; @Mixin(BaseContainerBlockEntity.class) public abstract class BaseContainerBlockEntityMixin extends BlockEntityMixin implements CustomNameableBridge { + @Shadow public void shadow$clearContent() {} + @Override public void bridge$setCustomDisplayName(final Component customName) { ((BaseContainerBlockEntityAccessor) this).accessor$setCustomName(customName); From 8e729ce754b55bb4b98e39fdd78f2f62af8337db Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 00:04:15 +0200 Subject: [PATCH 208/230] Fix crash on client startup in EntityStorageMixin --- .../storage/SimpleRegionStorageAccessor.java | 36 +++++++++++++++++++ .../resources/mixins.sponge.accessors.json | 1 + .../chunk/storage/EntityStorageMixin.java | 3 +- 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/accessors/java/org/spongepowered/common/accessor/world/level/chunk/storage/SimpleRegionStorageAccessor.java diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/level/chunk/storage/SimpleRegionStorageAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/level/chunk/storage/SimpleRegionStorageAccessor.java new file mode 100644 index 00000000000..d9c356ec44b --- /dev/null +++ b/src/accessors/java/org/spongepowered/common/accessor/world/level/chunk/storage/SimpleRegionStorageAccessor.java @@ -0,0 +1,36 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.accessor.world.level.chunk.storage; + +import net.minecraft.world.level.chunk.storage.IOWorker; +import net.minecraft.world.level.chunk.storage.SimpleRegionStorage; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(SimpleRegionStorage.class) +public interface SimpleRegionStorageAccessor { + + @Accessor("worker") IOWorker accessor$worker(); +} diff --git a/src/accessors/resources/mixins.sponge.accessors.json b/src/accessors/resources/mixins.sponge.accessors.json index a7e6436d199..a79c5654dfb 100644 --- a/src/accessors/resources/mixins.sponge.accessors.json +++ b/src/accessors/resources/mixins.sponge.accessors.json @@ -186,6 +186,7 @@ "world.level.chunk.LevelChunkAccessor", "world.level.chunk.storage.ChunkStorageAccessor", "world.level.chunk.storage.IOWorker$PendingStoreAccessor", + "world.level.chunk.storage.SimpleRegionStorageAccessor", "world.level.dimension.DimensionTypeAccessor", "world.level.entity.EntityTickListAccessor", "world.level.entity.PersistentEntitySectionManagerAccessor", diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java index 14fcccc3498..d445491cc00 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java @@ -45,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.accessor.world.level.chunk.storage.SimpleRegionStorageAccessor; import org.spongepowered.common.bridge.world.level.chunk.storage.IOWorkerBridge; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.tracking.PhaseTracker; @@ -66,7 +67,7 @@ public abstract class EntityStorageMixin { @Inject(method = "", at = @At("RETURN")) private void impl$setIOWorkerDimension(final SimpleRegionStorage $$0, final ServerLevel $$1, final Executor $$2, final CallbackInfo ci) { - ((IOWorkerBridge) $$0).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); + ((IOWorkerBridge) ((SimpleRegionStorageAccessor) $$0).accessor$worker()).bridge$setDimension(SpongeIOWorkerType.ENTITY, this.level.dimension()); } @Inject(method = "lambda$loadEntities$0", at = @At("RETURN"), cancellable = true) From 7bba041c76ec5ee21cc23d2b9e2e63829b10384f Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 00:05:29 +0200 Subject: [PATCH 209/230] Remove invalid unused shadow in ServerGamePacketListenerImplMixin_Vanilla --- .../network/ServerGamePacketListenerImplMixin_Vanilla.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 30c2a85e019..17cb28b2db9 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -54,11 +54,9 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo // @formatter:off @Shadow public ServerPlayer player; - @Shadow protected abstract void shadow$performChatCommand(final ServerboundChatCommandPacket $$0, final LastSeenMessages $$1); + @Shadow protected abstract void shadow$performUnsignedChatCommand(String $$0); //@formatter:on - @Shadow protected abstract void performUnsignedChatCommand(String $$0); - @SuppressWarnings({"unchecked", "rawtypes"}) @Redirect(method = "lambda$handlePlaceRecipe$10", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) @@ -96,7 +94,7 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this.player); frame.addContext(EventContextKeys.COMMAND, $$0); - this.performUnsignedChatCommand($$0); + this.shadow$performUnsignedChatCommand($$0); } } } From a9ac58626ce310cd44c9f621e5dc514d31eb4163 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 00:35:18 +0200 Subject: [PATCH 210/230] Fix mixin injection failure --- .../ServerGamePacketListenerImplMixin.java | 16 +++++++++++++--- ...erverGamePacketListenerImplMixin_Vanilla.java | 14 -------------- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java index 36c81596313..a5e37b6a370 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java @@ -34,11 +34,13 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.network.chat.LastSeenMessages; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; import net.minecraft.network.protocol.game.ClientboundCommandSuggestionsPacket; import net.minecraft.network.protocol.game.ClientboundMoveVehiclePacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; +import net.minecraft.network.protocol.game.ServerboundChatCommandSignedPacket; import net.minecraft.network.protocol.game.ServerboundCommandSuggestionPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket; @@ -128,11 +130,10 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack @Shadow public abstract void shadow$teleport(double x, double y, double z, float yaw, float pitch, Set relativeArguments); @Shadow protected abstract CompletableFuture> shadow$filterTextPacket(final List $$0); @Shadow protected abstract void shadow$performUnsignedChatCommand(final String $$0); + @Shadow protected abstract void shadow$performSignedChatCommand(ServerboundChatCommandSignedPacket $$0, LastSeenMessages $$1); @Shadow protected abstract ParseResults shadow$parseCommand(final String $$0); // @formatter:on - @Shadow protected abstract void performUnsignedChatCommand(final String $$0); - @Nullable private ResourcePack impl$lastAcceptedPack; private int impl$ignorePackets; @@ -506,7 +507,16 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this.player); frame.addContext(EventContextKeys.COMMAND, $$0); - this.performUnsignedChatCommand($$0); + this.shadow$performUnsignedChatCommand($$0); + } + } + + @Redirect(method = "lambda$handleSignedChatCommand$8", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;performSignedChatCommand(Lnet/minecraft/network/protocol/game/ServerboundChatCommandSignedPacket;Lnet/minecraft/network/chat/LastSeenMessages;)V")) + public void impl$onPerformSignedChatCommand(final ServerGamePacketListenerImpl instance, final ServerboundChatCommandSignedPacket $$0, final LastSeenMessages $$1) { + try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { + frame.pushCause(this.player); + frame.addContext(EventContextKeys.COMMAND, $$0.command()); + this.shadow$performSignedChatCommand($$0, $$1); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 17cb28b2db9..81ff455568f 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -52,11 +52,6 @@ @Mixin(value = ServerGamePacketListenerImpl.class, priority = 999) public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCommonPacketListenerImplMixin_Vanilla implements ServerGamePacketListener { - // @formatter:off - @Shadow public ServerPlayer player; - @Shadow protected abstract void shadow$performUnsignedChatCommand(String $$0); - //@formatter:on - @SuppressWarnings({"unchecked", "rawtypes"}) @Redirect(method = "lambda$handlePlaceRecipe$10", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/inventory/RecipeBookMenu;handlePlacement(ZLnet/minecraft/world/item/crafting/RecipeHolder;Lnet/minecraft/server/level/ServerPlayer;)V")) @@ -88,13 +83,4 @@ public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCo // private double vanilla$getPlatformReach(final ServerboundInteractPacket packet) { // return PlatformHooks.INSTANCE.getGeneralHooks().getEntityReachDistanceSq(this.player, packet.getTarget(this.player.serverLevel())); // } - - @Redirect(method = "lambda$handleChatCommand$7", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerGamePacketListenerImpl;performUnsignedChatCommand(Ljava/lang/String;)V")) - private void vanilla$onPerformChatCommand(final ServerGamePacketListenerImpl instance, final String $$0) { - try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { - frame.pushCause(this.player); - frame.addContext(EventContextKeys.COMMAND, $$0); - this.shadow$performUnsignedChatCommand($$0); - } - } } From 0bf10df1995707356c98e141c9fcd7e11f26bf81 Mon Sep 17 00:00:00 2001 From: Gabriel Harris-Rouquette Date: Sun, 5 May 2024 16:09:20 -0700 Subject: [PATCH 211/230] chore: update macos natives --- gradle/verification-metadata.xml | 69 ++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index f020be7afd5..c037c099f1e 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -5,6 +5,19 @@ false + + + + + + + + + + + + + @@ -35,6 +48,14 @@ + + + + + + + + @@ -3125,6 +3146,12 @@ + + + + + + @@ -3136,6 +3163,12 @@ + + + + + + @@ -3167,6 +3200,12 @@ + + + + + + @@ -3198,6 +3237,12 @@ + + + + + + @@ -3229,6 +3274,12 @@ + + + + + + @@ -3260,6 +3311,12 @@ + + + + + + @@ -3291,6 +3348,12 @@ + + + + + + @@ -3322,6 +3385,12 @@ + + + + + + From 280c2ed8ec9fc860c0c1b22c8a67fb18543f428e Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 01:34:49 +0200 Subject: [PATCH 212/230] Drop RandomizableContainerBlockEntityMixin_BugFix --- gradle.properties | 2 +- ...zableContainerBlockEntityMixin_BugFix.java | 47 ------------------- .../resources/mixins.sponge.bugfix.json | 7 --- 3 files changed, 1 insertion(+), 55 deletions(-) delete mode 100644 src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java delete mode 100644 src/mixins/resources/mixins.sponge.bugfix.json diff --git a/gradle.properties b/gradle.properties index df9090fc215..235cbf86e39 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ projectDescription=The SpongeAPI implementation targeting vanilla Minecraft and mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.concurrent.json,mixins.sponge.core.json,\ mixins.sponge.entityactivation.json,mixins.sponge.exploit.json,mixins.sponge.inventory.json,mixins.sponge.movementcheck.json,\ - mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json,mixins.sponge.bugfix.json + mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json superClassChanges=common.superclasschange minecraftVersion=1.20.6 diff --git a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java b/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java deleted file mode 100644 index bb820dea15d..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/bugfix/world/level/block/entity/RandomizableContainerBlockEntityMixin_BugFix.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.bugfix.world.level.block.entity; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.mixin.core.world.level.block.entity.BaseContainerBlockEntityMixin; - -@Mixin(RandomizableContainerBlockEntity.class) -public abstract class RandomizableContainerBlockEntityMixin_BugFix extends BaseContainerBlockEntityMixin { - - @Shadow - @Nullable - protected ResourceLocation lootTable; - - // Minecraft 1.19.4 - Fixes https://bugs.mojang.com/browse/MC-136917 - // @Override - public void clearContent() { - super.shadow$clearContent(); - this.lootTable = null; - } -} diff --git a/src/mixins/resources/mixins.sponge.bugfix.json b/src/mixins/resources/mixins.sponge.bugfix.json deleted file mode 100644 index 6a363b6bb29..00000000000 --- a/src/mixins/resources/mixins.sponge.bugfix.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "parent": "mixins.sponge.parent.json", - "package": "org.spongepowered.common.mixin.bugfix", - "mixins": [ - "world.level.block.entity.RandomizableContainerBlockEntityMixin_BugFix" - ] -} From f5072a94d6002d69428cbb16ffaea929bfba1a41 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 03:24:45 +0200 Subject: [PATCH 213/230] Fix FoodDataMixin --- .../common/mixin/core/world/food/FoodDataMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java index 866d73eb4ba..41a0d465762 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/food/FoodDataMixin.java @@ -66,7 +66,7 @@ public abstract class FoodDataMixin implements FoodDataBridge { this.foodLevel = this.impl$fireEventAndGetValue(Keys.FOOD_LEVEL, this.foodLevel, value); } - @Redirect(method = "eat(IF)V", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;foodLevel:I", opcode = Opcodes.PUTFIELD)) + @Redirect(method = "add", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;foodLevel:I", opcode = Opcodes.PUTFIELD)) private void impl$eatSetFoodLevel(final FoodData self, final int value) { this.foodLevel = this.impl$fireEventAndGetValue(Keys.FOOD_LEVEL, this.foodLevel, value); } @@ -81,7 +81,7 @@ public abstract class FoodDataMixin implements FoodDataBridge { this.saturationLevel = this.impl$fireEventAndGetValue(Keys.SATURATION, (double) this.saturationLevel, (double) value).floatValue(); } - @Redirect(method = "eat(IF)V", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;saturationLevel:F", opcode = Opcodes.PUTFIELD)) + @Redirect(method = "add", at = @At(value = "FIELD", target = "Lnet/minecraft/world/food/FoodData;saturationLevel:F", opcode = Opcodes.PUTFIELD)) private void impl$eatSetSaturationLevel(final FoodData self, final float value) { this.saturationLevel = this.impl$fireEventAndGetValue(Keys.SATURATION, (double) this.saturationLevel, (double) value).floatValue(); } From 4397847cc8c87c2c5fa16a478ba7ba30f62d2ff0 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 03:37:51 +0200 Subject: [PATCH 214/230] More fixes --- .../bridge/advancements/AdvancementBridge.java | 2 +- .../network/channel/SpongeChannelManager.java | 14 +++++++------- .../advancements/AdvancementProgressMixin.java | 16 +++++++++++++--- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/spongepowered/common/bridge/advancements/AdvancementBridge.java b/src/main/java/org/spongepowered/common/bridge/advancements/AdvancementBridge.java index 63eb3beebd6..50050708cf4 100644 --- a/src/main/java/org/spongepowered/common/bridge/advancements/AdvancementBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/advancements/AdvancementBridge.java @@ -33,7 +33,7 @@ public interface AdvancementBridge { - AdvancementCriterion bridge$getCriterion(); + AdvancementCriterion bridge$getCriterion(); void bridge$setCriterion(AdvancementCriterion criterion); diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java index 3756acdbb7d..7a7657a58ac 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java @@ -263,7 +263,7 @@ public Type type() { public void sendChannelRegistrations(final EngineConnection connection) { final Packet mcPacket = PacketUtil.createPlayPayload(new SpongeRegisterChannelPayload(this.channels.keySet()), connection.side()); - // TODO this is currently broken PacketSender.sendTo(connection, mcPacket);/ + PacketSender.sendTo(connection, mcPacket); } /** @@ -306,12 +306,12 @@ private void handleChannelRegistry(final EngineConnection connection, final Chan } public boolean handlePlayPayload(final EngineConnection connection, final CustomPacketPayload payload) { -// final ResourceKey channel = (ResourceKey) (Object) payload.id(); -// final ChannelBuf buf = this.bufferAllocator.buffer(); -// payload.write((FriendlyByteBuf) buf); -// -// return this.handlePlayPayload(connection, channel, buf); - return false; // TODO fix me + final ResourceKey channel = (ResourceKey) (Object) payload.type().id(); + final ChannelBuf buf = this.bufferAllocator.buffer(); + //TODO fixme + //payload.type((FriendlyByteBuf) buf); + + return this.handlePlayPayload(connection, channel, buf); } private void handleRegisterChannel(final EngineConnection connection, final ChannelBuf payload, diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java index 2caa05a7274..ea411fa083c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/AdvancementProgressMixin.java @@ -139,7 +139,12 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri final Optional advancement = this.impl$getOptionalAdvancement(); if (advancement.isPresent()) { this.impl$progressMap = new LinkedHashMap<>(); - this.impl$processProgressMap(advancement.get().criterion(), this.impl$progressMap); + if (advancement.get().criterion() != null) { + this.impl$processProgressMap(advancement.get().criterion(), this.impl$progressMap); + } else { + // TODO fix me + SpongeCommon.logger().warn("advancement has null criterion"); + } } else { this.impl$progressMap = null; } @@ -214,8 +219,13 @@ public abstract class AdvancementProgressMixin implements AdvancementProgressBri final Advancement advancement = this.impl$getOptionalAdvancement().orElse(null); if (advancement != null) { - final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); - ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); + if (advancement.criterion() != null) { + final ImplementationBackedCriterionProgress bridge = this.impl$progressMap.get(advancement.criterion().name()); + ci.setReturnValue(bridge != null && ((CriterionProgress) bridge).achieved()); + } else { + // TODO fix me + SpongeCommon.logger().warn("advancement has null criterion"); + } } } From f523de08dc6fd2184f370e51c56106b0e9e0ec6c Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Mon, 6 May 2024 04:23:27 +0200 Subject: [PATCH 215/230] Add archetype TODO --- .../common/block/entity/SpongeBlockEntityArchetype.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java index 59ae854ce1e..4c65288795c 100644 --- a/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java +++ b/src/main/java/org/spongepowered/common/block/entity/SpongeBlockEntityArchetype.java @@ -198,7 +198,8 @@ public String toString() { if (this.cachedBlockEntity == null) { final CompoundTag compound = this.compound.copy(); compound.putString(Constants.Item.BLOCK_ENTITY_ID, SpongeCommon.vanillaRegistry(Registries.BLOCK_ENTITY_TYPE).getKey((net.minecraft.world.level.block.entity.BlockEntityType) this.type).toString()); - this.cachedBlockEntity = net.minecraft.world.level.block.entity.BlockEntity.loadStatic(new BlockPos(0, 0, 0), (net.minecraft.world.level.block.state.BlockState) this.blockState, compound); + //TODO fixme + //this.cachedBlockEntity = net.minecraft.world.level.block.entity.BlockEntity.loadStatic(new BlockPos(0, 0, 0), (net.minecraft.world.level.block.state.BlockState) this.blockState, compound); } return Arrays.asList(this, (DataHolder) this.cachedBlockEntity); } From 664e73621c544a722f38764b7d289e1138d13c2a Mon Sep 17 00:00:00 2001 From: aromaa Date: Mon, 6 May 2024 17:23:12 +0300 Subject: [PATCH 216/230] WIP work on EngineConnection --- SpongeAPI | 2 +- .../bridge/network/ConnectionBridge.java | 2 + .../ServerLoginPacketListenerImplBridge.java | 4 + ...verHandshakePacketListenerImplBridge.java} | 8 +- .../velocity/VelocityForwardingInfo.java | 4 +- .../SpongeClientEngineConnection.java} | 15 ++-- .../network/SpongeEngineConnection.java} | 43 ++++++---- .../SpongeServerEngineConnection.java} | 19 ++--- .../network/channel/ConnectionUtil.java | 6 +- .../common/network/channel/PacketSender.java | 4 +- .../common/network/channel/SpongeChannel.java | 8 +- .../network/channel/SpongeChannelManager.java | 4 +- .../network/channel/TransactionStore.java | 10 +-- .../packet/SpongeBasicPacketChannel.java | 7 +- .../channel/packet/SpongePacketChannel.java | 9 ++- .../SpongeTransactionalPacketBinding.java | 21 ++--- .../network/packet/SpongePacketHandler.java | 6 +- .../server/level/ServerPlayerMixin_API.java | 9 ++- ...rverCommonPacketListenerImplMixin_API.java | 78 ------------------ ...ServerGamePacketListenerImplMixin_API.java | 52 ------------ ...HandshakePacketListenerImplMixin_API.java} | 16 ++-- ...erverLoginPacketListenerImplMixin_API.java | 79 ------------------- .../mixin/core/network/ConnectionMixin.java | 23 +++++- ...erverHandshakePacketListenerImplMixin.java | 44 ++++++++++- .../ServerCommonPacketListenerImplMixin.java | 8 +- ...rConfigurationPacketListenerImplMixin.java | 6 +- ...erverHandshakePacketListenerImplMixin.java | 70 +++++++++++++++- .../ServerLoginPacketListenerImplMixin.java | 6 +- .../core/server/players/PlayerListMixin.java | 2 +- src/mixins/resources/mixins.sponge.api.json | 6 +- src/mixins/resources/mixins.sponge.core.json | 2 - ...dshakePacketListenerImplMixin_Vanilla.java | 5 +- .../ClientPacketListenerMixin_Vanilla.java | 14 +++- .../network/FriendlyByteBufMixin_Vanilla.java | 4 - ...CommonPacketListenerImplMixin_Vanilla.java | 6 +- ...erGamePacketListenerImplMixin_Vanilla.java | 8 -- ...rLoginPacketListenerImplMixin_Vanilla.java | 6 +- ...boundCustomPayloadPacketMixin_Vanilla.java | 6 -- ...perBlockEntityMixin_Inventory_Vanilla.java | 1 - 39 files changed, 261 insertions(+), 362 deletions(-) rename src/main/java/org/spongepowered/common/bridge/{network/ConnectionHolderBridge.java => server/network/ServerHandshakePacketListenerImplBridge.java} (87%) rename src/{mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientPacketListenerMixin.java => main/java/org/spongepowered/common/network/SpongeClientEngineConnection.java} (68%) rename src/{mixins/java/org/spongepowered/common/mixin/api/minecraft/client/network/ClientNetHandlerMixin_API.java => main/java/org/spongepowered/common/network/SpongeEngineConnection.java} (61%) rename src/{mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin.java => main/java/org/spongepowered/common/network/SpongeServerEngineConnection.java} (67%) delete mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java delete mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java rename src/mixins/java/org/spongepowered/common/mixin/api/minecraft/{client/multiplayer/ClientPacketListenerMixin_API.java => server/network/ServerHandshakePacketListenerImplMixin_API.java} (69%) delete mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java diff --git a/SpongeAPI b/SpongeAPI index 5565cde1d2d..a459a98f095 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit 5565cde1d2d40fc5cb6ae2ddee63431255bcf51e +Subproject commit a459a98f0955c84398f0824175ccafec2c84c2b7 diff --git a/src/main/java/org/spongepowered/common/bridge/network/ConnectionBridge.java b/src/main/java/org/spongepowered/common/bridge/network/ConnectionBridge.java index 189d54f8dbb..3ccfdf87cfd 100644 --- a/src/main/java/org/spongepowered/common/bridge/network/ConnectionBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/network/ConnectionBridge.java @@ -27,6 +27,7 @@ import org.spongepowered.api.MinecraftVersion; import org.spongepowered.api.ResourceKey; import org.spongepowered.common.entity.player.ClientType; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.TransactionStore; import java.net.InetSocketAddress; @@ -56,4 +57,5 @@ public interface ConnectionBridge { void bridge$setClientType(ClientType clientType); + SpongeEngineConnection bridge$getEngineConnection(); } diff --git a/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java b/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java index 19083f22158..fae43a92b9a 100644 --- a/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java @@ -24,6 +24,8 @@ */ package org.spongepowered.common.bridge.network; +import net.minecraft.network.Connection; + import java.util.concurrent.ExecutorService; public interface ServerLoginPacketListenerImplBridge { @@ -31,4 +33,6 @@ public interface ServerLoginPacketListenerImplBridge { ExecutorService bridge$getExecutor(); void bridge$fireAuthEvent(); + + Connection bridge$getConnection(); } diff --git a/src/main/java/org/spongepowered/common/bridge/network/ConnectionHolderBridge.java b/src/main/java/org/spongepowered/common/bridge/server/network/ServerHandshakePacketListenerImplBridge.java similarity index 87% rename from src/main/java/org/spongepowered/common/bridge/network/ConnectionHolderBridge.java rename to src/main/java/org/spongepowered/common/bridge/server/network/ServerHandshakePacketListenerImplBridge.java index fc5131e2d6e..a1a5eb2e0fa 100644 --- a/src/main/java/org/spongepowered/common/bridge/network/ConnectionHolderBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/server/network/ServerHandshakePacketListenerImplBridge.java @@ -22,11 +22,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.bridge.network; +package org.spongepowered.common.bridge.server.network; -import net.minecraft.network.Connection; +public interface ServerHandshakePacketListenerImplBridge { -public interface ConnectionHolderBridge { - - Connection bridge$getConnection(); + boolean bridge$transferred(); } diff --git a/src/main/java/org/spongepowered/common/ipforward/velocity/VelocityForwardingInfo.java b/src/main/java/org/spongepowered/common/ipforward/velocity/VelocityForwardingInfo.java index 7613d4086f2..b120c352474 100644 --- a/src/main/java/org/spongepowered/common/ipforward/velocity/VelocityForwardingInfo.java +++ b/src/main/java/org/spongepowered/common/ipforward/velocity/VelocityForwardingInfo.java @@ -45,6 +45,8 @@ import org.spongepowered.common.accessor.network.ConnectionAccessor; import org.spongepowered.common.accessor.server.network.ServerLoginPacketListenerImplAccessor; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; +import org.spongepowered.common.bridge.network.ConnectionBridge; +import org.spongepowered.common.bridge.network.ServerLoginPacketListenerImplBridge; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -74,7 +76,7 @@ private static class VelocityChannel { } public static void sendQuery(final ServerLoginPacketListenerImpl mcConn) { - final EngineConnection conn = (EngineConnection) mcConn; + final EngineConnection conn = ((ConnectionBridge) ((ServerLoginPacketListenerImplBridge) mcConn).bridge$getConnection()).bridge$getEngineConnection(); VelocityChannel.CHANNEL .sendTo(conn, cbuf -> {}) .whenComplete((response, error) -> { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientPacketListenerMixin.java b/src/main/java/org/spongepowered/common/network/SpongeClientEngineConnection.java similarity index 68% rename from src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientPacketListenerMixin.java rename to src/main/java/org/spongepowered/common/network/SpongeClientEngineConnection.java index f3046ef4b97..49df1b5fc15 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientPacketListenerMixin.java +++ b/src/main/java/org/spongepowered/common/network/SpongeClientEngineConnection.java @@ -22,19 +22,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.core.client.multiplayer; +package org.spongepowered.common.network; -import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.network.Connection; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; -import org.spongepowered.common.mixin.api.minecraft.client.multiplayer.ClientCommonPacketListenerImpl_API; +import org.spongepowered.api.network.ClientSideConnection; -@Mixin(ClientPacketListener.class) -public abstract class ClientPacketListenerMixin extends ClientCommonPacketListenerImpl_API implements ConnectionHolderBridge { +public final class SpongeClientEngineConnection extends SpongeEngineConnection implements ClientSideConnection { - @Override - public Connection bridge$getConnection() { - return this.connection; + public SpongeClientEngineConnection(final Connection connection) { + super(connection); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/network/ClientNetHandlerMixin_API.java b/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java similarity index 61% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/network/ClientNetHandlerMixin_API.java rename to src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java index 04693dbac2f..e866b8a6ff1 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/network/ClientNetHandlerMixin_API.java +++ b/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java @@ -22,40 +22,51 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.minecraft.client.network; +package org.spongepowered.common.network; import net.kyori.adventure.text.Component; -import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; -import net.minecraft.client.multiplayer.ClientPacketListener; -import org.spongepowered.api.network.ClientSideConnection; -import org.spongepowered.asm.mixin.Mixin; +import net.minecraft.network.Connection; +import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.ConnectionBridge; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; import java.net.InetSocketAddress; -@Mixin({ ClientHandshakePacketListenerImpl.class, ClientPacketListener.class }) -public abstract class ClientNetHandlerMixin_API implements ClientSideConnection { +public abstract class SpongeEngineConnection implements EngineConnection { - @Override - public void close() { - ((ConnectionHolderBridge) this).bridge$getConnection().disconnect( - net.minecraft.network.chat.Component.translatable("disconnect.disconnected")); + protected final Connection connection; + + public SpongeEngineConnection(final Connection connection) { + this.connection = connection; } @Override - public void close(final Component reason) { - ((ConnectionHolderBridge) this).bridge$getConnection().disconnect(SpongeAdventure.asVanilla(reason)); + public EngineConnectionState state() { + return (EngineConnectionState) this.connection.getPacketListener(); } @Override public InetSocketAddress address() { - return ((ConnectionBridge) ((ConnectionHolderBridge) this).bridge$getConnection()).bridge$getAddress(); + return ((ConnectionBridge) this.connection).bridge$getAddress(); } @Override public InetSocketAddress virtualHost() { - return ((ConnectionBridge) ((ConnectionHolderBridge) this).bridge$getConnection()).bridge$getVirtualHost(); + return ((ConnectionBridge) this.connection).bridge$getVirtualHost(); + } + + @Override + public void close() { + this.connection.disconnect(net.minecraft.network.chat.Component.translatable("disconnect.disconnected")); + } + + @Override + public void close(final Component reason) { + this.connection.disconnect(SpongeAdventure.asVanilla(reason)); + } + + public Connection connection() { + return this.connection; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin.java b/src/main/java/org/spongepowered/common/network/SpongeServerEngineConnection.java similarity index 67% rename from src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin.java rename to src/main/java/org/spongepowered/common/network/SpongeServerEngineConnection.java index 5bf5bd8f44e..da7d2066ba6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin.java +++ b/src/main/java/org/spongepowered/common/network/SpongeServerEngineConnection.java @@ -22,22 +22,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.core.client.multiplayer; +package org.spongepowered.common.network; -import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; import net.minecraft.network.Connection; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; +import org.spongepowered.api.network.ServerSideConnection; -@Mixin(ClientHandshakePacketListenerImpl.class) -public abstract class ClientHandshakePacketListenerImplMixin implements ConnectionHolderBridge { +public final class SpongeServerEngineConnection extends SpongeEngineConnection implements ServerSideConnection { - @Shadow @Final private Connection connection; - - @Override - public Connection bridge$getConnection() { - return this.connection; + public SpongeServerEngineConnection(final Connection connection) { + super(connection); } + } diff --git a/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java b/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java index 2de1eb3a80a..67d71d559d8 100644 --- a/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java +++ b/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java @@ -30,7 +30,7 @@ import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.common.bridge.network.ConnectionBridge; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; +import org.spongepowered.common.network.SpongeEngineConnection; import java.util.Set; @@ -42,12 +42,12 @@ public static boolean isLoginPhase(final EngineConnection connection) { } public static Set getRegisteredChannels(final EngineConnection connection) { - final Connection networkManager = ((ConnectionHolderBridge) connection).bridge$getConnection(); + final Connection networkManager = ((SpongeEngineConnection) connection).connection(); return ((ConnectionBridge) networkManager).bridge$getRegisteredChannels(); } public static TransactionStore getTransactionStore(final EngineConnection connection) { - final Connection networkManager = ((ConnectionHolderBridge) connection).bridge$getConnection(); + final Connection networkManager = ((SpongeEngineConnection) connection).connection(); return ((ConnectionBridge) networkManager).bridge$getTransactionStore(); } diff --git a/src/main/java/org/spongepowered/common/network/channel/PacketSender.java b/src/main/java/org/spongepowered/common/network/channel/PacketSender.java index 8ef647ae74f..ffa5b9a77bc 100644 --- a/src/main/java/org/spongepowered/common/network/channel/PacketSender.java +++ b/src/main/java/org/spongepowered/common/network/channel/PacketSender.java @@ -32,7 +32,7 @@ import org.spongepowered.api.Sponge; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; +import org.spongepowered.common.network.SpongeEngineConnection; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; @@ -45,7 +45,7 @@ public static void sendTo(final EngineConnection connection, final Packet pac } public static void sendTo(final EngineConnection connection, final Packet packet, final @Nullable Consumer<@Nullable Throwable> listener) { - final Connection networkManager = ((ConnectionHolderBridge) connection).bridge$getConnection(); + final Connection networkManager = ((SpongeEngineConnection) connection).connection(); networkManager.send(packet, listener == null ? null : new SpongePacketSendListener(connection.side(), listener)); } diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java index ab173750d32..89e42fc4cfc 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java @@ -32,9 +32,6 @@ import org.spongepowered.api.network.ClientSideConnection; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; -import org.spongepowered.api.network.LocalPlayerConnection; -import org.spongepowered.api.network.PlayerConnection; -import org.spongepowered.api.network.ServerPlayerConnection; import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.api.network.channel.Channel; import org.spongepowered.api.network.channel.ChannelBuf; @@ -147,14 +144,15 @@ public static Class getConnectionClass(final Eng public static @Nullable H getRequestHandler(final EngineConnection connection, final Map, H> handlersMap) { H handler = null; - if (connection instanceof LocalPlayerConnection) { + //TODO: Fix me + /*if (connection instanceof LocalPlayerConnection) { handler = handlersMap.get(LocalPlayerConnection.class); } else if (connection instanceof ServerPlayerConnection) { handler = handlersMap.get(ServerPlayerConnection.class); } if (handler == null && connection instanceof PlayerConnection) { handler = handlersMap.get(PlayerConnection.class); - } + }*/ if (handler == null) { if (connection instanceof ClientSideConnection) { handler = handlersMap.get(ClientSideConnection.class); diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java index 7a7657a58ac..27f32574c4d 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java @@ -55,9 +55,9 @@ import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.client.MinecraftBridge; import org.spongepowered.common.bridge.network.ConnectionBridge; -import org.spongepowered.common.bridge.network.ConnectionHolderBridge; import org.spongepowered.common.entity.player.ClientType; import org.spongepowered.common.network.PacketUtil; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.packet.SpongeBasicPacketChannel; import org.spongepowered.common.network.channel.packet.SpongePacketChannel; import org.spongepowered.common.network.channel.raw.SpongeRawDataChannel; @@ -201,7 +201,7 @@ private void handleClientType(final EngineConnection connection, final ChannelBu return; } - ((ConnectionBridge) ((ConnectionHolderBridge) connection).bridge$getConnection()).bridge$setClientType(clientType); + ((ConnectionBridge) ((SpongeEngineConnection) connection).connection()).bridge$setClientType(clientType); } /** diff --git a/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java b/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java index 36af16356d0..4a396b657bf 100644 --- a/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java +++ b/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java @@ -41,14 +41,14 @@ */ public final class TransactionStore { - private final Supplier connection; + private final EngineConnection connection; private final ConcurrentMap lookup = Caffeine.newBuilder() .expireAfterAccess(15, TimeUnit.SECONDS) .removalListener((RemovalListener) (key, value, cause) -> { if (cause == RemovalCause.EXPIRED && value != null) { value.getChannel().handleTransactionResponse( - this.getConnection(), value.getData(), TransactionResult.failure(new TimeoutException())); + this.connection(), value.getData(), TransactionResult.failure(new TimeoutException())); } }) .build().asMap(); @@ -72,7 +72,7 @@ public Object getData() { } } - public TransactionStore(final Supplier connection) { + public TransactionStore(final EngineConnection connection) { this.connection = connection; } @@ -81,8 +81,8 @@ public TransactionStore(final Supplier connection) { * * @return The engine connection */ - public EngineConnection getConnection() { - return this.connection.get(); + public EngineConnection connection() { + return this.connection; } /** diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java index 2a3570ee690..4939d5b7368 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java @@ -31,6 +31,7 @@ import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.ClientSideConnection; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; import org.spongepowered.api.network.channel.ChannelIOException; @@ -279,8 +280,8 @@ protected void handleLoginRequestPayload(final EngineConnection connection, fina // A transactional packet binding final SpongeTransactionalPacketBinding, Packet> transactionalBinding = (SpongeTransactionalPacketBinding) binding; - final RequestPacketHandler handler = - (RequestPacketHandler) transactionalBinding.getRequestHandler(connection); + final RequestPacketHandler handler = + (RequestPacketHandler) transactionalBinding.getRequestHandler(connection.state()); boolean success = false; if (handler != null) { final SpongeRequestPacketResponse response = new SpongeRequestPacketResponse() { @@ -305,7 +306,7 @@ protected void success0(final Packet response) { } }; try { - handler.handleRequest(packet, connection, response); + handler.handleRequest(packet, connection.state(), response); success = true; } catch (final Throwable ex) { this.handleException(connection, new ChannelIOException("Failed to handle request packet", ex), null); diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java index 930c8eca000..03fd869c3c6 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java @@ -30,6 +30,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; @@ -337,7 +338,7 @@ private void handleResponsePacket(final EngineConnection connection, final int t this.handleTransactionResponse(connection, transactionData, result, dynamicOpcode); } - private void handleRequestPacket(final C connection, + private void handleRequestPacket(final EngineConnection connection, final int opcode, final int transactionId, final ChannelBuf payload) { final SpongePacketBinding binding = this.requireBinding(opcode); @@ -355,8 +356,8 @@ private void handleRequestPacket(final C connection // TODO: Send cause of failure somehow? if (binding instanceof SpongeTransactionalPacketBinding) { - final RequestPacketHandler, Packet, C> handler = - ((SpongeTransactionalPacketBinding) binding).getRequestHandler(connection); + final RequestPacketHandler, Packet, ? super EngineConnectionState> handler = + ((SpongeTransactionalPacketBinding) binding).getRequestHandler(connection.state()); if (handler != null) { final SpongeRequestPacketResponse requestPacketResponse = new SpongeRequestPacketResponse() { @@ -373,7 +374,7 @@ protected void success0(final Packet response) { } }; try { - handler.handleRequest((RequestPacket) request, connection, requestPacketResponse); + handler.handleRequest((RequestPacket) request, connection.state(), requestPacketResponse); success = true; } catch (final Throwable ex) { this.handleException(connection, new ChannelException("Failed to handle request packet", ex), null); diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java index 90bfed9eb3f..1404cc24e84 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java @@ -27,6 +27,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.packet.Packet; import org.spongepowered.api.network.channel.packet.PacketHandler; import org.spongepowered.api.network.channel.packet.RequestPacket; @@ -53,20 +54,14 @@ public SpongeTransactionalPacketBinding(final int opcode, final Class

request super(opcode, requestPacketType); } - public @Nullable RequestPacketHandler getRequestHandler(final C connection) { - return (RequestPacketHandler) SpongeChannel.getRequestHandler(connection, this.requestHandlers); + public @Nullable RequestPacketHandler getRequestHandler(final S connection) { + return null; //TODO: fix me + //return (RequestPacketHandler) SpongeChannel.getRequestHandler(connection, this.requestHandlers); } @Override - public TransactionalPacketBinding setRequestHandler( - final EngineConnectionSide side, final RequestPacketHandler handler) { - Objects.requireNonNull(side, "side"); - return this.setRequestHandler(SpongeChannel.getConnectionClass(side), handler); - } - - @Override - public TransactionalPacketBinding setRequestHandler(final Class connectionType, - final RequestPacketHandler handler) { + public TransactionalPacketBinding setRequestHandler(final Class connectionType, + final RequestPacketHandler handler) { Objects.requireNonNull(connectionType, "connectionType"); Objects.requireNonNull(handler, "handler"); this.requestHandlers.put(connectionType, handler); @@ -74,9 +69,9 @@ public TransactionalPacketBinding setRequestH } @Override - public TransactionalPacketBinding setRequestHandler(final RequestPacketHandler handler) { + public TransactionalPacketBinding setRequestHandler(final RequestPacketHandler handler) { Objects.requireNonNull(handler, "handler"); - return this.setRequestHandler(EngineConnection.class, handler); + return this.setRequestHandler(EngineConnectionState.class, handler); } @Override diff --git a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java index 52140483488..3a4cee69aa0 100644 --- a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java +++ b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java @@ -34,7 +34,7 @@ import org.spongepowered.api.ResourceKey; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.network.ClientSideConnection; -import org.spongepowered.api.network.EngineConnectionTypes; +import org.spongepowered.api.network.EngineConnectionStates; import org.spongepowered.api.network.channel.packet.PacketChannel; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.CreatorTrackedBridge; @@ -54,7 +54,7 @@ public final class SpongePacketHandler { public static void init(final SpongeChannelManager registry) { SpongePacketHandler.channel = registry.createChannel(ResourceKey.sponge("default"), PacketChannel.class); SpongePacketHandler.channel.registerTransactional(RequestBlockTrackerDataPacket.class, TrackerDataResponsePacket.class, 0) - .setRequestHandler(EngineConnectionTypes.SERVER_PLAYER, (requestPacket, connection, response) -> { + .setRequestHandler(EngineConnectionStates.SERVER_GAME, (requestPacket, connection, response) -> { final ServerPlayer player = connection.player(); if (!player.hasPermission("sponge.debug.block-tracking")) { return; @@ -73,7 +73,7 @@ public static void init(final SpongeChannelManager registry) { response.success(SpongePacketHandler.createTrackerDataResponse(owner, notifier)); }); SpongePacketHandler.channel.registerTransactional(RequestEntityTrackerDataPacket.class, TrackerDataResponsePacket.class, 1) - .setRequestHandler(EngineConnectionTypes.SERVER_PLAYER, (requestPacket, connection, response) -> { + .setRequestHandler(EngineConnectionStates.SERVER_GAME, (requestPacket, connection, response) -> { final ServerPlayer player = connection.player(); if (!player.hasPermission("sponge.debug.entity-tracking")) { return; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java index 7215790fc65..f26f2edb284 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/ServerPlayerMixin_API.java @@ -41,6 +41,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; +import net.minecraft.network.Connection; import net.minecraft.network.chat.ChatType; import net.minecraft.network.chat.MessageSignature; import net.minecraft.network.chat.PlayerChatMessage; @@ -85,7 +86,7 @@ import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.message.PlayerChatEvent; import org.spongepowered.api.event.world.ChangeWorldBorderEvent; -import org.spongepowered.api.network.ServerPlayerConnection; +import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.resourcepack.ResourcePack; import org.spongepowered.api.scoreboard.Scoreboard; @@ -102,6 +103,7 @@ import org.spongepowered.common.accessor.server.network.ServerGamePacketListenerImplAccessor; import org.spongepowered.common.accessor.world.level.border.WorldBorderAccessor; import org.spongepowered.common.adventure.SpongeAdventure; +import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.server.PlayerAdvancementsBridge; import org.spongepowered.common.bridge.server.ServerScoreboardBridge; import org.spongepowered.common.bridge.server.level.ServerPlayerBridge; @@ -212,8 +214,9 @@ public void spawnParticles(final ParticleEffect particleEffect, final Vector3d p } @Override - public ServerPlayerConnection connection() { - return (ServerPlayerConnection) this.connection; + public ServerSideConnection connection() { + final Connection connection = ((ServerCommonPacketListenerImplAccessor) this.connection).accessor$connection(); + return (ServerSideConnection) ((ConnectionBridge) connection).bridge$getEngineConnection(); } /** diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java deleted file mode 100644 index 74b86409068..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.minecraft.server.network; - -import net.kyori.adventure.text.Component; -import net.minecraft.network.Connection; -import net.minecraft.server.network.ServerCommonPacketListenerImpl; -import org.spongepowered.api.network.ServerSideConnection; -import org.spongepowered.api.profile.GameProfile; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.adventure.SpongeAdventure; -import org.spongepowered.common.bridge.network.ConnectionBridge; -import org.spongepowered.common.profile.SpongeGameProfile; - -import java.net.InetSocketAddress; -import java.util.Objects; - -@Mixin(value = ServerCommonPacketListenerImpl.class, priority = 999) -public abstract class ServerCommonPacketListenerImplMixin_API implements ServerSideConnection { - - // @formatter:off - @Shadow @Final public Connection connection; - - @Shadow public abstract void shadow$disconnect(net.minecraft.network.chat.Component reason); - @Shadow protected abstract com.mojang.authlib.GameProfile playerProfile(); - // @formatter:on - - @Override - public void close() { - this.shadow$disconnect(net.minecraft.network.chat.Component.translatable("disconnect.disconnected")); - } - - @Override - public void close(final Component reason) { - Objects.requireNonNull(reason, "reason"); - this.shadow$disconnect(SpongeAdventure.asVanilla(reason)); - } - - @Override - public InetSocketAddress address() { - return ((ConnectionBridge) this.connection).bridge$getAddress(); - } - - @Override - public InetSocketAddress virtualHost() { - return ((ConnectionBridge) this.connection).bridge$getVirtualHost(); - } - - @Override - public GameProfile profile() { - return SpongeGameProfile.of(this.playerProfile()); - } - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java deleted file mode 100644 index c48e18dc847..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.minecraft.server.network; - -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.network.ServerPlayerConnection; -import org.spongepowered.api.profile.GameProfile; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.profile.SpongeGameProfile; - -@Mixin(ServerGamePacketListenerImpl.class) -public abstract class ServerGamePacketListenerImplMixin_API extends ServerCommonPacketListenerImplMixin_API implements ServerPlayerConnection { - - // @formatter:off - @Shadow public net.minecraft.server.level.ServerPlayer player; - // @formatter:on - - @Override - public GameProfile profile() { - return SpongeGameProfile.of(this.player.getGameProfile()); - } - - @Override - public ServerPlayer player() { - return (ServerPlayer) this.player; - } - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java similarity index 69% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java index b8f5ab880ee..e5289f67c73 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java @@ -22,18 +22,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.common.mixin.api.minecraft.client.multiplayer; +package org.spongepowered.common.mixin.api.minecraft.server.network; -import net.minecraft.client.multiplayer.ClientPacketListener; -import org.spongepowered.api.entity.living.player.client.LocalPlayer; -import org.spongepowered.api.network.LocalPlayerConnection; +import net.minecraft.server.network.ServerHandshakePacketListenerImpl; +import org.spongepowered.api.network.ServerConnectionIntentState; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.common.bridge.server.network.ServerHandshakePacketListenerImplBridge; -@Mixin(ClientPacketListener.class) -public abstract class ClientPacketListenerMixin_API extends ClientCommonPacketListenerImpl_API implements LocalPlayerConnection { +@Mixin(ServerHandshakePacketListenerImpl.class) +public abstract class ServerHandshakePacketListenerImplMixin_API implements ServerConnectionIntentState { @Override - public LocalPlayer player() { - return (LocalPlayer) this.minecraft.player; + public boolean transferred() { + return ((ServerHandshakePacketListenerImplBridge) this).bridge$transferred(); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java deleted file mode 100644 index 676a699e779..00000000000 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.common.mixin.api.minecraft.server.network; - - -import net.kyori.adventure.text.Component; -import net.minecraft.network.Connection; -import net.minecraft.server.network.ServerLoginPacketListenerImpl; -import org.spongepowered.api.network.ServerSideConnection; -import org.spongepowered.api.profile.GameProfile; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.common.adventure.SpongeAdventure; -import org.spongepowered.common.bridge.network.ConnectionBridge; -import org.spongepowered.common.profile.SpongeGameProfile; - -import java.net.InetSocketAddress; -import java.util.Objects; - - -@Mixin(ServerLoginPacketListenerImpl.class) -public abstract class ServerLoginPacketListenerImplMixin_API implements ServerSideConnection { - - // @formatter:off - @Shadow @Final public Connection connection; - @Shadow private com.mojang.authlib.GameProfile authenticatedProfile; - @Shadow public abstract void shadow$disconnect(net.minecraft.network.chat.Component reason); - // @formatter:on - - @Override - public void close() { - this.shadow$disconnect(net.minecraft.network.chat.Component.translatable("disconnect.disconnected")); - } - - @Override - public void close(final Component reason) { - Objects.requireNonNull(reason, "reason"); - this.shadow$disconnect(SpongeAdventure.asVanilla(reason)); - } - - @Override - public InetSocketAddress address() { - return ((ConnectionBridge) this.connection).bridge$getAddress(); - } - - @Override - public InetSocketAddress virtualHost() { - return ((ConnectionBridge) this.connection).bridge$getVirtualHost(); - } - - @Override - public GameProfile profile() { - return SpongeGameProfile.of(this.authenticatedProfile); - } - -} diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java index cdff6403cc7..9bed10f3a67 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java @@ -35,6 +35,7 @@ import net.minecraft.network.PacketSendListener; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; import org.checkerframework.checker.nullness.qual.Nullable; import org.objectweb.asm.Opcodes; import org.spongepowered.api.MinecraftVersion; @@ -52,7 +53,10 @@ import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.entity.player.ClientType; +import org.spongepowered.common.network.SpongeClientEngineConnection; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.SpongePacketHolder; +import org.spongepowered.common.network.SpongeServerEngineConnection; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.TransactionStore; import org.spongepowered.common.util.Constants; @@ -75,7 +79,7 @@ public abstract class ConnectionMixin extends SimpleChannelInboundHandler> pendingActions; @Shadow public abstract SocketAddress getRemoteAddress(); - private final TransactionStore impl$transactionStore = new TransactionStore(() -> (EngineConnection) this.packetListener); + private TransactionStore impl$transactionStore; private final Set impl$registeredChannels = Sets.newConcurrentHashSet(); @Nullable private InetSocketAddress impl$virtualHost; @@ -86,6 +90,8 @@ public abstract class ConnectionMixin extends SimpleChannelInboundHandler { - final EngineConnection connection = (EngineConnection) this; + final EngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); if (!channelRegistry.handleLoginRequestPayload(connection, packet)) { PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, packet.transactionId())); } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java index 3ca8d5cd2bb..85af2426f53 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java @@ -24,24 +24,32 @@ */ package org.spongepowered.vanilla.mixin.core.client.multiplayer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.CommonListenerCookie; +import net.minecraft.network.Connection; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.game.ClientGamePacketListener; import org.spongepowered.api.Sponge; -import org.spongepowered.api.network.EngineConnection; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.network.channel.SpongeChannelManager; @Mixin(ClientPacketListener.class) -public abstract class ClientPacketListenerMixin_Vanilla implements ClientGamePacketListener { +public abstract class ClientPacketListenerMixin_Vanilla extends ClientCommonPacketListenerImpl implements ClientGamePacketListener { + + protected ClientPacketListenerMixin_Vanilla(Minecraft $$0, Connection $$1, CommonListenerCookie $$2) { + super($$0, $$1, $$2); + } @Inject(method = "handleCustomPayload", cancellable = true, at = @At(value = "HEAD")) private void vanilla$handleCustomPayload(final CustomPacketPayload packet, CallbackInfo ci) { final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - if (channelRegistry.handlePlayPayload((EngineConnection) this, packet)) { + if (channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet)) { ci.cancel(); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java index d5161e11aa5..2577017f142 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/FriendlyByteBufMixin_Vanilla.java @@ -24,12 +24,8 @@ */ package org.spongepowered.vanilla.mixin.core.network; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.bridge.network.FriendlyByteBufBridge; @Mixin(FriendlyByteBuf.class) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java index 0fe5541a66e..7812c9d2ccf 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java @@ -24,17 +24,18 @@ */ package org.spongepowered.vanilla.mixin.core.server.network; +import net.minecraft.network.Connection; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerCommonPacketListenerImpl; import org.spongepowered.api.Sponge; -import org.spongepowered.api.network.EngineConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.network.channel.SpongeChannelManager; @Mixin(value = ServerCommonPacketListenerImpl.class, priority = 999) @@ -42,11 +43,12 @@ public abstract class ServerCommonPacketListenerImplMixin_Vanilla { // @formatter: off @Shadow @Final protected MinecraftServer server; + @Shadow @Final protected Connection connection; // @formatter: on @Inject(method = "handleCustomPayload", at = @At(value = "HEAD")) private void vanilla$onHandleCustomPayload(final ServerboundCustomPayloadPacket packet, final CallbackInfo ci) { final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - this.server.execute(() -> channelRegistry.handlePlayPayload((EngineConnection) this, packet.payload())); + this.server.execute(() -> channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet.payload())); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java index 81ff455568f..a1b2325e913 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerGamePacketListenerImplMixin_Vanilla.java @@ -24,22 +24,15 @@ */ package org.spongepowered.vanilla.mixin.core.server.network; -import net.minecraft.network.chat.LastSeenMessages; import net.minecraft.network.protocol.game.ServerGamePacketListener; -import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; -import net.minecraft.network.protocol.game.ServerboundInteractPacket; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.inventory.RecipeBookMenu; import net.minecraft.world.item.crafting.RecipeHolder; import org.checkerframework.checker.nullness.qual.NonNull; -import org.spongepowered.api.event.CauseStackManager; -import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.crafting.CraftingInventory; import org.spongepowered.api.item.inventory.query.QueryTypes; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.SpongeCommon; @@ -47,7 +40,6 @@ import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.context.transaction.EffectTransactor; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; -import org.spongepowered.common.hooks.PlatformHooks; @Mixin(value = ServerGamePacketListenerImpl.class, priority = 999) public abstract class ServerGamePacketListenerImplMixin_Vanilla extends ServerCommonPacketListenerImplMixin_Vanilla implements ServerGamePacketListener { diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java index acfa9e6bc8b..da7f7d41a8f 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java @@ -44,7 +44,6 @@ import org.spongepowered.api.event.EventContext; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.network.ServerSideConnectionEvent; -import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -54,6 +53,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.network.ServerLoginPacketListenerImplBridge; import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.SpongeChannelManager; @@ -104,13 +104,13 @@ public abstract class ServerLoginPacketListenerImplMixin_Vanilla implements Serv ci.cancel(); final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - this.server.execute(() -> channelRegistry.handleLoginResponsePayload((EngineConnection) this, packet)); + this.server.execute(() -> channelRegistry.handleLoginResponsePayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet)); } @Inject(method = "tick", at = @At("HEAD")) private void impl$onTick(final CallbackInfo ci) { if (this.state == ServerLoginPacketListenerImpl.State.NEGOTIATING) { - final ServerSideConnection connection = (ServerSideConnection) this; + final ServerSideConnection connection = (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection(); if (this.impl$handshakeState == ServerLoginPacketListenerImplMixin_Vanilla.HANDSHAKE_NOT_STARTED) { this.impl$handshakeState = ServerLoginPacketListenerImplMixin_Vanilla.HANDSHAKE_CLIENT_TYPE; diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java index 91b20ec2029..96bcec8a4de 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java @@ -24,16 +24,10 @@ */ package org.spongepowered.vanilla.mixin.core.server.network.protocol.common; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ServerboundCustomPayloadPacket.class) public abstract class ServerboundCustomPayloadPacketMixin_Vanilla { diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java index 17b1d205a5e..77740256098 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/inventory/event/world/level/block/entity/HopperBlockEntityMixin_Inventory_Vanilla.java @@ -30,7 +30,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.HopperBlockEntity; -import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.transaction.SlotTransaction; import org.spongepowered.asm.mixin.Mixin; From 97a409a1607a71f9e5abe41dee20870bcc623e16 Mon Sep 17 00:00:00 2001 From: aromaa Date: Mon, 13 May 2024 17:26:07 +0300 Subject: [PATCH 217/230] Finish up the changes to EngineConnection and ServerSideConnectionEvent --- SpongeAPI | 2 +- .../ServerLoginPacketListenerImplBridge.java | 2 - .../network/SpongeEngineConnection.java | 69 ++++++- .../packet/SpongeBasicPacketChannel.java | 8 +- .../channel/packet/SpongePacketChannel.java | 9 +- ...entCommonPacketListenerImplMixin_API.java} | 14 +- ...figurationPacketListenerImplMixin_API.java | 46 +++++ ...tHandshakePacketListenerImplMixin_API.java | 53 ++++++ .../ClientPacketListenerMixin_API.java | 52 +++++ ...rHandshakePacketListenerImplMixin_API.java | 39 ++++ ...rverCommonPacketListenerImplMixin_API.java | 48 +++++ ...figurationPacketListenerImplMixin_API.java | 40 ++++ ...ServerGamePacketListenerImplMixin_API.java | 60 ++++++ ...rHandshakePacketListenerImplMixin_API.java | 4 +- ...erverLoginPacketListenerImplMixin_API.java | 52 +++++ .../rcon/RconConsoleSourceMixin_API.java | 5 + .../mixin/core/network/ConnectionMixin.java | 13 +- ...erverHandshakePacketListenerImplMixin.java | 14 +- .../ServerCommonPacketListenerImplMixin.java | 2 + ...rConfigurationPacketListenerImplMixin.java | 60 +++++- .../ServerGamePacketListenerImplMixin.java | 9 +- ...erverHandshakePacketListenerImplMixin.java | 26 +-- .../ServerLoginPacketListenerImplMixin.java | 65 +++++-- .../core/server/players/PlayerListMixin.java | 5 +- src/mixins/resources/mixins.sponge.api.json | 10 +- .../test/connection/ConnectionTests.java | 179 ++++++++++++++++++ .../resources/META-INF/sponge_plugins.json | 6 + ...rLoginPacketListenerImplMixin_Vanilla.java | 4 +- 28 files changed, 821 insertions(+), 75 deletions(-) rename src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/{ClientCommonPacketListenerImpl_API.java => ClientCommonPacketListenerImplMixin_API.java} (83%) create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientConfigurationPacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientHandshakePacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/MemoryServerHandshakePacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerConfigurationPacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java create mode 100644 src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java create mode 100644 testplugins/src/main/java/org/spongepowered/test/connection/ConnectionTests.java diff --git a/SpongeAPI b/SpongeAPI index a459a98f095..3a01dbfd7c2 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit a459a98f0955c84398f0824175ccafec2c84c2b7 +Subproject commit 3a01dbfd7c2a262fcc3eb5f07c6de317c46ea870 diff --git a/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java b/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java index fae43a92b9a..0b82d04bb67 100644 --- a/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java +++ b/src/main/java/org/spongepowered/common/bridge/network/ServerLoginPacketListenerImplBridge.java @@ -32,7 +32,5 @@ public interface ServerLoginPacketListenerImplBridge { ExecutorService bridge$getExecutor(); - void bridge$fireAuthEvent(); - Connection bridge$getConnection(); } diff --git a/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java b/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java index e866b8a6ff1..9271f8d1f7e 100644 --- a/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java +++ b/src/main/java/org/spongepowered/common/network/SpongeEngineConnection.java @@ -24,26 +24,51 @@ */ package org.spongepowered.common.network; +import com.mojang.authlib.GameProfile; import net.kyori.adventure.text.Component; import net.minecraft.network.Connection; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import org.spongepowered.api.event.Cancellable; +import org.spongepowered.api.event.SpongeEventFactory; +import org.spongepowered.api.event.network.ServerSideConnectionEvent; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionState; +import org.spongepowered.api.network.ServerSideConnection; +import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.ConnectionBridge; +import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.profile.SpongeGameProfile; import java.net.InetSocketAddress; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; public abstract class SpongeEngineConnection implements EngineConnection { protected final Connection connection; + private final AtomicReference eventFireState; + + private @MonotonicNonNull GameProfile gameProfile; + public SpongeEngineConnection(final Connection connection) { this.connection = connection; + + this.eventFireState = new AtomicReference<>(EventFireState.NONE); } @Override - public EngineConnectionState state() { - return (EngineConnectionState) this.connection.getPacketListener(); + public boolean active() { + return this.connection.isConnected(); + } + + @Override + public Optional state() { + if (this.active()) { + return Optional.of((EngineConnectionState) this.connection.getPacketListener()); + } + return Optional.empty(); } @Override @@ -66,7 +91,47 @@ public void close(final Component reason) { this.connection.disconnect(SpongeAdventure.asVanilla(reason)); } + public void setGameProfile(final GameProfile gameProfile) { + this.gameProfile = gameProfile; + } + public Connection connection() { return this.connection; } + + public void disconnected() { + if (this.eventFireState.getAndSet(EventFireState.DISCONNECTED).shouldFireDisconnectionImmediately()) { + this.fireDisconnectEvent(); + } + } + + public boolean postGuardedEvent(final ServerSideConnectionEvent event) { + if (!this.eventFireState.compareAndSet(EventFireState.NONE, EventFireState.IN_FLIGHT) + && !this.eventFireState.compareAndSet(EventFireState.POST, EventFireState.IN_FLIGHT)) { + return false; + } + SpongeCommon.post(event); + if (!this.eventFireState.compareAndSet(EventFireState.IN_FLIGHT, EventFireState.POST)) { + this.fireDisconnectEvent(); + } + return event instanceof Cancellable cancellable && cancellable.isCancelled(); + } + + private void fireDisconnectEvent() { + this.eventFireState.set(EventFireState.DISCONNECTED); + final ServerSideConnectionEvent.Disconnect event = SpongeEventFactory.createServerSideConnectionEventDisconnect( + PhaseTracker.getCauseStackManager().currentCause(), (ServerSideConnection) this, Optional.ofNullable(this.gameProfile).map(SpongeGameProfile::of)); + SpongeCommon.post(event); + } + + private enum EventFireState { + NONE, + IN_FLIGHT, + POST, + DISCONNECTED; + + boolean shouldFireDisconnectionImmediately() { + return this == EventFireState.POST; + } + } } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java index 4939d5b7368..627d44966a0 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java @@ -265,6 +265,10 @@ protected void handlePlayPayload(final EngineConnection connection, final Channe protected void handleLoginRequestPayload(final EngineConnection connection, final int transactionId, final ChannelBuf payload) { // Is currently always executed on the client, // the server always expects a response + final @Nullable EngineConnectionState state = connection.state().orElse(null); + if (state == null) { + return; + } final int opcode = this.readOpcode(payload); final SpongePacketBinding binding = this.requireBinding(opcode); @@ -281,7 +285,7 @@ protected void handleLoginRequestPayload(final EngineConnection connection, fina final SpongeTransactionalPacketBinding, Packet> transactionalBinding = (SpongeTransactionalPacketBinding) binding; final RequestPacketHandler handler = - (RequestPacketHandler) transactionalBinding.getRequestHandler(connection.state()); + (RequestPacketHandler) transactionalBinding.getRequestHandler(state); boolean success = false; if (handler != null) { final SpongeRequestPacketResponse response = new SpongeRequestPacketResponse() { @@ -306,7 +310,7 @@ protected void success0(final Packet response) { } }; try { - handler.handleRequest(packet, connection.state(), response); + handler.handleRequest(packet, state, response); success = true; } catch (final Throwable ex) { this.handleException(connection, new ChannelIOException("Failed to handle request packet", ex), null); diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java index 03fd869c3c6..6aa08e36256 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java @@ -340,6 +340,11 @@ private void handleResponsePacket(final EngineConnection connection, final int t private void handleRequestPacket(final EngineConnection connection, final int opcode, final int transactionId, final ChannelBuf payload) { + final @Nullable EngineConnectionState state = connection.state().orElse(null); + if (state == null) { + return; + } + final SpongePacketBinding binding = this.requireBinding(opcode); final Packet request; @@ -357,7 +362,7 @@ private void handleRequestPacket(final EngineConnection connection, // TODO: Send cause of failure somehow? if (binding instanceof SpongeTransactionalPacketBinding) { final RequestPacketHandler, Packet, ? super EngineConnectionState> handler = - ((SpongeTransactionalPacketBinding) binding).getRequestHandler(connection.state()); + ((SpongeTransactionalPacketBinding) binding).getRequestHandler(state); if (handler != null) { final SpongeRequestPacketResponse requestPacketResponse = new SpongeRequestPacketResponse() { @@ -374,7 +379,7 @@ protected void success0(final Packet response) { } }; try { - handler.handleRequest((RequestPacket) request, connection.state(), requestPacketResponse); + handler.handleRequest((RequestPacket) request, state, requestPacketResponse); success = true; } catch (final Throwable ex) { this.handleException(connection, new ChannelException("Failed to handle request packet", ex), null); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImpl_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImplMixin_API.java similarity index 83% rename from src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImpl_API.java rename to src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImplMixin_API.java index 9b894b53ce0..2a3a30381d4 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImpl_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientCommonPacketListenerImplMixin_API.java @@ -26,13 +26,21 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; -import net.minecraft.network.Connection; +import org.spongepowered.api.network.ClientConnectionState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(ClientCommonPacketListenerImpl.class) -public abstract class ClientCommonPacketListenerImpl_API { - @Shadow @Final protected Connection connection; +public abstract class ClientCommonPacketListenerImplMixin_API implements ClientConnectionState { + + // @formatter:off @Shadow @Final protected Minecraft minecraft; + @Shadow protected boolean isTransferring; + // @formatter:on + + @Override + public boolean transferred() { + return this.isTransferring; + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientConfigurationPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientConfigurationPacketListenerImplMixin_API.java new file mode 100644 index 00000000000..e9458e8535e --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientConfigurationPacketListenerImplMixin_API.java @@ -0,0 +1,46 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.client.multiplayer; + +import net.minecraft.client.multiplayer.ClientConfigurationPacketListenerImpl; +import org.spongepowered.api.network.ClientConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ClientConfigurationPacketListenerImpl.class) +public abstract class ClientConfigurationPacketListenerImplMixin_API extends ClientCommonPacketListenerImplMixin_API implements ClientConnectionState.Configuration { + + // @formatter:off + @Shadow @Final private com.mojang.authlib.GameProfile localGameProfile; + // @formatter:on + + @Override + public GameProfile profile() { + return SpongeGameProfile.of(this.localGameProfile); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientHandshakePacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientHandshakePacketListenerImplMixin_API.java new file mode 100644 index 00000000000..78381018197 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientHandshakePacketListenerImplMixin_API.java @@ -0,0 +1,53 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.client.multiplayer; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; +import org.spongepowered.api.network.ClientConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ClientHandshakePacketListenerImpl.class) +public abstract class ClientHandshakePacketListenerImplMixin_API implements ClientConnectionState.Login { + + // @formatter:off + @Shadow @Final private Minecraft minecraft; + @Shadow @Final private boolean wasTransferredTo; + // @formatter:on + + @Override + public boolean transferred() { + return this.wasTransferredTo; + } + + @Override + public GameProfile profile() { + return new SpongeGameProfile(this.minecraft.getUser().getProfileId(), this.minecraft.getUser().getName()); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java new file mode 100644 index 00000000000..1635a97f22f --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/client/multiplayer/ClientPacketListenerMixin_API.java @@ -0,0 +1,52 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.client.multiplayer; + +import net.minecraft.client.multiplayer.ClientPacketListener; +import org.spongepowered.api.entity.living.player.client.LocalPlayer; +import org.spongepowered.api.network.EngineConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ClientPacketListener.class) +public class ClientPacketListenerMixin_API extends ClientCommonPacketListenerImplMixin_API implements EngineConnectionState.Game { + + // @formatter:off + @Shadow @Final private com.mojang.authlib.GameProfile localGameProfile; + // @formatter:on + + @Override + public GameProfile profile() { + return SpongeGameProfile.of(this.localGameProfile); + } + + @Override + public LocalPlayer player() { + return (LocalPlayer) this.minecraft.player; + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/MemoryServerHandshakePacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/MemoryServerHandshakePacketListenerImplMixin_API.java new file mode 100644 index 00000000000..d4ddc203ff5 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/MemoryServerHandshakePacketListenerImplMixin_API.java @@ -0,0 +1,39 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.server.network; + +import net.minecraft.server.network.MemoryServerHandshakePacketListenerImpl; +import org.spongepowered.api.network.ServerConnectionState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.common.bridge.server.network.ServerHandshakePacketListenerImplBridge; + +@Mixin(MemoryServerHandshakePacketListenerImpl.class) +public abstract class MemoryServerHandshakePacketListenerImplMixin_API implements ServerConnectionState.Intent { + + @Override + public boolean transferred() { + return ((ServerHandshakePacketListenerImplBridge) this).bridge$transferred(); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java new file mode 100644 index 00000000000..cfdfed03801 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerCommonPacketListenerImplMixin_API.java @@ -0,0 +1,48 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.server.network; + +import com.mojang.authlib.GameProfile; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import org.spongepowered.api.network.EngineConnectionState; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(ServerCommonPacketListenerImpl.class) +public abstract class ServerCommonPacketListenerImplMixin_API implements EngineConnectionState { + + // @formatter:off + @Shadow @Final private boolean transferred; + + @Shadow protected abstract GameProfile shadow$playerProfile(); + @Shadow public abstract int shadow$latency(); + // @formatter:on + + @Override + public boolean transferred() { + return this.transferred; + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerConfigurationPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerConfigurationPacketListenerImplMixin_API.java new file mode 100644 index 00000000000..273b110b4cc --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerConfigurationPacketListenerImplMixin_API.java @@ -0,0 +1,40 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.server.network; + +import net.minecraft.server.network.ServerConfigurationPacketListenerImpl; +import org.spongepowered.api.network.ServerConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ServerConfigurationPacketListenerImpl.class) +public abstract class ServerConfigurationPacketListenerImplMixin_API extends ServerCommonPacketListenerImplMixin_API implements ServerConnectionState.Configuration { + + @Override + public GameProfile profile() { + return SpongeGameProfile.of(this.shadow$playerProfile()); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java new file mode 100644 index 00000000000..3422a315dc0 --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerGamePacketListenerImplMixin_API.java @@ -0,0 +1,60 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.server.network; + +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.api.entity.living.player.server.ServerPlayer; +import org.spongepowered.api.network.ServerConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Implements; +import org.spongepowered.asm.mixin.Interface; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ServerGamePacketListenerImpl.class) +@Implements(@Interface(iface = ServerConnectionState.Game.class, prefix = "api$", remap = Interface.Remap.NONE)) +public abstract class ServerGamePacketListenerImplMixin_API extends ServerCommonPacketListenerImplMixin_API implements ServerConnectionState.Game { + + // @formatter:off + @Shadow public net.minecraft.server.level.ServerPlayer player; + // @formatter:on + + @Override + public GameProfile profile() { + return SpongeGameProfile.of(this.shadow$playerProfile()); + } + + @Override + public ServerPlayer player() { + return (ServerPlayer) this.player; + } + + //TODO: Fix me + /*@Intrinsic + public int api$latency() { + return this.shadow$latency(); + }*/ +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java index e5289f67c73..7ea296d8697 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerHandshakePacketListenerImplMixin_API.java @@ -25,12 +25,12 @@ package org.spongepowered.common.mixin.api.minecraft.server.network; import net.minecraft.server.network.ServerHandshakePacketListenerImpl; -import org.spongepowered.api.network.ServerConnectionIntentState; +import org.spongepowered.api.network.ServerConnectionState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.bridge.server.network.ServerHandshakePacketListenerImplBridge; @Mixin(ServerHandshakePacketListenerImpl.class) -public abstract class ServerHandshakePacketListenerImplMixin_API implements ServerConnectionIntentState { +public abstract class ServerHandshakePacketListenerImplMixin_API implements ServerConnectionState.Intent { @Override public boolean transferred() { diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java new file mode 100644 index 00000000000..f26b8b379da --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/network/ServerLoginPacketListenerImplMixin_API.java @@ -0,0 +1,52 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.api.minecraft.server.network; + +import net.minecraft.server.network.ServerLoginPacketListenerImpl; +import org.spongepowered.api.network.ServerConnectionState; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.common.profile.SpongeGameProfile; + +@Mixin(ServerLoginPacketListenerImpl.class) +public abstract class ServerLoginPacketListenerImplMixin_API implements ServerConnectionState.Login { + + // @formatter:off + @Shadow private com.mojang.authlib.GameProfile authenticatedProfile; + @Shadow @Final private boolean transferred; + // @formatter:on + + @Override + public boolean transferred() { + return this.transferred; + } + + @Override + public GameProfile profile() { + return SpongeGameProfile.of(this.authenticatedProfile); + } +} diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/rcon/RconConsoleSourceMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/rcon/RconConsoleSourceMixin_API.java index 9701717736e..6bbc9c153ba 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/rcon/RconConsoleSourceMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/rcon/RconConsoleSourceMixin_API.java @@ -94,4 +94,9 @@ public void sendMessage(final @NonNull Identity identity, final @NonNull Compone public @NonNull Pointers pointers() { return RconConsoleSourceMixin_API.API$POINTERS; } + + @Override + public boolean active() { + return this.bridge$getClient().isRunning(); + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java index 9bed10f3a67..9a1949fa806 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java @@ -40,7 +40,10 @@ import org.objectweb.asm.Opcodes; import org.spongepowered.api.MinecraftVersion; import org.spongepowered.api.ResourceKey; +import org.spongepowered.api.event.SpongeEventFactory; +import org.spongepowered.api.event.network.ServerSideConnectionEvent; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -53,12 +56,14 @@ import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.entity.player.ClientType; +import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.network.SpongeClientEngineConnection; import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.SpongePacketHolder; import org.spongepowered.common.network.SpongeServerEngineConnection; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.TransactionStore; +import org.spongepowered.common.profile.SpongeGameProfile; import org.spongepowered.common.util.Constants; import java.io.IOException; @@ -208,13 +213,9 @@ public void accept(final Connection connection) { return instance.add(consumer); } - @Inject(method = "handleDisconnection", - at = @At( - value = "FIELD", - target = "Lnet/minecraft/network/Connection;disconnectionHandled:Z", - opcode = Opcodes.PUTFIELD, - shift = At.Shift.AFTER)) + @Inject(method = "handleDisconnection", at = @At("RETURN")) private void impl$onDisconnected(final CallbackInfo ci) { + this.impl$engineConnection.disconnected(); Consumer consumer; while ((consumer = this.pendingActions.poll()) != null) { if (consumer instanceof SpongePacketHolder packetHolder) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/MemoryServerHandshakePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/MemoryServerHandshakePacketListenerImplMixin.java index 4369a7a78e2..681cca073a2 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/MemoryServerHandshakePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/MemoryServerHandshakePacketListenerImplMixin.java @@ -26,10 +26,8 @@ import net.kyori.adventure.text.Component; import net.minecraft.network.Connection; -import net.minecraft.network.protocol.handshake.ClientIntentionPacket; import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; import net.minecraft.network.protocol.login.LoginProtocols; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.MemoryServerHandshakePacketListenerImpl; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.network.ServerSideConnectionEvent; @@ -39,13 +37,12 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.server.network.ServerHandshakePacketListenerImplBridge; import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.network.SpongeEngineConnection; @Mixin(MemoryServerHandshakePacketListenerImpl.class) public abstract class MemoryServerHandshakePacketListenerImplMixin implements ServerHandshakePacketListenerImplBridge { @@ -61,14 +58,11 @@ public abstract class MemoryServerHandshakePacketListenerImplMixin implements Se target = "Lnet/minecraft/network/Connection;setupInboundProtocol(Lnet/minecraft/network/ProtocolInfo;Lnet/minecraft/network/PacketListener;)V"), cancellable = true) private void impl$onLogin(final CallbackInfo ci) { + final SpongeEngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); final Component message = Component.text("You are not allowed to log in to this server."); final ServerSideConnectionEvent.Intent event = SpongeEventFactory.createServerSideConnectionEventIntent( - PhaseTracker.getCauseStackManager().currentCause(), - message, - message, - (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection(), - true); - if (SpongeCommon.post(event)) { + PhaseTracker.getCauseStackManager().currentCause(), message, message, (ServerSideConnection) connection, false); + if (connection.postGuardedEvent(event)) { ci.cancel(); final net.minecraft.network.chat.Component kickReason = SpongeAdventure.asVanilla(event.message()); this.connection.setupOutboundProtocol(LoginProtocols.CLIENTBOUND); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerCommonPacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerCommonPacketListenerImplMixin.java index 7e1f354a92e..e924d962776 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerCommonPacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerCommonPacketListenerImplMixin.java @@ -29,6 +29,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerCommonPacketListenerImpl; import org.checkerframework.checker.nullness.qual.Nullable; @@ -49,6 +50,7 @@ public abstract class ServerCommonPacketListenerImplMixin { @Shadow @Final protected MinecraftServer server; @Shadow public abstract void shadow$send(final Packet $$0, @Nullable final PacketSendListener $$1); @Shadow public abstract void shadow$disconnect(Component reason); + @Shadow public void shadow$handleCustomPayload(final ServerboundCustomPayloadPacket $$0) { } // @formatter:on @Nullable public ResourcePack impl$lastReceivedPack; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java index 2785778220c..8c4bf928714 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java @@ -25,13 +25,17 @@ package org.spongepowered.common.mixin.core.server.network; import com.mojang.authlib.GameProfile; -import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket; -import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.server.network.ConfigurationTask; import net.minecraft.server.network.ServerConfigurationPacketListenerImpl; import net.minecraft.server.players.PlayerList; -import org.spongepowered.api.network.EngineConnection; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.event.SpongeEventFactory; +import org.spongepowered.api.event.network.ServerSideConnectionEvent; +import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -43,11 +47,16 @@ import org.spongepowered.common.SpongeServer; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.server.players.PlayerListBridge; -import org.spongepowered.common.network.channel.SpongeChannelManager; +import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.network.channel.ConnectionUtil; +import org.spongepowered.common.network.channel.TransactionStore; +import org.spongepowered.common.profile.SpongeGameProfile; import java.io.IOException; import java.net.SocketAddress; +import java.util.Queue; import java.util.concurrent.CompletionException; +import java.util.function.Consumer; @Mixin(ServerConfigurationPacketListenerImpl.class) @@ -55,10 +64,15 @@ public abstract class ServerConfigurationPacketListenerImplMixin extends ServerC // @formatter:off @Shadow @Final private GameProfile gameProfile; + @Shadow @Final private Queue configurationTasks; + @Shadow @Nullable private ConfigurationTask currentTask; @Shadow public abstract void shadow$handleConfigurationFinished(ServerboundFinishConfigurationPacket $$0); + @Shadow protected abstract void shadow$finishCurrentTask(ConfigurationTask.Type $$0); // @formatter:on + private static final ConfigurationTask.Type impl$SPONGE_CONFIGURATION_TYPE = new ConfigurationTask.Type("sponge_configuration"); + private boolean impl$skipBanService; @Inject(method = "handleConfigurationFinished", cancellable = true, at = @At(value = "INVOKE", @@ -128,4 +142,42 @@ public abstract class ServerConfigurationPacketListenerImplMixin extends ServerC return null; } + @Inject(method = "addOptionalTasks", at = @At("TAIL")) + private void impl$callConfigurationEvent(final CallbackInfo ci) { + this.configurationTasks.add(new ConfigurationTask() { + @Override + public void start(final Consumer> var1) { + final ServerSideConnection connection = (ServerSideConnection) ((ConnectionBridge) ServerConfigurationPacketListenerImplMixin.this.connection).bridge$getEngineConnection(); + final ServerSideConnectionEvent.Configuration event = SpongeEventFactory.createServerSideConnectionEventConfiguration( + PhaseTracker.getCauseStackManager().currentCause(), + connection, + SpongeGameProfile.of(ServerConfigurationPacketListenerImplMixin.this.gameProfile)); + SpongeCommon.post(event); + final TransactionStore store = ConnectionUtil.getTransactionStore(connection); + if (store.isEmpty()) { + ServerConfigurationPacketListenerImplMixin.this.shadow$finishCurrentTask(ServerConfigurationPacketListenerImplMixin.impl$SPONGE_CONFIGURATION_TYPE); + } + } + + @Override + public Type type() { + return ServerConfigurationPacketListenerImplMixin.impl$SPONGE_CONFIGURATION_TYPE; + } + }); + } + + @Override + public void shadow$handleCustomPayload(final ServerboundCustomPayloadPacket $$0) { + super.shadow$handleCustomPayload($$0); + + if (this.currentTask == null || this.currentTask.type() != ServerConfigurationPacketListenerImplMixin.impl$SPONGE_CONFIGURATION_TYPE) { + return; + } + + final ServerSideConnection connection = (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection(); + final TransactionStore store = ConnectionUtil.getTransactionStore(connection); + if (store.isEmpty()) { + this.shadow$finishCurrentTask(ServerConfigurationPacketListenerImplMixin.impl$SPONGE_CONFIGURATION_TYPE); + } + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java index a5e37b6a370..3c8af3b358b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerGamePacketListenerImplMixin.java @@ -104,6 +104,7 @@ import org.spongepowered.common.event.tracking.phase.packet.BasicPacketContext; import org.spongepowered.common.event.tracking.phase.packet.PacketPhase; import org.spongepowered.common.item.util.ItemStackUtil; +import org.spongepowered.common.profile.SpongeGameProfile; import org.spongepowered.common.util.CommandUtil; import org.spongepowered.common.util.VecHelper; import org.spongepowered.math.vector.Vector3d; @@ -431,11 +432,13 @@ public abstract class ServerGamePacketListenerImplMixin extends ServerCommonPack frame.pushCause(this.player); final Component message = SpongeAdventure.asAdventure($$0); final Audience audience = Sponge.server().broadcastAudience(); - final ServerSideConnectionEvent.Disconnect event = SpongeEventFactory.createServerSideConnectionEventDisconnect( + final ServerSideConnectionEvent.Leave event = SpongeEventFactory.createServerSideConnectionEventLeave( PhaseTracker.getCauseStackManager().currentCause(), audience, Optional.of(audience), message, message, - spongePlayer.connection(), spongePlayer); + spongePlayer.connection(), spongePlayer, SpongeGameProfile.of(this.player.getGameProfile()), false); SpongeCommon.post(event); - event.audience().ifPresent(a -> a.sendMessage(spongePlayer, event.message())); + if (!event.isMessageCancelled()) { + event.audience().ifPresent(a -> a.sendMessage(spongePlayer, event.message())); + } } ((ServerPlayerBridge) this.player).bridge$getWorldBorderListener().onPlayerDisconnect(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerHandshakePacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerHandshakePacketListenerImplMixin.java index 55a2b77a110..04cee3c99bb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerHandshakePacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerHandshakePacketListenerImplMixin.java @@ -43,11 +43,11 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.server.network.ServerHandshakePacketListenerImplBridge; import org.spongepowered.common.event.tracking.PhaseTracker; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.util.NetworkUtil; @Mixin(ServerHandshakePacketListenerImpl.class) @@ -78,14 +78,11 @@ public abstract class ServerHandshakePacketListenerImplMixin implements ServerHa target = "Lnet/minecraft/server/MinecraftServer;getStatus()Lnet/minecraft/network/protocol/status/ServerStatus;")), cancellable = true) private void impl$onLogin(final ClientIntentionPacket $$0, final CallbackInfo ci) { + final SpongeEngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); final Component message = Component.text("You are not allowed to log in to this server."); final ServerSideConnectionEvent.Intent event = SpongeEventFactory.createServerSideConnectionEventIntent( - PhaseTracker.getCauseStackManager().currentCause(), - message, - message, - (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection(), - true); - if (SpongeCommon.post(event)) { + PhaseTracker.getCauseStackManager().currentCause(), message, message, (ServerSideConnection) connection, false); + if (connection.postGuardedEvent(event)) { final net.minecraft.network.chat.Component kickReason = SpongeAdventure.asVanilla(event.message()); this.connection.setupOutboundProtocol(LoginProtocols.CLIENTBOUND); this.connection.send(new ClientboundLoginDisconnectPacket(kickReason)); @@ -97,21 +94,18 @@ public abstract class ServerHandshakePacketListenerImplMixin implements ServerHa @Redirect(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;acceptsTransfers()Z")) private boolean impl$onTransfer(final MinecraftServer instance) { this.impl$transferred = true; + final SpongeEngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); final Component message = Component.translatable("multiplayer.disconnect.transfers_disabled"); final ServerSideConnectionEvent.Intent event = SpongeEventFactory.createServerSideConnectionEventIntent( - PhaseTracker.getCauseStackManager().currentCause(), - message, - message, - (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection(), - true); - event.setCancelled(instance.acceptsTransfers()); - if (SpongeCommon.post(event)) { + PhaseTracker.getCauseStackManager().currentCause(), message, message, (ServerSideConnection) connection, true); + event.setCancelled(!instance.acceptsTransfers()); + if (connection.postGuardedEvent(event)) { ((ConnectionBridge) this.connection).bridge$setKickReason(SpongeAdventure.asVanilla(event.message())); } - return event.isCancelled(); + return !event.isCancelled(); } - @ModifyArg(method = "handleIntention", at = @At(value = "NEW", target = "net/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket")) + @ModifyArg(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket;(Lnet/minecraft/network/chat/Component;)V")) private net.minecraft.network.chat.Component impl$setTransferDisconnectMessage(final net.minecraft.network.chat.Component component) { return ((ConnectionBridge) this.connection).bridge$getKickReason(); } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerLoginPacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerLoginPacketListenerImplMixin.java index edf331fecfe..81d877281db 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerLoginPacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerLoginPacketListenerImplMixin.java @@ -32,6 +32,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerLoginPacketListenerImpl; import net.minecraft.server.players.PlayerList; +import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; import org.spongepowered.api.event.Cause; import org.spongepowered.api.event.EventContext; @@ -49,8 +50,12 @@ import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.bridge.network.ServerLoginPacketListenerImplBridge; +import org.spongepowered.common.bridge.server.players.PlayerListBridge; +import org.spongepowered.common.network.SpongeEngineConnection; +import org.spongepowered.common.profile.SpongeGameProfile; import java.net.SocketAddress; +import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -61,7 +66,7 @@ public abstract class ServerLoginPacketListenerImplMixin implements ServerLoginP @Shadow @Final static Logger LOGGER; @Shadow @Final Connection connection; - @Shadow com.mojang.authlib.GameProfile authenticatedProfile; + @Shadow private com.mojang.authlib.GameProfile authenticatedProfile; @Shadow @Final MinecraftServer server; @Shadow private ServerLoginPacketListenerImpl.State state; @@ -73,8 +78,6 @@ public abstract class ServerLoginPacketListenerImplMixin implements ServerLoginP .setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)) .build()); - private boolean impl$accepted = false; - @Override public Connection bridge$getConnection() { return this.connection; @@ -83,7 +86,7 @@ public abstract class ServerLoginPacketListenerImplMixin implements ServerLoginP @Redirect(method = "verifyLoginAndFinishConnectionSetup", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/players/PlayerList;canPlayerLogin(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Lnet/minecraft/network/chat/Component;")) private Component impl$onCanPlayerLogin(final PlayerList instance, final SocketAddress $$0, final GameProfile $$1) { - //We check for this on the configuration handler, skip here for now. + //We check this as part of auth event. return null; } @@ -100,13 +103,34 @@ public abstract class ServerLoginPacketListenerImplMixin implements ServerLoginP private void impl$handleAuthEventCancellation(final CallbackInfo ci) { ci.cancel(); - if (this.server.usesAuthentication() && !this.connection.isMemoryConnection()) { - //We are already off the network thread for online servers. - this.bridge$fireAuthEvent(); - } else { - //Execute the Auth event off the network thread to not block it. - this.bridge$getExecutor().submit(this::bridge$fireAuthEvent); - } + ((PlayerListBridge) this.server.getPlayerList()).bridge$canPlayerLogin(this.connection.getRemoteAddress(), this.authenticatedProfile) + .handle((componentOpt, throwable) -> { + if (throwable != null) { + // An error occurred during login checks so we ask to abort. + ((ConnectionBridge) this.connection).bridge$setKickReason(Component.literal("An error occurred checking ban/whitelist status.")); + SpongeCommon.logger().error("An error occurred when checking the ban/whitelist status of {}.", this.authenticatedProfile.getId().toString()); + SpongeCommon.logger().error(throwable); + } else if (componentOpt != null) { + // We handle this later + ((ConnectionBridge) this.connection).bridge$setKickReason(componentOpt); + } + return null; + }).handleAsync((ignored, throwable) -> { + if (throwable != null) { + // We're just going to disconnect here, because something went horribly wrong. + if (throwable instanceof CompletionException) { + throw (CompletionException) throwable; + } else { + throw new CompletionException(throwable); + } + } + this.impl$fireAuthEvent(); + return null; + }, this.bridge$getExecutor()).exceptionally(throwable -> { + SpongeCommon.logger().error("Forcibly disconnecting user {}({}) due to an error during login.", this.authenticatedProfile.getName(), this.authenticatedProfile.getId(), throwable); + this.shadow$disconnect(Component.literal("Internal Server Error: unable to complete login.")); + return null; + }); } @Override @@ -114,14 +138,21 @@ public abstract class ServerLoginPacketListenerImplMixin implements ServerLoginP return ServerLoginPacketListenerImplMixin.impl$EXECUTOR; } - @Override - public void bridge$fireAuthEvent() { - final net.kyori.adventure.text.Component disconnectMessage = net.kyori.adventure.text.Component.text("You are not allowed to log in to this server."); + private void impl$fireAuthEvent() { + final @Nullable Component kickReason = ((ConnectionBridge) this.connection).bridge$getKickReason(); + final net.kyori.adventure.text.Component disconnectMessage; + if (kickReason != null) { + disconnectMessage = SpongeAdventure.asAdventure(kickReason); + } else { + disconnectMessage = net.kyori.adventure.text.Component.text("You are not allowed to log in to this server."); + } + final SpongeEngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); + connection.setGameProfile(this.authenticatedProfile); final Cause cause = Cause.of(EventContext.empty(), this); final ServerSideConnectionEvent.Auth event = SpongeEventFactory.createServerSideConnectionEventAuth( - cause, disconnectMessage, disconnectMessage, (ServerSideConnection) ((ConnectionBridge) this.connection).bridge$getEngineConnection()); - SpongeCommon.post(event); - if (event.isCancelled()) { + cause, disconnectMessage, disconnectMessage, (ServerSideConnection) connection, + SpongeGameProfile.of(this.authenticatedProfile)); + if (connection.postGuardedEvent(event)) { this.impl$disconnectClient(event.message()); return; } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java index a164cafc15b..490e8aeaea6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java @@ -155,7 +155,6 @@ public abstract class PlayerListMixin implements PlayerListBridge { final net.minecraft.server.level.@Nullable ServerPlayer $$2, final ChatType.Bound $$4); // @formatter:on - private boolean impl$isGameMechanicRespawn = false; private boolean impl$isDuringSystemMessageEvent = false; @@ -296,7 +295,7 @@ public abstract class PlayerListMixin implements PlayerListBridge { final Cause cause = Cause.of(EventContext.empty(), connection, user); final ServerSideConnectionEvent.Login event = SpongeEventFactory.createServerSideConnectionEventLogin(cause, disconnectMessage, - disconnectMessage, location, location, rotation, rotation, connection, user); + disconnectMessage, location, location, rotation, rotation, connection, SpongeGameProfile.of(mcPlayer.getGameProfile()), user); if (kickReason != null) { event.setCancelled(true); } @@ -431,7 +430,7 @@ public abstract class PlayerListMixin implements PlayerListBridge { final Component joinComponent = SpongeAdventure.asAdventure(((ServerPlayerBridge) mcPlayer).bridge$getConnectionMessageToSend()); final ServerSideConnectionEvent.Join event = SpongeEventFactory.createServerSideConnectionEventJoin(cause, audience, - Optional.of(audience), joinComponent, joinComponent, connection, player, false); + Optional.of(audience), joinComponent, joinComponent, connection, player, SpongeGameProfile.of(mcPlayer.getGameProfile()), false); SpongeCommon.post(event); if (!event.isMessageCancelled()) { event.audience().ifPresent(audience1 -> audience1.sendMessage(Identity.nil(), event.message())); diff --git a/src/mixins/resources/mixins.sponge.api.json b/src/mixins/resources/mixins.sponge.api.json index 5e2e6b6239a..465c95547f1 100644 --- a/src/mixins/resources/mixins.sponge.api.json +++ b/src/mixins/resources/mixins.sponge.api.json @@ -50,7 +50,12 @@ "minecraft.server.level.TicketMixin_API", "minecraft.server.level.TicketTypeMixin_API", "minecraft.server.level.WorldGenRegionMixin_API", + "minecraft.server.network.MemoryServerHandshakePacketListenerImplMixin_API", + "minecraft.server.network.ServerCommonPacketListenerImplMixin_API", + "minecraft.server.network.ServerConfigurationPacketListenerImplMixin_API", + "minecraft.server.network.ServerGamePacketListenerImplMixin_API", "minecraft.server.network.ServerHandshakePacketListenerImplMixin_API", + "minecraft.server.network.ServerLoginPacketListenerImplMixin_API", "minecraft.server.packs.PackResourcesMixin_API", "minecraft.server.packs.PackTypeMixin_API", "minecraft.server.packs.repository.PackCompatibilityMixin_API", @@ -465,9 +470,12 @@ ], "client": [ "minecraft.client.MinecraftMixin_API", - "minecraft.client.multiplayer.ClientCommonPacketListenerImpl_API", + "minecraft.client.multiplayer.ClientCommonPacketListenerImplMixin_API", + "minecraft.client.multiplayer.ClientConfigurationPacketListenerImplMixin_API", + "minecraft.client.multiplayer.ClientHandshakePacketListenerImplMixin_API", "minecraft.client.multiplayer.ClientLevel_ClientLevelDataMixin_API", "minecraft.client.multiplayer.ClientLevelMixin_API", + "minecraft.client.multiplayer.ClientPacketListenerMixin_API", "minecraft.client.player.AbstractClientPlayerMixin_API", "minecraft.client.player.LocalPlayerMixin_API", "minecraft.client.player.RemotePlayerMixin_API", diff --git a/testplugins/src/main/java/org/spongepowered/test/connection/ConnectionTests.java b/testplugins/src/main/java/org/spongepowered/test/connection/ConnectionTests.java new file mode 100644 index 00000000000..bc6d8ea35cd --- /dev/null +++ b/testplugins/src/main/java/org/spongepowered/test/connection/ConnectionTests.java @@ -0,0 +1,179 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.test.connection; + +import com.google.inject.Inject; +import net.kyori.adventure.identity.Identity; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.command.Command; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.parameter.CommandContext; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.filter.IsCancelled; +import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; +import org.spongepowered.api.event.network.ServerSideConnectionEvent; +import org.spongepowered.api.network.ServerConnectionState; +import org.spongepowered.api.network.ServerSideConnection; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.api.util.Tristate; +import org.spongepowered.plugin.PluginContainer; +import org.spongepowered.plugin.builtin.jvm.Plugin; +import org.spongepowered.test.LoadableModule; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +@Plugin("connectiontests") +public class ConnectionTests implements LoadableModule { + + private final PluginContainer plugin; + + private boolean acceptTransfer; + + @Inject + public ConnectionTests(final PluginContainer plugin) { + this.plugin = plugin; + } + + @Override + public void enable(final CommandContext ctx) { + Sponge.eventManager().registerListeners(this.plugin, new Listeners()); + } + + @Override + public void disable(CommandContext ctx) { + Sponge.eventManager().unregisterListeners(this.plugin); + } + + @Listener + private void registerCommands(final RegisterCommandEvent event) { + event.register(this.plugin, Command.builder() + .executor(context -> { + this.acceptTransfer = !this.acceptTransfer; + final Component newState = Component.text( + this.acceptTransfer ? "ON" : "OFF", this.acceptTransfer ? NamedTextColor.GREEN : NamedTextColor.RED); + context.sendMessage(Identity.nil(), Component.text("Accept Transfers: ").append(newState)); + return CommandResult.success(); + }) + .build(), "toggleAcceptTransfers" + ); + } + + private final class Listeners { + + private final Map connectionData = new ConcurrentHashMap<>(); + + @Listener + @IsCancelled(Tristate.UNDEFINED) + private void onIntent(final ServerSideConnectionEvent.Intent event) { + if (ConnectionTests.this.acceptTransfer && event.isTransfer()) { + event.setCancelled(false); + } + this.connectionData.put(event.connection(), new ConnectionData(event.isTransfer())); + Sponge.game().systemSubject().sendMessage(Component.text("Intent from " + event.connection().address() + " with transfer " + event.isTransfer())); + this.checkState(event); + } + + @Listener + private void onAuth(final ServerSideConnectionEvent.Auth event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.profile().name() + " authenticated!")); + final @Nullable ConnectionData connectionData = this.connectionData.get(event.connection()); + if (connectionData != null) { + connectionData.profile = event.profile(); + } + this.checkState(event); + } + + @Listener + private void onHandshake(final ServerSideConnectionEvent.Handshake event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.profile().name() + " performing handshake!")); + this.checkState(event); + } + + @Listener + private void onConfiguration(final ServerSideConnectionEvent.Configuration event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.profile().name() + " in configuration phase!")); + this.checkState(event); + } + + @Listener + private void onLogin(final ServerSideConnectionEvent.Login event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.profile().name() + " login!")); + this.checkState(event); + } + + @Listener + private void onJoin(final ServerSideConnectionEvent.Join event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.player().name() + " joined!")); + this.checkState(event); + } + + @Listener + private void onLeave(final ServerSideConnectionEvent.Leave event) { + Sponge.game().systemSubject().sendMessage(Component.text("User " + event.player().name() + " left!")); + this.checkState(event); + } + + @Listener + private void onDisconnect(final ServerSideConnectionEvent.Disconnect event) { + Sponge.game().systemSubject().sendMessage(Component.text("Connection from " + event.connection().address() + " disconnected! " + event.profile())); + this.checkState(event); + this.connectionData.remove(event.connection()); + } + + private void checkState(final ServerSideConnectionEvent event) { + final @Nullable ConnectionData connectionData = this.connectionData.get(event.connection()); + if (connectionData == null) { + return; + } + + event.connection().state().ifPresent(state -> { + if (!Objects.equals(connectionData.transferred, state.transferred())) { + Sponge.game().systemSubject().sendMessage(Component.text("Transfer data mismatch in " + event, NamedTextColor.RED)); + } + + if (state instanceof ServerConnectionState.Authenticated authenticatedState) { + if (!Objects.equals(connectionData.profile, authenticatedState.profile())) { + Sponge.game().systemSubject().sendMessage(Component.text("Profile data mismatch in " + event, NamedTextColor.RED)); + } + } + }); + } + + private static final class ConnectionData { + private final boolean transferred; + + private GameProfile profile; + + ConnectionData(boolean transferred) { + this.transferred = transferred; + } + } + } +} diff --git a/testplugins/src/main/resources/META-INF/sponge_plugins.json b/testplugins/src/main/resources/META-INF/sponge_plugins.json index fc5219e2b24..16966540939 100644 --- a/testplugins/src/main/resources/META-INF/sponge_plugins.json +++ b/testplugins/src/main/resources/META-INF/sponge_plugins.json @@ -315,6 +315,12 @@ "name": "Infinite Ticks Data Test", "entrypoint": "org.spongepowered.test.data.InfiniteTicksDataTest", "description": "Testing Infinite Ticks Data" + }, + { + "id": "connectiontests", + "name": "Connection Tests", + "entrypoint": "org.spongepowered.test.connection.ConnectionTests", + "description": "Connection Tests" } ] } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java index da7f7d41a8f..4d7df96291f 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java @@ -58,6 +58,7 @@ import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.SpongeChannelManager; import org.spongepowered.common.network.channel.TransactionStore; +import org.spongepowered.common.profile.SpongeGameProfile; import java.math.BigInteger; import java.net.InetAddress; @@ -81,6 +82,7 @@ public abstract class ServerLoginPacketListenerImplMixin_Vanilla implements Serv @Shadow @Final Connection connection; @Shadow @Final private byte[] challenge; @Shadow @Nullable String requestedUsername; + @Shadow private GameProfile authenticatedProfile; @Shadow public abstract void shadow$disconnect(Component reason); @Shadow abstract void shadow$startClientVerification(GameProfile $$0); @@ -124,7 +126,7 @@ public abstract class ServerLoginPacketListenerImplMixin_Vanilla implements Serv ((SpongeChannelManager) Sponge.channelManager()).sendLoginChannelRegistry(connection).thenAccept(result -> { final Cause cause = Cause.of(EventContext.empty(), this); final ServerSideConnectionEvent.Handshake event = - SpongeEventFactory.createServerSideConnectionEventHandshake(cause, connection); + SpongeEventFactory.createServerSideConnectionEventHandshake(cause, connection, SpongeGameProfile.of(this.authenticatedProfile)); SpongeCommon.post(event); this.impl$handshakeState = ServerLoginPacketListenerImplMixin_Vanilla.HANDSHAKE_SYNC_PLUGIN_DATA; }); From bd5d3d456b45f0890457c6fb8a166c16ee72f972 Mon Sep 17 00:00:00 2001 From: aromaa Date: Mon, 13 May 2024 21:55:15 +0300 Subject: [PATCH 218/230] Fix particle options --- .../effect/particle/SpongeParticleHelper.java | 177 +++++++++--------- .../common/util/ParticleOptionUtil.java | 22 +-- 2 files changed, 95 insertions(+), 104 deletions(-) diff --git a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java index 7b1b493f170..3cc0a622f25 100644 --- a/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java +++ b/src/main/java/org/spongepowered/common/effect/particle/SpongeParticleHelper.java @@ -29,6 +29,7 @@ import net.minecraft.core.particles.DustColorTransitionOptions; import net.minecraft.core.particles.DustParticleOptions; import net.minecraft.core.particles.ItemParticleOption; +import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.particles.SculkChargeParticleOptions; import net.minecraft.core.particles.ShriekParticleOption; import net.minecraft.core.particles.SimpleParticleType; @@ -112,62 +113,62 @@ private static CachedParticlePacket getNamedPacket(final ParticleEffect effect, // The only way we can see what options are supported for a particular named particle // is to compare the internal type's deserializer to some static deserializer fields. // If only mojang had some type akin to our ParticleEffect... - // TODO fix me -// if (internalType.getDeserializer() == BlockParticleOption.DESERIALIZER) { -// // This particle type supports a block state option. -// final BlockState state = effect.optionOrDefault(ParticleOptions.BLOCK_STATE).get(); -// final BlockParticleOption particleData = new BlockParticleOption( -// (net.minecraft.core.particles.ParticleType) internalType, -// (net.minecraft.world.level.block.state.BlockState) state); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { -// final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); -// final Color toColor = effect.optionOrDefault(ParticleOptions.TO_COLOR).get(); -// final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); -// final DustColorTransitionOptions particleData = new DustColorTransitionOptions( -// new org.joml.Vector3f( -// (float) color.red() / 255, -// (float) color.green() / 255, -// (float) color.blue() / 255 -// ), -// new org.joml.Vector3f( -// (float) toColor.red() / 255, -// (float) toColor.green() / 255, -// (float) toColor.blue() / 255 -// ), -// (float) scale); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == DustParticleOptions.DESERIALIZER) { -// // This particle type supports a color option. -// final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); -// final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); -// final DustParticleOptions particleData = new DustParticleOptions(new org.joml.Vector3f( -// (float) color.red() / 255, -// (float) color.green() / 255, -// (float) color.blue() / 255), -// (float) scale); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == ItemParticleOption.DESERIALIZER) { -// // This particle type supports an item option. -// final ItemStackSnapshot snapshot = effect.optionOrDefault(ParticleOptions.ITEM_STACK_SNAPSHOT).get(); -// final ItemParticleOption particleData = new ItemParticleOption( -// (net.minecraft.core.particles.ParticleType) internalType, -// (net.minecraft.world.item.ItemStack) (Object) snapshot.createStack()); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { -// final double roll = effect.optionOrDefault(ParticleOptions.ROLL).get(); -// final SculkChargeParticleOptions particleData = new SculkChargeParticleOptions((float) roll); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == ShriekParticleOption.DESERIALIZER) { -// final int delay = effect.optionOrDefault(ParticleOptions.DELAY).get(); -// final ShriekParticleOption particleData = new ShriekParticleOption(delay); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } else if (internalType.getDeserializer() == VibrationParticleOption.DESERIALIZER) { -// final Ticks delay = effect.optionOrDefault(ParticleOptions.TRAVEL_TIME).get(); -// // TODO add position source -// final VibrationParticleOption particleData = new VibrationParticleOption(new BlockPositionSource(BlockPos.ZERO), (int) delay.ticks()); -// return new NamedCachedPacket(particleData, offset, quantity, velocity); -// } + if (internalType == ParticleTypes.BLOCK || internalType == ParticleTypes.BLOCK_MARKER + || internalType == ParticleTypes.FALLING_DUST || internalType == ParticleTypes.DUST_PILLAR) { + //This particle type supports a block state option. + final BlockState state = effect.optionOrDefault(ParticleOptions.BLOCK_STATE).get(); + final BlockParticleOption particleData = new BlockParticleOption( + (net.minecraft.core.particles.ParticleType) internalType, + (net.minecraft.world.level.block.state.BlockState) state); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.DUST_COLOR_TRANSITION) { + final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); + final Color toColor = effect.optionOrDefault(ParticleOptions.TO_COLOR).get(); + final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); + final DustColorTransitionOptions particleData = new DustColorTransitionOptions( + new org.joml.Vector3f( + (float) color.red() / 255, + (float) color.green() / 255, + (float) color.blue() / 255 + ), + new org.joml.Vector3f( + (float) toColor.red() / 255, + (float) toColor.green() / 255, + (float) toColor.blue() / 255 + ), + (float) scale); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.DUST) { + //This particle type supports a color option. + final Color color = effect.optionOrDefault(ParticleOptions.COLOR).get(); + final double scale = effect.optionOrDefault(ParticleOptions.SCALE).get(); + final DustParticleOptions particleData = new DustParticleOptions(new org.joml.Vector3f( + (float) color.red() / 255, + (float) color.green() / 255, + (float) color.blue() / 255), + (float) scale); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.ITEM) { + //This particle type supports an item option. + final ItemStackSnapshot snapshot = effect.optionOrDefault(ParticleOptions.ITEM_STACK_SNAPSHOT).get(); + final ItemParticleOption particleData = new ItemParticleOption( + (net.minecraft.core.particles.ParticleType) internalType, + (net.minecraft.world.item.ItemStack) (Object) snapshot.createStack()); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.SCULK_CHARGE) { + final double roll = effect.optionOrDefault(ParticleOptions.ROLL).get(); + final SculkChargeParticleOptions particleData = new SculkChargeParticleOptions((float) roll); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.SHRIEK) { + final int delay = effect.optionOrDefault(ParticleOptions.DELAY).get(); + final ShriekParticleOption particleData = new ShriekParticleOption(delay); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } else if (internalType == ParticleTypes.VIBRATION) { + final Ticks delay = effect.optionOrDefault(ParticleOptions.TRAVEL_TIME).get(); + // TODO add position source + final VibrationParticleOption particleData = new VibrationParticleOption(new BlockPositionSource(BlockPos.ZERO), (int) delay.ticks()); + return new NamedCachedPacket(particleData, offset, quantity, velocity); + } // Otherwise, we don't really know how to get a valid IParticleData. Sorry mods! return EmptyCachedPacket.INSTANCE; @@ -226,42 +227,34 @@ public static ParticleEffect spongeParticleOptions(final net.minecraft.core.part return new SpongeParticleEffect((ParticleType) type, Collections.emptyMap()); } - // TODO fix me -// if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { -// final BlockParticleOption particleData = (BlockParticleOption) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getState())); -// } else if (type.getDeserializer() == DustColorTransitionOptions.DESERIALIZER) { -// final DustColorTransitionOptions particleData = (DustColorTransitionOptions) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of( -// ParticleOptions.COLOR.get(), Color.of( -// Vector3f.from(particleData.getFromColor().x, particleData.getFromColor().y, particleData.getFromColor().z).mul(255)), -// ParticleOptions.TO_COLOR.get(), Color.of( -// Vector3f.from(particleData.getToColor().x, particleData.getToColor().y, particleData.getToColor().z).mul(255)), -// ParticleOptions.SCALE.get(), particleData.getScale() -// )); -// } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { -// // This particle type supports a color option. -// final DustParticleOptions particleData = (DustParticleOptions) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of( -// ParticleOptions.COLOR.get(), Color.of( -// Vector3f.from(particleData.getColor().x, particleData.getColor().y, particleData.getColor().z).mul(255)), -// ParticleOptions.SCALE.get(), particleData.getScale() -// )); -// } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { -// // This particle type supports an item option. -// final ItemParticleOption particleData = (ItemParticleOption) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), particleData.getItem().copy())); -// } else if (type.getDeserializer() == SculkChargeParticleOptions.DESERIALIZER) { -// final SculkChargeParticleOptions particleData = (SculkChargeParticleOptions) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.ROLL.get(), particleData.roll())); -// } else if (type.getDeserializer() == ShriekParticleOption.DESERIALIZER) { -// final ShriekParticleOption particleData = (ShriekParticleOption) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.DELAY.get(), particleData.getDelay())); -// } else if (type.getDeserializer() == VibrationParticleOption.DESERIALIZER) { -// // TODO add position source -// final VibrationParticleOption particleData = (VibrationParticleOption) effect; -// return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.TRAVEL_TIME.get(), Ticks.of(particleData.getArrivalInTicks()))); -// } + if (effect instanceof BlockParticleOption blockOptions) { + return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), blockOptions.getState())); + } else if (effect instanceof DustColorTransitionOptions dustColorTransitionOptions) { + return new SpongeParticleEffect((ParticleType) type, Map.of( + ParticleOptions.COLOR.get(), Color.of( + Vector3f.from(dustColorTransitionOptions.getFromColor().x, dustColorTransitionOptions.getFromColor().y, dustColorTransitionOptions.getFromColor().z).mul(255)), + ParticleOptions.TO_COLOR.get(), Color.of( + Vector3f.from(dustColorTransitionOptions.getToColor().x, dustColorTransitionOptions.getToColor().y, dustColorTransitionOptions.getToColor().z).mul(255)), + ParticleOptions.SCALE.get(), dustColorTransitionOptions.getScale() + )); + } else if (effect instanceof DustParticleOptions dustOptions) { + // This particle type supports a color option. + return new SpongeParticleEffect((ParticleType) type, Map.of( + ParticleOptions.COLOR.get(), Color.of( + Vector3f.from(dustOptions.getColor().x, dustOptions.getColor().y, dustOptions.getColor().z).mul(255)), + ParticleOptions.SCALE.get(), dustOptions.getScale() + )); + } else if (effect instanceof ItemParticleOption itemOptions) { + // This particle type supports an item option. + return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.BLOCK_STATE.get(), itemOptions.getItem().copy())); + } else if (effect instanceof SculkChargeParticleOptions sculkChargeOptions) { + return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.ROLL.get(), sculkChargeOptions.roll())); + } else if (effect instanceof ShriekParticleOption shriekOption) { + return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.DELAY.get(), shriekOption.getDelay())); + } else if (effect instanceof VibrationParticleOption vibrationOptions) { + // TODO add position source + return new SpongeParticleEffect((ParticleType) type, Map.of(ParticleOptions.TRAVEL_TIME.get(), Ticks.of(vibrationOptions.getArrivalInTicks()))); + } return new SpongeParticleEffect((ParticleType) type, Collections.emptyMap()); } diff --git a/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java b/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java index b3fdd092987..0bb53430fc5 100644 --- a/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java +++ b/src/main/java/org/spongepowered/common/util/ParticleOptionUtil.java @@ -25,10 +25,8 @@ package org.spongepowered.common.util; import com.google.common.collect.ImmutableMap; -import net.minecraft.core.particles.BlockParticleOption; -import net.minecraft.core.particles.DustParticleOptions; -import net.minecraft.core.particles.ItemParticleOption; import net.minecraft.core.particles.ParticleType; +import net.minecraft.core.particles.ParticleTypes; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.effect.particle.ParticleOption; import org.spongepowered.api.effect.particle.ParticleOptions; @@ -50,15 +48,15 @@ public static ImmutableMap, Object> generateDefaultsForNamed(P options.put(ParticleOptions.OFFSET.get(), Vector3d.ZERO); options.put(ParticleOptions.QUANTITY.get(), 1); - // TODO fix me -// if (type.getDeserializer() == BlockParticleOption.DESERIALIZER) { -// options.put(ParticleOptions.BLOCK_STATE.get(), BlockTypes.AIR.get().defaultState()); -// } else if (type.getDeserializer() == ItemParticleOption.DESERIALIZER) { -// options.put(ParticleOptions.ITEM_STACK_SNAPSHOT.get(), ItemStackSnapshot.empty()); -// } else if (type.getDeserializer() == DustParticleOptions.DESERIALIZER) { -// options.put(ParticleOptions.COLOR.get(), Color.RED); -// options.put(ParticleOptions.SCALE.get(), 1.0d); -// } + if (type == ParticleTypes.BLOCK || type == ParticleTypes.BLOCK_MARKER + || type == ParticleTypes.FALLING_DUST || type == ParticleTypes.DUST_PILLAR) { + options.put(ParticleOptions.BLOCK_STATE.get(), BlockTypes.AIR.get().defaultState()); + } else if (type == ParticleTypes.ITEM) { + options.put(ParticleOptions.ITEM_STACK_SNAPSHOT.get(), ItemStackSnapshot.empty()); + } else if (type == ParticleTypes.DUST) { + options.put(ParticleOptions.COLOR.get(), Color.RED); + options.put(ParticleOptions.SCALE.get(), 1.0d); + } return ImmutableMap.copyOf(options); } From 1df928cbd4d551b0f91eff0d5428a09c08694bde Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 02:34:22 +0300 Subject: [PATCH 219/230] Fix channels --- .../common/network/PacketUtil.java | 36 +- .../common/network/channel/ChannelUtils.java | 48 +++ .../network/channel/ConnectionUtil.java | 7 +- .../common/network/channel/SpongeChannel.java | 85 +++-- .../SpongeChannelExceptionHandlerFactory.java | 5 +- .../network/channel/SpongeChannelManager.java | 63 ++-- .../network/channel/SpongeChannelPayload.java | 52 +++ .../network/channel/TransactionStore.java | 6 +- .../channel/packet/AbstractPacketChannel.java | 34 +- .../packet/PacketToResponseHandler.java | 14 +- .../packet/SpongeBasicPacketChannel.java | 59 ++-- .../packet/SpongeHandlerPacketBinding.java | 39 +-- .../channel/packet/SpongePacketChannel.java | 121 ++++--- .../SpongeTransactionalPacketBinding.java | 52 +-- .../channel/raw/SpongeRawDataChannel.java | 11 +- .../raw/SpongeRawLoginDataChannel.java | 42 ++- .../channel/raw/SpongeRawPlayDataChannel.java | 47 ++- .../network/packet/SpongePacketHandler.java | 3 +- ...rConfigurationPacketListenerImplMixin.java | 12 +- .../test/channel/ChannelTest.java | 310 +++++++++--------- ...dshakePacketListenerImplMixin_Vanilla.java | 3 +- .../ClientPacketListenerMixin_Vanilla.java | 3 +- .../ClientboundCustomPayloadPacketMixin.java | 22 +- .../ClientboundCustomQueryPacketMixin.java | 65 ++++ ...CommonPacketListenerImplMixin_Vanilla.java | 3 +- ...rLoginPacketListenerImplMixin_Vanilla.java | 3 +- ...boundCustomPayloadPacketMixin_Vanilla.java | 34 +- .../resources/mixins.spongevanilla.core.json | 1 + 28 files changed, 661 insertions(+), 519 deletions(-) create mode 100644 src/main/java/org/spongepowered/common/network/channel/ChannelUtils.java create mode 100644 src/main/java/org/spongepowered/common/network/channel/SpongeChannelPayload.java create mode 100644 vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/login/ClientboundCustomQueryPacketMixin.java diff --git a/src/main/java/org/spongepowered/common/network/PacketUtil.java b/src/main/java/org/spongepowered/common/network/PacketUtil.java index 440edaa5dca..73265e64e8e 100644 --- a/src/main/java/org/spongepowered/common/network/PacketUtil.java +++ b/src/main/java/org/spongepowered/common/network/PacketUtil.java @@ -39,6 +39,7 @@ import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.packet.Packet; +import org.spongepowered.common.network.channel.SpongeChannelPayload; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -84,35 +85,14 @@ public static net.minecraft.network.protocol.Packet createPlayPayload(final C } } - public static net.minecraft.network.protocol.Packet createPlayPayload(final ResourceKey channel, final ChannelBuf payload, final EngineConnectionSide side) { - // TODO fix me -// if (side == EngineConnectionSide.CLIENT) { -// return new ServerboundCustomPayloadPacket(new CustomPacketPayload() { -// @Override -// public void write(FriendlyByteBuf var1) { -// var1.writeBytes((FriendlyByteBuf)payload); -// } -// -// @Override -// public ResourceLocation id() { -// return (ResourceLocation) (Object) channel; -// } -// }); -// } else if (side == EngineConnectionSide.SERVER) { -// return new ClientboundCustomPayloadPacket(new CustomPacketPayload() { -// @Override -// public void write(FriendlyByteBuf var1) { -// var1.writeBytes((FriendlyByteBuf)payload); -// } -// -// @Override -// public ResourceLocation id() { -// return (ResourceLocation) (Object) channel; -// } -// }); -// } else { + public static net.minecraft.network.protocol.Packet createPlayPayload(final CustomPacketPayload.Type channel, final ChannelBuf payload, final EngineConnectionSide side) { + if (side == EngineConnectionSide.CLIENT) { + return new ServerboundCustomPayloadPacket(new SpongeChannelPayload(channel, (FriendlyByteBuf) payload)); + } else if (side == EngineConnectionSide.SERVER) { + return new ClientboundCustomPayloadPacket(new SpongeChannelPayload(channel, (FriendlyByteBuf) payload)); + } else { throw new UnsupportedOperationException(); -// } + } } // TODO: Use Lmbda instead? diff --git a/src/main/java/org/spongepowered/common/network/channel/ChannelUtils.java b/src/main/java/org/spongepowered/common/network/channel/ChannelUtils.java new file mode 100644 index 00000000000..3d8278eb786 --- /dev/null +++ b/src/main/java/org/spongepowered/common/network/channel/ChannelUtils.java @@ -0,0 +1,48 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.network.channel; + +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import org.spongepowered.api.Sponge; +import org.spongepowered.common.util.Constants; + +import java.util.ArrayList; + +@SuppressWarnings({"rawtypes", "unchecked"}) +public final class ChannelUtils { + public static final CustomPacketPayload.Type REGISTER = CustomPacketPayload.createType(Constants.Channels.REGISTER_KEY.toString()); + + public static ArrayList spongeChannelCodecs(final int maxPayloadSize) { + ArrayList channels = new ArrayList<>(); + channels.add(new CustomPacketPayload.TypeAndCodec<>(ChannelUtils.REGISTER, SpongeChannelPayload.streamCodec(ChannelUtils.REGISTER, maxPayloadSize))); + Sponge.game().channelManager().channels().forEach(c -> + channels.add(new CustomPacketPayload.TypeAndCodec<>(((SpongeChannel) c).payloadType(), SpongeChannelPayload.streamCodec(((SpongeChannel) c).payloadType(), maxPayloadSize)))); + return channels; + } + + private ChannelUtils() { + } + +} diff --git a/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java b/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java index 67d71d559d8..b084789a010 100644 --- a/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java +++ b/src/main/java/org/spongepowered/common/network/channel/ConnectionUtil.java @@ -25,10 +25,9 @@ package org.spongepowered.common.network.channel; import net.minecraft.network.Connection; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; -import net.minecraft.network.protocol.login.ServerLoginPacketListener; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.network.SpongeEngineConnection; @@ -37,8 +36,8 @@ public final class ConnectionUtil { public static boolean isLoginPhase(final EngineConnection connection) { - return connection instanceof ClientLoginPacketListener || - connection instanceof ServerLoginPacketListener; + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); + return state instanceof EngineConnectionState.Login; } public static Set getRegisteredChannels(final EngineConnection connection) { diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java index 89e42fc4cfc..9029e20e9ca 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannel.java @@ -25,13 +25,17 @@ package org.spongepowered.common.network.channel; import com.google.common.collect.Multimap; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; +import org.spongepowered.api.network.ClientConnectionState; import org.spongepowered.api.network.ClientSideConnection; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; +import org.spongepowered.api.network.ServerConnectionState; import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.api.network.channel.Channel; import org.spongepowered.api.network.channel.ChannelBuf; @@ -54,8 +58,9 @@ public abstract class SpongeChannel implements Channel { private final SpongeChannelManager manager; private final Logger logger; private final int type; + private final CustomPacketPayload.Type payloadType; - private volatile ChannelExceptionHandler exceptionHandler = + private volatile ChannelExceptionHandler exceptionHandler = ChannelExceptionHandler.logEverything().suppress(ChannelNotSupportedException.class); public SpongeChannel(final int type, final ResourceKey key, final SpongeChannelManager manager) { @@ -63,6 +68,7 @@ public SpongeChannel(final int type, final ResourceKey key, final SpongeChannelM this.key = key; this.manager = manager; this.logger = LogManager.getLogger("channel/" + key.formatted()); + this.payloadType = CustomPacketPayload.createType(key.toString()); } public int getType() { @@ -73,6 +79,10 @@ public Logger getLogger() { return this.logger; } + public CustomPacketPayload.Type payloadType() { + return this.payloadType; + } + @Override public SpongeChannelManager manager() { return this.manager; @@ -84,7 +94,7 @@ public ResourceKey key() { } @Override - public void setExceptionHandler(final ChannelExceptionHandler handler) { + public void setExceptionHandler(final ChannelExceptionHandler handler) { Objects.requireNonNull(handler, "handler"); this.exceptionHandler = handler; } @@ -96,9 +106,9 @@ public String toString() { .toString(); } - public boolean checkSupported(final EngineConnection connection, final CompletableFuture future) { + public boolean checkSupported(final EngineConnection connection, final EngineConnectionState state, final CompletableFuture future) { if (!ConnectionUtil.getRegisteredChannels(connection).contains(this.key())) { - this.handleException(connection, new ChannelNotSupportedException("The channel \"" + this.key() + "\" isn't supported."), future); + this.handleException(connection, state, new ChannelNotSupportedException("The channel \"" + this.key() + "\" isn't supported."), future); return false; } return true; @@ -110,7 +120,7 @@ public boolean checkSupported(final EngineConnection connection, final Completab * @param connection The connection to decode the payload for * @param payload The payload */ - protected abstract void handlePlayPayload(EngineConnection connection, ChannelBuf payload); + protected abstract void handlePlayPayload(EngineConnection connection, EngineConnectionState state, ChannelBuf payload); /** * Handles a login request payload packet. This is currently guaranteed to be run on the client. @@ -119,7 +129,7 @@ public boolean checkSupported(final EngineConnection connection, final Completab * @param transactionId The transaction id of the request * @param payload The payload, or null if no response */ - protected abstract void handleLoginRequestPayload(EngineConnection connection, int transactionId, ChannelBuf payload); + protected abstract void handleLoginRequestPayload(EngineConnection connection, EngineConnectionState state, int transactionId, ChannelBuf payload); /** * Handles the response to a transaction for the stored data. @@ -128,11 +138,11 @@ public boolean checkSupported(final EngineConnection connection, final Completab * @param stored The data that was stored alongside the payload * @param result The result of the transaction */ - protected abstract void handleTransactionResponse(EngineConnection connection, Object stored, TransactionResult result); + protected abstract void handleTransactionResponse(EngineConnection connection, EngineConnectionState state, Object stored, TransactionResult result); - public void handleException(final EngineConnection connection, final Throwable cause, final @Nullable CompletableFuture future) { + public void handleException(final EngineConnection connection, final EngineConnectionState state, final Throwable cause, final @Nullable CompletableFuture future) { try { - this.exceptionHandler.handle(connection, this, ChannelExceptionUtil.of(cause), future); + this.exceptionHandler.handle(state, this, ChannelExceptionUtil.of(cause), future); } catch (final Throwable ex) { SpongeCommon.logger().error("The exception handler of the channel " + this.key() + " failed to handle an exception.", ex); } @@ -142,35 +152,60 @@ public static Class getConnectionClass(final Eng return (Class) (side == EngineConnectionSide.CLIENT ? ClientSideConnection.class : ServerSideConnection.class); } - public static @Nullable H getRequestHandler(final EngineConnection connection, final Map, H> handlersMap) { + public static @Nullable H getRequestHandler(final EngineConnectionState state, final Map, H> handlersMap) { H handler = null; - //TODO: Fix me - /*if (connection instanceof LocalPlayerConnection) { - handler = handlersMap.get(LocalPlayerConnection.class); - } else if (connection instanceof ServerPlayerConnection) { - handler = handlersMap.get(ServerPlayerConnection.class); + if (state instanceof ClientConnectionState) { + if (state instanceof ClientConnectionState.Game) { + handler = handlersMap.get(ClientConnectionState.Game.class); + } else if (state instanceof ClientConnectionState.Configuration) { + handler = handlersMap.get(ClientConnectionState.Configuration.class); + } else if (state instanceof ClientConnectionState.Login) { + handler = handlersMap.get(ClientConnectionState.Login.class); + } + if (handler == null && state instanceof ClientConnectionState.Authenticated) { + handler = handlersMap.get(ClientConnectionState.Authenticated.class); + } + if (handler == null) { + handler = handlersMap.get(ClientConnectionState.class); + } + } else if (state instanceof ServerConnectionState) { + if (state instanceof ServerConnectionState.Game) { + handler = handlersMap.get(ServerConnectionState.Game.class); + } else if (state instanceof ServerConnectionState.Configuration) { + handler = handlersMap.get(ServerConnectionState.Configuration.class); + } else if (state instanceof ServerConnectionState.Login) { + handler = handlersMap.get(ServerConnectionState.Login.class); + } + if (handler == null && state instanceof ServerConnectionState.Authenticated) { + handler = handlersMap.get(ServerConnectionState.Authenticated.class); + } + if (handler == null) { + handler = handlersMap.get(ServerConnectionState.class); + } } - if (handler == null && connection instanceof PlayerConnection) { - handler = handlersMap.get(PlayerConnection.class); - }*/ if (handler == null) { - if (connection instanceof ClientSideConnection) { - handler = handlersMap.get(ClientSideConnection.class); - } else if (connection instanceof ServerSideConnection) { - handler = handlersMap.get(ServerSideConnection.class); + if (state instanceof EngineConnectionState.Game) { + handler = handlersMap.get(EngineConnectionState.Game.class); + } else if (state instanceof EngineConnectionState.Configuration) { + handler = handlersMap.get(EngineConnectionState.Configuration.class); + } else if (state instanceof EngineConnectionState.Login) { + handler = handlersMap.get(EngineConnectionState.Login.class); + } + if (handler == null && state instanceof EngineConnectionState.Authenticated) { + handler = handlersMap.get(EngineConnectionState.Authenticated.class); } } if (handler == null) { - handler = handlersMap.get(EngineConnection.class); + handler = handlersMap.get(EngineConnectionState.class); } return handler; } - public static Collection getResponseHandlers(final EngineConnection connection, final Multimap, H> handlersMap) { + public static Collection getResponseHandlers(final EngineConnectionState state, final Multimap, H> handlersMap) { Collection handlers = null; boolean modifiable = false; for (final Map.Entry, Collection> entry : handlersMap.asMap().entrySet()) { - if (entry.getKey().isInstance(connection)) { + if (entry.getKey().isInstance(state)) { if (handlers == null) { handlers = entry.getValue(); } else if (!modifiable) { diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java index cbf708f712c..a168af0328d 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java @@ -25,11 +25,12 @@ package org.spongepowered.common.network.channel; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelExceptionHandler; public final class SpongeChannelExceptionHandlerFactory implements ChannelExceptionHandler.Factory { - private final ChannelExceptionHandler logEverything; + private final ChannelExceptionHandler logEverything; public SpongeChannelExceptionHandlerFactory() { this.logEverything = (connection, channel, exception, future) -> { @@ -42,7 +43,7 @@ public SpongeChannelExceptionHandlerFactory() { @Override - public ChannelExceptionHandler logEverything() { + public ChannelExceptionHandler logEverything() { return this.logEverything; } } diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java index 27f32574c4d..42b874be936 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelManager.java @@ -26,10 +26,7 @@ import com.google.common.collect.ImmutableList; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket; import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket; @@ -38,11 +35,8 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; -import org.spongepowered.api.item.ItemTypes; -import org.spongepowered.api.item.inventory.Inventory; -import org.spongepowered.api.item.inventory.query.Query; -import org.spongepowered.api.item.inventory.query.QueryTypes; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.Channel; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelManager; @@ -240,29 +234,8 @@ public void write(FriendlyByteBuf var1) { return future; } - public record SpongeRegisterChannelPayload(Collection channels) implements CustomPacketPayload - { - public static final StreamCodec STREAM_CODEC = CustomPacketPayload.codec( - SpongeRegisterChannelPayload::write, SpongeRegisterChannelPayload::new - ); - public static final CustomPacketPayload.Type TYPE = CustomPacketPayload.createType(Constants.Channels.REGISTER_KEY.value()); - - public SpongeRegisterChannelPayload(FriendlyByteBuf $$0) { - this(RegisterChannelUtil.decodePayload((ChannelBuf) $$0)); - } - - private void write(FriendlyByteBuf $$0) { - $$0.writeBytes((FriendlyByteBuf) RegisterChannelUtil.encodePayload(this.channels)); - } - - @Override - public Type type() { - return TYPE; - } - } - public void sendChannelRegistrations(final EngineConnection connection) { - final Packet mcPacket = PacketUtil.createPlayPayload(new SpongeRegisterChannelPayload(this.channels.keySet()), connection.side()); + final Packet mcPacket = PacketUtil.createPlayPayload(ChannelUtils.REGISTER, RegisterChannelUtil.encodePayload(this.channels.keySet()), connection.side()); PacketSender.sendTo(connection, mcPacket); } @@ -305,13 +278,15 @@ private void handleChannelRegistry(final EngineConnection connection, final Chan } } - public boolean handlePlayPayload(final EngineConnection connection, final CustomPacketPayload payload) { + public boolean handlePlayPayload(final EngineConnection connection, final EngineConnectionState state, final CustomPacketPayload payload) { + if (!(payload instanceof SpongeChannelPayload spongeChannelPayload)) { + return false; + } final ResourceKey channel = (ResourceKey) (Object) payload.type().id(); final ChannelBuf buf = this.bufferAllocator.buffer(); - //TODO fixme - //payload.type((FriendlyByteBuf) buf); + ((FriendlyByteBuf) buf).writeBytes(spongeChannelPayload.payload().copy()); - return this.handlePlayPayload(connection, channel, buf); + return this.handlePlayPayload(connection, state, channel, buf); } private void handleRegisterChannel(final EngineConnection connection, final ChannelBuf payload, @@ -326,7 +301,7 @@ private void handleRegisterChannel(final EngineConnection connection, final Chan } } - private boolean handlePlayPayload(final EngineConnection connection, final ResourceKey channelKey, final ChannelBuf payload) { + private boolean handlePlayPayload(final EngineConnection connection, final EngineConnectionState state, final ResourceKey channelKey, final ChannelBuf payload) { if (channelKey.equals(Constants.Channels.SPONGE_CLIENT_TYPE)) { this.handleClientType(connection, payload); return true; @@ -343,7 +318,7 @@ private boolean handlePlayPayload(final EngineConnection connection, final Resou final SpongeChannel channel = this.channels.get(channelKey); if (channel != null) { try { - channel.handlePlayPayload(connection, payload); + channel.handlePlayPayload(connection, state, payload); } finally { ChannelBuffers.release(payload); } @@ -353,7 +328,7 @@ private boolean handlePlayPayload(final EngineConnection connection, final Resou } } - public boolean handleLoginRequestPayload(final EngineConnection connection, final ClientboundCustomQueryPacket packet) { + public boolean handleLoginRequestPayload(final EngineConnection connection, final EngineConnectionState state, final ClientboundCustomQueryPacket packet) { // Server -> Client request final ResourceKey channel = (ResourceKey) (Object) packet.payload().id(); final int transactionId = packet.transactionId(); @@ -361,13 +336,13 @@ public boolean handleLoginRequestPayload(final EngineConnection connection, fina packet.payload().write((FriendlyByteBuf) payload); try { - return this.handleLoginRequestPayload(connection, channel, transactionId, payload); + return this.handleLoginRequestPayload(connection, state, channel, transactionId, payload); } finally { ChannelBuffers.release(payload); } } - private boolean handleLoginRequestPayload(final EngineConnection connection, final ResourceKey channelKey, + private boolean handleLoginRequestPayload(final EngineConnection connection, final EngineConnectionState state, final ResourceKey channelKey, final int transactionId, final ChannelBuf payload) { if (channelKey.equals(Constants.Channels.SPONGE_CLIENT_TYPE)) { final ClientType clientType = ((MinecraftBridge) Sponge.client()).bridge$getClientType(); @@ -392,13 +367,13 @@ private boolean handleLoginRequestPayload(final EngineConnection connection, fin } final SpongeChannel channel = this.channels.get(actualChannelKey); if (channel != null) { - channel.handleLoginRequestPayload(connection, transactionId, actualPayload); + channel.handleLoginRequestPayload(connection, state, transactionId, actualPayload); return true; } return false; } - public void handleLoginResponsePayload(final EngineConnection connection, final ServerboundCustomQueryAnswerPacket packet) { + public void handleLoginResponsePayload(final EngineConnection connection, final EngineConnectionState state, final ServerboundCustomQueryAnswerPacket packet) { // Client -> Server response final int transactionId = packet.transactionId(); @@ -412,7 +387,7 @@ public void handleLoginResponsePayload(final EngineConnection connection, final } try { - this.handleLoginResponsePayload(connection, transactionId, payload); + this.handleLoginResponsePayload(connection, state, transactionId, payload); } finally { if (payload != null) { ChannelBuffers.release(payload); @@ -420,7 +395,7 @@ public void handleLoginResponsePayload(final EngineConnection connection, final } } - private void handleLoginResponsePayload(final EngineConnection connection, final int transactionId, final @Nullable ChannelBuf payload) { + private void handleLoginResponsePayload(final EngineConnection connection, final EngineConnectionState state, final int transactionId, final @Nullable ChannelBuf payload) { // Sponge magic... Allows normal packets to be send during the login phase from the client to server if (transactionId == Constants.Channels.LOGIN_PAYLOAD_IGNORED_TRANSACTION_ID) { return; @@ -428,7 +403,7 @@ private void handleLoginResponsePayload(final EngineConnection connection, final if (transactionId == Constants.Channels.LOGIN_PAYLOAD_TRANSACTION_ID) { if (payload != null) { final ResourceKey channelKey = ResourceKey.resolve(payload.readString()); - this.handlePlayPayload(connection, channelKey, payload); + this.handlePlayPayload(connection, state, channelKey, payload); } return; } @@ -454,6 +429,6 @@ private void handleLoginResponsePayload(final EngineConnection connection, final } final TransactionResult result = payload == null ? TransactionResult.failure(new NoResponseException()) : TransactionResult.success(payload); - entry.getChannel().handleTransactionResponse(connection, entry.getData(), result); + entry.getChannel().handleTransactionResponse(connection, state, entry.getData(), result); } } diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelPayload.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelPayload.java new file mode 100644 index 00000000000..0984f2d2398 --- /dev/null +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelPayload.java @@ -0,0 +1,52 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.network.channel; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public record SpongeChannelPayload(Type type, FriendlyByteBuf payload) implements CustomPacketPayload { + + public static StreamCodec streamCodec(final Type type, final int maxPayloadSize) { + return CustomPacketPayload.codec( + SpongeChannelPayload::write, (b) -> { + int readableBytes = b.readableBytes(); + if (readableBytes >= 0 && readableBytes <= maxPayloadSize) { + return new SpongeChannelPayload(type, new FriendlyByteBuf(b.readBytes(b.readableBytes()))); + } + throw new IllegalArgumentException("Payload may not be larger than " + maxPayloadSize + " bytes"); + }); + } + + private void write(FriendlyByteBuf $$0) { + $$0.writeBytes(this.payload); + } + + @Override + public Type type() { + return this.type; + } +} diff --git a/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java b/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java index 4a396b657bf..72c8007ee45 100644 --- a/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java +++ b/src/main/java/org/spongepowered/common/network/channel/TransactionStore.java @@ -29,12 +29,13 @@ import com.github.benmanes.caffeine.cache.RemovalListener; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.TimeoutException; +import org.spongepowered.common.network.SpongeEngineConnection; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; /** * A storage for transaction id mappings. @@ -47,8 +48,9 @@ public final class TransactionStore { .expireAfterAccess(15, TimeUnit.SECONDS) .removalListener((RemovalListener) (key, value, cause) -> { if (cause == RemovalCause.EXPIRED && value != null) { + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) this.connection()).connection().getPacketListener(); value.getChannel().handleTransactionResponse( - this.connection(), value.getData(), TransactionResult.failure(new TimeoutException())); + this.connection(), state, value.getData(), TransactionResult.failure(new TimeoutException())); } }) .build().asMap(); diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/AbstractPacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/AbstractPacketChannel.java index 2ea29e4fc64..48a1723f411 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/AbstractPacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/AbstractPacketChannel.java @@ -28,6 +28,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; import org.spongepowered.api.network.channel.ChannelIOException; @@ -210,36 +211,39 @@ public Optional> binding(final int opcode) { return Optional.ofNullable(this.byOpcode.get(opcode)); } - protected

, R extends Packet, C extends EngineConnection> void handleResponse(final C connection, + protected

, R extends Packet, S extends EngineConnectionState> void handleResponse( + final EngineConnection connection, final S state, final TransactionalPacketBinding binding, final P request, final R response) { - for (final ResponsePacketHandler handler : - ((SpongeTransactionalPacketBinding) binding).getResponseHandlers(connection)) { + for (final ResponsePacketHandler handler : + ((SpongeTransactionalPacketBinding) binding).getResponseHandlers(state)) { try { - handler.handleResponse(response, request, connection); + handler.handleResponse(response, request, state); } catch (final Throwable t) { - this.handleException(connection, new ChannelException("Failed to handle packet", t), null); + this.handleException(connection, state, new ChannelException("Failed to handle packet", t), null); } } } - protected

, R extends Packet, C extends EngineConnection> void handleResponseFailure(final C connection, - final TransactionalPacketBinding binding, final P request, final ChannelException response) { - for (final ResponsePacketHandler handler : - ((SpongeTransactionalPacketBinding) binding).getResponseHandlers(connection)) { + protected

, R extends Packet, S extends EngineConnectionState> void handleResponseFailure( + final EngineConnection connection, final S state, final TransactionalPacketBinding binding, + final P request, final ChannelException response) { + for (final ResponsePacketHandler handler : + ((SpongeTransactionalPacketBinding) binding).getResponseHandlers(state)) { try { - handler.handleFailure(response, request, connection); + handler.handleFailure(response, request, state); } catch (final Throwable t) { - this.handleException(connection, new ChannelException("Failed to handle packet failure", t), null); + this.handleException(connection, state, new ChannelException("Failed to handle packet failure", t), null); } } } - protected

void handle(final C connection, final HandlerPacketBinding

binding, final P packet) { - for (final PacketHandler handler : ((SpongeHandlerPacketBinding

) binding).getHandlers(connection)) { + protected

void handle(final EngineConnection connection, final S state, + final HandlerPacketBinding

binding, final P packet) { + for (final PacketHandler handler : ((SpongeHandlerPacketBinding

) binding).getHandlers(state)) { try { - handler.handle(packet, connection); + handler.handle(packet, state); } catch (final Throwable t) { - this.handleException(connection, new ChannelException("Failed to handle packet", t), null); + this.handleException(connection, state, new ChannelException("Failed to handle packet", t), null); } } } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/PacketToResponseHandler.java b/src/main/java/org/spongepowered/common/network/channel/packet/PacketToResponseHandler.java index e64b9648a82..2f87f55c8a7 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/PacketToResponseHandler.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/PacketToResponseHandler.java @@ -24,23 +24,23 @@ */ package org.spongepowered.common.network.channel.packet; -import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.packet.Packet; import org.spongepowered.api.network.channel.packet.PacketHandler; import org.spongepowered.api.network.channel.packet.RequestPacket; import org.spongepowered.api.network.channel.packet.ResponsePacketHandler; -public final class PacketToResponseHandler

, R extends Packet, C extends EngineConnection> - implements ResponsePacketHandler { +public final class PacketToResponseHandler

, R extends Packet, S extends EngineConnectionState> + implements ResponsePacketHandler { - private final PacketHandler handler; + private final PacketHandler handler; - public PacketToResponseHandler(final PacketHandler handler) { + public PacketToResponseHandler(final PacketHandler handler) { this.handler = handler; } @Override - public void handleResponse(final R responsePacket, final P requestPacket, final C connection) { - this.handler.handle(responsePacket, connection); + public void handleResponse(final R responsePacket, final P requestPacket, final S state) { + this.handler.handle(responsePacket, state); } } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java index 627d44966a0..799523045e2 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeBasicPacketChannel.java @@ -43,6 +43,7 @@ import org.spongepowered.api.network.channel.packet.basic.BasicHandshakePacketDispatcher; import org.spongepowered.api.network.channel.packet.basic.BasicPacketChannel; import org.spongepowered.common.network.PacketUtil; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.ChannelBuffers; import org.spongepowered.common.network.channel.ChannelExceptionUtil; import org.spongepowered.common.network.channel.ConnectionUtil; @@ -64,17 +65,18 @@ public final class SpongeBasicPacketChannel extends AbstractPacketChannel implem @Override public CompletableFuture sendTo(final EngineConnection connection, final RequestPacket packet) { ConnectionUtil.checkHandshakePhase(connection); + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); if (connection instanceof ClientSideConnection) { throw new UnsupportedOperationException( "Request packets from the client to server are currently not supported for basic packet channels."); } final CompletableFuture future = new CompletableFuture<>(); - this.sendRequestTo(connection, packet, future::complete, null, future); + this.sendRequestTo(connection, state, packet, future::complete, null, future); return future; } - private

, R extends Packet> void sendRequestTo(final EngineConnection connection, final P request, - final @Nullable Consumer success, final @Nullable Runnable sendSuccess, final CompletableFuture future) { + private

, R extends Packet> void sendRequestTo(final EngineConnection connection, final EngineConnectionState state, + final P request, final @Nullable Consumer success, final @Nullable Runnable sendSuccess, final CompletableFuture future) { final SpongeTransactionalPacketBinding binding = (SpongeTransactionalPacketBinding) SpongeBasicPacketChannel.this.requireBinding(request.getClass()); @@ -82,7 +84,7 @@ private

, R extends Packet> void sendRequestTo(final try { payload = SpongeBasicPacketChannel.this.encodeLoginPayload(binding.opcode(), request); } catch (final Throwable ex) { - SpongeBasicPacketChannel.this.handleException(connection, ex, future); + SpongeBasicPacketChannel.this.handleException(connection, state, ex, future); return; } @@ -104,7 +106,7 @@ public void write(FriendlyByteBuf var1) { PacketSender.sendTo(connection, mcPacket, throwable -> { if (throwable != null) { // Failed before it could reach the client - SpongeBasicPacketChannel.this.handleException(connection, ChannelExceptionUtil.of(throwable), future); + SpongeBasicPacketChannel.this.handleException(connection, state, ChannelExceptionUtil.of(throwable), future); } else { final TransactionData transactionData = new TransactionData<>(request, binding, success, future); transactionStore.put(transactionId, SpongeBasicPacketChannel.this, transactionData); @@ -115,7 +117,7 @@ public void write(FriendlyByteBuf var1) { }); } - private CompletableFuture sendNormalTo(final EngineConnection connection, final Packet packet) { + private CompletableFuture sendNormalTo(final EngineConnection connection, final EngineConnectionState state, final Packet packet) { final PacketBinding binding = SpongeBasicPacketChannel.this.requireBinding(packet.getClass()); final CompletableFuture future = new CompletableFuture<>(); @@ -123,7 +125,7 @@ private CompletableFuture sendNormalTo(final EngineConnection connection, try { payload = SpongeBasicPacketChannel.this.encodePayload(binding.opcode(), packet); } catch (final Throwable ex) { - SpongeBasicPacketChannel.this.handleException(connection, ChannelExceptionUtil.of(ex), future); + SpongeBasicPacketChannel.this.handleException(connection, state, ChannelExceptionUtil.of(ex), future); return future; } @@ -150,17 +152,18 @@ public void write(FriendlyByteBuf var1) { @Override public CompletableFuture sendTo(final EngineConnection connection, final Packet packet) { ConnectionUtil.checkHandshakePhase(connection); + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); if (connection instanceof ClientSideConnection) { throw new UnsupportedOperationException( "Packets from the client to server are currently not supported for basic packet channels."); } if (packet instanceof RequestPacket) { final CompletableFuture future = new CompletableFuture<>(); - this.sendRequestTo(connection, (RequestPacket) packet, + this.sendRequestTo(connection, state, (RequestPacket) packet, result -> {}, () -> future.complete(null), future); return future; } else { - return this.sendNormalTo(connection, packet); + return this.sendNormalTo(connection, state, packet); } } @@ -187,11 +190,12 @@ public boolean isSupportedBy(final EngineConnection connection) { @Override public CompletableFuture sendTo(final EngineConnection connection, final Packet packet) { ConnectionUtil.checkPlayPhase(connection); + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); final PacketBinding binding = SpongeBasicPacketChannel.this.requireBinding(packet.getClass()); final CompletableFuture future = new CompletableFuture<>(); - if (!SpongeBasicPacketChannel.this.checkSupported(connection, future)) { + if (!SpongeBasicPacketChannel.this.checkSupported(connection, state, future)) { return future; } @@ -199,11 +203,11 @@ public CompletableFuture sendTo(final EngineConnection connection, final P try { payload = SpongeBasicPacketChannel.this.encodePayload(binding.opcode(), packet); } catch (final Throwable ex) { - SpongeBasicPacketChannel.this.handleException(connection, ex, future); + SpongeBasicPacketChannel.this.handleException(connection, state, ex, future); return future; } - final net.minecraft.network.protocol.Packet mcPacket = PacketUtil.createPlayPayload(SpongeBasicPacketChannel.this.key(), payload, connection.side()); + final net.minecraft.network.protocol.Packet mcPacket = PacketUtil.createPlayPayload(SpongeBasicPacketChannel.this.payloadType(), payload, connection.side()); PacketSender.sendTo(connection, mcPacket, future); return future; } @@ -251,25 +255,20 @@ private int readOpcode(final ChannelBuf payload) { } @Override - protected void handlePlayPayload(final EngineConnection connection, final ChannelBuf payload) { + protected void handlePlayPayload(final EngineConnection connection, final EngineConnectionState state, final ChannelBuf payload) { final int opcode = this.readOpcode(payload); final SpongePacketBinding binding = this.requireBinding(opcode); final Packet packet = this.decodePayload(() -> binding.getPacketConstructor().get(), payload); if (binding instanceof SpongeHandlerPacketBinding) { - this.handle(connection, (SpongeHandlerPacketBinding) binding, packet); + this.handle(connection, state, (SpongeHandlerPacketBinding) binding, packet); } } @Override - protected void handleLoginRequestPayload(final EngineConnection connection, final int transactionId, final ChannelBuf payload) { + protected void handleLoginRequestPayload(final EngineConnection connection, final EngineConnectionState state, final int transactionId, final ChannelBuf payload) { // Is currently always executed on the client, // the server always expects a response - final @Nullable EngineConnectionState state = connection.state().orElse(null); - if (state == null) { - return; - } - final int opcode = this.readOpcode(payload); final SpongePacketBinding binding = this.requireBinding(opcode); final Packet packet = this.decodePayload(() -> binding.getPacketConstructor().get(), payload); @@ -277,7 +276,7 @@ protected void handleLoginRequestPayload(final EngineConnection connection, fina // A normal packet binding if (binding instanceof SpongeHandlerPacketBinding) { final SpongeHandlerPacketBinding handlerBinding = (SpongeHandlerPacketBinding) binding; - this.handle(connection, handlerBinding, packet); + this.handle(connection, state, handlerBinding, packet); // The server always expects a response PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, transactionId)); } else { @@ -305,7 +304,7 @@ protected void success0(final Packet response) { }, transactionId); PacketSender.sendTo(connection, mcPacket); } catch (final Throwable ex) { - SpongeBasicPacketChannel.this.handleException(connection, new ChannelIOException("Failed to encode response packet", ex), null); + SpongeBasicPacketChannel.this.handleException(connection, state, new ChannelIOException("Failed to encode response packet", ex), null); } } }; @@ -313,7 +312,7 @@ protected void success0(final Packet response) { handler.handleRequest(packet, state, response); success = true; } catch (final Throwable ex) { - this.handleException(connection, new ChannelIOException("Failed to handle request packet", ex), null); + this.handleException(connection, state, new ChannelIOException("Failed to handle request packet", ex), null); } } if (!success) { @@ -324,14 +323,14 @@ protected void success0(final Packet response) { } @Override - protected void handleTransactionResponse(final EngineConnection connection, final Object stored, final TransactionResult result) { + protected void handleTransactionResponse(final EngineConnection connection, final EngineConnectionState state, final Object stored, final TransactionResult result) { final TransactionData, Packet> transactionData = (TransactionData, Packet>) stored; - this.handleTransactionResponse(connection, transactionData, result); + this.handleTransactionResponse(connection, state, transactionData, result); } private

, R extends Packet> void handleTransactionResponse(final EngineConnection connection, - final TransactionData transactionData, final TransactionResult result) { + final EngineConnectionState state, final TransactionData transactionData, final TransactionResult result) { final SpongeTransactionalPacketBinding binding = transactionData.binding; final P request = transactionData.request; if (result.isSuccess()) { @@ -362,13 +361,13 @@ private

, R extends Packet> void handleTransactionRes transactionData.success.accept(responsePacket); } - this.handleResponse(connection, binding, request, responsePacket); + this.handleResponse(connection, state, binding, request, responsePacket); } catch (final Throwable ex) { - this.handleException(connection, ex, transactionData.future); + this.handleException(connection, state, ex, transactionData.future); } } else { - this.handleException(connection, result.getCause(), transactionData.future); - this.handleResponseFailure(connection, binding, request, result.getCause()); + this.handleException(connection, state, result.getCause(), transactionData.future); + this.handleResponseFailure(connection, state, binding, request, result.getCause()); } } } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java index 23c589e45a6..0283d3537e9 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java @@ -26,6 +26,7 @@ import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.packet.HandlerPacketBinding; import org.spongepowered.api.network.channel.packet.Packet; import org.spongepowered.api.network.channel.packet.PacketBinding; @@ -45,45 +46,31 @@ public final class SpongeHandlerPacketBinding

extends SpongePa super(opcode, packetType); } - public Collection> getHandlers(final C connection) { - return (Collection) SpongeChannel.getResponseHandlers(connection, this.handlers.get()); + public Collection> getHandlers(final S state) { + return (Collection) SpongeChannel.getResponseHandlers(state, this.handlers.get()); } @Override - public PacketBinding

addHandler(final EngineConnectionSide side, - final PacketHandler handler) { - Objects.requireNonNull(side, "side"); - return this.addHandler(SpongeChannel.getConnectionClass(side), handler); - } - - @Override - public PacketBinding

addHandler(final Class connectionType, - final PacketHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + public PacketBinding

addHandler(final Class connectionState, + final PacketHandler handler) { + Objects.requireNonNull(connectionState, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.handlers.modify(map -> map.put(connectionType, handler)); + this.handlers.modify(map -> map.put(connectionState, handler)); return this; } @Override - public PacketBinding

addHandler(final PacketHandler handler) { - return this.addHandler(EngineConnection.class, handler); - } - - @Override - public PacketBinding

removeHandler(final EngineConnectionSide side, - final PacketHandler handler) { - Objects.requireNonNull(side, "side"); - return this.removeHandler(SpongeChannel.getConnectionClass(side), handler); + public PacketBinding

addHandler(final PacketHandler handler) { + return this.addHandler(EngineConnectionState.class, handler); } @Override - public PacketBinding

removeHandler(final Class connectionType, - final PacketHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + public PacketBinding

removeHandler(final Class connectionState, + final PacketHandler handler) { + Objects.requireNonNull(connectionState, "connectionType"); Objects.requireNonNull(handler, "handler"); this.handlers.modify(map -> map.entries() - .removeIf(entry -> entry.getKey().isAssignableFrom(connectionType) && entry.getValue() == handler)); + .removeIf(entry -> entry.getKey().isAssignableFrom(connectionState) && entry.getValue() == handler)); return this; } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java index 6aa08e36256..d7c0073d20f 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java @@ -41,6 +41,7 @@ import org.spongepowered.api.network.channel.packet.RequestPacket; import org.spongepowered.api.network.channel.packet.RequestPacketHandler; import org.spongepowered.common.network.PacketUtil; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.SpongeChannelManager; @@ -94,10 +95,8 @@ public SpongePacketChannel(final int type, final ResourceKey key, final SpongeCh super(type, key, manager); } - private

, R extends Packet> void sendRequestPacketTo(final EngineConnection connection, final P packet, - final CompletableFuture future, - final @Nullable Consumer response, - final @Nullable Runnable sendSuccess) { + private

, R extends Packet> void sendRequestPacketTo(final EngineConnection connection, final EngineConnectionState state, + final P packet, final CompletableFuture future, final @Nullable Consumer response, final @Nullable Runnable sendSuccess) { final SpongeTransactionalPacketBinding binding = (SpongeTransactionalPacketBinding) this.requireBinding(packet.getClass()); @@ -136,13 +135,13 @@ public void write(FriendlyByteBuf var1) { } else { payload.writeVarLong(SpongePacketChannel.packTypeAndValue(SpongePacketChannel.TYPE_REQUEST, transactionId)); payload.writeVarInt(binding.opcode()); - mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.key(), payload, side); + mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.payloadType(), payload, side); } try { this.encodePayload(payload, packet); } catch (final Throwable ex) { - this.handleException(connection, ex, future); + this.handleException(connection, state, ex, future); return; } @@ -154,7 +153,7 @@ public void write(FriendlyByteBuf var1) { final net.minecraft.network.protocol.Packet mcPacket = mcPacketSupplier.get(); PacketSender.sendTo(connection, mcPacket, throwable -> { if (throwable != null) { - this.handleException(connection, throwable, future); + this.handleException(connection, state, throwable, future); // Failed before it could reach the client, so complete it // and remove it from the store if (response != null) { @@ -167,7 +166,8 @@ public void write(FriendlyByteBuf var1) { } private

, R extends Packet> void sendResponsePacketTo(final EngineConnection connection, - final @Nullable SpongeTransactionalPacketBinding requestBinding, final @Nullable R packet, final int transactionId) { + final EngineConnectionState state, final @Nullable SpongeTransactionalPacketBinding requestBinding, + final @Nullable R packet, final int transactionId) { final boolean isLoginPhase = ConnectionUtil.isLoginPhase(connection); final EngineConnectionSide side = connection.side(); @@ -199,7 +199,7 @@ public void write(FriendlyByteBuf var1) { } } else { payload.writeVarLong(SpongePacketChannel.packTypeAndValue(type, transactionId)); - mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.key(), payload, side); + mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.payloadType(), payload, side); } } else { // Dynamic opcode @@ -229,15 +229,17 @@ public void write(FriendlyByteBuf var1) { } else { payload.writeVarLong(SpongePacketChannel.packTypeAndValue(SpongePacketChannel.TYPE_DYNAMIC_RESPONSE, transactionId)); payload.writeVarInt(opcode); - mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.key(), payload, side); + mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.payloadType(), payload, side); } } - try { - this.encodePayload(payload, packet); - } catch (final Throwable ex) { - this.handleException(connection, new ChannelIOException("Failed to encode request response", ex), null); - return; + if (packet != null) { + try { + this.encodePayload(payload, packet); + } catch (final Throwable ex) { + this.handleException(connection, state, new ChannelIOException("Failed to encode request response", ex), null); + return; + } } final net.minecraft.network.protocol.Packet mcPacket = mcPacketSupplier.get(); @@ -279,7 +281,7 @@ public void write(FriendlyByteBuf var1) { } } else { payload.writeVarLong(SpongePacketChannel.packTypeAndValue(SpongePacketChannel.TYPE_NORMAL, binding.opcode())); - mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.key(), payload, side); + mcPacketSupplier = () -> PacketUtil.createPlayPayload(this.payloadType(), payload, side); } try { @@ -295,11 +297,12 @@ public void write(FriendlyByteBuf var1) { @Override public CompletableFuture sendTo(final EngineConnection connection, final RequestPacket packet) { + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); final CompletableFuture future = new CompletableFuture<>(); - if (!this.checkSupported(connection, future)) { + if (!this.checkSupported(connection, state, future)) { return future; } - this.sendRequestPacketTo(connection, packet, future, future::complete, null); + this.sendRequestPacketTo(connection, state, packet, future, future::complete, null); return future; } @@ -311,12 +314,13 @@ public boolean isSupportedBy(final EngineConnection connection) { @Override public CompletableFuture sendTo(final EngineConnection connection, final Packet packet) { + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); final CompletableFuture future = new CompletableFuture<>(); - if (!this.checkSupported(connection, future)) { + if (!this.checkSupported(connection, state, future)) { return future; } if (packet instanceof RequestPacket) { - this.sendRequestPacketTo(connection, (RequestPacket) packet, + this.sendRequestPacketTo(connection, state, (RequestPacket) packet, future, null, () -> future.complete(null)); } else { this.sendNormalPacketTo(connection, packet, future); @@ -324,7 +328,7 @@ public CompletableFuture sendTo(final EngineConnection connection, final P return future; } - private void handleResponsePacket(final EngineConnection connection, final int transactionId, final @Nullable ChannelBuf payload, + private void handleResponsePacket(final EngineConnection connection, final EngineConnectionState state, final int transactionId, final @Nullable ChannelBuf payload, final int dynamicOpcode) { final TransactionStore store = ConnectionUtil.getTransactionStore(connection); final TransactionStore.Entry stored = store.remove(transactionId); @@ -335,24 +339,19 @@ private void handleResponsePacket(final EngineConnection connection, final int t (TransactionData, Packet>) stored.getData(); final TransactionResult result = payload == null ? TransactionResult.failure(new NoResponseException()) : TransactionResult.success(payload); - this.handleTransactionResponse(connection, transactionData, result, dynamicOpcode); + this.handleTransactionResponse(connection, state, transactionData, result, dynamicOpcode); } - private void handleRequestPacket(final EngineConnection connection, + private void handleRequestPacket(final EngineConnection connection, final EngineConnectionState state, final int opcode, final int transactionId, final ChannelBuf payload) { - final @Nullable EngineConnectionState state = connection.state().orElse(null); - if (state == null) { - return; - } - final SpongePacketBinding binding = this.requireBinding(opcode); final Packet request; try { request = this.decodePayload(binding.getPacketConstructor(), payload); } catch (final Throwable ex) { - this.sendResponsePacketTo(connection, null, null, transactionId); - this.handleException(connection, new ChannelIOException("Failed to decode request packet", ex), null); + this.sendResponsePacketTo(connection, state, null, null, transactionId); + this.handleException(connection, state, new ChannelIOException("Failed to decode request packet", ex), null); return; } @@ -370,86 +369,86 @@ private void handleRequestPacket(final EngineConnection connection, @Override protected void fail0(final ChannelException exception) { // TODO: Use response failure? - SpongePacketChannel.this.sendResponsePacketTo(connection, null, null, transactionId); + SpongePacketChannel.this.sendResponsePacketTo(connection, state, null, null, transactionId); } @Override protected void success0(final Packet response) { - SpongePacketChannel.this.sendResponsePacketTo(connection, (SpongeTransactionalPacketBinding) binding, response, transactionId); + SpongePacketChannel.this.sendResponsePacketTo(connection, state, (SpongeTransactionalPacketBinding) binding, response, transactionId); } }; try { handler.handleRequest((RequestPacket) request, state, requestPacketResponse); success = true; } catch (final Throwable ex) { - this.handleException(connection, new ChannelException("Failed to handle request packet", ex), null); + this.handleException(connection, state, new ChannelException("Failed to handle request packet", ex), null); responseFailure = ex; } } } if (!success) { // TODO: Use response failure? - this.sendResponsePacketTo(connection, null, null, transactionId); + this.sendResponsePacketTo(connection, state, null, null, transactionId); } } - private void handleNormalPacket(final EngineConnection connection, final int opcode, final ChannelBuf payload) { + private void handleNormalPacket(final EngineConnection connection, final EngineConnectionState state, final int opcode, final ChannelBuf payload) { final SpongePacketBinding binding = this.requireBinding(opcode); final Packet packet = this.decodePayload(binding.getPacketConstructor(), payload); if (binding instanceof SpongeHandlerPacketBinding) { - this.handle(connection, (SpongeHandlerPacketBinding) binding, packet); + this.handle(connection, state, (SpongeHandlerPacketBinding) binding, packet); } } @Override - protected void handlePlayPayload(final EngineConnection connection, final ChannelBuf payload) { + protected void handlePlayPayload(final EngineConnection connection, final EngineConnectionState state, final ChannelBuf payload) { final long typeAndValue = payload.readVarLong(); final int type = SpongePacketChannel.extractType(typeAndValue); final int value = SpongePacketChannel.extractValue(typeAndValue); if (type == SpongePacketChannel.TYPE_NORMAL) { - this.handleNormalPacket(connection, value, payload); + this.handleNormalPacket(connection, state, value, payload); } else if (type == SpongePacketChannel.TYPE_REQUEST) { final int opcode = payload.readVarInt(); - this.handleRequestPacket(connection, opcode, value, payload); + this.handleRequestPacket(connection, state, opcode, value, payload); } else if (type == SpongePacketChannel.TYPE_RESPONSE) { - this.handleResponsePacket(connection, value, payload, SpongePacketChannel.NO_DYNAMIC_OPCODE); + this.handleResponsePacket(connection, state, value, payload, SpongePacketChannel.NO_DYNAMIC_OPCODE); } else if (type == SpongePacketChannel.TYPE_NO_RESPONSE) { - this.handleResponsePacket(connection, value, null, SpongePacketChannel.NO_DYNAMIC_OPCODE); + this.handleResponsePacket(connection, state, value, null, SpongePacketChannel.NO_DYNAMIC_OPCODE); } else if (type == SpongePacketChannel.TYPE_DYNAMIC_RESPONSE) { final int opcode = payload.readVarInt(); - this.handleResponsePacket(connection, value, payload, opcode); + this.handleResponsePacket(connection, state, value, payload, opcode); } else { - this.handleException(connection, new ChannelIOException("Unknown packet type: " + type), null); + this.handleException(connection, state, new ChannelIOException("Unknown packet type: " + type), null); } } @Override - protected void handleLoginRequestPayload(final EngineConnection connection, final int transactionId, final ChannelBuf payload) { + protected void handleLoginRequestPayload(final EngineConnection connection, EngineConnectionState state, final int transactionId, final ChannelBuf payload) { final long typeAndValue = payload.readVarLong(); final int type = SpongePacketChannel.extractType(typeAndValue); final int value = SpongePacketChannel.extractValue(typeAndValue); if (type == SpongePacketChannel.TYPE_NORMAL) { - this.handleNormalPacket(connection, value, payload); + this.handleNormalPacket(connection, state, value, payload); } else if (type == SpongePacketChannel.TYPE_REQUEST) { - this.handleRequestPacket(connection, value, transactionId, payload); + this.handleRequestPacket(connection, state, value, transactionId, payload); } else if (type == SpongePacketChannel.TYPE_RESPONSE) { - this.handleResponsePacket(connection, transactionId, payload, SpongePacketChannel.NO_DYNAMIC_OPCODE); + this.handleResponsePacket(connection, state, transactionId, payload, SpongePacketChannel.NO_DYNAMIC_OPCODE); } else if (type == SpongePacketChannel.TYPE_NO_RESPONSE) { - this.handleResponsePacket(connection, transactionId, null, SpongePacketChannel.NO_DYNAMIC_OPCODE); + this.handleResponsePacket(connection, state, transactionId, null, SpongePacketChannel.NO_DYNAMIC_OPCODE); } else if (type == SpongePacketChannel.TYPE_DYNAMIC_RESPONSE) { - this.handleResponsePacket(connection, transactionId, payload, value); + this.handleResponsePacket(connection, state, transactionId, payload, value); } else { - this.handleException(connection, new ChannelIOException("Unknown packet type: " + type), null); + this.handleException(connection, state, new ChannelIOException("Unknown packet type: " + type), null); } } @Override - protected void handleTransactionResponse(final EngineConnection connection, final Object stored, final TransactionResult result) { + protected void handleTransactionResponse(final EngineConnection connection, EngineConnectionState state, final Object stored, final TransactionResult result) { if (result.isSuccess()) { final ChannelBuf payload = result.getPayload(); final long typeAndValue = payload.readVarLong(); @@ -463,22 +462,22 @@ protected void handleTransactionResponse(final EngineConnection connection, fina final TransactionData, Packet> transactionData = (TransactionData, Packet>) stored; if (type == SpongePacketChannel.TYPE_RESPONSE) { - this.handleTransactionResponse(connection, transactionData, result, SpongePacketChannel.NO_DYNAMIC_OPCODE); + this.handleTransactionResponse(connection, state, transactionData, result, SpongePacketChannel.NO_DYNAMIC_OPCODE); } else if (type == SpongePacketChannel.TYPE_NO_RESPONSE) { - this.handleTransactionResponse(connection, transactionData, + this.handleTransactionResponse(connection, state, transactionData, TransactionResult.failure(new NoResponseException()), SpongePacketChannel.NO_DYNAMIC_OPCODE ); } else { - this.handleTransactionResponse(connection, transactionData, result, value); + this.handleTransactionResponse(connection, state, transactionData, result, value); } } else { - this.handleException(connection, new ChannelIOException("Unknown packet type: " + type), null); + this.handleException(connection, state, new ChannelIOException("Unknown packet type: " + type), null); } } } private

, R extends Packet> void handleTransactionResponse(final EngineConnection connection, - final TransactionData transactionData, final TransactionResult result, final int dynamicOpcode) { + EngineConnectionState state, final TransactionData transactionData, final TransactionResult result, final int dynamicOpcode) { if (result.isSuccess()) { final ChannelBuf payload = result.getPayload(); @@ -500,22 +499,22 @@ private

, R extends Packet> void handleTransactionRes try { packet = this.decodePayload(packetSupplier, payload); } catch (final Throwable ex) { - this.handleException(connection, new ChannelIOException("Failed to decode packet", ex), transactionData.future); + this.handleException(connection, state, new ChannelIOException("Failed to decode packet", ex), transactionData.future); return; } if (responseBinding != null) { - this.handle(connection, (SpongeHandlerPacketBinding) responseBinding, packet); + this.handle(connection, state, (SpongeHandlerPacketBinding) responseBinding, packet); } else { - this.handleResponse(connection, transactionData.binding, transactionData.request, packet); + this.handleResponse(connection, state, transactionData.binding, transactionData.request, packet); } if (transactionData.success != null) { transactionData.success.accept(packet); } } else { - this.handleException(connection, result.getCause(), transactionData.future); - this.handleResponseFailure(connection, transactionData.binding, transactionData.request, result.getCause()); + this.handleException(connection, state, result.getCause(), transactionData.future); + this.handleResponseFailure(connection, state, transactionData.binding, transactionData.request, result.getCause()); } } diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java index 1404cc24e84..d94bd1e3a23 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeTransactionalPacketBinding.java @@ -25,8 +25,6 @@ package org.spongepowered.common.network.channel.packet; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.packet.Packet; import org.spongepowered.api.network.channel.packet.PacketHandler; @@ -54,17 +52,16 @@ public SpongeTransactionalPacketBinding(final int opcode, final Class

request super(opcode, requestPacketType); } - public @Nullable RequestPacketHandler getRequestHandler(final S connection) { - return null; //TODO: fix me - //return (RequestPacketHandler) SpongeChannel.getRequestHandler(connection, this.requestHandlers); + public @Nullable RequestPacketHandler getRequestHandler(final S state) { + return (RequestPacketHandler) SpongeChannel.getRequestHandler(state, this.requestHandlers); } @Override - public TransactionalPacketBinding setRequestHandler(final Class connectionType, + public TransactionalPacketBinding setRequestHandler(final Class connectioState, final RequestPacketHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + Objects.requireNonNull(connectioState, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.requestHandlers.put(connectionType, handler); + this.requestHandlers.put(connectioState, handler); return this; } @@ -75,50 +72,35 @@ public TransactionalPacketBinding setRequestHandler(final RequestPacketHan } @Override - public TransactionalPacketBinding addResponseHandler( - final EngineConnectionSide side, final PacketHandler handler) { - Objects.requireNonNull(side, "side"); - return this.addResponseHandler(SpongeChannel.getConnectionClass(side), handler); - } - - @Override - public TransactionalPacketBinding addResponseHandler(final Class connectionType, - final PacketHandler handler) { - Objects.requireNonNull(handler, "handler"); - return this.addResponseHandler(connectionType, new PacketToResponseHandler<>(handler)); - } - - @Override - public TransactionalPacketBinding addResponseHandler( - final EngineConnectionSide side, final ResponsePacketHandler handler) { - Objects.requireNonNull(side, "side"); + public TransactionalPacketBinding addResponseHandler(final Class connectionState, + final PacketHandler handler) { Objects.requireNonNull(handler, "handler"); - return this.addResponseHandler(SpongeChannel.getConnectionClass(side), handler); + return this.addResponseHandler(connectionState, new PacketToResponseHandler<>(handler)); } @Override - public TransactionalPacketBinding addResponseHandler(final Class connectionType, - final ResponsePacketHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + public TransactionalPacketBinding addResponseHandler(final Class connectionState, + final ResponsePacketHandler handler) { + Objects.requireNonNull(connectionState, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.responseHandlers.modify(map -> map.put(connectionType, handler)); + this.responseHandlers.modify(map -> map.put(connectionState, handler)); return this; } @Override public TransactionalPacketBinding addResponseHandler( - final PacketHandler handler) { + final PacketHandler handler) { Objects.requireNonNull(handler, "handler"); return this.addResponseHandler(new PacketToResponseHandler<>(handler)); } @Override - public TransactionalPacketBinding addResponseHandler(final ResponsePacketHandler handler) { - return this.addResponseHandler(EngineConnection.class, handler); + public TransactionalPacketBinding addResponseHandler(final ResponsePacketHandler handler) { + return this.addResponseHandler(EngineConnectionState.class, handler); } - public Collection> getResponseHandlers(final C connection) { - return (Collection) SpongeChannel.getResponseHandlers(connection, this.responseHandlers.get()); + public Collection> getResponseHandlers(final S state) { + return (Collection) SpongeChannel.getResponseHandlers(state, this.responseHandlers.get()); } @Override diff --git a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawDataChannel.java b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawDataChannel.java index d627b7cc091..b5d7c760c1d 100644 --- a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawDataChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawDataChannel.java @@ -26,6 +26,7 @@ import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.raw.RawDataChannel; import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataChannel; @@ -56,17 +57,17 @@ public RawHandshakeDataChannel handshake() { } @Override - protected void handlePlayPayload(final EngineConnection connection, final ChannelBuf payload) { - this.play.handlePayload(connection, payload); + protected void handlePlayPayload(final EngineConnection connection, final EngineConnectionState state, final ChannelBuf payload) { + this.play.handlePayload(state, payload); } @Override - protected void handleLoginRequestPayload(EngineConnection connection, int transactionId, ChannelBuf payload) { - this.login.handleRequestPayload(connection, payload, transactionId); + protected void handleLoginRequestPayload(final EngineConnection connection, final EngineConnectionState state, final int transactionId, final ChannelBuf payload) { + this.login.handleRequestPayload(connection, state, payload, transactionId); } @Override - protected void handleTransactionResponse(EngineConnection connection, Object stored, TransactionResult result) { + protected void handleTransactionResponse(final EngineConnection connection, final EngineConnectionState state, final Object stored, final TransactionResult result) { this.login.handleTransactionResponse(connection, stored, result); } diff --git a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java index 3c2de0694fd..d79228f8ae0 100644 --- a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java @@ -28,9 +28,11 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.login.custom.CustomQueryPayload; import net.minecraft.resources.ResourceLocation; +import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; import org.spongepowered.api.network.channel.raw.RawDataChannel; @@ -38,6 +40,7 @@ import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataRequestHandler; import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataRequestResponse; import org.spongepowered.common.network.PacketUtil; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.SpongeChannel; @@ -61,8 +64,8 @@ public SpongeRawLoginDataChannel(final SpongeRawDataChannel parent) { this.parent = parent; } - private RawHandshakeDataRequestHandler getRequestHandler(final C connection) { - return (RawHandshakeDataRequestHandler) SpongeChannel.getRequestHandler(connection, this.requestHandlers); + private RawHandshakeDataRequestHandler getRequestHandler(final S state) { + return (RawHandshakeDataRequestHandler) SpongeChannel.getRequestHandler(state, this.requestHandlers); } @Override @@ -71,27 +74,20 @@ public RawDataChannel parent() { } @Override - public void setRequestHandler(final EngineConnectionSide side, - final RawHandshakeDataRequestHandler handler) { - Objects.requireNonNull(side, "side"); - this.setRequestHandler(SpongeChannel.getConnectionClass(side), handler); + public void setRequestHandler(final RawHandshakeDataRequestHandler handler) { + this.setRequestHandler(EngineConnectionState.class, handler); } @Override - public void setRequestHandler(final RawHandshakeDataRequestHandler handler) { - this.setRequestHandler(EngineConnection.class, handler); - } - - @Override - public void setRequestHandler(final Class connectionType, - final RawHandshakeDataRequestHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + public void setRequestHandler(final Class state, + final RawHandshakeDataRequestHandler handler) { + Objects.requireNonNull(state, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.requestHandlers.put(connectionType, handler); + this.requestHandlers.put(state, handler); } - void handleRequestPayload(final C connection, final ChannelBuf payload, final int transactionId) { - final RawHandshakeDataRequestHandler handler = this.getRequestHandler(connection); + void handleRequestPayload(final EngineConnection connection, final S state, final ChannelBuf payload, final int transactionId) { + final RawHandshakeDataRequestHandler handler = this.getRequestHandler(state); final RawHandshakeDataRequestResponse response = new RawHandshakeDataRequestResponse() { private boolean completed; @@ -117,7 +113,7 @@ public void success(final Consumer response) { try { payload = SpongeRawLoginDataChannel.this.parent.encodePayload(response); } catch (final Throwable t) { - SpongeRawLoginDataChannel.this.parent.handleException(connection, new ChannelException("Failed to encode login data response", t), null); + SpongeRawLoginDataChannel.this.parent.handleException(connection, state, new ChannelException("Failed to encode login data response", t), null); PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, transactionId)); return; } @@ -129,10 +125,10 @@ public void success(final Consumer response) { boolean success = false; if (handler != null) { try { - handler.handleRequest(payload, connection, response); + handler.handleRequest(payload, state, response); success = true; } catch (final Throwable t) { - this.parent.handleException(connection, new ChannelException("Failed to handle login data request", t), null); + this.parent.handleException(connection, state, new ChannelException("Failed to handle login data request", t), null); } } if (!success) { @@ -151,12 +147,14 @@ void handleTransactionResponse(final EngineConnection connection, final Object s public CompletableFuture sendTo(final EngineConnection connection, final Consumer payload) { ConnectionUtil.checkHandshakePhase(connection); + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); + final CompletableFuture future = new CompletableFuture<>(); final ChannelBuf buf; try { buf = this.parent.encodePayload(payload); } catch (final Throwable t) { - this.parent.handleException(connection, t, future); + this.parent.handleException(connection, state, t, future); return future; } @@ -167,7 +165,7 @@ public CompletableFuture sendTo(final EngineConnection connection, f if (result.isSuccess()) { future.complete(result.getPayload()); } else { - this.parent.handleException(connection, result.getCause(), future); + this.parent.handleException(connection, state, result.getCause(), future); } }; diff --git a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java index bb1cf77de9c..ccd1a4981ac 100644 --- a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java @@ -27,10 +27,12 @@ import net.minecraft.network.protocol.Packet; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel; import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler; import org.spongepowered.common.network.PacketUtil; +import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.channel.ConcurrentMultimap; import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.PacketSender; @@ -63,22 +65,15 @@ public boolean isSupportedBy(final EngineConnection connection) { } @Override - public void addHandler(final RawPlayDataHandler handler) { - this.addHandler(EngineConnection.class, handler); + public void addHandler(final RawPlayDataHandler handler) { + this.addHandler(EngineConnectionState.class, handler); } @Override - public void addHandler(final EngineConnectionSide side, final RawPlayDataHandler handler) { - Objects.requireNonNull(side, "side"); + public void addHandler(final Class connectionState, final RawPlayDataHandler handler) { + Objects.requireNonNull(connectionState, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.addHandler(SpongeChannel.getConnectionClass(side), handler); - } - - @Override - public void addHandler(final Class connectionType, final RawPlayDataHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); - Objects.requireNonNull(handler, "handler"); - this.handlers.modify(map -> map.put(connectionType, handler)); + this.handlers.modify(map -> map.put(connectionState, handler)); } @Override @@ -88,16 +83,10 @@ public void removeHandler(final RawPlayDataHandler handler) { } @Override - public void removeHandler(final EngineConnectionSide side, final RawPlayDataHandler handler) { - Objects.requireNonNull(side, "side"); - this.removeHandler(SpongeChannel.getConnectionClass(side), handler); - } - - @Override - public void removeHandler(final Class connectionType, final RawPlayDataHandler handler) { - Objects.requireNonNull(connectionType, "connectionType"); + public void removeHandler(final Class connectionState, final RawPlayDataHandler handler) { + Objects.requireNonNull(connectionState, "connectionType"); Objects.requireNonNull(handler, "handler"); - this.handlers.modify(map -> map.entries().removeIf(entry -> entry.getKey().isAssignableFrom(connectionType) && entry.getValue() == handler)); + this.handlers.modify(map -> map.entries().removeIf(entry -> entry.getKey().isAssignableFrom(connectionState) && entry.getValue() == handler)); } @Override @@ -107,27 +96,29 @@ public CompletableFuture sendTo(final EngineConnection connection, final C ConnectionUtil.checkPlayPhase(connection); + final EngineConnectionState state = (EngineConnectionState) ((SpongeEngineConnection) connection).connection().getPacketListener(); + final CompletableFuture future = new CompletableFuture<>(); final ChannelBuf payload; try { payload = this.parent.encodePayload(consumer); } catch (final Throwable ex) { - this.parent.handleException(connection, ex, future); + this.parent.handleException(connection, state, ex, future); return future; } - final Packet mcPacket = PacketUtil.createPlayPayload(this.parent.key(), payload, connection.side()); + final Packet mcPacket = PacketUtil.createPlayPayload(this.parent.payloadType(), payload, connection.side()); PacketSender.sendTo(connection, mcPacket, future); return future; } - private Collection> getHandlers(final C connection) { - return (Collection) SpongeChannel.getResponseHandlers(connection, this.handlers.get()); + private Collection> getHandlers(final S state) { + return (Collection) SpongeChannel.getResponseHandlers(state, this.handlers.get()); } - void handlePayload(final C connection, final ChannelBuf payload) { - for (final RawPlayDataHandler handler : this.getHandlers(connection)) { - handler.handlePayload(payload.slice(), connection); + void handlePayload(final S state, final ChannelBuf payload) { + for (final RawPlayDataHandler handler : this.getHandlers(state)) { + handler.handlePayload(payload.slice(), state); } } } diff --git a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java index 3a4cee69aa0..e6b404e838a 100644 --- a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java +++ b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java @@ -33,6 +33,7 @@ import net.minecraft.world.level.dimension.DimensionType; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.entity.living.player.server.ServerPlayer; +import org.spongepowered.api.network.ClientConnectionState; import org.spongepowered.api.network.ClientSideConnection; import org.spongepowered.api.network.EngineConnectionStates; import org.spongepowered.api.network.channel.packet.PacketChannel; @@ -91,7 +92,7 @@ public static void init(final SpongeChannelManager registry) { response.success(SpongePacketHandler.createTrackerDataResponse(owner, notifier)); }); - SpongePacketHandler.channel.register(ChangeViewerEnvironmentPacket.class, 3).addHandler(ClientSideConnection.class, + SpongePacketHandler.channel.register(ChangeViewerEnvironmentPacket.class, 3).addHandler(ClientConnectionState.class, (packet, connection) -> { final ClientLevel world = Minecraft.getInstance().level; if (world == null) { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java index 8c4bf928714..9971f26d153 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/network/ServerConfigurationPacketListenerImplMixin.java @@ -49,6 +49,7 @@ import org.spongepowered.common.bridge.server.players.PlayerListBridge; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.network.channel.ConnectionUtil; +import org.spongepowered.common.network.channel.SpongeChannelManager; import org.spongepowered.common.network.channel.TransactionStore; import org.spongepowered.common.profile.SpongeGameProfile; @@ -112,10 +113,6 @@ public abstract class ServerConfigurationPacketListenerImplMixin extends ServerC } } - //TODO: Fix me - /*((SpongeChannelManager) SpongeCommon.game().channelManager()).sendChannelRegistrations( - ((ConnectionBridge) this.connection).bridge$getEngineConnection());*/ - try { this.impl$skipBanService = true; this.shadow$handleConfigurationFinished($$0); @@ -180,4 +177,11 @@ public Type type() { this.shadow$finishCurrentTask(ServerConfigurationPacketListenerImplMixin.impl$SPONGE_CONFIGURATION_TYPE); } } + + @Inject(method = "handleConfigurationFinished", at = @At(value = "INVOKE", + target = "Lnet/minecraft/server/players/PlayerList;getPlayerForLogin(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/server/level/ClientInformation;)Lnet/minecraft/server/level/ServerPlayer;")) + private void impl$sendChannels(final CallbackInfo ci) { + ((SpongeChannelManager) SpongeCommon.game().channelManager()).sendChannelRegistrations( + ((ConnectionBridge) this.connection).bridge$getEngineConnection()); + } } diff --git a/testplugins/src/main/java/org/spongepowered/test/channel/ChannelTest.java b/testplugins/src/main/java/org/spongepowered/test/channel/ChannelTest.java index 484b2b788e9..4919f95586e 100644 --- a/testplugins/src/main/java/org/spongepowered/test/channel/ChannelTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/channel/ChannelTest.java @@ -26,6 +26,8 @@ import com.google.inject.Inject; import org.spongepowered.api.ResourceKey; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.lifecycle.RegisterChannelEvent; import org.spongepowered.api.event.network.ServerSideConnectionEvent; import org.spongepowered.api.network.ClientConnectionState; @@ -46,162 +48,170 @@ @Plugin("channeltest") public final class ChannelTest { - private final PluginContainer plugin; + private static final boolean ENABLED = Boolean.getBoolean("sponge.channelTest"); - private PacketChannel channel; - private BasicPacketChannel basicChannel; - private RawDataChannel rawChannel; + private final PluginContainer plugin; @Inject public ChannelTest(final PluginContainer plugin) { this.plugin = plugin; + if (ChannelTest.ENABLED) { + Sponge.game().eventManager().registerListeners(this.plugin, new Listeners()); + } } -// @Listener - private void onRegisterChannel(final RegisterChannelEvent event) { - this.channel = event.register(ResourceKey.of("channeltest", "default"), PacketChannel.class); - this.channel.register(PrintTextPacket.class, 0) - .addHandler((packet, connection) -> { - this.logReceived(this.channel, packet, connection); - this.plugin.logger().info(packet.getText()); - }); - this.channel.registerTransactional(PingPacket.class, PongPacket.class, 1) - .setRequestHandler((requestPacket, connection, response) -> { - this.logReceived(this.channel, requestPacket, connection); - response.success(new PongPacket(requestPacket.getId())); - }); - - this.basicChannel = event.register(ResourceKey.of("channeltest", "basic"), BasicPacketChannel.class); - this.basicChannel.register(PrintTextPacket.class, 0) - .addHandler((packet, connection) -> { - this.logReceived(this.basicChannel, packet, connection); - this.plugin.logger().info(packet.getText()); - }); - this.basicChannel.registerTransactional(PingPacket.class, PongPacket.class, 1) - .setRequestHandler((requestPacket, connection, response) -> { - this.logReceived(this.basicChannel, requestPacket, connection); - response.success(new PongPacket(requestPacket.getId())); - }); - - this.rawChannel = event.register(ResourceKey.of("channeltest", "raw"), RawDataChannel.class); - this.rawChannel.handshake() - .setRequestHandler((request, connection, response) -> { - final int value = request.readVarInt(); - this.logReceived(this.rawChannel, value, connection); - if (value == 0) { - response.fail(new NoResponseException()); - } else { - response.success(buf -> buf.writeVarInt(value * 2)); - } - }); - } - -// @Listener - private void onConnectionHandshake(final ServerSideConnectionEvent.Handshake event) { - this.plugin.logger().info("Starting handshake phase."); - final PingPacket pingPacket1 = new PingPacket(123); - final ServerSideConnection connection = event.connection(); - this.channel.sendTo(connection, pingPacket1) - .thenAccept(response1 -> { - this.logReceived(this.channel, response1, connection); - final PingPacket pingPacket2 = new PingPacket(456); - this.channel.sendTo(connection, pingPacket2) - .thenAccept(response2 -> { - this.logReceived(this.channel, response2, connection); - this.channel.sendTo(connection, new PrintTextPacket("Finished handshake phase.")); - this.plugin.logger().info("Finished handshake phase."); - }) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to {}", pingPacket2, cause); - return null; - }); - }) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); - return null; - }); - - final PingPacket basicPingPacket1 = new PingPacket(1123); - this.basicChannel.handshake().sendTo(connection, basicPingPacket1) - .thenAccept(response1 -> { - this.logReceived(this.basicChannel, response1, connection); - final PingPacket basicPingPacket2 = new PingPacket(1456); - this.basicChannel.handshake().sendTo(connection, basicPingPacket2) - .thenAccept(response2 -> { - this.logReceived(this.channel, response2, connection); - this.basicChannel.handshake().sendTo(connection, new PrintTextPacket("Finished handshake phase for basic channel.")); - this.plugin.logger().info("Finished handshake phase for basic channel."); - }) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to {}", basicPingPacket2, cause); - return null; - }); - }) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); - return null; - }); - - this.rawChannel.handshake().sendTo(connection, buf -> buf.writeVarInt(200)) - .thenAccept(response -> this.logReceived(this.rawChannel, response.readVarInt(), connection)) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to raw 200 value", cause); - return null; - }); - - this.rawChannel.handshake().sendTo(connection, buf -> buf.writeVarInt(0)) - .thenAccept(response -> this.logReceived(this.rawChannel, response.readVarInt(), connection)) - .exceptionally(cause -> { - if (cause instanceof CompletionException) { - cause = cause.getCause(); - } - if (cause instanceof NoResponseException) { - this.plugin.logger().error("Successfully received no response exception"); - } else { - this.plugin.logger().error("Failed to get a response to raw 0 value", cause); - } - return null; - }); - } - -// @Listener - private void onConnectionLogin(final ServerSideConnectionEvent.Login event) { - this.plugin.logger().info("Player \"" + event.user().profile().name().orElse("unknown") + "\" is logging in."); - } - -// @Listener - private void onConnectionJoin(final ServerSideConnectionEvent.Join event) { - this.plugin.logger().info("Player \"" + event.player().name() + "\" joined."); - - final ServerSideConnection connection = event.connection(); - final PingPacket pingPacket1 = new PingPacket(789); - this.channel.sendTo(connection, pingPacket1) - .thenAccept(response1 -> this.logReceived(this.channel, response1, connection)) - .exceptionally(cause -> { - this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); - return null; - }); - - this.basicChannel.play().sendTo(connection, new PrintTextPacket("You successfully joined the server.")) - .exceptionally(cause -> { - this.plugin.logger().error(cause); - return null; - }); - } - - private static String getName(final EngineConnectionSide side) { - return side == EngineConnectionSide.CLIENT ? "client" : "server"; - } - - private static String getName(final EngineConnectionState side) { - return side instanceof ClientConnectionState ? "client" : "server"; - } - - private void logReceived(final Channel channel, final Object packet, final EngineConnection connection) { - this.plugin.logger().info("Received {} through {} on the {} side.", packet, channel.key(), ChannelTest.getName(connection.side())); - } - - private void logReceived(final Channel channel, final Object packet, final EngineConnectionState connection) { - this.plugin.logger().info("Received {} through {} on the {} side.", packet, channel.key(), ChannelTest.getName(connection)); + final class Listeners { + + private PacketChannel channel; + private BasicPacketChannel basicChannel; + private RawDataChannel rawChannel; + + @Listener + private void onRegisterChannel(final RegisterChannelEvent event) { + this.channel = event.register(ResourceKey.of("channeltest", "default"), PacketChannel.class); + this.channel.register(PrintTextPacket.class, 0) + .addHandler((packet, connection) -> { + this.logReceived(this.channel, packet, connection); + ChannelTest.this.plugin.logger().info(packet.getText()); + }); + this.channel.registerTransactional(PingPacket.class, PongPacket.class, 1) + .setRequestHandler((requestPacket, connection, response) -> { + this.logReceived(this.channel, requestPacket, connection); + response.success(new PongPacket(requestPacket.getId())); + }); + + this.basicChannel = event.register(ResourceKey.of("channeltest", "basic"), BasicPacketChannel.class); + this.basicChannel.register(PrintTextPacket.class, 0) + .addHandler((packet, connection) -> { + this.logReceived(this.basicChannel, packet, connection); + ChannelTest.this.plugin.logger().info(packet.getText()); + }); + this.basicChannel.registerTransactional(PingPacket.class, PongPacket.class, 1) + .setRequestHandler((requestPacket, connection, response) -> { + this.logReceived(this.basicChannel, requestPacket, connection); + response.success(new PongPacket(requestPacket.getId())); + }); + + this.rawChannel = event.register(ResourceKey.of("channeltest", "raw"), RawDataChannel.class); + this.rawChannel.handshake() + .setRequestHandler((request, connection, response) -> { + final int value = request.readVarInt(); + this.logReceived(this.rawChannel, value, connection); + if (value == 0) { + response.fail(new NoResponseException()); + } else { + response.success(buf -> buf.writeVarInt(value * 2)); + } + }); + } + + @Listener + private void onConnectionHandshake(final ServerSideConnectionEvent.Handshake event) { + ChannelTest.this.plugin.logger().info("Starting handshake phase."); + final PingPacket pingPacket1 = new PingPacket(123); + final ServerSideConnection connection = event.connection(); + this.channel.sendTo(connection, pingPacket1) + .thenAccept(response1 -> { + this.logReceived(this.channel, response1, connection); + final PingPacket pingPacket2 = new PingPacket(456); + this.channel.sendTo(connection, pingPacket2) + .thenAccept(response2 -> { + this.logReceived(this.channel, response2, connection); + this.channel.sendTo(connection, new PrintTextPacket("Finished handshake phase.")); + ChannelTest.this.plugin.logger().info("Finished handshake phase."); + }) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to {}", pingPacket2, cause); + return null; + }); + }) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); + return null; + }); + + final PingPacket basicPingPacket1 = new PingPacket(1123); + this.basicChannel.handshake().sendTo(connection, basicPingPacket1) + .thenAccept(response1 -> { + this.logReceived(this.basicChannel, response1, connection); + final PingPacket basicPingPacket2 = new PingPacket(1456); + this.basicChannel.handshake().sendTo(connection, basicPingPacket2) + .thenAccept(response2 -> { + this.logReceived(this.channel, response2, connection); + this.basicChannel.handshake().sendTo(connection, new PrintTextPacket("Finished handshake phase for basic channel.")); + ChannelTest.this.plugin.logger().info("Finished handshake phase for basic channel."); + }) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to {}", basicPingPacket2, cause); + return null; + }); + }) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); + return null; + }); + + this.rawChannel.handshake().sendTo(connection, buf -> buf.writeVarInt(200)) + .thenAccept(response -> this.logReceived(this.rawChannel, response.readVarInt(), connection)) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to raw 200 value", cause); + return null; + }); + + this.rawChannel.handshake().sendTo(connection, buf -> buf.writeVarInt(0)) + .thenAccept(response -> this.logReceived(this.rawChannel, response.readVarInt(), connection)) + .exceptionally(cause -> { + if (cause instanceof CompletionException) { + cause = cause.getCause(); + } + if (cause instanceof NoResponseException) { + ChannelTest.this.plugin.logger().error("Successfully received no response exception"); + } else { + ChannelTest.this.plugin.logger().error("Failed to get a response to raw 0 value", cause); + } + return null; + }); + } + + @Listener + private void onConnectionLogin(final ServerSideConnectionEvent.Login event) { + ChannelTest.this.plugin.logger().info("Player \"" + event.user().profile().name().orElse("unknown") + "\" is logging in."); + } + + @Listener + private void onConnectionJoin(final ServerSideConnectionEvent.Join event) { + ChannelTest.this.plugin.logger().info("Player \"" + event.player().name() + "\" joined."); + + final ServerSideConnection connection = event.connection(); + final PingPacket pingPacket1 = new PingPacket(789); + this.channel.sendTo(connection, pingPacket1) + .thenAccept(response1 -> this.logReceived(this.channel, response1, connection)) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error("Failed to get a response to {}", pingPacket1, cause); + return null; + }); + + this.basicChannel.play().sendTo(connection, new PrintTextPacket("You successfully joined the server.")) + .exceptionally(cause -> { + ChannelTest.this.plugin.logger().error(cause); + return null; + }); + } + + private static String getName(final EngineConnectionSide side) { + return side == EngineConnectionSide.CLIENT ? "client" : "server"; + } + + private static String getName(final EngineConnectionState side) { + return side instanceof ClientConnectionState ? "client" : "server"; + } + + private void logReceived(final Channel channel, final Object packet, final EngineConnection connection) { + ChannelTest.this.plugin.logger().info("Received {} through {} on the {} side.", packet, channel.key(), Listeners.getName(connection.side())); + } + + private void logReceived(final Channel channel, final Object packet, final EngineConnectionState connection) { + ChannelTest.this.plugin.logger().info("Received {} through {} on the {} side.", packet, channel.key(), Listeners.getName(connection)); + } } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin_Vanilla.java index bdd0d38b55e..e6959608dbb 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientHandshakePacketListenerImplMixin_Vanilla.java @@ -31,6 +31,7 @@ import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket; import org.spongepowered.api.Sponge; import org.spongepowered.api.network.EngineConnection; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -58,7 +59,7 @@ public abstract class ClientHandshakePacketListenerImplMixin_Vanilla implements final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); this.minecraft.execute(() -> { final EngineConnection connection = ((ConnectionBridge) this.connection).bridge$getEngineConnection(); - if (!channelRegistry.handleLoginRequestPayload(connection, packet)) { + if (!channelRegistry.handleLoginRequestPayload(connection, (EngineConnectionState) this, packet)) { PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, packet.transactionId())); } }); diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java index 85af2426f53..340fa0ee4df 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/client/multiplayer/ClientPacketListenerMixin_Vanilla.java @@ -32,6 +32,7 @@ import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.game.ClientGamePacketListener; import org.spongepowered.api.Sponge; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -49,7 +50,7 @@ protected ClientPacketListenerMixin_Vanilla(Minecraft $$0, Connection $$1, Commo @Inject(method = "handleCustomPayload", cancellable = true, at = @At(value = "HEAD")) private void vanilla$handleCustomPayload(final CustomPacketPayload packet, CallbackInfo ci) { final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - if (channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet)) { + if (channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), (EngineConnectionState) this, packet)) { ci.cancel(); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java index e386a0dd82d..65217f8062a 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/common/ClientboundCustomPayloadPacketMixin.java @@ -25,23 +25,35 @@ package org.spongepowered.vanilla.mixin.core.network.protocol.common; import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.common.network.channel.SpongeChannelManager; +import org.spongepowered.common.network.channel.ChannelUtils; import java.util.ArrayList; import java.util.List; +@SuppressWarnings({"rawtypes", "unchecked"}) @Mixin(ClientboundCustomPayloadPacket.class) public abstract class ClientboundCustomPayloadPacketMixin { + // @formatter: off + @Shadow @Final private static int MAX_PAYLOAD_SIZE; + // @formatter: on + + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Lists;newArrayList([Ljava/lang/Object;)Ljava/util/ArrayList;"), remap = false) + private static ArrayList vanilla$registerCustomPacketPayloadsGame(final Object[] registrations) { + final ArrayList allRegistrations = new ArrayList<>(List.of(registrations)); + allRegistrations.addAll(ChannelUtils.spongeChannelCodecs(ClientboundCustomPayloadPacketMixin.MAX_PAYLOAD_SIZE)); + return allRegistrations; + } + @Redirect(method = "", at = @At(value = "INVOKE", target = "Ljava/util/List;of(Ljava/lang/Object;)Ljava/util/List;")) - private static List vanilla$registerCustomPacketPayloads(Object registrations) { + private static List vanilla$registerCustomPacketPayloadsConfiguration(final Object registrations) { final List allRegistrations = new ArrayList<>(List.of(registrations)); - allRegistrations.add(new CustomPacketPayload.TypeAndCodec<>(SpongeChannelManager.SpongeRegisterChannelPayload.TYPE, SpongeChannelManager.SpongeRegisterChannelPayload.STREAM_CODEC)); + allRegistrations.addAll(ChannelUtils.spongeChannelCodecs(ClientboundCustomPayloadPacketMixin.MAX_PAYLOAD_SIZE)); return allRegistrations; } - } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/login/ClientboundCustomQueryPacketMixin.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/login/ClientboundCustomQueryPacketMixin.java new file mode 100644 index 00000000000..1f7bfa02f21 --- /dev/null +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/network/protocol/login/ClientboundCustomQueryPacketMixin.java @@ -0,0 +1,65 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.vanilla.mixin.core.network.protocol.login; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket; +import net.minecraft.network.protocol.login.custom.CustomQueryPayload; +import net.minecraft.resources.ResourceLocation; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ClientboundCustomQueryPacket.class) +public abstract class ClientboundCustomQueryPacketMixin { + + // @formatter: off + @Shadow @Final private static int MAX_PAYLOAD_SIZE; + // @formatter: on + + @Inject(method = "readPayload", at = @At("HEAD"), cancellable = true) + private static void impl$onReadUnknownPayload(final ResourceLocation $$0, final FriendlyByteBuf $$1, final CallbackInfoReturnable cir) { + final int readableBytes = $$1.readableBytes(); + if (readableBytes >= 0 && readableBytes <= ClientboundCustomQueryPacketMixin.MAX_PAYLOAD_SIZE) { + final var payload = new FriendlyByteBuf($$1.readBytes(readableBytes)); + cir.setReturnValue(new CustomQueryPayload() { + @Override + public ResourceLocation id() { + return $$0; + } + + @Override + public void write(FriendlyByteBuf buf) { + buf.writeBytes(payload.copy()); + } + }); + } else { + throw new IllegalArgumentException("Payload may not be larger than " + ClientboundCustomQueryPacketMixin.MAX_PAYLOAD_SIZE + " bytes"); + } + } +} diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java index 7812c9d2ccf..23dbc43a217 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerCommonPacketListenerImplMixin_Vanilla.java @@ -29,6 +29,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerCommonPacketListenerImpl; import org.spongepowered.api.Sponge; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -49,6 +50,6 @@ public abstract class ServerCommonPacketListenerImplMixin_Vanilla { @Inject(method = "handleCustomPayload", at = @At(value = "HEAD")) private void vanilla$onHandleCustomPayload(final ServerboundCustomPayloadPacket packet, final CallbackInfo ci) { final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - this.server.execute(() -> channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet.payload())); + this.server.execute(() -> channelRegistry.handlePlayPayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), (EngineConnectionState) this, packet.payload())); } } diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java index 4d7df96291f..cb5672bc0c9 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/ServerLoginPacketListenerImplMixin_Vanilla.java @@ -44,6 +44,7 @@ import org.spongepowered.api.event.EventContext; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.network.ServerSideConnectionEvent; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -106,7 +107,7 @@ public abstract class ServerLoginPacketListenerImplMixin_Vanilla implements Serv ci.cancel(); final SpongeChannelManager channelRegistry = (SpongeChannelManager) Sponge.channelManager(); - this.server.execute(() -> channelRegistry.handleLoginResponsePayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), packet)); + this.server.execute(() -> channelRegistry.handleLoginResponsePayload(((ConnectionBridge) this.connection).bridge$getEngineConnection(), (EngineConnectionState) this, packet)); } @Inject(method = "tick", at = @At("HEAD")) diff --git a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java index 96bcec8a4de..95c7bedd716 100644 --- a/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java +++ b/vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/network/protocol/common/ServerboundCustomPayloadPacketMixin_Vanilla.java @@ -28,7 +28,14 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.common.network.channel.ChannelUtils; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings({"rawtypes", "unchecked"}) @Mixin(ServerboundCustomPayloadPacket.class) public abstract class ServerboundCustomPayloadPacketMixin_Vanilla { @@ -36,25 +43,10 @@ public abstract class ServerboundCustomPayloadPacketMixin_Vanilla { @Shadow @Final private static int MAX_PAYLOAD_SIZE; // @formatter: on -// @Inject(method = "readPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;"), cancellable = true) -// private static void impl$onReadUnknownPayload(ResourceLocation id, FriendlyByteBuf buf, final CallbackInfoReturnable cir) { -// int readableBytes = buf.readableBytes(); -// if (readableBytes >= 0 && readableBytes <= ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE) { -// final var payload = new FriendlyByteBuf(buf.readBytes(readableBytes)); -// -// cir.setReturnValue(new CustomPacketPayload() { -// @Override -// public void write(FriendlyByteBuf buf) { -// buf.writeBytes(payload.copy()); -// } -// -// @Override -// public ResourceLocation id() { -// return id; -// } -// }); -// } else { -// throw new IllegalArgumentException("Payload may not be larger than " + ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE + " bytes"); -// } -// } + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Lists;newArrayList([Ljava/lang/Object;)Ljava/util/ArrayList;"), remap = false) + private static ArrayList vanilla$registerCustomPacketPayloads(final Object[] registrations) { + final ArrayList allRegistrations = new ArrayList<>(List.of(registrations)); + allRegistrations.addAll(ChannelUtils.spongeChannelCodecs(ServerboundCustomPayloadPacketMixin_Vanilla.MAX_PAYLOAD_SIZE)); + return allRegistrations; + } } diff --git a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json index 42ee3453677..1882feee5e5 100644 --- a/vanilla/src/mixins/resources/mixins.spongevanilla.core.json +++ b/vanilla/src/mixins/resources/mixins.spongevanilla.core.json @@ -22,6 +22,7 @@ "commands.CommandsMixin_Vanilla", "network.FriendlyByteBufMixin_Vanilla", "network.protocol.common.ClientboundCustomPayloadPacketMixin", + "network.protocol.login.ClientboundCustomQueryPacketMixin", "server.BootstrapMixin_Vanilla", "server.MinecraftServerMixin_Vanilla", "server.commands.SpreadPlayersCommandMixin_Vanilla", From 1aea417130227be9803512728328a0e5265bc17d Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 02:35:10 +0300 Subject: [PATCH 220/230] spotlessApply --- .../enchantment/ItemEnchantmentsAccessor.java | 1 - .../criterion/SpongeDummyTrigger.java | 1 - .../criterion/SpongeScoreTrigger.java | 1 - .../provider/world/WorldPropertiesData.java | 1 - .../event/SpongeCommonEventFactory.java | 1 - .../common/hooks/GeneralHooks.java | 2 -- .../item/ItemStackDataComponentsUpdater.java | 27 ++++++++++++++++--- .../recipe/cooking/SpongeBlastingRecipe.java | 1 - .../cooking/SpongeCampfireCookingRecipe.java | 1 - .../recipe/cooking/SpongeSmeltingRecipe.java | 1 - .../recipe/cooking/SpongeSmokingRecipe.java | 1 - .../crafting/custom/SpongeSpecialRecipe.java | 1 - .../crafting/shaped/SpongeShapedRecipe.java | 3 --- .../shapeless/SpongeShapelessRecipe.java | 2 -- .../recipe/ingredient/SpongeIngredient.java | 1 - .../recipe/smithing/SpongeSmithingRecipe.java | 1 - .../SpongeStonecuttingRecipe.java | 2 -- .../SpongeMapDecorationBuilder.java | 3 --- .../common/network/PacketUtil.java | 2 -- .../SpongeChannelExceptionHandlerFactory.java | 1 - .../packet/SpongeHandlerPacketBinding.java | 2 -- .../channel/packet/SpongePacketChannel.java | 2 +- .../raw/SpongeRawLoginDataChannel.java | 2 -- .../channel/raw/SpongeRawPlayDataChannel.java | 1 - .../network/packet/SpongePacketHandler.java | 1 - .../registry/loader/SpongeRegistryLoader.java | 4 --- .../common/user/SpongeUserManager.java | 4 --- .../spongepowered/common/util/Constants.java | 1 - .../world/server/SpongeWorldManager.java | 1 - .../world/volume/VolumeStreamUtils.java | 2 +- .../core/MappedRegistryMixin_API.java | 1 - .../minecraft/map/MapDecorationMixin_API.java | 3 +-- .../server/level/WorldGenRegionMixin_API.java | 2 +- .../world/entity/LivingEntityMixin_API.java | 1 - .../item/crafting/RecipeManagerMixin_API.java | 4 --- .../world/item/crafting/RecipeMixin_API.java | 1 - .../enchantment/EnchantmentMixin_API.java | 1 - .../minecraft/world/level/LevelMixin_API.java | 2 +- .../BannerPatternLayers_LayerMixin_API.java | 2 -- .../level/chunk/ChunkAccessMixin_API.java | 2 +- .../level/chunk/ProtoChunkMixin_API.java | 2 +- .../StructureProcessorTypeMixin_API.java | 1 - .../mixin/core/block/BedBlockMixin.java | 1 - .../mixin/core/network/ConnectionMixin.java | 7 ----- .../core/network/FriendlyByteBufMixin.java | 10 ------- .../core/network/PacketEncoderMixin.java | 8 ------ .../mixin/core/world/entity/MobMixin.java | 1 - .../core/world/entity/animal/WolfMixin.java | 4 +-- .../core/world/entity/player/PlayerMixin.java | 2 -- .../chunk/storage/EntityStorageMixin.java | 1 - .../storage/DimensionDataStorageMixin.java | 1 - .../WritableBookItemMixin_LimitBookSize.java | 11 -------- 52 files changed, 33 insertions(+), 109 deletions(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java index bef861f4181..d3a86c01221 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/enchantment/ItemEnchantmentsAccessor.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.accessor.world.item.enchantment; -import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.minecraft.core.Holder; import net.minecraft.world.item.enchantment.Enchantment; diff --git a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java index afc034d4c37..e9c244445b1 100644 --- a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java +++ b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeDummyTrigger.java @@ -31,7 +31,6 @@ import net.minecraft.advancements.critereon.SimpleCriterionTrigger; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; import java.util.Optional; diff --git a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java index 2eb09d15eed..cf02aad5240 100644 --- a/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java +++ b/src/main/java/org/spongepowered/common/advancement/criterion/SpongeScoreTrigger.java @@ -31,7 +31,6 @@ import net.minecraft.advancements.critereon.SimpleCriterionTrigger; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; import java.util.Optional; diff --git a/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java b/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java index 04d6f524f06..e2c4b2ccfa8 100644 --- a/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java +++ b/src/main/java/org/spongepowered/common/data/provider/world/WorldPropertiesData.java @@ -42,7 +42,6 @@ import org.spongepowered.common.data.provider.DataProviderRegistrator; import org.spongepowered.common.util.VecHelper; import org.spongepowered.common.world.weather.SpongeWeather; -import org.spongepowered.math.vector.Vector3i; public final class WorldPropertiesData { diff --git a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java index d101974221a..acb07d0647e 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java +++ b/src/main/java/org/spongepowered/common/event/SpongeCommonEventFactory.java @@ -36,7 +36,6 @@ import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.MapItem; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; diff --git a/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java b/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java index 0e898f94035..f0d91d4c46b 100644 --- a/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java +++ b/src/main/java/org/spongepowered/common/hooks/GeneralHooks.java @@ -26,8 +26,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.status.ServerStatus; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Entity; import org.spongepowered.api.Sponge; import java.util.Optional; diff --git a/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java b/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java index 6b9534eb88f..9858d825f67 100644 --- a/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java +++ b/src/main/java/org/spongepowered/common/item/ItemStackDataComponentsUpdater.java @@ -1,11 +1,32 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ package org.spongepowered.common.item; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataContentUpdater; import org.spongepowered.api.data.persistence.DataView; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.util.Constants; class ItemStackDataComponentsUpdater implements DataContentUpdater { diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java index 0fd5caf6333..d7b377823a9 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeBlastingRecipe.java @@ -25,7 +25,6 @@ package org.spongepowered.common.item.recipe.cooking; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.BlastingRecipe; diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java index 8dadbfdfc3a..9deec819dfb 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeCampfireCookingRecipe.java @@ -25,7 +25,6 @@ package org.spongepowered.common.item.recipe.cooking; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CampfireCookingRecipe; diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java index e518fbb560c..9dec90b4c4e 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmeltingRecipe.java @@ -25,7 +25,6 @@ package org.spongepowered.common.item.recipe.cooking; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CookingBookCategory; diff --git a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java index 2a7e5517908..26e4492f5d8 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/cooking/SpongeSmokingRecipe.java @@ -25,7 +25,6 @@ package org.spongepowered.common.item.recipe.cooking; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CookingBookCategory; diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java index 56b2366d96b..8bc472781da 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/custom/SpongeSpecialRecipe.java @@ -26,7 +26,6 @@ import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java index 3eb951e1f5a..da579b6fe18 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shaped/SpongeShapedRecipe.java @@ -30,12 +30,9 @@ import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; -import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapedRecipePattern; import org.spongepowered.common.bridge.world.item.crafting.RecipeResultBridge; diff --git a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java index 656ae496ba0..439fff51607 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/crafting/shapeless/SpongeShapelessRecipe.java @@ -30,8 +30,6 @@ import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; diff --git a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java index 17f79ab1e5c..e0c5ba23f01 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java +++ b/src/main/java/org/spongepowered/common/item/recipe/ingredient/SpongeIngredient.java @@ -29,7 +29,6 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import org.apache.commons.lang3.NotImplementedException; diff --git a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java index d98e6bace98..8e71cb9657b 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/smithing/SpongeSmithingRecipe.java @@ -30,7 +30,6 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; diff --git a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java index 3da81e3e330..2c2510cb335 100644 --- a/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java +++ b/src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStonecuttingRecipe.java @@ -30,9 +30,7 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; diff --git a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java index 19bae566f56..f66e259aeba 100644 --- a/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java +++ b/src/main/java/org/spongepowered/common/map/decoration/SpongeMapDecorationBuilder.java @@ -34,16 +34,13 @@ import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; -import org.spongepowered.api.data.type.DyeColors; import org.spongepowered.api.map.decoration.MapDecoration; import org.spongepowered.api.map.decoration.MapDecorationType; -import org.spongepowered.api.map.decoration.MapDecorationTypes; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientations; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.bridge.world.storage.MapDecorationBridge; import org.spongepowered.common.map.decoration.orientation.SpongeMapDecorationOrientation; -import org.spongepowered.common.registry.RegistryLoader; import org.spongepowered.common.util.Constants; import org.spongepowered.common.util.MapUtil; import org.spongepowered.math.vector.Vector2i; diff --git a/src/main/java/org/spongepowered/common/network/PacketUtil.java b/src/main/java/org/spongepowered/common/network/PacketUtil.java index 73265e64e8e..716fa13fbba 100644 --- a/src/main/java/org/spongepowered/common/network/PacketUtil.java +++ b/src/main/java/org/spongepowered/common/network/PacketUtil.java @@ -32,10 +32,8 @@ import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket; import net.minecraft.network.protocol.login.custom.CustomQueryAnswerPayload; import net.minecraft.network.protocol.login.custom.CustomQueryPayload; -import net.minecraft.resources.ResourceLocation; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.packet.Packet; diff --git a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java index a168af0328d..00c0ce0a2f9 100644 --- a/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java +++ b/src/main/java/org/spongepowered/common/network/channel/SpongeChannelExceptionHandlerFactory.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.network.channel; -import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelExceptionHandler; diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java index 0283d3537e9..d9496633947 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongeHandlerPacketBinding.java @@ -24,8 +24,6 @@ */ package org.spongepowered.common.network.channel.packet; -import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.packet.HandlerPacketBinding; import org.spongepowered.api.network.channel.packet.Packet; diff --git a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java index d7c0073d20f..256fe6e46c2 100644 --- a/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/packet/SpongePacketChannel.java @@ -30,8 +30,8 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.EngineConnectionSide; +import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; import org.spongepowered.api.network.channel.ChannelIOException; diff --git a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java index d79228f8ae0..09642ebad79 100644 --- a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java @@ -28,10 +28,8 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.login.custom.CustomQueryPayload; import net.minecraft.resources.ResourceLocation; -import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; diff --git a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java index ccd1a4981ac..39fe3f0cc12 100644 --- a/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java +++ b/src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawPlayDataChannel.java @@ -26,7 +26,6 @@ import net.minecraft.network.protocol.Packet; import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.EngineConnectionState; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel; diff --git a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java index e6b404e838a..d6822835665 100644 --- a/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java +++ b/src/main/java/org/spongepowered/common/network/packet/SpongePacketHandler.java @@ -34,7 +34,6 @@ import org.spongepowered.api.ResourceKey; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.network.ClientConnectionState; -import org.spongepowered.api.network.ClientSideConnection; import org.spongepowered.api.network.EngineConnectionStates; import org.spongepowered.api.network.channel.packet.PacketChannel; import org.spongepowered.common.SpongeCommon; diff --git a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java index fc95fd2c8ab..4e4e42550bd 100644 --- a/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java +++ b/src/main/java/org/spongepowered/common/registry/loader/SpongeRegistryLoader.java @@ -31,7 +31,6 @@ import net.minecraft.world.item.RecordItem; import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorPreset; import net.minecraft.world.level.material.MapColor; -import net.minecraft.world.level.saveddata.maps.MapDecoration; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.adventure.ResolveOperation; import org.spongepowered.api.adventure.ResolveOperations; @@ -43,7 +42,6 @@ import org.spongepowered.api.data.persistence.DataFormats; import org.spongepowered.api.data.type.BodyPart; import org.spongepowered.api.data.type.BodyParts; -import org.spongepowered.api.data.type.DyeColors; import org.spongepowered.api.data.type.MatterType; import org.spongepowered.api.data.type.MatterTypes; import org.spongepowered.api.data.type.NotePitch; @@ -85,8 +83,6 @@ import org.spongepowered.api.map.color.MapColorTypes; import org.spongepowered.api.map.color.MapShade; import org.spongepowered.api.map.color.MapShades; -import org.spongepowered.api.map.decoration.MapDecorationType; -import org.spongepowered.api.map.decoration.MapDecorationTypes; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientations; import org.spongepowered.api.registry.RegistryKey; diff --git a/src/main/java/org/spongepowered/common/user/SpongeUserManager.java b/src/main/java/org/spongepowered/common/user/SpongeUserManager.java index f67603f1cfb..7dd9080a2a4 100644 --- a/src/main/java/org/spongepowered/common/user/SpongeUserManager.java +++ b/src/main/java/org/spongepowered/common/user/SpongeUserManager.java @@ -47,9 +47,7 @@ import org.spongepowered.common.entity.player.SpongeUserView; import org.spongepowered.common.profile.SpongeGameProfile; -import java.io.File; import java.io.IOException; -import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -57,10 +55,8 @@ import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; diff --git a/src/main/java/org/spongepowered/common/util/Constants.java b/src/main/java/org/spongepowered/common/util/Constants.java index 9520cee5075..e45100da453 100644 --- a/src/main/java/org/spongepowered/common/util/Constants.java +++ b/src/main/java/org/spongepowered/common/util/Constants.java @@ -31,7 +31,6 @@ import com.google.common.collect.HashBiMap; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; -import jdk.jfr.Percentage; import net.minecraft.commands.arguments.CompoundTagArgument; import net.minecraft.commands.arguments.ResourceLocationArgument; import net.minecraft.core.BlockPos; diff --git a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java index 4a146862f09..c55ed636ee9 100644 --- a/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java +++ b/src/main/java/org/spongepowered/common/world/server/SpongeWorldManager.java @@ -49,7 +49,6 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.CustomSpawner; import net.minecraft.world.level.ForcedChunksSavedData; -import net.minecraft.world.level.GameRules; import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelSettings; diff --git a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java index 6df112f0e46..182dbe467ea 100644 --- a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java +++ b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java @@ -40,11 +40,11 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.ProtoChunk; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.entity.EntitySection; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java index 86db0c69b2f..b6f870bd4a5 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/core/MappedRegistryMixin_API.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.api.minecraft.core; -import com.mojang.serialization.Lifecycle; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.MappedRegistry; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java index d88cd2404ca..e3d4016104f 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/map/MapDecorationMixin_API.java @@ -24,16 +24,15 @@ */ package org.spongepowered.common.mixin.api.minecraft.map; -import net.minecraft.network.chat.Component; import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.chat.Component; import net.minecraft.world.level.saveddata.maps.MapDecoration; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.map.decoration.MapDecorationType; import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.world.storage.MapDecorationBridge; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java index 3e875e294f0..c90a924d7f6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/server/level/WorldGenRegionMixin_API.java @@ -28,9 +28,9 @@ import net.minecraft.server.level.WorldGenRegion; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.status.ChunkStatus; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.ResourceKey; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java index 62e3d7baea8..da69c88dc09 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/LivingEntityMixin_API.java @@ -25,7 +25,6 @@ package org.spongepowered.common.mixin.api.minecraft.world.entity; import net.minecraft.core.Holder; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeMap; import org.spongepowered.api.data.Keys; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java index b09dd0d0f8b..e7536de73be 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeManagerMixin_API.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.mixin.api.minecraft.world.item.crafting; -import com.google.common.collect.ImmutableMap; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.inventory.CraftingContainer; @@ -45,15 +44,12 @@ import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.accessor.world.inventory.CraftingMenuAccessor; import org.spongepowered.common.accessor.world.inventory.InventoryMenuAccessor; import org.spongepowered.common.accessor.world.level.block.entity.AbstractFurnaceBlockEntityAccessor; import org.spongepowered.common.item.util.ItemStackUtil; import java.util.Collection; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java index 0a25ba15e38..06000af2650 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/crafting/RecipeMixin_API.java @@ -28,7 +28,6 @@ import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import org.checkerframework.checker.nullness.qual.NonNull; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java index 68c7763d13f..bcc440ac9d0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/item/enchantment/EnchantmentMixin_API.java @@ -29,7 +29,6 @@ import net.minecraft.world.item.enchantment.Enchantment; import org.spongepowered.api.item.enchantment.EnchantmentType; import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Interface.Remap; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index 1224489195b..f2a76d5506d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -48,9 +48,9 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkSource; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.entity.EntityTypeTest; import net.minecraft.world.level.storage.LevelData; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java index fb9ede182e1..511316c5980 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/block/entity/BannerPatternLayers_LayerMixin_API.java @@ -25,8 +25,6 @@ package org.spongepowered.common.mixin.api.minecraft.world.level.block.entity; import net.minecraft.core.Holder; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; import net.minecraft.world.level.block.entity.BannerPattern; import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.spongepowered.api.ResourceKey; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java index 91f130a4880..5ccc1a3555c 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ChunkAccessMixin_API.java @@ -27,8 +27,8 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.levelgen.Heightmap; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.entity.Entity; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java index 76a298ddcca..714cdd0702b 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/chunk/ProtoChunkMixin_API.java @@ -30,10 +30,10 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.chunk.UpgradeData; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.levelgen.BelowZeroRetrogen; import net.minecraft.world.level.levelgen.blending.BlendingData; import org.checkerframework.checker.nullness.qual.Nullable; diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java index 5be0f737ce6..6a2c6060c27 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/levelgen/structure/templatesystem/StructureProcessorTypeMixin_API.java @@ -26,7 +26,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; import com.mojang.serialization.MapCodec; import net.minecraft.resources.RegistryOps; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java index b0c27fe4efb..23a051d7372 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/block/BedBlockMixin.java @@ -25,7 +25,6 @@ package org.spongepowered.common.mixin.core.block; import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java index 9a1949fa806..d8f0116ffd9 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/ConnectionMixin.java @@ -37,13 +37,8 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.PacketFlow; import org.checkerframework.checker.nullness.qual.Nullable; -import org.objectweb.asm.Opcodes; import org.spongepowered.api.MinecraftVersion; import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.event.SpongeEventFactory; -import org.spongepowered.api.event.network.ServerSideConnectionEvent; -import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.ServerSideConnection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -56,14 +51,12 @@ import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.ConnectionBridge; import org.spongepowered.common.entity.player.ClientType; -import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.network.SpongeClientEngineConnection; import org.spongepowered.common.network.SpongeEngineConnection; import org.spongepowered.common.network.SpongePacketHolder; import org.spongepowered.common.network.SpongeServerEngineConnection; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.TransactionStore; -import org.spongepowered.common.profile.SpongeGameProfile; import org.spongepowered.common.util.Constants; import java.io.IOException; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java index 4a11799ae72..230f1a81331 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/FriendlyByteBufMixin.java @@ -24,20 +24,10 @@ */ package org.spongepowered.common.mixin.core.network; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.StringTag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.Component; import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.util.locale.Locales; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.common.adventure.NativeComponentRenderer; import org.spongepowered.common.bridge.network.FriendlyByteBufBridge; -import org.spongepowered.common.util.Constants; import java.util.Locale; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java index fc24284f1b1..60fc8e6a4b7 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/network/PacketEncoderMixin.java @@ -24,17 +24,9 @@ */ package org.spongepowered.common.mixin.core.network; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; import net.minecraft.network.PacketEncoder; import net.minecraft.network.PacketListener; -import net.minecraft.network.protocol.Packet; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.common.adventure.SpongeAdventure; -import org.spongepowered.common.bridge.network.FriendlyByteBufBridge; @Mixin(PacketEncoder.class) public class PacketEncoderMixin { diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java index 6c982ee7580..1b21c0b81c0 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/MobMixin.java @@ -31,7 +31,6 @@ import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.GoalSelector; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.Level; import org.checkerframework.checker.nullness.qual.Nullable; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java index 19a9d08300a..acdd474b2f6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/animal/WolfMixin.java @@ -78,13 +78,13 @@ public abstract class WolfMixin extends AgableMobMixin implements AggressiveEnti PhaseTracker.getCauseStackManager().popCause(); } } - + @Inject(method = "tryToTame", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/Wolf;tame(Lnet/minecraft/world/entity/player/Player;)V"), cancellable = true) private void impl$onTame(final Player player, final CallbackInfo ci) { try { - + PhaseTracker.getCauseStackManager().pushCause(player); if (!SpongeCommon.post(SpongeEventFactory.createTameEntityEvent(PhaseTracker.getCauseStackManager().currentCause(), (Wolf) this))) { this.shadow$level().broadcastEntityEvent((net.minecraft.world.entity.animal.Wolf) (Object) this, (byte)6); diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java index d80b21e7186..08cc82ebe88 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/entity/player/PlayerMixin.java @@ -28,7 +28,6 @@ import com.mojang.datafixers.util.Either; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; -import net.minecraft.core.Registry; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.syncher.EntityDataAccessor; @@ -50,7 +49,6 @@ import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.pattern.BlockInWorld; import net.minecraft.world.phys.AABB; import net.minecraft.world.scores.Scoreboard; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java index d445491cc00..26642c62d44 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/storage/EntityStorageMixin.java @@ -29,7 +29,6 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.EntityStorage; -import net.minecraft.world.level.chunk.storage.IOWorker; import net.minecraft.world.level.chunk.storage.SimpleRegionStorage; import net.minecraft.world.level.entity.ChunkEntities; import org.checkerframework.checker.nullness.qual.Nullable; diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java index bc77c2550aa..31bd3782263 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/storage/DimensionDataStorageMixin.java @@ -39,7 +39,6 @@ import java.io.File; import java.util.function.BiFunction; -import java.util.function.Function; @Mixin(DimensionDataStorage.class) public abstract class DimensionDataStorageMixin { diff --git a/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java b/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java index 5cc62814d1b..45a1fe6c595 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java +++ b/src/mixins/java/org/spongepowered/common/mixin/exploit/world/item/WritableBookItemMixin_LimitBookSize.java @@ -24,20 +24,9 @@ */ package org.spongepowered.common.mixin.exploit.world.item; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; import net.minecraft.world.item.WritableBookItem; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Constant; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyConstant; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.common.applaunch.config.core.SpongeConfigs; -import java.nio.charset.StandardCharsets; -import java.util.stream.IntStream; @Mixin(WritableBookItem.class) public abstract class WritableBookItemMixin_LimitBookSize { From 491d5f08d314b7ceec9d85f78ba0175204bbe687 Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 02:35:36 +0300 Subject: [PATCH 221/230] Bump the API --- SpongeAPI | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SpongeAPI b/SpongeAPI index 3a01dbfd7c2..ff8cbeb0ce3 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit 3a01dbfd7c2a262fcc3eb5f07c6de317c46ea870 +Subproject commit ff8cbeb0ce389a54ca4091710f1b7ea61cd38ffa From 29904d882707e485f14ddfc1ad7615066f860dc2 Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 21:09:16 +0300 Subject: [PATCH 222/230] Update chunk generation deadlock patch --- .../core/server/level/ChunkMapMixin.java | 17 ++++++ .../level/chunk/ChunkStatusTasksMixin.java | 6 ++- .../level/chunk/status/ChunkStatusMixin.java | 54 +++++++++++++++++++ src/mixins/resources/mixins.sponge.core.json | 1 + 4 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/status/ChunkStatusMixin.java diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java index 8d2824ded78..8d4c5712540 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/server/level/ChunkMapMixin.java @@ -70,6 +70,7 @@ import org.spongepowered.math.vector.Vector3i; import java.util.concurrent.CompletableFuture; +import java.util.function.Function; @Mixin(ChunkMap.class) public abstract class ChunkMapMixin implements ChunkMapBridge { @@ -209,4 +210,20 @@ public abstract class ChunkMapMixin implements ChunkMapBridge { cir.setReturnValue(ChunkHolder.UNLOADED_CHUNK_FUTURE); } } + + @Redirect(method = "lambda$scheduleChunkGeneration$30", + at = @At(value = "INVOKE", + target = "Ljava/util/concurrent/CompletableFuture;thenApply(Ljava/util/function/Function;)Ljava/util/concurrent/CompletableFuture;", + remap = false), + slice = @Slice( + from = @At(value = "INVOKE", + target = "Lnet/minecraft/server/level/progress/ChunkProgressListener;onStatusChange(Lnet/minecraft/world/level/ChunkPos;Lnet/minecraft/world/level/chunk/status/ChunkStatus;)V"))) + private CompletableFuture> impl$guardForUnloadedChunkOnGenerate(final CompletableFuture instance, + final Function> function) { + //See ChunkStatusTasksMixin, only applies for when generation is cancelled due to world unload + if (instance != null) { + return instance.thenApply(function); + } + return ChunkHolder.UNLOADED_CHUNK_FUTURE; + } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java index 3258b233b42..422763c5588 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/ChunkStatusTasksMixin.java @@ -46,6 +46,7 @@ public abstract class ChunkStatusTasksMixin { /** * @author aromaa - December 17th, 2023 - 1.19.4 * @author aromaa - December 18th, 2023 - Updated to 1.20.2 + * @author aromaa - May 14th, 2024 - Updated to 1.20.6 * @reason Fixes a deadlock when the world is unloading/unloaded. * The Blender#of method calls to the IOWorker#isOldChunkAround which * submits a task to the main thread while blocking the current thread @@ -55,6 +56,10 @@ public abstract class ChunkStatusTasksMixin { * to throw a special exception when the IOWorker has finished up its work * and catches it here to convert it to a ChunkLoadingFailure. * + * In previous versions you were able to return ChunkResult here but this + * is no longer the case, so we instead return null here which + * needs to be checking for in ChunkMap. + * * See IOWorkerMixin#createOldDataForRegion */ @Overwrite @@ -69,7 +74,6 @@ static CompletableFuture generateBiomes(final WorldGenContext $$0, throw e; } - // TODO what to return here? return ChunkHolder.UNLOADED_CHUNK_FUTURE; return null; } //Sponge end } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/status/ChunkStatusMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/status/ChunkStatusMixin.java new file mode 100644 index 00000000000..c30b08c760a --- /dev/null +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/chunk/status/ChunkStatusMixin.java @@ -0,0 +1,54 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.common.mixin.core.world.level.chunk.status; + +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.Slice; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +@Mixin(ChunkStatus.class) +public abstract class ChunkStatusMixin { + + @Redirect(method = "generate", at = @At(value = "INVOKE", + target = "Ljava/util/concurrent/CompletableFuture;thenApply(Ljava/util/function/Function;)Ljava/util/concurrent/CompletableFuture;", + remap = false), + slice = @Slice( + from = @At(value = "INVOKE", + target = "Lnet/minecraft/world/level/chunk/status/ChunkStatus$GenerationTask;doWork(Lnet/minecraft/world/level/chunk/status/WorldGenContext;Lnet/minecraft/world/level/chunk/status/ChunkStatus;Ljava/util/concurrent/Executor;Lnet/minecraft/world/level/chunk/status/ToFullChunk;Ljava/util/List;Lnet/minecraft/world/level/chunk/ChunkAccess;)Ljava/util/concurrent/CompletableFuture;"))) + private CompletableFuture impl$guardForUnloadedChunkOnGenerate(final CompletableFuture instance, + final Function function) { + //See ChunkStatusTasksMixin, only applies for when generation is cancelled due to world unload + if (instance != null) { + return instance.thenApply(function); + } + return null; + } +} diff --git a/src/mixins/resources/mixins.sponge.core.json b/src/mixins/resources/mixins.sponge.core.json index 159df0c435e..43fd41c9b35 100644 --- a/src/mixins/resources/mixins.sponge.core.json +++ b/src/mixins/resources/mixins.sponge.core.json @@ -239,6 +239,7 @@ "world.level.chunk.ChunkSerializerMixin", "world.level.chunk.ChunkStatusTasksMixin", "world.level.chunk.LevelChunkMixin", + "world.level.chunk.status.ChunkStatusMixin", "world.level.chunk.storage.EntityStorageMixin", "world.level.chunk.storage.IOWorkerMixin", "world.level.dimension.DimensionTypeMixin", From ac33cb3f3660cc1172d27a7110a3af7819b679ff Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 21:22:44 +0300 Subject: [PATCH 223/230] Fix explosion mixin --- .../common/mixin/core/world/level/ExplosionMixin.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java index 61a811bf4b7..2b14f786fd6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/level/ExplosionMixin.java @@ -27,6 +27,7 @@ import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.sounds.SoundEvent; import net.minecraft.util.Mth; @@ -95,12 +96,12 @@ public abstract class ExplosionMixin implements ExplosionBridge { private double impl$knockback; @Inject( - method = "(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/sounds/SoundEvent;)V", + method = "(Lnet/minecraft/world/level/Level;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/damagesource/DamageSource;Lnet/minecraft/world/level/ExplosionDamageCalculator;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/core/particles/ParticleOptions;Lnet/minecraft/core/Holder;)V", at = @At("RETURN") ) - private void impl$onConstructed(final Level worldIn, final Entity exploderIn, final DamageSource $$2, final ExplosionDamageCalculator $$3, final double $$4, - final double $$5, final double $$6, final float $$7, final boolean $$8, final net.minecraft.world.level.Explosion.BlockInteraction modeIn, - final ParticleOptions $$10, final ParticleOptions $$11, final SoundEvent $$12, final CallbackInfo ci) { + private void impl$onConstructed(final Level $$0, final Entity $$1, final DamageSource $$2, final ExplosionDamageCalculator $$3, final double $$4, + final double $$5, final double $$6, final float $$7, final boolean $$8, final net.minecraft.world.level.Explosion.BlockInteraction $$9, + final ParticleOptions $$10, final ParticleOptions $$11, final Holder $$12, final CallbackInfo ci) { // In Vanilla and Forge, 'damagesTerrain' controls both smoke particles and block damage // Sponge-created explosions will explicitly set 'impl$shouldBreakBlocks' to its proper value this.impl$shouldBreakBlocks = this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY || this.blockInteraction == net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; From 70ba1fc8df25ef0b2eb8ad59aaa09592800a6b14 Mon Sep 17 00:00:00 2001 From: aromaa Date: Tue, 14 May 2024 21:35:30 +0300 Subject: [PATCH 224/230] Remove MC-268011 patch, fixed in 1.20.6 --- .../common/mixin/core/world/item/ItemStackMixin.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java index 03bce62279c..c318259702d 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/world/item/ItemStackMixin.java @@ -131,14 +131,4 @@ public abstract class ItemStackMixin implements SpongeDataHolderBridge, DataComp public NBTDataType data$getNBTDataType() { return NBTDataTypes.ITEMSTACK; } - - @Inject(method = "setEntityRepresentation", at = @At("HEAD"), cancellable = true) - private void impl$onSetEntityRepresentation(final CallbackInfo ci) { - //If a plugin or a mod spawns in an air item entity it will end up rooting - //the entity and its assigned world in the static EMPTY item stack. Prevent this. - //Or even Minecraft itself... MC-268011 - if ((Object) this == ItemStack.EMPTY) { - ci.cancel(); - } - } } From 5bc7e7bece22372a56ce5b47a77fae3e01799fb9 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 21:34:05 +0200 Subject: [PATCH 225/230] Fix generator compile errors --- .../vanilla/generator/GeneratorMain.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java index f64ac04571c..2afc63662fc 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java @@ -55,14 +55,13 @@ import net.minecraft.world.entity.animal.horse.Markings; import net.minecraft.world.entity.animal.horse.Variant; import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.DyeColor; -import net.minecraft.world.item.FireworkRocketItem; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.Rarity; -import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.item.component.FireworkExplosion; import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.WorldDataConfiguration; import net.minecraft.world.level.block.state.properties.BambooLeaves; import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; import org.tinylog.Logger; @@ -147,7 +146,7 @@ private static Pair loadVanill // and call to WorldStem.load in net.minecraft.server.Main // We don't currently try to load any datapacks here final var packRepository = ServerPacksSource.createVanillaTrustedRepository(); - MinecraftServer.configurePackRepository(packRepository, DataPackConfig.DEFAULT, /* safeMode = */ false, FeatureFlags.DEFAULT_FLAGS); + MinecraftServer.configurePackRepository(packRepository, WorldDataConfiguration.DEFAULT, /* safeMode = */ false, true); final CloseableResourceManager resourceManager = new MultiPackResourceManager(PackType.SERVER_DATA, packRepository.openAllSelected()); // WorldLoader.load @@ -165,7 +164,7 @@ private static Pair loadVanill final RegistryAccess.Frozen compositeRegistries = withDimensions.getAccessForLoading(RegistryLayer.RELOADABLE); final var resourcesFuture = ReloadableServerResources.loadResources( resourceManager, - compositeRegistries, + withDimensions, packRepository.getRequestedFeatureFlags(), CommandSelection.ALL, 2, // functionPermissionLevel @@ -176,7 +175,7 @@ private static Pair loadVanill resourceManager.close(); } }).thenApply(resources -> { - resources.updateRegistryTags(compositeRegistries); + resources.updateRegistryTags(); return resources; }); @@ -221,7 +220,7 @@ private static List generators(final Context context) { new EnumEntriesValidator<>( "item", "FireworkShapes", - FireworkRocketItem.Shape.class, + FireworkExplosion.Shape.class, "getName", "sponge" ), From 838cc6a9dd7b3b03bfe6cbe9db4d61ade7b66f70 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 21:50:21 +0200 Subject: [PATCH 226/230] Fix ArmorMaterial and FireworkShape generator --- .../vanilla/generator/GeneratorMain.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java index 2afc63662fc..c8d44f6a9ed 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java @@ -55,7 +55,6 @@ import net.minecraft.world.entity.animal.horse.Markings; import net.minecraft.world.entity.animal.horse.Variant; import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.Rarity; @@ -221,7 +220,7 @@ private static List generators(final Context context) { "item", "FireworkShapes", FireworkExplosion.Shape.class, - "getName", + "getSerializedName", "sponge" ), new EnumEntriesValidator<>( @@ -238,12 +237,12 @@ private static List generators(final Context context) { "getName", "sponge" ), - new EnumEntriesValidator<>( + new RegistryEntriesGenerator<>( "data.type", "ArmorMaterials", - ArmorMaterials.class, - "getName", - "sponge" + "ArmorMaterials", + context.relativeClass("data.type", "ArmorMaterial"), + Registries.ARMOR_MATERIAL ), new EnumEntriesValidator<>( "data.type", @@ -575,7 +574,8 @@ private static List generators(final Context context) { ), new BlockStateDataProviderGenerator(), new BlockStatePropertiesGenerator(), - new BlockStatePropertyKeysGenerator(), + // TODO fix me + //new BlockStatePropertyKeysGenerator(), new RegistryEntriesGenerator<>( "world.generation.feature", "PlacedFeatures", From e98c350d33e908bfd0eaa8ddfd4be74c4c766469 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 22:18:29 +0200 Subject: [PATCH 227/230] Update armor material generator --- .../java/org/spongepowered/vanilla/generator/GeneratorMain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java index c8d44f6a9ed..34f9c48bf3d 100644 --- a/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java +++ b/generator/src/main/java/org/spongepowered/vanilla/generator/GeneratorMain.java @@ -240,7 +240,7 @@ private static List generators(final Context context) { new RegistryEntriesGenerator<>( "data.type", "ArmorMaterials", - "ArmorMaterials", + "ARMOR_MATERIAL", context.relativeClass("data.type", "ArmorMaterial"), Registries.ARMOR_MATERIAL ), From 113ba8338da10446f2aa89b95594660988606bb1 Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 22:19:20 +0200 Subject: [PATCH 228/230] Bump SpongeAPI --- SpongeAPI | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SpongeAPI b/SpongeAPI index ff8cbeb0ce3..e46968716d9 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit ff8cbeb0ce389a54ca4091710f1b7ea61cd38ffa +Subproject commit e46968716d90be76a49dd5662d641e2458585ffa From f77cc3b100c6bd350d9a80050b8babd4cba28a9e Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 22:32:49 +0200 Subject: [PATCH 229/230] Bump mixin compatibility level to java 21 --- vanilla/src/mixins/resources/mixins.spongevanilla.tracker.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vanilla/src/mixins/resources/mixins.spongevanilla.tracker.json b/vanilla/src/mixins/resources/mixins.spongevanilla.tracker.json index eab0d84caff..13577bb895b 100644 --- a/vanilla/src/mixins/resources/mixins.spongevanilla.tracker.json +++ b/vanilla/src/mixins/resources/mixins.spongevanilla.tracker.json @@ -3,7 +3,7 @@ "minVersion": "0.8", "package": "org.spongepowered.vanilla.mixin.tracker", "target": "@env(DEFAULT)", - "compatibilityLevel": "JAVA_17", + "compatibilityLevel": "JAVA_21", "priority": 1302, "mixins": [ "server.level.ServerPlayerGameModeMixin_Vanilla_Tracker", From aff621e75dc8f9aa30b0c58a16dbed61d3e54e2c Mon Sep 17 00:00:00 2001 From: ImMorpheus Date: Tue, 14 May 2024 22:41:56 +0200 Subject: [PATCH 230/230] Fix MerchantOfferAccessor --- .../accessor/world/item/trading/MerchantOfferAccessor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/accessors/java/org/spongepowered/common/accessor/world/item/trading/MerchantOfferAccessor.java b/src/accessors/java/org/spongepowered/common/accessor/world/item/trading/MerchantOfferAccessor.java index 092ece09bbc..365133ce50c 100644 --- a/src/accessors/java/org/spongepowered/common/accessor/world/item/trading/MerchantOfferAccessor.java +++ b/src/accessors/java/org/spongepowered/common/accessor/world/item/trading/MerchantOfferAccessor.java @@ -26,12 +26,13 @@ import net.minecraft.world.item.trading.MerchantOffer; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(MerchantOffer.class) public interface MerchantOfferAccessor { - @Accessor("rewardExp") void accessor$rewardExp(final boolean rewardExp); + @Accessor("rewardExp") @Mutable void accessor$rewardExp(final boolean rewardExp); @Accessor("demand") void accessor$demand(final int demand);