Be more resilient with different enchantment NBT types

Fixes #2911
This commit is contained in:
Camotoy 2022-04-01 15:20:30 -04:00
parent 2a05dd57ff
commit fb26e263cc
No known key found for this signature in database
GPG key ID: 7EEFB66FE798081F
2 changed files with 15 additions and 10 deletions

View file

@ -121,10 +121,6 @@ public class EnchantmentTranslator extends NbtItemStackTranslator {
private CompoundTag remapEnchantment(CompoundTag tag) { private CompoundTag remapEnchantment(CompoundTag tag) {
Tag javaEnchLvl = tag.get("lvl");
if (!(javaEnchLvl instanceof ShortTag || javaEnchLvl instanceof IntTag))
return null;
Tag javaEnchId = tag.get("id"); Tag javaEnchId = tag.get("id");
if (!(javaEnchId instanceof StringTag)) if (!(javaEnchId instanceof StringTag))
return null; return null;
@ -135,9 +131,12 @@ public class EnchantmentTranslator extends NbtItemStackTranslator {
return null; return null;
} }
Tag javaEnchLvl = tag.get("lvl");
CompoundTag bedrockTag = new CompoundTag(""); CompoundTag bedrockTag = new CompoundTag("");
bedrockTag.put(new ShortTag("id", (short) enchantment.ordinal())); bedrockTag.put(new ShortTag("id", (short) enchantment.ordinal()));
bedrockTag.put(new ShortTag("lvl", ((Number) javaEnchLvl.getValue()).shortValue())); // If the tag cannot parse, Java Edition 1.18.2 sets to 0
bedrockTag.put(new ShortTag("lvl", javaEnchLvl != null && javaEnchLvl.getValue() instanceof Number lvl ? lvl.shortValue() : 0));
return bedrockTag; return bedrockTag;
} }

View file

@ -29,21 +29,27 @@ import com.github.steveice10.opennbt.tag.builtin.*;
import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntMap;
import org.geysermc.geyser.session.GeyserSession; import org.geysermc.geyser.session.GeyserSession;
import javax.annotation.Nullable;
public class ItemUtils { public class ItemUtils {
private static Int2IntMap DYE_COLORS = null; private static Int2IntMap DYE_COLORS = null;
public static int getEnchantmentLevel(CompoundTag itemNBTData, String enchantmentId) { public static int getEnchantmentLevel(@Nullable CompoundTag itemNBTData, String enchantmentId) {
ListTag enchantments = (itemNBTData == null ? null : itemNBTData.get("Enchantments")); if (itemNBTData == null) {
return 0;
}
ListTag enchantments = itemNBTData.get("Enchantments");
if (enchantments != null) { if (enchantments != null) {
int enchantmentLevel = 0;
for (Tag tag : enchantments) { for (Tag tag : enchantments) {
CompoundTag enchantment = (CompoundTag) tag; CompoundTag enchantment = (CompoundTag) tag;
StringTag enchantId = enchantment.get("id"); StringTag enchantId = enchantment.get("id");
if (enchantId.getValue().equals(enchantmentId)) { if (enchantId.getValue().equals(enchantmentId)) {
enchantmentLevel = (int) ((ShortTag) enchantment.get("lvl")).getValue(); Tag lvl = enchantment.get("lvl");
if (lvl != null && lvl.getValue() instanceof Number number) {
return number.intValue();
}
} }
} }
return enchantmentLevel;
} }
return 0; return 0;
} }