Java Code Examples for org.bukkit.entity.Player#getWorld()

The following examples show how to use org.bukkit.entity.Player#getWorld() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NearCommand.java    From HolographicDisplays with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(CommandSender sender, String label, String[] args) throws CommandException {
	Player player = CommandValidator.getPlayerSender(sender);
	int radius = CommandValidator.getInteger(args[0]);
	CommandValidator.isTrue(radius > 0, "Radius must be at least 1.");
	
	World world = player.getWorld();
	int radiusSquared = radius * radius;
	List<NamedHologram> nearHolograms = new ArrayList<>();
	
	for (NamedHologram hologram : NamedHologramManager.getHolograms()) {
		if (hologram.getLocation().getWorld().equals(world) && hologram.getLocation().distanceSquared(player.getLocation()) <= radiusSquared) {
			nearHolograms.add(hologram);
		}
	}
	
	CommandValidator.isTrue(!nearHolograms.isEmpty(), "There are no holograms in the given radius.");
	
	player.sendMessage(Strings.formatTitle("Near holograms"));
	for (NamedHologram nearHologram : nearHolograms) {
		player.sendMessage(Colors.SECONDARY_SHADOW + "- " + Colors.SECONDARY + Colors.BOLD + nearHologram.getName() + " " + Colors.SECONDARY_SHADOW + "at x: " + (int) nearHologram.getX() + ", y: " + (int) nearHologram.getY() + ", z: " + (int) nearHologram.getZ() + " (lines: " + nearHologram.size() + ")");
	}
}
 
Example 2
Source File: MiscUtils.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Player findTarget(Game game, Player player, double maxDist) {
    Player playerTarget = null;
    RunningTeam team = game.getTeamOfPlayer(player);

    ArrayList<Player> foundTargets = new ArrayList<>(game.getConnectedPlayers());
    foundTargets.removeAll(team.getConnectedPlayers());


    for (Player p : foundTargets) {
        GamePlayer gamePlayer = Main.getPlayerGameProfile(p);
        if (player.getWorld() != p.getWorld()) {
            continue;
        }

        if (gamePlayer.isSpectator) {
            continue;
        }

        double realDistance = player.getLocation().distance(p.getLocation());
        if (realDistance < maxDist) {
            playerTarget = p;
            maxDist = realDistance;
        }
    }
    return playerTarget;
}
 
Example 3
Source File: EconomyUtil.java    From GriefDefender with MIT License 6 votes vote down vote up
public void economyCreateClaimConfirmation(Player player, GDPlayerData playerData, int height, Vector3i point1, Vector3i point2, ClaimType claimType, boolean cuboid, Claim parent) {
    GDClaim claim = new GDClaim(player.getWorld(), point1, point2, claimType, player.getUniqueId(), cuboid);
    claim.parent = (GDClaim) parent;
    final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(player);
    final int claimCost = BlockUtil.getInstance().getClaimBlockCost(player.getWorld(), claim.lesserBoundaryCorner, claim.greaterBoundaryCorner, claim.cuboid);
    final Double economyBlockCost = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Double.class), user, Options.ECONOMY_BLOCK_COST, claim);
    final double requiredFunds = claimCost * economyBlockCost;
    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ECONOMY_CLAIM_BUY_CONFIRMATION,
            ImmutableMap.of("amount", "$" + String.format("%.2f", requiredFunds)));
    final Component buyConfirmationText = TextComponent.builder()
            .append(message)
            .append(TextComponent.builder()
                .append("\n[")
                .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN))
                .append("]\n")
                .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, economyClaimBuyConfirmed(player, playerData, height, requiredFunds, point1, point2, claimType, cuboid, parent), true))).build())
            .build();
    GriefDefenderPlugin.sendMessage(player, buyConfirmationText);
}
 
Example 4
Source File: NMSUtilsHologramInteraction.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void updatePlayerHologram(Player player, Location holoLocation) {
       List<Hologram> holograms;
       if (!this.holograms.containsKey(player)) {
           this.holograms.put(player, new ArrayList<>());
       }

       holograms = this.holograms.get(player);
       Hologram holo = this.getHologramByLocation(holograms, holoLocation);
       if (holo == null && player.getWorld() == holoLocation.getWorld()) {
           holograms.add(this.createPlayerStatisticHologram(player, holoLocation));
       } else if (holo != null) {
           if (holo.getLocation().getWorld() == player.getWorld()) {
               this.updatePlayerStatisticHologram(player, holo);
           } else {
               holograms.remove(holo);
               holo.destroy();
           }
       }
}
 
Example 5
Source File: ForceFieldAdapter.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent e) {
    if(e.isCancelled()) return;

    Player player = e.getPlayer();
    ICombatManager combatManager = this.plugin.getCombatManager();
    if(!combatManager.isInCombat(player)) return;

    UUID uuid = player.getUniqueId();
    PacketContainer packet = e.getPacket();
    World world = player.getWorld();

    WrapperPlayServerBlockChange block = new WrapperPlayServerBlockChange(packet);
    Location location = packet.getBlockPositionModifier().read(0).toLocation(world);
    if(this.forceField.fakeBlocks.containsKey(uuid) && this.forceField.isSafe(location, player) && this.forceField.isSafeSurround(location, player) && ForceField.canPlace(location) && this.forceField.fakeBlocks.get(uuid).contains(location)) {
        block.setBlockData(this.forceField.wrappedData(block.getBlockData()));
    }
}
 
Example 6
Source File: TestCargoNodeListener.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@ParameterizedTest
@SlimefunItemsSource(items = { "CARGO_INPUT_NODE", "CARGO_OUTPUT_NODE", "CARGO_OUTPUT_NODE_2" })
public void testInvalidPlacement(ItemStack item) {
    Player player = server.addPlayer();
    Location l = new Location(player.getWorld(), 190, 50, 400);
    Block b = l.getBlock();
    Block against = b.getRelative(BlockFace.DOWN);

    BlockPlaceEvent event = new BlockPlaceEvent(b, new BlockStateMock(), against, item, player, true, EquipmentSlot.HAND);
    listener.onCargoNodePlace(event);
    Assertions.assertTrue(event.isCancelled());
}
 
Example 7
Source File: CopyFlagCommand.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (sender instanceof ConsoleCommandSender) {
        HandleHelpPage(sender, 1);
        return true;
    }

    Player player = (Player) sender;

    if (args.length == 2) {
        World w = player.getWorld();
        Region from = RedProtect.get().rm.getRegion(args[0], w.getName());
        Region to = RedProtect.get().rm.getRegion(args[1], w.getName());
        if (from == null || !from.isLeader(player)) {
            RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.region.doesntexist") + ": " + args[0]);
            return true;
        }
        if (to == null || !to.isLeader(player)) {
            RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.region.doesntexist") + ": " + args[1]);
            return true;
        }
        for (Map.Entry<String, Object> key : from.getFlags().entrySet()) {
            to.setFlag(sender, key.getKey(), key.getValue());
        }
        RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.region.flag.copied") + args[0] + " > " + args[1]);
        RedProtect.get().logger.addLog("Player " + player.getName() + " Copied FLAGS from " + args[0] + " to " + args[1]);
        return true;
    }

    RedProtect.get().lang.sendCommandHelp(sender, "copyflag", true);
    return true;
}
 
Example 8
Source File: Sniper.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public AsyncWorld getWorld() {
    AsyncWorld world = permanentWorld;
    if (world == null) {
        Player bukkitPlayer = getPlayer();
        World bukkitWorld = bukkitPlayer.getWorld();
        world = AsyncWorld.wrap(bukkitWorld);
        permanentWorld = world;
    }
    return world;
}
 
Example 9
Source File: WEHook.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public static void setSelectionFromRP(Player p, Location pos1, Location pos2) {
    WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
    BukkitWorld ws = new BukkitWorld(p.getWorld());
    if (worldEdit.getSession(p) == null || !worldEdit.getSession(p).isSelectionDefined(ws)) {
        setSelection(ws, p, pos1, pos2);
    } else {
        worldEdit.getSession(p).getRegionSelector(ws).clear();
        RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("cmdmanager.region.select-we.hide"));
    }
    worldEdit.getSession(p).dispatchCUISelection(worldEdit.wrapPlayer(p));
}
 
Example 10
Source File: TeleportationService.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
private Location buildLocationFromAuth(Player player, PlayerAuth auth) {
    World world = bukkitService.getWorld(auth.getWorld());
    if (world == null) {
        world = player.getWorld();
    }
    return new Location(world, auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(),
        auth.getYaw(), auth.getPitch());
}
 
Example 11
Source File: CommandClaimAbandonWorld.java    From GriefDefender with MIT License 5 votes vote down vote up
@CommandCompletion("@gdworlds @gddummy")
@CommandAlias("abandonworld")
@Description("Special admin command used to abandon ALL user claims in world")
@Subcommand("abandon world")
@Syntax("[<world>]")
public void execute(Player player, @Optional String worldName) {
    World world = player.getWorld();
    if (worldName != null) {
        world = Bukkit.getWorld(worldName);
        if (world == null) {
            TextAdapter.sendComponent(player, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.COMMAND_WORLD_NOT_FOUND,
                    ImmutableMap.of("world", worldName)));
            return;
        }
    }
    final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(player.getWorld().getUID());
    if (claimWorldManager.getWorldClaims().size() == 0) {
        try {
            throw new CommandException(MessageCache.getInstance().CLAIM_NO_CLAIMS);
        } catch (CommandException e) {
            TextAdapter.sendComponent(player, e.getText());
            return;
        }
    }

    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ABANDON_WORLD_WARNING, ImmutableMap.of(
            "world", TextComponent.of(world.getName())));
    final Component confirmationText = TextComponent.builder()
            .append(message)
            .append(TextComponent.builder()
                .append("\n[")
                .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN))
                .append("]\n")
                .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, createConfirmationConsumer(player, world), true)))
                .hoverEvent(HoverEvent.showText(MessageCache.getInstance().UI_CLICK_CONFIRM)).build())
            .build();
    TextAdapter.sendComponent(player, confirmationText);
}
 
Example 12
Source File: ChickenGizmo.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
Chicken(Player player) {
    this.player = player;
    this.entity = new NMSHacks.FakeChicken(
        player.getWorld(),
        identityProvider.currentIdentity(player).getPublicName()
    );

    eventRegistry.registerListener(this);
}
 
Example 13
Source File: SafeBoat.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param e - event
 *            This event aims to put the player in a safe place when they
 *            exit the boat
 */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onBoatExit(VehicleExitEvent e) {
    final Entity boat = e.getVehicle();
    if (!boat.getType().equals(EntityType.BOAT)) {
        // Not a boat
        return;
    }
    // LivingEntity entity = e.getExited();
    final Entity entityObj = e.getExited();
    if (!(entityObj instanceof Player)) {
        return;
    }
    final Player player = (Player) entityObj;
    final World playerWorld = player.getWorld();
    if (!playerWorld.getName().equalsIgnoreCase(Settings.worldName)) {
        // Not the right world
        return;
    }
    if (SafeBoat.ignoreList.contains(player.getUniqueId())) {
        return;
    }
    // Set the boat exit flag for this player
    // midTeleport.add(player.getUniqueId());
    if (exitedBoat.containsKey(player.getUniqueId())) {
        // Debounce
        e.setCancelled(true);
    } else {
        exitedBoat.put(player.getUniqueId(), boat);
    }
    return;
}
 
Example 14
Source File: WorldEditHandler7_beta_1.java    From AreaShop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public WorldEditSelection getPlayerSelection(Player player) {
	try {
		Region region = pluginInterface.getWorldEdit().getSession(player).getSelection(BukkitAdapter.adapt(player.getWorld()));
		return new WorldEditSelection(
				player.getWorld(),
				BukkitAdapter.adapt(player.getWorld(), region.getMinimumPoint()),
				BukkitAdapter.adapt(player.getWorld(), region.getMaximumPoint())
		);
	} catch (IncompleteRegionException e) {
		return null;
	}
}
 
Example 15
Source File: ClaimBlockTask.java    From GriefDefender with MIT License 4 votes vote down vote up
@Override
public void run() {
    for (World world : Bukkit.getServer().getWorlds()) {
        for (Player player : world.getPlayers()) {
            final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
            final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
            final GDPermissionUser holder = PermissionHolderCache.getInstance().getOrCreateUser(player);
            final int accrualPerHour = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Integer.class), holder, Options.BLOCKS_ACCRUED_PER_HOUR, claim).intValue();
            if (accrualPerHour > 0) {
                Location lastLocation = playerData.lastAfkCheckLocation;
                // if he's not in a vehicle and has moved at least three blocks since the last check and he's not being pushed around by fluids
                if (player.getVehicle() == null &&
                        (lastLocation == null || lastLocation.getWorld() != player.getWorld() || lastLocation.distanceSquared(player.getLocation()) >= 0) &&
                        !NMSUtil.getInstance().isBlockWater(player.getLocation().getBlock())) {
                    int accruedBlocks = playerData.getBlocksAccruedPerHour() / 12;
                    if (accruedBlocks < 0) {
                        accruedBlocks = 1;
                    }

                    if (GriefDefenderPlugin.getInstance().isEconomyModeEnabled()) {
                        final VaultProvider vaultProvider = GriefDefenderPlugin.getInstance().getVaultProvider();
                        if (!vaultProvider.hasAccount(player)) {
                            continue;
                        }
                        vaultProvider.depositPlayer(player, accruedBlocks);
                    } else {
                        int currentTotal = playerData.getAccruedClaimBlocks();
                        if ((currentTotal + accruedBlocks) > playerData.getMaxAccruedClaimBlocks()) {
                            playerData.setAccruedClaimBlocks(playerData.getMaxAccruedClaimBlocks());
                            playerData.lastAfkCheckLocation = player.getLocation();
                            return;
                        }

                        playerData.setAccruedClaimBlocks(playerData.getAccruedClaimBlocks() + accruedBlocks);
                    }
                }

                playerData.lastAfkCheckLocation = player.getLocation();
            }
        }
    }
}
 
Example 16
Source File: FightHitbox.java    From Hawk with GNU General Public License v3.0 4 votes vote down vote up
private void processDirection(InteractEntityEvent e, float yaw, float pitch) {
    Entity entity = e.getEntity();
    if (!(entity instanceof Player) && !CHECK_OTHER_ENTITIES)
        return;
    Player attacker = e.getPlayer();
    int ping = ServerUtils.getPing(attacker);
    if (ping > PING_LIMIT && PING_LIMIT != -1)
        return;

    HawkPlayer att = e.getHawkPlayer();
    Location attackerEyeLocation = att.getPosition().clone().add(new Vector(0, 1.62, 0)).toLocation(att.getWorld());
    Vector attackerDirection = MathPlus.getDirection(yaw, pitch);

    double maxReach = MAX_REACH;
    if (attacker.getGameMode() == GameMode.CREATIVE)
        maxReach += 1.9;

    Vector victimLocation;
    if (LAG_COMPENSATION)
        //No need to add 50ms; the move and attack are already chronologically so close together
        victimLocation = hawk.getLagCompensator().getHistoryLocation(ping, e.getEntity()).toVector();
    else
        victimLocation = e.getEntity().getLocation().toVector();

    Vector eyePos = new Vector(attackerEyeLocation.getX(), attacker.isSneaking() ? attackerEyeLocation.getY() - 0.08 : attackerEyeLocation.getY(), attackerEyeLocation.getZ());
    Vector direction = new Vector(attackerDirection.getX(), attackerDirection.getY(), attackerDirection.getZ());
    Ray attackerRay = new Ray(eyePos, direction);

    AABB victimAABB;
    victimAABB = WrappedEntity.getWrappedEntity(entity).getHitbox(victimLocation);
    victimAABB.expand(BOX_EPSILON, BOX_EPSILON, BOX_EPSILON);

    Vector intersectVec3d = victimAABB.intersectsRay(attackerRay, 0, Float.MAX_VALUE);

    if (DEBUG_HITBOX) {
        victimAABB.highlight(hawk, attacker.getWorld(), 0.29);
    }

    if (DEBUG_RAY) {
        attackerRay.highlight(hawk, attacker.getWorld(), maxReach, 0.1);
    }

    if (intersectVec3d != null) {
        Location intersect = new Location(attacker.getWorld(), intersectVec3d.getX(), intersectVec3d.getY(), intersectVec3d.getZ());
        double interDistance = intersect.distance(attackerEyeLocation);
        if (interDistance > maxReach) {
            punish(att, 1, true, e, new Placeholder("type", "Reach: " + MathPlus.round(interDistance, 2) + "m"));
            return;
        }
        if (CHECK_OCCLUSION && interDistance > 1D) {
            BlockIterator iter = new BlockIterator(attacker.getWorld(), eyePos, attackerDirection, 0, (int) interDistance + 1);
            while (iter.hasNext()) {
                Block bukkitBlock = iter.next();

                if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
                    continue;

                WrappedBlock b = WrappedBlock.getWrappedBlock(bukkitBlock, att.getClientVersion());
                Vector intersection = b.getHitBox().intersectsRay(new Ray(attackerEyeLocation.toVector(), attackerDirection), 0, Float.MAX_VALUE);
                if (intersection != null) {
                    if (intersection.distance(eyePos) < interDistance) {
                        punish(att, 1, true, e, new Placeholder("type", "Interacted through " + b.getBukkitBlock().getType()));
                        return;
                    }
                }
            }

        }
    } else if (CHECK_BOX_INTERSECTION) {
        punish(att, 1, true, e, new Placeholder("type", "Did not hit hitbox."));
        return;
    }

    reward(att); //reward player
}
 
Example 17
Source File: SingleGameCycle.java    From BedwarsRel with GNU General Public License v3.0 4 votes vote down vote up
private void kickPlayer(Player player, boolean wasSpectator) {
  for (Player freePlayer : this.getGame().getFreePlayers()) {
    player.showPlayer(freePlayer);
  }

  if (wasSpectator && this.getGame().isFull()) {
    this.getGame().playerLeave(player, false);
    return;
  }

  if (BedwarsRel.getInstance().toMainLobby()) {
    if (BedwarsRel.getInstance().allPlayersBackToMainLobby()) {
      this.getGame().playerLeave(player, false);
      return;
    } else {
      player.teleport(this.getGame().getLobby());
    }
  } else {
    player.teleport(this.getGame().getLobby());
  }

  if (BedwarsRel.getInstance().isHologramsEnabled()
      && BedwarsRel.getInstance().getHolographicInteractor() != null
      && this.getGame().getLobby() == player.getWorld()) {
    BedwarsRel.getInstance().getHolographicInteractor().updateHolograms(player);
  }

  if (BedwarsRel.getInstance().statisticsEnabled()) {
    PlayerStatistic statistic =
        BedwarsRel.getInstance().getPlayerStatisticManager().getStatistic(player);
    BedwarsRel.getInstance().getPlayerStatisticManager().storeStatistic(statistic);

    if (BedwarsRel.getInstance().getBooleanConfig("statistics.show-on-game-end", true)) {
      BedwarsRel.getInstance().getServer().dispatchCommand(player, "bw stats");
    }
  }

  this.getGame().setPlayerDamager(player, null);

  PlayerStorage storage = this.getGame().getPlayerStorage(player);
  storage.clean();
  storage.loadLobbyInventory(this.getGame());
}
 
Example 18
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public boolean canBreak(Player p, Block b) {
    if (!RedProtect.get().config.configRoot().private_cat.use || p.hasPermission("redprotect.bypass")) {
        return true;
    }
    Region reg = RedProtect.get().rm.getTopRegion(b.getLocation());
    if (reg == null && !RedProtect.get().config.configRoot().private_cat.allow_outside) {
        return true;
    }
    int x = b.getX();
    int y = b.getY();
    int z = b.getZ();
    World w = p.getWorld();

    boolean deny = true;

    if (isSign(b) && validatePrivateSign(b)) {
        deny = false;
        if (validateBreakSign(b, p)) {
            return true;
        }
    }

    String signbtype = b.getType().name();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;

    if (blocks.stream().anyMatch(signbtype::matches)) {
        for (int sx = -1; sx <= 1; sx++) {
            for (int sy = -1; sy <= 1; sy++) {
                for (int sz = -1; sz <= 1; sz++) {
                    Block bs = w.getBlockAt(x + sx, y + sy, z + sz);
                    if (isSign(bs) && (validatePrivateSign(bs))) {
                        deny = false;
                        if (validateBreakSign(bs, p)) {
                            return true;
                        }
                    }

                    String blocktype2 = b.getType().name();

                    int x2 = bs.getX();
                    int y2 = bs.getY();
                    int z2 = bs.getZ();

                    if (blocks.stream().anyMatch(blocktype2::matches)) {
                        for (int ux = -1; ux <= 1; ux++) {
                            for (int uy = -1; uy <= 1; uy++) {
                                for (int uz = -1; uz <= 1; uz++) {
                                    Block bu = w.getBlockAt(x2 + ux, y2 + uy, z2 + uz);
                                    if (isSign(bu) && (validatePrivateSign(bu))) {
                                        deny = false;
                                        if (validateBreakSign(bu, p)) {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return deny;
}
 
Example 19
Source File: Reward.java    From CombatLogX with GNU General Public License v3.0 4 votes vote down vote up
protected boolean canActivateReward(Player player, Entity enemy) {
    if(player == null || enemy == null) return false;
    
    World world = player.getWorld();
    return (calculateChance() && isWorldAllowed(world) && isMobAllowed(enemy));
}
 
Example 20
Source File: PacketConverter7.java    From Hawk with GNU General Public License v3.0 4 votes vote down vote up
private static Event packetToUseEvent(PacketPlayInBlockPlace packet, Player p, HawkPlayer pp) {
    Material mat;
    if (packet.getItemStack() != null && packet.getItemStack().getItem() != null) {
        Block block = Block.a(packet.getItemStack().getItem());
        //noinspection deprecation
        mat = Material.getMaterial(Block.getId(block));
    } else {
        mat = null;
    }

    int x = packet.c();
    int y = packet.d();
    int z = packet.e();
    Vector targetedPosition = new Vector(x, y, z);
    InteractWorldEvent.BlockFace face;
    //Debug.broadcastMessage("FACE: " + packet.getFace());
    //Debug.broadcastMessage(x + " " + y + " " + z);
    //Debug.broadcastMessage(mat + "");

    InteractWorldEvent.InteractionType interactionType;
    //first vector is for 1.8 clients, second is for 1.7
    if(!targetedPosition.equals(new Vector(-1, -1, -1)) && !targetedPosition.equals(new Vector(-1, 255, -1))) {
        if(mat != null && mat != Material.AIR) {
            interactionType = InteractWorldEvent.InteractionType.PLACE_BLOCK;
        }
        else {
            interactionType = InteractWorldEvent.InteractionType.INTERACT_BLOCK;
        }
    }
    else {
        ItemStack item = p.getInventory().getItem(pp.getHeldItemSlot());
        if(item == null)
            return null;
        return new InteractItemEvent(p, pp, item, InteractItemEvent.Action.START_USE_ITEM, new WrappedPacket7(packet, WrappedPacket.PacketType.BLOCK_PLACE));
    }

    switch (packet.getFace()) {
        case 0:
            face = InteractWorldEvent.BlockFace.BOTTOM;
            y -= 1;
            break;
        case 1:
            face = InteractWorldEvent.BlockFace.TOP;
            y += 1;
            break;
        case 2:
            face = InteractWorldEvent.BlockFace.NORTH;
            z -= 1;
            break;
        case 3:
            face = InteractWorldEvent.BlockFace.SOUTH;
            z += 1;
            break;
        case 4:
            face = InteractWorldEvent.BlockFace.WEST;
            x -= 1;
            break;
        case 5:
            face = InteractWorldEvent.BlockFace.EAST;
            x += 1;
            break;
        default:
            face = InteractWorldEvent.BlockFace.INVALID;
            break;
    }

    Vector cursorPos = new Vector(packet.h(), packet.i(), packet.j());

    Location placedLocation = new Location(p.getWorld(), x, y, z);
    return new InteractWorldEvent(p, pp, placedLocation, mat, face, cursorPos, interactionType, new WrappedPacket7(packet, WrappedPacket.PacketType.BLOCK_PLACE));
}