| 1 | package net.minecraft.world.level.storage.loot.predicates;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.MapCodec;
|
| 5 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 6 | import java.util.ArrayList;
|
| 7 | import java.util.List;
|
| 8 | import java.util.Set;
|
| 9 | import net.minecraft.core.Holder;
|
| 10 | import net.minecraft.util.ExtraCodecs;
|
| 11 | import net.minecraft.util.context.ContextKey;
|
| 12 | import net.minecraft.world.item.ItemInstance;
|
| 13 | import net.minecraft.world.item.enchantment.Enchantment;
|
| 14 | import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
| 15 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 16 | import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
| 17 |
|
| 18 | public record BonusLevelTableCondition(Holder<Enchantment> enchantment, List<Float> values) implements LootItemCondition {
|
| 19 | public static final MapCodec<BonusLevelTableCondition> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 20 | i -> i.group(
|
| 21 | Enchantment.CODEC.fieldOf("enchantment").forGetter(BonusLevelTableCondition::enchantment),
|
| 22 | ExtraCodecs.nonEmptyList(Codec.FLOAT.listOf()).fieldOf("chances").forGetter(BonusLevelTableCondition::values)
|
| 23 | )
|
| 24 | .apply(i, BonusLevelTableCondition::new)
|
| 25 | );
|
| 26 |
|
| 27 | @Override
|
| 28 | public MapCodec<BonusLevelTableCondition> codec() {
|
| 29 | return MAP_CODEC;
|
| 30 | }
|
| 31 |
|
| 32 | @Override
|
| 33 | public Set<ContextKey<?>> getReferencedContextParams() {
|
| 34 | return Set.of(LootContextParams.TOOL);
|
| 35 | }
|
| 36 |
|
| 37 | public boolean test(final LootContext context) {
|
| 38 | ItemInstance tool = context.getOptional(LootContextParams.TOOL);
|
| 39 | int level = tool != null ? EnchantmentHelper.getItemEnchantmentLevel(this.enchantment, tool) : 0;
|
| 40 | float chance = this.values.get(Math.min(level, this.values.size() - 1));
|
| 41 | return context.getRandom().nextFloat() < chance;
|
| 42 | }
|
| 43 |
|
| 44 | public static LootItemCondition.Builder bonusLevelFlatChance(final Holder<Enchantment> enchantment, final float... chances) {
|
| 45 | List<Float> chancesList = new ArrayList<>(chances.length);
|
| 46 |
|
| 47 | for (float chance : chances) {
|
| 48 | chancesList.add(chance);
|
| 49 | }
|
| 50 |
|
| 51 | return () -> new BonusLevelTableCondition(enchantment, chancesList);
|
| 52 | }
|
| 53 | }
|
| 54 |
|