use of org.lanternpowered.server.entity.event.CollectEntityEvent in project LanternServer by LanternPowered.
the class LanternItem method tryToPickupItems.
private void tryToPickupItems() {
final Set<Entity> entities = getWorld().getIntersectingEntities(getBoundingBox().get().expand(2.0, 0.5, 2.0), entity -> entity != this && entity instanceof Carrier);
if (entities.isEmpty()) {
return;
}
ItemStack itemStack = get(Keys.REPRESENTED_ITEM).map(ItemStackSnapshot::createStack).orElse(null);
if (itemStack == null) {
remove();
return;
}
// TODO: Call pre pickup event
for (Entity entity : entities) {
// Ignore dead entities
if (entity instanceof LanternLiving && ((LanternLiving) entity).isDead()) {
continue;
}
Inventory inventory = ((Carrier) entity).getInventory();
if (inventory instanceof PlayerInventory) {
inventory = ((PlayerInventory) inventory).getMain();
}
final PeekedOfferTransactionResult peekResult = ((IInventory) inventory).peekOffer(itemStack);
final ItemStack rejected = peekResult.getRejectedItem().orElse(null);
final CauseStack causeStack = CauseStack.current();
final ChangeInventoryEvent.Pickup event;
try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
frame.addContext(LanternEventContextKeys.ORIGINAL_ITEM_STACK, itemStack);
if (rejected != null) {
frame.addContext(LanternEventContextKeys.REST_ITEM_STACK, rejected);
}
event = SpongeEventFactory.createChangeInventoryEventPickup(causeStack.getCurrentCause(), inventory, peekResult.getTransactions());
event.setCancelled(!peekResult.isSuccess());
Sponge.getEventManager().post(event);
}
if (event.isCancelled() && !isRemoved()) {
// Don't continue if the entity was removed during the event
continue;
}
event.getTransactions().stream().filter(Transaction::isValid).forEach(transaction -> transaction.getSlot().set(transaction.getFinal().createStack()));
final int added;
if (rejected != null) {
added = itemStack.getQuantity() - rejected.getQuantity();
itemStack = rejected;
} else {
added = itemStack.getQuantity();
}
if (added != 0 && entity instanceof Living) {
triggerEvent(new CollectEntityEvent((Living) entity, added));
}
if (rejected == null || isRemoved()) {
itemStack = null;
}
if (itemStack == null) {
break;
}
}
if (itemStack != null) {
offer(Keys.REPRESENTED_ITEM, itemStack.createSnapshot());
} else {
remove();
}
}
use of org.lanternpowered.server.entity.event.CollectEntityEvent in project LanternServer by LanternPowered.
the class EntityProtocol method handleEvent.
@Override
protected void handleEvent(EntityProtocolUpdateContext context, EntityEvent event) {
if (event instanceof CollectEntityEvent) {
final LanternLiving collector = (LanternLiving) ((CollectEntityEvent) event).getCollector();
context.getId(collector).ifPresent(id -> {
final int count = ((CollectEntityEvent) event).getCollectedItemsCount();
context.sendToAll(() -> new MessagePlayOutEntityCollectItem(id, getRootEntityId(), count));
});
} else {
super.handleEvent(context, event);
}
}
Aggregations