mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-21 20:52:34 +00:00
Forge 1.19.4
Properly move `ServerStatusPing` to codec Reimplement custom display contexts Co-authored-by: Matyrobbrt <[email protected]> Co-authored-by: coehlrich <[email protected]> Signed-off-by: SizableShrimp <[email protected]>
This commit is contained in:
1 parent
1f44339d6e
commit
44c689f171
347 files changed
+2545
-2436
No files matched your search
@@ -107,7 +107,7 @@ public class ConnectionData
|
||||
public static ModMismatchData registry(Multimap<ResourceLocation, ResourceLocation> mismatchedRegistryData, ConnectionData connectionData)
|
||||
{
|
||||
List<ResourceLocation> mismatchedRegistryMods = mismatchedRegistryData.values().stream().map(ResourceLocation::getNamespace).distinct().map(id -> new ResourceLocation(id, "")).toList();
|
||||
Map<ResourceLocation, String> mismatchedRegistryModData = mismatchedRegistryMods.stream().map(id -> ModList.get().getModContainerById(id.getNamespace()).map(modContainer -> Pair.of(id, modContainer.getModInfo().getVersion().toString())).orElse(Pair.of(id, NetworkRegistry.ABSENT))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
Map<ResourceLocation, String> mismatchedRegistryModData = mismatchedRegistryMods.stream().map(id -> ModList.get().getModContainerById(id.getNamespace()).map(modContainer -> Pair.of(id, modContainer.getModInfo().getVersion().toString())).orElse(Pair.of(id, NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
Map<ResourceLocation, Pair<String, String>> presentModData = getServerSidePresentModData(mismatchedRegistryModData.keySet(), connectionData);
|
||||
|
||||
return new ModMismatchData(mismatchedRegistryModData, presentModData, false);
|
||||
@@ -140,7 +140,7 @@ public class ConnectionData
|
||||
{
|
||||
mismatchedModVersions = ModList.get().getMods().stream().map(info -> Pair.of(info.getModId(), info.getVersion().toString())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
}
|
||||
return mismatchedChannels.keySet().stream().map(channel -> Pair.of(channel, mismatchedChannels.get(channel).equals(NetworkRegistry.ABSENT) ? NetworkRegistry.ABSENT : mismatchedModVersions.getOrDefault(channel.getNamespace(), NetworkRegistry.ABSENT))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
return mismatchedChannels.keySet().stream().map(channel -> Pair.of(channel, mismatchedChannels.get(channel).equals(NetworkRegistry.ABSENT.version()) ? NetworkRegistry.ABSENT.version() : mismatchedModVersions.getOrDefault(channel.getNamespace(), NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ public class NetworkHooks
|
||||
AbstractContainerMenu c = containerSupplier.createMenu(openContainerId, player.getInventory(), player);
|
||||
MenuType<?> type = c.getType();
|
||||
PlayMessages.OpenContainer msg = new PlayMessages.OpenContainer(type, openContainerId, containerSupplier.getDisplayName(), output);
|
||||
NetworkConstants.playChannel.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT);
|
||||
NetworkConstants.playChannel.sendTo(msg, player.connection.connection, NetworkDirection.PLAY_TO_CLIENT);
|
||||
|
||||
player.containerMenu = c;
|
||||
player.initMenu(player.containerMenu);
|
||||
|
||||
@@ -45,10 +45,8 @@ public class NetworkRegistry
|
||||
* Special value for clientAcceptedVersions and serverAcceptedVersions predicates indicating the other side lacks
|
||||
* this channel.
|
||||
*/
|
||||
@SuppressWarnings("RedundantStringConstructorCall")
|
||||
public static String ABSENT = new String("ABSENT \uD83E\uDD14");
|
||||
public static ServerStatusPing.ChannelData ABSENT = new ServerStatusPing.ChannelData(new ResourceLocation("absent"), "ABSENT \uD83E\uDD14", false);
|
||||
|
||||
@SuppressWarnings("RedundantStringConstructorCall")
|
||||
public static String ACCEPTVANILLA = new String("ALLOWVANILLA \uD83D\uDC93\uD83D\uDC93\uD83D\uDC93");
|
||||
|
||||
/**
|
||||
@@ -68,7 +66,7 @@ public class NetworkRegistry
|
||||
*/
|
||||
public static Predicate<String> acceptMissingOr(Predicate<String> versionCheck)
|
||||
{
|
||||
return versionCheck.or(ABSENT::equals).or(ACCEPTVANILLA::equals);
|
||||
return versionCheck.or(ABSENT.version()::equals).or(ACCEPTVANILLA::equals);
|
||||
}
|
||||
|
||||
public static List<String> getServerNonVanillaNetworkMods()
|
||||
@@ -172,11 +170,10 @@ public class NetworkRegistry
|
||||
* @see HandshakeMessages.S2CModList
|
||||
* @see HandshakeMessages.C2SModListReply
|
||||
*/
|
||||
static Map<ResourceLocation, Pair<String, Boolean>> buildChannelVersionsForListPing() {
|
||||
static Map<ResourceLocation, ServerStatusPing.ChannelData> buildChannelVersionsForListPing() {
|
||||
return instances.entrySet().stream().
|
||||
map( p -> Pair.of(p.getKey(), Pair.of(p.getValue().getNetworkProtocolVersion(), p.getValue().tryClientVersionOnServer(ABSENT)))).
|
||||
filter(p -> !p.getLeft().getNamespace().equals("fml")).
|
||||
collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
|
||||
filter(p -> !p.getKey().getNamespace().equals("fml")).
|
||||
collect(Collectors.toMap(Map.Entry::getKey, val -> new ServerStatusPing.ChannelData(val.getKey(), val.getValue().getNetworkProtocolVersion(), val.getValue().tryClientVersionOnServer(ABSENT.version()))));
|
||||
}
|
||||
|
||||
static List<String> listRejectedVanillaMods(BiFunction<NetworkInstance, String, Boolean> testFunction) {
|
||||
@@ -186,7 +183,7 @@ public class NetworkRegistry
|
||||
final boolean test = testFunction.apply(ni, incomingVersion);
|
||||
LOGGER.debug(NETREGISTRY, "Channel '{}' : Vanilla acceptance test: {}", ni.getChannelName(), test ? "ACCEPTED" : "REJECTED");
|
||||
return Pair.of(ni.getChannelName(), test);
|
||||
}).filter(p->!p.getRight()).collect(Collectors.toList());
|
||||
}).filter(p->!p.getRight()).toList();
|
||||
|
||||
if (!results.isEmpty()) {
|
||||
LOGGER.error(NETREGISTRY, "Channels [{}] rejected vanilla connections",
|
||||
@@ -228,7 +225,7 @@ public class NetworkRegistry
|
||||
private static Map<ResourceLocation, String> validateChannels(final Map<ResourceLocation, String> incoming, final String originName, BiFunction<NetworkInstance, String, Boolean> testFunction) {
|
||||
final Map<ResourceLocation, String> results = instances.values().stream().
|
||||
map(ni -> {
|
||||
final String incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT);
|
||||
final String incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT.version());
|
||||
final boolean test = testFunction.apply(ni, incomingVersion);
|
||||
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' from {} : {}", ni.getChannelName(), incomingVersion, originName, test ? "ACCEPTED" : "REJECTED");
|
||||
return Pair.of(Pair.of(ni.getChannelName(), incomingVersion), test);
|
||||
@@ -258,20 +255,20 @@ public class NetworkRegistry
|
||||
return gatheredPayloads;
|
||||
}
|
||||
|
||||
public static boolean checkListPingCompatibilityForClient(Map<ResourceLocation, Pair<String, Boolean>> incoming) {
|
||||
public static boolean checkListPingCompatibilityForClient(Map<ResourceLocation, ServerStatusPing.ChannelData> incoming) {
|
||||
Set<ResourceLocation> handled = new HashSet<>();
|
||||
final List<Pair<ResourceLocation, Boolean>> results = instances.values().stream().
|
||||
filter(p -> !p.getChannelName().getNamespace().equals("fml")).
|
||||
map(ni -> {
|
||||
final Pair<String, Boolean> incomingVersion = incoming.getOrDefault(ni.getChannelName(), Pair.of(ABSENT, true));
|
||||
final boolean test = ni.tryServerVersionOnClient(incomingVersion.getLeft());
|
||||
final ServerStatusPing.ChannelData incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT);
|
||||
final boolean test = ni.tryServerVersionOnClient(incomingVersion.version());
|
||||
handled.add(ni.getChannelName());
|
||||
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' during listping : {}", ni.getChannelName(), incomingVersion, test ? "ACCEPTED" : "REJECTED");
|
||||
return Pair.of(ni.getChannelName(), test);
|
||||
}).filter(p->!p.getRight()).collect(Collectors.toList());
|
||||
final List<ResourceLocation> missingButRequired = incoming.entrySet().stream().
|
||||
filter(p -> !p.getKey().getNamespace().equals("fml")).
|
||||
filter(p -> !p.getValue().getRight()).
|
||||
filter(p -> !p.getValue().required()).
|
||||
filter(p -> !handled.contains(p.getKey())).
|
||||
map(Map.Entry::getKey).
|
||||
collect(Collectors.toList());
|
||||
|
||||
@@ -5,31 +5,24 @@
|
||||
|
||||
package net.minecraftforge.network;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.minecraft.ResourceLocationException;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.fml.IExtensionPoint;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
/**
|
||||
* Represents additional data sent by FML when a server is pinged.
|
||||
@@ -59,14 +52,11 @@ import java.util.stream.StreamSupport;
|
||||
*
|
||||
* <p>
|
||||
* Modern versions will send binary data, which is encoded in a custom format optimized for UTF-16 code point count.
|
||||
* See {@link Serializer#encodeOptimized(ByteBuf)} and {@link Serializer#decodeOptimized(String)}.
|
||||
* See {@link #encodeOptimized(ByteBuf)} and {@link #decodeOptimized(String)}.
|
||||
* Essentially 15 bits of binary data are encoded into every UTF-16 code point. The resulting string is then stored in
|
||||
* the "d" property of the resulting JSON.
|
||||
*
|
||||
* <p>
|
||||
* For the format of the binary data see {@link Serializer#serialize(ServerStatusPing)}.
|
||||
*
|
||||
* <p>
|
||||
* The "channels" and "mods" properties are retained for backwards compatibility,
|
||||
* but left empty. A client that cannot read the old format would not be able to connect anyways, but the properties
|
||||
* must exist to not cause exceptions.
|
||||
@@ -81,48 +71,49 @@ import java.util.stream.StreamSupport;
|
||||
* }</pre>
|
||||
*
|
||||
*/
|
||||
public class ServerStatusPing
|
||||
public record ServerStatusPing(
|
||||
Map<ResourceLocation, ChannelData> channels,
|
||||
Map<String, String> mods,
|
||||
int fmlNetworkVer,
|
||||
boolean truncated
|
||||
)
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Codec<ByteBuf> BYTE_BUF_CODEC = Codec.STRING
|
||||
.xmap(ServerStatusPing::decodeOptimized, ServerStatusPing::encodeOptimized);
|
||||
|
||||
public static final Codec<ServerStatusPing> CODEC = RecordCodecBuilder.create(in -> in.group(
|
||||
Codec.INT.fieldOf("fmlNetworkVersion").forGetter(ServerStatusPing::getFMLNetworkVersion),
|
||||
|
||||
ServerStatusPing.BYTE_BUF_CODEC.optionalFieldOf("d").forGetter(ping -> Optional.of(ping.toBuf())),
|
||||
|
||||
ChannelData.CODEC.listOf().optionalFieldOf("channels").forGetter(ping -> Optional.of(List.of())),
|
||||
ModInfo.CODEC.listOf().optionalFieldOf("mods").forGetter(ping -> Optional.of(List.of())),
|
||||
|
||||
// legacy versions see truncated lists, modern versions ignore this truncated flag (binary data has its own)
|
||||
Codec.BOOL.optionalFieldOf("truncated").forGetter(ping -> Optional.of(ping.isTruncated()))
|
||||
).apply(in, (fmlVer, buf, channels, mods, truncated) -> buf.map(byteBuf -> deserializeOptimized(fmlVer, byteBuf))
|
||||
.orElseGet(() -> new ServerStatusPing(
|
||||
channels.orElseGet(List::of).stream().collect(Collectors.toMap(ChannelData::res, Function.identity())),
|
||||
mods.orElseGet(List::of).stream().collect(Collectors.toMap(ModInfo::modId, ModInfo::modmarker)),
|
||||
fmlVer, truncated.orElse(false)
|
||||
))));
|
||||
|
||||
private final transient Map<ResourceLocation, Pair<String, Boolean>> channels;
|
||||
private final transient Map<String, String> mods;
|
||||
private final transient int fmlNetworkVer;
|
||||
private final transient boolean truncated;
|
||||
|
||||
public ServerStatusPing()
|
||||
{
|
||||
this.channels = NetworkRegistry.buildChannelVersionsForListPing();
|
||||
this.mods = new HashMap<>();
|
||||
ModList.get().forEachModContainer((modid, mc) ->
|
||||
mods.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class)
|
||||
.map(IExtensionPoint.DisplayTest::suppliedVersion)
|
||||
.map(Supplier::get)
|
||||
.orElse(NetworkConstants.IGNORESERVERONLY)));
|
||||
this.fmlNetworkVer = NetworkConstants.FMLNETVERSION;
|
||||
this.truncated = false;
|
||||
this(
|
||||
NetworkRegistry.buildChannelVersionsForListPing(),
|
||||
Util.make(new HashMap<>(), map -> ModList.get().forEachModContainer((modid, mc) ->
|
||||
map.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class)
|
||||
.map(IExtensionPoint.DisplayTest::suppliedVersion)
|
||||
.map(Supplier::get)
|
||||
.orElse(NetworkConstants.IGNORESERVERONLY)))),
|
||||
NetworkConstants.FMLNETVERSION,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
private ServerStatusPing(Map<ResourceLocation, Pair<String, Boolean>> deserialized, Map<String,String> modMarkers, int fmlNetVer, boolean truncated) {
|
||||
this.channels = ImmutableMap.copyOf(deserialized);
|
||||
this.mods = modMarkers;
|
||||
this.fmlNetworkVer = fmlNetVer;
|
||||
this.truncated = truncated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "FMLStatusPing{" +
|
||||
"channels=" + channels +
|
||||
", mods=" + mods +
|
||||
", fmlNetworkVer="
|
||||
+ fmlNetworkVer +
|
||||
", truncated=" + truncated +
|
||||
'}';
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override // Don't compare the truncated flag as it is irrelevant
|
||||
public boolean equals(Object o)
|
||||
{
|
||||
if (this == o) return true;
|
||||
@@ -136,266 +127,220 @@ public class ServerStatusPing
|
||||
return Objects.hash(channels, mods, fmlNetworkVer);
|
||||
}
|
||||
|
||||
private List<Map.Entry<ResourceLocation, Pair<String, Boolean>>> getChannelsForMod(String modId)
|
||||
private List<Map.Entry<ResourceLocation, ChannelData>> getChannelsForMod(String modId)
|
||||
{
|
||||
return channels.entrySet().stream()
|
||||
.filter(c -> c.getKey().getNamespace().equals(modId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<Map.Entry<ResourceLocation, Pair<String, Boolean>>> getNonModChannels()
|
||||
private List<Map.Entry<ResourceLocation, ChannelData>> getNonModChannels()
|
||||
{
|
||||
return channels.entrySet().stream()
|
||||
.filter(c -> !mods.containsKey(c.getKey().getNamespace()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static class Serializer
|
||||
{
|
||||
public static ServerStatusPing deserialize(JsonObject forgeData)
|
||||
public ByteBuf toBuf() {
|
||||
// The following techniques are used to keep the size down:
|
||||
// 1. Try and group channels by ModID, this relies on the assumption that a mod "examplemod" uses a channel
|
||||
// like "examplemod:network". In that case only the "path" of the ResourceLocation is written
|
||||
// 2. Avoid sending IGNORESERVERONLY in plain text, instead use a flag (if set, no version string is sent)
|
||||
//
|
||||
// The size can be estimated as follows (assuming there are no non-mod network channels)
|
||||
// bytes = 2
|
||||
// + mod_count * (avg_mod_id_length + avg_mod_version_length + 1)
|
||||
// + (mod_count * avg_channel_count_per_mod) * (avg_mod_channel_length + avg_mod_channel_version_length + 1)
|
||||
// + 1
|
||||
// for 600 mods with an average ModID and channel length of 20, an average channel of 1 per mod and an
|
||||
// average version length of 5 this turns out to be 31203 bytes, which easily fits into the upper limit of
|
||||
// roughly 60000 bytes. As such it is estimated that the upper limit will never be reached.
|
||||
// we still check though and potentially truncate the list
|
||||
var reachedSizeLimit = false;
|
||||
var buf = new FriendlyByteBuf(Unpooled.buffer());
|
||||
buf.writeBoolean(false); // placeholder for whether we are truncating
|
||||
buf.writeShort(mods.size()); // short so that we can replace it later in case of truncation
|
||||
int writtenCount = 0;
|
||||
for (var modEntry : mods.entrySet())
|
||||
{
|
||||
try
|
||||
var isIgnoreServerOnly = modEntry.getValue().equals(NetworkConstants.IGNORESERVERONLY);
|
||||
|
||||
var channelsForMod = getChannelsForMod(modEntry.getKey());
|
||||
var channelSizeAndVersionFlag = channelsForMod.size() << 1;
|
||||
if (isIgnoreServerOnly)
|
||||
{
|
||||
if (forgeData.has("d"))
|
||||
{
|
||||
return deserializeOptimized(forgeData);
|
||||
}
|
||||
final Map<ResourceLocation, Pair<String, Boolean>> channels = StreamSupport.stream(GsonHelper.getAsJsonArray(forgeData, "channels").spliterator(), false).
|
||||
map(JsonElement::getAsJsonObject).
|
||||
collect(Collectors.toMap(jo -> new ResourceLocation(GsonHelper.getAsString(jo, "res")),
|
||||
jo -> Pair.of(GsonHelper.getAsString(jo, "version"), GsonHelper.getAsBoolean(jo, "required")))
|
||||
);
|
||||
|
||||
final Map<String, String> mods = StreamSupport.stream(GsonHelper.getAsJsonArray(forgeData, "mods").spliterator(), false).
|
||||
map(JsonElement::getAsJsonObject).
|
||||
collect(Collectors.toMap(jo -> GsonHelper.getAsString(jo, "modId"), jo->GsonHelper.getAsString(jo, "modmarker")));
|
||||
|
||||
final int remoteFMLVersion = GsonHelper.getAsInt(forgeData, "fmlNetworkVersion");
|
||||
final boolean truncated = GsonHelper.getAsBoolean(forgeData, "truncated", false);
|
||||
return new ServerStatusPing(channels, mods, remoteFMLVersion, truncated);
|
||||
channelSizeAndVersionFlag |= VERSION_FLAG_IGNORESERVERONLY;
|
||||
}
|
||||
catch (JsonSyntaxException | IndexOutOfBoundsException | ResourceLocationException e)
|
||||
buf.writeVarInt(channelSizeAndVersionFlag);
|
||||
|
||||
buf.writeUtf(modEntry.getKey());
|
||||
if (!isIgnoreServerOnly)
|
||||
{
|
||||
LOGGER.debug(NetworkConstants.NETWORK, "Encountered an error parsing status ping data", e);
|
||||
return null;
|
||||
buf.writeUtf(modEntry.getValue());
|
||||
}
|
||||
|
||||
// write the channels for this mod, if any
|
||||
for (var entry : channelsForMod)
|
||||
{
|
||||
buf.writeUtf(entry.getKey().getPath());
|
||||
buf.writeUtf(entry.getValue().version());
|
||||
buf.writeBoolean(entry.getValue().required());
|
||||
}
|
||||
|
||||
writtenCount++;
|
||||
|
||||
if (buf.readableBytes() >= 60000)
|
||||
{
|
||||
reachedSizeLimit = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static JsonObject serialize(ServerStatusPing forgeData)
|
||||
if (!reachedSizeLimit)
|
||||
{
|
||||
// The following techniques are used to keep the size down:
|
||||
// 1. Try and group channels by ModID, this relies on the assumption that a mod "examplemod" uses a channel
|
||||
// like "examplemod:network". In that case only the "path" of the ResourceLocation is written
|
||||
// 2. Avoid sending IGNORESERVERONLY in plain text, instead use a flag (if set, no version string is sent)
|
||||
//
|
||||
// The size can be estimated as follows (assuming there are no non-mod network channels)
|
||||
// bytes = 2
|
||||
// + mod_count * (avg_mod_id_length + avg_mod_version_length + 1)
|
||||
// + (mod_count * avg_channel_count_per_mod) * (avg_mod_channel_length + avg_mod_channel_version_length + 1)
|
||||
// + 1
|
||||
// for 600 mods with an average ModID and channel length of 20, an average channel of 1 per mod and an
|
||||
// average version length of 5 this turns out to be 31203 bytes, which easily fits into the upper limit of
|
||||
// roughly 60000 bytes. As such it is estimated that the upper limit will never be reached.
|
||||
// we still check though and potentially truncate the list
|
||||
|
||||
var reachedSizeLimit = false;
|
||||
var buf = new FriendlyByteBuf(Unpooled.buffer());
|
||||
buf.writeBoolean(false); // placeholder for whether we are truncating
|
||||
buf.writeShort(forgeData.mods.size()); // short so that we can replace it later in case of truncation
|
||||
int writtenCount = 0;
|
||||
for (var modEntry : forgeData.mods.entrySet())
|
||||
// write any channels that don't match up with a ModID.
|
||||
var nonModChannels = getNonModChannels();
|
||||
buf.writeVarInt(nonModChannels.size());
|
||||
for (var entry : nonModChannels)
|
||||
{
|
||||
var isIgnoreServerOnly = modEntry.getValue().equals(NetworkConstants.IGNORESERVERONLY);
|
||||
|
||||
var channelsForMod = forgeData.getChannelsForMod(modEntry.getKey());
|
||||
var channelSizeAndVersionFlag = channelsForMod.size() << 1;
|
||||
if (isIgnoreServerOnly)
|
||||
{
|
||||
channelSizeAndVersionFlag |= VERSION_FLAG_IGNORESERVERONLY;
|
||||
}
|
||||
buf.writeVarInt(channelSizeAndVersionFlag);
|
||||
|
||||
buf.writeUtf(modEntry.getKey());
|
||||
if (!isIgnoreServerOnly)
|
||||
{
|
||||
buf.writeUtf(modEntry.getValue());
|
||||
}
|
||||
|
||||
// write the channels for this mod, if any
|
||||
for (var entry : channelsForMod)
|
||||
{
|
||||
buf.writeUtf(entry.getKey().getPath());
|
||||
buf.writeUtf(entry.getValue().getLeft());
|
||||
buf.writeBoolean(entry.getValue().getRight());
|
||||
}
|
||||
|
||||
writtenCount++;
|
||||
|
||||
if (buf.readableBytes() >= 60000)
|
||||
{
|
||||
reachedSizeLimit = true;
|
||||
break;
|
||||
}
|
||||
buf.writeResourceLocation(entry.getKey());
|
||||
buf.writeUtf(entry.getValue().version());
|
||||
buf.writeBoolean(entry.getValue().required());
|
||||
}
|
||||
|
||||
if (!reachedSizeLimit)
|
||||
{
|
||||
// write any channels that don't match up with a ModID.
|
||||
var nonModChannels = forgeData.getNonModChannels();
|
||||
buf.writeVarInt(nonModChannels.size());
|
||||
for (var entry : nonModChannels)
|
||||
{
|
||||
buf.writeResourceLocation(entry.getKey());
|
||||
buf.writeUtf(entry.getValue().getLeft());
|
||||
buf.writeBoolean(entry.getValue().getRight());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
buf.setShort(1, writtenCount);
|
||||
buf.writeVarInt(0);
|
||||
}
|
||||
|
||||
buf.setBoolean(0, reachedSizeLimit);
|
||||
|
||||
var obj = new JsonObject();
|
||||
obj.addProperty("fmlNetworkVersion", forgeData.fmlNetworkVer);
|
||||
obj.addProperty("d", encodeOptimized(buf));
|
||||
|
||||
// add dummy properties, so old versions do not crash when deserializing
|
||||
obj.add("channels", new JsonArray());
|
||||
obj.add("mods", new JsonArray());
|
||||
// legacy versions see truncated lists, modern versions ignore this truncated flag (binary data has its own)
|
||||
obj.addProperty("truncated", true);
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
{
|
||||
buf.setShort(1, writtenCount);
|
||||
buf.writeVarInt(0);
|
||||
}
|
||||
|
||||
private static final int VERSION_FLAG_IGNORESERVERONLY = 0b1;
|
||||
buf.setBoolean(0, reachedSizeLimit);
|
||||
return buf;
|
||||
}
|
||||
|
||||
private static ServerStatusPing deserializeOptimized(JsonObject forgeData)
|
||||
private static final int VERSION_FLAG_IGNORESERVERONLY = 0b1;
|
||||
|
||||
private static ServerStatusPing deserializeOptimized(int fmlNetworkVersion, ByteBuf bbuf) {
|
||||
var buf = new FriendlyByteBuf(bbuf);
|
||||
boolean truncated;
|
||||
Map<ResourceLocation, ChannelData> channels;
|
||||
Map<String, String> mods;
|
||||
|
||||
try
|
||||
{
|
||||
int remoteFMLVersion = GsonHelper.getAsInt(forgeData, "fmlNetworkVersion");
|
||||
var buf = new FriendlyByteBuf(decodeOptimized(GsonHelper.getAsString(forgeData, "d")));
|
||||
|
||||
boolean truncated;
|
||||
Map<ResourceLocation, Pair<String, Boolean>> channels;
|
||||
Map<String, String> mods;
|
||||
|
||||
try
|
||||
{
|
||||
truncated = buf.readBoolean();
|
||||
var modsSize = buf.readUnsignedShort();
|
||||
mods = new HashMap<>();
|
||||
channels = new HashMap<>();
|
||||
for (var i = 0; i < modsSize; i++) {
|
||||
var channelSizeAndVersionFlag = buf.readVarInt();
|
||||
var channelSize = channelSizeAndVersionFlag >>> 1;
|
||||
var isIgnoreServerOnly = (channelSizeAndVersionFlag & VERSION_FLAG_IGNORESERVERONLY) != 0;
|
||||
var modId = buf.readUtf();
|
||||
var modVersion = isIgnoreServerOnly ? NetworkConstants.IGNORESERVERONLY : buf.readUtf();
|
||||
for (var i1 = 0; i1 < channelSize; i1++) {
|
||||
var channelName = buf.readUtf();
|
||||
var channelVersion = buf.readUtf();
|
||||
var requiredOnClient = buf.readBoolean();
|
||||
channels.put(new ResourceLocation(modId, channelName), Pair.of(channelVersion, requiredOnClient));
|
||||
}
|
||||
|
||||
mods.put(modId, modVersion);
|
||||
}
|
||||
|
||||
var nonModChannelCount = buf.readVarInt();
|
||||
for (var i = 0; i < nonModChannelCount; i++) {
|
||||
var channelName = buf.readResourceLocation();
|
||||
truncated = buf.readBoolean();
|
||||
var modsSize = buf.readUnsignedShort();
|
||||
mods = new HashMap<>();
|
||||
channels = new HashMap<>();
|
||||
for (var i = 0; i < modsSize; i++) {
|
||||
var channelSizeAndVersionFlag = buf.readVarInt();
|
||||
var channelSize = channelSizeAndVersionFlag >>> 1;
|
||||
var isIgnoreServerOnly = (channelSizeAndVersionFlag & VERSION_FLAG_IGNORESERVERONLY) != 0;
|
||||
var modId = buf.readUtf();
|
||||
var modVersion = isIgnoreServerOnly ? NetworkConstants.IGNORESERVERONLY : buf.readUtf();
|
||||
for (var i1 = 0; i1 < channelSize; i1++) {
|
||||
var channelName = buf.readUtf();
|
||||
var channelVersion = buf.readUtf();
|
||||
var requiredOnClient = buf.readBoolean();
|
||||
channels.put(channelName, Pair.of(channelVersion, requiredOnClient));
|
||||
final ResourceLocation id = new ResourceLocation(modId, channelName);
|
||||
channels.put(id, new ChannelData(id, channelVersion, requiredOnClient));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
buf.release();
|
||||
|
||||
mods.put(modId, modVersion);
|
||||
}
|
||||
|
||||
return new ServerStatusPing(channels, mods, remoteFMLVersion, truncated);
|
||||
var nonModChannelCount = buf.readVarInt();
|
||||
for (var i = 0; i < nonModChannelCount; i++) {
|
||||
var channelName = buf.readResourceLocation();
|
||||
var channelVersion = buf.readUtf();
|
||||
var requiredOnClient = buf.readBoolean();
|
||||
channels.put(channelName, new ChannelData(channelName, channelVersion, requiredOnClient));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
buf.release();
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode given ByteBuf to a String. This is optimized for UTF-16 Code-Point count.
|
||||
* Supports at most 2^30 bytes in length
|
||||
*/
|
||||
private static String encodeOptimized(ByteBuf buf)
|
||||
return new ServerStatusPing(channels, mods, fmlNetworkVersion, truncated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode given ByteBuf to a String. This is optimized for UTF-16 Code-Point count.
|
||||
* Supports at most 2^30 bytes in length
|
||||
*/
|
||||
private static String encodeOptimized(ByteBuf buf)
|
||||
{
|
||||
var byteLength = buf.readableBytes();
|
||||
var sb = new StringBuilder();
|
||||
sb.append((char) (byteLength & 0x7FFF));
|
||||
sb.append((char) ((byteLength >>> 15) & 0x7FFF));
|
||||
|
||||
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
|
||||
int bitsInBuf = 0;
|
||||
while (buf.isReadable())
|
||||
{
|
||||
var byteLength = buf.readableBytes();
|
||||
var sb = new StringBuilder();
|
||||
sb.append((char) (byteLength & 0x7FFF));
|
||||
sb.append((char) ((byteLength >>> 15) & 0x7FFF));
|
||||
|
||||
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
|
||||
int bitsInBuf = 0;
|
||||
while (buf.isReadable())
|
||||
{
|
||||
if (bitsInBuf >= 15)
|
||||
{
|
||||
char c = (char) (buffer & 0x7FFF);
|
||||
sb.append(c);
|
||||
buffer >>>= 15;
|
||||
bitsInBuf -= 15;
|
||||
}
|
||||
var b = buf.readUnsignedByte();
|
||||
buffer |= (int) b << bitsInBuf;
|
||||
bitsInBuf += 8;
|
||||
}
|
||||
|
||||
if (bitsInBuf > 0)
|
||||
if (bitsInBuf >= 15)
|
||||
{
|
||||
char c = (char) (buffer & 0x7FFF);
|
||||
sb.append(c);
|
||||
buffer >>>= 15;
|
||||
bitsInBuf -= 15;
|
||||
}
|
||||
return sb.toString();
|
||||
var b = buf.readUnsignedByte();
|
||||
buffer |= (int) b << bitsInBuf;
|
||||
bitsInBuf += 8;
|
||||
}
|
||||
buf.release();
|
||||
|
||||
/**
|
||||
* Decode binary data encoded by {@link #encodeOptimized}
|
||||
*/
|
||||
private static ByteBuf decodeOptimized(String s)
|
||||
if (bitsInBuf > 0)
|
||||
{
|
||||
var size0 = ((int) s.charAt(0));
|
||||
var size1 = ((int) s.charAt(1));
|
||||
var size = size0 | (size1 << 15);
|
||||
char c = (char) (buffer & 0x7FFF);
|
||||
sb.append(c);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
var buf = Unpooled.buffer(size);
|
||||
/**
|
||||
* Decode binary data encoded by {@link #encodeOptimized}
|
||||
*/
|
||||
private static ByteBuf decodeOptimized(String s)
|
||||
{
|
||||
var size0 = ((int) s.charAt(0));
|
||||
var size1 = ((int) s.charAt(1));
|
||||
var size = size0 | (size1 << 15);
|
||||
|
||||
int stringIndex = 2;
|
||||
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
|
||||
int bitsInBuf = 0;
|
||||
while (stringIndex < s.length())
|
||||
{
|
||||
while (bitsInBuf >= 8)
|
||||
{
|
||||
buf.writeByte(buffer);
|
||||
buffer >>>= 8;
|
||||
bitsInBuf -= 8;
|
||||
}
|
||||
var buf = Unpooled.buffer(size);
|
||||
|
||||
var c = s.charAt(stringIndex);
|
||||
buffer |= (((int) c) & 0x7FFF) << bitsInBuf;
|
||||
bitsInBuf += 15;
|
||||
stringIndex++;
|
||||
}
|
||||
|
||||
// write any leftovers
|
||||
while (buf.readableBytes() < size)
|
||||
int stringIndex = 2;
|
||||
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
|
||||
int bitsInBuf = 0;
|
||||
while (stringIndex < s.length())
|
||||
{
|
||||
while (bitsInBuf >= 8)
|
||||
{
|
||||
buf.writeByte(buffer);
|
||||
buffer >>>= 8;
|
||||
bitsInBuf -= 8;
|
||||
}
|
||||
return buf;
|
||||
|
||||
var c = s.charAt(stringIndex);
|
||||
buffer |= (((int) c) & 0x7FFF) << bitsInBuf;
|
||||
bitsInBuf += 15;
|
||||
stringIndex++;
|
||||
}
|
||||
|
||||
// write any leftovers
|
||||
while (buf.readableBytes() < size)
|
||||
{
|
||||
buf.writeByte(buffer);
|
||||
buffer >>>= 8;
|
||||
bitsInBuf -= 8;
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, Pair<String, Boolean>> getRemoteChannels()
|
||||
public Map<ResourceLocation, ChannelData> getRemoteChannels()
|
||||
{
|
||||
return this.channels;
|
||||
}
|
||||
@@ -414,4 +359,19 @@ public class ServerStatusPing
|
||||
{
|
||||
return truncated;
|
||||
}
|
||||
|
||||
public record ModInfo(String modId, String modmarker) {
|
||||
public static final Codec<ModInfo> CODEC = RecordCodecBuilder.create(in -> in.group(
|
||||
Codec.STRING.fieldOf("modId").forGetter(ModInfo::modId),
|
||||
Codec.STRING.fieldOf("modmarker").forGetter(ModInfo::modmarker)
|
||||
).apply(in, ModInfo::new));
|
||||
}
|
||||
|
||||
public record ChannelData(ResourceLocation res, String version, boolean required) {
|
||||
public static final Codec<ChannelData> CODEC = RecordCodecBuilder.create(in -> in.group(
|
||||
ResourceLocation.CODEC.fieldOf("res").forGetter(ChannelData::res),
|
||||
Codec.STRING.fieldOf("version").forGetter(ChannelData::version),
|
||||
Codec.BOOL.fieldOf("required").forGetter(ChannelData::required)
|
||||
).apply(in, ChannelData::new));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user