| 1 | package net.minecraft.world.item.enchantment.effects;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.MapCodec;
|
| 5 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 6 | import java.util.Optional;
|
| 7 | import net.minecraft.core.BlockPos;
|
| 8 | import net.minecraft.core.Holder;
|
| 9 | import net.minecraft.core.HolderSet;
|
| 10 | import net.minecraft.core.registries.Registries;
|
| 11 | import net.minecraft.core.registries.codec.RegistryCodecs;
|
| 12 | import net.minecraft.server.level.ServerLevel;
|
| 13 | import net.minecraft.server.level.ServerPlayer;
|
| 14 | import net.minecraft.world.entity.Entity;
|
| 15 | import net.minecraft.world.entity.EntitySpawnReason;
|
| 16 | import net.minecraft.world.entity.EntityType;
|
| 17 | import net.minecraft.world.entity.LightningBolt;
|
| 18 | import net.minecraft.world.item.enchantment.EnchantedItemInUse;
|
| 19 | import net.minecraft.world.level.Level;
|
| 20 | import net.minecraft.world.phys.Vec3;
|
| 21 |
|
| 22 | public record SummonEntityEffect(HolderSet<EntityType<?>> entityTypes, boolean joinTeam) implements EnchantmentEntityEffect {
|
| 23 | public static final MapCodec<SummonEntityEffect> CODEC = RecordCodecBuilder.mapCodec(
|
| 24 | i -> i.group(
|
| 25 | RegistryCodecs.holderSet(Registries.ENTITY_TYPE).fieldOf("entity").forGetter(SummonEntityEffect::entityTypes),
|
| 26 | Codec.BOOL.optionalFieldOf("join_team", false).forGetter(SummonEntityEffect::joinTeam)
|
| 27 | )
|
| 28 | .apply(i, SummonEntityEffect::new)
|
| 29 | );
|
| 30 |
|
| 31 | @Override
|
| 32 | public void apply(final ServerLevel serverLevel, final int enchantmentLevel, final EnchantedItemInUse item, final Entity entity, final Vec3 position) {
|
| 33 | BlockPos blockPos = BlockPos.containing(position);
|
| 34 | if (Level.isInSpawnableBounds(blockPos)) {
|
| 35 | Optional<Holder<EntityType<?>>> entityType = this.entityTypes().getRandomElement(serverLevel.getRandom());
|
| 36 | if (!entityType.isEmpty()) {
|
| 37 | Entity spawned = entityType.get().value().spawn(serverLevel, blockPos, EntitySpawnReason.TRIGGERED);
|
| 38 | if (spawned != null) {
|
| 39 | if (spawned instanceof LightningBolt lightningBolt && item.owner() instanceof ServerPlayer player) {
|
| 40 | lightningBolt.setCause(player);
|
| 41 | }
|
| 42 |
|
| 43 | if (this.joinTeam && entity.getTeam() != null) {
|
| 44 | serverLevel.getScoreboard().addPlayerToTeam(spawned.getScoreboardName(), entity.getTeam());
|
| 45 | }
|
| 46 |
|
| 47 | spawned.snapTo(position.x, position.y, position.z, spawned.getYRot(), spawned.getXRot());
|
| 48 | }
|
| 49 | }
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | @Override
|
| 54 | public MapCodec<SummonEntityEffect> codec() {
|
| 55 | return CODEC;
|
| 56 | }
|
| 57 | }
|
| 58 |
|