Skip to content

Commit

Permalink
Migrate networking
Browse files Browse the repository at this point in the history
  • Loading branch information
Gaming32 committed Apr 19, 2024
1 parent b69a669 commit 9d91e4d
Show file tree
Hide file tree
Showing 23 changed files with 224 additions and 245 deletions.
18 changes: 9 additions & 9 deletions common/src/main/java/io/github/gaming32/bingo/Bingo.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,14 @@ public static void init() {
});

BingoNetworking.instance().onRegister(registrar -> {
registrar.register(PacketFlow.CLIENTBOUND, InitBoardPacket.ID, InitBoardPacket::new);
registrar.register(PacketFlow.CLIENTBOUND, RemoveBoardPacket.ID, buf -> RemoveBoardPacket.INSTANCE);
registrar.register(PacketFlow.CLIENTBOUND, ResyncStatesPacket.ID, ResyncStatesPacket::new);
registrar.register(PacketFlow.CLIENTBOUND, SyncTeamPacket.ID, SyncTeamPacket::new);
registrar.register(PacketFlow.CLIENTBOUND, UpdateProgressPacket.ID, UpdateProgressPacket::new);
registrar.register(PacketFlow.CLIENTBOUND, UpdateStatePacket.ID, UpdateStatePacket::new);

registrar.register(PacketFlow.SERVERBOUND, KeyPressedPacket.ID, KeyPressedPacket::new);
registrar.register(PacketFlow.CLIENTBOUND, InitBoardPacket.TYPE, InitBoardPacket.CODEC);
registrar.register(PacketFlow.CLIENTBOUND, RemoveBoardPacket.TYPE, RemoveBoardPacket.CODEC);
registrar.register(PacketFlow.CLIENTBOUND, ResyncStatesPacket.TYPE, ResyncStatesPacket.CODEC);
registrar.register(PacketFlow.CLIENTBOUND, SyncTeamPacket.TYPE, SyncTeamPacket.CODEC);
registrar.register(PacketFlow.CLIENTBOUND, UpdateProgressPacket.TYPE, UpdateProgressPacket.CODEC);
registrar.register(PacketFlow.CLIENTBOUND, UpdateStatePacket.TYPE, UpdateStatePacket.CODEC);

registrar.register(PacketFlow.SERVERBOUND, KeyPressedPacket.TYPE, KeyPressedPacket.CODEC);
});

if (BingoPlatform.platform.isClient()) {
Expand Down Expand Up @@ -227,6 +227,6 @@ public static MutableComponent ensureHasFallback(MutableComponent component) {
}

public static boolean isInstalledOnClient(ServerPlayer player) {
return BingoNetworking.instance().canPlayerReceive(player, InitBoardPacket.ID);
return BingoNetworking.instance().canPlayerReceive(player, InitBoardPacket.TYPE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ private IconRenderers() {
}

public static <I extends GoalIcon> void register(GoalIconType<I> iconType, IconRenderer<I> renderer) {
final ResourceLocation id = GoalIconType.REGISTRAR.registry().getKey(iconType);
final ResourceLocation id = GoalIconType.REGISTER.registry().getKey(iconType);
if (id == null) {
throw new IllegalArgumentException("Tried to register renderer for unregistered icon type " + iconType);
}
Expand All @@ -28,7 +28,7 @@ public static <I extends GoalIcon> void register(RegistryValue<GoalIconType<I>>
}

public static <I extends GoalIcon> IconRenderer<I> getRenderer(GoalIconType<I> iconType) {
final ResourceLocation id = GoalIconType.REGISTRAR.registry().getKey(iconType);
final ResourceLocation id = GoalIconType.REGISTER.registry().getKey(iconType);
if (id == null) {
throw new NoSuchElementException("Unknown id for icon type " + iconType);
}
Expand Down
12 changes: 8 additions & 4 deletions common/src/main/java/io/github/gaming32/bingo/data/BingoTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
import com.mojang.serialization.DataResult;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.gaming32.bingo.Bingo;
import io.github.gaming32.bingo.util.BingoStreamCodecs;
import io.github.gaming32.bingo.util.BingoUtil;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatImmutableList;
import it.unimi.dsi.fastutil.floats.FloatList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
Expand All @@ -30,8 +33,8 @@

public record BingoTag(FloatList difficultyMax, boolean allowedOnSameLine, SpecialType specialType) {
private static final Codec<FloatList> DIFFICULTY_MAX_CODEC = ExtraCodecs.nonEmptyList(
ExtraCodecs.validate(
Codec.FLOAT, f -> f >= 0f && f <= 1f
Codec.FLOAT.validate(
f -> f >= 0f && f <= 1f
? DataResult.success(f)
: DataResult.error(() -> "Value in difficulty_max must be in range [0,1]")
).listOf()
Expand All @@ -40,8 +43,8 @@ public record BingoTag(FloatList difficultyMax, boolean allowedOnSameLine, Speci
public static final Codec<BingoTag> CODEC = RecordCodecBuilder.create(instance ->
instance.group(
DIFFICULTY_MAX_CODEC.fieldOf("difficulty_max").forGetter(BingoTag::difficultyMax),
ExtraCodecs.strictOptionalField(Codec.BOOL, "allowed_on_same_line", true).forGetter(BingoTag::allowedOnSameLine),
ExtraCodecs.strictOptionalField(SpecialType.CODEC, "special_type", SpecialType.NONE).forGetter(BingoTag::specialType)
Codec.BOOL.optionalFieldOf("allowed_on_same_line", true).forGetter(BingoTag::allowedOnSameLine),
SpecialType.CODEC.optionalFieldOf("special_type", SpecialType.NONE).forGetter(BingoTag::specialType)
).apply(instance, BingoTag::new)
);

Expand Down Expand Up @@ -163,6 +166,7 @@ public enum SpecialType implements StringRepresentable {

@SuppressWarnings("deprecation")
public static final EnumCodec<SpecialType> CODEC = StringRepresentable.fromEnum(SpecialType::values);
public static final StreamCodec<FriendlyByteBuf, SpecialType> STREAM_CODEC = BingoStreamCodecs.enum_(SpecialType.class);

public final int incompleteColor;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package io.github.gaming32.bingo.data.icons;

import com.mojang.serialization.Codec;
import io.netty.buffer.ByteBuf;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.Item;
Expand All @@ -11,10 +14,11 @@
import net.minecraft.world.level.block.state.BlockState;

public interface GoalIcon {
Codec<GoalIcon> CODEC = GoalIconType.REGISTRAR
Codec<GoalIcon> CODEC = GoalIconType.REGISTER
.registry()
.byNameCodec()
.dispatch(GoalIcon::type, type -> type.codec().codec());
.dispatch(GoalIcon::type, GoalIconType::codec);
StreamCodec<ByteBuf, GoalIcon> STREAM_CODEC = ByteBufCodecs.fromCodec(CODEC);

/**
* Used for rendering count, as well as for a fallback for Vanilla clients.
Expand All @@ -25,35 +29,24 @@ public interface GoalIcon {

@SuppressWarnings("unchecked")
static GoalIcon infer(Object obj) {
if (obj == null) {
return EmptyIcon.INSTANCE;
}
if (obj instanceof GoalIcon icon) {
return icon;
}
if (obj instanceof ItemStack stack) {
return new ItemIcon(stack);
}
if (obj instanceof Block block) {
return BlockIcon.ofBlock(block);
}
if (obj instanceof BlockState state) {
return BlockIcon.ofBlock(state);
}
if (obj instanceof ItemLike item) {
return ItemIcon.ofItem(item);
}
if (obj instanceof EntityType<?> entityType) {
return EntityIcon.ofSpawnEgg(entityType);
}
if (obj instanceof TagKey<?> tagKey) {
if (tagKey.registry() == Registries.ITEM) {
return new ItemTagCycleIcon((TagKey<Item>) tagKey);
return switch (obj) {
case null -> EmptyIcon.INSTANCE;
case GoalIcon icon -> icon;
case ItemStack stack -> new ItemIcon(stack);
case Block block -> BlockIcon.ofBlock(block);
case BlockState state -> BlockIcon.ofBlock(state);
case ItemLike item -> ItemIcon.ofItem(item);
case EntityType<?> entityType -> EntityIcon.ofSpawnEgg(entityType);
case TagKey<?> tagKey -> {
if (tagKey.registry() == Registries.ITEM) {
yield new ItemTagCycleIcon((TagKey<Item>)tagKey);
}
if (tagKey.registry() == Registries.ENTITY_TYPE) {
yield new EntityTypeTagCycleIcon((TagKey<EntityType<?>>)tagKey);
}
throw new IllegalArgumentException("No TagCycleIcon for registry " + tagKey.registry().location());
}
if (tagKey.registry() == Registries.ENTITY_TYPE) {
return new EntityTypeTagCycleIcon((TagKey<EntityType<?>>) tagKey);
}
}
throw new IllegalArgumentException("Couldn't infer GoalIcon from " + obj);
default -> throw new IllegalArgumentException("Couldn't infer GoalIcon from " + obj);
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import io.github.gaming32.bingo.platform.registry.RegistryValue;

public interface GoalIconType<I extends GoalIcon> {
DeferredRegister<GoalIconType<?>> REGISTRAR = new RegistryBuilder("goal_icon_type")
DeferredRegister<GoalIconType<?>> REGISTER = new RegistryBuilder("goal_icon_type")
.synced()
.defaultId("empty")
.build();
Expand All @@ -24,7 +24,7 @@ public interface GoalIconType<I extends GoalIcon> {
MapCodec<I> codec();

static <I extends GoalIcon> RegistryValue<GoalIconType<I>> register(String id, MapCodec<I> codec) {
return REGISTRAR.register(id, () -> new GoalIconType<>() {
return REGISTER.register(id, () -> new GoalIconType<>() {
@Override
public MapCodec<I> codec() {
return codec;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
import java.util.stream.Stream;

public interface BingoSub {
Codec<BingoSub> CODEC = BingoSubType.REGISTRAR
Codec<BingoSub> CODEC = BingoSubType.REGISTER
.registry()
.byNameCodec()
.dispatch(BingoSub::type, type -> type.codec().codec());
Codec<BingoSub> INNER_CODEC = BingoSubType.REGISTRAR
.dispatch(BingoSub::type, BingoSubType::codec);
Codec<BingoSub> INNER_CODEC = BingoSubType.REGISTER
.registry()
.byNameCodec()
.dispatch("bingo_type", BingoSub::type, type -> type.codec().codec());
.dispatch("bingo_type", BingoSub::type, BingoSubType::codec);

Dynamic<?> substitute(Map<String, Dynamic<?>> referable, RandomSource rand);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import io.github.gaming32.bingo.platform.registry.RegistryValue;

public interface BingoSubType<S extends BingoSub> {
DeferredRegister<BingoSubType<?>> REGISTRAR = new RegistryBuilder("bingo_sub_type")
DeferredRegister<BingoSubType<?>> REGISTER = new RegistryBuilder("bingo_sub_type")
.build();

RegistryValue<BingoSubType<CompoundBingoSub>> COMPOUND = register("compound", CompoundBingoSub.CODEC);
Expand All @@ -17,7 +17,7 @@ public interface BingoSubType<S extends BingoSub> {
MapCodec<S> codec();

static <S extends BingoSub> RegistryValue<BingoSubType<S>> register(String id, MapCodec<S> codec) {
return REGISTRAR.register(id, () -> new BingoSubType<>() {
return REGISTER.register(id, () -> new BingoSubType<>() {
@Override
public MapCodec<S> codec() {
return codec;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
import io.github.gaming32.bingo.data.BingoTag;
import io.github.gaming32.bingo.util.BingoCodecs;
import io.github.gaming32.bingo.util.BingoUtil;
import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.storage.loot.LootDataResolver;
Expand Down Expand Up @@ -366,6 +369,7 @@ public static final class Teams {
private static final Teams[] CACHE = {NONE, TEAM1, TEAM2, new Teams(0b11)};

public static final Codec<Teams> CODEC = Codec.INT.xmap(Teams::fromBits, Teams::toBits);
public static final StreamCodec<ByteBuf, Teams> STREAM_CODEC = ByteBufCodecs.VAR_INT.map(Teams::fromBits, Teams::toBits);

private final int bits;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import io.github.gaming32.bingo.Bingo;
import io.github.gaming32.bingo.data.BingoGoal;
import io.github.gaming32.bingo.data.BingoTag;
import io.github.gaming32.bingo.util.BingoStreamCodecs;
import net.minecraft.ChatFormatting;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.scores.PlayerTeam;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
Expand Down Expand Up @@ -235,7 +237,7 @@ public String getName() {
"blackout", BLACKOUT
));

Codec<BingoGameMode> PERSISTENCE_CODEC = ExtraCodecs.stringResolverCodec(BingoGameMode::getName, GAME_MODES::get);
Codec<BingoGameMode> PERSISTENCE_CODEC = Codec.stringResolver(BingoGameMode::getName, GAME_MODES::get);

@Nullable
default CommandSyntaxException checkAllowedConfig(GameConfig config) {
Expand Down Expand Up @@ -265,6 +267,8 @@ record GameConfig(BingoGameMode gameMode, int size, Collection<PlayerTeam> teams
}

enum RenderMode {
FANCY, ALL_TEAMS
FANCY, ALL_TEAMS;

public static final StreamCodec<FriendlyByteBuf, RenderMode> STREAM_CODEC = BingoStreamCodecs.enum_(RenderMode.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class MixinKeyMapping {
)
)
private static void onKeyPress(InputConstants.Key key, CallbackInfo ci, @Local KeyMapping keyMapping) {
if (BingoNetworking.instance().canServerReceive(KeyPressedPacket.ID)) {
if (BingoNetworking.instance().canServerReceive(KeyPressedPacket.TYPE)) {
new KeyPressedPacket(keyMapping.getName()).sendToServer();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import net.minecraft.server.level.ServerPlayer;

public abstract class AbstractCustomPayload implements CustomPacketPayload {
protected static ResourceLocation id(String id) {
return new ResourceLocation(Bingo.MOD_ID, id);
protected static <P extends AbstractCustomPayload> Type<P> type(String id) {
return new Type<>(new ResourceLocation(Bingo.MOD_ID, id));
}

public final void sendToServer() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package io.github.gaming32.bingo.network;

import io.github.gaming32.bingo.platform.BingoPlatform;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
Expand Down Expand Up @@ -32,17 +32,24 @@ public void sendTo(Iterable<ServerPlayer> players, CustomPacketPayload packet) {
}
}

public abstract boolean canServerReceive(ResourceLocation id);
public abstract boolean canServerReceive(CustomPacketPayload.Type<?> type);

public abstract boolean canPlayerReceive(ServerPlayer player, ResourceLocation id);
public abstract boolean canPlayerReceive(ServerPlayer player, CustomPacketPayload.Type<?> type);

public abstract static class Registrar {
public abstract <P extends CustomPacketPayload> void register(
@Nullable PacketFlow flow, ResourceLocation id, FriendlyByteBuf.Reader<P> reader, BiConsumer<P, Context> handler
@Nullable PacketFlow flow,
CustomPacketPayload.Type<P> type,
StreamCodec<? super RegistryFriendlyByteBuf, P> codec,
BiConsumer<P, Context> handler
);

public <P extends AbstractCustomPayload> void register(@Nullable PacketFlow flow, ResourceLocation id, FriendlyByteBuf.Reader<P> reader) {
register(flow, id, reader, AbstractCustomPayload::handle);
public <P extends AbstractCustomPayload> void register(
@Nullable PacketFlow flow,
CustomPacketPayload.Type<P> type,
StreamCodec<? super RegistryFriendlyByteBuf, P> codec
) {
register(flow, type, codec, AbstractCustomPayload::handle);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import io.github.gaming32.bingo.data.BingoTag;
import io.github.gaming32.bingo.data.icons.GoalIcon;
import io.github.gaming32.bingo.game.ActiveGoal;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;

import java.util.Optional;
Expand All @@ -18,6 +20,16 @@ public record ClientGoal(
GoalIcon icon,
BingoTag.SpecialType specialType
) {
public static final StreamCodec<RegistryFriendlyByteBuf, ClientGoal> STREAM_CODEC = StreamCodec.composite(
ResourceLocation.STREAM_CODEC, ClientGoal::id,
ComponentSerialization.STREAM_CODEC, ClientGoal::name,
ComponentSerialization.OPTIONAL_STREAM_CODEC, ClientGoal::tooltip,
ResourceLocation.STREAM_CODEC.apply(ByteBufCodecs::optional), ClientGoal::tooltipIcon,
GoalIcon.STREAM_CODEC, ClientGoal::icon,
BingoTag.SpecialType.STREAM_CODEC, ClientGoal::specialType,
ClientGoal::new
);

public ClientGoal(ActiveGoal goal) {
this(
goal.goal().id(),
Expand All @@ -28,26 +40,4 @@ public ClientGoal(ActiveGoal goal) {
goal.goal().goal().getSpecialType()
);
}

@SuppressWarnings("deprecation")
public ClientGoal(FriendlyByteBuf buf) {
this(
buf.readResourceLocation(),
buf.readComponent(),
buf.readOptional(FriendlyByteBuf::readComponent),
buf.readOptional(FriendlyByteBuf::readResourceLocation),
buf.readWithCodecTrusted(NbtOps.INSTANCE, GoalIcon.CODEC),
buf.readEnum(BingoTag.SpecialType.class)
);
}

@SuppressWarnings("deprecation")
public void serialize(FriendlyByteBuf buf) {
buf.writeResourceLocation(id);
buf.writeComponent(name);
buf.writeOptional(tooltip, FriendlyByteBuf::writeComponent);
buf.writeOptional(tooltipIcon, FriendlyByteBuf::writeResourceLocation);
buf.writeWithCodec(NbtOps.INSTANCE, GoalIcon.CODEC, icon);
buf.writeEnum(specialType);
}
}
Loading

0 comments on commit 9d91e4d

Please sign in to comment.