Search in sources :

Example 31 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class BrewingStandBlockEntityMixin method impl$onTick.

@Inject(method = "tick", cancellable = true, locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "FIELD", target = "Lnet/minecraft/world/level/block/entity/BrewingStandBlockEntity;brewTime:I", ordinal = 1))
private void impl$onTick(CallbackInfo ci, ItemStack fuelStack, boolean isBrewable, boolean isBrewing, ItemStack ingredientStack) {
    if (this.brewTime != 0 && isBrewable && this.ingredient == ingredientStack.getItem()) {
        final Cause currentCause = Sponge.server().causeStackManager().currentCause();
        final BrewingEvent.Tick event = SpongeEventFactory.createBrewingEventTick(currentCause, (BrewingStand) this, ItemStackUtil.snapshotOf(ingredientStack));
        if (Sponge.eventManager().post(event)) {
            this.brewTime++;
        }
    }
}
Also used : BrewingEvent(org.spongepowered.api.event.block.entity.BrewingEvent) Cause(org.spongepowered.api.event.Cause) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 32 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class BlockTransactionType method consumeEventsAndMarker.

@Override
protected void consumeEventsAndMarker(PhaseContext<@NonNull ?> context, final Collection<? extends ChangeBlockEvent.All> changeBlockEvents) {
    final Multimap<ResourceKey, ChangeBlockEvent.All> eventsByWorld = LinkedListMultimap.create();
    changeBlockEvents.forEach(event -> eventsByWorld.put(event.world().key(), event));
    eventsByWorld.asMap().forEach((key, events) -> {
        final Optional<ServerWorld> serverWorld = ((SpongeServer) SpongeCommon.server()).worldManager().world(key);
        if (!serverWorld.isPresent()) {
            return;
        }
        final ListMultimap<BlockPos, SpongeBlockSnapshot> positions = LinkedListMultimap.create();
        // Gather transactions that were valid
        events.stream().filter(event -> !event.isCancelled()).flatMap(event -> event.transactions().stream()).filter(BlockTransaction::isValid).forEach(transactions -> {
            // Then "put" the most recent transactions such that we have a complete rebuild of
            // each position according to what originally existed and then
            // the ultimate final block on that position
            final SpongeBlockSnapshot original = (SpongeBlockSnapshot) transactions.original();
            positions.put(original.getBlockPos(), original);
            positions.put(original.getBlockPos(), (SpongeBlockSnapshot) transactions.finalReplacement());
        });
        // just return.
        if (positions.isEmpty()) {
            return;
        }
        final ImmutableList<BlockTransactionReceipt> transactions = positions.asMap().values().stream().map(spongeBlockSnapshots -> {
            final List<SpongeBlockSnapshot> snapshots = new ArrayList<>(spongeBlockSnapshots);
            if (snapshots.isEmpty() || snapshots.size() < 2) {
                // Error case
                return Optional.<BlockTransactionReceipt>empty();
            }
            final SpongeBlockSnapshot original = snapshots.get(0);
            final SpongeBlockSnapshot result = snapshots.get(snapshots.size() - 1);
            final Operation operation = context.getBlockOperation(original, result);
            final BlockTransactionReceipt eventTransaction = new BlockTransactionReceipt(original, result, operation);
            context.postBlockTransactionApplication(original.blockChange, eventTransaction);
            return Optional.of(eventTransaction);
        }).filter(Optional::isPresent).map(Optional::get).collect(ImmutableList.toImmutableList());
        final Cause cause = PhaseTracker.getInstance().currentCause();
        SpongeCommon.post(SpongeEventFactory.createChangeBlockEventPost(cause, transactions, serverWorld.get()));
    });
}
Also used : LinkedListMultimap(com.google.common.collect.LinkedListMultimap) NonNull(org.checkerframework.checker.nullness.qual.NonNull) ServerWorld(org.spongepowered.api.world.server.ServerWorld) ListMultimap(com.google.common.collect.ListMultimap) ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) SpongeServer(org.spongepowered.common.SpongeServer) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Collection(java.util.Collection) SpongeBlockSnapshot(org.spongepowered.common.block.SpongeBlockSnapshot) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Multimap(com.google.common.collect.Multimap) Cause(org.spongepowered.api.event.Cause) ArrayList(java.util.ArrayList) BlockTransactionReceipt(org.spongepowered.api.block.transaction.BlockTransactionReceipt) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) BlockPos(net.minecraft.core.BlockPos) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) BlockTransaction(org.spongepowered.api.block.transaction.BlockTransaction) ResourceKey(org.spongepowered.api.ResourceKey) Optional(java.util.Optional) Operation(org.spongepowered.api.block.transaction.Operation) BlockTransactionReceipt(org.spongepowered.api.block.transaction.BlockTransactionReceipt) Optional(java.util.Optional) Operation(org.spongepowered.api.block.transaction.Operation) ResourceKey(org.spongepowered.api.ResourceKey) ServerWorld(org.spongepowered.api.world.server.ServerWorld) SpongeBlockSnapshot(org.spongepowered.common.block.SpongeBlockSnapshot) Cause(org.spongepowered.api.event.Cause) BlockPos(net.minecraft.core.BlockPos) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Example 33 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class InventoryBasedTransaction method generateEvent.

@Override
public Optional<ChangeInventoryEvent> generateEvent(final PhaseContext<@NonNull ?> context, @Nullable final GameTransaction<@NonNull ?> parent, final ImmutableList<GameTransaction<ChangeInventoryEvent>> gameTransactions, final Cause currentCause) {
    final ImmutableList<InventoryBasedTransaction> containerBasedTransactions = gameTransactions.stream().filter(tx -> tx instanceof InventoryBasedTransaction).map(tx -> (InventoryBasedTransaction) tx).filter(tx -> !tx.used).collect(ImmutableList.toImmutableList());
    final List<SlotTransaction> slotTransactions = containerBasedTransactions.stream().map(InventoryBasedTransaction::getSlotTransactions).flatMap(List::stream).collect(Collectors.toList());
    for (InventoryBasedTransaction transaction : containerBasedTransactions) {
        transaction.used = true;
    }
    final List<Entity> entities = containerBasedTransactions.stream().map(InventoryBasedTransaction::getEntitiesSpawned).flatMap(List::stream).collect(Collectors.toList());
    // TODO on pickup grouping does not work?
    final Map<Slot, List<SlotTransaction>> collected = slotTransactions.stream().collect(Collectors.groupingBy(SlotTransaction::slot));
    slotTransactions.clear();
    collected.values().forEach(list -> {
        final SlotTransaction first = list.get(0);
        if (list.size() > 1) {
            final ItemStackSnapshot last = list.get(list.size() - 1).defaultReplacement();
            slotTransactions.add(new SlotTransaction(first.slot(), first.original(), last));
        } else {
            slotTransactions.add(first);
        }
    });
    return containerBasedTransactions.stream().map(t -> t.createInventoryEvent(slotTransactions, entities, context, currentCause)).filter(Optional::isPresent).map(Optional::get).findFirst();
}
Also used : Inventory(org.spongepowered.api.item.inventory.Inventory) NonNull(org.checkerframework.checker.nullness.qual.NonNull) SpawnEntityTransaction(org.spongepowered.common.event.tracking.context.transaction.world.SpawnEntityTransaction) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) TransactionTypes(org.spongepowered.common.event.tracking.context.transaction.type.TransactionTypes) ArrayList(java.util.ArrayList) MonotonicNonNull(org.checkerframework.checker.nullness.qual.MonotonicNonNull) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) CauseStackManager(org.spongepowered.api.event.CauseStackManager) LinkedList(java.util.LinkedList) Nullable(org.checkerframework.checker.nullness.qual.Nullable) SpawnEntityEvent(org.spongepowered.api.event.entity.SpawnEntityEvent) Slot(org.spongepowered.api.item.inventory.Slot) Entity(org.spongepowered.api.entity.Entity) Collectors(java.util.stream.Collectors) Player(net.minecraft.world.entity.player.Player) Cause(org.spongepowered.api.event.Cause) EntityUtil(org.spongepowered.common.entity.EntityUtil) List(java.util.List) GameTransaction(org.spongepowered.common.event.tracking.context.transaction.GameTransaction) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) ChangeInventoryEvent(org.spongepowered.api.event.item.inventory.ChangeInventoryEvent) PacketPhaseUtil(org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil) Optional(java.util.Optional) Collections(java.util.Collections) Entity(org.spongepowered.api.entity.Entity) Optional(java.util.Optional) Slot(org.spongepowered.api.item.inventory.Slot) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) List(java.util.List) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction)

Example 34 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class DropFromPlayerInventoryTransaction method createInventoryEvent.

@Override
Optional<ChangeInventoryEvent> createInventoryEvent(final List<SlotTransaction> slotTransactions, final List<Entity> entities, final PhaseContext<@NonNull ?> context, final Cause currentCause) {
    TrackingUtil.setCreatorReference(entities, this.player);
    final Cause causeWithSpawnType = Cause.builder().from(currentCause).build(EventContext.builder().from(currentCause.context()).add(EventContextKeys.SPAWN_TYPE, SpawnTypes.DROPPED_ITEM.get()).build());
    if (this.dropAll) {
        return Optional.of(SpongeEventFactory.createChangeInventoryEventDropFull(causeWithSpawnType, entities, this.inventory, this.slot, slotTransactions));
    }
    return Optional.of(SpongeEventFactory.createChangeInventoryEventDropSingle(causeWithSpawnType, entities, this.inventory, this.slot, slotTransactions));
}
Also used : Cause(org.spongepowered.api.event.Cause)

Example 35 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class DamageEventUtil method createAttackEnchantmentFunction.

public static List<DamageFunction> createAttackEnchantmentFunction(final net.minecraft.world.item.ItemStack heldItem, final MobType creatureAttribute, final float attackStrength) {
    if (heldItem.isEmpty()) {
        return Collections.emptyList();
    }
    final ListTag enchantmentCompounds = heldItem.getEnchantmentTags();
    if (enchantmentCompounds.isEmpty()) {
        return Collections.emptyList();
    }
    final Map<Enchantment, Collection<Integer>> enchantments = new HashMap<>();
    for (int i = 0; i < enchantmentCompounds.size(); ++i) {
        final String id = enchantmentCompounds.getCompound(i).getString("id");
        final int enchantmentLevel = enchantmentCompounds.getCompound(i).getInt("lvl");
        final Enchantment enchantment = Registry.ENCHANTMENT.get(new ResourceLocation(id));
        if (enchantment != null) {
            enchantments.computeIfAbsent(enchantment, k -> new ArrayList<>()).add(enchantmentLevel);
        }
    }
    if (enchantments.isEmpty()) {
        return Collections.emptyList();
    }
    final List<DamageFunction> damageModifierFunctions = new ArrayList<>();
    final ItemStackSnapshot snapshot = ItemStackUtil.snapshotOf(heldItem);
    for (final Map.Entry<Enchantment, Collection<Integer>> enchantment : enchantments.entrySet()) {
        final DamageModifier enchantmentModifier = DamageModifier.builder().type(DamageModifierTypes.WEAPON_ENCHANTMENT).cause(Cause.of(EventContext.empty(), snapshot, enchantment)).build();
        final DoubleUnaryOperator enchantmentFunction = (damage) -> {
            double totalDamage = 0;
            for (final int level : enchantment.getValue()) {
                totalDamage += (double) enchantment.getKey().getDamageBonus(level, creatureAttribute) * attackStrength;
            }
            return totalDamage;
        };
        damageModifierFunctions.add(new DamageFunction(enchantmentModifier, enchantmentFunction));
    }
    return damageModifierFunctions;
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation) LivingEntity(net.minecraft.world.entity.LivingEntity) AABB(net.minecraft.world.phys.AABB) LivingEntityAccessor(org.spongepowered.common.accessor.world.entity.LivingEntityAccessor) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) MobType(net.minecraft.world.entity.MobType) EventContext(org.spongepowered.api.event.EventContext) Registry(net.minecraft.core.Registry) ChunkSource(net.minecraft.world.level.chunk.ChunkSource) CreatorTrackedBridge(org.spongepowered.common.bridge.CreatorTrackedBridge) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Map(java.util.Map) PotionEffect(org.spongepowered.api.effect.potion.PotionEffect) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Player(net.minecraft.world.entity.player.Player) List(java.util.List) BlockPos(net.minecraft.core.BlockPos) BlockDamageSource(org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource) Optional(java.util.Optional) ServerLocation(org.spongepowered.api.world.server.ServerLocation) Enchantment(net.minecraft.world.item.enchantment.Enchantment) LevelChunk(net.minecraft.world.level.chunk.LevelChunk) LevelChunkBridge(org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge) EventContextKeys(org.spongepowered.api.event.EventContextKeys) ServerWorld(org.spongepowered.api.world.server.ServerWorld) BlockState(net.minecraft.world.level.block.state.BlockState) HashMap(java.util.HashMap) DamageModifierTypes(org.spongepowered.api.event.cause.entity.damage.DamageModifierTypes) MobEffects(net.minecraft.world.effect.MobEffects) DoubleUnaryOperator(java.util.function.DoubleUnaryOperator) ArrayList(java.util.ArrayList) EntityDamageSource(net.minecraft.world.damagesource.EntityDamageSource) ItemStackUtil(org.spongepowered.common.item.util.ItemStackUtil) DamageSource(net.minecraft.world.damagesource.DamageSource) EnchantmentHelper(net.minecraft.world.item.enchantment.EnchantmentHelper) CombatRules(net.minecraft.world.damagesource.CombatRules) Server(org.spongepowered.api.Server) CauseStackManager(org.spongepowered.api.event.CauseStackManager) FallingBlockDamageSource(org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource) Cause(org.spongepowered.api.event.Cause) Entity(net.minecraft.world.entity.Entity) DamageFunction(org.spongepowered.api.event.cause.entity.damage.DamageFunction) DamageModifier(org.spongepowered.api.event.cause.entity.damage.DamageModifier) EquipmentSlot(net.minecraft.world.entity.EquipmentSlot) Attributes(net.minecraft.world.entity.ai.attributes.Attributes) Mth(net.minecraft.util.Mth) Collections(java.util.Collections) ListTag(net.minecraft.nbt.ListTag) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ListTag(net.minecraft.nbt.ListTag) DamageModifier(org.spongepowered.api.event.cause.entity.damage.DamageModifier) ResourceLocation(net.minecraft.resources.ResourceLocation) DamageFunction(org.spongepowered.api.event.cause.entity.damage.DamageFunction) Collection(java.util.Collection) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) Enchantment(net.minecraft.world.item.enchantment.Enchantment) Map(java.util.Map) HashMap(java.util.HashMap) DoubleUnaryOperator(java.util.function.DoubleUnaryOperator)

Aggregations

Cause (org.spongepowered.api.event.Cause)55 ItemStackSnapshot (org.spongepowered.api.item.inventory.ItemStackSnapshot)19 ServerWorld (org.spongepowered.api.world.server.ServerWorld)18 Inject (org.spongepowered.asm.mixin.injection.Inject)18 ArrayList (java.util.ArrayList)16 BlockPos (net.minecraft.core.BlockPos)15 CauseStackManager (org.spongepowered.api.event.CauseStackManager)15 List (java.util.List)13 Optional (java.util.Optional)12 ServerLocation (org.spongepowered.api.world.server.ServerLocation)12 Entity (net.minecraft.world.entity.Entity)11 Player (net.minecraft.world.entity.player.Player)11 Collections (java.util.Collections)10 Collection (java.util.Collection)9 Map (java.util.Map)9 LivingEntity (net.minecraft.world.entity.LivingEntity)9 EventContext (org.spongepowered.api.event.EventContext)9 HashMap (java.util.HashMap)8 BlockState (net.minecraft.world.level.block.state.BlockState)8 ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)8