| 1 | package net.minecraft.advancements.predicates;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import com.mojang.serialization.Codec;
|
| 5 | import io.netty.buffer.ByteBuf;
|
| 6 | import net.minecraft.core.component.DataComponentGetter;
|
| 7 | import net.minecraft.core.component.DataComponents;
|
| 8 | import net.minecraft.nbt.CompoundTag;
|
| 9 | import net.minecraft.nbt.NbtUtils;
|
| 10 | import net.minecraft.nbt.Tag;
|
| 11 | import net.minecraft.nbt.TagParser;
|
| 12 | import net.minecraft.network.codec.ByteBufCodecs;
|
| 13 | import net.minecraft.network.codec.StreamCodec;
|
| 14 | import net.minecraft.util.ProblemReporter;
|
| 15 | import net.minecraft.world.entity.Entity;
|
| 16 | import net.minecraft.world.entity.player.Player;
|
| 17 | import net.minecraft.world.item.ItemStack;
|
| 18 | import net.minecraft.world.item.component.CustomData;
|
| 19 | import net.minecraft.world.level.storage.TagValueOutput;
|
| 20 | import org.jspecify.annotations.Nullable;
|
| 21 | import org.slf4j.Logger;
|
| 22 |
|
| 23 | public record NbtPredicate(CompoundTag tag) {
|
| 24 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 25 | public static final Codec<NbtPredicate> CODEC = TagParser.LENIENT_CODEC.xmap(NbtPredicate::new, NbtPredicate::tag);
|
| 26 | public static final StreamCodec<ByteBuf, NbtPredicate> STREAM_CODEC = ByteBufCodecs.COMPOUND_TAG.map(NbtPredicate::new, NbtPredicate::tag);
|
| 27 | public static final String SELECTED_ITEM_TAG = "SelectedItem";
|
| 28 |
|
| 29 | public boolean matches(final DataComponentGetter components) {
|
| 30 | CustomData data = components.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY);
|
| 31 | return data.matchedBy(this.tag);
|
| 32 | }
|
| 33 |
|
| 34 | public boolean matches(final Entity entity) {
|
| 35 | return this.matches(getEntityTagToCompare(entity));
|
| 36 | }
|
| 37 |
|
| 38 | public boolean matches(final @Nullable Tag tag) {
|
| 39 | return tag != null && NbtUtils.compareNbt(this.tag, tag, true);
|
| 40 | }
|
| 41 |
|
| 42 | public static CompoundTag getEntityTagToCompare(final Entity entity) {
|
| 43 | try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), LOGGER)) {
|
| 44 | TagValueOutput output = TagValueOutput.createWithContext(reporter, entity.registryAccess());
|
| 45 | entity.saveWithoutId(output);
|
| 46 | if (entity instanceof Player player) {
|
| 47 | ItemStack selected = player.getInventory().getSelectedItem();
|
| 48 | if (!selected.isEmpty()) {
|
| 49 | output.store("SelectedItem", ItemStack.CODEC, selected);
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | return output.buildResult();
|
| 54 | }
|
| 55 | }
|
| 56 | }
|
| 57 |
|