| 1 | package net.minecraft.world.entity;
|
| 2 |
|
| 3 | import com.google.common.collect.Maps;
|
| 4 | import com.mojang.datafixers.util.Either;
|
| 5 | import com.mojang.serialization.Codec;
|
| 6 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 7 | import java.util.List;
|
| 8 | import java.util.Map;
|
| 9 | import java.util.function.Function;
|
| 10 | import net.minecraft.resources.ResourceKey;
|
| 11 | import net.minecraft.world.level.storage.loot.LootTable;
|
| 12 |
|
| 13 | public record EquipmentTable(ResourceKey<LootTable> lootTable, Map<EquipmentSlot, Float> slotDropChances) {
|
| 14 | public static final Codec<Map<EquipmentSlot, Float>> DROP_CHANCES_CODEC = Codec.either(Codec.FLOAT, Codec.unboundedMap(EquipmentSlot.CODEC, Codec.FLOAT))
|
| 15 | .xmap(
|
| 16 | either -> either.map(EquipmentTable::createForAllSlots, Function.identity()),
|
| 17 | provider -> {
|
| 18 | boolean dropChancesTheSame = provider.values().stream().distinct().count() == 1L;
|
| 19 | boolean allSlotsArePresent = provider.keySet().containsAll(EquipmentSlot.VALUES);
|
| 20 | return dropChancesTheSame && allSlotsArePresent
|
| 21 | ? Either.left(provider.values().stream().findFirst().orElse(0.0F))
|
| 22 | : Either.right((Map<EquipmentSlot, Float>)provider);
|
| 23 | }
|
| 24 | );
|
| 25 | public static final Codec<EquipmentTable> CODEC = RecordCodecBuilder.create(
|
| 26 | i -> i.group(
|
| 27 | LootTable.KEY_CODEC.fieldOf("loot_table").forGetter(EquipmentTable::lootTable),
|
| 28 | DROP_CHANCES_CODEC.optionalFieldOf("slot_drop_chances", Map.of()).forGetter(EquipmentTable::slotDropChances)
|
| 29 | )
|
| 30 | .apply(i, EquipmentTable::new)
|
| 31 | );
|
| 32 |
|
| 33 | public EquipmentTable(final ResourceKey<LootTable> lootTable, final float dropChance) {
|
| 34 | this(lootTable, createForAllSlots(dropChance));
|
| 35 | }
|
| 36 |
|
| 37 | private static Map<EquipmentSlot, Float> createForAllSlots(final float dropChance) {
|
| 38 | return createForAllSlots(List.of(EquipmentSlot.values()), dropChance);
|
| 39 | }
|
| 40 |
|
| 41 | private static Map<EquipmentSlot, Float> createForAllSlots(final List<EquipmentSlot> slots, final float dropChance) {
|
| 42 | Map<EquipmentSlot, Float> values = Maps.newHashMap();
|
| 43 |
|
| 44 | for (EquipmentSlot slot : slots) {
|
| 45 | values.put(slot, dropChance);
|
| 46 | }
|
| 47 |
|
| 48 | return values;
|
| 49 | }
|
| 50 | }
|
| 51 |
|