use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.
the class LanternWorld method broadcast.
public void broadcast(Supplier<Message> message, @Nullable Predicate<LanternPlayer> filter) {
Set<LanternPlayer> players = this.players;
if (filter != null) {
players = players.stream().filter(filter).collect(Collectors.toSet());
}
if (players.isEmpty()) {
return;
}
final Message message0 = message.get();
players.forEach(player -> player.getConnection().send(message0));
}
use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.
the class ConsumableInteractionBehavior method tryUse.
@Override
public BehaviorResult tryUse(BehaviorPipeline<Behavior> pipeline, BehaviorContext context) {
final Optional<Player> optPlayer = context.getContext(ContextKeys.PLAYER);
if (optPlayer.isPresent()) {
final Player player = optPlayer.get();
final ItemStack itemStack = context.requireContext(ContextKeys.USED_ITEM_STACK);
final FoodRestorationProperty foodRestorationProperty = itemStack.getProperty(FoodRestorationProperty.class).orElse(null);
if (foodRestorationProperty != null && foodRestorationProperty.getValue() != 0.0) {
final Optional<Integer> maxFood = player.get(LanternKeys.MAX_FOOD_LEVEL);
final Optional<Integer> optFoodLevel = player.get(Keys.FOOD_LEVEL);
if (optFoodLevel.isPresent()) {
player.offer(Keys.FOOD_LEVEL, Math.min(optFoodLevel.get() + foodRestorationProperty.getValue(), maxFood.orElse(Integer.MAX_VALUE)));
}
}
final HealthRestorationProperty healthRestorationProperty = itemStack.getProperty(HealthRestorationProperty.class).orElse(null);
if (healthRestorationProperty != null && healthRestorationProperty.getValue() != 0.0) {
final Optional<Double> maxHealth = player.get(Keys.MAX_HEALTH);
final Optional<Double> optHealth = player.get(Keys.HEALTH);
if (optHealth.isPresent()) {
player.offer(Keys.HEALTH, Math.min(optHealth.get() + healthRestorationProperty.getValue(), maxHealth.orElse(Double.MAX_VALUE)));
}
}
final SaturationProperty saturationProperty = itemStack.getProperty(SaturationProperty.class).orElse(null);
if (saturationProperty != null && saturationProperty.getValue() != 0.0) {
final Optional<Double> optSaturation = player.get(Keys.SATURATION);
if (optSaturation.isPresent()) {
player.offer(Keys.SATURATION, Math.min(optSaturation.get() + saturationProperty.getValue(), player.get(Keys.FOOD_LEVEL).orElse(20)));
}
}
final ApplicableEffectProperty applicableEffectProperty = itemStack.getProperty(ApplicableEffectProperty.class).orElse(null);
if (applicableEffectProperty != null && !applicableEffectProperty.getValue().isEmpty()) {
final List<PotionEffect> potionEffects = player.get(Keys.POTION_EFFECTS).orElse(Collections.emptyList());
player.offer(Keys.POTION_EFFECTS, PotionEffectHelper.merge(potionEffects, applicableEffectProperty.getValue()));
}
if (this.consumer != null) {
this.consumer.apply(player, pipeline, context);
}
if (!player.get(Keys.GAME_MODE).orElse(GameModes.NOT_SET).equals(GameModes.CREATIVE)) {
final Slot slot = context.requireContext(ContextKeys.USED_SLOT);
slot.poll(1);
if (this.restItemSupplier != null) {
if (slot.peek().isPresent()) {
((LanternPlayer) player).getInventory().getMain().offer(this.restItemSupplier.get());
} else {
slot.set(this.restItemSupplier.get());
}
}
}
return BehaviorResult.SUCCESS;
}
return BehaviorResult.PASS;
}
use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.
the class LanternServer method shutdown.
@SuppressWarnings("deprecation")
@Override
public void shutdown(Text kickMessage) {
checkNotNull(kickMessage, "kickMessage");
if (this.shuttingDown) {
return;
}
this.shuttingDown = true;
// Stop the console
this.consoleManager.shutdown();
final Cause gameCause = Cause.of(EventContext.empty(), this.game);
this.game.postGameStateChange(SpongeEventFactory.createGameStoppingServerEvent(gameCause));
// Debug a message
this.logger.info("Stopping the server... ({})", LanternTexts.toLegacy(kickMessage));
// Kick all the online players
getOnlinePlayers().forEach(player -> ((LanternPlayer) player).getConnection().disconnect(kickMessage));
// Stop the network servers - starts the shutdown process
// It may take a second or two for Netty to totally clean up
this.networkManager.shutdown();
if (this.queryServer != null) {
this.queryServer.shutdown();
}
if (this.rconServer != null) {
this.rconServer.shutdown();
}
// Stop the world manager
this.worldManager.shutdown();
// Shutdown the executor
this.executor.shutdown();
// Stop the async scheduler
this.game.getScheduler().shutdownAsyncScheduler(10, TimeUnit.SECONDS);
final Collection<ProviderRegistration<?>> serviceRegistrations;
try {
final ServiceManager serviceManager = this.game.getServiceManager();
checkState(serviceManager instanceof SimpleServiceManager || serviceManager instanceof LanternServiceManager);
final Field field = (serviceManager instanceof SimpleServiceManager ? SimpleServiceManager.class : LanternServiceManager.class).getDeclaredField("providers");
field.setAccessible(true);
// noinspection unchecked
final Map<Class<?>, ProviderRegistration<?>> map = (Map<Class<?>, ProviderRegistration<?>>) field.get(serviceManager);
serviceRegistrations = map.values();
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
// Close all the services if possible
serviceRegistrations.forEach(provider -> {
final Object service = provider.getProvider();
if (service instanceof CloseableService) {
try {
((CloseableService) service).close();
} catch (Exception e) {
this.logger.error("A error occurred while closing the {}.", provider.getService().getName(), e);
}
}
});
// Shutdown the game profile manager
this.game.getGameProfileManager().getDefaultCache().save();
final GameProfileCache cache = this.game.getGameProfileManager().getCache();
if (cache instanceof CloseableService) {
try {
((CloseableService) cache).close();
} catch (Exception e) {
this.logger.error("A error occurred while closing the GameProfileCache.", e);
}
}
try {
this.game.getOpsConfig().save();
} catch (IOException e) {
this.logger.error("A error occurred while saving the ops config.", e);
}
this.game.postGameStateChange(SpongeEventFactory.createGameStoppedServerEvent(gameCause));
this.game.postGameStateChange(SpongeEventFactory.createGameStoppingEvent(gameCause));
this.game.postGameStateChange(SpongeEventFactory.createGameStoppedEvent(gameCause));
// Wait for a while and terminate any rogue threads
new ShutdownMonitorThread().start();
}
use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.
the class LanternLiving method handleDeath.
private void handleDeath() {
// have already been thrown.
if (getWorld() == null) {
setDead(true);
}
if (isDead()) {
return;
}
setDead(true);
final CauseStack causeStack = CauseStack.current();
// Only players can keep their inventory
final boolean keepsInventory = this instanceof LanternPlayer && getWorld().getOrCreateRule(RuleTypes.KEEP_INVENTORY).getValue();
// Post the entity destruction event
final DestructEntityEvent.Death event = SpongeEventFactory.createDestructEntityEventDeath(causeStack.getCurrentCause(), MessageChannel.TO_NONE, Optional.empty(), new MessageEvent.MessageFormatter(), this, keepsInventory, false);
postDestructEvent(event);
try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
// Add the destruct event to the cause, this can be used
// to track the cause of the entity death.
frame.pushCause(event);
// Post the harvest event
handleDeath(causeStack);
}
// Clear the inventory, if keepsInventory is false in the thrown Death event
if (!event.getKeepInventory() && this instanceof Carrier) {
((Carrier) this).getInventory().clear();
}
}
use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.
the class VanillaContainerInteractionBehavior method handleShiftClick.
@Override
public void handleShiftClick(ClientContainer clientContainer, ClientSlot clientSlot, MouseButton mouseButton) {
final LanternPlayer player = clientContainer.getPlayer();
if (player != this.container.getPlayerInventory().getCarrier().orElse(null) || !(clientSlot instanceof ClientSlot.Slot) || mouseButton == MouseButton.MIDDLE) {
return;
}
final AbstractInventorySlot slot = ((ClientSlot.Slot) clientSlot).getSlot();
final ItemStack itemStack = slot.peek().orElse(null);
final Transaction<ItemStackSnapshot> cursorTransaction;
final List<SlotTransaction> transactions = new ArrayList<>();
if (slot instanceof CraftingOutput) {
final ItemStackSnapshot cursorItem = LanternItemStack.toSnapshot(getCursorItem());
cursorTransaction = new Transaction<>(cursorItem, cursorItem);
final AbstractInventory parent = slot.parent();
if (parent instanceof CraftingInventory) {
final CraftingInventory inventory = (CraftingInventory) parent;
final Optional<ExtendedCraftingResult> optResult = Lantern.getRegistry().getCraftingRecipeRegistry().getExtendedResult(inventory.getCraftingGrid(), player.getWorld());
if (optResult.isPresent()) {
final ExtendedCraftingResult result = optResult.get();
final ItemStackSnapshot resultItem = result.getResult().getResult();
int times = result.getMaxTimes();
final ItemStack itemStack1 = resultItem.createStack();
itemStack1.setQuantity(times * itemStack1.getQuantity());
final AbstractInventory targetInventory = this.container.getPlayerInventory().getView(LanternPlayerInventory.View.REVERSE_MAIN_AND_HOTBAR);
PeekedOfferTransactionResult peekResult = targetInventory.peekOffer(itemStack1);
if (peekResult.isSuccess()) {
transactions.add(new SlotTransaction(slot, resultItem, ItemStackSnapshot.NONE));
final ItemStack rejectedItem = peekResult.getRejectedItem().orElse(null);
if (rejectedItem != null) {
final int added = itemStack1.getQuantity() - rejectedItem.getQuantity();
times = added / resultItem.getQuantity();
final int diff = added % resultItem.getQuantity();
if (diff != 0) {
itemStack1.setQuantity(resultItem.getQuantity() * times);
peekResult = targetInventory.peekOffer(itemStack1);
checkState(peekResult.isSuccess());
}
}
transactions.addAll(peekResult.getTransactions());
updateCraftingGrid(player, inventory, result.getMatrixResult(times), transactions);
}
} else {
// No actual transaction, there shouldn't have been a item in the crafting result slot
transactions.add(new SlotTransaction(slot, ItemStackSnapshot.NONE, ItemStackSnapshot.NONE));
}
} else {
Lantern.getLogger().warn("Found a CraftingOutput slot without a CraftingInventory as parent.");
return;
}
} else {
final ItemStackSnapshot cursorItem = LanternItemStack.toSnapshot(getCursorItem());
cursorTransaction = new Transaction<>(cursorItem, cursorItem);
if (itemStack != null) {
final IInventory target = this.container.getOpenInventory().getShiftClickBehavior().getTarget(this.container, slot);
final PeekedOfferTransactionResult result = target.peekOffer(itemStack.copy());
if (result.isSuccess()) {
transactions.addAll(result.getTransactions());
final ItemStack rejectedItem = result.getRejectedItem().orElse(null);
if (rejectedItem != null) {
slot.peekPoll(itemStack.getQuantity() - rejectedItem.getQuantity(), stack -> true).ifPresent(peekResult -> transactions.addAll(peekResult.getTransactions()));
} else {
slot.peekPoll(stack -> true).ifPresent(peekResult -> transactions.addAll(peekResult.getTransactions()));
}
}
}
}
final List<SlotTransaction> transactions1 = this.container.transformSlots(transactions);
final CauseStack causeStack = CauseStack.current();
final ClickInventoryEvent.Shift event;
if (mouseButton == MouseButton.LEFT) {
event = SpongeEventFactory.createClickInventoryEventShiftPrimary(causeStack.getCurrentCause(), cursorTransaction, this.container, transactions1);
} else {
event = SpongeEventFactory.createClickInventoryEventShiftSecondary(causeStack.getCurrentCause(), cursorTransaction, this.container, transactions1);
}
finishInventoryEvent(event);
}
Aggregations