Update fabwork and convert all packets to use codecs

This commit is contained in:
Sollace 2024-09-29 21:37:44 +01:00
parent 8fdb173e4b
commit 98eff467c4
No known key found for this signature in database
GPG key ID: E52FACE7B5C773DB
27 changed files with 230 additions and 295 deletions

View file

@ -20,7 +20,7 @@ org.gradle.daemon=false
modrinth_project_id=9K7RJlvM modrinth_project_id=9K7RJlvM
# Dependencies # Dependencies
fabwork_version=1.3.2-beta.1+1.21 fabwork_version=1.3.2-beta.2+1.21
modmenu_version=11.0.0-beta.1 modmenu_version=11.0.0-beta.1
minelp_version=4.12.0+1.21 minelp_version=4.12.0+1.21
kirin_version=1.19.0+1.21 kirin_version=1.19.0+1.21

View file

@ -2,7 +2,17 @@ package com.minelittlepony.unicopia;
import java.util.Set; import java.util.Set;
import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
public record SyncedConfig ( public record SyncedConfig (
Set<String> wantItNeedItExcludeList, Set<String> wantItNeedItExcludeList,
Set<String> dimensionsWithoutAtmosphere) { Set<String> dimensionsWithoutAtmosphere) {
public static final PacketCodec<ByteBuf, SyncedConfig> PACKET_CODEC = PacketCodec.tuple(
PacketCodecUtils.STRING_SET, SyncedConfig::wantItNeedItExcludeList,
PacketCodecUtils.STRING_SET, SyncedConfig::dimensionsWithoutAtmosphere,
SyncedConfig::new
);
} }

View file

@ -12,10 +12,14 @@ import com.minelittlepony.unicopia.Unicopia;
import com.minelittlepony.unicopia.util.RegistryUtils; import com.minelittlepony.unicopia.util.RegistryUtils;
import net.minecraft.util.*; import net.minecraft.util.*;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.registry.Registry; import net.minecraft.registry.Registry;
public interface Abilities { public interface Abilities {
Registry<Ability<?>> REGISTRY = RegistryUtils.createSimple(Unicopia.id("abilities")); Registry<Ability<?>> REGISTRY = RegistryUtils.createSimple(Unicopia.id("abilities"));
PacketCodec<RegistryByteBuf, Ability<?>> PACKET_CODEC = PacketCodecs.registryValue(REGISTRY.getKey());
Map<AbilitySlot, Set<Ability<?>>> BY_SLOT = new EnumMap<>(AbilitySlot.class); Map<AbilitySlot, Set<Ability<?>>> BY_SLOT = new EnumMap<>(AbilitySlot.class);
BiFunction<AbilitySlot, Race.Composite, List<Ability<?>>> BY_SLOT_AND_COMPOSITE_RACE = Util.memoize((slot, race) -> { BiFunction<AbilitySlot, Race.Composite, List<Ability<?>>> BY_SLOT_AND_COMPOSITE_RACE = Util.memoize((slot, race) -> {
return BY_SLOT.computeIfAbsent(slot, s -> new LinkedHashSet<>()) return BY_SLOT.computeIfAbsent(slot, s -> new LinkedHashSet<>())

View file

@ -6,7 +6,7 @@ import com.minelittlepony.unicopia.Race;
import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.ability.data.Hit;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import io.netty.buffer.ByteBuf; import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
@ -108,7 +108,7 @@ public interface Ability<T extends Hit> {
/** /**
* Gets the serializer to use for reading data over the network. * Gets the serializer to use for reading data over the network.
*/ */
PacketCodec<? extends ByteBuf, T> getSerializer(); PacketCodec<? super RegistryByteBuf, T> getSerializer();
/** /**
* Called on the client to get any data required to activate the ability. * Called on the client to get any data required to activate the ability.

View file

@ -1,5 +1,8 @@
package com.minelittlepony.unicopia.ability; package com.minelittlepony.unicopia.ability;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
public enum ActivationType { public enum ActivationType {
@ -9,6 +12,7 @@ public enum ActivationType {
TRIPLE_TAP; TRIPLE_TAP;
private static final ActivationType[] VALUES = values(); private static final ActivationType[] VALUES = values();
public static final PacketCodec<ByteBuf, ActivationType> PACKET_CODEC = PacketCodecs.indexed(i -> VALUES[i], ActivationType::ordinal);
public ActivationType getNext() { public ActivationType getNext() {
return VALUES[Math.min(VALUES.length - 1, ordinal() + 1)]; return VALUES[Math.min(VALUES.length - 1, ordinal() + 1)];
@ -22,6 +26,7 @@ public enum ActivationType {
return this != NONE; return this != NONE;
} }
@Deprecated
public static ActivationType of(int id) { public static ActivationType of(int id) {
return VALUES[MathHelper.clamp(id, 0, VALUES.length)]; return VALUES[MathHelper.clamp(id, 0, VALUES.length)];
} }

View file

@ -8,11 +8,15 @@ import java.util.stream.Stream;
import com.minelittlepony.unicopia.Unicopia; import com.minelittlepony.unicopia.Unicopia;
import com.minelittlepony.unicopia.command.CommandArgumentEnum; import com.minelittlepony.unicopia.command.CommandArgumentEnum;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.netty.buffer.ByteBuf;
import net.minecraft.command.argument.EnumArgumentType; import net.minecraft.command.argument.EnumArgumentType;
import net.minecraft.component.type.AttributeModifiersComponent; import net.minecraft.component.type.AttributeModifiersComponent;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList; import net.minecraft.nbt.NbtList;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.text.*; import net.minecraft.text.*;
import net.minecraft.util.Formatting; import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
@ -59,6 +63,7 @@ public enum Trait implements CommandArgumentEnum<Trait> {
POISON(TraitGroup.DARKNESS), POISON(TraitGroup.DARKNESS),
BLOOD(TraitGroup.DARKNESS); BLOOD(TraitGroup.DARKNESS);
private static final Trait[] VALUES = values();
private static final Map<Identifier, Trait> IDS = Arrays.stream(values()).collect(Collectors.toMap(Trait::getId, Function.identity())); private static final Map<Identifier, Trait> IDS = Arrays.stream(values()).collect(Collectors.toMap(Trait::getId, Function.identity()));
private static final EnumCodec<Trait> NAME_CODEC = StringIdentifiable.createCodec(Trait::values, n -> n.toLowerCase(Locale.ROOT)); private static final EnumCodec<Trait> NAME_CODEC = StringIdentifiable.createCodec(Trait::values, n -> n.toLowerCase(Locale.ROOT));
public static final Codec<Trait> CODEC = Identifier.CODEC.xmap(id -> IDS.get(id), Trait::getId); public static final Codec<Trait> CODEC = Identifier.CODEC.xmap(id -> IDS.get(id), Trait::getId);
@ -66,6 +71,7 @@ public enum Trait implements CommandArgumentEnum<Trait> {
l -> l.stream().distinct().collect(Collectors.toSet()), l -> l.stream().distinct().collect(Collectors.toSet()),
s -> s.stream().toList() s -> s.stream().toList()
); );
public static final PacketCodec<ByteBuf, Trait> PACKET_CODEC = PacketCodecs.indexed(i -> VALUES[i], Trait::ordinal);
private final Identifier id; private final Identifier id;
private final Identifier sprite; private final Identifier sprite;

View file

@ -10,17 +10,22 @@ import com.minelittlepony.unicopia.command.CommandArgumentEnum;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.minelittlepony.unicopia.item.GlassesItem; import com.minelittlepony.unicopia.item.GlassesItem;
import com.minelittlepony.unicopia.util.AnimationUtil; import com.minelittlepony.unicopia.util.AnimationUtil;
import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.MinecraftClient; import net.minecraft.client.MinecraftClient;
import net.minecraft.client.model.ModelPart; import net.minecraft.client.model.ModelPart;
import net.minecraft.client.render.entity.model.BipedEntityModel; import net.minecraft.client.render.entity.model.BipedEntityModel;
import net.minecraft.client.render.entity.model.PlayerEntityModel; import net.minecraft.client.render.entity.model.PlayerEntityModel;
import net.minecraft.client.util.math.MatrixStack; import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.command.argument.EnumArgumentType; import net.minecraft.command.argument.EnumArgumentType;
import net.minecraft.component.DataComponentTypes;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.sound.SoundEvent; import net.minecraft.sound.SoundEvent;
import net.minecraft.text.Text;
import net.minecraft.util.Arm; import net.minecraft.util.Arm;
import net.minecraft.util.Hand; import net.minecraft.util.Hand;
import net.minecraft.util.StringIdentifiable; import net.minecraft.util.StringIdentifiable;
@ -34,8 +39,8 @@ public class PlayerPoser {
public void applyPosing(MatrixStack matrices, PlayerEntity player, BipedEntityModel<?> model, Context context) { public void applyPosing(MatrixStack matrices, PlayerEntity player, BipedEntityModel<?> model, Context context) {
Pony pony = Pony.of(player); Pony pony = Pony.of(player);
float tickDelta = MinecraftClient.getInstance().getTickDelta(); float tickDelta = MinecraftClient.getInstance().getRenderTickCounter().getTickDelta(false);
float progress = pony.getAnimationProgress(MinecraftClient.getInstance().getTickDelta()); float progress = pony.getAnimationProgress(MinecraftClient.getInstance().getRenderTickCounter().getTickDelta(false));
AnimationInstance animation = pony.getAnimation(); AnimationInstance animation = pony.getAnimation();
Race ponyRace = MineLPDelegate.getInstance().getPlayerPonyRace(player); Race ponyRace = MineLPDelegate.getInstance().getPlayerPonyRace(player);
Arm mainArm = player.getMainArm(); Arm mainArm = player.getMainArm();
@ -72,7 +77,8 @@ public class PlayerPoser {
} }
} }
if (glasses.hasCustomName() && "Cool Shades".equals(glasses.getName().getString())) { Text name = glasses.get(DataComponentTypes.CUSTOM_NAME);
if (name != null && "Cool Shades".equals(name.getString())) {
final float bop = AnimationUtil.beat(player.age, HEAD_NOD_DURATION, HEAD_NOD_GAP) * 3F; final float bop = AnimationUtil.beat(player.age, HEAD_NOD_DURATION, HEAD_NOD_GAP) * 3F;
head.pitch += bop / 10F; head.pitch += bop / 10F;
@ -396,6 +402,11 @@ public class PlayerPoser {
public record AnimationInstance(Animation animation, Animation.Recipient recipient) { public record AnimationInstance(Animation animation, Animation.Recipient recipient) {
public static final AnimationInstance NONE = new AnimationInstance(Animation.NONE, Animation.Recipient.ANYONE); public static final AnimationInstance NONE = new AnimationInstance(Animation.NONE, Animation.Recipient.ANYONE);
public static final PacketCodec<ByteBuf, AnimationInstance> PACKET_CODEC = PacketCodec.tuple(
PacketCodecUtils.ofEnum(Animation.class), AnimationInstance::animation,
PacketCodecUtils.ofEnum(Animation.Recipient.class), AnimationInstance::recipient,
AnimationInstance::new
);
public boolean isOf(Animation animation) { public boolean isOf(Animation animation) {
return animation() == animation; return animation() == animation;

View file

@ -12,7 +12,6 @@ import net.minecraft.block.Blocks;
import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.Enchantments; import net.minecraft.enchantment.Enchantments;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityGroup;
import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.FlyingItemEntity; import net.minecraft.entity.FlyingItemEntity;
import net.minecraft.entity.LivingEntity; import net.minecraft.entity.LivingEntity;
@ -127,7 +126,9 @@ public class FilledJarItem extends ProjectileItem implements ProjectileDelegate.
butterfly.updatePosition(projectile.getX(), projectile.getY(), projectile.getZ()); butterfly.updatePosition(projectile.getX(), projectile.getY(), projectile.getZ());
projectile.getWorld().spawnEntity(butterfly); projectile.getWorld().spawnEntity(butterfly);
} else { } else {
stack.damage(1, projectile.getWorld().random, null); if (projectile.getWorld() instanceof ServerWorld sw) {
stack.damage(1, sw, null, i -> {});
}
projectile.dropStack(stack); projectile.dropStack(stack);
} }
projectile.getWorld().syncWorldEvent(WorldEvents.BLOCK_BROKEN, projectile.getBlockPos(), Block.getRawIdFromState(Blocks.GLASS.getDefaultState())); projectile.getWorld().syncWorldEvent(WorldEvents.BLOCK_BROKEN, projectile.getBlockPos(), Block.getRawIdFromState(Blocks.GLASS.getDefaultState()));

View file

@ -12,31 +12,31 @@ import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
public interface Channel { public interface Channel {
C2SPacketType<MsgPlayerAbility<?>> CLIENT_PLAYER_ABILITY = SimpleNetworking.clientToServer(Unicopia.id("player_ability"), MsgPlayerAbility::read); C2SPacketType<MsgPlayerAbility<?>> CLIENT_PLAYER_ABILITY = SimpleNetworking.clientToServer(Unicopia.id("player_ability"), MsgPlayerAbility.PACKET_CODEC);
C2SPacketType<MsgCasterLookRequest.Reply> CLIENT_CASTER_LOOK = SimpleNetworking.clientToServer(Unicopia.id("caster_look"), MsgCasterLookRequest.Reply::new); C2SPacketType<MsgCasterLookRequest.Reply> CLIENT_CASTER_LOOK = SimpleNetworking.clientToServer(Unicopia.id("caster_look"), MsgCasterLookRequest.Reply.PACKET_CODEC);
C2SPacketType<MsgRequestSpeciesChange> CLIENT_REQUEST_SPECIES_CHANGE = SimpleNetworking.clientToServer(Unicopia.id("request_capabilities"), MsgRequestSpeciesChange::new); C2SPacketType<MsgRequestSpeciesChange> CLIENT_REQUEST_SPECIES_CHANGE = SimpleNetworking.clientToServer(Unicopia.id("request_capabilities"), MsgRequestSpeciesChange.PACKET_CODEC);
C2SPacketType<MsgMarkTraitRead> MARK_TRAIT_READ = SimpleNetworking.clientToServer(Unicopia.id("mark_trait_read"), MsgMarkTraitRead::new); C2SPacketType<MsgMarkTraitRead> MARK_TRAIT_READ = SimpleNetworking.clientToServer(Unicopia.id("mark_trait_read"), MsgMarkTraitRead.PACKET_CODEC);
C2SPacketType<MsgRemoveSpell> REMOVE_SPELL = SimpleNetworking.clientToServer(Unicopia.id("remove_spell"), MsgRemoveSpell::new); C2SPacketType<MsgRemoveSpell> REMOVE_SPELL = SimpleNetworking.clientToServer(Unicopia.id("remove_spell"), MsgRemoveSpell.PACKET_CODEC);
C2SPacketType<MsgPlayerFlightControlsInput> FLIGHT_CONTROLS_INPUT = SimpleNetworking.clientToServer(Unicopia.id("flight_controls"), MsgPlayerFlightControlsInput::new); C2SPacketType<MsgPlayerFlightControlsInput> FLIGHT_CONTROLS_INPUT = SimpleNetworking.clientToServer(Unicopia.id("flight_controls"), MsgPlayerFlightControlsInput.PACKET_CODEC);
S2CPacketType<MsgPlayerCapabilities> SERVER_PLAYER_CAPABILITIES = SimpleNetworking.serverToClient(Unicopia.id("player_capabilities"), MsgPlayerCapabilities::new); S2CPacketType<MsgPlayerCapabilities> SERVER_PLAYER_CAPABILITIES = SimpleNetworking.serverToClient(Unicopia.id("player_capabilities"), MsgPlayerCapabilities.PACKET_CODEC);
S2CPacketType<MsgBlockDestruction> SERVER_BLOCK_DESTRUCTION = SimpleNetworking.serverToClient(Unicopia.id("block_destruction"), MsgBlockDestruction::new); S2CPacketType<MsgBlockDestruction> SERVER_BLOCK_DESTRUCTION = SimpleNetworking.serverToClient(Unicopia.id("block_destruction"), MsgBlockDestruction.PACKET_CODEC);
S2CPacketType<MsgCancelPlayerAbility> CANCEL_PLAYER_ABILITY = SimpleNetworking.serverToClient(Unicopia.id("player_ability_cancel"), MsgCancelPlayerAbility.PACKET_CODEC); S2CPacketType<MsgCancelPlayerAbility> CANCEL_PLAYER_ABILITY = SimpleNetworking.serverToClient(Unicopia.id("player_ability_cancel"), MsgCancelPlayerAbility.PACKET_CODEC);
S2CPacketType<MsgCasterLookRequest> SERVER_REQUEST_PLAYER_LOOK = SimpleNetworking.serverToClient(Unicopia.id("request_player_look"), MsgCasterLookRequest::new); S2CPacketType<MsgCasterLookRequest> SERVER_REQUEST_PLAYER_LOOK = SimpleNetworking.serverToClient(Unicopia.id("request_player_look"), MsgCasterLookRequest.PACKET_CODEC);
S2CPacketType<MsgUnlockTraits> UNLOCK_TRAITS = SimpleNetworking.serverToClient(Unicopia.id("unlock_traits"), MsgUnlockTraits::new); S2CPacketType<MsgUnlockTraits> UNLOCK_TRAITS = SimpleNetworking.serverToClient(Unicopia.id("unlock_traits"), MsgUnlockTraits.PACKET_CODEC);
S2CPacketType<MsgTribeSelect> SERVER_SELECT_TRIBE = SimpleNetworking.serverToClient(Unicopia.id("select_tribe"), MsgTribeSelect::new); S2CPacketType<MsgTribeSelect> SERVER_SELECT_TRIBE = SimpleNetworking.serverToClient(Unicopia.id("select_tribe"), MsgTribeSelect.PACKET_CODEC);
S2CPacketType<MsgSpellbookStateChanged<PlayerEntity>> SERVER_SPELLBOOK_UPDATE = SimpleNetworking.serverToClient(Unicopia.id("server_spellbook_update"), MsgSpellbookStateChanged::new); S2CPacketType<MsgSpellbookStateChanged<PlayerEntity>> SERVER_SPELLBOOK_UPDATE = SimpleNetworking.serverToClient(Unicopia.id("server_spellbook_update"), MsgSpellbookStateChanged.packetCodec());
C2SPacketType<MsgSpellbookStateChanged<ServerPlayerEntity>> CLIENT_SPELLBOOK_UPDATE = SimpleNetworking.clientToServer(Unicopia.id("client_spellbook_update"), MsgSpellbookStateChanged::new); C2SPacketType<MsgSpellbookStateChanged<ServerPlayerEntity>> CLIENT_SPELLBOOK_UPDATE = SimpleNetworking.clientToServer(Unicopia.id("client_spellbook_update"), MsgSpellbookStateChanged.packetCodec());
S2CPacketType<MsgServerResources> SERVER_RESOURCES = SimpleNetworking.serverToClient(Unicopia.id("resources"), MsgServerResources.PACKET_CODEC); S2CPacketType<MsgServerResources> SERVER_RESOURCES = SimpleNetworking.serverToClient(Unicopia.id("resources"), MsgServerResources.PACKET_CODEC);
S2CPacketType<MsgTrackedValues> SERVER_TRACKED_ENTITY_DATA = SimpleNetworking.serverToClient(Unicopia.id("tracked_entity_date"), MsgTrackedValues::new); S2CPacketType<MsgTrackedValues> SERVER_TRACKED_ENTITY_DATA = SimpleNetworking.serverToClient(Unicopia.id("tracked_entity_date"), MsgTrackedValues.PACKET_CODEC);
S2CPacketType<MsgPlayerAnimationChange> SERVER_PLAYER_ANIMATION_CHANGE = SimpleNetworking.serverToClient(Unicopia.id("player_animation_change"), MsgPlayerAnimationChange::new); S2CPacketType<MsgPlayerAnimationChange> SERVER_PLAYER_ANIMATION_CHANGE = SimpleNetworking.serverToClient(Unicopia.id("player_animation_change"), MsgPlayerAnimationChange.PACKET_CODEC);
S2CPacketType<MsgSkyAngle> SERVER_SKY_ANGLE = SimpleNetworking.serverToClient(Unicopia.id("sky_angle"), MsgSkyAngle::new); S2CPacketType<MsgSkyAngle> SERVER_SKY_ANGLE = SimpleNetworking.serverToClient(Unicopia.id("sky_angle"), MsgSkyAngle.PACKET_CODEC);
S2CPacketType<MsgConfigurationChange> CONFIGURATION_CHANGE = SimpleNetworking.serverToClient(Unicopia.id("config"), MsgConfigurationChange::new); S2CPacketType<MsgConfigurationChange> CONFIGURATION_CHANGE = SimpleNetworking.serverToClient(Unicopia.id("config"), MsgConfigurationChange.PACKET_CODEC);
S2CPacketType<MsgZapAppleStage> SERVER_ZAP_STAGE = SimpleNetworking.serverToClient(Unicopia.id("zap_stage"), MsgZapAppleStage::new); S2CPacketType<MsgZapAppleStage> SERVER_ZAP_STAGE = SimpleNetworking.serverToClient(Unicopia.id("zap_stage"), MsgZapAppleStage.PACKET_CODEC);
S2CPacketType<MsgTrinketBroken> SERVER_TRINKET_BROKEN = SimpleNetworking.serverToClient(Unicopia.id("trinket_broken"), MsgTrinketBroken.PACKET_CODEC); S2CPacketType<MsgTrinketBroken> SERVER_TRINKET_BROKEN = SimpleNetworking.serverToClient(Unicopia.id("trinket_broken"), MsgTrinketBroken.PACKET_CODEC);
static void bootstrap() { static void bootstrap() {

View file

@ -1,29 +1,17 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import com.sollace.fabwork.api.packets.Packet; import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
/** /**
* Sent by the server to update block destruction progress on the client. * Sent by the server to update block destruction progress on the client.
*/ */
public record MsgBlockDestruction (Long2ObjectMap<Float> destructions) implements Packet { public record MsgBlockDestruction(Long2ObjectMap<Float> destructions) {
MsgBlockDestruction(PacketByteBuf buffer) { public static final PacketCodec<ByteBuf, MsgBlockDestruction> PACKET_CODEC = PacketCodec.tuple(
this(new Long2ObjectOpenHashMap<>()); PacketCodecs.map(Long2ObjectOpenHashMap::new, PacketCodecs.VAR_LONG, PacketCodecs.FLOAT), MsgBlockDestruction::destructions,
int size = buffer.readInt(); MsgBlockDestruction::new
for (int i = 0; i < size; i++) { );
destructions.put(buffer.readLong(), (Float)buffer.readFloat());
}
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(destructions.size());
destructions.forEach((p, i) -> {
buffer.writeLong(p);
buffer.writeFloat(i);
});
}
} }

View file

@ -7,45 +7,33 @@ import com.minelittlepony.unicopia.ability.magic.Caster;
import com.minelittlepony.unicopia.ability.magic.SpellPredicate; import com.minelittlepony.unicopia.ability.magic.SpellPredicate;
import com.minelittlepony.unicopia.ability.magic.spell.OrientedSpell; import com.minelittlepony.unicopia.ability.magic.spell.OrientedSpell;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import com.sollace.fabwork.api.packets.Packet; import io.netty.buffer.ByteBuf;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Uuids;
/** /**
* Sent to the client when the server needs to know precisely where the player is looking. * Sent to the client when the server needs to know precisely where the player is looking.
*/ */
public record MsgCasterLookRequest (UUID spellId) implements Packet { public record MsgCasterLookRequest (UUID spellId) {
public static final PacketCodec<ByteBuf, MsgCasterLookRequest> PACKET_CODEC = Uuids.PACKET_CODEC.xmap(MsgCasterLookRequest::new, MsgCasterLookRequest::spellId);
public MsgCasterLookRequest(PacketByteBuf buffer) {
this(buffer.readUuid());
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeUuid(spellId);
}
public record Reply ( public record Reply (
UUID spellId, UUID spellId,
Rot rotation Rot rotation
) implements HandledPacket<ServerPlayerEntity> { ) implements Handled<ServerPlayerEntity> {
public static final PacketCodec<PacketByteBuf, Reply> PACKET_CODEC = PacketCodec.tuple(
Reply(PacketByteBuf buffer) { Uuids.PACKET_CODEC, Reply::spellId,
this(buffer.readUuid(), Rot.CODEC.decode(buffer)); Rot.CODEC, Reply::rotation,
} Reply::new
);
public Reply(OrientedSpell spell, Caster<?> caster) { public Reply(OrientedSpell spell, Caster<?> caster) {
this(spell.getUuid(), Rot.of(caster)); this(spell.getUuid(), Rot.of(caster));
} }
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeUuid(spellId);
Rot.CODEC.encode(buffer, rotation);
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {
Pony pony = Pony.of(sender); Pony pony = Pony.of(sender);

View file

@ -1,24 +1,9 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import java.util.HashSet;
import com.minelittlepony.unicopia.SyncedConfig; import com.minelittlepony.unicopia.SyncedConfig;
import com.sollace.fabwork.api.packets.Packet; import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.PacketByteBuf;
public record MsgConfigurationChange(SyncedConfig config) implements Packet {
public MsgConfigurationChange(PacketByteBuf buffer) {
this(new SyncedConfig(
buffer.readCollection(HashSet::new, PacketByteBuf::readString),
buffer.readCollection(HashSet::new, PacketByteBuf::readString)
));
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeCollection(config.wantItNeedItExcludeList(), PacketByteBuf::writeString);
buffer.writeCollection(config.dimensionsWithoutAtmosphere(), PacketByteBuf::writeString);
}
public record MsgConfigurationChange(SyncedConfig config) {
public static final PacketCodec<ByteBuf, MsgConfigurationChange> PACKET_CODEC = SyncedConfig.PACKET_CODEC.xmap(MsgConfigurationChange::new, MsgConfigurationChange::config);
} }

View file

@ -5,25 +5,17 @@ import java.util.Set;
import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait; import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
public record MsgMarkTraitRead (Set<Trait> traits) implements HandledPacket<ServerPlayerEntity> { public record MsgMarkTraitRead (Set<Trait> traits) implements Handled<ServerPlayerEntity> {
MsgMarkTraitRead(PacketByteBuf buffer) { public static final PacketCodec<PacketByteBuf, MsgMarkTraitRead> PACKET_CODEC = PacketCodec.tuple(
this(new HashSet<>()); Trait.PACKET_CODEC.collect(PacketCodecs.toCollection(HashSet::new)), MsgMarkTraitRead::traits,
int length = buffer.readInt(); MsgMarkTraitRead::new
for (int i = 0; i < length; i++) { );
Trait.fromId(buffer.readIdentifier()).ifPresent(traits::add);
}
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(traits.size());
traits.forEach(trait -> buffer.writeIdentifier(trait.getId()));
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {

View file

@ -1,15 +1,13 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import java.util.Optional; import java.util.Optional;
import com.minelittlepony.unicopia.ability.Abilities; import com.minelittlepony.unicopia.ability.Abilities;
import com.minelittlepony.unicopia.ability.Ability; import com.minelittlepony.unicopia.ability.Ability;
import com.minelittlepony.unicopia.ability.ActivationType; import com.minelittlepony.unicopia.ability.ActivationType;
import com.minelittlepony.unicopia.ability.data.Hit; import com.minelittlepony.unicopia.ability.data.Hit;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
@ -20,29 +18,28 @@ public record MsgPlayerAbility<T extends Hit> (
Ability<T> power, Ability<T> power,
Optional<T> data, Optional<T> data,
ActivationType type ActivationType type
) implements HandledPacket<ServerPlayerEntity> { ) implements Handled<ServerPlayerEntity> {
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings("unchecked") public static final PacketCodec<RegistryByteBuf, MsgPlayerAbility<?>> PACKET_CODEC = PacketCodec.of(
static <T extends Hit> MsgPlayerAbility<T> read(PacketByteBuf buffer) { (packet, buffer) -> {
Ability<T> power = (Ability<T>) Abilities.REGISTRY.get(buffer.readIdentifier()); Abilities.PACKET_CODEC.encode(buffer, packet.power());
return new MsgPlayerAbility<>( buffer.writeOptional(packet.data(), (b, d) -> ((PacketCodec)packet.power().getSerializer()).encode(buffer, d));
power, ActivationType.PACKET_CODEC.encode(buffer, packet.type());
buffer.readOptional(b -> ((PacketCodec<PacketByteBuf, T>)power.getSerializer()).decode(b)), },
ActivationType.of(buffer.readInt()) buffer -> {
); Ability<?> power = Abilities.PACKET_CODEC.decode(buffer);
} return new MsgPlayerAbility(
power,
@SuppressWarnings("unchecked") buffer.readOptional(b -> power.getSerializer().decode(buffer)),
@Override ActivationType.PACKET_CODEC.decode(buffer)
public void toBuffer(PacketByteBuf buffer) { );
buffer.writeIdentifier(Abilities.REGISTRY.getId(power)); }
buffer.writeOptional(data, (b, d) -> ((PacketCodec<PacketByteBuf, T>)power.getSerializer()).encode(b, d)); );
buffer.writeInt(type.ordinal());
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {
Pony player = Pony.of(sender); Pony player = Pony.of(sender);
if (player == null) { if (player == null) {
return; return;
} }

View file

@ -2,12 +2,12 @@ package com.minelittlepony.unicopia.network;
import java.util.UUID; import java.util.UUID;
import com.minelittlepony.unicopia.client.render.PlayerPoser.Animation;
import com.minelittlepony.unicopia.client.render.PlayerPoser.AnimationInstance; import com.minelittlepony.unicopia.client.render.PlayerPoser.AnimationInstance;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.Packet;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.util.Uuids;
/** /**
* Sent to the client when a player's animation changes. * Sent to the client when a player's animation changes.
@ -16,28 +16,15 @@ public record MsgPlayerAnimationChange (
UUID playerId, UUID playerId,
AnimationInstance animation, AnimationInstance animation,
int duration int duration
) implements Packet { ) {
public static final PacketCodec<PacketByteBuf, MsgPlayerAnimationChange> PACKET_CODEC = PacketCodec.tuple(
MsgPlayerAnimationChange(PacketByteBuf buffer) { Uuids.PACKET_CODEC, MsgPlayerAnimationChange::playerId,
this( AnimationInstance.PACKET_CODEC, MsgPlayerAnimationChange::animation,
buffer.readUuid(), PacketCodecs.INTEGER, MsgPlayerAnimationChange::duration,
new AnimationInstance( MsgPlayerAnimationChange::new
buffer.readEnumConstant(Animation.class), );
buffer.readEnumConstant(Animation.Recipient.class)
),
buffer.readInt()
);
}
public MsgPlayerAnimationChange(Pony player, AnimationInstance animation, int duration) { public MsgPlayerAnimationChange(Pony player, AnimationInstance animation, int duration) {
this(player.asEntity().getUuid(), animation, duration); this(player.asEntity().getUuid(), animation, duration);
} }
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeUuid(playerId);
buffer.writeEnumConstant(animation.animation());
buffer.writeEnumConstant(animation.recipient());
buffer.writeInt(duration);
}
} }

View file

@ -1,9 +1,9 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs; import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtCompound;
@ -13,15 +13,20 @@ import net.minecraft.nbt.NbtCompound;
* <p> * <p>
* Also used by the server to notify a race change. * Also used by the server to notify a race change.
*/ */
public class MsgPlayerCapabilities implements HandledPacket<PlayerEntity> { public class MsgPlayerCapabilities implements Handled<PlayerEntity> {
public static final PacketCodec<RegistryByteBuf, MsgPlayerCapabilities> PACKET_CODEC = PacketCodec.tuple(
PacketCodecs.INTEGER, i -> i.playerId,
PacketCodecs.NBT_COMPOUND, i -> i.compoundTag,
MsgPlayerCapabilities::new
);
protected final int playerId; protected final int playerId;
private final NbtCompound compoundTag; private final NbtCompound compoundTag;
MsgPlayerCapabilities(PacketByteBuf buffer) { MsgPlayerCapabilities(int playerId, NbtCompound compoundTag) {
playerId = buffer.readInt(); this.playerId = playerId;
compoundTag = PacketCodecs.NBT_COMPOUND.decode(buffer); this.compoundTag = compoundTag;
} }
public MsgPlayerCapabilities(Pony player) { public MsgPlayerCapabilities(Pony player) {
@ -30,12 +35,6 @@ public class MsgPlayerCapabilities implements HandledPacket<PlayerEntity> {
player.toSyncronisedNbt(compoundTag, player.asWorld().getRegistryManager()); player.toSyncronisedNbt(compoundTag, player.asWorld().getRegistryManager());
} }
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(playerId);
PacketCodecs.NBT_COMPOUND.encode(buffer, compoundTag);
}
@Override @Override
public void handle(PlayerEntity sender) { public void handle(PlayerEntity sender) {
Pony player = Pony.of(sender.getWorld().getEntityById(playerId)).orElse(null); Pony player = Pony.of(sender.getWorld().getEntityById(playerId)).orElse(null);

View file

@ -1,29 +1,26 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.network.PacketByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
public record MsgPlayerFlightControlsInput ( public record MsgPlayerFlightControlsInput (
boolean ascending, boolean ascending,
boolean descending boolean descending
) implements HandledPacket<ServerPlayerEntity> { ) implements Handled<ServerPlayerEntity> {
public static final PacketCodec<ByteBuf, MsgPlayerFlightControlsInput> PACKET_CODEC = PacketCodec.tuple(
PacketCodecs.BOOL, MsgPlayerFlightControlsInput::ascending,
PacketCodecs.BOOL, MsgPlayerFlightControlsInput::descending,
MsgPlayerFlightControlsInput::new
);
public MsgPlayerFlightControlsInput(Pony pony) { public MsgPlayerFlightControlsInput(Pony pony) {
this(pony.getJumpingHeuristic().getState(), pony.asEntity().isSneaking()); this(pony.getJumpingHeuristic().getState(), pony.asEntity().isSneaking());
} }
public MsgPlayerFlightControlsInput(PacketByteBuf buffer) {
this(buffer.readBoolean(), buffer.readBoolean());
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeBoolean(ascending);
buffer.writeBoolean(descending);
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {
sender.setSneaking(descending); sender.setSneaking(descending);

View file

@ -4,28 +4,22 @@ import java.util.UUID;
import com.minelittlepony.unicopia.ability.magic.spell.Spell; import com.minelittlepony.unicopia.ability.magic.spell.Spell;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Uuids;
/** /**
* Sent to the server when a player dismisses a spell from their dismiss spell screen * Sent to the server when a player dismisses a spell from their dismiss spell screen
*/ */
public record MsgRemoveSpell (UUID id) implements HandledPacket<ServerPlayerEntity> { public record MsgRemoveSpell (UUID id) implements Handled<ServerPlayerEntity> {
MsgRemoveSpell(PacketByteBuf buffer) { public static final PacketCodec<ByteBuf, MsgRemoveSpell> PACKET_CODEC = Uuids.PACKET_CODEC.xmap(MsgRemoveSpell::new, MsgRemoveSpell::id);
this(buffer.readUuid());
}
public MsgRemoveSpell(Spell spell) { public MsgRemoveSpell(Spell spell) {
this(spell.getUuid()); this(spell.getUuid());
} }
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeUuid(id);
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {
Pony player = Pony.of(sender); Pony player = Pony.of(sender);

View file

@ -4,9 +4,10 @@ import com.minelittlepony.unicopia.*;
import com.minelittlepony.unicopia.entity.player.Pony; import com.minelittlepony.unicopia.entity.player.Pony;
import com.minelittlepony.unicopia.server.world.UGameRules; import com.minelittlepony.unicopia.server.world.UGameRules;
import com.minelittlepony.unicopia.server.world.UnicopiaWorldProperties; import com.minelittlepony.unicopia.server.world.UnicopiaWorldProperties;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.*; import net.minecraft.text.*;
@ -19,17 +20,12 @@ import net.minecraft.text.*;
public record MsgRequestSpeciesChange ( public record MsgRequestSpeciesChange (
boolean force, boolean force,
Race newRace Race newRace
) implements HandledPacket<ServerPlayerEntity> { ) implements Handled<ServerPlayerEntity> {
public static final PacketCodec<RegistryByteBuf, MsgRequestSpeciesChange> PACKET_CODEC = PacketCodec.tuple(
MsgRequestSpeciesChange(PacketByteBuf buffer) { PacketCodecs.BOOL, MsgRequestSpeciesChange::force,
this(buffer.readBoolean(), Race.REGISTRY.get(buffer.readRegistryKey(Race.REGISTRY_KEY))); PacketCodecs.registryValue(Race.REGISTRY_KEY), MsgRequestSpeciesChange::newRace,
} MsgRequestSpeciesChange::new
);
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeBoolean(force);
buffer.writeRegistryKey(Race.REGISTRY.getKey(newRace).get());
}
@Override @Override
public void handle(ServerPlayerEntity sender) { public void handle(ServerPlayerEntity sender) {

View file

@ -1,19 +1,11 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import com.sollace.fabwork.api.packets.Packet; import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.codec.PacketCodecs;
public record MsgSkyAngle ( public record MsgSkyAngle (
float tangentalSkyAngle float tangentalSkyAngle
) implements Packet { ) {
public static final PacketCodec<ByteBuf, MsgSkyAngle> PACKET_CODEC = PacketCodecs.FLOAT.xmap(MsgSkyAngle::new, MsgSkyAngle::tangentalSkyAngle);
public MsgSkyAngle(PacketByteBuf buffer) {
this(buffer.readFloat());
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeFloat(tangentalSkyAngle());
}
} }

View file

@ -2,11 +2,11 @@ package com.minelittlepony.unicopia.network;
import com.minelittlepony.unicopia.container.SpellbookScreenHandler; import com.minelittlepony.unicopia.container.SpellbookScreenHandler;
import com.minelittlepony.unicopia.container.SpellbookState; import com.minelittlepony.unicopia.container.SpellbookState;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.RegistryByteBuf; import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
/** /**
@ -16,22 +16,22 @@ import net.minecraft.server.network.ServerPlayerEntity;
public record MsgSpellbookStateChanged<T extends PlayerEntity> ( public record MsgSpellbookStateChanged<T extends PlayerEntity> (
int syncId, int syncId,
SpellbookState state SpellbookState state
) implements HandledPacket<T> { ) implements Handled<T> {
private static final PacketCodec<RegistryByteBuf, MsgSpellbookStateChanged<?>> PACKET_CODEC = PacketCodec.tuple(
PacketCodecs.INTEGER, MsgSpellbookStateChanged::syncId,
SpellbookState.PACKET_CODEC, MsgSpellbookStateChanged::state,
MsgSpellbookStateChanged::new
);
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends PlayerEntity> PacketCodec<RegistryByteBuf, MsgSpellbookStateChanged<T>> packetCodec() {
return (PacketCodec)PACKET_CODEC;
}
public static <T extends PlayerEntity> MsgSpellbookStateChanged<T> create(SpellbookScreenHandler handler, SpellbookState state) { public static <T extends PlayerEntity> MsgSpellbookStateChanged<T> create(SpellbookScreenHandler handler, SpellbookState state) {
return new MsgSpellbookStateChanged<>(handler.syncId, state); return new MsgSpellbookStateChanged<>(handler.syncId, state);
} }
public MsgSpellbookStateChanged(RegistryByteBuf buffer) {
this(buffer.readInt(), SpellbookState.PACKET_CODEC.decode(buffer));
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(syncId);
SpellbookState.PACKET_CODEC.encode((RegistryByteBuf)buffer, state);
}
@Override @Override
public void handle(T sender) { public void handle(T sender) {
if (sender.currentScreenHandler.syncId != syncId) { if (sender.currentScreenHandler.syncId != syncId) {

View file

@ -4,21 +4,14 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import com.minelittlepony.unicopia.Race; import com.minelittlepony.unicopia.Race;
import com.sollace.fabwork.api.packets.Packet; import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.network.PacketByteBuf; public record MsgTribeSelect (Set<Race> availableRaces, String serverMessage) {
public static final PacketCodec<RegistryByteBuf, MsgTribeSelect> PACKET_CODEC = PacketCodec.tuple(
public record MsgTribeSelect (Set<Race> availableRaces, String serverMessage) implements Packet { PacketCodecs.registryValue(Race.REGISTRY_KEY).collect(PacketCodecs.toCollection(HashSet::new)), MsgTribeSelect::availableRaces,
public MsgTribeSelect(PacketByteBuf buffer) { PacketCodecs.STRING, MsgTribeSelect::serverMessage,
this( MsgTribeSelect::new
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.writeRegistryKey(Race.REGISTRY.getKey(race).get()));
buffer.writeString(serverMessage);
}
} }

View file

@ -4,26 +4,17 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait; import com.minelittlepony.unicopia.ability.magic.spell.trait.Trait;
import com.sollace.fabwork.api.packets.Packet;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
public record MsgUnlockTraits (Set<Trait> traits) implements Packet { public record MsgUnlockTraits (Set<Trait> traits) {
MsgUnlockTraits(PacketByteBuf buffer) { public static final PacketCodec<PacketByteBuf, MsgUnlockTraits> PACKET_CODEC = PacketCodec.tuple(
this(new HashSet<>()); Trait.PACKET_CODEC.collect(PacketCodecs.toCollection(HashSet::new)), MsgUnlockTraits::traits,
int length = buffer.readInt(); MsgUnlockTraits::new
for (int i = 0; i < length; i++) { );
Trait.fromId(buffer.readIdentifier()).ifPresent(traits::add);
}
}
public MsgUnlockTraits(Set<Trait> traits) { public MsgUnlockTraits(Set<Trait> traits) {
this.traits = new HashSet<>(traits); this.traits = new HashSet<>(traits);
} }
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(traits.size());
traits.forEach(trait -> buffer.writeIdentifier(trait.getId()));
}
} }

View file

@ -1,20 +1,11 @@
package com.minelittlepony.unicopia.network; package com.minelittlepony.unicopia.network;
import com.minelittlepony.unicopia.server.world.ZapAppleStageStore; import com.minelittlepony.unicopia.server.world.ZapAppleStageStore;
import com.sollace.fabwork.api.packets.Packet; import io.netty.buffer.ByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.PacketByteBuf;
public record MsgZapAppleStage ( public record MsgZapAppleStage (
ZapAppleStageStore.Stage stage ZapAppleStageStore.Stage stage
) implements Packet { ) {
public static final PacketCodec<ByteBuf, MsgZapAppleStage> PACKET_CODEC = ZapAppleStageStore.Stage.PACKET_CODEC.xmap(MsgZapAppleStage::new, MsgZapAppleStage::stage);
public MsgZapAppleStage(PacketByteBuf buffer) {
this(buffer.readEnumConstant(ZapAppleStageStore.Stage.class));
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeEnumConstant(stage);
}
} }

View file

@ -10,8 +10,7 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils; import com.minelittlepony.unicopia.util.serialization.PacketCodecUtils;
import com.sollace.fabwork.api.packets.HandledPacket; import com.sollace.fabwork.api.packets.Handled;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf; import net.minecraft.network.PacketByteBuf;
@ -23,21 +22,13 @@ public record MsgTrackedValues(
int owner, int owner,
Optional<TrackerObjects> updatedObjects, Optional<TrackerObjects> updatedObjects,
Optional<TrackerEntries> updatedTrackers Optional<TrackerEntries> updatedTrackers
) implements HandledPacket<PlayerEntity> { ) implements Handled<PlayerEntity> {
public MsgTrackedValues(PacketByteBuf buffer) { public static final PacketCodec<PacketByteBuf, MsgTrackedValues> PACKET_CODEC = PacketCodec.tuple(
this( PacketCodecs.INTEGER, MsgTrackedValues::owner,
buffer.readInt(), PacketCodecs.optional(TrackerObjects.PACKET_CODEC), MsgTrackedValues::updatedObjects,
TrackerObjects.OPTIONAL_PACKET_CODEC.decode(buffer), PacketCodecs.optional(TrackerEntries.PACKET_CODEC), MsgTrackedValues::updatedTrackers,
TrackerEntries.OPTIONAL_PACKET_CODEC.decode(buffer) MsgTrackedValues::new
); );
}
@Override
public void toBuffer(PacketByteBuf buffer) {
buffer.writeInt(owner);
TrackerObjects.OPTIONAL_PACKET_CODEC.encode(buffer, updatedObjects);
TrackerEntries.OPTIONAL_PACKET_CODEC.encode(buffer, updatedTrackers);
}
@Override @Override
public void handle(PlayerEntity sender) { public void handle(PlayerEntity sender) {
@ -54,7 +45,6 @@ public record MsgTrackedValues(
PacketCodecs.map(HashMap::new, Uuids.PACKET_CODEC, PacketCodecUtils.BUFFER), TrackerObjects::values, PacketCodecs.map(HashMap::new, Uuids.PACKET_CODEC, PacketCodecUtils.BUFFER), TrackerObjects::values,
TrackerObjects::new TrackerObjects::new
); );
public static final PacketCodec<PacketByteBuf, Optional<TrackerObjects>> OPTIONAL_PACKET_CODEC = PacketCodecs.optional(PACKET_CODEC);
} }
public record TrackerEntries(int id, boolean wipe, List<DataTracker.Pair<?>> values, Map<Integer, PacketByteBuf> objects) { public record TrackerEntries(int id, boolean wipe, List<DataTracker.Pair<?>> values, Map<Integer, PacketByteBuf> objects) {
@ -65,6 +55,5 @@ public record MsgTrackedValues(
PacketCodecs.map(HashMap::new, PacketCodecs.INTEGER, PacketCodecUtils.BUFFER), TrackerEntries::objects, PacketCodecs.map(HashMap::new, PacketCodecs.INTEGER, PacketCodecUtils.BUFFER), TrackerEntries::objects,
TrackerEntries::new TrackerEntries::new
); );
public static final PacketCodec<PacketByteBuf, Optional<TrackerEntries>> OPTIONAL_PACKET_CODEC = PacketCodecs.optional(PACKET_CODEC);
} }
} }

View file

@ -14,9 +14,12 @@ import com.minelittlepony.unicopia.particle.ParticleUtils;
import com.minelittlepony.unicopia.util.MeteorlogicalUtil; import com.minelittlepony.unicopia.util.MeteorlogicalUtil;
import com.minelittlepony.unicopia.util.Tickable; import com.minelittlepony.unicopia.util.Tickable;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.entity.LightningEntity; import net.minecraft.entity.LightningEntity;
import net.minecraft.nbt.*; import net.minecraft.nbt.*;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.registry.RegistryWrapper.WrapperLookup; import net.minecraft.registry.RegistryWrapper.WrapperLookup;
import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundCategory;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
@ -153,6 +156,8 @@ public class ZapAppleStageStore extends PersistentState implements Tickable {
static final Stage[] VALUES = values(); static final Stage[] VALUES = values();
static final float MAX = VALUES.length; static final float MAX = VALUES.length;
public static final PacketCodec<ByteBuf, Stage> PACKET_CODEC = PacketCodecs.indexed(i -> VALUES[i], Stage::ordinal);
private final float ordinal = ordinal(); private final float ordinal = ordinal();
public Stage getNext() { public Stage getNext() {
@ -180,7 +185,7 @@ public class ZapAppleStageStore extends PersistentState implements Tickable {
return MathHelper.lerp(getStageProgress(world), ordinal, ordinal + 1) / MAX; return MathHelper.lerp(getStageProgress(world), ordinal, ordinal + 1) / MAX;
} }
public static Stage byId(int id) { private static Stage byId(int id) {
return VALUES[MathHelper.clamp(id, 0, VALUES.length)]; return VALUES[MathHelper.clamp(id, 0, VALUES.length)];
} }

View file

@ -1,8 +1,10 @@
package com.minelittlepony.unicopia.util.serialization; package com.minelittlepony.unicopia.util.serialization;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.IntFunction; import java.util.function.IntFunction;
@ -12,6 +14,7 @@ import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs; import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKey;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@ -35,6 +38,17 @@ public interface PacketCodecUtils {
); );
PacketCodec<PacketByteBuf, Optional<Vec3d>> OPTIONAL_VECTOR = PacketCodecs.optional(VECTOR); PacketCodec<PacketByteBuf, Optional<Vec3d>> OPTIONAL_VECTOR = PacketCodecs.optional(VECTOR);
PacketCodec<ByteBuf, Optional<BlockPos>> OPTIONAL_POS = PacketCodecs.optional(BlockPos.PACKET_CODEC); PacketCodec<ByteBuf, Optional<BlockPos>> OPTIONAL_POS = PacketCodecs.optional(BlockPos.PACKET_CODEC);
PacketCodec<ByteBuf, Set<String>> STRING_SET = PacketCodecs.STRING.collect(PacketCodecs.toCollection(HashSet::new));
Function<Class<?>, PacketCodec<ByteBuf, ?>> ENUM_CODEC_CACHE = Util.memoize(type -> {
final Object[] values = type.getEnumConstants();
return PacketCodecs.indexed(i -> values[i], i -> ((Enum<?>)i).ordinal());
});
@SuppressWarnings("unchecked")
static <T extends Enum<T>> PacketCodec<ByteBuf, T> ofEnum(Class<T> type) {
return (PacketCodec<ByteBuf, T>)ENUM_CODEC_CACHE.apply(type);
}
static <B extends ByteBuf, K, V> PacketCodec.ResultFunction<B, V, Map<K, V>> toMap(Function<V, K> keyFunction) { static <B extends ByteBuf, K, V> PacketCodec.ResultFunction<B, V, Map<K, V>> toMap(Function<V, K> keyFunction) {
return codec -> map(HashMap::new, codec, keyFunction, -1); return codec -> map(HashMap::new, codec, keyFunction, -1);