Search in sources :

Example 56 with GlowPlayer

use of net.glowstone.entity.GlowPlayer in project Glowstone by GlowstoneMC.

the class InteractEntityHandler method handle.

@Override
public void handle(GlowSession session, InteractEntityMessage message) {
    GlowPlayer player = session.getPlayer();
    EventFactory eventFactory = EventFactory.getInstance();
    // You can't do anything when you're dead
    if (player.isDead()) {
        GlowServer.logger.info("Player " + player.getName() + " tried to interact with an entity while dead");
        return;
    }
    GlowEntity possibleTarget = player.getWorld().getEntityManager().getEntity(message.getId());
    GlowLivingEntity target = possibleTarget instanceof GlowLivingEntity ? (GlowLivingEntity) possibleTarget : null;
    EquipmentSlot hand = message.getHandSlot();
    if (message.getAction() == Action.ATTACK.ordinal()) {
        if (target == null) {
            if (possibleTarget != null) {
                possibleTarget.entityInteract(player, message);
            } else {
                GlowServer.logger.info("Player " + player.getName() + " tried to attack an entity that does not exist");
            }
        } else if (!target.isDead() && target.canTakeDamage(DamageCause.ENTITY_ATTACK)) {
            // Calculate damage amount
            ItemStack itemInHand = InventoryUtil.itemOrEmpty(player.getInventory().getItem(hand));
            Material type = itemInHand.getType();
            boolean critical = player.getFallDistance() > 0.0F && !player.isOnGround() && !player.isInWater() && !player.isInsideVehicle() && !player.isSprinting();
            float damage = AttackDamage.getMeleeDamage(type, critical);
            if (critical) {
                // Critical-hit effect
                target.playAnimation(EntityAnimation.CRITICAL_HIT);
            }
            // Set entity on fire if the item has Fire Aspect
            if (itemInHand.containsEnchantment(Enchantment.FIRE_ASPECT)) {
                target.setFireTicks(target.getFireTicks() + itemInHand.getEnchantmentLevel(Enchantment.FIRE_ASPECT) * 80);
            }
            boolean showMagicCrit = false;
            // Apply other enchantments that amplify damage
            if (itemInHand.containsEnchantment(Enchantment.DAMAGE_ALL)) {
                // Sharpness
                int level = itemInHand.getEnchantmentLevel(Enchantment.DAMAGE_ALL);
                if (level > 0) {
                    damage += 1.0F + 0.5F * (level - 1);
                }
                if (!showMagicCrit) {
                    showMagicCrit = ToolType.SWORD.matches(type) || ToolType.AXE.matches(type);
                }
            }
            if (itemInHand.containsEnchantment(Enchantment.DAMAGE_ARTHROPODS)) {
                // Endermites)
                if (target.isArthropod()) {
                    int level = itemInHand.getEnchantmentLevel(Enchantment.DAMAGE_ARTHROPODS);
                    if (level > 0) {
                        damage += level * 2.5F;
                    // TODO: add Slowness potion effect (after damaging and checking for
                    // event-cancellation)
                    }
                }
                if (!showMagicCrit) {
                    showMagicCrit = ToolType.SWORD.matches(type) || ToolType.AXE.matches(type);
                }
            }
            if (itemInHand.containsEnchantment(Enchantment.DAMAGE_UNDEAD)) {
                // Smite (applies to "undead" mobs)
                if (target.isUndead()) {
                    int level = itemInHand.getEnchantmentLevel(Enchantment.DAMAGE_UNDEAD);
                    damage += level * 2.5F;
                }
                if (!showMagicCrit) {
                    showMagicCrit = ToolType.SWORD.matches(type) || ToolType.AXE.matches(type);
                }
            }
            if (showMagicCrit) {
                target.playAnimation(EntityAnimation.MAGIC_CRITICAL_HIT);
            }
            // Apply damage. Calls the EntityDamageByEntityEvent
            target.damage(damage, player, DamageCause.ENTITY_ATTACK);
            player.incrementStatistic(Statistic.DAMAGE_DEALT, Math.round(damage));
            player.addExhaustion(0.1f);
            if (target.isDead()) {
                player.incrementStatistic(target.getType() == EntityType.PLAYER ? Statistic.PLAYER_KILLS : Statistic.MOB_KILLS);
            }
            // Apply durability loss (if applicable)
            short durabilityLoss = AttackDamage.getMeleeDurabilityLoss(type);
            if (durabilityLoss > 0 && !InventoryUtil.isEmpty(itemInHand) && player.getGameMode() != GameMode.CREATIVE) {
                // Yes, this actually subtracts
                itemInHand.setDurability((short) (itemInHand.getDurability() + durabilityLoss));
            }
        }
    } else if (message.getAction() == Action.INTERACT_AT.ordinal()) {
        // used for adjusting specific portions of armor stands
        PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent(player, possibleTarget, new Vector(message.getTargetX(), message.getTargetY(), message.getTargetZ()), hand);
        eventFactory.callEvent(event);
        if (!event.isCancelled()) {
            possibleTarget.entityInteract(player, message);
        }
    } else if (message.getAction() == Action.INTERACT.ordinal()) {
        // Todo: Handle hand variable
        PlayerInteractEntityEvent event = new PlayerInteractEntityEvent(player, possibleTarget, hand);
        eventFactory.callEvent(event);
        if (!event.isCancelled()) {
            possibleTarget.entityInteract(player, message);
        }
    } else {
        GlowServer.logger.info("Player " + player.getName() + " sent unknown interact action: " + message.getAction());
    }
}
Also used : PlayerInteractAtEntityEvent(org.bukkit.event.player.PlayerInteractAtEntityEvent) GlowPlayer(net.glowstone.entity.GlowPlayer) GlowEntity(net.glowstone.entity.GlowEntity) EquipmentSlot(org.bukkit.inventory.EquipmentSlot) EventFactory(net.glowstone.EventFactory) GlowLivingEntity(net.glowstone.entity.GlowLivingEntity) Material(org.bukkit.Material) ItemStack(org.bukkit.inventory.ItemStack) Vector(org.bukkit.util.Vector) PlayerInteractEntityEvent(org.bukkit.event.player.PlayerInteractEntityEvent)

Example 57 with GlowPlayer

use of net.glowstone.entity.GlowPlayer in project Glowstone by GlowstoneMC.

the class PlayerUpdateHandler method handle.

@Override
public void handle(GlowSession session, PlayerUpdateMessage message) {
    GlowPlayer player = session.getPlayer();
    Location oldLocation = player.getLocation();
    Location newLocation = oldLocation.clone();
    message.update(newLocation);
    // don't let players reach an illegal position
    if (Math.abs(newLocation.getBlockX()) > 32000000 || Math.abs(newLocation.getBlockZ()) > 32000000) {
        session.getPlayer().kickPlayer("Illegal position");
        return;
    }
    /*
          don't let players move more than 100 blocks in a single packet
          if they move greater than 10 blocks, but less than 100, just warn
          this is NOT robust hack prevention - only to prevent client
          confusion about where its actual location is (e.g. during login)
        */
    if (message.moved() && !player.isDead()) {
        if (player.teleportedTo != null) {
            if (newLocation.equals(player.teleportedTo)) {
                player.endTeleport();
                return;
            } else {
                // outdated location, so skip packet
                return;
            }
        } else {
            double distance = newLocation.distanceSquared(oldLocation);
            if (distance > 100 * 100) {
                player.kickPlayer("You moved too quickly :( (Hacking?)");
                return;
            } else if (distance > 100) {
                GlowServer.logger.warning(player.getName() + " moved too quickly!");
            }
        }
    }
    // call move event if movement actually occurred and there are handlers registered
    if (!oldLocation.equals(newLocation) && PlayerMoveEvent.getHandlerList().getRegisteredListeners().length > 0) {
        PlayerMoveEvent event = EventFactory.getInstance().callEvent(new PlayerMoveEvent(player, oldLocation, newLocation));
        if (event.isCancelled()) {
            // tell client they're back where they started
            session.send(new PositionRotationMessage(oldLocation));
            return;
        }
        if (!event.getTo().equals(newLocation)) {
            // teleport to the set destination: fires PlayerTeleportEvent and
            // handles if the destination is in another world
            player.teleport(event.getTo(), TeleportCause.PLUGIN);
            return;
        }
        if (!Objects.equals(player.getLocation(), oldLocation)) {
            // plugin changed location on move event
            return;
        }
    }
    // move event was not fired or did nothing, simply update location
    player.setRawLocation(newLocation);
    if (Position.hasRotated(oldLocation, newLocation)) {
        player.setHeadYaw(newLocation.getYaw());
    }
    // do stuff with onGround if we need to
    if (player.isOnGround() != message.isOnGround()) {
        if (message.isOnGround() && player.getVelocity().getY() > 0) {
            // jump
            player.incrementStatistic(Statistic.JUMP);
            if (player.isSprinting()) {
                player.addExhaustion(0.2f);
            } else {
                player.addExhaustion(0.05f);
            }
        }
        player.setOnGround(message.isOnGround());
    }
    // Checks if the player is still wearing the Elytra
    ItemStack chestplate = player.getInventory().getChestplate();
    boolean hasElytra = chestplate != null && chestplate.getType() == Material.ELYTRA && chestplate.getDurability() < chestplate.getType().getMaxDurability();
    if (player.isGliding() && (player.isOnGround() || !hasElytra)) {
        player.setGliding(false);
    }
    player.addMoveExhaustion(newLocation);
    // track movement stats
    Vector delta = newLocation.clone().subtract(oldLocation).toVector();
    delta.setX(Math.abs(delta.getX()));
    delta.setY(Math.abs(delta.getY()));
    delta.setZ(Math.abs(delta.getZ()));
    int flatDistance = (int) Math.round(Math.hypot(delta.getX(), delta.getZ()) * 100.0);
    if (flatDistance <= 0) {
        return;
    }
    if (player.isInsideVehicle()) {
        final GlowEntity vehicle = player.getVehicle();
        if (vehicle != null) {
            switch(vehicle.getType()) {
                case BOAT:
                    player.incrementStatistic(Statistic.BOAT_ONE_CM, flatDistance);
                    break;
                case MINECART:
                    player.incrementStatistic(Statistic.MINECART_ONE_CM, flatDistance);
                    break;
                default:
                    break;
            }
        }
    } else if (message.isOnGround()) {
        if (player.isSprinting()) {
            player.incrementStatistic(Statistic.SPRINT_ONE_CM, flatDistance);
        } else if (player.isSneaking()) {
            player.incrementStatistic(Statistic.CROUCH_ONE_CM, flatDistance);
        } else {
            player.incrementStatistic(Statistic.WALK_ONE_CM, flatDistance);
        }
    } else if (player.isFlying()) {
        player.incrementStatistic(Statistic.FLY_ONE_CM, flatDistance);
    } else if (player.isInWater()) {
        player.incrementStatistic(Statistic.SWIM_ONE_CM, flatDistance);
    }
}
Also used : PositionRotationMessage(net.glowstone.net.message.play.game.PositionRotationMessage) GlowPlayer(net.glowstone.entity.GlowPlayer) GlowEntity(net.glowstone.entity.GlowEntity) PlayerMoveEvent(org.bukkit.event.player.PlayerMoveEvent) ItemStack(org.bukkit.inventory.ItemStack) Vector(org.bukkit.util.Vector) Location(org.bukkit.Location)

Example 58 with GlowPlayer

use of net.glowstone.entity.GlowPlayer in project Glowstone by GlowstoneMC.

the class PlayerAbilitiesHandler method handle.

@Override
public void handle(GlowSession session, PlayerAbilitiesMessage message) {
    // player sends this when changing whether or not they are currently flying
    // other values should match what we've sent in the past but are ignored here
    GlowPlayer player = session.getPlayer();
    boolean flyingFlag = (message.getFlags() & 0x02) != 0;
    // the current flying state
    boolean isFlying = player.isFlying();
    boolean canFly = player.getAllowFlight();
    if (isFlying != flyingFlag) {
        // or enabled it and is allowed to fly
        if (!flyingFlag || canFly) {
            PlayerToggleFlightEvent event = EventFactory.getInstance().callEvent(new PlayerToggleFlightEvent(player, flyingFlag));
            if (event.isCancelled()) {
                session.getServer().sendPlayerAbilities(player);
            } else {
                player.setFlying(flyingFlag);
            }
        }
    }
}
Also used : PlayerToggleFlightEvent(org.bukkit.event.player.PlayerToggleFlightEvent) GlowPlayer(net.glowstone.entity.GlowPlayer)

Example 59 with GlowPlayer

use of net.glowstone.entity.GlowPlayer in project Glowstone by GlowstoneMC.

the class PlayerSwingArmHandler method handle.

@Override
public void handle(GlowSession session, PlayerSwingArmMessage message) {
    GlowPlayer player = session.getPlayer();
    EventFactory eventFactory = EventFactory.getInstance();
    Block block = player.getTargetBlock((Set<Material>) null, 6);
    if (block == null || block.isEmpty()) {
        if (eventFactory.onPlayerInteract(player, Action.LEFT_CLICK_AIR, message.getHandSlot()).useItemInHand() == Result.DENY) {
            return;
        }
    // todo: item interactions with air
    }
    if (!eventFactory.callEvent(new PlayerAnimationEvent(player)).isCancelled()) {
        // play the animation to others
        player.playAnimation(message.getHand() == 1 ? EntityAnimation.SWING_OFF_HAND : EntityAnimation.SWING_MAIN_HAND);
    }
}
Also used : GlowPlayer(net.glowstone.entity.GlowPlayer) EventFactory(net.glowstone.EventFactory) Block(org.bukkit.block.Block) PlayerAnimationEvent(org.bukkit.event.player.PlayerAnimationEvent) Material(org.bukkit.Material)

Example 60 with GlowPlayer

use of net.glowstone.entity.GlowPlayer in project Glowstone by GlowstoneMC.

the class TabCompleteHandler method handle.

@Override
public void handle(GlowSession session, TabCompleteMessage message) {
    GlowPlayer sender = session.getPlayer();
    String buffer = message.getText();
    List<String> completions = new ArrayList<>();
    // complete command or username
    if (!buffer.isEmpty() && buffer.charAt(0) == '/') {
        List<String> items;
        if (!buffer.isEmpty() && buffer.charAt(0) == '/') {
            items = session.getServer().getCommandMap().tabComplete(sender, buffer.substring(1));
        } else {
            items = session.getServer().getCommandMap().tabComplete(sender, buffer);
        }
        if (items != null) {
            completions.addAll(items);
        }
    } else {
        int space = buffer.lastIndexOf(' ');
        String lastWord;
        if (space == -1) {
            lastWord = buffer;
        } else {
            lastWord = buffer.substring(space + 1);
        }
        // from Command
        for (Player player : session.getServer().getOnlinePlayers()) {
            String name = player.getName();
            if (sender.canSee(player) && StringUtil.startsWithIgnoreCase(name, lastWord)) {
                completions.add(name);
            }
        }
        completions.sort(String.CASE_INSENSITIVE_ORDER);
    }
    // call event and send response
    EventFactory.getInstance().callEvent(new PlayerChatTabCompleteEvent(sender, buffer, completions));
    // TODO: 1.13, properly implement tab-completion
    session.send(new TabCompleteResponseMessage(0, 0, 0, completions.stream().map(str -> new TabCompleteResponseMessage.Completion(str, null)).collect(Collectors.toList())));
}
Also used : List(java.util.List) MessageHandler(com.flowpowered.network.MessageHandler) PlayerChatTabCompleteEvent(org.bukkit.event.player.PlayerChatTabCompleteEvent) EventFactory(net.glowstone.EventFactory) StringUtil(org.bukkit.util.StringUtil) GlowSession(net.glowstone.net.GlowSession) TabCompleteMessage(net.glowstone.net.message.play.player.TabCompleteMessage) TabCompleteResponseMessage(net.glowstone.net.message.play.player.TabCompleteResponseMessage) GlowPlayer(net.glowstone.entity.GlowPlayer) Player(org.bukkit.entity.Player) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) PlayerChatTabCompleteEvent(org.bukkit.event.player.PlayerChatTabCompleteEvent) GlowPlayer(net.glowstone.entity.GlowPlayer) Player(org.bukkit.entity.Player) TabCompleteResponseMessage(net.glowstone.net.message.play.player.TabCompleteResponseMessage) GlowPlayer(net.glowstone.entity.GlowPlayer) ArrayList(java.util.ArrayList)

Aggregations

GlowPlayer (net.glowstone.entity.GlowPlayer)69 ItemStack (org.bukkit.inventory.ItemStack)15 Vector (org.bukkit.util.Vector)10 EventFactory (net.glowstone.EventFactory)9 Location (org.bukkit.Location)9 Player (org.bukkit.entity.Player)9 GlowEntity (net.glowstone.entity.GlowEntity)8 Message (com.flowpowered.network.Message)7 ArrayList (java.util.ArrayList)7 GlowBlock (net.glowstone.block.GlowBlock)7 Material (org.bukkit.Material)6 World (org.bukkit.World)6 Entity (org.bukkit.entity.Entity)6 List (java.util.List)5 GlowWorld (net.glowstone.GlowWorld)5 LocalizedStringImpl (net.glowstone.i18n.LocalizedStringImpl)5 BlockFace (org.bukkit.block.BlockFace)5 CommandTarget (net.glowstone.command.CommandTarget)4 AsyncableMessage (com.flowpowered.network.AsyncableMessage)3 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)3