diff --git a/.github/workflows/gradle-build.yml b/.github/workflows/gradle-build.yml index 453b1676..54fe6895 100644 --- a/.github/workflows/gradle-build.yml +++ b/.github/workflows/gradle-build.yml @@ -12,7 +12,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: 17 + java-version: 21 - name: Build Gradle uses: eskatos/gradle-command-action@v1 with: diff --git a/.github/workflows/gradle-check.yml b/.github/workflows/gradle-check.yml index 90dab4e4..a5c886c7 100644 --- a/.github/workflows/gradle-check.yml +++ b/.github/workflows/gradle-check.yml @@ -12,7 +12,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: 17 + java-version: 21 - name: Build Gradle uses: eskatos/gradle-command-action@v1 with: diff --git a/.github/workflows/gradle-publish.yml b/.github/workflows/gradle-publish.yml index ab6a77f9..2b75d8bb 100644 --- a/.github/workflows/gradle-publish.yml +++ b/.github/workflows/gradle-publish.yml @@ -16,7 +16,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: 17 + java-version: 21 - name: Prepare Datagen uses: eskatos/gradle-command-action@v1 with: diff --git a/build.gradle b/build.gradle index 118dbbc7..d3fda4d2 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ apply plugin: 'io.github.dexman545.outlet' java { toolchain { - languageVersion = JavaLanguageVersion.of(17) + languageVersion = JavaLanguageVersion.of(21) } withSourcesJar() } diff --git a/gradle.properties b/gradle.properties index 9cdeb9d9..2c44e384 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,7 +20,7 @@ org.gradle.daemon=false modrinth_project_id=9K7RJlvM # Dependencies - fabwork_version=1.3.1+1.21 + fabwork_version=1.3.2-beta.1+1.21 modmenu_version=11.0.0-beta.1 minelp_version=4.12.0+1.21 kirin_version=1.19.0+1.21 diff --git a/src/main/java/com/minelittlepony/unicopia/Debug.java b/src/main/java/com/minelittlepony/unicopia/Debug.java index 2e3533df..0d45e1c9 100644 --- a/src/main/java/com/minelittlepony/unicopia/Debug.java +++ b/src/main/java/com/minelittlepony/unicopia/Debug.java @@ -24,7 +24,7 @@ public interface Debug { AtomicReference LAST_TESTED_WORLD = new AtomicReference<>(null); static void runTests(World world) { - if (!CHECK_GAME_VALUES || !world.getDimensionKey().getValue().equals(DimensionTypes.OVERWORLD_ID) || (LAST_TESTED_WORLD.getAndSet(world) == world)) { + if (!CHECK_GAME_VALUES || !world.getDimensionEntry().matchesKey(DimensionTypes.OVERWORLD) || (LAST_TESTED_WORLD.getAndSet(world) == world)) { return; } diff --git a/src/main/java/com/minelittlepony/unicopia/Race.java b/src/main/java/com/minelittlepony/unicopia/Race.java index 8607c091..c900a985 100644 --- a/src/main/java/com/minelittlepony/unicopia/Race.java +++ b/src/main/java/com/minelittlepony/unicopia/Race.java @@ -202,7 +202,7 @@ public record Race ( Identifier id = Identifier.tryParse(s); if (id != null) { if (id.getNamespace() == Identifier.DEFAULT_NAMESPACE) { - id = new Identifier(Unicopia.DEFAULT_NAMESPACE, id.getPath()); + id = Unicopia.id(id.getPath()); } return REGISTRY.getOrEmpty(id).orElse(def); } @@ -231,7 +231,7 @@ public record Race ( Identifier id = context.getArgument(name, RegistryKey.class).getValue(); final Identifier idf = id; if (id.getNamespace() == Identifier.DEFAULT_NAMESPACE && !REGISTRY.containsId(id)) { - id = new Identifier(REGISTRY_KEY.getValue().getNamespace(), id.getPath()); + id = REGISTRY_KEY.getValue().withPath(id.getPath()); } return REGISTRY.getOrEmpty(id).orElseThrow(() -> UNKNOWN_RACE_EXCEPTION.create(idf)); } diff --git a/src/main/java/com/minelittlepony/unicopia/UConventionalTags.java b/src/main/java/com/minelittlepony/unicopia/UConventionalTags.java index 31b02f7f..ab8653b5 100644 --- a/src/main/java/com/minelittlepony/unicopia/UConventionalTags.java +++ b/src/main/java/com/minelittlepony/unicopia/UConventionalTags.java @@ -16,7 +16,7 @@ public interface UConventionalTags { TagKey CORALS = block("corals"); private static TagKey block(String name) { - return TagKey.of(RegistryKeys.BLOCK, new Identifier("c", name)); + return TagKey.of(RegistryKeys.BLOCK, Identifier.of("c", name)); } } @@ -65,7 +65,7 @@ public interface UConventionalTags { TagKey TOOL_KNIVES = item("tools/knives"); private static TagKey item(String name) { - return TagKey.of(RegistryKeys.ITEM, new Identifier("c", name)); + return TagKey.of(RegistryKeys.ITEM, Identifier.of("c", name)); } } } diff --git a/src/main/java/com/minelittlepony/unicopia/UGameEvents.java b/src/main/java/com/minelittlepony/unicopia/UGameEvents.java index cc808688..df3fa748 100644 --- a/src/main/java/com/minelittlepony/unicopia/UGameEvents.java +++ b/src/main/java/com/minelittlepony/unicopia/UGameEvents.java @@ -2,16 +2,17 @@ package com.minelittlepony.unicopia; import net.minecraft.util.Identifier; import net.minecraft.registry.Registry; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.registry.Registries; import net.minecraft.world.event.GameEvent; public interface UGameEvents { - GameEvent PIE_STOMP = register("pie_stomp", 5); + RegistryEntry PIE_STOMP = register("pie_stomp", 5); - static GameEvent register(String name, int range) { + static RegistryEntry register(String name, int range) { Identifier id = Unicopia.id(name); - return Registry.register(Registries.GAME_EVENT, id, new GameEvent(range)); + return Registry.registerReference(Registries.GAME_EVENT, id, new GameEvent(range)); } static void bootstrap() { diff --git a/src/main/java/com/minelittlepony/unicopia/USounds.java b/src/main/java/com/minelittlepony/unicopia/USounds.java index 99117ddb..df7900f7 100644 --- a/src/main/java/com/minelittlepony/unicopia/USounds.java +++ b/src/main/java/com/minelittlepony/unicopia/USounds.java @@ -56,7 +56,7 @@ public interface USounds { SoundEvent ENTITY_HOT_AIR_BALLOON_BURNER_FIRE = ENTITY_GHAST_SHOOT; SoundEvent ENTITY_HOT_AIR_BALLOON_STEP = BLOCK_WOOL_STEP; SoundEvent ENTITY_HOT_AIR_BALLOON_BASKET_STEP = BLOCK_BAMBOO_STEP; - SoundEvent ENTITY_HOT_AIR_BALLOON_EQUIP_CANOPY = ITEM_ARMOR_EQUIP_LEATHER; + RegistryEntry ENTITY_HOT_AIR_BALLOON_EQUIP_CANOPY = ITEM_ARMOR_EQUIP_LEATHER; SoundEvent ENTITY_HOT_AIR_BALLOON_EQUIP_BURNER = ENTITY_IRON_GOLEM_DAMAGE; SoundEvent ENTITY_SOMBRA_AMBIENT = register("entity.sombra.ambient"); diff --git a/src/main/java/com/minelittlepony/unicopia/UTags.java b/src/main/java/com/minelittlepony/unicopia/UTags.java index 7d16f2bc..cf06e053 100644 --- a/src/main/java/com/minelittlepony/unicopia/UTags.java +++ b/src/main/java/com/minelittlepony/unicopia/UTags.java @@ -137,7 +137,7 @@ public interface UTags { TagKey HAS_NO_ATMOSPHERE = dimension("has_no_atmosphere"); private static TagKey dimension(String name) { - return TagKey.of(RegistryKeys.DIMENSION_TYPE, new Identifier("c", name)); + return TagKey.of(RegistryKeys.DIMENSION_TYPE, Identifier.of("c", name)); } } diff --git a/src/main/java/com/minelittlepony/unicopia/Unicopia.java b/src/main/java/com/minelittlepony/unicopia/Unicopia.java index a6057f85..e26aa90c 100644 --- a/src/main/java/com/minelittlepony/unicopia/Unicopia.java +++ b/src/main/java/com/minelittlepony/unicopia/Unicopia.java @@ -57,7 +57,7 @@ public class Unicopia implements ModInitializer { } public static Identifier id(String name) { - return new Identifier(DEFAULT_NAMESPACE, name); + return Identifier.of(DEFAULT_NAMESPACE, name); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/Ability.java b/src/main/java/com/minelittlepony/unicopia/ability/Ability.java index dd1c9c23..0710b1b1 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/Ability.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/Ability.java @@ -6,6 +6,8 @@ import com.minelittlepony.unicopia.Race; import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.entity.player.Pony; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.Util; @@ -106,7 +108,7 @@ public interface Ability { /** * Gets the serializer to use for reading data over the network. */ - Hit.Serializer getSerializer(); + PacketCodec getSerializer(); /** * Called on the client to get any data required to activate the ability. diff --git a/src/main/java/com/minelittlepony/unicopia/ability/AbilityDispatcher.java b/src/main/java/com/minelittlepony/unicopia/ability/AbilityDispatcher.java index 93eacb89..e2b95348 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/AbilityDispatcher.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/AbilityDispatcher.java @@ -17,6 +17,7 @@ import com.minelittlepony.unicopia.util.NbtSerialisable; import com.minelittlepony.unicopia.util.Tickable; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Identifier; public class AbilityDispatcher implements Tickable, NbtSerialisable { @@ -83,20 +84,20 @@ public class AbilityDispatcher implements Tickable, NbtSerialisable { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { if (compound.contains("stats")) { stats.clear(); NbtCompound li = compound.getCompound("stats"); li.getKeys().forEach(key -> { - getStat(AbilitySlot.valueOf(key)).fromNBT(li.getCompound(key)); + getStat(AbilitySlot.valueOf(key)).fromNBT(li.getCompound(key), lookup); }); } } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { NbtCompound li = new NbtCompound(); - stats.forEach((key, value) -> li.put(key.name(), value.toNBT())); + stats.forEach((key, value) -> li.put(key.name(), value.toNBT(lookup))); compound.put("stats", li); } @@ -283,7 +284,7 @@ public class AbilityDispatcher implements Tickable, NbtSerialisable { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putInt("warmup", warmup); compound.putInt("cooldown", cooldown); compound.putInt("maxWarmup", maxWarmup); @@ -295,13 +296,13 @@ public class AbilityDispatcher implements Tickable, NbtSerialisable { } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { warmup = compound.getInt("warmup"); cooldown = compound.getInt("cooldown"); maxWarmup = compound.getInt("maxWarmup"); maxCooldown = compound.getInt("maxCooldown"); triggered = compound.getBoolean("triggered"); - activeAbility = Abilities.REGISTRY.getOrEmpty(new Identifier(compound.getString("activeAbility"))); + activeAbility = Abilities.REGISTRY.getOrEmpty(Identifier.of(compound.getString("activeAbility"))); } } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/AbstractSpellCastingAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/AbstractSpellCastingAbility.java index abe2489e..0be8ddcd 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/AbstractSpellCastingAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/AbstractSpellCastingAbility.java @@ -5,6 +5,8 @@ import com.minelittlepony.unicopia.ability.magic.spell.effect.CustomisedSpellTyp import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.particle.MagicParticleEffect; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.text.Text; import net.minecraft.util.ActionResult; import net.minecraft.util.TypedActionResult; @@ -52,8 +54,8 @@ abstract class AbstractSpellCastingAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/BatPonyHangAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/BatPonyHangAbility.java index 95566b44..6c71e186 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/BatPonyHangAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/BatPonyHangAbility.java @@ -6,6 +6,8 @@ import com.minelittlepony.unicopia.ability.data.Multi; import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.TraceHelper; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.util.math.BlockPos; /** @@ -43,8 +45,8 @@ public class BatPonyHangAbility implements Ability { } @Override - public Multi.Serializer getSerializer() { - return Multi.SERIALIZER; + public PacketCodec getSerializer() { + return Multi.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/CarryAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/CarryAbility.java index 936ffa83..1ca3341f 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/CarryAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/CarryAbility.java @@ -11,9 +11,11 @@ import com.minelittlepony.unicopia.entity.Living; import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.TraceHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.world.World; /** @@ -48,8 +50,8 @@ public class CarryAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/ChangeFormAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/ChangeFormAbility.java index 6f4cc3e0..d3b84876 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/ChangeFormAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/ChangeFormAbility.java @@ -15,7 +15,11 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.item.FriendshipBraceletItem; import com.minelittlepony.unicopia.item.UItems; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Identifier; @@ -58,8 +62,8 @@ public class ChangeFormAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override @@ -77,7 +81,7 @@ public class ChangeFormAbility implements Ability { player.subtractEnergyCost(5 * targets.size()); TrinketsDelegate.EquippedStack amulet = UItems.PEARL_NECKLACE.getForEntity(player.asEntity()); if (!amulet.stack().isEmpty()) { - amulet.stack().damage(1, player.asEntity(), amulet.breakStatusSender()); + amulet.stack().damage(1, (ServerWorld)player.asWorld(), (ServerPlayerEntity)player.asEntity(), amulet.breakStatusSender()); } boolean isTransforming = player.getSuppressedRace().isUnset(); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/ChangelingFeedAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/ChangelingFeedAbility.java index 974f212c..0ea48d92 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/ChangelingFeedAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/ChangelingFeedAbility.java @@ -15,6 +15,7 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.TraceHelper; import com.minelittlepony.unicopia.util.VecHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.mob.HostileEntity; @@ -23,6 +24,7 @@ import net.minecraft.entity.passive.MerchantEntity; import net.minecraft.entity.passive.PigEntity; import net.minecraft.entity.passive.SheepEntity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; /** @@ -54,8 +56,8 @@ public class ChangelingFeedAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyGrowAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyGrowAbility.java index af04192f..896021e0 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyGrowAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyGrowAbility.java @@ -18,6 +18,7 @@ import com.minelittlepony.unicopia.server.world.ModificationType; import com.minelittlepony.unicopia.util.TraceHelper; import com.minelittlepony.unicopia.util.VecHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; @@ -26,6 +27,7 @@ import net.minecraft.block.FarmlandBlock; import net.minecraft.item.BoneMealItem; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; @@ -54,8 +56,8 @@ public class EarthPonyGrowAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Pos.SERIALIZER; + public PacketCodec getSerializer() { + return Pos.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyKickAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyKickAbility.java index f8e4e861..263463e9 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyKickAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyKickAbility.java @@ -6,7 +6,6 @@ import java.util.stream.Stream; import org.jetbrains.annotations.Nullable; import com.minelittlepony.unicopia.Race; -import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.ability.data.Pos; import com.minelittlepony.unicopia.ability.data.tree.TreeType; import com.minelittlepony.unicopia.client.minelittlepony.MineLPDelegate; @@ -20,6 +19,7 @@ import com.minelittlepony.unicopia.server.world.BlockDestructionManager; import com.minelittlepony.unicopia.server.world.ModificationType; import com.minelittlepony.unicopia.util.*; +import io.netty.buffer.ByteBuf; import net.minecraft.block.BeehiveBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; @@ -30,6 +30,7 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.passive.BeeEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Identifier; @@ -145,8 +146,8 @@ public class EarthPonyKickAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Pos.SERIALIZER; + public PacketCodec getSerializer() { + return Pos.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyStompAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyStompAbility.java index e1761d25..600c5bc7 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyStompAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/EarthPonyStompAbility.java @@ -23,6 +23,7 @@ import com.minelittlepony.unicopia.server.world.ModificationType; import com.minelittlepony.unicopia.util.PosHelper; import com.minelittlepony.unicopia.util.VecHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.enchantment.EnchantmentHelper; @@ -31,6 +32,7 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.BlockStateParticleEffect; import net.minecraft.registry.tag.BlockTags; import net.minecraft.server.world.ServerWorld; @@ -69,7 +71,7 @@ public class EarthPonyStompAbility implements Ability { public Identifier getIcon(Pony player) { Identifier id = Abilities.REGISTRY.getId(this); Race race = player.getObservedSpecies(); - return new Identifier(id.getNamespace(), "textures/gui/ability/" + id.getPath() + return id.withPath(p -> "textures/gui/ability/" + p + "_" + (race.isHuman() ? Race.EARTH : race).getId().getPath() + ".png"); } @@ -94,8 +96,8 @@ public class EarthPonyStompAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } private void thrustDownwards(Pony player) { diff --git a/src/main/java/com/minelittlepony/unicopia/ability/FlyingDashAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/FlyingDashAbility.java index af66c200..7b5dd353 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/FlyingDashAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/FlyingDashAbility.java @@ -7,6 +7,9 @@ import org.jetbrains.annotations.Nullable; import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.entity.player.Pony; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; + /** * Dashing ability for flying creatures. */ @@ -29,8 +32,8 @@ public class FlyingDashAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/HugAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/HugAbility.java index caca424f..46cc8c65 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/HugAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/HugAbility.java @@ -34,7 +34,7 @@ public class HugAbility extends CarryAbility { creeper.startRiding(player, true); Living.getOrEmpty(creeper).ifPresent(living -> living.setCarrier(player)); } else if (rider != null) { - rider.teleport(player.getX(), player.getY() + 0.5, player.getZ()); + rider.teleport(player.getX(), player.getY() + 0.5, player.getZ(), false); rider.setYaw(player.getYaw() + 180); if (rider instanceof FriendlyCreeperEntity) { diff --git a/src/main/java/com/minelittlepony/unicopia/ability/KirinRageAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/KirinRageAbility.java index dce16e46..554f1182 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/KirinRageAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/KirinRageAbility.java @@ -11,6 +11,8 @@ import com.minelittlepony.unicopia.ability.magic.spell.effect.SpellType; import com.minelittlepony.unicopia.block.state.StateMaps; import com.minelittlepony.unicopia.entity.player.Pony; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; import net.minecraft.sound.SoundCategory; import net.minecraft.text.Text; @@ -36,8 +38,8 @@ public class KirinRageAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/NirikBlastAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/NirikBlastAbility.java index 65c6f353..8ad4412c 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/NirikBlastAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/NirikBlastAbility.java @@ -11,9 +11,11 @@ import com.minelittlepony.unicopia.client.render.PlayerPoser.Animation.Recipient import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.ExplosionUtil; +import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageTypes; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.sound.SoundEvents; @@ -42,8 +44,8 @@ public class NirikBlastAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/PeckAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/PeckAbility.java index db5b09fc..1958aa41 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/PeckAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/PeckAbility.java @@ -5,18 +5,19 @@ import java.util.Optional; import com.minelittlepony.unicopia.EquinePredicates; import com.minelittlepony.unicopia.USounds; import com.minelittlepony.unicopia.ability.data.Hit; -import com.minelittlepony.unicopia.ability.data.Numeric; import com.minelittlepony.unicopia.entity.Living; import com.minelittlepony.unicopia.entity.damage.UDamageTypes; import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.TraceHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.registry.tag.BlockTags; import net.minecraft.server.world.ServerWorld; @@ -59,8 +60,8 @@ public class PeckAbility implements Ability { } @Override - public Numeric.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } protected LivingEntity findTarget(PlayerEntity player, World w) { diff --git a/src/main/java/com/minelittlepony/unicopia/ability/PegasusCaptureStormAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/PegasusCaptureStormAbility.java index 6b59dfe4..dd847d20 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/PegasusCaptureStormAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/PegasusCaptureStormAbility.java @@ -9,7 +9,9 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.item.UItems; import com.minelittlepony.unicopia.particle.MagicParticleEffect; +import io.netty.buffer.ByteBuf; import net.minecraft.item.ItemStack; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.network.packet.s2c.play.GameStateChangeS2CPacket; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.Text; @@ -39,8 +41,8 @@ public class PegasusCaptureStormAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/PegasusRainboomAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/PegasusRainboomAbility.java index 6e1fd02f..6af9e83d 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/PegasusRainboomAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/PegasusRainboomAbility.java @@ -10,6 +10,9 @@ import com.minelittlepony.unicopia.ability.magic.spell.effect.SpellType; import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.particle.MagicParticleEffect; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; + /** * Pegasus ability to perform rainbooms */ @@ -32,8 +35,8 @@ public class PegasusRainboomAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/ScreechAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/ScreechAbility.java index 100905b9..fe0b34e5 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/ScreechAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/ScreechAbility.java @@ -16,7 +16,9 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.util.RegistryUtils; import com.minelittlepony.unicopia.util.VecHelper; +import io.netty.buffer.ByteBuf; import net.minecraft.entity.LivingEntity; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.particle.ParticleTypes; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; @@ -58,8 +60,8 @@ public class ScreechAbility implements Ability { } @Override - public Numeric.Serializer getSerializer() { - return Numeric.SERIALIZER; + public PacketCodec getSerializer() { + return Numeric.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/SeaponySonarPulseAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/SeaponySonarPulseAbility.java index f1be14f7..332ca32f 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/SeaponySonarPulseAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/SeaponySonarPulseAbility.java @@ -13,11 +13,13 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.particle.ParticleUtils; import com.minelittlepony.unicopia.particle.UParticles; +import io.netty.buffer.ByteBuf; import net.minecraft.block.ChestBlock; import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityGroup; import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.SpawnGroup; import net.minecraft.entity.mob.HostileEntity; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.registry.tag.FluidTags; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; @@ -44,8 +46,8 @@ public class SeaponySonarPulseAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override @@ -58,7 +60,7 @@ public class SeaponySonarPulseAbility implements Ability { player.setAnimation(Animation.ARMS_UP, Animation.Recipient.ANYONE); for (Entity target : player.findAllEntitiesInRange(64, e -> { - return (e instanceof LivingEntity && (e instanceof HostileEntity || ((LivingEntity)e).getGroup() == EntityGroup.AQUATIC)) && e.isSubmergedInWater(); + return (e instanceof LivingEntity && (e instanceof HostileEntity || isWaterCreature(((LivingEntity)e).getType().getSpawnGroup()))) && e.isSubmergedInWater(); }).sorted(Comparator.comparing(e -> e.distanceTo(player.asEntity()))).toList()) { Vec3d offset = target.getPos().subtract(player.getOriginVector()); float distance = target.distanceTo(player.asEntity()); @@ -105,4 +107,12 @@ public class SeaponySonarPulseAbility implements Ability { @Override public void coolDown(Pony player, AbilitySlot slot) { } + + private static boolean isWaterCreature(SpawnGroup group) { + return switch (group) { + case AXOLOTLS, UNDERGROUND_WATER_CREATURE, WATER_CREATURE, WATER_AMBIENT -> true; + default -> false; + }; + } + } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/TimeChangeAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/TimeChangeAbility.java index 99e7d543..c6df8e5c 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/TimeChangeAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/TimeChangeAbility.java @@ -3,13 +3,15 @@ package com.minelittlepony.unicopia.ability; import java.util.Optional; import com.minelittlepony.unicopia.Race; -import com.minelittlepony.unicopia.ability.data.Hit.Serializer; import com.minelittlepony.unicopia.ability.data.Rot; import com.minelittlepony.unicopia.ability.magic.spell.CastingMethod; import com.minelittlepony.unicopia.ability.magic.spell.effect.SpellType; import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.server.world.UGameRules; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; + public class TimeChangeAbility implements Ability { @Override @@ -33,8 +35,8 @@ public class TimeChangeAbility implements Ability { } @Override - public Serializer getSerializer() { - return Rot.SERIALIZER; + public PacketCodec getSerializer() { + return Rot.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/ToggleFlightAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/ToggleFlightAbility.java index a3c3e6fa..ec86c1a1 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/ToggleFlightAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/ToggleFlightAbility.java @@ -10,6 +10,8 @@ import com.minelittlepony.unicopia.client.render.PlayerPoser.Animation; import com.minelittlepony.unicopia.entity.Living; import com.minelittlepony.unicopia.entity.player.Pony; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.util.Identifier; import net.minecraft.util.math.Vec3d; @@ -32,15 +34,14 @@ public class ToggleFlightAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Hit.SERIALIZER; + public PacketCodec getSerializer() { + return Hit.CODEC; } @Override public Identifier getIcon(Pony player) { - Identifier id = Abilities.REGISTRY.getId(this); Race race = player.getObservedSpecies(); - return new Identifier(id.getNamespace(), "textures/gui/ability/" + id.getPath() + return Abilities.REGISTRY.getId(this).withPath(p -> "textures/gui/ability/" + p + (player.getPhysics().isFlying() ? "_land" : "_takeoff") + "_" + (race.isHuman() ? Race.EARTH : race).getId().getPath() + ".png"); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/UnicornDispellAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/UnicornDispellAbility.java index 36c603c2..c3b52f8a 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/UnicornDispellAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/UnicornDispellAbility.java @@ -14,6 +14,8 @@ import com.minelittlepony.unicopia.particle.MagicParticleEffect; import com.minelittlepony.unicopia.util.TraceHelper; import com.minelittlepony.unicopia.util.VecHelper; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.text.Text; import net.minecraft.util.Identifier; @@ -39,13 +41,12 @@ public class UnicornDispellAbility implements Ability { @Override public Identifier getIcon(Pony player) { - Identifier id = Abilities.REGISTRY.getId(this); - return new Identifier(id.getNamespace(), "textures/gui/ability/" + id.getPath() + (player.getSpecies() == Race.CHANGELING ? "_changeling" : "") + ".png"); + return Abilities.REGISTRY.getId(this).withPath(p -> "textures/gui/ability/" + p + (player.getSpecies() == Race.CHANGELING ? "_changeling" : "") + ".png"); } @Override - public Pos.Serializer getSerializer() { - return Pos.SERIALIZER; + public PacketCodec getSerializer() { + return Pos.CODEC; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/UnicornTeleportAbility.java b/src/main/java/com/minelittlepony/unicopia/ability/UnicornTeleportAbility.java index 39cc5763..226adf3d 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/UnicornTeleportAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/UnicornTeleportAbility.java @@ -3,7 +3,6 @@ package com.minelittlepony.unicopia.ability; import java.util.Optional; import com.minelittlepony.unicopia.USounds; -import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.ability.data.Pos; import com.minelittlepony.unicopia.ability.magic.Caster; import com.minelittlepony.unicopia.ability.magic.spell.effect.SpellType; @@ -14,6 +13,7 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.particle.MagicParticleEffect; import com.minelittlepony.unicopia.util.Trace; +import io.netty.buffer.ByteBuf; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.LeavesBlock; @@ -21,6 +21,7 @@ import net.minecraft.block.PowderSnowBlock; import net.minecraft.block.ShapeContext; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.sound.SoundCategory; import net.minecraft.text.Text; @@ -131,8 +132,8 @@ public class UnicornTeleportAbility implements Ability { } @Override - public Hit.Serializer getSerializer() { - return Pos.SERIALIZER; + public PacketCodec getSerializer() { + return Pos.CODEC; } @Override @@ -177,10 +178,11 @@ public class UnicornTeleportAbility implements Ability { yPos, destination.z() + offset.getZ() ); - participant.teleport(dest.x, dest.y, dest.z); + // TODO: teleport -> requestTeleport + participant.requestTeleport(dest.x, dest.y, dest.z); if (participant.getWorld().getBlockCollisions(participant, participant.getBoundingBox()).iterator().hasNext()) { dest = destination.vec(); - participant.teleport(dest.x, participant.getY(), dest.z); + participant.requestTeleport(dest.x, participant.getY(), dest.z); } teleporter.subtractEnergyCost(distance); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/data/Hit.java b/src/main/java/com/minelittlepony/unicopia/ability/data/Hit.java index e61f1d7f..0f38d16a 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/data/Hit.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/data/Hit.java @@ -2,17 +2,13 @@ package com.minelittlepony.unicopia.ability.data; import java.util.Optional; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; public interface Hit { Optional INSTANCE = Optional.of(new Hit() {}); - Serializer SERIALIZER = new Serializer<>(buf -> INSTANCE.get(), (buf, t) -> {}); + PacketCodec CODEC = PacketCodec.unit(INSTANCE.get()); static Optional of(boolean value) { return value ? INSTANCE : Optional.empty(); } - - public record Serializer ( - PacketByteBuf.PacketReader read, - PacketByteBuf.PacketWriter write) { - } } \ No newline at end of file diff --git a/src/main/java/com/minelittlepony/unicopia/ability/data/Multi.java b/src/main/java/com/minelittlepony/unicopia/ability/data/Multi.java index 8a90e535..e059f99b 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/data/Multi.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/data/Multi.java @@ -1,14 +1,16 @@ package com.minelittlepony.unicopia.ability.data; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.util.math.Vec3i; public record Multi (Pos pos, int hitType) implements Hit { - public static final Serializer SERIALIZER = new Serializer<>( - buf -> new Multi(Pos.SERIALIZER.read().apply(buf), buf.readInt()), - (buf, t) -> { - Pos.SERIALIZER.write().accept(buf, t.pos()); - buf.writeInt(t.hitType()); - }); + public static final PacketCodec CODEC = PacketCodec.tuple( + Pos.CODEC, Multi::pos, + PacketCodecs.INTEGER, Multi::hitType, + Multi::new + ); public Multi(Vec3i pos, int hit) { this(new Pos(pos), hit); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/data/Numeric.java b/src/main/java/com/minelittlepony/unicopia/ability/data/Numeric.java index 772160b3..8794741f 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/data/Numeric.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/data/Numeric.java @@ -2,10 +2,12 @@ package com.minelittlepony.unicopia.ability.data; import java.util.Optional; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; + public record Numeric (int type) implements Hit { - public static final Serializer SERIALIZER = new Serializer<>( - buf -> new Numeric(buf.readInt()), - (buf, t) -> buf.writeInt(t.type())); + public static final PacketCodec CODEC = PacketCodecs.INTEGER.xmap(Numeric::new, Numeric::type); public static Optional of(int type) { return Optional.of(new Numeric(type)); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/data/Pos.java b/src/main/java/com/minelittlepony/unicopia/ability/data/Pos.java index b818996b..3db0ad8e 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/data/Pos.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/data/Pos.java @@ -2,16 +2,18 @@ package com.minelittlepony.unicopia.ability.data; import com.minelittlepony.unicopia.ability.magic.Caster; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.util.math.*; public record Pos (int x, int y, int z) implements Hit { - public static final Serializer SERIALIZER = new Serializer<>( - buf -> new Pos(buf.readInt(), buf.readInt(), buf.readInt()), - (buf, t) -> { - buf.writeInt(t.x()); - buf.writeInt(t.y()); - buf.writeInt(t.z()); - }); + public static final PacketCodec CODEC = PacketCodec.tuple( + PacketCodecs.INTEGER, Pos::x, + PacketCodecs.INTEGER, Pos::y, + PacketCodecs.INTEGER, Pos::z, + Pos::new + ); public Pos(Vec3i pos) { this(pos.getX(), pos.getY(), pos.getZ()); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/data/Rot.java b/src/main/java/com/minelittlepony/unicopia/ability/data/Rot.java index 104ed191..1d05d0ec 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/data/Rot.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/data/Rot.java @@ -2,15 +2,17 @@ package com.minelittlepony.unicopia.ability.data; import com.minelittlepony.unicopia.EntityConvertable; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.util.math.Vec3d; public record Rot (float pitch, float yaw) implements Hit { - public static final Serializer SERIALIZER = new Serializer<>( - buf -> new Rot(buf.readFloat(), buf.readFloat()), - (buf, t) -> { - buf.writeFloat(t.pitch()); - buf.writeFloat(t.yaw()); - }); + public static final PacketCodec CODEC = PacketCodec.tuple( + PacketCodecs.FLOAT, Rot::pitch, + PacketCodecs.FLOAT, Rot::yaw, + Rot::new + ); public Rot applyTo(EntityConvertable target) { Vec3d pos = target.getOriginVector(); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/MultiSpellSlot.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/MultiSpellSlot.java index 50cb5902..3dd698e5 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/MultiSpellSlot.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/MultiSpellSlot.java @@ -14,12 +14,14 @@ import com.minelittlepony.unicopia.network.track.MsgTrackedValues; import com.minelittlepony.unicopia.network.track.ObjectTracker; import com.minelittlepony.unicopia.network.track.Trackable; import com.minelittlepony.unicopia.network.track.TrackableObject; +import com.minelittlepony.unicopia.network.track.MsgTrackedValues.TrackerEntries; import com.minelittlepony.unicopia.util.NbtSerialisable; -import com.minelittlepony.unicopia.util.serialization.PacketCodec; import io.netty.buffer.Unpooled; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; /** * Container for multiple spells @@ -68,12 +70,12 @@ class MultiSpellSlot implements SpellSlots, NbtSerialisable { } @Override - public void toNBT(NbtCompound compound) { - compound.put("spells", NbtSerialisable.writeMap(tracker.entries(), UUID::toString, entry -> entry.spell.toNBT())); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + compound.put("spells", NbtSerialisable.writeMap(tracker.entries(), UUID::toString, entry -> entry.spell.toNBT(lookup))); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { tracker.load(NbtSerialisable.readMap(compound.getCompound("spells"), key -> { try { return UUID.fromString(key); @@ -82,7 +84,7 @@ class MultiSpellSlot implements SpellSlots, NbtSerialisable { }, (key, nbt) -> { try { Entry entry = new Entry<>(owner); - entry.spell.fromNBT((NbtCompound)nbt); + entry.spell.fromNBT((NbtCompound)nbt, lookup); return entry; } catch (Throwable t) { Unicopia.LOGGER.warn("Exception loading tracked object: {}", t.getMessage()); @@ -135,34 +137,34 @@ class MultiSpellSlot implements SpellSlots, NbtSerialisable { } @Override - public void readTrackedNbt(NbtCompound nbt) { - spell.fromNBT(nbt); + public void readTrackedNbt(NbtCompound nbt, WrapperLookup lookup) { + spell.fromNBT(nbt, lookup); } @Override - public NbtCompound writeTrackedNbt() { - return spell.toNBT(); + public NbtCompound writeTrackedNbt(WrapperLookup lookup) { + return spell.toNBT(lookup); } @Override - public void read(PacketByteBuf buffer) { + public void read(PacketByteBuf buffer, WrapperLookup lookup) { byte contentType = buffer.readByte(); if (contentType == 1) { - readTrackedNbt(PacketCodec.COMPRESSED_NBT.read(buffer)); + readTrackedNbt(PacketCodecs.NBT_COMPOUND.decode(buffer), lookup); } else { T spell = this.spell.get(); if (spell != null) { - spell.getDataTracker().load(new MsgTrackedValues.TrackerEntries(buffer)); + spell.getDataTracker().load(MsgTrackedValues.TrackerEntries.PACKET_CODEC.decode(buffer)); } } } @Override - public Optional write(Status status) { + public Optional write(Status status, WrapperLookup lookup) { if (status != Status.DEFAULT) { PacketByteBuf buffer = new PacketByteBuf(Unpooled.buffer()); buffer.writeByte(1); - PacketCodec.COMPRESSED_NBT.write(buffer, spell.toNBT()); + PacketCodecs.NBT_COMPOUND.encode(buffer, spell.toNBT(lookup)); return Optional.of(buffer); } @Nullable T spell = this.spell.get(); @@ -172,7 +174,7 @@ class MultiSpellSlot implements SpellSlots, NbtSerialisable { return spell.getDataTracker().getDirtyPairs().map(entries -> { PacketByteBuf buffer = new PacketByteBuf(Unpooled.buffer()); buffer.writeByte(0); - entries.write(buffer); + TrackerEntries.PACKET_CODEC.encode(buffer, entries); return buffer; }); } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/SingleSpellSlot.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/SingleSpellSlot.java index 94d6c664..02c0124c 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/SingleSpellSlot.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/SingleSpellSlot.java @@ -9,6 +9,7 @@ import com.minelittlepony.unicopia.ability.magic.spell.Spell; import com.minelittlepony.unicopia.network.track.Trackable; import com.minelittlepony.unicopia.util.NbtSerialisable; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; /** * Container for a single spell @@ -57,13 +58,13 @@ class SingleSpellSlot implements SpellSlots, NbtSerialisable { } @Override - public void toNBT(NbtCompound compound) { - compound.put("effect", entry.spell.toNBT()); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + compound.put("effect", entry.spell.toNBT(lookup)); } @Override - public void fromNBT(NbtCompound compound) { - entry.spell.fromNBT(compound.getCompound("effect")); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + entry.spell.fromNBT(compound.getCompound("effect"), lookup); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDelegatingSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDelegatingSpell.java index 9ff86367..74967fbe 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDelegatingSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDelegatingSpell.java @@ -11,6 +11,7 @@ import com.minelittlepony.unicopia.network.track.DataTracker; import com.minelittlepony.unicopia.server.world.Ether; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public abstract class AbstractDelegatingSpell implements Spell { private UUID uuid = UUID.randomUUID(); @@ -109,17 +110,17 @@ public abstract class AbstractDelegatingSpell implements Spell { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putUuid("uuid", uuid); - compound.put("spell", delegate.toNBT()); + compound.put("spell", delegate.toNBT(lookup)); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { if (compound.contains("uuid")) { uuid = compound.getUuid("uuid"); } - delegate.fromNBT(compound.getCompound("spell")); + delegate.fromNBT(compound.getCompound("spell"), lookup); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDisguiseSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDisguiseSpell.java index b4e6ad08..aeffdd0c 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDisguiseSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/AbstractDisguiseSpell.java @@ -14,6 +14,7 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.ProjectileEntity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; /** * Base implementation for a spell that changes the player's appearance. @@ -53,14 +54,14 @@ public abstract class AbstractDisguiseSpell extends AbstractSpell implements Dis } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); disguise.toNBT(compound); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); disguise.fromNBT(compound); } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/ChangelingFeedingSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/ChangelingFeedingSpell.java index 1bae80a1..256b83f2 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/ChangelingFeedingSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/ChangelingFeedingSpell.java @@ -23,6 +23,7 @@ import net.minecraft.entity.effect.StatusEffects; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.MathHelper; public class ChangelingFeedingSpell extends AbstractSpell { @@ -141,22 +142,22 @@ public class ChangelingFeedingSpell extends AbstractSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putFloat("healthToDrain", healthToDrain); compound.putInt("foodToDrain", foodToDrain); compound.putFloat("damageThisTick", damageThisTick); - compound.put("targets", EntityReference.getSerializer().writeAll(targets)); + compound.put("targets", EntityReference.getSerializer().writeAll(targets, lookup)); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); healthToDrain = compound.getFloat("healthToDrain"); foodToDrain = compound.getInt("foodToDrain"); damageThisTick = compound.getFloat("damageThisTick"); targets = compound.contains("targets", NbtElement.LIST_TYPE) - ? EntityReference.getSerializer().readAll(compound.getList("targets", NbtElement.COMPOUND_TYPE)).toList() + ? EntityReference.getSerializer().readAll(compound.getList("targets", NbtElement.COMPOUND_TYPE), lookup).toList() : List.of(); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/DispersableDisguiseSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/DispersableDisguiseSpell.java index 2b7f7cb8..d037a150 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/DispersableDisguiseSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/DispersableDisguiseSpell.java @@ -15,6 +15,7 @@ import com.minelittlepony.unicopia.particle.MagicParticleEffect; import com.minelittlepony.unicopia.particle.UParticles; import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; /** * Shapeshifts the player. @@ -95,15 +96,15 @@ public class DispersableDisguiseSpell extends AbstractDisguiseSpell implements I } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putInt("suppressionCounter", suppressionCounter); compound.putBoolean("forced", forced); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); suppressionCounter = compound.getInt("suppressionCounter"); forced = compound.getBoolean("forced"); if (suppressionCounter > 0) { diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/EmptySpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/EmptySpell.java index f4dca074..d2f94ff9 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/EmptySpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/EmptySpell.java @@ -8,6 +8,7 @@ import com.minelittlepony.unicopia.ability.magic.spell.effect.SpellType; import com.minelittlepony.unicopia.network.track.DataTracker; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Util; public final class EmptySpell implements Spell { @@ -16,10 +17,10 @@ public final class EmptySpell implements Spell { private EmptySpell() {} @Override - public void toNBT(NbtCompound compound) { } + public void toNBT(NbtCompound compound, WrapperLookup lookup) { } @Override - public void fromNBT(NbtCompound compound) { } + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { } @Override public CustomisedSpellType getTypeAndTraits() { diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/PlacementControlSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/PlacementControlSpell.java index e3f31a03..e0507901 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/PlacementControlSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/PlacementControlSpell.java @@ -18,6 +18,7 @@ import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Identifier; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; @@ -120,9 +121,9 @@ public class PlacementControlSpell extends AbstractSpell implements OrientedSpel } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - compound.put("spell", Spell.writeNbt(delegate)); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + compound.put("spell", Spell.writeNbt(delegate, lookup)); position.get().ifPresent(pos -> compound.put("position", NbtSerialisable.writeVector(pos))); orientation.get().ifPresent(o -> compound.put("orientation", NbtSerialisable.writeVector(o))); dimension.get().ifPresent(d -> compound.putString("dimension", d.getValue().toString())); @@ -132,9 +133,9 @@ public class PlacementControlSpell extends AbstractSpell implements OrientedSpel } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - delegate = Spell.readNbt(compound.getCompound("spell")); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + delegate = Spell.readNbt(compound.getCompound("spell"), lookup); placedEntityId.set(compound.containsUuid("placedEntityId") ? compound.getUuid("placedEntityId") : null); position.set(compound.contains("position") ? Optional.of(NbtSerialisable.readVector(compound.getList("position", NbtElement.DOUBLE_TYPE))) : Optional.empty()); orientation.set(compound.contains("orientation") ? Optional.of(NbtSerialisable.readVector(compound.getList("orientation", NbtElement.DOUBLE_TYPE))) : Optional.empty()); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RageAbilitySpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RageAbilitySpell.java index dbf98cf2..ef4a3376 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RageAbilitySpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RageAbilitySpell.java @@ -15,6 +15,7 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageTypes; import net.minecraft.nbt.NbtCompound; import net.minecraft.particle.ParticleTypes; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BlockView; @@ -130,14 +131,14 @@ public class RageAbilitySpell extends AbstractSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putInt("age", age); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); age = compound.getInt("age"); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RainboomAbilitySpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RainboomAbilitySpell.java index 173d73f0..2e7adac2 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RainboomAbilitySpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/RainboomAbilitySpell.java @@ -19,6 +19,7 @@ import com.minelittlepony.unicopia.util.shape.Sphere; import net.minecraft.block.BlockState; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.Vec3d; /** @@ -85,14 +86,14 @@ public class RainboomAbilitySpell extends AbstractSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putInt("age", age); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); age = compound.getInt("age"); boundParticle = null; } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/Spell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/Spell.java index 6add4b0f..ac647fc7 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/Spell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/Spell.java @@ -18,13 +18,15 @@ import com.minelittlepony.unicopia.server.world.Ether; import com.minelittlepony.unicopia.util.NbtSerialisable; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Util; /** * Interface for a magic spells */ public interface Spell extends NbtSerialisable, Affine { - Serializer SERIALIZER = Serializer.of(Spell::readNbt, Spell::writeNbt); + @Deprecated + Serializer SERIALIZER = Serializer.of(Spell::readNbt, Spell::writeNbt); /** * Returns the full type that describes this spell. @@ -133,7 +135,7 @@ public interface Spell extends NbtSerialisable, Affine { } @Nullable - static T readNbt(@Nullable NbtCompound compound) { + static T readNbt(@Nullable NbtCompound compound, WrapperLookup lookup) { try { if (compound != null) { return CustomisedSpellType.fromNBT(compound).create(compound); @@ -149,16 +151,16 @@ public interface Spell extends NbtSerialisable, Affine { return compound == null || !compound.containsUuid("uuid") ? Util.NIL_UUID : compound.getUuid("uuid"); } - static NbtCompound writeNbt(@Nullable Spell effect) { + static NbtCompound writeNbt(@Nullable Spell effect, WrapperLookup lookup) { if (effect == null) { return new NbtCompound(); } - NbtCompound compound = effect.toNBT(); + NbtCompound compound = effect.toNBT(lookup); effect.getTypeAndTraits().toNbt(compound); return compound; } - static Spell copy(T spell) { - return readNbt(writeNbt(spell)); + static Spell copy(T spell, WrapperLookup lookup) { + return readNbt(writeNbt(spell, lookup), lookup); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/SpellReference.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/SpellReference.java index 66cd3acc..39255734 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/SpellReference.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/SpellReference.java @@ -11,6 +11,7 @@ import com.minelittlepony.unicopia.ability.magic.SpellPredicate; import com.minelittlepony.unicopia.util.NbtSerialisable; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public final class SpellReference implements NbtSerialisable { @Nullable @@ -50,19 +51,19 @@ public final class SpellReference implements NbtSerialisable { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { if (spell != null && !spell.isDead()) { - spell.toNBT(compound); + spell.toNBT(compound, lookup); spell.getTypeAndTraits().toNbt(compound); } } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { if (spell == null || !Objects.equals(Spell.getUuid(compound), spell.getUuid())) { - spell = Spell.readNbt(compound); + spell = Spell.readNbt(compound, lookup); } else { - spell.fromNBT(compound); + spell.fromNBT(compound, lookup); } } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimeControlAbilitySpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimeControlAbilitySpell.java index 8490cbeb..3616c4f4 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimeControlAbilitySpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimeControlAbilitySpell.java @@ -8,6 +8,7 @@ import com.minelittlepony.unicopia.server.world.UGameRules; import com.minelittlepony.unicopia.server.world.UnicopiaWorldProperties; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; /** @@ -75,16 +76,16 @@ public class TimeControlAbilitySpell extends AbstractSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putBoolean("initilized", initilized); compound.putLong("timeOffset", timeOffset); compound.putFloat("angleOffset", angleOffset); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); initilized = compound.getBoolean("initilized"); timeOffset = compound.getLong("timeOffset"); angleOffset = compound.getFloat("angleOffset"); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimedSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimedSpell.java index 18546975..78695f74 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimedSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/TimedSpell.java @@ -8,6 +8,7 @@ import com.minelittlepony.unicopia.util.NbtSerialisable; import com.minelittlepony.unicopia.util.Tickable; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.MathHelper; /** @@ -44,13 +45,13 @@ public interface TimedSpell extends Spell { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putInt("duration", duration); compound.putInt("maxDuration", maxDuration); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { duration = compound.getInt("duration"); maxDuration = compound.getInt("maxDuration"); } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/attribute/AttributeFormat.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/attribute/AttributeFormat.java index 17fdd132..9c6d82f3 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/attribute/AttributeFormat.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/attribute/AttributeFormat.java @@ -5,7 +5,7 @@ import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait; import com.minelittlepony.unicopia.client.UnicopiaClient; import com.minelittlepony.unicopia.client.gui.ItemTraitsTooltipRenderer; -import net.minecraft.item.ItemStack; +import net.minecraft.component.type.AttributeModifiersComponent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; @@ -15,7 +15,7 @@ public enum AttributeFormat { REGULAR { @Override public String formatValue(float value) { - return ItemStack.MODIFIER_FORMAT.format(value); + return AttributeModifiersComponent.DECIMAL_FORMAT.format(value); } }, TIME { @@ -27,7 +27,7 @@ public enum AttributeFormat { PERCENTAGE { @Override public String formatValue(float value) { - return ItemStack.MODIFIER_FORMAT.format((int)(Math.abs(value) * 100)) + "%"; + return AttributeModifiersComponent.DECIMAL_FORMAT.format((int)(Math.abs(value) * 100)) + "%"; } }; @@ -61,7 +61,7 @@ public enum AttributeFormat { ? trait.getName() : Text.translatable("spell_attribute.unicopia.added_trait.unknown").formatted(Formatting.YELLOW) : trait.getName().copy().formatted(Formatting.OBFUSCATED, Formatting.YELLOW); - Text count = Text.literal(ItemStack.MODIFIER_FORMAT.format(value)); + Text count = Text.literal(AttributeModifiersComponent.DECIMAL_FORMAT.format(value)); return Text.translatable("spell_attribute.unicopia.added_trait." + ((value > 0) ? "plus" : "take"), name, count).formatted(Formatting.DARK_AQUA); } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/AltarRecipeMatch.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/AltarRecipeMatch.java index 820f7667..253dc7da 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/AltarRecipeMatch.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/AltarRecipeMatch.java @@ -34,7 +34,6 @@ public record AltarRecipeMatch( public void craft() { ItemStack clockStack = result.copyWithCount(target.getStack().getCount()); - clockStack.setNbt(target.getStack().getNbt()); target.setStack(clockStack); target.setInvulnerable(true); ingredients.forEach(Entity::discard); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/IngredientWithSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/IngredientWithSpell.java index 04c95b3b..f866d317 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/IngredientWithSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/IngredientWithSpell.java @@ -15,8 +15,11 @@ import com.mojang.serialization.Codec; import net.minecraft.item.ItemConvertible; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.recipe.Ingredient; +import net.minecraft.util.Identifier; import net.minecraft.util.collection.DefaultedList; public class IngredientWithSpell implements Predicate { @@ -27,6 +30,11 @@ public class IngredientWithSpell implements Predicate { pair -> new IngredientWithSpell(pair.getFirst(), pair.getSecond()), ingredient -> new Pair<>(ingredient.stack, ingredient.spell) ); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.optional(Ingredient.PACKET_CODEC), i -> i.stack, + PacketCodecs.optional(Identifier.PACKET_CODEC.xmap(SpellType::getKey, SpellType::getId)), i -> i.spell, + IngredientWithSpell::new + ); public static final Codec> LIST_CODEC = CODEC.listOf().xmap( list -> DefaultedList.copyOf(EMPTY, list.toArray(IngredientWithSpell[]::new)), @@ -75,16 +83,4 @@ public class IngredientWithSpell implements Predicate { public boolean isEmpty() { return stack.filter(INGREDIENT_IS_PRESENT).isEmpty() && spell.isEmpty(); } - - public void write(PacketByteBuf buf) { - buf.writeOptional(stack, (b, i) -> i.write(b)); - buf.writeOptional(spell.map(SpellType::getId), PacketByteBuf::writeIdentifier); - } - - public static IngredientWithSpell fromPacket(PacketByteBuf buf) { - return new IngredientWithSpell( - buf.readOptional(Ingredient::fromPacket), - buf.readOptional(PacketByteBuf::readIdentifier).flatMap(SpellType.REGISTRY::getOrEmpty) - ); - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellCraftingRecipe.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellCraftingRecipe.java index f65fca75..76d1ef1a 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellCraftingRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellCraftingRecipe.java @@ -14,19 +14,40 @@ import com.minelittlepony.unicopia.util.CodecUtils; import com.minelittlepony.unicopia.util.InventoryUtil; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.world.World; /** * A recipe for creating a new spell from input traits and items. */ public class SpellCraftingRecipe implements SpellbookRecipe { + private static final Codec RESULT_CODEC = CodecUtils.extend(ItemStack.CODEC, SpellType.REGISTRY.getCodec().fieldOf("spell")).xmap( + pair -> pair.getSecond().map(spell -> EnchantableItem.enchant(pair.getFirst().orElse(ItemStack.EMPTY), spell)).orElse(pair.getFirst().orElse(ItemStack.EMPTY)), + stack -> Pair.of(Optional.of(stack), EnchantableItem.getSpellKeyOrEmpty(stack)) + ); + + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + IngredientWithSpell.CODEC.fieldOf("material").forGetter(recipe -> recipe.material), + TraitIngredient.CODEC.fieldOf("traits").forGetter(recipe -> recipe.requiredTraits), + IngredientWithSpell.CODEC.listOf().fieldOf("ingredients").forGetter(recipe -> recipe.requiredItems), + RESULT_CODEC.fieldOf("result").forGetter(recipe -> recipe.output) + ).apply(instance, SpellCraftingRecipe::new)); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + IngredientWithSpell.PACKET_CODEC, recipe -> recipe.material, + TraitIngredient.PACKET_CODEC, recipe -> recipe.requiredTraits, + IngredientWithSpell.PACKET_CODEC.collect(PacketCodecs.toList()), recipe -> recipe.requiredItems, + ItemStack.PACKET_CODEC, recipe -> recipe.output, + SpellCraftingRecipe::new + ); + /** * The ingredient to modify */ @@ -104,7 +125,7 @@ public class SpellCraftingRecipe implements SpellbookRecipe { } @Override - public ItemStack craft(SpellbookInventory inventory, DynamicRegistryManager registries) { + public ItemStack craft(SpellbookInventory inventory, WrapperLookup registries) { return getResult(registries).copy(); } @@ -114,7 +135,7 @@ public class SpellCraftingRecipe implements SpellbookRecipe { } @Override - public ItemStack getResult(DynamicRegistryManager registries) { + public ItemStack getResult(WrapperLookup registries) { return output; } @@ -122,41 +143,4 @@ public class SpellCraftingRecipe implements SpellbookRecipe { public RecipeSerializer getSerializer() { return URecipes.TRAIT_REQUIREMENT; } - - public static class Serializer implements RecipeSerializer { - private static final Codec RESULT_CODEC = CodecUtils.extend(ItemStack.RECIPE_RESULT_CODEC, SpellType.REGISTRY.getCodec().fieldOf("spell")).xmap( - pair -> pair.getSecond().map(spell -> EnchantableItem.enchant(pair.getFirst().orElse(ItemStack.EMPTY), spell)).orElse(pair.getFirst().orElse(ItemStack.EMPTY)), - stack -> Pair.of(Optional.of(stack), EnchantableItem.getSpellKeyOrEmpty(stack)) - ); - - private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - IngredientWithSpell.CODEC.fieldOf("material").forGetter(recipe -> recipe.material), - TraitIngredient.CODEC.fieldOf("traits").forGetter(recipe -> recipe.requiredTraits), - IngredientWithSpell.CODEC.listOf().fieldOf("ingredients").forGetter(recipe -> recipe.requiredItems), - RESULT_CODEC.fieldOf("result").forGetter(recipe -> recipe.output) - ).apply(instance, SpellCraftingRecipe::new)); - - @Override - public Codec codec() { - return CODEC; - } - - @Override - public SpellCraftingRecipe read(PacketByteBuf buf) { - return new SpellCraftingRecipe( - IngredientWithSpell.fromPacket(buf), - TraitIngredient.fromPacket(buf), - buf.readCollection(DefaultedList::ofSize, IngredientWithSpell::fromPacket), - buf.readItemStack() - ); - } - - @Override - public void write(PacketByteBuf buf, SpellCraftingRecipe recipe) { - recipe.material.write(buf); - recipe.requiredTraits.write(buf); - buf.writeCollection(recipe.requiredItems, (b, i) -> i.write(b)); - buf.writeItemStack(recipe.output); - } - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellDuplicatingRecipe.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellDuplicatingRecipe.java index 79b9b1bd..60cc2c08 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellDuplicatingRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellDuplicatingRecipe.java @@ -5,22 +5,24 @@ import com.minelittlepony.unicopia.container.inventory.SpellbookInventory; import com.minelittlepony.unicopia.item.*; import com.minelittlepony.unicopia.recipe.URecipes; import com.minelittlepony.unicopia.util.InventoryUtil; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.world.World; /** * A recipe for creating a new spell from input traits and items. */ public record SpellDuplicatingRecipe (IngredientWithSpell material) implements SpellbookRecipe { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( IngredientWithSpell.CODEC.fieldOf("material").forGetter(recipe -> recipe.material) ).apply(instance, SpellDuplicatingRecipe::new)); + public static final PacketCodec PACKET_CODEC = IngredientWithSpell.PACKET_CODEC.xmap(SpellDuplicatingRecipe::new, SpellDuplicatingRecipe::material); @Override public void buildCraftingTree(CraftingTreeBuilder builder) { @@ -50,7 +52,7 @@ public record SpellDuplicatingRecipe (IngredientWithSpell material) implements S } @Override - public ItemStack craft(SpellbookInventory inventory, DynamicRegistryManager registries) { + public ItemStack craft(SpellbookInventory inventory, WrapperLookup registries) { return InventoryUtil.stream(inventory) .filter(i -> i.isOf(UItems.GEMSTONE)) .filter(EnchantableItem::isEnchanted) @@ -68,7 +70,7 @@ public record SpellDuplicatingRecipe (IngredientWithSpell material) implements S } @Override - public ItemStack getResult(DynamicRegistryManager registries) { + public ItemStack getResult(WrapperLookup registries) { ItemStack stack = UItems.GEMSTONE.getDefaultStack(); stack.setCount(2); return stack; @@ -78,21 +80,4 @@ public record SpellDuplicatingRecipe (IngredientWithSpell material) implements S public RecipeSerializer getSerializer() { return URecipes.SPELL_DUPLICATING; } - - public static class Serializer implements RecipeSerializer { - @Override - public Codec codec() { - return CODEC; - } - - @Override - public SpellDuplicatingRecipe read(PacketByteBuf buf) { - return new SpellDuplicatingRecipe(IngredientWithSpell.fromPacket(buf)); - } - - @Override - public void write(PacketByteBuf buf, SpellDuplicatingRecipe recipe) { - recipe.material.write(buf); - } - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellEnhancingRecipe.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellEnhancingRecipe.java index 9c601e18..9a41928b 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellEnhancingRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellEnhancingRecipe.java @@ -3,23 +3,25 @@ package com.minelittlepony.unicopia.ability.magic.spell.crafting; import com.minelittlepony.unicopia.ability.magic.spell.trait.SpellTraits; import com.minelittlepony.unicopia.container.inventory.SpellbookInventory; import com.minelittlepony.unicopia.item.*; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.minelittlepony.unicopia.recipe.URecipes; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.world.World; /** * Recipe for adding traits to an existing spell. */ public record SpellEnhancingRecipe (IngredientWithSpell material) implements SpellbookRecipe { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( IngredientWithSpell.CODEC.fieldOf("material").forGetter(recipe -> recipe.material) ).apply(instance, SpellEnhancingRecipe::new)); + public static final PacketCodec PACKET_CODEC = IngredientWithSpell.PACKET_CODEC.xmap(SpellEnhancingRecipe::new, SpellEnhancingRecipe::material); public IngredientWithSpell getBaseMaterial() { return material; @@ -42,7 +44,7 @@ public record SpellEnhancingRecipe (IngredientWithSpell material) implements Spe } @Override - public ItemStack craft(SpellbookInventory inventory, DynamicRegistryManager registries) { + public ItemStack craft(SpellbookInventory inventory, WrapperLookup registries) { return SpellTraits.of(inventory.getItemToModify()) .add(inventory.getTraits()) .applyTo(inventory.getItemToModify()); @@ -54,7 +56,7 @@ public record SpellEnhancingRecipe (IngredientWithSpell material) implements Spe } @Override - public ItemStack getResult(DynamicRegistryManager registries) { + public ItemStack getResult(WrapperLookup registries) { return UItems.GEMSTONE.getDefaultStack(); } @@ -62,21 +64,4 @@ public record SpellEnhancingRecipe (IngredientWithSpell material) implements Spe public RecipeSerializer getSerializer() { return URecipes.TRAIT_COMBINING; } - - public static class Serializer implements RecipeSerializer { - @Override - public Codec codec() { - return CODEC; - } - - @Override - public SpellEnhancingRecipe read(PacketByteBuf buf) { - return new SpellEnhancingRecipe(IngredientWithSpell.fromPacket(buf)); - } - - @Override - public void write(PacketByteBuf buf, SpellEnhancingRecipe recipe) { - recipe.material().write(buf); - } - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellShapedCraftingRecipe.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellShapedCraftingRecipe.java index e0a70a61..a82a6080 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellShapedCraftingRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/SpellShapedCraftingRecipe.java @@ -2,21 +2,37 @@ package com.minelittlepony.unicopia.ability.magic.spell.crafting; import com.minelittlepony.unicopia.item.EnchantableItem; import com.minelittlepony.unicopia.recipe.URecipes; -import com.minelittlepony.unicopia.util.InventoryUtil; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.inventory.RecipeInputInventory; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.recipe.RawShapedRecipe; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.ShapedRecipe; import net.minecraft.recipe.book.CraftingRecipeCategory; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.util.dynamic.Codecs; +import net.minecraft.recipe.input.CraftingRecipeInput; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public class SpellShapedCraftingRecipe extends ShapedRecipe { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + Codec.STRING.optionalFieldOf("group", "").forGetter(SpellShapedCraftingRecipe::getGroup), + CraftingRecipeCategory.CODEC.fieldOf("category").orElse(CraftingRecipeCategory.MISC).forGetter(SpellShapedCraftingRecipe::getCategory), + RawShapedRecipe.CODEC.forGetter(recipe -> recipe.raw), ItemStack.VALIDATED_CODEC.fieldOf("result").forGetter(recipe -> recipe.result), + Codec.BOOL.optionalFieldOf("show_notification", true).forGetter(SpellShapedCraftingRecipe::showNotification) + ).apply(instance, SpellShapedCraftingRecipe::new)); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.STRING, SpellShapedCraftingRecipe::getGroup, + CraftingRecipeCategory.PACKET_CODEC, SpellShapedCraftingRecipe::getCategory, + RawShapedRecipe.PACKET_CODEC, recipe -> recipe.raw, + ItemStack.PACKET_CODEC, recipe -> recipe.result, + PacketCodecs.BOOL, SpellShapedCraftingRecipe::showNotification, + SpellShapedCraftingRecipe::new + ); + private final RawShapedRecipe raw; private final ItemStack result; @@ -27,8 +43,8 @@ public class SpellShapedCraftingRecipe extends ShapedRecipe { } @Override - public ItemStack craft(RecipeInputInventory inventory, DynamicRegistryManager registries) { - return InventoryUtil.stream(inventory) + public ItemStack craft(CraftingRecipeInput inventory, WrapperLookup registries) { + return inventory.getStacks().stream() .filter(stack -> stack.getItem() instanceof EnchantableItem) .filter(EnchantableItem::isEnchanted) .map(stack -> ((EnchantableItem)stack.getItem()).getSpellEffect(stack)) @@ -41,38 +57,4 @@ public class SpellShapedCraftingRecipe extends ShapedRecipe { public RecipeSerializer getSerializer() { return URecipes.CRAFTING_MAGICAL_SERIALIZER; } - - public static class Serializer implements RecipeSerializer { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codecs.createStrictOptionalFieldCodec(Codec.STRING, "group", "").forGetter(SpellShapedCraftingRecipe::getGroup), - CraftingRecipeCategory.CODEC.fieldOf("category").orElse(CraftingRecipeCategory.MISC).forGetter(SpellShapedCraftingRecipe::getCategory), - RawShapedRecipe.CODEC.forGetter(recipe -> recipe.raw), ItemStack.RECIPE_RESULT_CODEC.fieldOf("result").forGetter(recipe -> recipe.result), - Codecs.createStrictOptionalFieldCodec(Codec.BOOL, "show_notification", true).forGetter(SpellShapedCraftingRecipe::showNotification) - ).apply(instance, SpellShapedCraftingRecipe::new)); - - @Override - public Codec codec() { - return CODEC; - } - - @Override - public SpellShapedCraftingRecipe read(PacketByteBuf buffer) { - return new SpellShapedCraftingRecipe( - buffer.readString(), - buffer.readEnumConstant(CraftingRecipeCategory.class), - RawShapedRecipe.readFromBuf(buffer), - buffer.readItemStack(), - buffer.readBoolean() - ); - } - - @Override - public void write(PacketByteBuf packetByteBuf, SpellShapedCraftingRecipe shapedRecipe) { - packetByteBuf.writeString(shapedRecipe.getGroup()); - packetByteBuf.writeEnumConstant(shapedRecipe.getCategory()); - shapedRecipe.raw.writeToBuf(packetByteBuf); - packetByteBuf.writeItemStack(shapedRecipe.result); - packetByteBuf.writeBoolean(shapedRecipe.showNotification()); - } - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/TraitIngredient.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/TraitIngredient.java index 8f5937ed..7362e5b7 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/TraitIngredient.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/crafting/TraitIngredient.java @@ -10,7 +10,8 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.dynamic.Codecs; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; public record TraitIngredient ( Optional min, @@ -27,10 +28,15 @@ public record TraitIngredient ( ingredient -> !ingredient.isEmpty() ? DataResult.success(ingredient) : DataResult.error(() -> "No min or max supplied for ingredient"), DataResult::success ); - public static final Codec CODEC = Codecs.xor(INLINE_CODEC, STRUCTURED_CODEC).flatXmap( + public static final Codec CODEC = Codec.xor(INLINE_CODEC, STRUCTURED_CODEC).flatXmap( either -> either.left().or(either::right).map(DataResult::success).orElseGet(() -> DataResult.error(() -> "Invalid traits")), ingredient -> DataResult.success(ingredient.max.isEmpty() ? Either.left(ingredient) : Either.right(ingredient)) ); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.optional(SpellTraits.PACKET_CODEC), TraitIngredient::min, + PacketCodecs.optional(SpellTraits.PACKET_CODEC), TraitIngredient::max, + TraitIngredient::new + ); public static TraitIngredient of(SpellTraits minTraits) { if (minTraits.isEmpty()) { @@ -60,13 +66,4 @@ public record TraitIngredient ( boolean maxMatch = max.map(m -> m.includes(t)).orElse(true); return minMatch && maxMatch; } - - public void write(PacketByteBuf buf) { - buf.writeOptional(min, (b, m) -> m.write(b)); - buf.writeOptional(max, (b, m) -> m.write(b)); - } - - public static TraitIngredient fromPacket(PacketByteBuf buf) { - return new TraitIngredient(SpellTraits.fromPacketOrEmpty(buf), SpellTraits.fromPacketOrEmpty(buf)); - } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/AbstractSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/AbstractSpell.java index 16839123..0a14386e 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/AbstractSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/AbstractSpell.java @@ -10,6 +10,7 @@ import com.minelittlepony.unicopia.network.track.TrackableDataType; import com.minelittlepony.unicopia.server.world.Ether; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public abstract class AbstractSpell implements Spell { @@ -97,7 +98,7 @@ public abstract class AbstractSpell implements Spell { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putBoolean("dying", dying.get()); compound.putBoolean("dead", dead.get()); compound.putBoolean("hidden", hidden.get()); @@ -106,7 +107,7 @@ public abstract class AbstractSpell implements Spell { } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { if (compound.containsUuid("uuid")) { uuid = compound.getUuid("uuid"); } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/CustomisedSpellType.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/CustomisedSpellType.java index 48aac638..a0a052ff 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/CustomisedSpellType.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/CustomisedSpellType.java @@ -17,6 +17,7 @@ import com.minelittlepony.unicopia.entity.effect.EffectUtils; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; @@ -51,10 +52,10 @@ public record CustomisedSpellType ( } @Nullable - public T create(NbtCompound compound) { + public T create(NbtCompound compound, WrapperLookup lookup) { T spell = create(); if (spell != null) { - spell.fromNBT(compound); + spell.fromNBT(compound, lookup); } return spell; } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DarkVortexSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DarkVortexSpell.java index 14eaa665..4d54aa48 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DarkVortexSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DarkVortexSpell.java @@ -40,6 +40,7 @@ import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.particle.ParticleTypes; import net.minecraft.predicate.entity.EntityPredicates; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.sound.SoundCategory; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.hit.EntityHitResult; @@ -303,14 +304,14 @@ public class DarkVortexSpell extends AbstractSpell implements ProjectileDelegate } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putFloat("accumulatedMass", accumulatedMass.get()); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); accumulatedMass.set(compound.getFloat("accumulatedMass")); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DisplacementSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DisplacementSpell.java index d9659de6..9e2713df 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DisplacementSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/DisplacementSpell.java @@ -15,6 +15,7 @@ import com.minelittlepony.unicopia.projectile.ProjectileDelegate; import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.math.Vec3d; @@ -94,7 +95,8 @@ public class DisplacementSpell extends AbstractSpell implements HomingSpell, Pro } private void teleport(Caster source, Entity entity, Vec3d pos, Vec3d vel) { - entity.teleport(pos.x, pos.y, pos.z); + // TODO: teleport -> requestTeleport + entity.requestTeleport(pos.x, pos.y, pos.z); entity.setVelocity(vel); entity.setGlowing(false); entity.playSound(USounds.SPELL_DISPLACEMENT_TELEPORT, 1, 1); @@ -124,16 +126,16 @@ public class DisplacementSpell extends AbstractSpell implements HomingSpell, Pro } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putInt("ticks", ticks); - compound.put("target", target.toNBT()); + compound.put("target", target.toNBT(lookup)); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); ticks = compound.getInt("ticks"); - target.fromNBT(compound.getCompound("target")); + target.fromNBT(compound.getCompound("target"), lookup); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FeatherFallSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FeatherFallSpell.java index 8f7ffabf..ce44b28d 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FeatherFallSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FeatherFallSpell.java @@ -19,6 +19,7 @@ import com.minelittlepony.unicopia.particle.ParticleUtils; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; @@ -124,14 +125,14 @@ public class FeatherFallSpell extends AbstractSpell implements TimedSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - timer.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + timer.toNBT(compound, lookup); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - timer.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + timer.fromNBT(compound, lookup); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FireBoltSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FireBoltSpell.java index 04cf61fd..6f4c1115 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FireBoltSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/FireBoltSpell.java @@ -18,6 +18,7 @@ import net.minecraft.entity.Entity; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.predicate.entity.EntityPredicates; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.hit.EntityHitResult; public class FireBoltSpell extends AbstractSpell implements HomingSpell, @@ -112,14 +113,14 @@ public class FireBoltSpell extends AbstractSpell implements HomingSpell, } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - compound.put("target", target.toNBT()); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + compound.put("target", target.toNBT(lookup)); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - target.fromNBT(compound.getCompound("target")); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + target.fromNBT(compound.getCompound("target"), lookup); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/HydrophobicSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/HydrophobicSpell.java index cd6a198c..1c98db3b 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/HydrophobicSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/HydrophobicSpell.java @@ -17,13 +17,17 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.particle.UParticles; import com.minelittlepony.unicopia.projectile.MagicProjectileEntity; import com.minelittlepony.unicopia.server.world.Ether; +import com.minelittlepony.unicopia.util.CodecUtils; import com.minelittlepony.unicopia.util.NbtSerialisable; import com.minelittlepony.unicopia.util.shape.*; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.*; import net.minecraft.fluid.*; import net.minecraft.nbt.*; import net.minecraft.state.property.Properties; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.registry.tag.TagKey; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; @@ -129,16 +133,16 @@ public class HydrophobicSpell extends AbstractSpell { } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - compound.put("storedFluidPositions", Entry.SERIALIZER.writeAll(storedFluidPositions)); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + compound.put("storedFluidPositions", NbtSerialisable.encode(Entry.SET_CODEC, storedFluidPositions)); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); storedFluidPositions.clear(); - storedFluidPositions.addAll(Entry.SERIALIZER.readAll(compound.getList("storedFluidPositions", NbtElement.COMPOUND_TYPE)).toList()); + NbtSerialisable.decode(Entry.SET_CODEC, compound.getList("storedFluidPositions", NbtElement.COMPOUND_TYPE)).ifPresent(storedFluidPositions::addAll); } /** * Calculates the maximum radius of the shield. aka The area of effect. @@ -152,15 +156,11 @@ public class HydrophobicSpell extends AbstractSpell { } record Entry (BlockPos pos, BlockState blockState) { - public static final Serializer SERIALIZER = Serializer.of(compound -> new Entry( - NbtSerialisable.BLOCK_POS.read(compound.getCompound("pos")), - NbtSerialisable.decode(BlockState.CODEC, compound.get("blockState")).orElse(Blocks.AIR.getDefaultState()) - ), entry -> { - NbtCompound compound = new NbtCompound(); - compound.put("pos", NbtSerialisable.BLOCK_POS.write(entry.pos)); - compound.put("blockState", NbtSerialisable.encode(BlockState.CODEC, entry.blockState)); - return compound; - }); + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + BlockPos.CODEC.fieldOf("pos").forGetter(Entry::pos), + BlockState.CODEC.optionalFieldOf("blockState", Blocks.AIR.getDefaultState()).forGetter(Entry::blockState) + ).apply(instance, Entry::new)); + public static final Codec> SET_CODEC = CodecUtils.setOf(CODEC); void restore(World world) { BlockState state = world.getBlockState(pos); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/LightSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/LightSpell.java index d1bf985f..28ad17c9 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/LightSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/LightSpell.java @@ -24,6 +24,7 @@ import com.minelittlepony.unicopia.util.VecHelper; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtList; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.MathHelper; public class LightSpell extends AbstractSpell implements TimedSpell, ProjectileDelegate.HitListener { @@ -109,26 +110,26 @@ public class LightSpell extends AbstractSpell implements TimedSpell, ProjectileD } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - timer.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + timer.toNBT(compound, lookup); if (!lights.isEmpty()) { NbtList list = new NbtList(); lights.forEach(light -> { - list.add(light.toNBT()); + list.add(light.toNBT(lookup)); }); compound.put("lights", list); } } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - timer.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + timer.fromNBT(compound, lookup); lights.clear(); if (compound.contains("lights", NbtElement.LIST_TYPE)) { compound.getList("lights", NbtElement.COMPOUND_TYPE).forEach(nbt -> { - lights.add(new EntityReference<>((NbtCompound)nbt)); + lights.add(new EntityReference<>((NbtCompound)nbt, lookup)); }); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MimicSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MimicSpell.java index 1108bd43..110bc912 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MimicSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MimicSpell.java @@ -6,6 +6,7 @@ import com.minelittlepony.unicopia.ability.magic.spell.attribute.TooltipFactory; import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public class MimicSpell extends AbstractDisguiseSpell implements HomingSpell, TimedSpell { @@ -40,14 +41,14 @@ public class MimicSpell extends AbstractDisguiseSpell implements HomingSpell, Ti } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - timer.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + timer.toNBT(compound, lookup); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - timer.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + timer.fromNBT(compound, lookup); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MindSwapSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MindSwapSpell.java index eefb6ebb..bc0dbf8f 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MindSwapSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/MindSwapSpell.java @@ -25,6 +25,7 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.world.GameMode; @@ -192,18 +193,18 @@ public class MindSwapSpell extends MimicSpell implements ProjectileDelegate.Enti } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); - compound.put("counterpart", counterpart.toNBT()); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); + compound.put("counterpart", counterpart.toNBT(lookup)); compound.putBoolean("initialized", initialized); myStoredInventory.ifPresent(mine -> compound.put("myStoredInventory", mine.toNBT(new NbtCompound()))); theirStoredInventory.ifPresent(mine -> compound.put("theirStoredInventory", mine.toNBT(new NbtCompound()))); } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); - counterpart.fromNBT(compound.getCompound("counterpart")); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); + counterpart.fromNBT(compound.getCompound("counterpart"), lookup); initialized = compound.getBoolean("initialized"); myStoredInventory = Optional.ofNullable(compound.contains("myStoredInventory", NbtElement.COMPOUND_TYPE) ? Inventory.fromNBT(compound.getCompound("myStoredInventory")) : null); theirStoredInventory = Optional.ofNullable(compound.contains("theirStoredInventory", NbtElement.COMPOUND_TYPE) ? Inventory.fromNBT(compound.getCompound("theirStoredInventory")) : null); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/NecromancySpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/NecromancySpell.java index 2ad5cce3..36e00501 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/NecromancySpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/NecromancySpell.java @@ -35,6 +35,7 @@ import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtList; import net.minecraft.particle.ParticleTypes; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.math.BlockPos; @@ -217,24 +218,24 @@ public class NecromancySpell extends AbstractAreaEffectSpell implements Projecti } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putInt("spawnCountdown", spawnCountdown); if (summonedEntities.size() > 0) { NbtList list = new NbtList(); - summonedEntities.forEach(ref -> list.add(ref.toNBT())); + summonedEntities.forEach(ref -> list.add(ref.toNBT(lookup))); compound.put("summonedEntities", list); } } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); spawnCountdown = compound.getInt("spawnCountdown"); summonedEntities.clear(); if (compound.contains("summonedEntities")) { compound.getList("summonedEntities", NbtElement.COMPOUND_TYPE).forEach(tag -> { - summonedEntities.add(new EntityReference<>((NbtCompound)tag)); + summonedEntities.add(new EntityReference<>((NbtCompound)tag, lookup)); }); } } diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/PortalSpell.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/PortalSpell.java index bb007fe5..edd37b52 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/PortalSpell.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/effect/PortalSpell.java @@ -26,6 +26,7 @@ import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.PositionFlag; import net.minecraft.particle.ParticleTypes; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Util; @@ -226,10 +227,10 @@ public class PortalSpell extends AbstractSpell implements PlacementControlSpell. } @Override - public void toNBT(NbtCompound compound) { - super.toNBT(compound); + public void toNBT(NbtCompound compound, WrapperLookup lookup) { + super.toNBT(compound, lookup); compound.putUuid("targetPortalId", targetPortalId.get()); - compound.put("teleportationTarget", teleportationTarget.toNBT()); + compound.put("teleportationTarget", teleportationTarget.toNBT(lookup)); compound.putFloat("pitch", getPitch()); compound.putFloat("yaw", getYaw()); compound.putFloat("targetPortalPitch", getTargetPitch()); @@ -237,10 +238,10 @@ public class PortalSpell extends AbstractSpell implements PlacementControlSpell. } @Override - public void fromNBT(NbtCompound compound) { - super.fromNBT(compound); + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { + super.fromNBT(compound, lookup); targetPortalId.set(compound.containsUuid("targetPortalId") ? compound.getUuid("targetPortalId") : Util.NIL_UUID); - teleportationTarget.fromNBT(compound.getCompound("teleportationTarget")); + teleportationTarget.fromNBT(compound.getCompound("teleportationTarget"), lookup); pitch.set(compound.getFloat("pitch")); yaw.set(compound.getFloat("yaw")); targetPortalPitch.set(compound.getFloat("targetPortalPitch")); diff --git a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/trait/SpellTraits.java b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/trait/SpellTraits.java index 48cd1872..616c8341 100644 --- a/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/trait/SpellTraits.java +++ b/src/main/java/com/minelittlepony/unicopia/ability/magic/spell/trait/SpellTraits.java @@ -35,6 +35,8 @@ import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtOps; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.math.MathHelper; @@ -51,6 +53,7 @@ public final class SpellTraits implements Iterable> { map -> DataResult.success(fromEntries(map.entrySet().stream()).orElse(EMPTY)), traits -> DataResult.success(traits.traits) ); + public static final PacketCodec PACKET_CODEC = PacketCodec.ofStatic((a, b) -> b.write(a), SpellTraits::fromPacket); public static void load(Map newRegistry) { REGISTRY = newRegistry; @@ -169,6 +172,7 @@ public final class SpellTraits implements Iterable> { return nbt; } + @Deprecated public void write(PacketByteBuf buf) { buf.writeInt(traits.size()); traits.forEach((trait, value) -> { @@ -264,10 +268,12 @@ public final class SpellTraits implements Iterable> { return CODEC.decode(NbtOps.INSTANCE, traits).result().map(Pair::getFirst); } + @Deprecated public static Optional fromPacketOrEmpty(PacketByteBuf buf) { return buf.readOptional(SpellTraits::fromPacket).filter(SpellTraits::isPresent); } + @Deprecated public static SpellTraits fromPacket(PacketByteBuf buf) { Map entries = new HashMap<>(); int count = buf.readInt(); diff --git a/src/main/java/com/minelittlepony/unicopia/advancement/CustomEventCriterion.java b/src/main/java/com/minelittlepony/unicopia/advancement/CustomEventCriterion.java index 91ff5931..f32109cb 100644 --- a/src/main/java/com/minelittlepony/unicopia/advancement/CustomEventCriterion.java +++ b/src/main/java/com/minelittlepony/unicopia/advancement/CustomEventCriterion.java @@ -16,7 +16,6 @@ import net.minecraft.entity.Entity; import net.minecraft.predicate.entity.EntityPredicate; import net.minecraft.predicate.entity.LootContextPredicate; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.dynamic.Codecs; public class CustomEventCriterion extends AbstractCriterion { @Override @@ -61,7 +60,7 @@ public class CustomEventCriterion extends AbstractCriterion CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codecs.createStrictOptionalFieldCodec(EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC, "player").forGetter(Conditions::player), + EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC.optionalFieldOf("player").forGetter(Conditions::player), Codec.STRING.fieldOf("event").forGetter(Conditions::event), RacePredicate.CODEC.optionalFieldOf("races", RacePredicate.EMPTY).forGetter(Conditions::races), CodecUtils.tristateOf("flying").forGetter(Conditions::flying), diff --git a/src/main/java/com/minelittlepony/unicopia/advancement/RaceChangeCriterion.java b/src/main/java/com/minelittlepony/unicopia/advancement/RaceChangeCriterion.java index fe59d1b3..967bbb58 100644 --- a/src/main/java/com/minelittlepony/unicopia/advancement/RaceChangeCriterion.java +++ b/src/main/java/com/minelittlepony/unicopia/advancement/RaceChangeCriterion.java @@ -12,7 +12,6 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.predicate.entity.EntityPredicate; import net.minecraft.predicate.entity.LootContextPredicate; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.dynamic.Codecs; public class RaceChangeCriterion extends AbstractCriterion { @Override @@ -31,7 +30,7 @@ public class RaceChangeCriterion extends AbstractCriterion CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codecs.createStrictOptionalFieldCodec(EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC, "player").forGetter(Conditions::player), + EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC.optionalFieldOf("player").forGetter(Conditions::player), Race.REGISTRY.getCodec().fieldOf("race").forGetter(Conditions::race) ).apply(instance, Conditions::new)); diff --git a/src/main/java/com/minelittlepony/unicopia/advancement/SendViaDragonBreathScrollCriterion.java b/src/main/java/com/minelittlepony/unicopia/advancement/SendViaDragonBreathScrollCriterion.java index ce7c0cdd..43a10e4f 100644 --- a/src/main/java/com/minelittlepony/unicopia/advancement/SendViaDragonBreathScrollCriterion.java +++ b/src/main/java/com/minelittlepony/unicopia/advancement/SendViaDragonBreathScrollCriterion.java @@ -19,7 +19,6 @@ import net.minecraft.predicate.item.ItemPredicate; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.TypeFilter; -import net.minecraft.util.dynamic.Codecs; public class SendViaDragonBreathScrollCriterion extends AbstractCriterion { @Override @@ -57,7 +56,7 @@ public class SendViaDragonBreathScrollCriterion extends AbstractCriterion CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codecs.createStrictOptionalFieldCodec(EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC, "player").forGetter(Conditions::player), + EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC.optionalFieldOf("player").forGetter(Conditions::player), ItemPredicate.CODEC.optionalFieldOf("item").forGetter(Conditions::item), Codec.BOOL.optionalFieldOf("is_receiving_end", false).forGetter(Conditions::isReceivingEnd), Codec.STRING.optionalFieldOf("recipient_name").forGetter(Conditions::recipientName), diff --git a/src/main/java/com/minelittlepony/unicopia/advancement/TraitDiscoveredCriterion.java b/src/main/java/com/minelittlepony/unicopia/advancement/TraitDiscoveredCriterion.java index 70e30105..2c060daa 100644 --- a/src/main/java/com/minelittlepony/unicopia/advancement/TraitDiscoveredCriterion.java +++ b/src/main/java/com/minelittlepony/unicopia/advancement/TraitDiscoveredCriterion.java @@ -14,7 +14,6 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.predicate.entity.EntityPredicate; import net.minecraft.predicate.entity.LootContextPredicate; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.dynamic.Codecs; public class TraitDiscoveredCriterion extends AbstractCriterion { @Override @@ -34,7 +33,7 @@ public class TraitDiscoveredCriterion extends AbstractCriterion player, Set traits) implements AbstractCriterion.Conditions { public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codecs.createStrictOptionalFieldCodec(EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC, "player").forGetter(Conditions::player), + EntityPredicate.LOOT_CONTEXT_PREDICATE_CODEC.optionalFieldOf("player").forGetter(Conditions::player), Trait.SET_CODEC.fieldOf("traits").forGetter(Conditions::traits) ).apply(instance, Conditions::new)); diff --git a/src/main/java/com/minelittlepony/unicopia/block/BlockConstructionUtils.java b/src/main/java/com/minelittlepony/unicopia/block/BlockConstructionUtils.java index 5fa144f2..21196b3a 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/BlockConstructionUtils.java +++ b/src/main/java/com/minelittlepony/unicopia/block/BlockConstructionUtils.java @@ -7,7 +7,7 @@ import net.minecraft.block.ButtonBlock; import net.minecraft.block.LeavesBlock; import net.minecraft.block.MapColor; import net.minecraft.block.PillarBlock; -import net.minecraft.block.enums.Instrument; +import net.minecraft.block.enums.NoteBlockInstrument; import net.minecraft.block.piston.PistonBehavior; import net.minecraft.entity.EntityType; import net.minecraft.sound.BlockSoundGroup; @@ -29,11 +29,11 @@ public interface BlockConstructionUtils { } static PillarBlock createLogBlock(MapColor topMapColor, MapColor sideMapColor) { - return new PillarBlock(AbstractBlock.Settings.create().mapColor(state -> state.get(PillarBlock.AXIS) == Direction.Axis.Y ? topMapColor : sideMapColor).instrument(Instrument.BASS).strength(2.0f).sounds(BlockSoundGroup.WOOD).burnable()); + return new PillarBlock(AbstractBlock.Settings.create().mapColor(state -> state.get(PillarBlock.AXIS) == Direction.Axis.Y ? topMapColor : sideMapColor).instrument(NoteBlockInstrument.BASS).strength(2.0f).sounds(BlockSoundGroup.WOOD).burnable()); } static PillarBlock createWoodBlock(MapColor mapColor) { - return new PillarBlock(AbstractBlock.Settings.create().mapColor(mapColor).instrument(Instrument.BASS).strength(2.0f).sounds(BlockSoundGroup.WOOD).burnable()); + return new PillarBlock(AbstractBlock.Settings.create().mapColor(mapColor).instrument(NoteBlockInstrument.BASS).strength(2.0f).sounds(BlockSoundGroup.WOOD).burnable()); } static LeavesBlock createLeavesBlock(BlockSoundGroup soundGroup) { diff --git a/src/main/java/com/minelittlepony/unicopia/block/CrystalDoorBlock.java b/src/main/java/com/minelittlepony/unicopia/block/CrystalDoorBlock.java index 26cc79d7..383e73a4 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/CrystalDoorBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/CrystalDoorBlock.java @@ -24,13 +24,14 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.Properties; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; @@ -98,33 +99,32 @@ public class CrystalDoorBlock extends DoorBlock implements BlockEntityProvider { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + protected ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (!shouldProvideAccess(world, pos, player)) { - if (isLocked(world, pos) || !player.getStackInHand(hand).isOf(UItems.MEADOWBROOKS_STAFF)) { + if (isLocked(world, pos) || !stack.isOf(UItems.MEADOWBROOKS_STAFF)) { playOpenCloseSound(player, world, pos, false); setOnGuard(state, world, pos, true); - return ActionResult.CONSUME; + return ItemActionResult.CONSUME; } else { world.playSound(player, pos, USounds.ENTITY_CRYSTAL_SHARDS_AMBIENT, SoundCategory.BLOCKS, 1, world.getRandom().nextFloat() * 0.1F + 0.9F); } } else if (!isLocked(world, pos)) { - ItemStack heldStack = player.getStackInHand(hand); - if (heldStack.isOf(UItems.FRIENDSHIP_BRACELET)) { + if (stack.isOf(UItems.FRIENDSHIP_BRACELET)) { @Nullable - UUID signator = FriendshipBraceletItem.getSignatorId(heldStack); + UUID signator = FriendshipBraceletItem.getSignatorId(stack); if (signator != null) { BlockEntityUtil.getOrCreateBlockEntity(world, state.get(HALF) == DoubleBlockHalf.LOWER ? pos.up() : pos, UBlockEntities.CRYSTAL_DOOR).ifPresent(data -> { data.setSignator(signator); setOnGuard(state, world, pos, true); world.playSound(player, pos, USounds.ENTITY_CRYSTAL_SHARDS_AMBIENT, SoundCategory.BLOCKS, 1, world.getRandom().nextFloat() * 0.1F + 0.9F); }); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } } else { setOnGuard(state, world, pos, false); } } - return super.onUse(state, world, pos, player, hand, hit); + return super.onUseWithItem(stack, state, world, pos, player, hand, hit); } private void setOnGuard(BlockState state, World world, BlockPos pos, boolean locked) { @@ -178,12 +178,12 @@ public class CrystalDoorBlock extends DoorBlock implements BlockEntityProvider { } @Override - public void readNbt(NbtCompound nbt) { + public void readNbt(NbtCompound nbt, WrapperLookup lookup) { signator = nbt.containsUuid("signator") ? nbt.getUuid("signator") : null; } @Override - protected void writeNbt(NbtCompound nbt) { + protected void writeNbt(NbtCompound nbt, WrapperLookup lookup) { if (signator != null) { nbt.putUuid("signator", signator); } diff --git a/src/main/java/com/minelittlepony/unicopia/block/CuringJokeBlock.java b/src/main/java/com/minelittlepony/unicopia/block/CuringJokeBlock.java index d5d0dced..df25ef40 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/CuringJokeBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/CuringJokeBlock.java @@ -1,7 +1,5 @@ package com.minelittlepony.unicopia.block; -import java.util.List; - import com.minelittlepony.unicopia.ability.EarthPonyGrowAbility.Growable; import com.minelittlepony.unicopia.entity.mob.IgnominiousBulbEntity; import com.minelittlepony.unicopia.particle.MagicParticleEffect; @@ -10,8 +8,9 @@ import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.BlockState; import net.minecraft.block.FlowerBlock; -import net.minecraft.block.SuspiciousStewIngredient; -import net.minecraft.client.util.ParticleUtil; +import net.minecraft.component.type.SuspiciousStewEffectsComponent; +import net.minecraft.particle.ParticleUtil; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.entity.Dismounting; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.util.math.BlockPos; @@ -24,11 +23,11 @@ public class CuringJokeBlock extends FlowerBlock implements Growable { FlowerBlock.createSettingsCodec() ).apply(instance, CuringJokeBlock::new)); - public CuringJokeBlock(StatusEffect suspiciousStewEffect, int effectDuration, Settings settings) { + public CuringJokeBlock(RegistryEntry suspiciousStewEffect, int effectDuration, Settings settings) { super(suspiciousStewEffect, effectDuration, settings); } - protected CuringJokeBlock(List effects, Settings settings) { + protected CuringJokeBlock(SuspiciousStewEffectsComponent effects, Settings settings) { super(effects, settings); } diff --git a/src/main/java/com/minelittlepony/unicopia/block/EdibleBlock.java b/src/main/java/com/minelittlepony/unicopia/block/EdibleBlock.java index 707853b1..a6f02b56 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/EdibleBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/EdibleBlock.java @@ -17,6 +17,7 @@ import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.HayBlock; import net.minecraft.block.ShapeContext; +import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; @@ -27,6 +28,7 @@ import net.minecraft.state.property.BooleanProperty; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.Identifier; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.Util; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; @@ -94,10 +96,18 @@ public class EdibleBlock extends HayBlock { for (EdibleBlock edibleBlock : REGISTRY) { Block match = edibleBlock.getBaseBlock(); if (match != Blocks.AIR && state.isOf(match)) { - ActionResult result = StateUtil.copyState(state, edibleBlock.getDefaultState()).onUse(world, player, hand, hitResult); + BlockState copiedState = StateUtil.copyState(state, edibleBlock.getDefaultState()); + ItemActionResult result = copiedState.onUseWithItem(player.getStackInHand(hand), world, player, hand, hitResult); if (result.isAccepted()) { - return result; + return result.toActionResult(); + } + + if (result == ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION && hand == Hand.MAIN_HAND) { + ActionResult actionResult = copiedState.onUse(world, player, hitResult); + if (actionResult.isAccepted()) { + return actionResult; + } } } } @@ -144,13 +154,11 @@ public class EdibleBlock extends HayBlock { @Override @Deprecated - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + protected ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (player.isSpectator()) { - return ActionResult.FAIL; + return ItemActionResult.FAIL; } - ItemStack stack = player.getStackInHand(hand); - if (!stack.isEmpty() && stack.isOf(Registries.ITEM.get(material))) { BooleanProperty segment = getHitCorner(hit, 1); @@ -167,23 +175,23 @@ public class EdibleBlock extends HayBlock { } world.playSound(player, pos, getSoundGroup(state).getPlaceSound(), SoundCategory.BLOCKS); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } - return ActionResult.FAIL; + return ItemActionResult.FAIL; } BooleanProperty corner = getHitCorner(hit, -1); if (!state.get(corner)) { - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } boolean usingHoe = stack.isIn(ItemTags.HOES); if (!usingHoe) { if (!(player.isCreative() || player.getHungerManager().isNotFull()) || !player.isSneaking()) { - return ActionResult.FAIL; + return ItemActionResult.FAIL; } } @@ -197,7 +205,7 @@ public class EdibleBlock extends HayBlock { } if (usingHoe) { - stack.damage(1, player, p -> p.sendToolBreakStatus(hand)); + stack.damage(1, player, LivingEntity.getSlotForHand(hand)); dropStack(world, pos, Registries.ITEM.get(material).getDefaultStack()); player.playSound(USounds.Vanilla.ITEM_HOE_TILL, 1, 1); } else { @@ -207,7 +215,7 @@ public class EdibleBlock extends HayBlock { } player.getHungerManager().add(2, 1.3F); } - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } static BooleanProperty getHitCorner(BlockHitResult hit, int direction) { diff --git a/src/main/java/com/minelittlepony/unicopia/block/FancyBedBlock.java b/src/main/java/com/minelittlepony/unicopia/block/FancyBedBlock.java index 8869cf1a..3084f960 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/FancyBedBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/FancyBedBlock.java @@ -24,6 +24,7 @@ import net.minecraft.entity.mob.PiglinBrain; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.registry.tag.BlockTags; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.DyeColor; @@ -150,18 +151,18 @@ public class FancyBedBlock extends BedBlock { } @Override - public void readNbt(NbtCompound nbt) { + public void readNbt(NbtCompound nbt, WrapperLookup lookup) { pattern = SheetPattern.byId(nbt.getString("pattern")); } @Override - protected void writeNbt(NbtCompound nbt) { + protected void writeNbt(NbtCompound nbt, WrapperLookup lookup) { nbt.putString("pattern", pattern.asString()); } @Override - public NbtCompound toInitialChunkDataNbt() { - return createNbt(); + public NbtCompound toInitialChunkDataNbt(WrapperLookup lookup) { + return createNbt(lookup); } public String getBase() { diff --git a/src/main/java/com/minelittlepony/unicopia/block/HiveBlock.java b/src/main/java/com/minelittlepony/unicopia/block/HiveBlock.java index 21f89efd..844aea45 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/HiveBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/HiveBlock.java @@ -34,13 +34,14 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.particle.ParticleTypes; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.Property; import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; @@ -142,7 +143,7 @@ public class HiveBlock extends ConnectingBlock implements BlockEntityProvider { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) { if (EquineContext.of(player).getCompositeRace().includes(Race.CHANGELING)) { world.setBlockState(pos, state.with(CONSUMING, true)); if (!world.isClient) { @@ -214,22 +215,22 @@ public class HiveBlock extends ConnectingBlock implements BlockEntityProvider { } @Override - public void readNbt(NbtCompound nbt) { + public void readNbt(NbtCompound nbt, WrapperLookup lookup) { opening = nbt.getBoolean("opening"); closing = nbt.getBoolean("closing"); storedBlocks.clear(); if (nbt.contains("storedBlocks", NbtElement.LIST_TYPE)) { - Entry.SERIALIZER.readAll(nbt.getList("storedBlocks", NbtElement.COMPOUND_TYPE)).forEach(entry -> { + Entry.SERIALIZER.readAll(nbt.getList("storedBlocks", NbtElement.COMPOUND_TYPE), lookup).forEach(entry -> { storedBlocks.put(entry.pos(), entry); }); } } @Override - protected void writeNbt(NbtCompound nbt) { + protected void writeNbt(NbtCompound nbt, WrapperLookup lookup) { nbt.putBoolean("opening", opening); nbt.putBoolean("closing", closing); - nbt.put("storedBlocks", Entry.SERIALIZER.writeAll(storedBlocks.values())); + nbt.put("storedBlocks", Entry.SERIALIZER.writeAll(storedBlocks.values(), lookup)); } static void tick(World world, BlockPos pos, BlockState state, TileData data) { @@ -312,22 +313,23 @@ public class HiveBlock extends ConnectingBlock implements BlockEntityProvider { } record Entry (BlockPos pos, BlockState state, @Nullable BlockEntity data) { - public static final Serializer SERIALIZER = Serializer.of(compound -> new Entry( - NbtSerialisable.BLOCK_POS.read(compound.getCompound("pos")), + public static final Serializer SERIALIZER = Serializer.of((compound, lookup) -> new Entry( + NbtSerialisable.BLOCK_POS.read(compound.getCompound("pos"), lookup), NbtSerialisable.decode(BlockState.CODEC, compound.get("state")).orElse(Blocks.AIR.getDefaultState()), - compound.getCompound("data") - ), entry -> { + compound.getCompound("data"), + lookup + ), (entry, lookup) -> { NbtCompound compound = new NbtCompound(); - compound.put("pos", NbtSerialisable.BLOCK_POS.write(entry.pos())); + compound.put("pos", NbtSerialisable.BLOCK_POS.write(entry.pos(), lookup)); compound.put("state", NbtSerialisable.encode(BlockState.CODEC, entry.state())); if (entry.data() != null) { - compound.put("data", entry.data().createNbtWithId()); + compound.put("data", entry.data().createNbtWithId(lookup)); } return compound; }); - Entry(BlockPos pos, BlockState state, NbtCompound nbt) { - this(pos, state, BlockEntity.createFromNbt(pos, state, nbt)); + Entry(BlockPos pos, BlockState state, NbtCompound nbt, WrapperLookup lookup) { + this(pos, state, BlockEntity.createFromNbt(pos, state, nbt, lookup)); } @SuppressWarnings("deprecation") @@ -365,7 +367,7 @@ public class HiveBlock extends ConnectingBlock implements BlockEntityProvider { } @Override - public boolean listen(ServerWorld world, GameEvent event, Emitter emitter, Vec3d emitterPos) { + public boolean listen(ServerWorld world, RegistryEntry event, Emitter emitter, Vec3d emitterPos) { if (isImportant(event) || (EquinePredicates.IS_PLAYER.test(emitter.sourceEntity()) && !EquinePredicates.CHANGELING.test(emitter.sourceEntity()))) { closing = true; markDirty(); @@ -374,7 +376,7 @@ public class HiveBlock extends ConnectingBlock implements BlockEntityProvider { return false; } - private boolean isImportant(GameEvent event) { + private boolean isImportant(RegistryEntry event) { return event == GameEvent.EXPLODE || event == GameEvent.PRIME_FUSE || event == GameEvent.SHRIEK; diff --git a/src/main/java/com/minelittlepony/unicopia/block/ItemJarBlock.java b/src/main/java/com/minelittlepony/unicopia/block/ItemJarBlock.java index d5c9c7c3..af9629a3 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/ItemJarBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/ItemJarBlock.java @@ -25,9 +25,11 @@ import net.minecraft.nbt.NbtElement; import net.minecraft.network.listener.ClientPlayPacketListener; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.TypedActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; @@ -52,11 +54,11 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (hand == Hand.OFF_HAND) { - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } - return world.getBlockEntity(pos, UBlockEntities.ITEM_JAR).map(data -> data.interact(player, hand)).orElse(ActionResult.PASS); + return world.getBlockEntity(pos, UBlockEntities.ITEM_JAR).map(data -> data.interact(player, hand)).orElse(ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION); } @Deprecated @@ -110,10 +112,10 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven super(UBlockEntities.ITEM_JAR, pos, state); } - public ActionResult interact(PlayerEntity player, Hand hand) { + public ItemActionResult interact(PlayerEntity player, Hand hand) { TypedActionResult result = contents.interact(player, hand); contents = result.getValue(); - return result.getResult(); + return result.getResult().isAccepted() ? ItemActionResult.SUCCESS : result.getResult() == ActionResult.FAIL ? ItemActionResult.FAIL : ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } public JarContents getContents() { @@ -146,8 +148,8 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven } @Override - public NbtCompound toInitialChunkDataNbt() { - return createNbt(); + public NbtCompound toInitialChunkDataNbt(WrapperLookup lookup) { + return createNbt(lookup); } @Override @@ -159,9 +161,9 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven } @Override - public void readNbt(NbtCompound nbt) { + public void readNbt(NbtCompound nbt, WrapperLookup lookup) { if (nbt.contains("items", NbtElement.COMPOUND_TYPE)) { - contents = new ItemsJarContents(this, nbt.getCompound("items")); + contents = new ItemsJarContents(this, nbt.getCompound("items"), lookup); } else if (nbt.contains("entity", NbtElement.COMPOUND_TYPE)) { contents = new EntityJarContents(this, nbt.getCompound("entity")); } else if (nbt.contains("fluid", NbtElement.COMPOUND_TYPE)) { @@ -172,14 +174,14 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven } @Override - protected void writeNbt(NbtCompound nbt) { + protected void writeNbt(NbtCompound nbt, WrapperLookup lookup) { var items = getItems(); if (items != null) { - nbt.put("items", items.toNBT(new NbtCompound())); + nbt.put("items", items.toNBT(new NbtCompound(), lookup)); } else if (getEntity() != null) { - nbt.put("entity", getEntity().toNBT(new NbtCompound())); + nbt.put("entity", getEntity().toNBT(new NbtCompound(), lookup)); } else if (getFluid() != null) { - nbt.put("fluid", getFluid().toNBT(new NbtCompound())); + nbt.put("fluid", getFluid().toNBT(new NbtCompound(), lookup)); } else if (getFakeFluid() != null) { nbt.put("fakeFluid", getFakeFluid().toNBT(new NbtCompound())); } @@ -191,7 +193,7 @@ public class ItemJarBlock extends JarBlock implements BlockEntityProvider, Inven void onDestroyed(); - NbtCompound toNBT(NbtCompound compound); + NbtCompound toNBT(NbtCompound compound, WrapperLookup lookup); default void consumeAndSwap(PlayerEntity player, Hand hand, ItemStack output) { player.setStackInHand(hand, ItemUsage.exchangeStack(player.getStackInHand(hand), player, output.copy())); diff --git a/src/main/java/com/minelittlepony/unicopia/block/PieBlock.java b/src/main/java/com/minelittlepony/unicopia/block/PieBlock.java index 8f53a961..69b5bee4 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/PieBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/PieBlock.java @@ -20,8 +20,8 @@ import net.minecraft.sound.SoundCategory; import net.minecraft.stat.Stats; import net.minecraft.state.StateManager; import net.minecraft.state.property.*; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.*; import net.minecraft.util.math.random.Random; @@ -80,39 +80,38 @@ public class PieBlock extends Block implements Waterloggable { @Deprecated @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { - ItemStack itemStack = player.getStackInHand(hand); + public ItemActionResult onUseWithItem(ItemStack itemStack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (world.isClient) { if (itemStack.isIn(UTags.Items.CAN_CUT_PIE)) { - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } if (tryEat(world, pos, state, player).isAccepted()) { - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } if (itemStack.isEmpty()) { - return ActionResult.CONSUME; + return ItemActionResult.CONSUME; } } if (itemStack.isIn(UTags.Items.CAN_CUT_PIE)) { SoundEmitter.playSoundAt(player, USounds.BLOCK_PIE_SLICE, SoundCategory.NEUTRAL, 1, 1); removeSlice(world, pos, state, player); - itemStack.damage(1, player, p -> p.sendToolBreakStatus(hand)); + itemStack.damage(1, player, LivingEntity.getSlotForHand(hand)); SoundEmitter.playSoundAt(player, USounds.BLOCK_PIE_SLICE_POP, SoundCategory.NEUTRAL, 0.5F, world.getRandom().nextFloat() * 0.1F + 0.9F); Block.dropStack(world, pos, sliceItem.asItem().getDefaultStack()); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } return tryEat(world, pos, state, player); } - protected ActionResult tryEat(WorldAccess world, BlockPos pos, BlockState state, PlayerEntity player) { + protected ItemActionResult tryEat(WorldAccess world, BlockPos pos, BlockState state, PlayerEntity player) { if (!player.canConsume(false)) { - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } player.incrementStat(Stats.EAT_CAKE_SLICE); player.getHungerManager().add(state.get(STOMPED) ? 1 : 2, 0.1f); @@ -126,7 +125,7 @@ public class PieBlock extends Block implements Waterloggable { } removeSlice(world, pos, state, player); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } protected void removeSlice(WorldAccess world, BlockPos pos, BlockState state, PlayerEntity player) { @@ -232,7 +231,7 @@ public class PieBlock extends Block implements Waterloggable { } @Override - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { + public boolean canPathfindThrough(BlockState state, NavigationType type) { return false; } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/SpikesBlock.java b/src/main/java/com/minelittlepony/unicopia/block/SpikesBlock.java index 5ba3ec3a..af004548 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/SpikesBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/SpikesBlock.java @@ -17,7 +17,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; -import net.minecraft.world.BlockView; import net.minecraft.world.World; import net.minecraft.world.WorldAccess; import net.minecraft.world.WorldView; @@ -95,7 +94,7 @@ public class SpikesBlock extends OrientedBlock { } @Override - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { + public boolean canPathfindThrough(BlockState state, NavigationType type) { return false; } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/UBlocks.java b/src/main/java/com/minelittlepony/unicopia/block/UBlocks.java index 62473abf..4ae7df9d 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/UBlocks.java +++ b/src/main/java/com/minelittlepony/unicopia/block/UBlocks.java @@ -35,7 +35,6 @@ import com.minelittlepony.unicopia.item.UItems; import com.minelittlepony.unicopia.item.cloud.CloudBlockItem; import com.minelittlepony.unicopia.item.group.ItemGroupRegistry; import com.minelittlepony.unicopia.server.world.UTreeGen; -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.registry.CompostingChanceRegistry; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.fabricmc.fabric.api.registry.OxidizableBlocksRegistry; @@ -44,7 +43,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.block.*; import net.minecraft.block.AbstractBlock.Settings; import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.block.enums.Instrument; +import net.minecraft.block.enums.NoteBlockInstrument; import net.minecraft.block.piston.PistonBehavior; import net.minecraft.item.*; import net.minecraft.sound.BlockSoundGroup; @@ -69,7 +68,7 @@ public interface UBlocks { .strength(2) .sounds(BlockSoundGroup.STONE))); - Block FROSTED_OBSIDIAN = register("frosted_obsidian", new FrostedObsidianBlock(FabricBlockSettings.copy(Blocks.OBSIDIAN).ticksRandomly())); + Block FROSTED_OBSIDIAN = register("frosted_obsidian", new FrostedObsidianBlock(Block.Settings.copy(Blocks.OBSIDIAN).ticksRandomly())); Block ZAP_LOG = register("zap_log", new ZapAppleLogBlock(Blocks.OAK_LOG.getDefaultState(), ZapAppleLogBlock.settings(MapColor.GRAY, MapColor.DEEPSLATE_GRAY)), ItemGroups.BUILDING_BLOCKS); Block ZAP_WOOD = register("zap_wood", new ZapAppleLogBlock(Blocks.OAK_WOOD.getDefaultState(), ZapAppleLogBlock.settings(MapColor.DEEPSLATE_GRAY, MapColor.DEEPSLATE_GRAY)), ItemGroups.BUILDING_BLOCKS); @@ -110,14 +109,14 @@ public interface UBlocks { Block PALM_SLAB = register("palm_slab", new SlabBlock(Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).strength(2, 3).sounds(BlockSoundGroup.WOOD).pistonBehavior(PistonBehavior.NORMAL)), ItemGroups.BUILDING_BLOCKS); Block PALM_FENCE = register("palm_fence", new FenceBlock(Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).strength(2, 3).sounds(BlockSoundGroup.WOOD).pistonBehavior(PistonBehavior.NORMAL)), ItemGroups.BUILDING_BLOCKS); Block PALM_FENCE_GATE = register("palm_fence_gate", new FenceGateBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).strength(2, 3).sounds(BlockSoundGroup.WOOD).pistonBehavior(PistonBehavior.NORMAL)), ItemGroups.BUILDING_BLOCKS); - Block PALM_DOOR = register("palm_door", new DoorBlock(UWoodTypes.PALM.setType(), Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).instrument(Instrument.BASS).strength(3.0f).nonOpaque().burnable().pistonBehavior(PistonBehavior.DESTROY)), ItemGroups.FUNCTIONAL); - Block PALM_TRAPDOOR = register("palm_trapdoor", new TrapdoorBlock(UWoodTypes.PALM.setType(), Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).instrument(Instrument.BASS).strength(3).nonOpaque().allowsSpawning(BlockConstructionUtils::never).burnable()), ItemGroups.FUNCTIONAL); + Block PALM_DOOR = register("palm_door", new DoorBlock(UWoodTypes.PALM.setType(), Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).instrument(NoteBlockInstrument.BASS).strength(3.0f).nonOpaque().burnable().pistonBehavior(PistonBehavior.DESTROY)), ItemGroups.FUNCTIONAL); + Block PALM_TRAPDOOR = register("palm_trapdoor", new TrapdoorBlock(UWoodTypes.PALM.setType(), Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).instrument(NoteBlockInstrument.BASS).strength(3).nonOpaque().allowsSpawning(BlockConstructionUtils::never).burnable()), ItemGroups.FUNCTIONAL); Block PALM_PRESSURE_PLATE = register("palm_pressure_plate", new PressurePlateBlock(UWoodTypes.PALM.setType(), Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).noCollision().strength(0.5f).sounds(BlockSoundGroup.WOOD).pistonBehavior(PistonBehavior.DESTROY)), ItemGroups.BUILDING_BLOCKS); Block PALM_BUTTON = register("palm_button", BlockConstructionUtils.woodenButton(UWoodTypes.PALM.setType()), ItemGroups.BUILDING_BLOCKS); - Block PALM_SIGN = register("palm_sign", new SignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).solid().instrument(Instrument.BASS).noCollision().strength(1).burnable().sounds(BlockSoundGroup.WOOD))); - Block PALM_WALL_SIGN = register("palm_wall_sign", new WallSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).solid().instrument(Instrument.BASS).noCollision().strength(1).dropsLike(PALM_SIGN).burnable())); - Block PALM_HANGING_SIGN = register("palm_hanging_sign", new HangingSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_LOG.getDefaultMapColor()).solid().instrument(Instrument.BASS).noCollision().strength(1).burnable())); - Block PALM_WALL_HANGING_SIGN = register("palm_wall_hanging_sign", new WallHangingSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_LOG.getDefaultMapColor()).solid().instrument(Instrument.BASS).noCollision().strength(1.0f).burnable().dropsLike(PALM_HANGING_SIGN))); + Block PALM_SIGN = register("palm_sign", new SignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).solid().instrument(NoteBlockInstrument.BASS).noCollision().strength(1).burnable().sounds(BlockSoundGroup.WOOD))); + Block PALM_WALL_SIGN = register("palm_wall_sign", new WallSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_PLANKS.getDefaultMapColor()).solid().instrument(NoteBlockInstrument.BASS).noCollision().strength(1).dropsLike(PALM_SIGN).burnable())); + Block PALM_HANGING_SIGN = register("palm_hanging_sign", new HangingSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_LOG.getDefaultMapColor()).solid().instrument(NoteBlockInstrument.BASS).noCollision().strength(1).burnable())); + Block PALM_WALL_HANGING_SIGN = register("palm_wall_hanging_sign", new WallHangingSignBlock(UWoodTypes.PALM, Settings.create().mapColor(PALM_LOG.getDefaultMapColor()).solid().instrument(NoteBlockInstrument.BASS).noCollision().strength(1.0f).burnable().dropsLike(PALM_HANGING_SIGN))); Block PALM_LEAVES = register("palm_leaves", BlockConstructionUtils.createLeavesBlock(BlockSoundGroup.GRASS), ItemGroups.BUILDING_BLOCKS); Block BANANAS = register("bananas", new FruitBlock(Direction.DOWN, PALM_LEAVES, VoxelShapes.fullCube(), Settings.create().mapColor(MapColor.YELLOW).sounds(BlockSoundGroup.WOOD).noCollision().ticksRandomly().breakInstantly().pistonBehavior(PistonBehavior.DESTROY))); @@ -128,7 +127,7 @@ public interface UBlocks { 0xCCFFAA00, () -> UBlocks.MANGO, () -> UItems.MANGO.getDefaultStack(), - FabricBlockSettings.copy(Blocks.JUNGLE_LEAVES) + Block.Settings.copy(Blocks.JUNGLE_LEAVES) ), ItemGroups.NATURAL); Block MANGO = register("mango", new FruitBlock(Direction.DOWN, MANGO_LEAVES, FruitBlock.DEFAULT_SHAPE, Settings.create().mapColor(MapColor.ORANGE))); @@ -138,7 +137,7 @@ public interface UBlocks { 0xE5FFFF88, () -> UBlocks.GREEN_APPLE, () -> UItems.GREEN_APPLE.getDefaultStack(), - FabricBlockSettings.copy(Blocks.OAK_LEAVES) + Block.Settings.copy(Blocks.OAK_LEAVES) ), ItemGroups.NATURAL); Block GREEN_APPLE = register("green_apple", new FruitBlock(Direction.DOWN, GREEN_APPLE_LEAVES, FruitBlock.DEFAULT_SHAPE, Settings.create().mapColor(MapColor.GREEN))); Block GREEN_APPLE_SPROUT = register("green_apple_sprout", new SproutBlock(0xE5FFFF88, () -> UItems.GREEN_APPLE_SEEDS, () -> UTreeGen.GREEN_APPLE_TREE.sapling().map(Block::getDefaultState).get(), SproutBlock.settings())); @@ -147,7 +146,7 @@ public interface UBlocks { 0xE5FFCC88, () -> UBlocks.SWEET_APPLE, () -> UItems.SWEET_APPLE.getDefaultStack(), - FabricBlockSettings.copy(Blocks.OAK_LEAVES) + Block.Settings.copy(Blocks.OAK_LEAVES) ), ItemGroups.NATURAL); Block SWEET_APPLE = register("sweet_apple", new FruitBlock(Direction.DOWN, SWEET_APPLE_LEAVES, FruitBlock.DEFAULT_SHAPE, Settings.create().mapColor(MapColor.GREEN))); Block SWEET_APPLE_SPROUT = register("sweet_apple_sprout", new SproutBlock(0xE5FFCC88, () -> UItems.SWEET_APPLE_SEEDS, () -> UTreeGen.SWEET_APPLE_TREE.sapling().map(Block::getDefaultState).get(), SproutBlock.settings())); @@ -156,7 +155,7 @@ public interface UBlocks { 0xE5FFCCCC, () -> UBlocks.SOUR_APPLE, () -> UItems.SOUR_APPLE.getDefaultStack(), - FabricBlockSettings.copy(Blocks.OAK_LEAVES) + Block.Settings.copy(Blocks.OAK_LEAVES) ), ItemGroups.NATURAL); Block SOUR_APPLE = register("sour_apple", new FruitBlock(Direction.DOWN, SOUR_APPLE_LEAVES, FruitBlock.DEFAULT_SHAPE, Settings.create().mapColor(MapColor.GREEN))); Block SOUR_APPLE_SPROUT = register("sour_apple_sprout", new SproutBlock(0xE5FFCC88, () -> UItems.SOUR_APPLE_SEEDS, () -> UTreeGen.SOUR_APPLE_TREE.sapling().map(Block::getDefaultState).get(), SproutBlock.settings())); @@ -171,7 +170,7 @@ public interface UBlocks { MapColor.GOLD.color, () -> UBlocks.GOLDEN_APPLE, () -> Items.GOLDEN_APPLE.getDefaultStack(), - FabricBlockSettings.copy(Blocks.OAK_LEAVES) + Block.Settings.copy(Blocks.OAK_LEAVES) ), ItemGroups.NATURAL); Block GOLDEN_APPLE = register("golden_apple", new EnchantedFruitBlock(Direction.DOWN, GOLDEN_OAK_LEAVES, FruitBlock.DEFAULT_SHAPE, false, Settings.create().mapColor(MapColor.GOLD))); Block GOLDEN_OAK_SPROUT = register("golden_oak_sprout", new SproutBlock(0xE5FFCC88, () -> UItems.GOLDEN_OAK_SEEDS, () -> UTreeGen.GOLDEN_APPLE_TREE.sapling().map(Block::getDefaultState).get(), SproutBlock.settings())); @@ -238,7 +237,7 @@ public interface UBlocks { Block CARVED_CLOUD = register("carved_cloud", new OrientedCloudBlock(false, Settings.copy(CLOUD).hardness(0.4F).requiresTool().solid()), ItemGroups.BUILDING_BLOCKS); Block UNSTABLE_CLOUD = register("unstable_cloud", new UnstableCloudBlock(Settings.copy(CLOUD)), ItemGroups.NATURAL); Block CLOUD_PILLAR = register("cloud_pillar", new CloudPillarBlock(Settings.create().mapColor(MapColor.GRAY).hardness(0.5F).resistance(0).sounds(BlockSoundGroup.WOOL).solid()), ItemGroups.NATURAL); - Block CLOUD_CHEST = register("cloud_chest", new CloudChestBlock(DENSE_CLOUD.getDefaultState(), Settings.copy(DENSE_CLOUD).instrument(Instrument.BASS).strength(2.5f)), ItemGroups.FUNCTIONAL); + Block CLOUD_CHEST = register("cloud_chest", new CloudChestBlock(DENSE_CLOUD.getDefaultState(), Settings.copy(DENSE_CLOUD).instrument(NoteBlockInstrument.BASS).strength(2.5f)), ItemGroups.FUNCTIONAL); Block CLOTH_BED = register("cloth_bed", new FancyBedBlock("cloth", Settings.copy(Blocks.WHITE_BED).sounds(BlockSoundGroup.WOOD))); Block CLOUD_BED = register("cloud_bed", new CloudBedBlock("cloud", CLOUD.getDefaultState(), Settings.copy(Blocks.WHITE_BED).sounds(BlockSoundGroup.WOOL))); @@ -259,7 +258,7 @@ public interface UBlocks { Block ZAP_JAR = register("zap_jar", new JarBlock(Settings.copy(Blocks.GLASS))); Block WORM_BLOCK = register("worm_block", new ColoredFallingBlock(new ColorCode(0xFF0088), Settings.create().hardness(0.1F).resistance(0).requiresTool().sounds(BlockSoundGroup.MUD)), ItemGroups.NATURAL); - EdibleBlock HAY_BLOCK = register("hay_block", new EdibleBlock(new Identifier("hay_block"), new Identifier("wheat"), true)); + EdibleBlock HAY_BLOCK = register("hay_block", new EdibleBlock(Identifier.ofVanilla("hay_block"), Identifier.ofVanilla("wheat"), true)); private static T register(String name, T item) { return register(Unicopia.id(name), item); @@ -290,8 +289,8 @@ public interface UBlocks { static void bootstrap() { if (FabricLoader.getInstance().isModLoaded("farmersdelight")) { - register("rice_block", new EdibleBlock(new Identifier("farmersdelight", "rice_bale"), new Identifier("farmersdelight", "rice_panicle"), true)); - register("straw_block", new EdibleBlock(new Identifier("farmersdelight", "straw_bale"), new Identifier("farmersdelight", "straw"), true)); + register("rice_block", new EdibleBlock(Identifier.of("farmersdelight", "rice_bale"), Identifier.of("farmersdelight", "rice_panicle"), true)); + register("straw_block", new EdibleBlock(Identifier.of("farmersdelight", "straw_bale"), Identifier.of("farmersdelight", "straw"), true)); } BlockEntityTypeSupportHelper.of(BlockEntityType.SIGN).addSupportedBlocks(PALM_SIGN, PALM_WALL_SIGN); BlockEntityTypeSupportHelper.of(BlockEntityType.HANGING_SIGN).addSupportedBlocks(PALM_HANGING_SIGN, PALM_WALL_HANGING_SIGN); diff --git a/src/main/java/com/minelittlepony/unicopia/block/WeatherVaneBlock.java b/src/main/java/com/minelittlepony/unicopia/block/WeatherVaneBlock.java index aed78d3b..dbd6034f 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/WeatherVaneBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/WeatherVaneBlock.java @@ -14,6 +14,7 @@ import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.Packet; import net.minecraft.network.listener.ClientPlayPacketListener; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.util.math.*; @@ -73,13 +74,13 @@ public class WeatherVaneBlock extends BlockWithEntity { } @Override - public void readNbt(NbtCompound nbt) { + public void readNbt(NbtCompound nbt, WrapperLookup lookup) { angle = nbt.getFloat("angle"); airflow = new Vec3d(nbt.getDouble("windX"), 0, nbt.getDouble("windZ")); } @Override - protected void writeNbt(NbtCompound nbt) { + protected void writeNbt(NbtCompound nbt, WrapperLookup lookup) { nbt.putFloat("angle", angle); nbt.putDouble("windX", airflow.x); nbt.putDouble("windZ", airflow.z); @@ -91,8 +92,8 @@ public class WeatherVaneBlock extends BlockWithEntity { } @Override - public NbtCompound toInitialChunkDataNbt() { - return createNbt(); + public NbtCompound toInitialChunkDataNbt(WrapperLookup lookup) { + return createNbt(lookup); } public static void serverTick(World world, BlockPos pos, BlockState state, WeatherVane entity) { diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBedBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBedBlock.java index c851aff4..e674cfe6 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBedBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBedBlock.java @@ -15,8 +15,9 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.ai.pathing.NavigationType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemPlacementContext; -import net.minecraft.util.ActionResult; +import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; @@ -76,11 +77,11 @@ public class CloudBedBlock extends FancyBedBlock implements CloudLike { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (!baseBlock.canInteract(baseState, world, pos, EquineContext.of(player))) { - return ActionResult.PASS; + return ItemActionResult.SKIP_DEFAULT_BLOCK_INTERACTION; } - return super.onUse(state, world, pos, player, hand, hit); + return super.onUseWithItem(stack, state, world, pos, player, hand, hit); } @Deprecated @@ -91,7 +92,7 @@ public class CloudBedBlock extends FancyBedBlock implements CloudLike { @Override @Deprecated - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { - return baseState.canPathfindThrough(world, pos, type); + public boolean canPathfindThrough(BlockState state, NavigationType type) { + return baseState.canPathfindThrough(type); } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBlock.java index c1c74a05..db80cfcc 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudBlock.java @@ -187,7 +187,7 @@ public class CloudBlock extends Block implements CloudLike { @Override @Deprecated - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { + public boolean canPathfindThrough(BlockState state, NavigationType type) { System.out.println(InteractionManager.getInstance().getPathingEquineContext().collidesWithClouds()); return type != NavigationType.LAND || !InteractionManager.getInstance().getPathingEquineContext().collidesWithClouds(); } @@ -200,7 +200,6 @@ public class CloudBlock extends Block implements CloudLike { return context.collidesWithClouds() || context.hasFeatherTouch(); } - @SuppressWarnings("deprecation") protected boolean canReplace(BlockState state, ItemPlacementContext context, EquineContext equineContext) { return super.canReplace(state, context); } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudChestBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudChestBlock.java index ce7f0d4b..39e5d2c5 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudChestBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudChestBlock.java @@ -24,12 +24,13 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.DoubleInventory; import net.minecraft.item.ItemPlacementContext; +import net.minecraft.item.ItemStack; import net.minecraft.screen.GenericContainerScreenHandler; import net.minecraft.screen.NamedScreenHandlerFactory; import net.minecraft.screen.ScreenHandler; import net.minecraft.text.Text; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; @@ -137,11 +138,11 @@ public class CloudChestBlock extends ChestBlock implements CloudLike { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (!baseBlock.canInteract(baseState, world, pos, EquineContext.of(player))) { - return ActionResult.PASS; + return ItemActionResult.SKIP_DEFAULT_BLOCK_INTERACTION; } - return super.onUse(state, world, pos, player, hand, hit); + return super.onUseWithItem(stack, state, world, pos, player, hand, hit); } @Deprecated @@ -152,7 +153,7 @@ public class CloudChestBlock extends ChestBlock implements CloudLike { @Override @Deprecated - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { + public boolean canPathfindThrough(BlockState state, NavigationType type) { return type != NavigationType.LAND || !InteractionManager.getInstance().getPathingEquineContext().collidesWithClouds(); } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudDoorBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudDoorBlock.java index 6ee33082..80923d5a 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudDoorBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudDoorBlock.java @@ -16,8 +16,9 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.ai.pathing.NavigationType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemPlacementContext; -import net.minecraft.util.ActionResult; +import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; @@ -79,11 +80,11 @@ public class CloudDoorBlock extends DoorBlock implements CloudLike { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (!baseBlock.canInteract(baseState, world, pos, EquineContext.of(player))) { - return ActionResult.PASS; + return ItemActionResult.SKIP_DEFAULT_BLOCK_INTERACTION; } - return super.onUse(state, world, pos, player, hand, hit); + return super.onUseWithItem(stack, state, world, pos, player, hand, hit); } @Deprecated @@ -100,7 +101,7 @@ public class CloudDoorBlock extends DoorBlock implements CloudLike { @Override @Deprecated - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { - return !InteractionManager.getInstance().getPathingEquineContext().collidesWithClouds() || super.canPathfindThrough(state, world, pos, type); + public boolean canPathfindThrough(BlockState state, NavigationType type) { + return !InteractionManager.getInstance().getPathingEquineContext().collidesWithClouds() || super.canPathfindThrough(state, type); } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudStairsBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudStairsBlock.java index 454e1fd1..5201f703 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudStairsBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CloudStairsBlock.java @@ -108,7 +108,7 @@ public class CloudStairsBlock extends StairsBlock implements CloudLike { @Override @Deprecated - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { - return baseBlock.canPathfindThrough(state, world, pos, type); + public boolean canPathfindThrough(BlockState state, NavigationType type) { + return baseBlock.canPathfindThrough(state, type); } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/CompactedCloudBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/CompactedCloudBlock.java index 86456378..5de3e532 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/CompactedCloudBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/CompactedCloudBlock.java @@ -12,6 +12,7 @@ import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.ConnectingBlock; import net.minecraft.block.ShapeContext; +import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.registry.tag.ItemTags; @@ -20,10 +21,10 @@ import net.minecraft.sound.SoundEvents; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.Property; -import net.minecraft.util.ActionResult; import net.minecraft.util.BlockMirror; import net.minecraft.util.BlockRotation; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.Util; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; @@ -82,20 +83,19 @@ public class CompactedCloudBlock extends CloudBlock { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { - ItemStack stack = player.getStackInHand(hand); + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (stack.isIn(ItemTags.SHOVELS)) { BooleanProperty property = FACING_PROPERTIES.get(hit.getSide()); if (state.get(property)) { world.setBlockState(pos, state.with(property, false)); - stack.damage(1, player, p -> p.sendToolBreakStatus(hand)); + stack.damage(1, player, LivingEntity.getSlotForHand(hand)); world.playSound(null, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } } - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/NaturalCloudBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/NaturalCloudBlock.java index de0ec27e..3abc0533 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/NaturalCloudBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/NaturalCloudBlock.java @@ -12,6 +12,7 @@ import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.BedBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; +import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; @@ -19,8 +20,8 @@ import net.minecraft.registry.tag.ItemTags; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.state.property.BooleanProperty; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -49,17 +50,15 @@ public class NaturalCloudBlock extends PoreousCloudBlock { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { - ItemStack stack = player.getStackInHand(hand); - + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (stack.isIn(ItemTags.SHOVELS)) { BooleanProperty property = CompactedCloudBlock.FACING_PROPERTIES.get(hit.getSide()); world.setBlockState(pos, compactedBlock.get().getDefaultState().with(property, false)); - stack.damage(1, player, p -> p.sendToolBreakStatus(hand)); + stack.damage(1, player, LivingEntity.getSlotForHand(hand)); world.playSound(null, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/ShapingBenchBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/ShapingBenchBlock.java index 4e3d7a68..1eec2c05 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/ShapingBenchBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/ShapingBenchBlock.java @@ -15,7 +15,6 @@ import net.minecraft.screen.ScreenHandlerContext; import net.minecraft.screen.SimpleNamedScreenHandlerFactory; import net.minecraft.stat.Stats; import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; @@ -50,7 +49,7 @@ public class ShapingBenchBlock extends CloudBlock { } @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) { if (world.isClient) { return ActionResult.SUCCESS; } diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/Soakable.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/Soakable.java index a385788f..6baed1fd 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/Soakable.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/Soakable.java @@ -17,8 +17,8 @@ import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.state.property.IntProperty; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.Util; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; @@ -51,9 +51,8 @@ public interface Soakable { } } - static ActionResult tryCollectMoisture(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + static ItemActionResult tryCollectMoisture(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (state.getBlock() instanceof Soakable soakable) { - ItemStack stack = player.getStackInHand(hand); if (stack.getItem() == Items.GLASS_BOTTLE) { if (!player.isCreative()) { stack.split(1); @@ -67,11 +66,11 @@ public interface Soakable { world.emitGameEvent(player, GameEvent.FLUID_PICKUP, pos); updateMoisture(soakable, state, world, pos, soakable.getMoisture(state) - 1); - return ActionResult.SUCCESS; + return ItemActionResult.SUCCESS; } } - return ActionResult.PASS; + return ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } static void tickMoisture(BlockState state, ServerWorld world, BlockPos pos, Random random) { diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudBlock.java index bb177f18..b21aafad 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudBlock.java @@ -17,8 +17,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; import net.minecraft.server.world.ServerWorld; import net.minecraft.state.StateManager; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.random.Random; @@ -66,8 +66,8 @@ public class SoggyCloudBlock extends CloudBlock implements Soakable { @Override @Deprecated - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { - return Soakable.tryCollectMoisture(state, world, pos, player, hand, hit); + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + return Soakable.tryCollectMoisture(stack, state, world, pos, player, hand, hit); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudSlabBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudSlabBlock.java index 6867ce41..53d83307 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudSlabBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/SoggyCloudSlabBlock.java @@ -17,8 +17,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; import net.minecraft.server.world.ServerWorld; import net.minecraft.state.StateManager; -import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; +import net.minecraft.util.ItemActionResult; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.random.Random; @@ -66,8 +66,8 @@ public class SoggyCloudSlabBlock extends CloudSlabBlock { @Override @Deprecated - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { - return Soakable.tryCollectMoisture(state, world, pos, player, hand, hit); + public ItemActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + return Soakable.tryCollectMoisture(stack, state, world, pos, player, hand, hit); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/block/cloud/WaterloggableCloudBlock.java b/src/main/java/com/minelittlepony/unicopia/block/cloud/WaterloggableCloudBlock.java index 915ea406..898cf13c 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/cloud/WaterloggableCloudBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/cloud/WaterloggableCloudBlock.java @@ -24,7 +24,6 @@ import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.Properties; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; -import net.minecraft.world.BlockView; import net.minecraft.world.WorldAccess; public class WaterloggableCloudBlock extends PoreousCloudBlock implements Waterloggable { @@ -76,7 +75,7 @@ public class WaterloggableCloudBlock extends PoreousCloudBlock implements Waterl } @Override - public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { - return (type == NavigationType.WATER) == world.getFluidState(pos).isIn(FluidTags.WATER); + public boolean canPathfindThrough(BlockState state, NavigationType type) { + return (type == NavigationType.WATER) == state.getFluidState().isIn(FluidTags.WATER); } } diff --git a/src/main/java/com/minelittlepony/unicopia/block/jar/EntityJarContents.java b/src/main/java/com/minelittlepony/unicopia/block/jar/EntityJarContents.java index 967807c1..cfb6c2e2 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/jar/EntityJarContents.java +++ b/src/main/java/com/minelittlepony/unicopia/block/jar/EntityJarContents.java @@ -20,6 +20,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.registry.Registries; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Hand; import net.minecraft.util.Identifier; import net.minecraft.util.TypedActionResult; @@ -68,7 +69,7 @@ public record EntityJarContents ( } @Override - public NbtCompound toNBT(NbtCompound compound) { + public NbtCompound toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putString("entity", EntityType.getId(entityType).toString()); return compound; } diff --git a/src/main/java/com/minelittlepony/unicopia/block/jar/FakeFluidJarContents.java b/src/main/java/com/minelittlepony/unicopia/block/jar/FakeFluidJarContents.java index e49d648c..58179158 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/jar/FakeFluidJarContents.java +++ b/src/main/java/com/minelittlepony/unicopia/block/jar/FakeFluidJarContents.java @@ -15,6 +15,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.registry.Registries; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Hand; import net.minecraft.util.Identifier; import net.minecraft.util.TypedActionResult; @@ -28,8 +29,8 @@ public record FakeFluidJarContents ( ) implements JarContents { public FakeFluidJarContents(TileData tile, NbtCompound compound) { this(tile, compound.getString("fluid"), compound.getInt("color"), - Registries.ITEM.get(new Identifier(compound.getString("empty"))), - Registries.ITEM.get(new Identifier(compound.getString("filled")))); + Registries.ITEM.get(Identifier.of(compound.getString("empty"))), + Registries.ITEM.get(Identifier.of(compound.getString("filled")))); } @Override @@ -62,7 +63,7 @@ public record FakeFluidJarContents ( } @Override - public NbtCompound toNBT(NbtCompound compound) { + public NbtCompound toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putString("fluid", fluid); compound.putInt("color", color); compound.putString("empty", Registries.ITEM.getId(empty).toString()); diff --git a/src/main/java/com/minelittlepony/unicopia/block/jar/FluidOnlyJarContents.java b/src/main/java/com/minelittlepony/unicopia/block/jar/FluidOnlyJarContents.java index 0cdcab4b..353450d9 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/jar/FluidOnlyJarContents.java +++ b/src/main/java/com/minelittlepony/unicopia/block/jar/FluidOnlyJarContents.java @@ -4,6 +4,7 @@ import com.minelittlepony.unicopia.block.ItemJarBlock.FluidJarContents; import com.minelittlepony.unicopia.block.ItemJarBlock.JarContents; import com.minelittlepony.unicopia.block.ItemJarBlock.TileData; import com.minelittlepony.unicopia.util.FluidHelper; +import com.minelittlepony.unicopia.util.NbtSerialisable; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidConstants; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidVariant; @@ -11,6 +12,7 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; @@ -21,7 +23,7 @@ public record FluidOnlyJarContents ( ) implements FluidJarContents { public FluidOnlyJarContents(TileData tile, NbtCompound compound) { - this(tile, compound.getLong("amount"), FluidVariant.fromNbt(compound.getCompound("fluid"))); + this(tile, compound.getLong("amount"), NbtSerialisable.decode(FluidVariant.CODEC, compound.getCompound("fluid")).orElse(FluidVariant.blank())); } @Override @@ -47,8 +49,8 @@ public record FluidOnlyJarContents ( } @Override - public NbtCompound toNBT(NbtCompound compound) { - compound.put("fluid", fluid.toNbt()); + public NbtCompound toNBT(NbtCompound compound, WrapperLookup lookup) { + compound.put("fluid", NbtSerialisable.encode(FluidVariant.CODEC, fluid)); compound.putLong("amount", amount); return compound; } diff --git a/src/main/java/com/minelittlepony/unicopia/block/jar/ItemsJarContents.java b/src/main/java/com/minelittlepony/unicopia/block/jar/ItemsJarContents.java index 62f39881..ef06917f 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/jar/ItemsJarContents.java +++ b/src/main/java/com/minelittlepony/unicopia/block/jar/ItemsJarContents.java @@ -21,6 +21,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Hand; import net.minecraft.util.Pair; import net.minecraft.util.TypedActionResult; @@ -37,8 +38,8 @@ public record ItemsJarContents ( this(tile, new ArrayList<>(MAX_SIZE)); } - public ItemsJarContents(TileData tile, NbtCompound compound) { - this(tile, NbtSerialisable.ITEM_STACK.readAll(compound.getList("items", NbtElement.COMPOUND_TYPE)) + public ItemsJarContents(TileData tile, NbtCompound compound, WrapperLookup lookup) { + this(tile, NbtSerialisable.ITEM_STACK.readAll(compound.getList("items", NbtElement.COMPOUND_TYPE), lookup) .limit(MAX_SIZE) .collect(Collectors.toList())); } @@ -197,8 +198,8 @@ public record ItemsJarContents ( } @Override - public NbtCompound toNBT(NbtCompound compound) { - compound.put("items", NbtSerialisable.ITEM_STACK.writeAll(stacks)); + public NbtCompound toNBT(NbtCompound compound, WrapperLookup lookup) { + compound.put("items", NbtSerialisable.ITEM_STACK.writeAll(stacks, lookup)); return compound; } diff --git a/src/main/java/com/minelittlepony/unicopia/block/state/StateChange.java b/src/main/java/com/minelittlepony/unicopia/block/state/StateChange.java index 972eef4f..e6bb219b 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/state/StateChange.java +++ b/src/main/java/com/minelittlepony/unicopia/block/state/StateChange.java @@ -22,7 +22,7 @@ public abstract class StateChange { static { SERIALIZERS.put(Unicopia.id("set_state"), json -> { final String sstate = JsonHelper.getString(json, "state"); - final Identifier id = new Identifier(sstate); + final Identifier id = Identifier.of(sstate); final float chance = JsonHelper.getFloat(json, "chance", -1); return new StateChange() { @@ -96,7 +96,7 @@ public abstract class StateChange { public static StateChange fromJson(JsonObject json) { String action = JsonHelper.getString(json, "action"); - return Optional.of(SERIALIZERS.get(new Identifier(action))).map(serializer -> { + return Optional.of(SERIALIZERS.get(Identifier.of(action))).map(serializer -> { return serializer.apply(json); }).orElseThrow(() -> new IllegalArgumentException("Invalid action " + action)); } diff --git a/src/main/java/com/minelittlepony/unicopia/block/state/StateMapLoader.java b/src/main/java/com/minelittlepony/unicopia/block/state/StateMapLoader.java index e47cfc4d..36f3499d 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/state/StateMapLoader.java +++ b/src/main/java/com/minelittlepony/unicopia/block/state/StateMapLoader.java @@ -50,8 +50,7 @@ public class StateMapLoader extends JsonDataLoader implements IdentifiableResour resourceManager.findAllResources(DATA_TYPE, id -> id.getPath().endsWith(FILE_SUFFIX)).entrySet().stream().forEach(entry -> { Identifier resId = entry.getKey(); - String path = resId.getPath(); - Identifier id = new Identifier(resId.getNamespace(), path.substring(i, path.length() - FILE_SUFFIX_LENGTH)); + Identifier id = resId.withPath(p -> p.substring(i, p.length() - FILE_SUFFIX_LENGTH)); JsonArray entries = new JsonArray(); for (var resource : entry.getValue()) { diff --git a/src/main/java/com/minelittlepony/unicopia/block/state/StatePredicate.java b/src/main/java/com/minelittlepony/unicopia/block/state/StatePredicate.java index cb8e4fcd..20f793db 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/state/StatePredicate.java +++ b/src/main/java/com/minelittlepony/unicopia/block/state/StatePredicate.java @@ -12,7 +12,7 @@ import com.google.common.base.Predicates; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.fabricmc.fabric.api.tag.convention.v1.ConventionalBlockTags; +import net.fabricmc.fabric.api.tag.convention.v2.ConventionalBlockTags; import net.minecraft.block.*; import net.minecraft.state.property.Property; import net.minecraft.util.Identifier; @@ -55,7 +55,7 @@ public abstract class StatePredicate implements Predicate { predicates.add(ofState(JsonHelper.getString(o, "state"))); } if (o.has("tag")) { - Optional.of(JsonHelper.getString(o, "tag")).map(s -> TagKey.of(RegistryKeys.BLOCK, new Identifier(s))).ifPresent(tag -> { + Optional.of(JsonHelper.getString(o, "tag")).map(s -> TagKey.of(RegistryKeys.BLOCK, Identifier.of(s))).ifPresent(tag -> { predicates.add(new StatePredicate() { @Override public StateChange getInverse() { @@ -137,7 +137,7 @@ public abstract class StatePredicate implements Predicate { } public static Predicate ofState(String state) { - Identifier id = new Identifier(state.split("\\{")[0]); + Identifier id = Identifier.of(state.split("\\{")[0]); List properties = Optional.of(state) .filter(s -> s.contains("{")) .stream() diff --git a/src/main/java/com/minelittlepony/unicopia/block/zap/BaseZapAppleLeavesBlock.java b/src/main/java/com/minelittlepony/unicopia/block/zap/BaseZapAppleLeavesBlock.java index 03e73174..215d409c 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/zap/BaseZapAppleLeavesBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/zap/BaseZapAppleLeavesBlock.java @@ -72,7 +72,7 @@ public class BaseZapAppleLeavesBlock extends LeavesBlock implements TintedBlock, @Override public float calcBlockBreakingDelta(BlockState state, PlayerEntity player, BlockView world, BlockPos pos) { if (state.get(PERSISTENT)) { - return Blocks.OAK_LEAVES.calcBlockBreakingDelta(Blocks.OAK_LEAVES.getDefaultState(), player, world, pos); + return Blocks.OAK_LEAVES.getDefaultState().calcBlockBreakingDelta(player, world, pos); } float delta = super.calcBlockBreakingDelta(state, player, world, pos); diff --git a/src/main/java/com/minelittlepony/unicopia/block/zap/ZapAppleLogBlock.java b/src/main/java/com/minelittlepony/unicopia/block/zap/ZapAppleLogBlock.java index 50ec5498..6f183ba2 100644 --- a/src/main/java/com/minelittlepony/unicopia/block/zap/ZapAppleLogBlock.java +++ b/src/main/java/com/minelittlepony/unicopia/block/zap/ZapAppleLogBlock.java @@ -4,7 +4,7 @@ import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.*; -import net.minecraft.block.enums.Instrument; +import net.minecraft.block.enums.NoteBlockInstrument; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemPlacementContext; import net.minecraft.sound.BlockSoundGroup; @@ -24,7 +24,7 @@ public class ZapAppleLogBlock extends PillarBlock implements ElectrifiedBlock { public static Settings settings(MapColor topMapColor, MapColor sideMapColor) { return Settings.create() .mapColor(state -> state.get(PillarBlock.AXIS) == Direction.Axis.Y ? topMapColor : sideMapColor) - .instrument(Instrument.BASS) + .instrument(NoteBlockInstrument.BASS) .strength(2.0f) .sounds(BlockSoundGroup.WOOD) .burnable(); diff --git a/src/main/java/com/minelittlepony/unicopia/client/ClientBlockDestructionManager.java b/src/main/java/com/minelittlepony/unicopia/client/ClientBlockDestructionManager.java index 07fd40f8..4005f7ee 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/ClientBlockDestructionManager.java +++ b/src/main/java/com/minelittlepony/unicopia/client/ClientBlockDestructionManager.java @@ -6,7 +6,7 @@ import com.minelittlepony.unicopia.server.world.BlockDestructionManager; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import net.minecraft.client.render.BlockBreakingInfo; +import net.minecraft.entity.player.BlockBreakingInfo; import net.minecraft.util.math.BlockPos; public class ClientBlockDestructionManager { diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/DrawableUtil.java b/src/main/java/com/minelittlepony/unicopia/client/gui/DrawableUtil.java index 24f5141c..34316aae 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/DrawableUtil.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/DrawableUtil.java @@ -60,13 +60,12 @@ public interface DrawableUtil { float g = (color >> 16 & 255) / 255F; float b = (color >> 8 & 255) / 255F; float k = (color & 255) / 255F; - BufferBuilder bufferBuilder = Tessellator.getInstance().getBuffer(); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorProgram); - bufferBuilder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); - bufferBuilder.vertex(matrix, x1, y1, 0).color(r, g, b, k).next(); - bufferBuilder.vertex(matrix, x2, y2, 0).color(r, g, b, k).next(); + BufferBuilder bufferBuilder = Tessellator.getInstance().begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION_COLOR); + bufferBuilder.vertex(matrix, x1, y1, 0).color(r, g, b, k); + bufferBuilder.vertex(matrix, x2, y2, 0).color(r, g, b, k); BufferRenderer.drawWithGlobalProgram(bufferBuilder.end()); RenderSystem.disableBlend(); } @@ -113,8 +112,7 @@ public interface DrawableUtil { Matrix4f model = matrices.peek().getPositionMatrix(); - BufferBuilder bufferBuilder = Tessellator.getInstance().getBuffer(); - bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); + BufferBuilder bufferBuilder = Tessellator.getInstance().begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); for (double angle = -startAngle; angle >= -maxAngle; angle -= INCREMENT) { // center @@ -133,6 +131,6 @@ public interface DrawableUtil { private static void cylendricalVertex(BufferBuilder bufferBuilder, Matrix4f model, double radius, double angle, float r, float g, float b, float k) { bufferBuilder.vertex(model, (float)(radius * MathHelper.sin((float)angle)), - (float)(radius * MathHelper.cos((float)angle)), 0).color(r, g, b, k).normal(2, 2, 2).next(); + (float)(radius * MathHelper.cos((float)angle)), 0).color(r, g, b, k).normal(2, 2, 2); } } diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/GradientUtil.java b/src/main/java/com/minelittlepony/unicopia/client/gui/GradientUtil.java index 9ee147d2..10b90af7 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/GradientUtil.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/GradientUtil.java @@ -14,14 +14,12 @@ public interface GradientUtil { RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorProgram); - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferBuilder = tessellator.getBuffer(); - fillVerticalGradient(matrices.peek().getPositionMatrix(), bufferBuilder, startX, startY, stopY, endX, endY, z, colorStart, colorStop, colorEnd); - tessellator.draw(); + fillVerticalGradient(matrices.peek().getPositionMatrix(), Tessellator.getInstance(), startX, startY, stopY, endX, endY, z, colorStart, colorStop, colorEnd); + RenderSystem.setShaderColor(1, 1, 1, 1); RenderSystem.disableBlend(); } - private static void fillVerticalGradient(Matrix4f matrix, BufferBuilder builder, int startX, int startY, int stopY, int endX, int endY, int z, int colorStart, int colorStop, int colorEnd) { + private static void fillVerticalGradient(Matrix4f matrix, Tessellator tessellator, int startX, int startY, int stopY, int endX, int endY, int z, int colorStart, int colorStop, int colorEnd) { final float fromA = (colorStart >> 24 & 0xFF) / 255F; final float fromR = (colorStart >> 16 & 0xFF) / 255F; final float fromG = (colorStart >> 8 & 0xFF) / 255F; @@ -37,28 +35,26 @@ public interface GradientUtil { final float toG = (colorEnd >> 8 & 0xFF) / 255F; final float toB = (colorEnd & 0xFF) / 255F; - builder.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); - - builder.vertex(matrix, endX, stopY, z).color(stopR, stopG, stopB, stopA).next(); - builder.vertex(matrix, endX, startY, z).color(fromR, fromG, fromB, fromA).next(); - builder.vertex(matrix, startX, startY, z).color(fromR, fromG, fromB, fromA).next(); - builder.vertex(matrix, startX, stopY, z).color(stopR, stopG, stopB, stopA).next(); - builder.vertex(matrix, startX, endY, z).color(toR, toG, toB, toA).next(); - builder.vertex(matrix, endX, endY, z).color(stopR, toG, toB, toA).next(); + BufferBuilder builder = tessellator.begin(VertexFormat.DrawMode.TRIANGLE_FAN, VertexFormats.POSITION_COLOR); + builder.vertex(matrix, endX, stopY, z).color(stopR, stopG, stopB, stopA); + builder.vertex(matrix, endX, startY, z).color(fromR, fromG, fromB, fromA); + builder.vertex(matrix, startX, startY, z).color(fromR, fromG, fromB, fromA); + builder.vertex(matrix, startX, stopY, z).color(stopR, stopG, stopB, stopA); + builder.vertex(matrix, startX, endY, z).color(toR, toG, toB, toA); + builder.vertex(matrix, endX, endY, z).color(stopR, toG, toB, toA); + BufferRenderer.drawWithGlobalProgram(builder.end()); } static void fillRadialGradient(MatrixStack matrices, int startX, int startY, int endX, int endY, int colorStart, int colorEnd, int z, float radius) { RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorProgram); - Tessellator tessellator = Tessellator.getInstance(); - if (fillRadials(matrices.peek().getPositionMatrix(), tessellator.getBuffer(), startX, startY, endX, endY, z, colorStart, colorEnd, radius)) { - tessellator.draw(); - } + fillRadials(matrices.peek().getPositionMatrix(), Tessellator.getInstance(), startX, startY, endX, endY, z, colorStart, colorEnd, radius); + RenderSystem.setShaderColor(1, 1, 1, 1); RenderSystem.disableBlend(); } - private static boolean fillRadials(Matrix4f matrix, BufferBuilder builder, int startX, int startY, int endX, int endY, int z, int colorStart, int colorEnd, float radius) { + private static void fillRadials(Matrix4f matrix, Tessellator tessellator, int startX, int startY, int endX, int endY, int z, int colorStart, int colorEnd, float radius) { final float fromA = (colorStart >> 24 & 0xFF) / 255F; final float fromR = (colorStart >> 16 & 0xFF) / 255F; final float fromG = (colorStart >> 8 & 0xFF) / 255F; @@ -77,14 +73,14 @@ public interface GradientUtil { float innerRadius = outerRadius * (1 - radius); - builder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); + BufferBuilder builder = tessellator.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); for (double angle = 0; angle < DrawableUtil.TAU; angle += increment) { - clampedVertex(builder, matrix, innerRadius, angle + increment, z, startX, endX, startY, endY).color(toR, toG, toB, toA).next(); - clampedVertex(builder, matrix, innerRadius, angle, z, startX, endX, startY, endY).color(toR, toG, toB, toA).next(); - clampedVertex(builder, matrix, outerRadius, angle, z, startX, endX, startY, endY).color(fromR, fromG, fromB, fromA).next(); - clampedVertex(builder, matrix, outerRadius, angle + increment, z, startX, endX, startY, endY).color(fromR, fromG, fromB, fromA).next(); + clampedVertex(builder, matrix, innerRadius, angle + increment, z, startX, endX, startY, endY).color(toR, toG, toB, toA); + clampedVertex(builder, matrix, innerRadius, angle, z, startX, endX, startY, endY).color(toR, toG, toB, toA); + clampedVertex(builder, matrix, outerRadius, angle, z, startX, endX, startY, endY).color(fromR, fromG, fromB, fromA); + clampedVertex(builder, matrix, outerRadius, angle + increment, z, startX, endX, startY, endY).color(fromR, fromG, fromB, fromA); } - return true; + BufferRenderer.drawWithGlobalProgram(builder.end()); } static float getX(double radius, double angle) { diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/ItemTraitsTooltipRenderer.java b/src/main/java/com/minelittlepony/unicopia/client/gui/ItemTraitsTooltipRenderer.java index e4e304f6..fcb60e49 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/ItemTraitsTooltipRenderer.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/ItemTraitsTooltipRenderer.java @@ -12,7 +12,6 @@ import net.minecraft.client.font.TextRenderer; import net.minecraft.client.font.TextRenderer.TextLayerType; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.tooltip.TooltipComponent; -import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemStack; @@ -128,7 +127,9 @@ public class ItemTraitsTooltipRenderer implements Text, OrderedText, TooltipComp String count = value > 99 ? "99+" : Math.round(value) == value ? (int)value + "" : ((Math.round(value * 10) / 10F) + ""); - VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer()); + VertexConsumerProvider.Immediate immediate = MinecraftClient.getInstance().getBufferBuilders().getEffectVertexConsumers(); + // TODO: Before 1.21 was using tessellator's buffer but we can't get it without calling begin() + //VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer()); textRenderer.draw(count, 0, 0, 16777215, true, matrices.peek().getPositionMatrix(), immediate, TextLayerType.SEE_THROUGH, 0, 15728880); immediate.draw(); matrices.pop(); diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/MagicText.java b/src/main/java/com/minelittlepony/unicopia/client/gui/MagicText.java index 4387217f..020b7933 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/MagicText.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/MagicText.java @@ -6,7 +6,7 @@ import net.minecraft.util.math.MathHelper; public interface MagicText { static int getColor() { MinecraftClient client = MinecraftClient.getInstance(); - float ticks = client.player.age + client.getTickDelta(); + float ticks = client.player.age + client.getRenderTickCounter().getTickDelta(false); float sin = (MathHelper.sin(ticks / 10F) + 1) * 155 * 0.25F; float cos = (MathHelper.cos((ticks + 10) / 10F) + 1) * 155 * 0.25F; diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/SpellIconRenderer.java b/src/main/java/com/minelittlepony/unicopia/client/gui/SpellIconRenderer.java index 57c383d7..43eebec4 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/SpellIconRenderer.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/SpellIconRenderer.java @@ -36,7 +36,7 @@ public interface SpellIconRenderer { DrawableUtil.drawArc(modelStack, radius, radius + 3, 0, DrawableUtil.TAU, color & 0xFFFFFF2F); DrawableUtil.drawArc(modelStack, radius + 3, radius + 4, 0, DrawableUtil.TAU, color & 0xFFFFFFAF); pony.getSpellSlot().get(spell.and(SpellPredicate.IS_TIMED)).map(TimedSpell::getTimer).ifPresent(timer -> { - DrawableUtil.drawArc(modelStack, radius, radius + 3, 0, DrawableUtil.TAU * timer.getPercentTimeRemaining(client.getTickDelta()), 0xFFFFFFFF); + DrawableUtil.drawArc(modelStack, radius, radius + 3, 0, DrawableUtil.TAU * timer.getPercentTimeRemaining(client.getRenderTickCounter().getTickDelta(false)), 0xFFFFFFFF); }); long count = pony.getSpellSlot().stream(spell).count(); diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/TribeSelectionScreen.java b/src/main/java/com/minelittlepony/unicopia/client/gui/TribeSelectionScreen.java index a18e17ca..a07c97c5 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/TribeSelectionScreen.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/TribeSelectionScreen.java @@ -108,7 +108,7 @@ public class TribeSelectionScreen extends GameGui implements HidesHud { private void updateScolling() { final int itemWidth = 70 + 10; int x = (width - itemWidth) / 2; - float diff = MathHelper.lerp(client.getTickDelta(), prevScrollPosition, scrollPosition) / 4F; + float diff = MathHelper.lerp(client.getRenderTickCounter().getTickDelta(false), prevScrollPosition, scrollPosition) / 4F; for (int i = 0; i < options.size(); i++) { var option = options.get(i); @@ -125,7 +125,7 @@ public class TribeSelectionScreen extends GameGui implements HidesHud { if (!options.isEmpty()) { var element = options.get(0); - float diff = (targetScroll - MathHelper.lerp(client.getTickDelta(), prevScrollPosition, scrollPosition)) * 7; + float diff = (targetScroll - MathHelper.lerp(client.getRenderTickCounter().getTickDelta(false), prevScrollPosition, scrollPosition)) * 7; context.drawTexture(TEXTURE, (width / 2) + 40 + (scrollPosition < targetScroll ? (int)diff : 0), element.getY() - 20, 10, 165, 153, 30, 85, 312, 312); context.drawTexture(TEXTURE, (width / 2) - 80 + (scrollPosition > targetScroll ? (int)diff : 0), element.getY() - 20, 10, 195, 153, 30, 85, 312, 312); if (element.getBounds().left < 0) { diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/UHud.java b/src/main/java/com/minelittlepony/unicopia/client/gui/UHud.java index 687bcffb..d816b878 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/UHud.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/UHud.java @@ -28,6 +28,7 @@ import net.minecraft.client.gui.hud.InGameHud; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.component.DataComponentTypes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; @@ -254,7 +255,8 @@ public class UHud { if (hasSunglasses) { - if (glasses.hasCustomName() && "Cool Shades".equals(glasses.getName().getString())) { + Text customName = glasses.get(DataComponentTypes.CUSTOM_NAME); + if (customName != null && "Cool Shades".equals(customName.getString())) { final int delay = 7; final int current = client.player.age / delay; final int tint = DyeColor.byId(current % DyeColor.values().length).getSignColor(); @@ -264,7 +266,7 @@ public class UHud { client.getSoundManager().play( partySound = new LoopingSoundInstance<>(client.player, player -> { return UItems.SUNGLASSES.isApplicable(player) || true; - }, USounds.Vanilla.MUSIC_DISC_PIGSTEP, 1, 1, client.world.random) + }, USounds.Vanilla.MUSIC_DISC_PIGSTEP.value(), 1, 1, client.world.random) ); } else if (partySound != null) { partySound.setMuted(false); @@ -337,10 +339,10 @@ public class UHud { float centerX = MathHelper.sin(angle) * innerRadius; float centerY = MathHelper.cos(angle) * innerRadius; - vertexConsumer.vertex(matrix4f, centerX, centerY, 0).color(1F, 1F, 1F, alpha * 0.3F).next(); - vertexConsumer.vertex(matrix4f, MathHelper.sin(angle - wedgeAngle) * outerRadius, MathHelper.cos(angle - wedgeAngle) * outerRadius, 0).color(1F, 1F, 1F, alpha).next(); - vertexConsumer.vertex(matrix4f, MathHelper.sin(angle + wedgeAngle) * outerRadius, MathHelper.cos(angle + wedgeAngle) * outerRadius, 0).color(1F, 1F, 1F, alpha).next(); - vertexConsumer.vertex(matrix4f, centerX, centerY, 0).color(1F, 1F, 1F, alpha * 0.3F).next(); + vertexConsumer.vertex(matrix4f, centerX, centerY, 0).color(1F, 1F, 1F, alpha * 0.3F); + vertexConsumer.vertex(matrix4f, MathHelper.sin(angle - wedgeAngle) * outerRadius, MathHelper.cos(angle - wedgeAngle) * outerRadius, 0).color(1F, 1F, 1F, alpha); + vertexConsumer.vertex(matrix4f, MathHelper.sin(angle + wedgeAngle) * outerRadius, MathHelper.cos(angle + wedgeAngle) * outerRadius, 0).color(1F, 1F, 1F, alpha); + vertexConsumer.vertex(matrix4f, centerX, centerY, 0).color(1F, 1F, 1F, alpha * 0.3F); } context.getMatrices().pop(); } diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/IngredientTree.java b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/IngredientTree.java index 0ee21aae..bb445f6e 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/IngredientTree.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/IngredientTree.java @@ -5,9 +5,9 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import com.minelittlepony.client.util.render.RenderLayerUtil; import com.minelittlepony.common.client.gui.*; import com.minelittlepony.common.client.gui.element.Button; +import com.minelittlepony.common.util.render.RenderLayerUtil; import com.minelittlepony.unicopia.ability.magic.spell.crafting.SpellbookRecipe; import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait; import com.minelittlepony.unicopia.client.gui.ItemTraitsTooltipRenderer; @@ -15,7 +15,6 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.item.TooltipContext; import net.minecraft.client.render.*; import com.minelittlepony.unicopia.client.render.RenderLayers; import com.minelittlepony.unicopia.container.SpellbookState; @@ -23,7 +22,9 @@ import com.minelittlepony.unicopia.container.SpellbookState; import net.minecraft.client.render.item.ItemRenderer; import net.minecraft.client.render.model.json.ModelTransformationMode; import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.item.tooltip.TooltipType; public class IngredientTree implements SpellbookRecipe.CraftingTreeBuilder { private final List entries = new ArrayList<>(); @@ -252,7 +253,7 @@ public class IngredientTree implements SpellbookRecipe.CraftingTreeBuilder { if (stack.isEmpty()) { return List.of(); } - return stack.getTooltip(MinecraftClient.getInstance().player, TooltipContext.Default.BASIC); + return stack.getTooltip(Item.TooltipContext.create(MinecraftClient.getInstance().world), MinecraftClient.getInstance().player, TooltipType.BASIC); }; } diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookChapterList.java b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookChapterList.java index 6b206793..d45e979a 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookChapterList.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookChapterList.java @@ -53,7 +53,7 @@ public class SpellbookChapterList { Optional content) { public static Identifier createIcon(Identifier id, String suffex) { - return new Identifier(id.getNamespace(), "textures/gui/container/pages/" + id.getPath() + suffex + ".png"); + return id.withPath(p -> "textures/gui/container/pages/" + p + suffex + ".png"); } } diff --git a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookProfilePageContent.java b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookProfilePageContent.java index b0fe5fda..3578241d 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookProfilePageContent.java +++ b/src/main/java/com/minelittlepony/unicopia/client/gui/spellbook/SpellbookProfilePageContent.java @@ -63,7 +63,7 @@ public class SpellbookProfilePageContent implements SpellbookChapterList.Content int y = SpellbookScreen.TITLE_Y; - float tickDelta = client.getTickDelta(); + float tickDelta = client.getRenderTickCounter().getTickDelta(false); float delta = pony.asEntity().age + tickDelta; int currentLevel = pony.getLevel().get(); float currentScaledLevel = pony.getLevel().getScaled(1); diff --git a/src/main/java/com/minelittlepony/unicopia/client/render/RenderLayerUtil.java b/src/main/java/com/minelittlepony/unicopia/client/render/RenderLayerUtil.java index 1539a9ea..bceaabc2 100644 --- a/src/main/java/com/minelittlepony/unicopia/client/render/RenderLayerUtil.java +++ b/src/main/java/com/minelittlepony/unicopia/client/render/RenderLayerUtil.java @@ -11,14 +11,7 @@ import net.minecraft.screen.PlayerScreenHandler; import net.minecraft.util.Identifier; public interface RenderLayerUtil { - Identifier SHADOW_TEXTURE = new Identifier("textures/misc/shadow.png"); - - static Optional getTexture(RenderLayer layer) { - if (layer instanceof RenderLayer.MultiPhase multiphase) { - return multiphase.getPhases().texture.getId(); - } - return Optional.empty(); - } + Identifier SHADOW_TEXTURE = Identifier.ofVanilla("textures/misc/shadow.png"); static void createUnionBuffer(Consumer action, VertexConsumerProvider vertices, Function overlayFunction) { Immediate immediate = MinecraftClient.getInstance().getBufferBuilders().getEffectVertexConsumers(); diff --git a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketSlotBackSprites.java b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketSlotBackSprites.java index c97fde11..bf2f9e62 100644 --- a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketSlotBackSprites.java +++ b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketSlotBackSprites.java @@ -13,7 +13,7 @@ import net.minecraft.client.texture.NativeImageBackedTexture; import net.minecraft.util.Identifier; public class TrinketSlotBackSprites { - private static final Identifier BLANK_FACE = new Identifier("trinkets", "textures/gui/blank_back.png"); + private static final Identifier BLANK_FACE = Identifier.of("trinkets", "textures/gui/blank_back.png"); private static final Map CACHE = new HashMap<>(); diff --git a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegate.java b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegate.java index c73f5d46..3c72ff34 100644 --- a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegate.java +++ b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegate.java @@ -23,10 +23,10 @@ import net.minecraft.screen.slot.Slot; import net.minecraft.util.Identifier; public interface TrinketsDelegate { - Identifier MAIN_GLOVE = new Identifier("hand:glove"); - Identifier SECONDARY_GLOVE = new Identifier("offhand:glove"); - Identifier NECKLACE = new Identifier("chest:necklace"); - Identifier FACE = new Identifier("head:face"); + Identifier MAIN_GLOVE = Identifier.of("hand:glove"); + Identifier SECONDARY_GLOVE = Identifier.of("offhand:glove"); + Identifier NECKLACE = Identifier.of("chest:necklace"); + Identifier FACE = Identifier.of("head:face"); Set ALL = new TreeSet<>(List.of(MAIN_GLOVE, SECONDARY_GLOVE, NECKLACE, FACE)); @@ -48,7 +48,7 @@ public interface TrinketsDelegate { } default boolean equipStack(LivingEntity entity, Identifier slot, ItemStack stack) { - EquipmentSlot eq = MobEntity.getPreferredEquipmentSlot(stack); + EquipmentSlot eq = entity.getPreferredEquipmentSlot(stack); if (!entity.getEquippedStack(eq).isEmpty()) { return false; } @@ -126,11 +126,11 @@ public interface TrinketsDelegate { } } - record EquippedStack(ItemStack stack, Runnable sendUpdate, Consumer breakStatusSender) { + record EquippedStack(ItemStack stack, Runnable sendUpdate, Consumer breakStatusSender) { public static final EquippedStack EMPTY = new EquippedStack(ItemStack.EMPTY, () -> {}, l -> {}); EquippedStack(LivingEntity entity, EquipmentSlot slot) { - this(entity.getEquippedStack(slot), () -> {}, l -> l.sendEquipmentBreakStatus(slot)); + this(entity.getEquippedStack(slot), () -> {}, item -> entity.sendEquipmentBreakStatus(item, slot)); } } } diff --git a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegateImpl.java b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegateImpl.java index edbe0274..08ab892f 100644 --- a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegateImpl.java +++ b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/TrinketsDelegateImpl.java @@ -22,6 +22,7 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Equipment; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.screen.slot.Slot; import net.minecraft.sound.SoundEvent; import net.minecraft.util.Identifier; @@ -47,11 +48,13 @@ public class TrinketsDelegateImpl implements TrinketsDelegate { return getInventory(entity, slot).map(inventory -> { for (int position = 0; position < inventory.size(); position++) { if (inventory.getStack(position).isEmpty() && TrinketSlot.canInsert(stack, new SlotReference(inventory, position), entity)) { - SoundEvent soundEvent = stack.getItem() instanceof Equipment q ? q.getEquipSound() : null; + + Equipment q = Equipment.fromStack(stack); + RegistryEntry soundEvent = q == null ? null : q.getEquipSound(); inventory.setStack(position, stack.split(1)); if (soundEvent != null) { entity.emitGameEvent(GameEvent.EQUIP); - entity.playSound(soundEvent, 1, 1); + entity.playSound(soundEvent.value(), 1, 1); } return true; } @@ -63,12 +66,13 @@ public class TrinketsDelegateImpl implements TrinketsDelegate { @Override public void setEquippedStack(LivingEntity entity, Identifier slot, ItemStack stack) { getInventory(entity, slot).ifPresent(inventory -> { - SoundEvent soundEvent = stack.getItem() instanceof Equipment q ? q.getEquipSound() : null; + Equipment q = Equipment.fromStack(stack); + RegistryEntry soundEvent = q == null ? null : q.getEquipSound(); inventory.clear(); inventory.setStack(0, stack); if (soundEvent != null) { entity.emitGameEvent(GameEvent.EQUIP); - entity.playSound(soundEvent, 1, 1); + entity.playSound(soundEvent.value(), 1, 1); } }); } @@ -91,7 +95,7 @@ public class TrinketsDelegateImpl implements TrinketsDelegate { ItemStack oldStack = stack.copy(); return new EquippedStack(stack, inventory::markUpdate, l -> { inventory.markUpdate(); - Channel.SERVER_TRINKET_BROKEN.sendToSurroundingPlayers(new MsgTrinketBroken(oldStack, l.getId()), l); + Channel.SERVER_TRINKET_BROKEN.sendToSurroundingPlayers(new MsgTrinketBroken(oldStack, entity.getId()), entity); }); }); }); @@ -147,7 +151,7 @@ public class TrinketsDelegateImpl implements TrinketsDelegate { } private static Identifier getSlotId(SlotType slotType) { - return new Identifier(slotType.getGroup(), slotType.getName()); + return Identifier.of(slotType.getGroup(), slotType.getName()); } public static int getMaxCount(ItemStack stack, SlotReference ref, int normal) { @@ -176,11 +180,12 @@ public class TrinketsDelegateImpl implements TrinketsDelegate { Trinket trinket = TrinketsApi.getTrinket(stack.getItem()); - SoundEvent soundEvent = stack.getItem() instanceof Equipment q ? q.getEquipSound() : null; + Equipment q = Equipment.fromStack(stack); + RegistryEntry soundEvent = q == null ? null : q.getEquipSound(); inv.setStack(i, stack.split(trinket instanceof UnicopiaTrinket ut ? ut.getMaxCount(stack, ref) : stack.getMaxCount())); if (!stack.isEmpty() && soundEvent != null) { user.emitGameEvent(GameEvent.EQUIP); - user.playSound(soundEvent, 1, 1); + user.playSound(soundEvent.value(), 1, 1); } return true; diff --git a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/UnicopiaTrinket.java b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/UnicopiaTrinket.java index c8ce7e96..6b00ab7d 100644 --- a/src/main/java/com/minelittlepony/unicopia/compat/trinkets/UnicopiaTrinket.java +++ b/src/main/java/com/minelittlepony/unicopia/compat/trinkets/UnicopiaTrinket.java @@ -17,6 +17,9 @@ import net.minecraft.item.Equipment; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.predicate.entity.EntityPredicates; +import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.sound.SoundEvent; +import net.minecraft.world.event.GameEvent; public class UnicopiaTrinket implements Trinket { @@ -32,8 +35,13 @@ public class UnicopiaTrinket implements Trinket { return; } - if (!(stack.getItem() instanceof ItemTracker.Trackable) && stack.getItem() instanceof Equipment q) { - entity.playSound(q.getEquipSound(), 1, 1); + if (!(stack.getItem() instanceof ItemTracker.Trackable)) { + Equipment q = Equipment.fromStack(stack); + RegistryEntry soundEvent = q == null ? null : q.getEquipSound(); + if (soundEvent != null) { + entity.emitGameEvent(GameEvent.EQUIP); + entity.playSound(soundEvent.value(), 1, 1); + } } } @@ -43,8 +51,11 @@ public class UnicopiaTrinket implements Trinket { Living l = Living.living(entity); t.onUnequipped(l, l.getArmour().forceRemove(t)); } - if (stack.getItem() instanceof Equipment q) { - entity.playSound(q.getEquipSound(), 1, 1); + Equipment q = Equipment.fromStack(stack); + RegistryEntry soundEvent = q == null ? null : q.getEquipSound(); + if (soundEvent != null) { + entity.emitGameEvent(GameEvent.EQUIP); + entity.playSound(soundEvent.value(), 1, 1); } } diff --git a/src/main/java/com/minelittlepony/unicopia/container/ShapingBenchScreenHandler.java b/src/main/java/com/minelittlepony/unicopia/container/ShapingBenchScreenHandler.java index c490e971..760f123d 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/ShapingBenchScreenHandler.java +++ b/src/main/java/com/minelittlepony/unicopia/container/ShapingBenchScreenHandler.java @@ -6,9 +6,9 @@ import com.minelittlepony.unicopia.recipe.URecipes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.recipe.input.SingleStackRecipeInput; import net.minecraft.screen.ScreenHandlerContext; import net.minecraft.screen.ScreenHandlerType; import net.minecraft.screen.StonecutterScreenHandler; @@ -53,7 +53,7 @@ public class ShapingBenchScreenHandler extends StonecutterScreenHandler { setProperty(0, -1); slots.get(1).setStackNoCallbacks(ItemStack.EMPTY); if (!stack.isEmpty()) { - getAvailableRecipes().addAll(world.getRecipeManager().getAllMatches(URecipes.CLOUD_SHAPING, input, world)); + getAvailableRecipes().addAll(world.getRecipeManager().getAllMatches(URecipes.CLOUD_SHAPING, new SingleStackRecipeInput(input.getStack(0)), world)); } } } @@ -74,7 +74,7 @@ public class ShapingBenchScreenHandler extends StonecutterScreenHandler { srcSlot.onQuickTransfer(movingStack, originalStack); } else if (slot == 0 ? !insertItem(movingStack, 2, 38, false) - : (world.getRecipeManager().getFirstMatch(URecipes.CLOUD_SHAPING, new SimpleInventory(movingStack), world).isPresent() + : (world.getRecipeManager().getFirstMatch(URecipes.CLOUD_SHAPING, new SingleStackRecipeInput(movingStack), world).isPresent() ? !insertItem(movingStack, 0, 1, false) : (slot >= 2 && slot < 29 ? !insertItem(movingStack, 29, 38, false) diff --git a/src/main/java/com/minelittlepony/unicopia/container/SpellbookChapterLoader.java b/src/main/java/com/minelittlepony/unicopia/container/SpellbookChapterLoader.java index b0bd7262..38a8ee27 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/SpellbookChapterLoader.java +++ b/src/main/java/com/minelittlepony/unicopia/container/SpellbookChapterLoader.java @@ -25,10 +25,13 @@ import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.registry.DynamicRegistryManager; import net.minecraft.resource.JsonDataLoader; import net.minecraft.resource.ResourceManager; import net.minecraft.server.MinecraftServer; import net.minecraft.text.Text; +import net.minecraft.text.TextCodecs; import net.minecraft.text.TextColor; import net.minecraft.util.*; import net.minecraft.util.profiler.Profiler; @@ -89,7 +92,7 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab } private static Text readText(JsonElement json) { - return json.isJsonPrimitive() ? Text.translatable(json.getAsString()) : Text.Serialization.fromJsonTree(json); + return json.isJsonPrimitive() ? Text.translatable(json.getAsString()) : Text.Serialization.fromJsonTree(json, DynamicRegistryManager.EMPTY); } public enum Flow { @@ -122,7 +125,7 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab .toList(); } - public void write(PacketByteBuf buffer) { + public void write(RegistryByteBuf buffer) { buffer.writeIdentifier(id); buffer.writeEnumConstant(side); buffer.writeInt(tabY); @@ -162,24 +165,24 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab }); } - public void toBuffer(PacketByteBuf buffer) { - buffer.writeText(title); + public void toBuffer(RegistryByteBuf buffer) { + TextCodecs.PACKET_CODEC.encode(buffer, title); buffer.writeInt(level); buffer.writeInt(color); buffer.writeCollection(elements, Element::write); } public static void write(PacketByteBuf buffer, Page page) { - page.toBuffer(buffer); + page.toBuffer((RegistryByteBuf)buffer); } } private interface Element { - void toBuffer(PacketByteBuf buffer); + void toBuffer(RegistryByteBuf buffer); record Image (Identifier texture, Bounds bounds, Flow flow) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(0); buffer.writeIdentifier(texture); boundsToBuffer(bounds, buffer); @@ -189,7 +192,7 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab record Multi(int count, Element element) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeVarInt(count); element.toBuffer(buffer); } @@ -197,7 +200,7 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab record Id(byte id, Identifier value) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(id); buffer.writeIdentifier(value); } @@ -205,18 +208,18 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab record Stack (IngredientWithSpell ingredient, Bounds bounds) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(2); - ingredient.write(buffer); + IngredientWithSpell.PACKET_CODEC.encode(buffer, ingredient); boundsToBuffer(bounds, buffer); } } record TextBlock (Text text) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(3); - buffer.writeText(text); + TextCodecs.PACKET_CODEC.encode(buffer, text); } } @@ -241,14 +244,14 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab } @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(5); - buffer.writeCollection(commands, (b, c) -> c.toBuffer(b)); + buffer.writeCollection(commands, (b, c) -> c.toBuffer(buffer)); } record Set(int x, int y, int z, BlockState state) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(1); buffer.writeInt(x); buffer.writeInt(y); @@ -259,7 +262,7 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab } record Fill(int x1, int y1, int z1, int x2, int y2, int z2, BlockState state) implements Element { @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(2); buffer.writeInt(x1); buffer.writeInt(y1); @@ -293,14 +296,14 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab } @Override - public void toBuffer(PacketByteBuf buffer) { + public void toBuffer(RegistryByteBuf buffer) { buffer.writeByte(4); - buffer.writeCollection(entries, (b, c) -> c.toBuffer(b)); + buffer.writeCollection(entries, (b, c) -> c.toBuffer(buffer)); } } static void write(PacketByteBuf buffer, Element element) { - element.toBuffer(buffer); + element.toBuffer((RegistryByteBuf)buffer); } @Deprecated @@ -309,14 +312,14 @@ public class SpellbookChapterLoader extends JsonDataLoader implements Identifiab JsonObject el = JsonHelper.asObject(json, "element"); if (el.has("texture")) { return new Image( - new Identifier(JsonHelper.getString(el, "texture")), + Identifier.of(JsonHelper.getString(el, "texture")), boundsFromJson(el), Flow.valueOf(JsonHelper.getString(el, "flow", "RIGHT")) ); } if (el.has("recipe")) { - return new Id((byte)1, new Identifier(JsonHelper.getString(el, "recipe"))); + return new Id((byte)1, Identifier.of(JsonHelper.getString(el, "recipe"))); } if (el.has("item")) { diff --git a/src/main/java/com/minelittlepony/unicopia/container/SpellbookScreenHandler.java b/src/main/java/com/minelittlepony/unicopia/container/SpellbookScreenHandler.java index 4e53efe2..56efccbf 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/SpellbookScreenHandler.java +++ b/src/main/java/com/minelittlepony/unicopia/container/SpellbookScreenHandler.java @@ -18,6 +18,7 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.CraftingResultInventory; import net.minecraft.inventory.Inventory; +import net.minecraft.item.Equipment; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.packet.s2c.play.ScreenHandlerSlotUpdateS2CPacket; @@ -59,8 +60,8 @@ public class SpellbookScreenHandler extends ScreenHandler { @Nullable public UUID entityId; - protected SpellbookScreenHandler(int syncId, PlayerInventory inv, PacketByteBuf buf) { - this(syncId, inv, ScreenHandlerContext.EMPTY, new SpellbookState().fromPacket(buf), null); + protected SpellbookScreenHandler(int syncId, PlayerInventory inv, SpellbookState state) { + this(syncId, inv, ScreenHandlerContext.EMPTY, state, null); } public SpellbookScreenHandler(int syncId, PlayerInventory inv, ScreenHandlerContext context, SpellbookState state, UUID entityId) { @@ -121,7 +122,8 @@ public class SpellbookScreenHandler extends ScreenHandler { @Override public boolean canInsert(ItemStack stack) { - return eq == MobEntity.getPreferredEquipmentSlot(stack); + Equipment equipment = Equipment.fromStack(stack); + return equipment != null && eq == equipment.getSlotType(); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/container/SpellbookState.java b/src/main/java/com/minelittlepony/unicopia/container/SpellbookState.java index 9fedcffc..727cf520 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/SpellbookState.java +++ b/src/main/java/com/minelittlepony/unicopia/container/SpellbookState.java @@ -10,10 +10,16 @@ import com.minelittlepony.unicopia.util.NbtSerialisable; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Identifier; import net.minecraft.util.math.MathHelper; public class SpellbookState extends Synchronizable implements NbtSerialisable { + // TODO: SpellbookState needs a packet codec + public static final PacketCodec PACKET_CODEC = null; + public static final Identifier CRAFTING_ID = Unicopia.id("crafting"); public static final Identifier PROFILE_ID = Unicopia.id("profile"); public static final Identifier TRAIT_DEX_ID = Unicopia.id("traits"); @@ -64,23 +70,23 @@ public class SpellbookState extends Synchronizable implements Nb } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { currentPageId.ifPresent(id -> compound.putString("current_page", id.toString())); NbtCompound states = new NbtCompound(); compound.put("states", states); this.states.forEach((id, page) -> { - states.put(id.toString(), page.toNBT()); + states.put(id.toString(), page.toNBT(lookup)); }); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { currentPageId = compound.contains("current_page", NbtElement.STRING_TYPE) ? Optional.ofNullable(Identifier.tryParse(compound.getString("current_page"))) : Optional.empty(); NbtCompound states = compound.getCompound("states"); states.getKeys().stream().forEach(key -> { Identifier id = Identifier.tryParse(key); if (id != null) { - getState(id).fromNBT(states.getCompound(key)); + getState(id).fromNBT(states.getCompound(key), lookup); } }); } @@ -122,12 +128,12 @@ public class SpellbookState extends Synchronizable implements Nb } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putInt("offset", offset); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { offset = compound.getInt("offset"); } } diff --git a/src/main/java/com/minelittlepony/unicopia/container/UScreenHandlers.java b/src/main/java/com/minelittlepony/unicopia/container/UScreenHandlers.java index f62a097a..a13d837b 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/UScreenHandlers.java +++ b/src/main/java/com/minelittlepony/unicopia/container/UScreenHandlers.java @@ -10,7 +10,7 @@ import net.minecraft.resource.featuretoggle.FeatureFlags; import net.minecraft.registry.Registries; public interface UScreenHandlers { - ScreenHandlerType SPELL_BOOK = register("spell_book", new ExtendedScreenHandlerType<>(SpellbookScreenHandler::new)); + ScreenHandlerType SPELL_BOOK = register("spell_book", new ExtendedScreenHandlerType<>(SpellbookScreenHandler::new, SpellbookState.PACKET_CODEC)); ScreenHandlerType SHAPING_BENCH = register("shaping_bench", new ScreenHandlerType<>(ShapingBenchScreenHandler::new, FeatureFlags.VANILLA_FEATURES)); static ScreenHandlerType register(String name, ScreenHandlerType type) { diff --git a/src/main/java/com/minelittlepony/unicopia/container/inventory/OutputSlot.java b/src/main/java/com/minelittlepony/unicopia/container/inventory/OutputSlot.java index c28605f1..e7ff5d1a 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/inventory/OutputSlot.java +++ b/src/main/java/com/minelittlepony/unicopia/container/inventory/OutputSlot.java @@ -33,7 +33,7 @@ public class OutputSlot extends CraftingResultSlot implements SpellbookSlot { public void setStack(ItemStack stack) { if (!stack.isEmpty() && !ItemStack.areEqual(stack, getStack())) { BufferedExecutor.bufferExecution(player, () -> { - player.playSound(stack.getItem() == UItems.BOTCHED_GEM ? USounds.GUI_ABILITY_FAIL : USounds.GUI_SPELL_CRAFT_SUCCESS, SoundCategory.MASTER, 1, 0.3F); + player.playSoundToPlayer(stack.getItem() == UItems.BOTCHED_GEM ? USounds.GUI_ABILITY_FAIL : USounds.GUI_SPELL_CRAFT_SUCCESS, SoundCategory.MASTER, 1, 0.3F); }); } super.setStack(stack); diff --git a/src/main/java/com/minelittlepony/unicopia/container/inventory/SpellbookInventory.java b/src/main/java/com/minelittlepony/unicopia/container/inventory/SpellbookInventory.java index 10a8816d..259e05f6 100644 --- a/src/main/java/com/minelittlepony/unicopia/container/inventory/SpellbookInventory.java +++ b/src/main/java/com/minelittlepony/unicopia/container/inventory/SpellbookInventory.java @@ -6,9 +6,10 @@ import com.minelittlepony.unicopia.util.InventoryUtil; import net.minecraft.inventory.CraftingInventory; import net.minecraft.item.ItemStack; +import net.minecraft.recipe.input.RecipeInput; import net.minecraft.screen.slot.Slot; -public class SpellbookInventory extends CraftingInventory { +public class SpellbookInventory extends CraftingInventory implements RecipeInput { private final SpellbookScreenHandler handler; public SpellbookInventory(SpellbookScreenHandler handler, int width, int height) { @@ -40,4 +41,14 @@ public class SpellbookInventory extends CraftingInventory { .toArray(SpellTraits[]::new) ); } + + @Override + public ItemStack getStackInSlot(int slot) { + return this.getStack(slot); + } + + @Override + public int getSize() { + return size(); + } } \ No newline at end of file diff --git a/src/main/java/com/minelittlepony/unicopia/datagen/providers/AdvancementDisplayBuilder.java b/src/main/java/com/minelittlepony/unicopia/datagen/providers/AdvancementDisplayBuilder.java index be9fdd5f..2e33aff6 100644 --- a/src/main/java/com/minelittlepony/unicopia/datagen/providers/AdvancementDisplayBuilder.java +++ b/src/main/java/com/minelittlepony/unicopia/datagen/providers/AdvancementDisplayBuilder.java @@ -20,7 +20,7 @@ import net.minecraft.util.Identifier; import net.minecraft.util.Util; public class AdvancementDisplayBuilder { - private static final Identifier BACKGROUND = new Identifier("textures/gui/advancements/backgrounds/stone.png"); + private static final Identifier BACKGROUND = Identifier.ofVanilla("textures/gui/advancements/backgrounds/stone.png"); public static AdvancementDisplayBuilder create(ItemConvertible icon) { return new AdvancementDisplayBuilder(icon, Advancement.Builder.create(), false, false, false); diff --git a/src/main/java/com/minelittlepony/unicopia/datagen/providers/FoodGroupsGenerator.java b/src/main/java/com/minelittlepony/unicopia/datagen/providers/FoodGroupsGenerator.java index 47864d46..c2196b79 100644 --- a/src/main/java/com/minelittlepony/unicopia/datagen/providers/FoodGroupsGenerator.java +++ b/src/main/java/com/minelittlepony/unicopia/datagen/providers/FoodGroupsGenerator.java @@ -15,9 +15,10 @@ import com.minelittlepony.unicopia.diet.affliction.StatusEffectAffliction; import com.minelittlepony.unicopia.entity.effect.UEffects; import com.minelittlepony.unicopia.item.UFoodComponents; +import net.minecraft.component.type.FoodComponent; +import net.minecraft.component.type.FoodComponents; import net.minecraft.entity.effect.StatusEffects; -import net.minecraft.item.FoodComponent; -import net.minecraft.item.FoodComponents; + import net.minecraft.item.Item; import net.minecraft.registry.tag.ItemTags; import net.minecraft.registry.tag.TagKey; diff --git a/src/main/java/com/minelittlepony/unicopia/datagen/providers/ItemModels.java b/src/main/java/com/minelittlepony/unicopia/datagen/providers/ItemModels.java index 06d35675..5cf0dc60 100644 --- a/src/main/java/com/minelittlepony/unicopia/datagen/providers/ItemModels.java +++ b/src/main/java/com/minelittlepony/unicopia/datagen/providers/ItemModels.java @@ -18,16 +18,16 @@ import net.minecraft.util.Identifier; interface ItemModels { Model GENERATED = net.minecraft.data.client.Models.GENERATED; - Model CHEST = item(new Identifier("chest"), TextureKey.PARTICLE); - Model BUILTIN_ENTITY = new Model(Optional.of(new Identifier("builtin/entity")), Optional.empty()); + Model CHEST = item(Identifier.ofVanilla("chest"), TextureKey.PARTICLE); + Model BUILTIN_ENTITY = new Model(Optional.of(Identifier.ofVanilla("builtin/entity")), Optional.empty()); Model TEMPLATE_AMULET = item("template_amulet", TextureKey.LAYER0); Model TEMPLATE_EYEWEAR = item("template_eyewear", TextureKey.LAYER0); - Model TEMPLATE_SPAWN_EGG = item(new Identifier("template_spawn_egg")); + Model TEMPLATE_SPAWN_EGG = item(Identifier.ofVanilla("template_spawn_egg")); Model TEMPLATE_MUG = item("template_mug", TextureKey.LAYER0); Model TEMPLATE_PILLAR = item("template_pillar", TextureKey.TOP, TextureKey.BOTTOM, TextureKey.SIDE, TextureKey.END); Model HANDHELD_STAFF = item("handheld_staff", TextureKey.LAYER0); - Model TRIDENT_THROWING = item(new Identifier("trident_throwing"), TextureKey.LAYER0); - Model TRIDENT_IN_HAND = item(new Identifier("trident_in_hand"), TextureKey.LAYER0); + Model TRIDENT_THROWING = item(Identifier.ofVanilla("trident_throwing"), TextureKey.LAYER0); + Model TRIDENT_IN_HAND = item(Identifier.ofVanilla("trident_in_hand"), TextureKey.LAYER0); static Model item(String parent, TextureKey ... requiredTextureKeys) { return new Model(Optional.of(Unicopia.id("item/" + parent)), Optional.empty(), requiredTextureKeys); diff --git a/src/main/java/com/minelittlepony/unicopia/diet/FoodAttributes.java b/src/main/java/com/minelittlepony/unicopia/diet/FoodAttributes.java index d1682982..a5a9b9a5 100644 --- a/src/main/java/com/minelittlepony/unicopia/diet/FoodAttributes.java +++ b/src/main/java/com/minelittlepony/unicopia/diet/FoodAttributes.java @@ -2,59 +2,31 @@ package com.minelittlepony.unicopia.diet; import java.util.List; -import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.entity.effect.StatusEffectInstance; -import net.minecraft.item.FoodComponent; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.component.type.FoodComponent; +import net.minecraft.item.ItemStack; +import net.minecraft.network.RegistryByteBuf; final class FoodAttributes { static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codec.INT.fieldOf("hunger").forGetter(FoodComponent::getHunger), - Codec.FLOAT.fieldOf("saturation").forGetter(FoodComponent::getSaturationModifier), - Codec.BOOL.optionalFieldOf("petFood", false).forGetter(FoodComponent::isMeat), - Codec.BOOL.optionalFieldOf("fastFood", false).forGetter(FoodComponent::isAlwaysEdible), - Codec.BOOL.optionalFieldOf("eatenQuickly", false).forGetter(FoodComponent::isSnack) - ).apply(instance, FoodAttributes::create)); + Codec.INT.fieldOf("hunger").forGetter(FoodComponent::nutrition), + Codec.FLOAT.fieldOf("saturation").forGetter(FoodComponent::saturation), + Codec.BOOL.optionalFieldOf("fastFood", false).forGetter(FoodComponent::canAlwaysEat), + Codec.BOOL.optionalFieldOf("eatenQuickly", false).forGetter(food -> food.eatSeconds() < 1.6F), + ItemStack.CODEC.optionalFieldOf("usingConvertsInto").forGetter(FoodComponent::usingConvertsTo) + ).apply(instance, (nutrition, saturation, fastFood, eatenQuickly, convertsInto) -> { + return new FoodComponent(nutrition, saturation, fastFood, eatenQuickly ? 0.8F : 1.6F, convertsInto, List.of()); + })); - static FoodComponent create(int hunger, float saturation, boolean petFood, boolean fastFood, boolean eatenQuickly) { - return create(hunger, saturation, petFood, fastFood, eatenQuickly, List.of()).build(); + @Deprecated + static FoodComponent read(RegistryByteBuf buffer) { + return FoodComponent.PACKET_CODEC.decode(buffer); } - static FoodComponent.Builder create(int hunger, float saturation, boolean petFood, boolean fastFood, boolean eatenQuickly, List> effects) { - var builder = new FoodComponent.Builder() - .hunger(hunger) - .saturationModifier(saturation); - if (petFood) { - builder.meat(); - } - if (fastFood) { - builder.alwaysEdible(); - } - if (eatenQuickly) { - builder.snack(); - } - for (var effect : effects) { - builder.statusEffect(effect.getFirst(), effect.getSecond()); - } - return builder; - } - - static FoodComponent.Builder copy(FoodComponent food) { - return create(food.getHunger(), food.getSaturationModifier(), food.isMeat(), food.isAlwaysEdible(), food.isSnack(), food.getStatusEffects()); - } - - static FoodComponent read(PacketByteBuf buffer) { - return create(buffer.readInt(), buffer.readFloat(), buffer.readBoolean(), buffer.readBoolean(), buffer.readBoolean()); - } - - static void write(PacketByteBuf buffer, FoodComponent food) { - buffer.writeInt(food.getHunger()); - buffer.writeFloat(food.getSaturationModifier()); - buffer.writeBoolean(food.isMeat()); - buffer.writeBoolean(food.isAlwaysEdible()); - buffer.writeBoolean(food.isSnack()); + @Deprecated + static void write(RegistryByteBuf buffer, FoodComponent food) { + FoodComponent.PACKET_CODEC.encode(buffer, food); } } diff --git a/src/main/java/com/minelittlepony/unicopia/diet/FoodGroupEffects.java b/src/main/java/com/minelittlepony/unicopia/diet/FoodGroupEffects.java index ad207ed1..ae363418 100644 --- a/src/main/java/com/minelittlepony/unicopia/diet/FoodGroupEffects.java +++ b/src/main/java/com/minelittlepony/unicopia/diet/FoodGroupEffects.java @@ -10,8 +10,7 @@ import com.minelittlepony.unicopia.item.UFoodComponents; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.item.FoodComponent; +import net.minecraft.component.type.FoodComponent; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; diff --git a/src/main/java/com/minelittlepony/unicopia/entity/EntityReference.java b/src/main/java/com/minelittlepony/unicopia/entity/EntityReference.java index 3f6e9ca0..48f05e87 100644 --- a/src/main/java/com/minelittlepony/unicopia/entity/EntityReference.java +++ b/src/main/java/com/minelittlepony/unicopia/entity/EntityReference.java @@ -16,6 +16,7 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Util; import net.minecraft.util.math.Vec3d; @@ -31,11 +32,11 @@ import net.minecraft.world.World; * @param The type of the entity this reference points to. */ public class EntityReference implements NbtSerialisable, TrackableObject> { - private static final Serializer SERIALIZER = Serializer.of(EntityReference::new); + private static final Serializer SERIALIZER = Serializer.of(EntityReference::new); @SuppressWarnings("unchecked") - public static Serializer> getSerializer() { - return (Serializer>)SERIALIZER; + public static Serializer> getSerializer() { + return (Serializer>)SERIALIZER; } @Nullable @@ -51,8 +52,8 @@ public class EntityReference implements NbtSerialisable, Track set(entity); } - public EntityReference(NbtCompound nbt) { - fromNBT(nbt); + public EntityReference(NbtCompound nbt, WrapperLookup lookup) { + fromNBT(nbt, lookup); } @SuppressWarnings("unchecked") @@ -110,12 +111,12 @@ public class EntityReference implements NbtSerialisable, Track } @Override - public void toNBT(NbtCompound tag) { + public void toNBT(NbtCompound tag, WrapperLookup lookup) { getTarget().ifPresent(ref -> ref.toNBT(tag)); } @Override - public void fromNBT(NbtCompound tag) { + public void fromNBT(NbtCompound tag, WrapperLookup lookup) { this.reference = tag.contains("uuid") ? new EntityValues<>(tag) : null; this.dirty = true; } @@ -135,13 +136,13 @@ public class EntityReference implements NbtSerialisable, Track } @Override - public NbtCompound writeTrackedNbt() { - return toNBT(); + public NbtCompound writeTrackedNbt(WrapperLookup lookup) { + return toNBT(lookup); } @Override - public void readTrackedNbt(NbtCompound compound) { - fromNBT(compound); + public void readTrackedNbt(NbtCompound compound, WrapperLookup lookup) { + fromNBT(compound, lookup); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/entity/player/PlayerDimensions.java b/src/main/java/com/minelittlepony/unicopia/entity/player/PlayerDimensions.java index 491a66fd..5a2478e0 100644 --- a/src/main/java/com/minelittlepony/unicopia/entity/player/PlayerDimensions.java +++ b/src/main/java/com/minelittlepony/unicopia/entity/player/PlayerDimensions.java @@ -22,10 +22,10 @@ public final class PlayerDimensions { return getPredicate() .flatMap(e -> e.getTargetEyeHeight(pony)) .filter(h -> h > 0) - .or(() -> physics.isFlyingSurvival ? FLYING_EYE_HEIGHT : physics.isGravityNegative() ? Optional.of(dimensions.height) : Optional.empty()) + .or(() -> physics.isFlyingSurvival ? FLYING_EYE_HEIGHT : physics.isGravityNegative() ? Optional.of(dimensions.eyeHeight()) : Optional.empty()) .map(h -> { if (physics.isGravityNegative()) { - return dimensions.height - h + 0.1F; + return dimensions.eyeHeight() - h + 0.1F; } return h; }); @@ -35,7 +35,7 @@ public final class PlayerDimensions { return getPredicate() .flatMap(e -> e.getTargetDimensions(pony)) .or(() -> physics.isFlyingSurvival ? FLYING_DIMENSIONS : Optional.empty()) - .filter(d -> d.height > 0 && d.width > 0); + .filter(d -> d.height() > 0 && d.width() > 0); } Optional getPredicate() { diff --git a/src/main/java/com/minelittlepony/unicopia/item/HeavyProjectileItem.java b/src/main/java/com/minelittlepony/unicopia/item/HeavyProjectileItem.java index e76a2920..25283025 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/HeavyProjectileItem.java +++ b/src/main/java/com/minelittlepony/unicopia/item/HeavyProjectileItem.java @@ -7,12 +7,13 @@ import com.minelittlepony.unicopia.projectile.PhysicsBodyProjectileEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.PersistentProjectileEntity; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.sound.SoundEvent; import net.minecraft.world.World; public class HeavyProjectileItem extends ProjectileItem { - public HeavyProjectileItem(Settings settings, float projectileDamage) { + public HeavyProjectileItem(Item.Settings settings, float projectileDamage) { super(settings, projectileDamage); } diff --git a/src/main/java/com/minelittlepony/unicopia/item/MuffinItem.java b/src/main/java/com/minelittlepony/unicopia/item/MuffinItem.java index 260f7360..aa7d1ce4 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/MuffinItem.java +++ b/src/main/java/com/minelittlepony/unicopia/item/MuffinItem.java @@ -6,11 +6,12 @@ import com.minelittlepony.unicopia.advancement.UCriteria; import com.minelittlepony.unicopia.projectile.PhysicsBodyProjectileEntity; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class MuffinItem extends HeavyProjectileItem { - public MuffinItem(Settings settings, float projectileDamage) { + public MuffinItem(Item.Settings settings, float projectileDamage) { super(settings, projectileDamage); } diff --git a/src/main/java/com/minelittlepony/unicopia/item/ProjectileItem.java b/src/main/java/com/minelittlepony/unicopia/item/ProjectileItem.java index 43c3608a..9a2022e9 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/ProjectileItem.java +++ b/src/main/java/com/minelittlepony/unicopia/item/ProjectileItem.java @@ -12,7 +12,7 @@ abstract class ProjectileItem extends Item implements Projectile { private final float projectileDamage; - public ProjectileItem(Settings settings, float projectileDamage) { + public ProjectileItem(Item.Settings settings, float projectileDamage) { super(settings); this.projectileDamage = projectileDamage; Projectile.makeDispensable(this); @@ -20,8 +20,11 @@ abstract class ProjectileItem extends Item implements Projectile { @Override public TypedActionResult use(World world, PlayerEntity player, Hand hand) { - if (isFood() && !player.shouldCancelInteraction()) { - return super.use(world, player, hand); + if (!player.shouldCancelInteraction()) { + TypedActionResult result = super.use(world, player, hand); + if (result.getResult().isAccepted()) { + return result; + } } return triggerThrow(world, player, hand); diff --git a/src/main/java/com/minelittlepony/unicopia/item/UFoodComponents.java b/src/main/java/com/minelittlepony/unicopia/item/UFoodComponents.java index f278d3ad..e5c9919c 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/UFoodComponents.java +++ b/src/main/java/com/minelittlepony/unicopia/item/UFoodComponents.java @@ -1,9 +1,9 @@ package com.minelittlepony.unicopia.item; +import net.minecraft.component.type.FoodComponent; +import net.minecraft.component.type.FoodComponents; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; -import net.minecraft.item.FoodComponent; -import net.minecraft.item.FoodComponents; public interface UFoodComponents { FoodComponent OATS = builder(1, 0.7F).build(); @@ -32,12 +32,11 @@ public interface UFoodComponents { FoodComponent FRIED_EGG = builder(4, 0.4F).build(); FoodComponent ROTTEN_PUFFERFISH = new FoodComponent.Builder() - .hunger(4) + .nutrition(4) .saturationModifier(0.1F) .statusEffect(new StatusEffectInstance(StatusEffects.POISON, 1200, 1), 1) .statusEffect(new StatusEffectInstance(StatusEffects.HUNGER, 300, 2), 1) .statusEffect(new StatusEffectInstance(StatusEffects.NAUSEA, 300, 0), 1) - .meat() .build(); FoodComponent COOKED_PUFFERFISH = builder(5, 0.6F) .statusEffect(new StatusEffectInstance(StatusEffects.POISON, 1200, 1), 0.2F) @@ -45,7 +44,7 @@ public interface UFoodComponents { .statusEffect(new StatusEffectInstance(StatusEffects.NAUSEA, 300, 0), 0.4F) .build(); - FoodComponent WORMS = builder(1, 1.5F).alwaysEdible().meat().build(); + FoodComponent WORMS = builder(1, 1.5F).alwaysEdible().build(); FoodComponent INSECTS = builder(1, 0).alwaysEdible().build(); FoodComponent TOAST = builder(1, 0.6F).alwaysEdible().snack().build(); @@ -79,7 +78,7 @@ public interface UFoodComponents { static FoodComponent.Builder builder(int hunger, float saturation) { return new FoodComponent.Builder() - .hunger(hunger) + .nutrition(hunger) .saturationModifier(saturation); } } diff --git a/src/main/java/com/minelittlepony/unicopia/item/UItems.java b/src/main/java/com/minelittlepony/unicopia/item/UItems.java index 083e4ef8..1c00a00a 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/UItems.java +++ b/src/main/java/com/minelittlepony/unicopia/item/UItems.java @@ -18,12 +18,12 @@ import com.terraformersmc.terraform.boat.api.TerraformBoatTypeRegistry; import com.terraformersmc.terraform.boat.api.item.TerraformBoatItemHelper; import net.minecraft.block.Blocks; +import net.minecraft.component.type.FoodComponents; import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.vehicle.BoatEntity; import net.minecraft.item.*; import net.minecraft.item.Item.Settings; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.registry.CompostingChanceRegistry; import net.fabricmc.fabric.api.registry.FuelRegistry; import net.minecraft.sound.SoundEvent; @@ -92,7 +92,7 @@ public interface UItems { */ Item HORSE_SHOE_FRIES = register("horse_shoe_fries", new Item(new Item.Settings().maxCount(32).food(UFoodComponents.HAY_FRIES)), ItemGroups.FOOD_AND_DRINK); - Item WHEAT_WORMS = register("wheat_worms", new Item(new Item.Settings().maxCount(16).food(UFoodComponents.WORMS)), ItemGroups.NATURAL); + Item WHEAT_WORMS = register("wheat_worms", new Item(new Item.Settings().maxCount(16).food(UFoodComponents.WORMS)), ItemGroups.NATURAL); //ItemTags.WOLF_FOOD Item BAITED_FISHING_ROD = register("baited_fishing_rod", new BaitedFishingRodItem(new Item.Settings().maxDamage(64)), ItemGroups.TOOLS); Item MUFFIN = register("muffin", new MuffinItem(new Item.Settings().maxCount(32).food(FoodComponents.BREAD), 0), ItemGroups.FOOD_AND_DRINK); Item PINECONE = register("pinecone", new ForageableItem(new Item.Settings().food(UFoodComponents.PINECONE).maxCount(16), () -> Blocks.SPRUCE_LEAVES), ItemGroups.FOOD_AND_DRINK); @@ -234,7 +234,7 @@ public interface UItems { Item ROTTEN_COD = register("rotten_cod", new Item(new Item.Settings().food(FoodComponents.ROTTEN_FLESH)), ItemGroups.FOOD_AND_DRINK); Item ROTTEN_SALMON = register("rotten_salmon", new Item(new Item.Settings().food(FoodComponents.ROTTEN_FLESH)), ItemGroups.FOOD_AND_DRINK); Item ROTTEN_TROPICAL_FISH = register("rotten_tropical_fish", new Item(new Item.Settings().food(FoodComponents.ROTTEN_FLESH)), ItemGroups.FOOD_AND_DRINK); - Item ROTTEN_PUFFERFISH = register("rotten_pufferfish", new Item(new Item.Settings().food(UFoodComponents.ROTTEN_PUFFERFISH)), ItemGroups.FOOD_AND_DRINK); + Item ROTTEN_PUFFERFISH = register("rotten_pufferfish", new Item(new Item.Settings().food(UFoodComponents.ROTTEN_PUFFERFISH)), ItemGroups.FOOD_AND_DRINK); //ItemTags.WOLF_FOOD Item COOKED_TROPICAL_FISH = register("cooked_tropical_fish", new Item(new Item.Settings().food(FoodComponents.COOKED_COD)), ItemGroups.FOOD_AND_DRINK); Item COOKED_PUFFERFISH = register("cooked_pufferfish", new Item(new Item.Settings().food(UFoodComponents.COOKED_PUFFERFISH)), ItemGroups.FOOD_AND_DRINK); diff --git a/src/main/java/com/minelittlepony/unicopia/item/enchantment/UEnchantments.java b/src/main/java/com/minelittlepony/unicopia/item/enchantment/UEnchantments.java index a5143773..69c5b108 100644 --- a/src/main/java/com/minelittlepony/unicopia/item/enchantment/UEnchantments.java +++ b/src/main/java/com/minelittlepony/unicopia/item/enchantment/UEnchantments.java @@ -9,13 +9,12 @@ import com.minelittlepony.unicopia.entity.mob.UEntityAttributes; import com.minelittlepony.unicopia.item.enchantment.SimpleEnchantment.Options; import net.minecraft.enchantment.Enchantment; -import net.minecraft.enchantment.Enchantment.Rarity; import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.attribute.EntityAttributeModifier.Operation; -import net.minecraft.enchantment.EnchantmentTarget; import net.minecraft.registry.Registry; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.registry.Registries; public interface UEnchantments { @@ -29,7 +28,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment GEM_FINDER = register("gem_finder", new GemFindingEnchantment(Options.create(EnchantmentTarget.DIGGER, UEnchantmentValidSlots.HANDS).rarity(Rarity.RARE).maxLevel(3).treasure().traded().table())); + RegistryEntry GEM_FINDER = register("gem_finder", new GemFindingEnchantment(Options.create(EnchantmentTarget.DIGGER, UEnchantmentValidSlots.HANDS).rarity(Rarity.RARE).maxLevel(3).treasure().traded().table())); /** * Protects against wall collisions and earth pony attacks! @@ -38,7 +37,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment PADDED = register("padded", new SimpleEnchantment(Options.armor().rarity(Rarity.UNCOMMON).maxLevel(3).traded().table())); + RegistryEntry PADDED = register("padded", new SimpleEnchantment(Options.armor().rarity(Rarity.UNCOMMON).maxLevel(3).traded().table())); /** * Allows non-flying races to mine and interact with cloud blocks @@ -47,7 +46,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment FEATHER_TOUCH = register("feather_touch", new SimpleEnchantment(Options.create(EnchantmentTarget.BREAKABLE, UEnchantmentValidSlots.HANDS).rarity(Rarity.UNCOMMON).traded().table())); + RegistryEntry FEATHER_TOUCH = register("feather_touch", new SimpleEnchantment(Options.create(EnchantmentTarget.BREAKABLE, UEnchantmentValidSlots.HANDS).rarity(Rarity.UNCOMMON).traded().table())); /** * Heavy players move more slowly but are less likely to be flung around wildly. @@ -56,7 +55,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment HEAVY = register("heavy", new AttributedEnchantment(Options.armor().rarity(Rarity.RARE).maxLevel(4).traded().table())) + RegistryEntry HEAVY = register("heavy", new AttributedEnchantment(Options.armor().rarity(Rarity.RARE).maxLevel(4).traded().table())) .addModifier(EntityAttributes.GENERIC_MOVEMENT_SPEED, (user, level) -> { return new EntityAttributeModifier(UUID.fromString("a3d5a94f-4c40-48f6-a343-558502a13e10"), "Heavyness", (1 - level/(float)10) - 1, Operation.MULTIPLY_TOTAL); }); @@ -70,7 +69,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment HERDS = register("herds", new CollaboratorEnchantment(Options.create(EnchantmentTarget.WEAPON, EquipmentSlot.MAINHAND).rarity(Rarity.RARE).maxLevel(3).treasure().traded().table())); + RegistryEntry HERDS = register("herds", new CollaboratorEnchantment(Options.create(EnchantmentTarget.WEAPON, EquipmentSlot.MAINHAND).rarity(Rarity.RARE).maxLevel(3).treasure().traded().table())); /** * Alters gravity @@ -78,7 +77,7 @@ public interface UEnchantments { * Appears in: * - Trades */ - Enchantment REPULSION = register("repulsion", new AttributedEnchantment(Options.create(EnchantmentTarget.ARMOR_FEET, EquipmentSlot.FEET).rarity(Rarity.VERY_RARE).maxLevel(3).treasure().traded())) + RegistryEntry REPULSION = register("repulsion", new AttributedEnchantment(Options.create(EnchantmentTarget.ARMOR_FEET, EquipmentSlot.FEET).rarity(Rarity.VERY_RARE).maxLevel(3).treasure().traded())) .addModifier(UEntityAttributes.ENTITY_GRAVITY_MODIFIER, (user, level) -> { return new EntityAttributeModifier(UUID.fromString("1734bbd6-1916-4124-b710-5450ea70fbdb"), "Anti Grav", (0.5F - (0.375 * (level - 1))) - 1, Operation.MULTIPLY_TOTAL); }); @@ -88,7 +87,7 @@ public interface UEnchantments { * * Mobs really want your candy. You'd better give it to them. */ - Enchantment WANT_IT_NEED_IT = register("want_it_need_it", new WantItNeedItEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().treasure().traded())); + RegistryEntry WANT_IT_NEED_IT = register("want_it_need_it", new WantItNeedItEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().treasure().traded())); /** * Hahaha geddit? @@ -98,7 +97,7 @@ public interface UEnchantments { * Appears in: * - Trades */ - PoisonedJokeEnchantment POISONED_JOKE = register("poisoned_joke", new PoisonedJokeEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().traded())); + RegistryEntry POISONED_JOKE = register("poisoned_joke", new PoisonedJokeEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().traded())); /** * Who doesn't like a good freakout? @@ -106,7 +105,7 @@ public interface UEnchantments { * Appears in: * - Trades */ - Enchantment STRESSED = register("stressed", new StressfulEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().treasure().traded().maxLevel(3))); + RegistryEntry STRESSED = register("stressed", new StressfulEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).curse().treasure().traded().maxLevel(3))); /** * This item just wants to be held. @@ -115,7 +114,7 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment CLINGY = register("clingy", new SimpleEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).maxLevel(6).traded().table().treasure())); + RegistryEntry CLINGY = register("clingy", new SimpleEnchantment(Options.allItems().rarity(Rarity.VERY_RARE).maxLevel(6).traded().table().treasure())); /** * Items with loyalty are kept after death. @@ -124,7 +123,7 @@ public interface UEnchantments { * Appears in: * - Enchanting Table */ - Enchantment HEART_BOUND = register("heart_bound", new SimpleEnchantment(Options.create(EnchantmentTarget.VANISHABLE, UEnchantmentValidSlots.ANY).rarity(Rarity.UNCOMMON).maxLevel(5).treasure().table())); + RegistryEntry HEART_BOUND = register("heart_bound", new SimpleEnchantment(Options.create(EnchantmentTarget.VANISHABLE, UEnchantmentValidSlots.ANY).rarity(Rarity.UNCOMMON).maxLevel(5).treasure().table())); /** * Consumes drops whilst mining and produces experience instead @@ -133,12 +132,12 @@ public interface UEnchantments { * - Trades * - Enchanting Table */ - Enchantment CONSUMPTION = register("consumption", new ConsumptionEnchantment(Options.create(EnchantmentTarget.DIGGER, UEnchantmentValidSlots.HANDS).rarity(Rarity.VERY_RARE).treasure().table().traded())); + RegistryEntry CONSUMPTION = register("consumption", new ConsumptionEnchantment(Options.create(EnchantmentTarget.DIGGER, UEnchantmentValidSlots.HANDS).rarity(Rarity.VERY_RARE).treasure().table().traded())); static void bootstrap() { } static T register(String name, T enchantment) { REGISTRY.add(enchantment); - return Registry.register(Registries.ENCHANTMENT, Unicopia.id(name), enchantment); + return Registry.registerReference(Registries.ENCHANTMENT, Unicopia.id(name), enchantment); } } diff --git a/src/main/java/com/minelittlepony/unicopia/mixin/client/sodium/MixinSodiumWorldRenderer.java b/src/main/java/com/minelittlepony/unicopia/mixin/client/sodium/MixinSodiumWorldRenderer.java index fb9c23e0..847fe112 100644 --- a/src/main/java/com/minelittlepony/unicopia/mixin/client/sodium/MixinSodiumWorldRenderer.java +++ b/src/main/java/com/minelittlepony/unicopia/mixin/client/sodium/MixinSodiumWorldRenderer.java @@ -10,6 +10,7 @@ import com.minelittlepony.unicopia.client.ClientBlockDestructionManager; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.*; +import net.minecraft.entity.player.BlockBreakingInfo; @Pseudo @Mixin( diff --git a/src/main/java/com/minelittlepony/unicopia/mixin/trinkets/MixinTrinketInventory.java b/src/main/java/com/minelittlepony/unicopia/mixin/trinkets/MixinTrinketInventory.java index 4204107d..53bddf41 100644 --- a/src/main/java/com/minelittlepony/unicopia/mixin/trinkets/MixinTrinketInventory.java +++ b/src/main/java/com/minelittlepony/unicopia/mixin/trinkets/MixinTrinketInventory.java @@ -24,7 +24,7 @@ abstract class MixinTrinketInventory implements Inventory { int combinedCount = stack.getCount(); - if (ItemStack.canCombine(existingStack, stack)) { + if (ItemStack.areItemsAndComponentsEqual(existingStack, stack)) { combinedCount += existingStack.getCount(); } diff --git a/src/main/java/com/minelittlepony/unicopia/network/Channel.java b/src/main/java/com/minelittlepony/unicopia/network/Channel.java index ee3b3025..5cbe8e69 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/Channel.java +++ b/src/main/java/com/minelittlepony/unicopia/network/Channel.java @@ -21,7 +21,7 @@ public interface Channel { S2CPacketType SERVER_PLAYER_CAPABILITIES = SimpleNetworking.serverToClient(Unicopia.id("player_capabilities"), MsgPlayerCapabilities::new); S2CPacketType SERVER_BLOCK_DESTRUCTION = SimpleNetworking.serverToClient(Unicopia.id("block_destruction"), MsgBlockDestruction::new); - S2CPacketType CANCEL_PLAYER_ABILITY = SimpleNetworking.serverToClient(Unicopia.id("player_ability_cancel"), MsgCancelPlayerAbility::read); + S2CPacketType CANCEL_PLAYER_ABILITY = SimpleNetworking.serverToClient(Unicopia.id("player_ability_cancel"), MsgCancelPlayerAbility.PACKET_CODEC); S2CPacketType SERVER_REQUEST_PLAYER_LOOK = SimpleNetworking.serverToClient(Unicopia.id("request_player_look"), MsgCasterLookRequest::new); S2CPacketType UNLOCK_TRAITS = SimpleNetworking.serverToClient(Unicopia.id("unlock_traits"), MsgUnlockTraits::new); @@ -37,7 +37,7 @@ public interface Channel { S2CPacketType SERVER_SKY_ANGLE = SimpleNetworking.serverToClient(Unicopia.id("sky_angle"), MsgSkyAngle::new); S2CPacketType CONFIGURATION_CHANGE = SimpleNetworking.serverToClient(Unicopia.id("config"), MsgConfigurationChange::new); S2CPacketType SERVER_ZAP_STAGE = SimpleNetworking.serverToClient(Unicopia.id("zap_stage"), MsgZapAppleStage::new); - S2CPacketType SERVER_TRINKET_BROKEN = SimpleNetworking.serverToClient(Unicopia.id("trinket_broken"), MsgTrinketBroken::new); + S2CPacketType SERVER_TRINKET_BROKEN = SimpleNetworking.serverToClient(Unicopia.id("trinket_broken"), MsgTrinketBroken.PACKET_CODEC); static void bootstrap() { ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { @@ -48,16 +48,16 @@ public interface Channel { race = Race.UNSET; } if (race.isUnset()) { - sender.sendPacket(SERVER_SELECT_TRIBE.id(), new MsgTribeSelect(Race.allPermitted(handler.player), "gui.unicopia.tribe_selection.welcome").toBuffer()); + sender.sendPacket(SERVER_SELECT_TRIBE.toPacket(new MsgTribeSelect(Race.allPermitted(handler.player), "gui.unicopia.tribe_selection.welcome"))); } else { pony.setSpecies(race); Unicopia.LOGGER.info("Setting {}'s race to {} due to host setting", handler.player.getDisplayName().getString(), Race.REGISTRY.getId(race).toString()); } } - sender.sendPacket(SERVER_RESOURCES.id(), new MsgServerResources().toBuffer()); - sender.sendPacket(SERVER_SKY_ANGLE.id(), new MsgSkyAngle(UnicopiaWorldProperties.forWorld(handler.getPlayer().getServerWorld()).getTangentalSkyAngle()).toBuffer()); - sender.sendPacket(CONFIGURATION_CHANGE.id(), new MsgConfigurationChange(InteractionManager.getInstance().getSyncedConfig()).toBuffer()); - sender.sendPacket(SERVER_ZAP_STAGE.id(), new MsgZapAppleStage(ZapAppleStageStore.get(handler.player.getServerWorld()).getStage()).toBuffer()); + sender.sendPacket(SERVER_RESOURCES.toPacket(new MsgServerResources())); + sender.sendPacket(SERVER_SKY_ANGLE.toPacket(new MsgSkyAngle(UnicopiaWorldProperties.forWorld(handler.getPlayer().getServerWorld()).getTangentalSkyAngle()))); + sender.sendPacket(CONFIGURATION_CHANGE.toPacket(new MsgConfigurationChange(InteractionManager.getInstance().getSyncedConfig()))); + sender.sendPacket(SERVER_ZAP_STAGE.toPacket(new MsgZapAppleStage(ZapAppleStageStore.get(handler.player.getServerWorld()).getStage()))); }); } } diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgCancelPlayerAbility.java b/src/main/java/com/minelittlepony/unicopia/network/MsgCancelPlayerAbility.java index 40010b4f..edb69db1 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgCancelPlayerAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgCancelPlayerAbility.java @@ -1,18 +1,12 @@ package com.minelittlepony.unicopia.network; -import com.sollace.fabwork.api.packets.Packet; -import net.minecraft.network.PacketByteBuf; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.PacketCodec; /** * Sent to the client when an ability fails its server-side activation checks. */ -public final class MsgCancelPlayerAbility implements Packet { - static final MsgCancelPlayerAbility INSTANCE = new MsgCancelPlayerAbility(); - - static MsgCancelPlayerAbility read(PacketByteBuf buffer) { - return INSTANCE; - } - - @Override - public void toBuffer(PacketByteBuf buffer) { } +public final class MsgCancelPlayerAbility { + public static final MsgCancelPlayerAbility INSTANCE = new MsgCancelPlayerAbility(); + public static final PacketCodec PACKET_CODEC = PacketCodec.unit(INSTANCE); } diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgCasterLookRequest.java b/src/main/java/com/minelittlepony/unicopia/network/MsgCasterLookRequest.java index 96839624..34946aef 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgCasterLookRequest.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgCasterLookRequest.java @@ -33,7 +33,7 @@ public record MsgCasterLookRequest (UUID spellId) implements Packet { ) implements HandledPacket { Reply(PacketByteBuf buffer) { - this(buffer.readUuid(), Rot.SERIALIZER.read().apply(buffer)); + this(buffer.readUuid(), Rot.CODEC.decode(buffer)); } public Reply(OrientedSpell spell, Caster caster) { @@ -43,7 +43,7 @@ public record MsgCasterLookRequest (UUID spellId) implements Packet { @Override public void toBuffer(PacketByteBuf buffer) { buffer.writeUuid(spellId); - Rot.SERIALIZER.write().accept(buffer, rotation); + Rot.CODEC.encode(buffer, rotation); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgPlayerAbility.java b/src/main/java/com/minelittlepony/unicopia/network/MsgPlayerAbility.java index bbd5c309..53025eed 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgPlayerAbility.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgPlayerAbility.java @@ -10,6 +10,7 @@ import com.minelittlepony.unicopia.entity.player.Pony; import com.sollace.fabwork.api.packets.HandledPacket; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; import net.minecraft.server.network.ServerPlayerEntity; /** @@ -26,15 +27,16 @@ public record MsgPlayerAbility ( Ability power = (Ability) Abilities.REGISTRY.get(buffer.readIdentifier()); return new MsgPlayerAbility<>( power, - buffer.readOptional(power.getSerializer().read()), + buffer.readOptional(b -> ((PacketCodec)power.getSerializer()).decode(b)), ActivationType.of(buffer.readInt()) ); } + @SuppressWarnings("unchecked") @Override public void toBuffer(PacketByteBuf buffer) { buffer.writeIdentifier(Abilities.REGISTRY.getId(power)); - buffer.writeOptional(data, power.getSerializer().write()); + buffer.writeOptional(data, (b, d) -> ((PacketCodec)power.getSerializer()).encode(b, d)); buffer.writeInt(type.ordinal()); } diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgRequestSpeciesChange.java b/src/main/java/com/minelittlepony/unicopia/network/MsgRequestSpeciesChange.java index 0fe99689..c9990fc5 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgRequestSpeciesChange.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgRequestSpeciesChange.java @@ -22,13 +22,13 @@ public record MsgRequestSpeciesChange ( ) implements HandledPacket { MsgRequestSpeciesChange(PacketByteBuf buffer) { - this(buffer.readBoolean(), buffer.readRegistryValue(Race.REGISTRY)); + this(buffer.readBoolean(), Race.REGISTRY.get(buffer.readRegistryKey(Race.REGISTRY_KEY))); } @Override public void toBuffer(PacketByteBuf buffer) { buffer.writeBoolean(force); - buffer.writeRegistryValue(Race.REGISTRY, newRace); + buffer.writeRegistryKey(Race.REGISTRY.getKey(newRace).get()); } @Override diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgTribeSelect.java b/src/main/java/com/minelittlepony/unicopia/network/MsgTribeSelect.java index 401bf5ed..cf362f8a 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgTribeSelect.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgTribeSelect.java @@ -11,14 +11,14 @@ import net.minecraft.network.PacketByteBuf; public record MsgTribeSelect (Set availableRaces, String serverMessage) implements Packet { public MsgTribeSelect(PacketByteBuf buffer) { this( - buffer.readCollection(HashSet::new, buf -> buf.readRegistryValue(Race.REGISTRY)), + buffer.readCollection(HashSet::new, buf -> Race.REGISTRY.get(buf.readRegistryKey(Race.REGISTRY_KEY))), buffer.readString() ); } @Override public void toBuffer(PacketByteBuf buffer) { - buffer.writeCollection(availableRaces, (buf, race) -> buf.writeRegistryValue(Race.REGISTRY, race)); + buffer.writeCollection(availableRaces, (buf, race) -> buf.writeRegistryKey(Race.REGISTRY.getKey(race).get())); buffer.writeString(serverMessage); } } diff --git a/src/main/java/com/minelittlepony/unicopia/network/MsgTrinketBroken.java b/src/main/java/com/minelittlepony/unicopia/network/MsgTrinketBroken.java index 501be316..4d04138f 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/MsgTrinketBroken.java +++ b/src/main/java/com/minelittlepony/unicopia/network/MsgTrinketBroken.java @@ -1,21 +1,17 @@ package com.minelittlepony.unicopia.network; -import com.sollace.fabwork.api.packets.Packet; - import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; /** * Sent to the client when an item equipped in a trinket slot breaks */ -public record MsgTrinketBroken (ItemStack stack, int entityId) implements Packet { - public MsgTrinketBroken(PacketByteBuf buffer) { - this(buffer.readItemStack(), buffer.readInt()); - } - - @Override - public void toBuffer(PacketByteBuf buffer) { - buffer.writeItemStack(stack); - buffer.writeInt(entityId); - } +public record MsgTrinketBroken (ItemStack stack, int entityId) { + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + ItemStack.PACKET_CODEC, MsgTrinketBroken::stack, + PacketCodecs.INTEGER, MsgTrinketBroken::entityId, + MsgTrinketBroken::new + ); } diff --git a/src/main/java/com/minelittlepony/unicopia/network/track/DataTracker.java b/src/main/java/com/minelittlepony/unicopia/network/track/DataTracker.java index 1bc68115..b53fb7e5 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/track/DataTracker.java +++ b/src/main/java/com/minelittlepony/unicopia/network/track/DataTracker.java @@ -11,6 +11,7 @@ import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; public class DataTracker { private final List> codecs = new ObjectArrayList<>(); @@ -139,6 +140,8 @@ public class DataTracker { } static class Pair { + public static final PacketCodec> PACKET_CODEC = PacketCodec.ofStatic((buffer, pair) -> pair.write(buffer), Pair::new); + private final TrackableDataType type; public final int id; public T value; @@ -149,13 +152,13 @@ public class DataTracker { this.value = value; } - public Pair(PacketByteBuf buffer) { + private Pair(PacketByteBuf buffer) { this.id = buffer.readInt(); this.type = TrackableDataType.of(buffer); this.value = type.read(buffer); } - public void write(PacketByteBuf buffer) { + private void write(PacketByteBuf buffer) { buffer.writeInt(id); type.write(buffer, value); } diff --git a/src/main/java/com/minelittlepony/unicopia/network/track/MsgTrackedValues.java b/src/main/java/com/minelittlepony/unicopia/network/track/MsgTrackedValues.java index d9c405cc..610c346e 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/track/MsgTrackedValues.java +++ b/src/main/java/com/minelittlepony/unicopia/network/track/MsgTrackedValues.java @@ -9,12 +9,15 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; -import com.minelittlepony.unicopia.util.serialization.PacketCodec; +import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils; import com.sollace.fabwork.api.packets.HandledPacket; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.util.Uuids; public record MsgTrackedValues( int owner, @@ -24,16 +27,16 @@ public record MsgTrackedValues( public MsgTrackedValues(PacketByteBuf buffer) { this( buffer.readInt(), - buffer.readOptional(TrackerObjects::new), - buffer.readOptional(TrackerEntries::new) + TrackerObjects.OPTIONAL_PACKET_CODEC.decode(buffer), + TrackerEntries.OPTIONAL_PACKET_CODEC.decode(buffer) ); } @Override public void toBuffer(PacketByteBuf buffer) { buffer.writeInt(owner); - buffer.writeOptional(updatedObjects, (buf, obj) -> obj.write(buf)); - buffer.writeOptional(updatedTrackers, (buf, tracker) -> tracker.write(buf)); + TrackerObjects.OPTIONAL_PACKET_CODEC.encode(buffer, updatedObjects); + TrackerEntries.OPTIONAL_PACKET_CODEC.encode(buffer, updatedTrackers); } @Override @@ -45,37 +48,23 @@ public record MsgTrackedValues( } public record TrackerObjects(int id, Set removedValues, Map values) { - public TrackerObjects(PacketByteBuf buffer) { - this( - buffer.readInt(), - buffer.readCollection(HashSet::new, PacketByteBuf::readUuid), - buffer.readMap(HashMap::new, PacketByteBuf::readUuid, PacketCodec.RAW_BYTES::read) - ); - - } - - public void write(PacketByteBuf buffer) { - buffer.writeInt(id); - buffer.writeCollection(removedValues, PacketByteBuf::writeUuid); - buffer.writeMap(values, PacketByteBuf::writeUuid, PacketCodec.RAW_BYTES::write); - } + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.INTEGER, TrackerObjects::id, + Uuids.PACKET_CODEC.collect(PacketCodecs.toCollection(HashSet::new)), TrackerObjects::removedValues, + PacketCodecs.map(HashMap::new, Uuids.PACKET_CODEC, PacketCodecUtils.BUFFER), TrackerObjects::values, + TrackerObjects::new + ); + public static final PacketCodec> OPTIONAL_PACKET_CODEC = PacketCodecs.optional(PACKET_CODEC); } public record TrackerEntries(int id, boolean wipe, List> values, Map objects) { - public TrackerEntries(PacketByteBuf buffer) { - this( - buffer.readInt(), - buffer.readBoolean(), - buffer.readCollection(ArrayList::new, DataTracker.Pair::new), - buffer.readMap(PacketByteBuf::readInt, PacketCodec.RAW_BYTES::read) - ); - } - - public void write(PacketByteBuf buffer) { - buffer.writeInt(id); - buffer.writeBoolean(wipe); - buffer.writeCollection(values, (buf, pair) -> pair.write(buf)); - buffer.writeMap(objects, PacketByteBuf::writeInt, PacketCodec.RAW_BYTES::write); - } + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.INTEGER, TrackerEntries::id, + PacketCodecs.BOOL, TrackerEntries::wipe, + DataTracker.Pair.PACKET_CODEC.collect(PacketCodecs.toCollection(ArrayList::new)), TrackerEntries::values, + PacketCodecs.map(HashMap::new, PacketCodecs.INTEGER, PacketCodecUtils.BUFFER), TrackerEntries::objects, + TrackerEntries::new + ); + public static final PacketCodec> OPTIONAL_PACKET_CODEC = PacketCodecs.optional(PACKET_CODEC); } } diff --git a/src/main/java/com/minelittlepony/unicopia/network/track/TrackableDataType.java b/src/main/java/com/minelittlepony/unicopia/network/track/TrackableDataType.java index e918e3e7..b71c8e23 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/track/TrackableDataType.java +++ b/src/main/java/com/minelittlepony/unicopia/network/track/TrackableDataType.java @@ -2,7 +2,9 @@ package com.minelittlepony.unicopia.network.track; import com.minelittlepony.unicopia.Race; import com.minelittlepony.unicopia.Unicopia; -import com.minelittlepony.unicopia.util.serialization.PacketCodec; +import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils; + +import io.netty.buffer.ByteBuf; import java.util.Objects; import java.util.Optional; @@ -11,27 +13,30 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.registry.RegistryKey; import net.minecraft.util.Identifier; +import net.minecraft.util.Uuids; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -public record TrackableDataType(int id, PacketCodec codec) { +public record TrackableDataType(int id, PacketCodec codec) { private static final Int2ObjectMap> REGISTRY = new Int2ObjectOpenHashMap<>(); - public static final TrackableDataType INT = of(new Identifier("integer"), PacketCodec.INT); - public static final TrackableDataType FLOAT = of(new Identifier("float"), PacketCodec.FLOAT); - public static final TrackableDataType BOOLEAN = of(new Identifier("boolean"), PacketCodec.BOOLEAN); - public static final TrackableDataType UUID = of(new Identifier("uuid"), PacketCodec.UUID); - public static final TrackableDataType NBT = of(new Identifier("nbt"), PacketCodec.NBT); - public static final TrackableDataType COMPRESSED_NBT = of(new Identifier("compressed_nbt"), PacketCodec.COMPRESSED_NBT); - public static final TrackableDataType> RAW_BYTES = of(new Identifier("raw_bytes"), PacketCodec.RAW_BYTES.asOptional()); + public static final TrackableDataType INT = of(Identifier.of("integer"), PacketCodecs.INTEGER); + public static final TrackableDataType FLOAT = of(Identifier.of("float"), PacketCodecs.FLOAT); + public static final TrackableDataType BOOLEAN = of(Identifier.of("boolean"), PacketCodecs.BOOL); + public static final TrackableDataType UUID = of(Identifier.of("uuid"), Uuids.PACKET_CODEC); + public static final TrackableDataType NBT = of(Identifier.of("nbt"), PacketCodecs.NBT_COMPOUND); + public static final TrackableDataType COMPRESSED_NBT = of(Identifier.of("compressed_nbt"), PacketCodecs.NBT_COMPOUND); + public static final TrackableDataType> RAW_BYTES = of(Identifier.of("raw_bytes"), PacketCodecUtils.OPTIONAL_BUFFER); - public static final TrackableDataType> OPTIONAL_POS = of(new Identifier("optional_pos"), PacketCodec.OPTIONAL_POS); - public static final TrackableDataType> OPTIONAL_VECTOR = of(new Identifier("optional_vector"), PacketCodec.OPTIONAL_VECTOR); - private static final TrackableDataType>> OPTIONAL_REGISTRY_KEY = of(new Identifier("optional_registry_key"), PacketCodec.OPTIONAL_REGISTRY_KEY); + public static final TrackableDataType> OPTIONAL_POS = of(Identifier.of("optional_pos"), PacketCodecUtils.OPTIONAL_POS); + public static final TrackableDataType> OPTIONAL_VECTOR = of(Identifier.of("optional_vector"), PacketCodecUtils.OPTIONAL_VECTOR); + private static final TrackableDataType>> OPTIONAL_REGISTRY_KEY = of(Identifier.of("optional_registry_key"), PacketCodecUtils.OPTIONAL_REGISTRY_KEY); - public static final TrackableDataType RACE = TrackableDataType.of(Unicopia.id("race"), PacketCodec.ofRegistry(Race.REGISTRY)); + public static final TrackableDataType RACE = TrackableDataType.of(Unicopia.id("race"), PacketCodecs.registryValue(Race.REGISTRY_KEY)); @SuppressWarnings({ "rawtypes", "unchecked" }) public static TrackableDataType>> ofRegistryKey() { @@ -45,16 +50,16 @@ public record TrackableDataType(int id, PacketCodec codec) { } @SuppressWarnings("unchecked") - public static TrackableDataType of(Identifier typeName, PacketCodec codec) { - return (TrackableDataType)REGISTRY.computeIfAbsent(typeName.hashCode(), t -> new TrackableDataType<>(t, codec)); + public static TrackableDataType of(Identifier typeName, PacketCodec codec) { + return (TrackableDataType)REGISTRY.computeIfAbsent(typeName.hashCode(), t -> new TrackableDataType<>(t, (PacketCodec)codec)); } public T read(PacketByteBuf buffer) { - return codec().read(buffer); + return codec().decode(buffer); } public void write(PacketByteBuf buffer, T value) { buffer.writeInt(id); - codec().write(buffer, value); + codec().encode(buffer, value); } } diff --git a/src/main/java/com/minelittlepony/unicopia/network/track/TrackableObject.java b/src/main/java/com/minelittlepony/unicopia/network/track/TrackableObject.java index 8065aa81..956d5cb5 100644 --- a/src/main/java/com/minelittlepony/unicopia/network/track/TrackableObject.java +++ b/src/main/java/com/minelittlepony/unicopia/network/track/TrackableObject.java @@ -2,31 +2,31 @@ package com.minelittlepony.unicopia.network.track; import java.util.Optional; -import com.minelittlepony.unicopia.util.serialization.PacketCodec; - import io.netty.buffer.Unpooled; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; public interface TrackableObject> { Status getStatus(); - default void read(PacketByteBuf buffer) { - readTrackedNbt(PacketCodec.COMPRESSED_NBT.read(buffer)); + default void read(PacketByteBuf buffer, WrapperLookup lookup) { + readTrackedNbt(PacketCodecs.NBT_COMPOUND.decode(buffer), lookup); } - default Optional write(Status status) { + default Optional write(Status status, WrapperLookup lookup) { if (status == Status.NEW || status == Status.UPDATED) { PacketByteBuf buffer = new PacketByteBuf(Unpooled.buffer()); - PacketCodec.COMPRESSED_NBT.write(buffer, writeTrackedNbt()); + PacketCodecs.NBT_COMPOUND.encode(buffer, writeTrackedNbt(lookup)); return Optional.of(buffer); } return Optional.empty(); } - void readTrackedNbt(NbtCompound nbt); + void readTrackedNbt(NbtCompound nbt, WrapperLookup lookup); - NbtCompound writeTrackedNbt(); + NbtCompound writeTrackedNbt(WrapperLookup lookup); void discard(boolean immediate); diff --git a/src/main/java/com/minelittlepony/unicopia/particle/UParticles.java b/src/main/java/com/minelittlepony/unicopia/particle/UParticles.java index a474fed3..35423ecd 100644 --- a/src/main/java/com/minelittlepony/unicopia/particle/UParticles.java +++ b/src/main/java/com/minelittlepony/unicopia/particle/UParticles.java @@ -4,16 +4,16 @@ import com.minelittlepony.unicopia.Unicopia; import net.fabricmc.fabric.api.particle.v1.FabricParticleTypes; import net.minecraft.particle.BlockStateParticleEffect; -import net.minecraft.particle.DefaultParticleType; import net.minecraft.particle.ParticleType; +import net.minecraft.particle.SimpleParticleType; import net.minecraft.registry.Registry; import net.minecraft.registry.Registries; public interface UParticles { ParticleType UNICORN_MAGIC = register("unicorn_magic", FabricParticleTypes.complex(MagicParticleEffect.FACTORY)); - DefaultParticleType CHANGELING_MAGIC = register("changeling_magic", FabricParticleTypes.simple()); - DefaultParticleType BUBBLE = register("bubble", FabricParticleTypes.simple()); + SimpleParticleType CHANGELING_MAGIC = register("changeling_magic", FabricParticleTypes.simple()); + SimpleParticleType BUBBLE = register("bubble", FabricParticleTypes.simple()); ParticleType FOOTPRINT = register("footprint", FabricParticleTypes.complex(FootprintParticleEffect.FACTORY)); ParticleType DUST_CLOUD = register("dust_cloud", FabricParticleTypes.complex(BlockStateParticleEffect.PARAMETERS_FACTORY)); @@ -21,7 +21,7 @@ public interface UParticles { ParticleType RAINBOOM_TRAIL = register("rainboom_trail", FabricParticleTypes.complex(TargetBoundParticleEffect.FACTORY)); ParticleType WIND = register("wind", FabricParticleTypes.complex(TargetBoundParticleEffect.FACTORY)); - DefaultParticleType RAIN_DROPS = register("rain_drops", FabricParticleTypes.simple()); + SimpleParticleType RAIN_DROPS = register("rain_drops", FabricParticleTypes.simple()); ParticleType SPHERE = register("sphere", FabricParticleTypes.complex(true, SphereParticleEffect.FACTORY)); ParticleType DISK = register("disk", FabricParticleTypes.complex(true, SphereParticleEffect.FACTORY)); @@ -29,11 +29,11 @@ public interface UParticles { ParticleType HEALTH_DRAIN = register("health_drain", FabricParticleTypes.complex(true, FollowingParticleEffect.FACTORY)); ParticleType SPIRAL = register("spiral", FabricParticleTypes.complex(true, SpiralParticleEffect.FACTORY)); - DefaultParticleType GROUND_POUND = register("ground_pound", FabricParticleTypes.simple()); - DefaultParticleType CLOUDS_ESCAPING = register("clouds_escaping", FabricParticleTypes.simple(true)); + SimpleParticleType GROUND_POUND = register("ground_pound", FabricParticleTypes.simple()); + SimpleParticleType CLOUDS_ESCAPING = register("clouds_escaping", FabricParticleTypes.simple(true)); ParticleType LIGHTNING_BOLT = register("lightning_bolt", FabricParticleTypes.complex(true, LightningBoltParticleEffect.FACTORY)); - DefaultParticleType SHOCKWAVE = register("shockwave", FabricParticleTypes.simple(true)); + SimpleParticleType SHOCKWAVE = register("shockwave", FabricParticleTypes.simple(true)); static > T register(String name, T type) { return Registry.register(Registries.PARTICLE_TYPE, Unicopia.id(name), type); diff --git a/src/main/java/com/minelittlepony/unicopia/projectile/MagicBeamEntity.java b/src/main/java/com/minelittlepony/unicopia/projectile/MagicBeamEntity.java index 122bef3e..f668560c 100644 --- a/src/main/java/com/minelittlepony/unicopia/projectile/MagicBeamEntity.java +++ b/src/main/java/com/minelittlepony/unicopia/projectile/MagicBeamEntity.java @@ -66,13 +66,13 @@ public class MagicBeamEntity extends MagicProjectileEntity implements Caster void forEachDelegates(Consumer consumer, Function predicate) { try { - Optional.ofNullable(predicate.apply(getItem().getItem())).ifPresent(consumer); + Optional.ofNullable(predicate.apply(getStack().getItem())).ifPresent(consumer); } catch (Throwable t) { Unicopia.LOGGER.error("Error whilst ticking spell on entity {}", getMasterReference(), t); } diff --git a/src/main/java/com/minelittlepony/unicopia/projectile/PhysicsBodyProjectileEntity.java b/src/main/java/com/minelittlepony/unicopia/projectile/PhysicsBodyProjectileEntity.java index 04e58a42..d0900931 100644 --- a/src/main/java/com/minelittlepony/unicopia/projectile/PhysicsBodyProjectileEntity.java +++ b/src/main/java/com/minelittlepony/unicopia/projectile/PhysicsBodyProjectileEntity.java @@ -31,6 +31,7 @@ import net.minecraft.inventory.Inventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.nbt.NbtOps; import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKeys; import net.minecraft.registry.tag.BlockTags; @@ -56,7 +57,7 @@ public class PhysicsBodyProjectileEntity extends PersistentProjectileEntity impl private RegistryKey damageType = UDamageTypes.ROCK; public PhysicsBodyProjectileEntity(EntityType type, World world, ItemStack stack) { - super(type, world, stack); + super(type, 0, 0, 0, world, stack, null); } public PhysicsBodyProjectileEntity(World world, ItemStack stack) { @@ -64,18 +65,20 @@ public class PhysicsBodyProjectileEntity extends PersistentProjectileEntity impl } public PhysicsBodyProjectileEntity(World world, @Nullable LivingEntity thrower, ItemStack stack) { - super(UEntities.MUFFIN, thrower, world, stack); + super(UEntities.MUFFIN, thrower, world, stack, null); } @Override - protected void initDataTracker() { - super.initDataTracker(); - getDataTracker().startTracking(ITEM, ItemStack.EMPTY); - getDataTracker().startTracking(BOUNCY, false); + protected void initDataTracker(DataTracker.Builder builder) { + super.initDataTracker(builder); + builder.add(ITEM, ItemStack.EMPTY) + .add(BOUNCY, false); } + @Override public void setStack(ItemStack stack) { getDataTracker().set(ITEM, stack); + super.setStack(stack); } @Override @@ -273,7 +276,7 @@ public class PhysicsBodyProjectileEntity extends PersistentProjectileEntity impl super.writeCustomDataToNbt(nbt); ItemStack stack = getStack(); if (!stack.isEmpty()) { - nbt.put("Item", stack.writeNbt(new NbtCompound())); + ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, stack).result().ifPresent(item -> nbt.put("Item", item)); } nbt.putString("damageType", damageType.getValue().toString()); } @@ -281,7 +284,7 @@ public class PhysicsBodyProjectileEntity extends PersistentProjectileEntity impl @Override public void readCustomDataFromNbt(NbtCompound nbt) { super.readCustomDataFromNbt(nbt); - setStack(ItemStack.fromNbt(nbt.getCompound("Item"))); + setStack(ItemStack.fromNbtOrEmpty(getWorld().getRegistryManager(), nbt.getCompound("Item"))); if (nbt.contains("damageType", NbtElement.STRING_TYPE)) { Optional.ofNullable(Identifier.tryParse(nbt.getString("damageType"))).ifPresent(id -> { setDamageType(RegistryKey.of(RegistryKeys.DAMAGE_TYPE, id)); diff --git a/src/main/java/com/minelittlepony/unicopia/projectile/Projectile.java b/src/main/java/com/minelittlepony/unicopia/projectile/Projectile.java index c8b0c2a2..246d156d 100644 --- a/src/main/java/com/minelittlepony/unicopia/projectile/Projectile.java +++ b/src/main/java/com/minelittlepony/unicopia/projectile/Projectile.java @@ -10,29 +10,34 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.ProjectileEntity; import net.minecraft.item.ItemConvertible; import net.minecraft.item.ItemStack; +import net.minecraft.item.ProjectileItem; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; import net.minecraft.stat.Stats; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; +import net.minecraft.util.math.Direction; import net.minecraft.util.math.Position; import net.minecraft.world.World; -public interface Projectile extends ItemConvertible { - static void makeDispensable(Projectile projectile) { - DispenserBlock.registerBehavior(projectile.asItem(), new ProjectileDispenserBehavior(){ - @Override - protected ProjectileEntity createProjectile(World world, Position position, ItemStack stack) { - ProjectileEntity p = projectile.createProjectile(stack, world, null); - p.setPosition(position.getX(), position.getY(), position.getZ()); - return p; - } +public interface Projectile extends ItemConvertible, ProjectileItem { + ProjectileItem.Settings SETTINGS = ProjectileItem.Settings + .builder() + .uncertainty(0) + .build(); - @Override - protected float getVariation() { - return 0; - } - }); + static void makeDispensable(Projectile projectile) { + DispenserBlock.registerBehavior(projectile.asItem(), new ProjectileDispenserBehavior(projectile.asItem())); + } + + @Override + default ProjectileEntity createEntity(World world, Position pos, ItemStack stack, Direction direction) { + return createProjectile(stack, world, null); + } + + @Override + default ProjectileItem.Settings getProjectileSettings() { + return SETTINGS; } default TypedActionResult triggerThrow(World world, PlayerEntity player, Hand hand) { diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/GlowingRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/GlowingRecipe.java index 5cb6f9e8..70ffa14c 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/GlowingRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/GlowingRecipe.java @@ -2,12 +2,12 @@ package com.minelittlepony.unicopia.recipe; import com.minelittlepony.unicopia.item.GlowableItem; -import net.minecraft.inventory.RecipeInputInventory; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.book.CraftingRecipeCategory; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.recipe.input.CraftingRecipeInput; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Pair; public class GlowingRecipe extends ItemCombinationRecipe { @@ -17,7 +17,7 @@ public class GlowingRecipe extends ItemCombinationRecipe { } @Override - public final ItemStack craft(RecipeInputInventory inventory, DynamicRegistryManager registries) { + public final ItemStack craft(CraftingRecipeInput inventory, WrapperLookup registries) { Pair pair = runMatch(inventory); ItemStack result = pair.getLeft().copy(); diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/ItemCombinationRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/ItemCombinationRecipe.java index bdd8b17b..35500370 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/ItemCombinationRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/ItemCombinationRecipe.java @@ -1,9 +1,9 @@ package com.minelittlepony.unicopia.recipe; -import net.minecraft.inventory.RecipeInputInventory; import net.minecraft.item.ItemStack; import net.minecraft.recipe.SpecialCraftingRecipe; import net.minecraft.recipe.book.CraftingRecipeCategory; +import net.minecraft.recipe.input.CraftingRecipeInput; import net.minecraft.util.Pair; import net.minecraft.world.World; @@ -19,18 +19,18 @@ public abstract class ItemCombinationRecipe extends SpecialCraftingRecipe { } @Override - public final boolean matches(RecipeInputInventory inventory, World world) { + public final boolean matches(CraftingRecipeInput inventory, World world) { Pair result = runMatch(inventory); return !result.getLeft().isEmpty() && !result.getRight().isEmpty(); } - protected Pair runMatch(RecipeInputInventory inventory) { + protected Pair runMatch(CraftingRecipeInput inventory) { ItemStack bangle = ItemStack.EMPTY; ItemStack dust = ItemStack.EMPTY; - for(int i = 0; i < inventory.size(); i++) { - ItemStack stack = inventory.getStack(i); + for(int i = 0; i < inventory.getSize(); i++) { + ItemStack stack = inventory.getStackInSlot(i); if (!stack.isEmpty()) { if (isContainerItem(stack)) { diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/JarExtractRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/JarExtractRecipe.java index 1b4bb1c8..8b8491ba 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/JarExtractRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/JarExtractRecipe.java @@ -4,12 +4,12 @@ import org.jetbrains.annotations.Nullable; import com.minelittlepony.unicopia.item.UItems; -import net.minecraft.inventory.RecipeInputInventory; import net.minecraft.item.ItemStack; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.SpecialCraftingRecipe; import net.minecraft.recipe.book.CraftingRecipeCategory; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.recipe.input.CraftingRecipeInput; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.world.World; public class JarExtractRecipe extends SpecialCraftingRecipe { @@ -23,15 +23,15 @@ public class JarExtractRecipe extends SpecialCraftingRecipe { } @Override - public final boolean matches(RecipeInputInventory inventory, World world) { + public final boolean matches(CraftingRecipeInput inventory, World world) { return !craft(inventory, null).isEmpty(); } @Override - public ItemStack craft(RecipeInputInventory inventory, @Nullable DynamicRegistryManager manager) { + public ItemStack craft(CraftingRecipeInput inventory, @Nullable WrapperLookup manager) { ItemStack jar = ItemStack.EMPTY; - for (int i = 0; i < inventory.size(); i++) { - ItemStack stack = inventory.getStack(i); + for (int i = 0; i < inventory.getSize(); i++) { + ItemStack stack = inventory.getStackInSlot(i); if (stack.isEmpty()) { continue; } diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/JarInsertRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/JarInsertRecipe.java index 4867b2a9..2841eed7 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/JarInsertRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/JarInsertRecipe.java @@ -3,11 +3,11 @@ package com.minelittlepony.unicopia.recipe; import com.minelittlepony.unicopia.item.EmptyJarItem; import com.minelittlepony.unicopia.item.UItems; -import net.minecraft.inventory.RecipeInputInventory; import net.minecraft.item.ItemStack; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.book.CraftingRecipeCategory; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.recipe.input.CraftingRecipeInput; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Pair; import net.minecraft.util.collection.DefaultedList; @@ -18,7 +18,7 @@ public class JarInsertRecipe extends ItemCombinationRecipe { } @Override - public final ItemStack craft(RecipeInputInventory inventory, DynamicRegistryManager registries) { + public final ItemStack craft(CraftingRecipeInput inventory, WrapperLookup registries) { Pair pair = runMatch(inventory); return UItems.FILLED_JAR.setAppearance(UItems.FILLED_JAR.getDefaultStack(), pair.getRight()); @@ -45,7 +45,7 @@ public class JarInsertRecipe extends ItemCombinationRecipe { } @Override - public DefaultedList getRemainder(RecipeInputInventory inventory) { - return DefaultedList.ofSize(inventory.size(), ItemStack.EMPTY); + public DefaultedList getRemainder(CraftingRecipeInput inventory) { + return DefaultedList.ofSize(inventory.getSize(), ItemStack.EMPTY); } } diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/TransformCropsRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/TransformCropsRecipe.java index cab170d3..d7fdaad4 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/TransformCropsRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/TransformCropsRecipe.java @@ -5,26 +5,44 @@ import java.util.Set; import com.minelittlepony.unicopia.block.state.StateUtil; import com.minelittlepony.unicopia.entity.player.Pony; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; +import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.SingleStackInventory; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.recipe.Recipe; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.RecipeType; -import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.recipe.input.RecipeInput; import net.minecraft.registry.Registries; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.random.Random; import net.minecraft.world.World; public class TransformCropsRecipe implements Recipe { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + Registries.BLOCK.getCodec().fieldOf("target").forGetter(recipe -> recipe.target), + BlockState.CODEC.fieldOf("consume").forGetter(recipe -> recipe.catalyst), + BlockState.CODEC.fieldOf("output").forGetter(recipe -> recipe.output) + ).apply(instance, TransformCropsRecipe::new)); + private static final PacketCodec STATE_PACKET_CODEC = PacketCodecs.INTEGER.xmap(Block::getStateFromRawId, Block::getRawIdFromState); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.registryValue(RegistryKeys.BLOCK), recipe -> recipe.target, + STATE_PACKET_CODEC, recipe -> recipe.catalyst, + STATE_PACKET_CODEC, recipe -> recipe.output, + TransformCropsRecipe::new + ); + public static final int RADIUS = 3; public static final int SIDE_LENGTH = (2 * RADIUS) + 1; public static final int AREA = (SIDE_LENGTH * SIDE_LENGTH) - 1; @@ -76,12 +94,12 @@ public class TransformCropsRecipe implements Recipe= SIDE_LENGTH && height >= SIDE_LENGTH; } - public static class Serializer implements RecipeSerializer { - private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Registries.BLOCK.getCodec().fieldOf("target").forGetter(recipe -> recipe.target), - BlockState.CODEC.fieldOf("consume").forGetter(recipe -> recipe.catalyst), - BlockState.CODEC.fieldOf("output").forGetter(recipe -> recipe.output) - ).apply(instance, TransformCropsRecipe::new)); - - @Override - public Codec codec() { - return CODEC; - } - - @Override - public TransformCropsRecipe read(PacketByteBuf buffer) { - return new TransformCropsRecipe( - buffer.readRegistryValue(Registries.BLOCK), - Block.getStateFromRawId(buffer.readInt()), - Block.getStateFromRawId(buffer.readInt()) - ); - } - - @Override - public void write(PacketByteBuf buffer, TransformCropsRecipe recipe) { - buffer.writeRegistryValue(Registries.BLOCK, recipe.target); - buffer.writeInt(Block.getRawIdFromState(recipe.catalyst)); - buffer.writeInt(Block.getRawIdFromState(recipe.output)); - } - } - - public static record PlacementArea (Pony pony, BlockPos position) implements SingleStackInventory { + public static record PlacementArea (Pony pony, BlockPos position) implements SingleStackInventory, RecipeInput { @Override public void markDirty() { } @@ -156,8 +145,23 @@ public class TransformCropsRecipe implements Recipe CLOUD_SHAPING = RecipeType.register("unicopia:cloud_shaping"); RecipeType GROWING = RecipeType.register("unicopia:growing"); - RecipeSerializer ZAP_APPLE_SERIALIZER = RecipeSerializer.register("unicopia:crafting_zap_apple", new ZapAppleRecipe.Serializer()); - RecipeSerializer GLOWING_SERIALIZER = RecipeSerializer.register("unicopia:crafting_glowing", new SpecialRecipeSerializer<>(GlowingRecipe::new)); - RecipeSerializer JAR_INSERT_SERIALIZER = RecipeSerializer.register("unicopia:jar_insert", new SpecialRecipeSerializer<>(JarInsertRecipe::new)); - RecipeSerializer JAR_EXTRACT_SERIALIZER = RecipeSerializer.register("unicopia:jar_extract", new SpecialRecipeSerializer<>(JarExtractRecipe::new)); - RecipeSerializer CRAFTING_MAGICAL_SERIALIZER = RecipeSerializer.register("unicopia:crafting_magical", new SpellShapedCraftingRecipe.Serializer()); - RecipeSerializer TRAIT_REQUIREMENT = RecipeSerializer.register("unicopia:spellbook/crafting", new SpellCraftingRecipe.Serializer()); - RecipeSerializer TRAIT_COMBINING = RecipeSerializer.register("unicopia:spellbook/combining", new SpellEnhancingRecipe.Serializer()); - RecipeSerializer SPELL_DUPLICATING = RecipeSerializer.register("unicopia:spellbook/duplicating", new SpellDuplicatingRecipe.Serializer()); - RecipeSerializer CLOUD_SHAPING_SERIALIZER = RecipeSerializer.register("unicopia:cloud_shaping", new CuttingRecipe.Serializer<>(CloudShapingRecipe::new) {}); - RecipeSerializer TRANSFORM_CROP_SERIALIZER = RecipeSerializer.register("unicopia:transform_crop", new TransformCropsRecipe.Serializer()); + RecipeSerializer ZAP_APPLE_SERIALIZER = register("crafting_zap_apple", ZapAppleRecipe.CODEC, ZapAppleRecipe.PACKET_CODEC); + RecipeSerializer GLOWING_SERIALIZER = register("crafting_glowing", new SpecialRecipeSerializer<>(GlowingRecipe::new)); + RecipeSerializer JAR_INSERT_SERIALIZER = register("jar_insert", new SpecialRecipeSerializer<>(JarInsertRecipe::new)); + RecipeSerializer JAR_EXTRACT_SERIALIZER = register("jar_extract", new SpecialRecipeSerializer<>(JarExtractRecipe::new)); + RecipeSerializer CRAFTING_MAGICAL_SERIALIZER = register("crafting_magical", SpellShapedCraftingRecipe.CODEC, SpellShapedCraftingRecipe.PACKET_CODEC); + RecipeSerializer TRAIT_REQUIREMENT = register("spellbook/crafting", SpellCraftingRecipe.CODEC, SpellCraftingRecipe.PACKET_CODEC); + RecipeSerializer TRAIT_COMBINING = register("spellbook/combining", SpellEnhancingRecipe.CODEC, SpellEnhancingRecipe.PACKET_CODEC); + RecipeSerializer SPELL_DUPLICATING = register("spellbook/duplicating", SpellDuplicatingRecipe.CODEC, SpellDuplicatingRecipe.PACKET_CODEC); + RecipeSerializer CLOUD_SHAPING_SERIALIZER = register("cloud_shaping", new CuttingRecipe.Serializer<>(CloudShapingRecipe::new) {}); + RecipeSerializer TRANSFORM_CROP_SERIALIZER = register("transform_crop", TransformCropsRecipe.CODEC, TransformCropsRecipe.PACKET_CODEC); + + static > RecipeSerializer register(String name, MapCodec codec, PacketCodec packetCodec) { + return register(name, new RecipeSerializer<>() { + @Override + public MapCodec codec() { + return codec; + } + + @Override + public PacketCodec packetCodec() { + return packetCodec; + } + }); + } + + static , T extends Recipe> S register(String name, S serializer) { + return Registry.register(Registries.RECIPE_SERIALIZER, Unicopia.id(name), serializer); + } static void bootstrap() { LootTableEvents.MODIFY.register((res, manager, id, supplier, setter) -> { diff --git a/src/main/java/com/minelittlepony/unicopia/recipe/ZapAppleRecipe.java b/src/main/java/com/minelittlepony/unicopia/recipe/ZapAppleRecipe.java index 127e1c42..ac9df8a0 100644 --- a/src/main/java/com/minelittlepony/unicopia/recipe/ZapAppleRecipe.java +++ b/src/main/java/com/minelittlepony/unicopia/recipe/ZapAppleRecipe.java @@ -1,25 +1,22 @@ package com.minelittlepony.unicopia.recipe; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.minelittlepony.unicopia.item.UItems; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; import net.minecraft.recipe.ShapelessRecipe; import net.minecraft.recipe.book.CraftingRecipeCategory; import net.minecraft.util.collection.DefaultedList; import net.minecraft.registry.Registries; public class ZapAppleRecipe extends ShapelessRecipe { - public ZapAppleRecipe(String group, CraftingRecipeCategory category, ItemStack output, DefaultedList input) { - super(group, category, output, input); - } - - public static class Serializer implements RecipeSerializer { - private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( Codec.STRING.optionalFieldOf("group", "").forGetter(ZapAppleRecipe::getGroup), CraftingRecipeCategory.CODEC.optionalFieldOf("category", CraftingRecipeCategory.MISC).forGetter(ZapAppleRecipe::getCategory), Registries.ITEM.getCodec().xmap( @@ -28,35 +25,15 @@ public class ZapAppleRecipe extends ShapelessRecipe { ).fieldOf("appearance").forGetter(recipe -> recipe.getResult(null)), URecipes.SHAPELESS_RECIPE_INGREDIENTS_CODEC.fieldOf("ingredients").forGetter(ZapAppleRecipe::getIngredients) ).apply(instance, ZapAppleRecipe::new)); + public static final PacketCodec PACKET_CODEC = PacketCodec.tuple( + PacketCodecs.STRING, ZapAppleRecipe::getGroup, + CraftingRecipeCategory.PACKET_CODEC, ZapAppleRecipe::getCategory, + ItemStack.PACKET_CODEC, recipe -> recipe.getResult(null), + Ingredient.PACKET_CODEC.collect(PacketCodecs.toCollection(i -> DefaultedList.ofSize(i, Ingredient.EMPTY))), ZapAppleRecipe::getIngredients, + ZapAppleRecipe::new + ); - @Override - public Codec codec() { - return CODEC; - } - - @Override - public ZapAppleRecipe read(PacketByteBuf input) { - String group = input.readString(32767); - CraftingRecipeCategory category = input.readEnumConstant(CraftingRecipeCategory.class); - - DefaultedList ingredients = DefaultedList.ofSize(input.readVarInt(), Ingredient.EMPTY); - - for(int j = 0; j < ingredients.size(); ++j) { - ingredients.set(j, Ingredient.fromPacket(input)); - } - - return new ZapAppleRecipe(group, category, input.readItemStack(), ingredients); - } - - @Override - public void write(PacketByteBuf buffer, ZapAppleRecipe recipe) { - buffer.writeString(recipe.getGroup()); - buffer.writeEnumConstant(recipe.getCategory()); - buffer.writeVarInt(recipe.getIngredients().size()); - for (Ingredient ingredient : recipe.getIngredients()) { - ingredient.write(buffer); - } - buffer.writeItemStack(recipe.getResult(null)); - } + public ZapAppleRecipe(String group, CraftingRecipeCategory category, ItemStack output, DefaultedList input) { + super(group, category, output, input); } } diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/BlockDestructionManager.java b/src/main/java/com/minelittlepony/unicopia/server/world/BlockDestructionManager.java index 25464839..d04f2be3 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/BlockDestructionManager.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/BlockDestructionManager.java @@ -14,6 +14,7 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.block.BlockState; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; @@ -120,13 +121,13 @@ public class BlockDestructionManager implements Tickable { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { compound.putFloat("destruction", amount); compound.putInt("age", age); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { amount = compound.getFloat("destruction"); age = compound.getInt("age"); dirty = true; diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/DragonBreathStore.java b/src/main/java/com/minelittlepony/unicopia/server/world/DragonBreathStore.java index 0ea7eb60..20c4ff6f 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/DragonBreathStore.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/DragonBreathStore.java @@ -7,6 +7,7 @@ import com.minelittlepony.unicopia.item.UItems; import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Identifier; import net.minecraft.world.PersistentState; import net.minecraft.world.World; @@ -28,7 +29,7 @@ public class DragonBreathStore extends PersistentState { this(world); compound.getKeys().forEach(key -> { compound.getList(key, NbtElement.COMPOUND_TYPE).forEach(entry -> { - put(key, new Entry((NbtCompound)entry)); + put(key, new Entry((NbtCompound)entry, world.getRegistryManager())); }); }); } @@ -38,7 +39,7 @@ public class DragonBreathStore extends PersistentState { } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { synchronized (locker) { payloads.forEach((id, uuids) -> { NbtList list = new NbtList(); @@ -83,17 +84,14 @@ public class DragonBreathStore extends PersistentState { public void put(String recipient, ItemStack payload) { if (payload.getItem() == UItems.OATS) { - ItemStack oats = UItems.IMPORTED_OATS.getDefaultStack(); - oats.setNbt(payload.getNbt()); - oats.setCount(payload.getCount()); - put(recipient, oats); + put(recipient, payload.withItem(UItems.IMPORTED_OATS)); return; } synchronized (locker) { doPurge(); if (peekEntries(recipient).stream().noneMatch(i -> { - if (ItemStack.canCombine(i.payload(), payload)) { + if (ItemStack.areItemsAndComponentsEqual(i.payload(), payload)) { int combinedCount = i.payload().getCount() + payload.getCount(); if (combinedCount <= i.payload().getMaxCount()) { i.payload().setCount(combinedCount); @@ -126,13 +124,13 @@ public class DragonBreathStore extends PersistentState { long created, ItemStack payload) { - public Entry(NbtCompound compound) { - this(compound.getLong("created"), ItemStack.fromNbt(compound.getCompound("payload"))); + public Entry(NbtCompound compound, WrapperLookup lookup) { + this(compound.getLong("created"), ItemStack.fromNbtOrEmpty(lookup, compound.getCompound("payload"))); } public NbtCompound toNBT(NbtCompound compound) { compound.putLong("created", created); - compound.put("payload", payload().writeNbt(new NbtCompound())); + compound.put("payload", ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, payload()).getOrThrow()); return compound; } } diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/Ether.java b/src/main/java/com/minelittlepony/unicopia/server/world/Ether.java index 08c6a9a2..10bbeb4d 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/Ether.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/Ether.java @@ -18,6 +18,7 @@ import com.minelittlepony.unicopia.util.NbtSerialisable; import com.minelittlepony.unicopia.util.Tickable; import net.minecraft.nbt.*; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; @@ -42,7 +43,7 @@ public class Ether extends PersistentState implements Tickable { this.world = world; this.endpoints = NbtSerialisable.readMap(compound.getCompound("endpoints"), Identifier::tryParse, typeNbt -> { return NbtSerialisable.readMap((NbtCompound)typeNbt, UUID::fromString, entityNbt -> { - return NbtSerialisable.readMap((NbtCompound)entityNbt, UUID::fromString, nbt -> new Entry<>(nbt)); + return NbtSerialisable.readMap((NbtCompound)entityNbt, UUID::fromString, nbt -> new Entry<>(nbt, world.getRegistryManager())); }); }); } @@ -53,12 +54,12 @@ public class Ether extends PersistentState implements Tickable { } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { synchronized (locker) { pruneNodes(); compound.put("endpoints", NbtSerialisable.writeMap(endpoints, Identifier::toString, entities -> { return NbtSerialisable.writeMap(entities, UUID::toString, spells -> { - return NbtSerialisable.writeMap(spells, UUID::toString, Entry::toNBT); + return NbtSerialisable.writeMap(spells, UUID::toString, e -> e.toNBT(lookup)); }); })); return compound; @@ -201,10 +202,10 @@ public class Ether extends PersistentState implements Tickable { private BlockPos currentPos = BlockPos.ORIGIN; private BlockPos previousPos = BlockPos.ORIGIN; - private Entry(NbtElement nbt) { + private Entry(NbtElement nbt, WrapperLookup lookup) { this.entity = new EntityReference<>(); this.spell = new WeakReference<>(null); - this.fromNBT((NbtCompound)nbt); + this.fromNBT((NbtCompound)nbt, lookup); } public Entry(T spell, Caster caster) { @@ -356,7 +357,7 @@ public class Ether extends PersistentState implements Tickable { } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { entity.toNBT(compound); compound.putBoolean("removed", removed); compound.putFloat("pitch", pitch); @@ -373,7 +374,7 @@ public class Ether extends PersistentState implements Tickable { } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { entity.fromNBT(compound); removed = compound.getBoolean("removed"); pitch = compound.getFloat("pitch"); diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/FernFoliagePlacer.java b/src/main/java/com/minelittlepony/unicopia/server/world/FernFoliagePlacer.java index 71f49293..c1627980 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/FernFoliagePlacer.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/FernFoliagePlacer.java @@ -2,7 +2,7 @@ package com.minelittlepony.unicopia.server.world; import com.minelittlepony.unicopia.Unicopia; import com.minelittlepony.unicopia.block.UBlocks; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.BlockState; @@ -17,7 +17,7 @@ import net.minecraft.world.gen.foliage.FoliagePlacer; import net.minecraft.world.gen.foliage.FoliagePlacerType; public class FernFoliagePlacer extends FoliagePlacer { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> fillFoliagePlacerFields(instance).apply(instance, FernFoliagePlacer::new)); + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> fillFoliagePlacerFields(instance).apply(instance, FernFoliagePlacer::new)); public static final FoliagePlacerType TYPE = Registry.register(Registries.FOLIAGE_PLACER_TYPE, Unicopia.id("fern_foliage_placer"), new FoliagePlacerType<>(CODEC)); public FernFoliagePlacer(IntProvider radius, IntProvider offset) { diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/LightSources.java b/src/main/java/com/minelittlepony/unicopia/server/world/LightSources.java index 5c8f712e..a5ddbada 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/LightSources.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/LightSources.java @@ -12,6 +12,7 @@ import it.unimi.dsi.fastutil.objects.AbstractObject2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; @@ -44,7 +45,7 @@ public class LightSources extends PersistentState { } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { return compound; } diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/UWorldGen.java b/src/main/java/com/minelittlepony/unicopia/server/world/UWorldGen.java index 2c8d1903..765d97e5 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/UWorldGen.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/UWorldGen.java @@ -16,7 +16,7 @@ import net.fabricmc.fabric.api.biome.v1.BiomeModifications; import net.fabricmc.fabric.api.biome.v1.BiomeSelectors; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; -import net.minecraft.client.sound.MusicType; +import net.minecraft.sound.MusicType; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnGroup; import net.minecraft.registry.Registries; diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/UnicopiaWorldProperties.java b/src/main/java/com/minelittlepony/unicopia/server/world/UnicopiaWorldProperties.java index 6ba84df4..909a7185 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/UnicopiaWorldProperties.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/UnicopiaWorldProperties.java @@ -12,6 +12,7 @@ import net.minecraft.datafixer.DataFixTypes; import net.minecraft.entity.Entity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; @@ -81,7 +82,7 @@ public class UnicopiaWorldProperties extends PersistentState { } @Override - public NbtCompound writeNbt(NbtCompound tag) { + public NbtCompound writeNbt(NbtCompound tag, WrapperLookup lookup) { tag.putString("defaultRace", Race.REGISTRY.getId(defaultRace).toString()); tag.putFloat("tangentalSkyAngle", tangentalSkyAngle); tag.put("activeAltars", NbtSerialisable.BLOCK_POS.writeAll(activeAltarPositions)); @@ -90,7 +91,7 @@ public class UnicopiaWorldProperties extends PersistentState { public static UnicopiaWorldProperties forWorld(ServerWorld world) { return world.getPersistentStateManager().getOrCreate( - new Type<>(() -> new UnicopiaWorldProperties(world), nbt -> new UnicopiaWorldProperties(world, nbt), DataFixTypes.LEVEL), "unicopia_tribes" + new Type<>(() -> new UnicopiaWorldProperties(world), (nbt, lookup) -> new UnicopiaWorldProperties(world, nbt), DataFixTypes.LEVEL), "unicopia_tribes" ); } } diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/WeatherConditions.java b/src/main/java/com/minelittlepony/unicopia/server/world/WeatherConditions.java index ac2d4e84..91439de7 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/WeatherConditions.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/WeatherConditions.java @@ -13,6 +13,7 @@ import com.minelittlepony.unicopia.util.Tickable; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.registry.tag.BlockTags; import net.minecraft.registry.tag.FluidTags; import net.minecraft.util.Identifier; @@ -123,7 +124,7 @@ public class WeatherConditions extends PersistentState implements Tickable { } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { compound.putFloat("windYaw", windYaw); compound.putFloat("prevWindYaw", prevWindYaw); compound.putBoolean("prevDayState", prevDayState); diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/WorldOverlay.java b/src/main/java/com/minelittlepony/unicopia/server/world/WorldOverlay.java index a094a5aa..28533115 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/WorldOverlay.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/WorldOverlay.java @@ -15,9 +15,10 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.datafixer.DataFixTypes; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerChunkLoadingManager; import net.minecraft.server.world.ServerWorld; -import net.minecraft.server.world.ThreadedAnvilChunkStorage; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; @@ -41,7 +42,7 @@ public class WorldOverlay extends PersistentState return serverWorld.getPersistentStateManager().getOrCreate( new Type<>( () -> factory.apply(world), - compound -> loadFunc.apply(world, compound), + (compound, lookup) -> loadFunc.apply(world, compound), DataFixTypes.LEVEL ), id.getNamespace() + "_" + id.getPath().replace('/', '_') @@ -58,7 +59,7 @@ public class WorldOverlay extends PersistentState public static WorldOverlay getOverlay(World world, Identifier id, Function> overlayFactory) { return getPersistableStorage(world, id, (w, tag) -> { WorldOverlay overlay = overlayFactory.apply(w); - overlay.readNbt(tag); + overlay.readNbt(tag, w.getRegistryManager()); return overlay; }, overlayFactory); } @@ -70,19 +71,19 @@ public class WorldOverlay extends PersistentState } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { NbtCompound destructions = new NbtCompound(); this.chunks.forEach((id, chunk) -> { - destructions.put(id.toString(), chunk.toNBT()); + destructions.put(id.toString(), chunk.toNBT(lookup)); }); compound.put("chunks", destructions); return compound; } - public void readNbt(NbtCompound compound) { + public void readNbt(NbtCompound compound, WrapperLookup lookup) { NbtCompound d = compound.getCompound("chunks"); d.getKeys().forEach(id -> { - chunks.computeIfAbsent(Long.valueOf(id), Chunk::new).fromNBT(d.getCompound(id)); + chunks.computeIfAbsent(Long.valueOf(id), Chunk::new).fromNBT(d.getCompound(id), lookup); }); } @@ -159,7 +160,7 @@ public class WorldOverlay extends PersistentState return; } - ThreadedAnvilChunkStorage storage = world.getChunkManager().threadedAnvilChunkStorage; + ServerChunkLoadingManager storage = world.getChunkManager().chunkLoadingManager; List players = storage.getPlayersWatchingChunk(new ChunkPos(pos), false); @@ -169,20 +170,20 @@ public class WorldOverlay extends PersistentState } @Override - public void toNBT(NbtCompound compound) { + public void toNBT(NbtCompound compound, WrapperLookup lookup) { NbtCompound states = new NbtCompound(); this.states.forEach((id, state) -> { - states.put(id.toString(), state.toNBT()); + states.put(id.toString(), state.toNBT(lookup)); }); compound.put("states", states); } @Override - public void fromNBT(NbtCompound compound) { + public void fromNBT(NbtCompound compound, WrapperLookup lookup) { NbtCompound d = compound.getCompound("states"); chunks.clear(); d.getKeys().forEach(id -> { - states.computeIfAbsent(Long.valueOf(id), i -> factory.get()).fromNBT(d.getCompound(id)); + states.computeIfAbsent(Long.valueOf(id), i -> factory.get()).fromNBT(d.getCompound(id), lookup); }); } } diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/ZapAppleStageStore.java b/src/main/java/com/minelittlepony/unicopia/server/world/ZapAppleStageStore.java index a30fc4c6..dd024123 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/ZapAppleStageStore.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/ZapAppleStageStore.java @@ -17,6 +17,7 @@ import com.minelittlepony.unicopia.util.Tickable; import net.minecraft.entity.EntityType; import net.minecraft.entity.LightningEntity; import net.minecraft.nbt.*; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.sound.SoundCategory; import net.minecraft.util.Identifier; import net.minecraft.util.StringIdentifiable; @@ -134,7 +135,7 @@ public class ZapAppleStageStore extends PersistentState implements Tickable { } @Override - public NbtCompound writeNbt(NbtCompound compound) { + public NbtCompound writeNbt(NbtCompound compound, WrapperLookup lookup) { compound.putInt("stage", lastStage.ordinal()); compound.putBoolean("stageChanged", stageChanged); compound.putBoolean("playedMoonEffect", playedMoonEffect); diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/gen/CaveCarvingStructureProcessor.java b/src/main/java/com/minelittlepony/unicopia/server/world/gen/CaveCarvingStructureProcessor.java index cfb2db26..2e630c1a 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/gen/CaveCarvingStructureProcessor.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/gen/CaveCarvingStructureProcessor.java @@ -3,7 +3,8 @@ package com.minelittlepony.unicopia.server.world.gen; import org.jetbrains.annotations.Nullable; import com.minelittlepony.unicopia.server.world.UWorldGen; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; + import net.minecraft.structure.StructurePlacementData; import net.minecraft.structure.StructureTemplate; import net.minecraft.structure.processor.StructureProcessor; @@ -13,7 +14,7 @@ import net.minecraft.world.Heightmap; import net.minecraft.world.WorldView; public class CaveCarvingStructureProcessor extends StructureProcessor { - public static final Codec CODEC = Codec.unit(new CaveCarvingStructureProcessor()); + public static final MapCodec CODEC = MapCodec.unit(new CaveCarvingStructureProcessor()); @Override protected StructureProcessorType getType() { diff --git a/src/main/java/com/minelittlepony/unicopia/server/world/gen/SurfaceGrowthStructureProcessor.java b/src/main/java/com/minelittlepony/unicopia/server/world/gen/SurfaceGrowthStructureProcessor.java index 33ef60c7..0e06d73a 100644 --- a/src/main/java/com/minelittlepony/unicopia/server/world/gen/SurfaceGrowthStructureProcessor.java +++ b/src/main/java/com/minelittlepony/unicopia/server/world/gen/SurfaceGrowthStructureProcessor.java @@ -6,7 +6,7 @@ import java.util.function.Function; import java.util.stream.Collectors; import com.minelittlepony.unicopia.server.world.UWorldGen; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.BlockState; @@ -21,7 +21,7 @@ import net.minecraft.util.math.random.Random; import net.minecraft.world.ServerWorldAccess; public class SurfaceGrowthStructureProcessor extends StructureProcessor { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( RuleTest.TYPE_CODEC.fieldOf("input_predicate").forGetter(rule -> rule.inputPredicate), BlockState.CODEC.fieldOf("output_state").forGetter(rule -> rule.outputState) ).apply(instance, SurfaceGrowthStructureProcessor::new)); diff --git a/src/main/java/com/minelittlepony/unicopia/util/CodecUtils.java b/src/main/java/com/minelittlepony/unicopia/util/CodecUtils.java index 67d5f491..fb5cf212 100644 --- a/src/main/java/com/minelittlepony/unicopia/util/CodecUtils.java +++ b/src/main/java/com/minelittlepony/unicopia/util/CodecUtils.java @@ -14,11 +14,9 @@ import com.mojang.serialization.Decoder; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; import com.mojang.serialization.MapCodec; - import net.fabricmc.fabric.api.util.TriState; import net.minecraft.item.ItemConvertible; import net.minecraft.registry.Registries; -import net.minecraft.util.dynamic.Codecs; public interface CodecUtils { Codec ITEM = Registries.ITEM.getCodec().xmap(i -> () -> i, ItemConvertible::asItem); @@ -71,7 +69,7 @@ public interface CodecUtils { } static Codec xor(Codec left, Codec right) { - return Codecs.xor(left, right).xmap(either -> either.left().or(either::right).get(), Either::left); + return Codec.xor(left, right).xmap(either -> either.left().or(either::right).get(), Either::left); } static Codec> setOf(Codec codec) { diff --git a/src/main/java/com/minelittlepony/unicopia/util/ColorHelper.java b/src/main/java/com/minelittlepony/unicopia/util/ColorHelper.java index 4db63857..49218c26 100644 --- a/src/main/java/com/minelittlepony/unicopia/util/ColorHelper.java +++ b/src/main/java/com/minelittlepony/unicopia/util/ColorHelper.java @@ -6,6 +6,7 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.passive.SheepEntity; import net.minecraft.util.DyeColor; import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.ColorHelper.Argb; public interface ColorHelper { static int getRainbowColor(Entity entity, int speed, float tickDelta) { @@ -14,12 +15,9 @@ public interface ColorHelper { int p = n % o; int q = (n + 1) % o; float r = (entity.age % speed + tickDelta) / 25.0f; - float[] fs = SheepEntity.getRgbColor(DyeColor.byId(p)); - float[] gs = SheepEntity.getRgbColor(DyeColor.byId(q)); - float s = fs[0] * (1.0f - r) + gs[0] * r; - float t = fs[1] * (1.0f - r) + gs[1] * r; - float u = fs[2] * (1.0f - r) + gs[2] * r; - return Color.argbToHex(1, s, t, u); + int fs = SheepEntity.getRgbColor(DyeColor.byId(p)); + int gs = SheepEntity.getRgbColor(DyeColor.byId(q)); + return Argb.lerp(r, fs, gs); } static float[] changeSaturation(float red, float green, float blue, float intensity) { diff --git a/src/main/java/com/minelittlepony/unicopia/util/NbtSerialisable.java b/src/main/java/com/minelittlepony/unicopia/util/NbtSerialisable.java index 32f9ea21..2191c654 100644 --- a/src/main/java/com/minelittlepony/unicopia/util/NbtSerialisable.java +++ b/src/main/java/com/minelittlepony/unicopia/util/NbtSerialisable.java @@ -10,30 +10,33 @@ import com.mojang.serialization.Codec; import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; +import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; public interface NbtSerialisable { - Serializer BLOCK_POS = Serializer.of(NbtHelper::toBlockPos, NbtHelper::fromBlockPos); - Serializer ITEM_STACK = Serializer.of(ItemStack::fromNbt, stack -> stack.writeNbt(new NbtCompound())); + @Deprecated + Serializer BLOCK_POS = Serializer.ofCodec(BlockPos.CODEC); + @Deprecated + Serializer ITEM_STACK = Serializer.ofCodec(ItemStack.CODEC); /** * Called to save this to nbt to persist state on file or to transmit over the network * * @param compound Compound tag to write to. */ - void toNBT(NbtCompound compound); + void toNBT(NbtCompound compound, WrapperLookup lookup); /** * Called to load this state from nbt * * @param compound Compound tag to read from. */ - void fromNBT(NbtCompound compound); + void fromNBT(NbtCompound compound, WrapperLookup lookup); - default NbtCompound toNBT() { + default NbtCompound toNBT(WrapperLookup lookup) { NbtCompound compound = new NbtCompound(); - toNBT(compound); + toNBT(compound, lookup); return compound; } @@ -97,53 +100,56 @@ public interface NbtSerialisable { return nbt; } - interface Serializer { - T read(NbtCompound compound); + @Deprecated + interface Serializer { + T read(N compound, WrapperLookup lookup); - NbtCompound write(T t); + N write(T t, WrapperLookup lookup); - default Optional readOptional(String name, NbtCompound compound) { + @SuppressWarnings("unchecked") + default Optional readOptional(String name, NbtCompound compound, WrapperLookup lookup) { return compound.contains(name, NbtElement.COMPOUND_TYPE) - ? Optional.ofNullable(read(compound.getCompound(name))) + ? Optional.ofNullable(read((N)compound.get(name), lookup)) : Optional.empty(); } - default void writeOptional(String name, NbtCompound compound, Optional t) { - t.map(this::write).ifPresent(tag -> compound.put(name, tag)); + default void writeOptional(String name, NbtCompound compound, Optional t, WrapperLookup lookup) { + t.map(l -> write(l, lookup)).ifPresent(tag -> compound.put(name, tag)); } - default T read(NbtElement element) { - return read((NbtCompound)element); - } - - default NbtList writeAll(Collection ts) { + default NbtList writeAll(Collection ts, WrapperLookup lookup) { NbtList list = new NbtList(); - ts.stream().map(this::write).forEach(list::add); + ts.stream().map(l -> write(l, lookup)).forEach(list::add); return list; } - default Stream readAll(NbtList list) { - return list.stream().map(this::read).filter(Objects::nonNull); + @SuppressWarnings("unchecked") + default Stream readAll(NbtList list, WrapperLookup lookup) { + return list.stream().map(l -> read((N)l, lookup)).filter(Objects::nonNull); } - static Serializer of(Supplier factory) { - return of(nbt -> { + static Serializer of(Supplier factory) { + return of((nbt, lookup) -> { T value = factory.get(); - value.fromNBT(nbt); + value.fromNBT(nbt, lookup); return value; - }, value -> value.toNBT()); + }, (value, lookup) -> value.toNBT(lookup)); } - static Serializer of(Function read, Function write) { + static Serializer ofCodec(Codec codec) { + return of((value, lookup) -> decode(codec, value).get(), (t, lookup) -> encode(codec, t)); + } + + static Serializer of(BiFunction read, BiFunction write) { return new Serializer<>() { @Override - public T read(NbtCompound compound) { - return read.apply(compound); + public T read(N compound, WrapperLookup lookup) { + return read.apply(compound, lookup); } @Override - public NbtCompound write(T t) { - return write.apply(t); + public N write(T t, WrapperLookup lookup) { + return write.apply(t, lookup); } }; } diff --git a/src/main/java/com/minelittlepony/unicopia/util/Resources.java b/src/main/java/com/minelittlepony/unicopia/util/Resources.java index ab78f637..e2bf4c2a 100644 --- a/src/main/java/com/minelittlepony/unicopia/util/Resources.java +++ b/src/main/java/com/minelittlepony/unicopia/util/Resources.java @@ -18,7 +18,7 @@ import net.minecraft.util.Identifier; public interface Resources { Gson GSON = new GsonBuilder() - .registerTypeAdapter(Identifier.class, new ToStringAdapter<>(Identifier::new)) + .registerTypeAdapter(Identifier.class, new ToStringAdapter<>(Identifier::of)) .create(); static Stream getResources(ResourceManager manager, Identifier id) { @@ -29,7 +29,7 @@ public interface Resources { try (InputStreamReader reader = new InputStreamReader(res.getInputStream())) { return (GSON.>fromJson(reader, type)).stream(); } catch (JsonParseException e) { - Unicopia.LOGGER.warn(msg + res.getResourcePackName(), e); + Unicopia.LOGGER.warn(msg + res.getPackId(), e); } catch (IOException ignored) {} return Stream.empty(); diff --git a/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodec.java b/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodec.java index a9eec18a..a315d0a9 100644 --- a/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodec.java +++ b/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodec.java @@ -23,6 +23,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; +@Deprecated public record PacketCodec(PacketByteBuf.PacketReader reader, PacketByteBuf.PacketWriter writer) { public static final PacketCodec BOOLEAN = new PacketCodec<>(PacketByteBuf::readBoolean, PacketByteBuf::writeBoolean); public static final PacketCodec FLOAT = new PacketCodec<>(PacketByteBuf::readFloat, PacketByteBuf::writeFloat); diff --git a/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodecUtils.java b/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodecUtils.java new file mode 100644 index 00000000..7ae25a37 --- /dev/null +++ b/src/main/java/com/minelittlepony/unicopia/util/serialization/PacketCodecUtils.java @@ -0,0 +1,33 @@ +package com.minelittlepony.unicopia.util.serialization; + +import java.util.Optional; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.registry.RegistryKey; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; + +public interface PacketCodecUtils { + PacketCodec BUFFER = PacketCodec.of((buffer, bytes) -> { + buffer.writeInt(bytes.writerIndex()); + buffer.writeBytes(bytes); + }, buffer -> new PacketByteBuf(buffer.readBytes(buffer.readInt()))); + PacketCodec> OPTIONAL_BUFFER = PacketCodecs.optional(BUFFER); + PacketCodec> REGISTRY_KEY = PacketCodec.tuple( + Identifier.PACKET_CODEC, RegistryKey::getRegistry, + Identifier.PACKET_CODEC, RegistryKey::getValue, + (registry, value) -> RegistryKey.of(RegistryKey.ofRegistry(registry), value) + ); + PacketCodec>> OPTIONAL_REGISTRY_KEY = PacketCodecs.optional(REGISTRY_KEY); + PacketCodec VECTOR = PacketCodec.tuple( + PacketCodecs.DOUBLE, Vec3d::getX, + PacketCodecs.DOUBLE, Vec3d::getY, + PacketCodecs.DOUBLE, Vec3d::getZ, + Vec3d::new + ); + PacketCodec> OPTIONAL_VECTOR = PacketCodecs.optional(VECTOR); + PacketCodec> OPTIONAL_POS = PacketCodecs.optional(BlockPos.PACKET_CODEC); +} diff --git a/src/main/resources/unicopia.aw b/src/main/resources/unicopia.aw index 708479ac..6ded9865 100644 --- a/src/main/resources/unicopia.aw +++ b/src/main/resources/unicopia.aw @@ -6,7 +6,7 @@ accessible class net/minecraft/client/render/item/HeldItemRenderer$H accessible class net/minecraft/client/render/VertexConsumers$Union accessible class net/minecraft/client/gui/hud/InGameHud$HeartType -accessible method net/minecraft/world/gen/foliage/FoliagePlacerType (Lcom/mojang/serialization/Codec;)V +#accessible method net/minecraft/world/gen/foliage/FoliagePlacerType (Lcom/mojang/serialization/Codec;)V accessible field net/minecraft/entity/mob/CreeperEntity CHARGED Lnet/minecraft/entity/data/TrackedData; accessible field net/minecraft/entity/mob/CreeperEntity IGNITED Lnet/minecraft/entity/data/TrackedData; @@ -16,6 +16,6 @@ accessible method net/minecraft/client/render/RenderPhase$TextureBase accessible field net/minecraft/client/render/RenderLayer$MultiPhaseParameters texture Lnet/minecraft/client/render/RenderPhase$TextureBase; accessible field net/minecraft/loot/LootTable pools Ljava/util/List; -accessible method net/minecraft/block/entity/SkullBlockEntity fetchProfile (Ljava/lang/String;)Ljava/util/concurrent/CompletableFuture; +#accessible method net/minecraft/block/entity/SkullBlockEntity fetchProfile (Ljava/lang/String;)Ljava/util/concurrent/CompletableFuture; -accessible method net/minecraft/entity/LightningEntity cleanOxidation (Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;)V \ No newline at end of file +accessible method net/minecraft/entity/LightningEntity cleanOxidation (Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;)V